text
stringlengths
14
410k
label
int32
0
9
public boolean isSyncMark(int headerstring, int syncmode, int word) { boolean sync = false; if (syncmode == INITIAL_SYNC) { //sync = ((headerstring & 0xFFF00000) == 0xFFF00000); sync = ((headerstring & 0xFFE00000) == 0xFFE00000); // SZD: MPEG 2.5 } else { sync = ((headerstring & 0xFFF80C00) == word) && (((headerstring & 0x000000C0) == 0x000000C0) == single_ch_mode); } // filter out invalid sample rate if (sync) sync = (((headerstring >>> 10) & 3)!=3); // filter out invalid layer if (sync) sync = (((headerstring >>> 17) & 3)!=0); // filter out invalid version if (sync) sync = (((headerstring >>> 19) & 3)!=1); return sync; }
5
public RBMParameters(String data_file) { int line_num = 1; try { BufferedReader br = new BufferedReader(new FileReader(data_file)); String line = br.readLine(); String[] ar = line.split("\\s+"); m = Integer.parseInt(ar[0]); n = Integer.parseInt(ar[1]); T = Integer.parseInt(ar[2]); _weights = new double[m][n]; _examples = new double[T][m]; _visibleBias = new double[m]; _hiddenBias = new double[n]; for(int i=0; i<m; i++) { _visibleBias[i] = 0.0; } for(int i=0; i<n; i++) { _hiddenBias[i] = 0.0; } for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { _weights[i][j] = 0.0; } for(int t=0; t<T; t++) { _examples[t][i] = 0.0; } } for (int t=0; t<T; t++) { line_num++; line = br.readLine(); ar = line.split("\\s+"); //System.out.println(ar[0]); if(ar.length == m) { for(int i=0; i<m; i++) _examples[t][i] = Double.parseDouble(ar[i]); } else { continue; } } br.close(); } catch(Exception e) { throw new RuntimeException("error while reading parameter file: " + data_file + " on line " + line_num + " [" + e.getMessage() + "]"); } }
9
public void setLoginno(String loginno) { this.loginno = loginno; }
0
public void testCompareTo() { YearMonth test1 = new YearMonth(2005, 6); YearMonth test1a = new YearMonth(2005, 6); assertEquals(0, test1.compareTo(test1a)); assertEquals(0, test1a.compareTo(test1)); assertEquals(0, test1.compareTo(test1)); assertEquals(0, test1a.compareTo(test1a)); YearMonth test2 = new YearMonth(2005, 7); assertEquals(-1, test1.compareTo(test2)); assertEquals(+1, test2.compareTo(test1)); YearMonth test3 = new YearMonth(2005, 7, GregorianChronology.getInstanceUTC()); assertEquals(-1, test1.compareTo(test3)); assertEquals(+1, test3.compareTo(test1)); assertEquals(0, test3.compareTo(test2)); DateTimeFieldType[] types = new DateTimeFieldType[] { DateTimeFieldType.year(), DateTimeFieldType.monthOfYear(), }; int[] values = new int[] {2005, 6}; Partial p = new Partial(types, values); assertEquals(0, test1.compareTo(p)); try { test1.compareTo(null); fail(); } catch (NullPointerException ex) {} try { test1.compareTo(new LocalTime()); fail(); } catch (ClassCastException ex) {} Partial partial = new Partial() .with(DateTimeFieldType.centuryOfEra(), 1) .with(DateTimeFieldType.halfdayOfDay(), 0) .with(DateTimeFieldType.dayOfMonth(), 9); try { new YearMonth(1970, 6).compareTo(partial); fail(); } catch (ClassCastException ex) {} }
3
public boolean noticeChan(String chan, String msg){ boolean success = true; String[] msgSplit = msg.split("\n"); for(int i=0;i<msgSplit.length;i++) { if(!sendln("NOTICE " + chan + " :" + msgSplit[i]) ) { success = false; } } return success; }
2
private List<PartyResults> internalCalculations(List<Party> list){ int chair = 0; int votes = 0; int counter = 0; if (!(list.size()>0)) return results; // Set to 0 totalVotes, not already calculated totalVotes=0; totalChairs=0; results.clear(); for (Iterator it = list.iterator(); it.hasNext();) { Party p = (Party)it.next(); if (counter<3) { counter++; PartyResults pr = new PartyResults(); pr.setChairs(p.getChairs()); pr.setName(p.getName()); pr.setVotes(p.getVotes()); results.add(pr); } else { chair += p.getChairs(); votes += p.getVotes(); } totalVotes += p.getVotes(); totalChairs += p.getChairs(); } PartyResults other = new PartyResults(); other.setName("Others"); other.setChairs(chair); other.setVotes(votes); results.add(other); // We have the partial data calculated, now we only have to update the percentage and possible winner // votes -- x // total -- 100 x = votes*100/total // // chairs -- x // 650 -- 100 x = chairs*100/650 for (Iterator it = results.iterator(); it.hasNext();){ PartyResults p = (PartyResults) it.next(); if (totalChairs>0) p.setPercChairs(p.getChairs()*100.0/650); if (totalVotes>0) p.setPercVotes(p.getVotes()*100.0/totalVotes); } return results; }
6
private ArrayList<Sprite> makeNewSpriteArray(int sheepNum, int snailNum, int raccoonNum, int pandaNum , int amountToAdd) { ArrayList<Sprite> makeObstacle = new ArrayList<Sprite>(); for(int i = 0; i < sheepNum; i++){ Sprite makeSheep = new Sheep(CountryRunnerTitleScreen.difficulty); makeObstacle.add( makeSheep ); } for(int i = 0; i < amountToAdd; i++){ Sprite makeSheep = new Sheep(CountryRunnerTitleScreen.difficulty); makeObstacle.add(makeSheep); } for(int i = 0; i < snailNum; i++){ Sprite makeSnail = new Snail(CountryRunnerTitleScreen.difficulty); makeObstacle.add( makeSnail ); } for(int i = 0; i < amountToAdd/2; i ++){ Sprite makeSnail = new Snail(CountryRunnerTitleScreen.difficulty); makeObstacle.add(makeSnail); } for(int i = 0; i < raccoonNum; i++){ Sprite makeRaccoon = new Raccoon(CountryRunnerTitleScreen.difficulty); makeObstacle.add( makeRaccoon ); } for(int i = 0; i < amountToAdd / 6; i++){ Sprite makeRaccoon = new Raccoon(CountryRunnerTitleScreen.difficulty); makeObstacle.add(makeRaccoon); } for(int i = 0; i < pandaNum; i++){ Sprite makePanda = new Panda(CountryRunnerTitleScreen.difficulty); makeObstacle.add( makePanda ); } for(int i = 0; i < amountToAdd / 2; i++) { Sprite makePanda = new Panda(CountryRunnerTitleScreen.difficulty); makeObstacle.add(makePanda); } return makeObstacle; }
8
public void actionPerformed(ActionEvent ae){ String message = jtxtfldEnterMessage.getText(); if(validateMessage(message)){ ChatMessage chatMessage = new ChatMessage(user.getNick(), user.getID(), channel.getChannelID(), jtxtfldEnterMessage.getText()); writtenMessages.add(chatMessage); jtxtfldEnterMessage.setText(""); lastMessage = message; } }
1
public boolean fire(int r, int c) throws IOException { if (1 > r || 1 > c || 10 < r || 10 < c) { invalidShot = true; } else { switch (board[r][c]) { case "x": case "!": return unavailibleShot(); case "-": return missedShot(r, c); case "o": return hitShot(r, c); } } return false; }
8
public boolean run() { int i; ok = false; stdout.clear(); stderr.clear(); try { String line; String[] cmd = command.split(" "); ProcessBuilder pb= new ProcessBuilder(cmd); pb.redirectErrorStream(true); Process p = pb.start(); if (stdin.size() > 0) { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream())); for (i = 0; i < stdin.size(); i++) { writer.write(stdin.get(i)); writer.newLine(); writer.flush(); } writer.close(); } BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); while((line=reader.readLine()) != null) { if (line.startsWith("gpg:")) { stderr.add(line); } else { stdout.add(line); } } reader.close(); int exitCode = p.waitFor(); ok = (exitCode == 0) ? true : false; } catch(Exception e1) { stderr.add(e1.getMessage()); } return ok; }
6
public List<?> list(Class<?> clazz) { String simpleName = clazz.getSimpleName(); String hql = "from " + clazz.getName() + " " + simpleName; return getSession().createQuery(hql).list(); }
2
public double ranGamma(double k, double theta) { boolean accept = false; if (k < 1) { // Weibull algorithm double c = (1 / k); double d = ((1 - k) * Math.pow(k, (k / (1 - k)))); double u, v, z, e, x; do { u = rand.nextDouble(); v = rand.nextDouble(); z = -Math.log(u); e = -Math.log(v); x = Math.pow(z, c); if ((z + e) >= (d + x)) { accept = true; } } while (!accept); return (x * theta); } else { // Cheng's algorithm double b = (k - Math.log(4)); double c = (k + Math.sqrt(2 * k - 1)); double lam = Math.sqrt(2 * k - 1); double cheng = (1 + Math.log(4.5)); double u, v, x, y, z, r; do { u = rand.nextDouble(); v = rand.nextDouble(); y = ((1 / lam) * Math.log(v / (1 - v))); x = (k * Math.exp(y)); z = (u * v * v); r = (b + (c * y) - x); if ((r >= ((4.5 * z) - cheng)) || (r >= Math.log(z))) { accept = true; } } while (!accept); return (x * theta); } }
6
public void setNeighbors( int[] truckdrivin){ for(int g = 0; g <= truckdrivin.length-1; g++){ switch(inmode){ case 0: break; case 1: if(truckdrivin[g] > 0){neighborstate[g] = 1;} else{neighborstate[g] = 0;} break; case 2: neighborstate[g] = truckdrivin[g]; break; default: neighborstate[g] = truckdrivin[g]; break; } } }
5
@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 Prayer_ElectricStrike newOne=(Prayer_ElectricStrike)this.copyOf(); final CMMsg msg=CMClass.getMsg(mob,target,newOne,verbalCastCode(mob,target,auto),L(auto?"<T-NAME> is filled with a holy charge!":"^S<S-NAME> point(s) at <T-NAMESELF> and "+prayWord(mob)+"!^?")+CMLib.protocol().msp("lightning.wav",40)); final CMMsg msg2=CMClass.getMsg(mob,target,this,CMMsg.MSK_CAST_MALICIOUS_VERBAL|CMMsg.TYP_ELECTRIC|(auto?CMMsg.MASK_ALWAYS:0),null); final Room R=target.location(); if((R.okMessage(mob,msg))&&((R.okMessage(mob,msg2)))) { R.send(mob,msg); R.send(mob,msg2); if((msg.value()<=0)&&(msg2.value()<=0)) { final int harming=CMLib.dice().roll(1,adjustedLevel(mob,asLevel),5); CMLib.combat().postDamage(mob,target,this,harming,CMMsg.MASK_ALWAYS|CMMsg.TYP_ELECTRIC,Weapon.TYPE_STRIKING,L("^SThe ELECTRIC STRIKE <DAMAGES> <T-NAME>!^?")); } } } else return maliciousFizzle(mob,target,L("<S-NAME> @x1, but nothing happens.",prayWord(mob))); // return whether it worked return success; }
9
private void processFunctions(FileData coverageData, StringBuilder lcov) { int total = 0; int hit = 0; for (int functionNumber = 0; functionNumber < coverageData.getFunctions().size(); functionNumber++) { total++; Integer functionHits = coverageData.getFunctions().get(functionNumber); if (functionHits > 0) hit++; String functionName = "" + functionNumber; lcov.append(format(functionData, functionHits, functionName)); } lcov.append(format(functionFound, total)); lcov.append(format(functionHit, hit)); }
2
private RequestDispatcher goRegistrazione(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("username") == null || request.getParameter("password") == null || request.getParameter("password2") == null) { return getServletContext().getRequestDispatcher("/registrazione.jsp"); } else { try { if (DB.controllaUtente(request.getParameter("username"))) {//se l'utente è già presente restituisce l'errore request.setAttribute("errore", "err"); return getServletContext().getRequestDispatcher("/registrazione.jsp"); } else {//registra il nuovo utente DB.aggiungiUtente(request.getParameter("username"), request.getParameter("password")); goLogin(request, response); utenti = DB.caricaNomiUtenti(); return getServletContext().getRequestDispatcher("/registrato.html"); } } catch (SQLException ex) { throw new ServletException(ex.getMessage()); } } }
5
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final EventsType other = (EventsType) obj; if (this.row != other.row) { return false; } if (this.column != other.column) { return false; } if (this.visited != other.visited) { return false; } if (!Objects.equals(this.explore, other.explore)) { return false; } if (!Objects.equals(this.randomEvent, other.randomEvent)) { return false; } if (!Objects.equals(this.actorRandomEvent, other.actorRandomEvent)) { return false; } if (!Objects.equals(this.eventScene, other.eventScene)) { return false; } return true; }
9
public boolean mousedown(Coord c, int button) { for (Widget wdg = lchild; wdg != null; wdg = wdg.prev) { if (!wdg.visible) continue; Coord cc = xlate(wdg.c, true); if (c.isect(cc, (wdg.hsz == null) ? wdg.sz : wdg.hsz)) { if (wdg.mousedown(c.add(cc.inv()), button)) { return (true); } } } return (false); }
5
public void setLineEndingAtEnd(boolean lineEndingAtEnd) { this.lineEndingAtEnd = lineEndingAtEnd; }
0
public static String escapeIllegalXpathSearchChars(String s) { StringBuilder sb = new StringBuilder(); sb.append(s.substring(0, (s.length() - 1))); char c = s.charAt(s.length() - 1); // NOTE: keep this in sync with _ESCAPED_CHAR below! if (c == '!' || c == '(' || c == ':' || c == '^' || c == '[' || c == ']' || c == '{' || c == '}' || c == '?') { sb.append('\\'); } sb.append(c); return sb.toString(); }
9
String token() { if (idx == null && val.getClass().isArray()) { int len = Array.getLength(val); StringBuilder b = new StringBuilder(); for (int i = 0; i < len - 1; i++) { b.append(token + "[" + i + "],"); } b.append(token + "[" + (len - 1) + "]"); return b.toString(); } return token; }
3
static void parcoursArbre(Element e) { String s = ""; if (e.getAttributeValue("type").equals("node")) { //l'élément est un noeud Element question = e.getChild("question"); s += question.getAttributeValue("name") + "<"; s += question.getAttributeValue("patron") + " ?"; System.out.println(s); parcoursArbre(e.getChildren("node").get(0)); parcoursArbre(e.getChildren("node").get(1)); } else if (e.getAttributeValue("type").equals("leaf")) { //l'élément est une feuille Element pop = e.getChild("population"); if (pop.getAttribute("L0") != null) s += "L0 : " + pop.getAttributeValue("L0") + " "; if (pop.getAttribute("L1") != null) s += "L1 : " + pop.getAttributeValue("L1") + " "; if (pop.getAttribute("L2") != null) s += "L2 : " + pop.getAttributeValue("L2") + " "; System.out.println(s); } }
5
private void doFirstStep(Vertex<Text, Text, NullWritable> vertex) { // First superstep is special, because we can simply look at the neighbors // On first step value is not set, so using id Text currentComponent = vertex.getId(); for (Edge<Text, NullWritable> edge : vertex.getEdges()) { Text neighbor = edge.getTargetVertexId(); if (neighbor.compareTo(currentComponent) < 0) { currentComponent = new Text(neighbor); // do clone since neighbor is mutable } } vertex.setValue(currentComponent); for (Edge<Text, NullWritable> edge : vertex.getEdges()) { Text neighbor = edge.getTargetVertexId(); if (neighbor.compareTo(currentComponent) > 0) { sendMessage(neighbor, currentComponent); } } }
4
private static BeanInfo getExplicitBeanInfo(Class<?> beanClass) { String beanInfoClassName = beanClass.getName() + "BeanInfo"; //$NON-NLS-1$ try { return loadBeanInfo(beanInfoClassName, beanClass); } catch (Exception e) { // fall through } int index = beanInfoClassName.lastIndexOf('.'); String beanInfoName = index >= 0 ? beanInfoClassName .substring(index + 1) : beanInfoClassName; BeanInfo theBeanInfo = null; BeanDescriptor beanDescriptor = null; for (int i = 0; i < searchPath.length; i++) { beanInfoClassName = searchPath[i] + "." + beanInfoName; //$NON-NLS-1$ try { theBeanInfo = loadBeanInfo(beanInfoClassName, beanClass); } catch (Exception e) { // ignore, try next one continue; } beanDescriptor = theBeanInfo.getBeanDescriptor(); if (beanDescriptor != null && beanClass == beanDescriptor.getBeanClass()) { return theBeanInfo; } } if (BeanInfo.class.isAssignableFrom(beanClass)) { try { return loadBeanInfo(beanClass.getName(), beanClass); } catch (Exception e) { // fall through } } return null; }
9
@Override public AcknowledgementService handle(LocalDevice localDevice, Address from, OctetString linkService) throws BACnetException { AtomicWriteFileAck response; BACnetObject obj; FileObject file; try { // Find the file. obj = localDevice.getObjectRequired(fileIdentifier); if (!(obj instanceof FileObject)) throw new BACnetServiceException(ErrorClass.object, ErrorCode.rejectInconsistentParameters); file = (FileObject) obj; // Validation. FileAccessMethod fileAccessMethod = (FileAccessMethod) file .getProperty(PropertyIdentifier.fileAccessMethod); if (fileData == null && fileAccessMethod.equals(FileAccessMethod.streamAccess) || fileData != null && fileAccessMethod.equals(FileAccessMethod.recordAccess)) throw new BACnetErrorException(getChoiceId(), ErrorClass.object, ErrorCode.invalidFileAccessMethod); } catch (BACnetServiceException e) { throw new BACnetErrorException(getChoiceId(), e); } if (fileData == null) { throw new NotImplementedException(); } long start = fileStart.longValue(); if (start > file.length()) throw new BACnetErrorException(getChoiceId(), ErrorClass.object, ErrorCode.invalidFileStartPosition); try { file.writeData(start, fileData); response = new AtomicWriteFileAck(fileData == null, fileStart); } catch (IOException e) { throw new BACnetErrorException(getChoiceId(), ErrorClass.object, ErrorCode.fileAccessDenied); } return response; }
9
public void increment(int by) { // if given value is negative, we have to decrement if (by < 0) { decrement(Math.abs(by)); return; } // check if we would overflow int space_up = max - value; if (by > space_up) { // we simply use max value = max; } else { // no overflowing, this is easy value += by; } }
2
@Override public Iterator<T> iterator() { return new Iterator<T>() { boolean hasNext; T next; final Iterator<? extends T> i1 = s1.iterator(); Iterator<? extends T> i2; @Override public boolean hasNext() { if (i1.hasNext()) { next = i1.next(); hasNext = true; return true; } hasNext = false; if (i2 == null) { i2 = s2.iterator(); } while (i2.hasNext()) { final T n = i2.next(); if (!s1.contains(n)) { hasNext = true; next = n; } } return hasNext; } @Override public T next() { if (!hasNext) { throw new NoSuchElementException(); } return next; } }; }
7
public String getQuery() { if (_query == null) throw new java.util.NoSuchElementException(); return _query; }
1
public void setWalkable(int x, int y, boolean bool) { if(x < 0 || x > width || y < 0 || y > height){ throw new IllegalArgumentException("X & Y must be more than 0, but less than w/h"); } nodes[x][y].setWalkable(bool); }
4
public static void main(String[] args) { // Nature creates two new animals, gives sparrow the ability to fly. System.out.println("Nature provides birdy the ability to fly."); System.out.println("Nature doesn't give kitty the abilty to fly."); Cat kitty = new Cat("kitty", 6f, new NoFlyingAbilty()); Sparrow birdy = new Sparrow("birdy", 0.3f, new SparrowLikeFlyingAbility()); // Nature tests the flying abilities. System.out.println("\nNature asks kitty to fly."); kitty.getFlyingAbility().fly(); System.out.println("\nNature asks birdy to fly."); birdy.getFlyingAbility().fly(); // Nature feels sad that kitty cannot fly, gives it flying capabilities. System.out .println("\nNature gives kitty the power to fly like an eagle."); kitty.changeFlyingAbility(new EagleLikeFlyingAbility()); // And now nature asks the kitty to spread its wings. System.out.println("\nNature asks the kitty to spread its wings."); kitty.getFlyingAbility().fly(); }
0
protected String toXMLFragment() { StringBuffer xml = new StringBuffer(); if (isSetTokenId()) { xml.append("<TokenId>"); xml.append(escapeXML(getTokenId())); xml.append("</TokenId>"); } if (isSetFriendlyName()) { xml.append("<FriendlyName>"); xml.append(escapeXML(getFriendlyName())); xml.append("</FriendlyName>"); } if (isSetTokenStatus()) { xml.append("<TokenStatus>"); xml.append(getTokenStatus().value()); xml.append("</TokenStatus>"); } if (isSetDateInstalled()) { xml.append("<DateInstalled>"); xml.append(getDateInstalled() + ""); xml.append("</DateInstalled>"); } if (isSetCallerReference()) { xml.append("<CallerReference>"); xml.append(escapeXML(getCallerReference())); xml.append("</CallerReference>"); } if (isSetTokenType()) { xml.append("<TokenType>"); xml.append(getTokenType().value()); xml.append("</TokenType>"); } if (isSetOldTokenId()) { xml.append("<OldTokenId>"); xml.append(escapeXML(getOldTokenId())); xml.append("</OldTokenId>"); } if (isSetPaymentReason()) { xml.append("<PaymentReason>"); xml.append(escapeXML(getPaymentReason())); xml.append("</PaymentReason>"); } return xml.toString(); }
8
public String getContent() { return mContent; }
0
public void Email(JTextField a) { a.addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); if (Character.isLetterOrDigit(c) || c == '_' || c == '-' || c == '@' || c == '.' || c == 'ñ') { }else{ getToolkit().beep(); e.consume(); } } }); }
6
public void update(long deltaMs) { ArrayList<BaseProcess> toAttach = new ArrayList<BaseProcess>(); Iterator<BaseProcess> it = processes.iterator(); while(it.hasNext()) { BaseProcess current = it.next(); if(current.getState() == BaseProcess.ProcessState.UNINITIALIZED) { current.init(); } if(current.getState() == BaseProcess.ProcessState.RUNNING) { current.update(deltaMs); } if(current.isDead()) { switch(current.getState()) { case SUCCEEDED: current.onSuccess(); BaseProcess child = current.getChild(); if(child != null) { toAttach.add(child); } break; case FAILED: current.onFail(); break; case ABORTED: current.onAbort(); break; } it.remove(); } } for(BaseProcess p : toAttach) { attachProcess(p); } }
9
public void mouseDragged(MouseEvent e) { mouseMoved(e); }
0
public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; super.paintComponent(g2); // Draw randomly generated nodes for (Node p : myGraph.getNodes()) drawPoint(g2, p.x, p.y); //Draw selected Nodes g2.setColor(Color.blue); if (fromNode != null) graphPanel.drawPoint(g2 , fromNode.x, fromNode.y); if (toNode != null) graphPanel.drawPoint(g2 , toNode.x, toNode.y); g2.setColor(POINT_COLOR); g2.setStroke(new BasicStroke(2)); //g2.setColor(Color.red); drawEdges(g2, myGraph.getEdges()); g2.setStroke(new BasicStroke(3)); g2.setColor(Color.blue); drawEdges(g2, path); g2.setColor(POINT_COLOR); // Draw zoom box if (zoomBox != null) g2.draw(zoomBox); }
4
@SuppressWarnings("SleepWhileInLoop") private Repository forkAndWait(GitHubClient gitHubClient, Repository masterRepository) throws IOException { Properties properties = ApplicationProperties.getProperties(); RepositoryService repositoryService = new RepositoryService(gitHubClient); Repository repositoryFork = repositoryService.forkRepository(masterRepository); int maxAttempts = 5; for (int i = 0; i < maxAttempts; i++) { try { logger.log(Level.INFO, "Waiting for fork of {0} to become available...", masterRepository.getName()); Thread.sleep(5 * 1000); List<SearchRepository> searchRepositories = repositoryService.searchRepositories( masterRepository.getName() + " user:" + properties.getProperty(PropertiesConstants.GITHUB_ANON_USERNAME) + " fork:only"); if (searchRepositories.size() == 1) { return repositoryFork; } } catch (InterruptedException | IOException e) { logger.log(Level.INFO, "Error waiting for fork of {0} to create: {1}", new String[] {masterRepository.getName(), e.getMessage()}); } } logger.log(Level.INFO, "Fork for {0} took too long to create.", masterRepository.getName()); gitHubClient.delete("/repos/" + properties.getProperty(PropertiesConstants.GITHUB_ANON_USERNAME) + "/" + masterRepository.getName()); throw new IOException("Repository fork could not be created."); }
3
public Class getTypeClass() throws ClassNotFoundException { switch (typecode) { case TC_LONG: return Long.TYPE; case TC_FLOAT: return Float.TYPE; case TC_DOUBLE: return Double.TYPE; default: throw new AssertError("getTypeClass() called on illegal type"); } }
3
@Override public void e(float sideMot, float forMot) { if (this.passenger == null || !(this.passenger instanceof EntityHuman)) { super.e(sideMot, forMot); this.W = 0.5F; // Make sure the entity can walk over half slabs, // instead of jumping return; } EntityHuman human = (EntityHuman) this.passenger; if (!RideThaMob.control.contains(human.getBukkitEntity().getName())) { // Same as before super.e(sideMot, forMot); this.W = 0.5F; return; } this.lastYaw = this.yaw = this.passenger.yaw; this.pitch = this.passenger.pitch * 0.5F; // Set the entity's pitch, yaw, head rotation etc. this.b(this.yaw, this.pitch); // https://github.com/Bukkit/mc-dev/blob/master/net/minecraft/server/Entity.java#L163-L166 this.aO = this.aM = this.yaw; this.W = 1.0F; // The custom entity will now automatically climb up 1 // high blocks sideMot = ((EntityLiving) this.passenger).bd * 0.5F; forMot = ((EntityLiving) this.passenger).be; if (forMot <= 0.0F) { forMot *= 0.25F; // Make backwards slower } sideMot *= 0.75F; // Also make sideways slower float speed = 0.35F; // 0.2 is the default entity speed. I made it // slightly faster so that riding is better than // walking this.i(speed); // Apply the speed super.e(sideMot, forMot); // Apply the motion to the entity try { Field jump = null; jump = EntityLiving.class.getDeclaredField("bc"); jump.setAccessible(true); if (jump != null && this.onGround) { // Wouldn't want it jumping // while // on the ground would we? if (jump.getBoolean(this.passenger)) { double jumpHeight = 0.5D; this.motY = jumpHeight; // Used all the time in NMS for // entity jumping } } } catch (Exception e) { e.printStackTrace(); } }
8
public boolean equals(Object o) { if ( !(o instanceof DTNode) ) return false; if ( o == this ) return true; DTNode n = (DTNode)o; if ( n.left_bit != left_bit ) return false; if ( n.right_bit != right_bit ) return false; if ( !n.label.equals(label) ) return false; if ( children.size() != n.children.size() ) return false; for ( Map.Entry<Integer, DTNode> e : children.entrySet() ) { int value = e.getKey(); DTNode cdt = e.getValue(); DTNode odt = n.children.get(value); if ( cdt != odt ) return false; } return true; }
8
public void checkType(Symtab st) { exp1.setScope(scope); exp1.checkType(st); exp2.setScope(scope); exp2.checkType(st); String exp1Type = exp1.getType(st); String exp2Type = exp2.getType(st); if (!exp1Type.equals(exp2Type)) { if (!(st.lookup(exp1Type) != null && exp2Type.equals("null"))) { if (!exp1Type.equals("int") && !exp1Type.equals("decimal")) Main.error("type error in neq!"); if (!exp2Type.equals("int") && !exp1Type.equals("decimal")) Main.error("type error in neq!"); } } else expType = exp1.getType(st); }
7
public void setProduct(Product product) { this.product = product; }
0
public boolean collision(int index1, int index2) { if (getImage(index1) == null || getImage(index2) == null) { return false; } if (getImage(index1).getBounds().intersects( getImage(index2).getBounds())) { return (getImage(index1).isActive() && getImage(index2).isActive()); } return false; }
4
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(CustomerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CustomerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CustomerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CustomerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new CustomerFrame().setVisible(true); } }); }
6
private String expresion(Nodo chk){ String tem=new String(); Iterator e=chk.getNodo().iterator(); switch(chk.getToken()){ case Suma: tem+=this.expresion(((Nodo)e.next())); tem+=this.expresion(((Nodo)e.next())); tem+="\nadi"; break; case Resta: tem+=this.expresion(((Nodo)e.next())); tem+=this.expresion(((Nodo)e.next())); tem+="\nsbi"; break; case Division: tem+=this.expresion(((Nodo)e.next())); tem+=this.expresion(((Nodo)e.next())); tem+="\ndvi"; break; case Multiplicacion: tem+=this.expresion(((Nodo)e.next())); tem+=this.expresion(((Nodo)e.next())); tem+="\nmpi"; break; case Numero: if(chk.getTipoDato().equals("int")){ tem+="\nldc "+chk.getValorNumInt(); }else{ tem+="\nldc "+chk.getValorNumFloat(); } break; case Identificador: tem+="\nlod "+chk.getDato(); break; } return tem; }
7
@Override public void restart() throws MusicPlayerException { if ( this.mStreamPlayerRunnable == null ) { throw new IllegalStateException( "can't restart. not started yet" ); } if ( this.mStreamPlayerRunnable.isStopped() ) { try { this.mStreamPlayerRunnable.join(); } catch (InterruptedException e) { throw new MusicPlayerException( e ); } this.mStreamPlayerRunnable.reset(); this.mStreamPlayerRunnable.seek( 0 ); this.mPlaybackExecutor.execute( this.mStreamPlayerRunnable ); } else { this.mStreamPlayerRunnable.seek( 0 ); } }
3
private int pickAmount() { Random rand = new Random(); if (itemQuality == quality.poor) { return rand.nextInt(config.getPoorMaxAmount() - config.getPoorMinAmount() + 1) + config.getPoorMinAmount(); } else if (itemQuality == quality.average) { return rand.nextInt(config.getAverageMaxAmount() - config.getAverageMinAmount() + 1) + config.getAverageMinAmount(); } else if (itemQuality == quality.good) { return rand.nextInt(config.getGoodMaxAmount() - config.getGoodMinAmount() + 1) + config.getGoodMinAmount(); } else if (itemQuality == quality.top) { return rand.nextInt(config.getTopMaxAmount() - config.getTopMinAmount() + 1) + config.getTopMinAmount(); } return 0; }
4
public static List<Mixer> getMixers() { Info[] infos = AudioSystem.getMixerInfo(); List<Mixer> mixers = new ArrayList<Mixer>(infos.length); for (Info info : infos) { Mixer mixer = AudioSystem.getMixer(info); mixers.add(mixer); } return mixers; }
1
private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed if (inicio.principal.datos == null) { try { inicio.d.setAntiguedad(Integer.parseInt(txtAntiguedad.getText())); inicio.d.setHoraArma(Double.parseDouble(txtHoraArma.getText().replace(',', '.'))); inicio.d.setHoraExtra(Double.parseDouble(txtHoraExtra.getText().replace(',', '.'))); inicio.d.setHoraFestiva(Double.parseDouble(txtHoraFestiva.getText().replace(',', '.'))); inicio.d.setHoraNocturna(Double.parseDouble(txtHoraNocturna.getText().replace(',', '.'))); inicio.d.setHorasConvenio(Double.parseDouble(txtHorasConvenio.getText().replace(',', '.'))); inicio.d.setKilometraje(Double.parseDouble(txtKilometraje.getText().replace(',', '.'))); inicio.d.setNochebuena(Double.parseDouble(txtNochebuena.getText().replace(',', '.'))); inicio.d.setPeligro(Double.parseDouble(txtPeligrosidad.getText().replace(',', '.'))); inicio.d.setQuinquenio(Double.parseDouble(txtQuinquenio.getText().replace(',', '.'))); inicio.d.setRadio(Double.parseDouble(txtRadio.getText().replace(',', '.'))); inicio.d.setRadioBasica(Double.parseDouble(txtRadioBasica.getText().replace(',', '.'))); inicio.d.setSalarioBase(Double.parseDouble(txtSalarioBase.getText().replace(',', '.'))); inicio.d.setTransporte(Double.parseDouble(txtTransporte.getText().replace(',', '.'))); inicio.d.setTrienio(Double.parseDouble(txtTrienio.getText().replace(',', '.'))); inicio.d.setVestuario(Double.parseDouble(txtVestuario.getText().replace(',', '.'))); inicio.mostrarTitulo(); this.dispose(); } catch (NumberFormatException ex) { lblInfo.setVisible(true); } } else { try { inicio.principal.datos.setAntiguedad(Integer.parseInt(txtAntiguedad.getText())); inicio.principal.datos.setHoraArma(Double.parseDouble(txtHoraArma.getText().replace(',', '.'))); inicio.principal.datos.setHoraExtra(Double.parseDouble(txtHoraExtra.getText().replace(',', '.'))); inicio.principal.datos.setHoraFestiva(Double.parseDouble(txtHoraFestiva.getText().replace(',', '.'))); inicio.principal.datos.setHoraNocturna(Double.parseDouble(txtHoraNocturna.getText().replace(',', '.'))); inicio.principal.datos.setHorasConvenio(Double.parseDouble(txtHorasConvenio.getText().replace(',', '.'))); inicio.principal.datos.setKilometraje(Double.parseDouble(txtKilometraje.getText().replace(',', '.'))); inicio.principal.datos.setNochebuena(Double.parseDouble(txtNochebuena.getText().replace(',', '.'))); inicio.principal.datos.setPeligro(Double.parseDouble(txtPeligrosidad.getText().replace(',', '.'))); inicio.principal.datos.setQuinquenio(Double.parseDouble(txtQuinquenio.getText().replace(',', '.'))); inicio.principal.datos.setRadio(Double.parseDouble(txtRadio.getText().replace(',', '.'))); inicio.principal.datos.setRadioBasica(Double.parseDouble(txtRadioBasica.getText().replace(',', '.'))); inicio.principal.datos.setSalarioBase(Double.parseDouble(txtSalarioBase.getText().replace(',', '.'))); inicio.principal.datos.setTransporte(Double.parseDouble(txtTransporte.getText().replace(',', '.'))); inicio.principal.datos.setTrienio(Double.parseDouble(txtTrienio.getText().replace(',', '.'))); inicio.principal.datos.setVestuario(Double.parseDouble(txtVestuario.getText().replace(',', '.'))); inicio.mostrarTitulo(); this.dispose(); } catch (NumberFormatException ex) { lblInfo.setVisible(true); } } }//GEN-LAST:event_btnAceptarActionPerformed
3
public HashMap<String,String> getConfigurationData() { HashMap<String,String> l_tmp_map; Scanner l_reader; Scanner l_line_scanner; String l_tmp_key; String l_tmp_val; if( this.configuration_file == null) return null; l_tmp_map = new HashMap<String,String>(); l_reader = new Scanner( this.configuration_file ); while( l_reader.hasNext()) { l_tmp_key = null; l_tmp_val = null; l_line_scanner = new Scanner( l_reader.nextLine()); l_line_scanner.useDelimiter(this.configuration_sep); if(l_line_scanner.hasNext()) l_tmp_key = l_line_scanner.next().trim(); if(l_line_scanner.hasNext()) l_tmp_val = l_line_scanner.next().trim(); if( l_tmp_key != null && l_tmp_val != null) { l_tmp_val.replaceAll("[^\\w\\s]", ""); Logger.notify("CONFIGURATION get " + l_tmp_key + " is " + l_tmp_val + ";"); l_tmp_map.put( l_tmp_key, l_tmp_val ); } } if( l_tmp_map.size() < 0 ) return null; return l_tmp_map; }
7
public JSONObject getJSONObject(int index) throws JSONException { Object o = get(index); if (o instanceof JSONObject) { return (JSONObject)o; } throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); }
1
public State getOldBlock() { return myOldBlock; }
0
public String consumeToIgnoreCase(String seq) { int start = pos; String first = seq.substring(0, 1); boolean canScan = first.toLowerCase().equals(first.toUpperCase()); // if first is not cased, use index of while (!isEmpty()) { if (matches(seq)) break; if (canScan) { int skip = queue.indexOf(first, pos) - pos; if (skip == 0) // this char is the skip char, but not match, so force advance of pos pos++; else if (skip < 0) // no chance of finding, grab to end pos = queue.length(); else pos += skip; } else pos++; } String data = queue.substring(start, pos); return data; }
5
public void setId(String id) { this.id = id; }
0
public void setBullet(int id, int x, int y){ switch (id) { case 1:{ this.id = 1; this.pointX = x; this.pointY = y; this.bulletSpeed = 2; this.shotSpeed = 4; this.damage = 1; this.sprite = DisplayActions.getImage("EBullet2"); this.width = 5; this.height = 20; this.collides = true; break; } case 2:{ this.id = 2; this.pointX = x; this.pointY = y; this.bulletSpeed = 2; this.damage = 1; this.shotSpeed = 15; this.sprite = DisplayActions.getImage("EBullet2"); this.width = this.sprite.getWidth(); this.height = this.sprite.getHeight(); break; } case 3:{ this.id = 3; this.pointX = x; this.pointY = y; this.bulletSpeed = 5; this.damage = 1; this.shotSpeed = 384; this.sprite = DisplayActions.getImage("EBullet3"); this.width = this.sprite.getWidth(); this.height = this.sprite.getHeight(); break; } } }
3
public void setComments(String comments) { if (comments != null && comments.trim().length() > 256) { comments = comments.substring(0, 256); } this.comments = comments; }
2
public String getPassword() { return this.password; }
0
public int put(int key, int n) { int pos, t = 1; while (t < m) { pos = toHash(key, t); if (table[pos] == null) { table[pos] = new HashEntry(key, t); // ???????????????????????????????????????????????????????????????????????????????????? // // ???????????????????????????????????????????????????????????????????????????????????? // if (n % (Math.ceil(m / 50)) == 0) { Stats stats = new Stats(m, n, t); Main.statsLinear.add(stats); } // ???????????????????????????????????????????????????????????????????????????????????? // // ???????????????????????????????????????????????????????????????????????????????????? // return t; } t++; } return -1; }
3
public int getScore() { return score; }
0
public void loppuukoPeli() { if (this.logiikka.tarkistaVoitto(1)) { this.tekstiKentta.setText("Risti on voittaja!"); this.logiikka.setPelinTila(0); } else if (this.logiikka.tarkistaVoitto(2)) { this.tekstiKentta.setText("Nolla on voittaja!"); this.logiikka.setPelinTila(0); } else if (this.logiikka.onkoPoytaTaynna()) { this.tekstiKentta.setText("Tasapeli!"); } }
3
private void loadHighScore(){ try{ File f = new File(saveDataPath, fileName); if(!f.isFile()){ createSaveData(); } BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f))); highScore = Integer.parseInt(reader.readLine()); reader.close(); } catch(Exception e){ e.printStackTrace(); } }
2
private synchronized void seek(RandomAccessFile randomaccessfile, int pos) throws IOException { if (pos < 0 || pos > 0x3c00000) { System.out.println("Badseek - pos:" + pos + " len:" + randomaccessfile.length()); pos = 0x3c00000; try { Thread.sleep(1000L); } catch (Exception exception) { } } randomaccessfile.seek(pos); }
3
public void nextPermutation(int[] num) { List<Integer> list = new ArrayList<Integer>(); int length = num.length; if(num == null||length == 0) return ; int big = num[length-1]; int target = num[length-1]; int index = -1; for(int i =num.length-1 ;i>0;i--){ //检测是否降序排列 if(num[i-1] < num[i]){ // 如果不是 j target = num[i-1]; //记录目标值,该为的新值需要比该值大。 list.add(num[i-1]); list.add(num[i]); index = i-1; //记下坐标 break; } list.add(num[i]); } Collections.sort(list); if(index == -1){ // 全部是降序,则放回一个升序。 for (int i=0; i < list.size() ;i++ ) { num[i] = list.get(i); } return; } for (int i=0;i < list.size() ;i++ ) { // 寻找一个比target 大的最小值。 if(target < list.get(i)){ target = list.get(i); list.remove(i); //移除该值。 break; } } num[index] = target; for (int i=0; i < list.size() ;i++ ) { num[i+index+1] = list.get(i); } }
9
public boolean SetAnnounced(String player, Date newdate) { String datestr = ""; if (newdate != null) { datestr = new SimpleDateFormat("yyyy-MM-dd").format(newdate); } String query = "UPDATE birthdaygift SET lastAnnouncedDate=? WHERE player=?"; dbcon.PreparedUpdate(query, new String[]{datestr, player.toLowerCase()}); return true; }
1
private boolean testeSiegInReihe(Spieler spieler) { for (int reihennummer = 1; reihennummer <= Spielfeld.ANZAHL_REIHEN; reihennummer++){ int sequenceCounter = 0; for (int spaltennummer = 1; spaltennummer <= Spielfeld.ANZAHL_SPALTEN; spaltennummer++){ Stein steinfarbe = spielfeld.getSteinfarbe(spaltennummer, reihennummer); if (steinfarbe == null) break; if (steinfarbe.equals(spieler.getSteinfarbe())) { sequenceCounter++; if (sequenceCounter >= 4) return true; } else { sequenceCounter = 0; } } } return false; }
5
@Override public boolean accept(File dir, String name) { try{ if (name.substring(name.lastIndexOf(".")).equalsIgnoreCase(".dat")) return true; } catch (Exception e){ } return false; }
2
public void configureAction(Map<String, Object> config) { if (config == null) { this.task = null; this.gruntFile = null; this.page = null; } else { this.task = (String) config.get(Activator.KEY_TASK); this.gruntFile = (IFile) config.get(Activator.KEY_FILE); this.page = (IWorkbenchPage) config.get(Activator.KEY_PAGE); } }
1
public Dysk produkujemyDysk(){ return new DyskDlaLaptopa(); }
0
public void print(ArrayList<Double> values, String fileName, ArrayList<String> description) { String outString = ""; if(!_titlesPrinted){ outString += "\n"; _titlesPrinted = true; for (int i = 0 ; i < description.size(); i ++){ outString += description.get(i)+","; } outString += "\n"; } for(int i = 0 ; i < values.size(); i ++){ outString += values.get(i) + ", "; } outString += "\n"; PrintToFile(outString, fileName+".csv"); }
3
@Override public long getMass() { final long mass=this.mass; if(mass<0) { int newMass=phyStats().weight(); for(final Enumeration<Room> r=getProperMap(); r.hasMoreElements();) { final Room R=r.nextElement(); if(R!=null) { for(int i=0;i<R.numItems();i++) { final Item I=R.getItem(i); if(I!=null) newMass += I.phyStats().weight(); } for(int i=0;i<R.numInhabitants();i++) { final MOB M=R.fetchInhabitant(i); if(M!=null) newMass += M.phyStats().weight(); } } } this.mass=newMass; } return this.mass; }
7
@Override public void onDraw(Graphics G, int viewX, int viewY) { if (X>viewX&&X<viewX+300&&Y>viewY&&Y<viewY+300) { G.setColor(Color.DARK_GRAY); G.fillArc((int)(X-radius/2)-viewX, (int)(Y-radius/2)-viewY, radius, radius, 0, 360); G.setColor(Color.GRAY); G.fillArc(((int)X-2)-viewX, (int)(Y-2)-viewY, 4, 4, s1, a1); G.fillArc((int)(X-4)-viewX, (int)(Y-4)-viewY, 8, 8, s2, a2); G.fillArc((int)(X-6)-viewX, (int)(Y-6)-viewY, 12, 12, s3, a3); } }
4
@Override @SuppressWarnings("unchecked") protected <E> E getApiResponse(AbstractContentHandler contentHandler, InputStream inputStream, Class<E> clazz) throws ApiException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (logger.isInfoEnabled()) { inputStream = new InputStreamSplitter(inputStream, outputStream); } try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(contentHandler); xr.parse(new InputSource(inputStream)); return (E) contentHandler.getResponse(); } catch (Exception e) { throw new ApiException(e); } finally { logger.info("\nResponse:\n" + outputStream.toString()); } }
2
protected void householder( int j ) { // find the element with the largest absolute value in the column and make a copy int index = j+j*numCols; double max = 0; for( int i = j; i < numRows; i++ ) { double d = u[i] = dataQR[index]; // absolute value of d if( d < 0 ) d = -d; if( max < d ) { max = d; } index += numCols; } if( max == 0.0 ) { gamma = 0; error = true; } else { // compute the norm2 of the matrix, with each element // normalized by the max value to avoid overflow problems tau = 0; for( int i = j; i < numRows; i++ ) { u[i] /= max; double d = u[i]; tau += d*d; } tau = Math.sqrt(tau); if( u[j] < 0 ) tau = -tau; double u_0 = u[j] + tau; gamma = u_0/tau; for( int i = j+1; i < numRows; i++ ) { u[i] /= u_0; } u[j] = 1; tau *= max; } gammas[j] = gamma; }
7
public void update(String key){ synchronized(this.cache){ U fromCache = cache.get(key); if(!(fromCache == null)){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream objOut; try{ objOut = new ObjectOutputStream(baos); objOut.writeObject(fromCache); objOut.close(); this.backing.queue.add(new KeyValAction(key, this.group, baos, KVActions.PUT)); }catch(IOException e){ e.printStackTrace(); } } } }
2
@SuppressWarnings("unchecked") private void parseQuery(String query, Map<String, Object> parameters) throws UnsupportedEncodingException { if (query != null) { String pairs[] = query.split("[&]"); for (String pair : pairs) { String param[] = pair.split("[=]"); String key = null; String value = null; if (param.length > 0) { key = URLDecoder.decode(param[0], System.getProperty("file.encoding")); } if (param.length > 1) { value = URLDecoder.decode(param[1], System.getProperty("file.encoding")); } if (parameters.containsKey(key)) { Object obj = parameters.get(key); if (obj instanceof List<?>) { List<String> values = (List<String>) obj; values.add(value); } else if (obj instanceof String) { List<String> values = new ArrayList<String>(); values.add((String) obj); values.add(value); parameters.put(key, values); } } else { parameters.put(key, value); } } } }
8
@Override public void update(Document document) { NodeList node = null; NodeList items = null; Element element = null; node = document.getElementsByTagName("SomaticContext"); element = (Element) node.item(0); items = element.getElementsByTagName("FrameState"); if (!synchronizeMode && !updateFlag) return; for (int i = 0; i < items.getLength(); i++) { Element item = (Element) items.item(i); valuePanel.setFrame(item); // FIXME dirty hack String name = item.getAttribute("name"); if (name.equals("HeadPitch") || name.equals("LElbowRoll") || name.equals("LSole") || name.equals("RSole") || name.equals("RElbowRoll")) valuePanel.setChain(item); } updateFlag = false; }
8
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final PeopleInfo other = (PeopleInfo) obj; if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) { return false; } return true; }
5
private void readExcelFile(){ ArrayList<String> readTmp = new ArrayList<String>(); //儲存讀Excel用 Train tmp = new Train(); //儲存單筆火車用 try { InputStream excelFile = new FileInputStream("src/data_readme/Input_data_set_1.xls"); //要讀的檔案 jxl.Workbook readWorkBook = Workbook.getWorkbook(excelFile); //將其讀入workbook中 Sheet readSheet = readWorkBook.getSheet("Inbound Train Info"); //讀sheet tmp.inBoundTrainId = "-1"; for(int i=1 ; i<readSheet.getRows() ; i++){ //讀data for(int j=0 ; j<readSheet.getColumns() ; j++){ Cell cell = readSheet.getCell(j,i); //取得格子 String content = cell.getContents(); //取得格子資料 readTmp.add(content); } //存進去tmp train裡 if(tmp.inBoundTrainId.equals(readTmp.get(1))==false){ //若id不一樣,則代表是新的火車進來 trainSet.add(tmp); //所以先將tmp train存進去trainSet tmp=null; //告知JVM可回收 tmp = new Train(); //新另一個train tmp物件 tmp.day = readTmp.get(0); tmp.inBoundTrainId = readTmp.get(1); tmp.arrivalTime = readTmp.get(2); } tmp.inBoundBlock.add(readTmp.get(3)); //block持續儲存,新的火車會在上面判斷式清除舊的block list readTmp.clear(); } trainSet.add(tmp); //final add tmp=null; //告知JVM可回收 readTmp=null; //告知JVM可回收 trainSet.remove(0); //因為第一個物件是空值(inboundTrainId == -1) readWorkBook.close(); //關檔 } catch (FileNotFoundException e) { e.printStackTrace(); } catch (BiffException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
6
@Test public void testFailingAssumptionWithoutTestLinkAnnotation() { assumeNoException(new IllegalStateException("Could not connect to server")); }
0
private void pop(char c) throws JSONException { if (this.top <= 0) { throw new JSONException("Nesting error."); } char m = this.stack[this.top - 1] == null ? 'a' : 'k'; if (m != c) { throw new JSONException("Nesting error."); } this.top -= 1; this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; }
5
private int jjMoveStringLiteralDfa1_0(long active0) { try { curChar = input_stream.readChar(); } catch(IOException e) { jjStopStringLiteralDfa_0(0, active0); return 1; } switch(curChar) { case 97: return jjMoveStringLiteralDfa2_0(active0, 0x30000L); case 100: return jjMoveStringLiteralDfa2_0(active0, 0x100000L); case 101: return jjMoveStringLiteralDfa2_0(active0, 0x280000L); case 110: return jjMoveStringLiteralDfa2_0(active0, 0x40000L); case 114: return jjMoveStringLiteralDfa2_0(active0, 0x4000L); case 118: return jjMoveStringLiteralDfa2_0(active0, 0x8000L); default : break; } return jjStartNfa_0(0, active0); }
7
private boolean isValidState(String state){ if(state.equals(WumpusConsts.STATE_ALIVE) || state.equals(WumpusConsts.STATE_DEAD) || state.equals(WumpusConsts.STATE_GOAL)) { return true; } return false; }
3
@Override public int castingQuality(MOB mob, Physical target) { if(mob!=null) { if(mob.isInCombat()) return Ability.QUALITY_INDIFFERENT; if(CMLib.flags().isSitting(mob)) return Ability.QUALITY_INDIFFERENT; if(!CMLib.flags().isAliveAwakeMobileUnbound(mob,false)) return Ability.QUALITY_INDIFFERENT; if(target instanceof MOB) { if(CMLib.flags().canBeSeenBy(mob,(MOB)target)) return Ability.QUALITY_INDIFFERENT; final Item w=mob.fetchWieldedItem(); if((w==null)||(w.minRange()>0)||(w.maxRange()>0)) return Ability.QUALITY_INDIFFERENT; return Ability.QUALITY_MALICIOUS; } } return super.castingQuality(mob,target); }
9
public static void main(String[] args) { RendezvousObject robj = new RendezvousObject(); CallerThread cth = new CallerThread(robj); ServiceThread sth = new ServiceThread(robj); new Thread(cth, "Caller").start(); new Thread(sth, "Service").start(); }
0
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TimeStamp other = (TimeStamp) obj; if (procName == null) { if (other.procName != null) return false; } else if (!procName.equals(other.procName)) return false; if (time != other.time) return false; return true; }
7
@Override public void applyTemporaryToCurrent() { copyHashMap(tmp,cur); }
0
public static double quantile(double[] vals, double phi) { if (vals.length == 0) { return 0.0; } double[] sortedElements = Arrays.copyOf(vals, vals.length); Arrays.sort(sortedElements); int n = sortedElements.length; double index = phi * (n - 1); int lhs = (int) index; double delta = index - lhs; double result; if (lhs == n - 1) { result = sortedElements[lhs]; } else { result = (1 - delta) * sortedElements[lhs] + delta * sortedElements[lhs + 1]; } return result; }
2
protected JTable createTable(final Transition transition) { TableModel model = createModel(transition); final TipLambdaCellRenderer[] renders = new TipLambdaCellRenderer[model .getColumnCount()]; for (int i = 0; i < model.getColumnCount(); i++) renders[i] = new TipLambdaCellRenderer(model.getColumnName(i)); JTable table = new JTable(createModel(transition)) { public TableCellRenderer getCellRenderer(int r, int c) { return renders[c]; } protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) { if (ks.getKeyCode() == KeyEvent.VK_ENTER && !ks.isOnKeyRelease()) { stopEditing(false); if (e.isShiftDown()) { createTransition(transition.getFromState(), transition .getToState()); } return true; } else if (ks.getKeyCode() == KeyEvent.VK_ESCAPE) { stopEditing(true); return true; } return super.processKeyBinding(ks, e, condition, pressed); } }; table.setGridColor(Color.gray); table.setBorder(new javax.swing.border.EtchedBorder()); return table; }
5
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("<!DOCTYPE html>\n"); out.write("<html>\n"); out.write(" <head>\n"); out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n"); out.write(" \n"); out.write(" <title>JSP Page</title>\n"); out.write(" </head>\n"); out.write(" <body>\n"); out.write(" <table>\n"); out.write(" <tr>\n"); out.write(" <th>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${Book.getID()}", java.lang.String.class, (PageContext)_jspx_page_context, null)); out.write("</th>\n"); out.write(" <th>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${Book.getName()}", java.lang.String.class, (PageContext)_jspx_page_context, null)); out.write("</th>\n"); out.write(" <th>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${Book.getAuthor()}", java.lang.String.class, (PageContext)_jspx_page_context, null)); out.write("</th>\n"); out.write(" <th>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${Book.getPublisher()}", java.lang.String.class, (PageContext)_jspx_page_context, null)); out.write("</th>\n"); out.write(" <th>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${Book.getPrice()}", java.lang.String.class, (PageContext)_jspx_page_context, null)); out.write("</th>\n"); out.write(" </tr>\n"); out.write(" </table>\n"); out.write(" </body>\n"); out.write("</html>\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
5
public void render(int xMovement, int yMovement) { if(RenderWallSprite) { for (int y = 0; y < height; y++) { int yp = y + yMovement; if (yp < 0 || yp >= height) continue; for (int x = 0; x < width; x++) { int xp = x + xMovement; if (xp < 0 || xp >= width) continue; int PR = wall.SIZE - 1; pixels[xp + yp * width] = wall.pixels[(x & PR) + (y & PR) * (PR + 1)]; } } } else { for (int y = 0; y < height; y++) { int yy = y + yMovement; // if (yy < 0 || yy >= height) break; for (int x = 0; x < width; x++) { int xx = x + xMovement; // if(xx < 0 || xx >= width) break; int tileIndex = ((xx >> 4) & PixelWidth - 1) + ((yy >> 4) & PixelHeight - 1) * PixelWidth; pixels[x + y * width] = tiles[tileIndex]; } } } }
9
@Override public Vector2 mapSample(Vector2 sample) { sample.setX(sample.getX() * 2 - 1); sample.setY(sample.getY() * 2 - 1); double r; double phi; if (sample.getX() > -sample.getY()) if (sample.getX() > sample.getY()) { r = sample.getX(); phi = sample.getY() / sample.getX(); } else { r = sample.getY(); phi = 2 - sample.getX() / sample.getY(); } else if (sample.getX() < sample.getY()) { r = -sample.getX(); phi = 4 + sample.getY() / sample.getX(); } else { r = -sample.getY(); phi = 6 - sample.getX() / sample.getY(); } if (sample.getX() == 0 && sample.getY() == 0) { phi = 0; } phi *= Math.PI / 4; return new Vector2( r * Math.cos(phi), r * Math.sin(phi)); }
5
public boolean makeMove(String move) { Field[][] fields = gameboard.getFields(); int centerX = fields.length/2; int centerY = fields[centerX].length/2; if((move.equals("N") && !gameboard.isMoveable(centerX, centerY-1)) || (move.equals("E") && !gameboard.isMoveable(centerX+1, centerY)) || (move.equals("S") && !gameboard.isMoveable(centerX, centerY+1)) || (move.equals("W") && !gameboard.isMoveable(centerX-1, centerY))) { return false; } Ant ant = fields[centerX][centerY].getAnt(); if(ant == null) return false; ant.makeMove(move); vizFrame.updateGameboard(gameboard); sendMove(move); return true; }
9
private boolean addIfNeededToPruneSet(TagNode tagNode, CleanTimeValues cleanTimeValues) { if ( cleanTimeValues.pruneTagSet != null ) { for(ITagNodeCondition condition: cleanTimeValues.pruneTagSet) { if ( condition.satisfy(tagNode)) { addPruneNode(tagNode, cleanTimeValues); properties.fireConditionModification(condition, tagNode); return true; } } } if ( cleanTimeValues.allowTagSet != null && !cleanTimeValues.allowTagSet.isEmpty() ) { for(ITagNodeCondition condition: cleanTimeValues.allowTagSet) { if ( condition.satisfy(tagNode)) { return false; } } if (!tagNode.isAutoGenerated()) { properties.fireUserDefinedModification(true, tagNode, ErrorType.NotAllowedTag); } addPruneNode(tagNode, cleanTimeValues); return true; } return false; }
8
public void draw(Graphics2D g2) { BufferedImage image = animation.getImage(action); if (lookingRight) { g2.drawImage(image, (int) xPos, (int) yPos, width, height, null); } else { g2.drawImage(image, (int) xPos + width, (int) yPos, -width, height, null); } }
1
* @throws Exception */ private JMethod generateCommandSignature(JDefinedClass jClusterInterface, ZclCommandDescriptor zclCommandDescriptor, boolean addContext) throws Exception { if (zclCommandDescriptor.isResponse()) return null; // FIXME: the return type depends on the returned response!!!! JType jReturnType = null; ZclCommandDescriptor responseCommand = zclCommandDescriptor.getResponse(); if (responseCommand != null) jReturnType = jTypeForZbTypename(jModel, jClusterInterface.getPackage(), responseCommand.getName(), responseCommand); else jReturnType = jModel.VOID; JMethod jMethodCommandSignature = jClusterInterface.method(JMod.PUBLIC, jReturnType, getCommandName(zclCommandDescriptor)); jMethodCommandSignature._throws(ApplianceException.class); jMethodCommandSignature._throws(ServiceClusterException.class); if (addContext && !contextLast) jMethodCommandSignature.param(IEndPointRequestContext.class, "context"); Vector zclParametersDescriptors = zclCommandDescriptor.getParametersDescriptors(); for (int i = 0; i < zclParametersDescriptors.size(); i++) { ZclField zclParameterDescriptor = (ZclField) zclParametersDescriptors.get(i); JType type = jTypeForZbTypename(jModel, jClusterInterface.getPackage(), zclParameterDescriptor.getType(), zclParameterDescriptor); if (zclParameterDescriptor.isArray()) { jMethodCommandSignature.param(type.array(), zclParameterDescriptor.getName()); } else { jMethodCommandSignature.param(type, zclParameterDescriptor.getName()); } } if (addContext && contextLast) jMethodCommandSignature.param(IEndPointRequestContext.class, "context"); if (confirmationRequiredField) jMethodCommandSignature.param(boolean.class, "confirmationRequired"); return jMethodCommandSignature; }
9
public void set(int index, int datum) { RangeCheck(index); data[index] = datum; }
0
private int[] getStyle(int index) { if (m_styleOffsets==null || m_styles==null || index>=m_styleOffsets.length) { return null; } int offset=m_styleOffsets[index]/4; int style[]; { int count=0; for (int i=offset;i<m_styles.length;++i) { if (m_styles[i]==-1) { break; } count+=1; } if (count==0 || (count%3)!=0) { return null; } style=new int[count]; } for (int i=offset,j=0;i<m_styles.length;) { if (m_styles[i]==-1) { break; } style[j++]=m_styles[i++]; } return style; }
9
public void insert(Pnode node){ count++; if(pq==null){ pq=node; } else if(pq.freq>node.freq){ node.next=pq; pq=node; } else{ Pnode temp = pq; Pnode prev = null; while(temp.next!=null && temp.freq<=node.freq){ prev=temp; temp=temp.next; } if(temp.freq>node.freq){ prev.next=node; node.next=temp; } else{ temp.next=node; } } }
5
public void setWindow(LatLng center, double deltaLat, double deltaLng) { if (deltaLat == Double.NaN || deltaLat == Double.POSITIVE_INFINITY || deltaLat == Double.NEGATIVE_INFINITY) throw new IllegalArgumentException("Invalid latitude delta."); if (deltaLng == Double.NaN || deltaLng == Double.POSITIVE_INFINITY || deltaLng == Double.NEGATIVE_INFINITY) throw new IllegalArgumentException("Invalid longitude delta."); double dlat = min(abs(deltaLat), 180.0); this.setLatWindow(center.getLatitude(), dlat); double dlng = min(abs(deltaLng), 360.0); this.setLngWindow(center.getLongitude(), dlng); this.center = center; }
6
public void palyaEpites(Mezo[][] mezok, List<List<Mezo>> utvonalak) { this.utvonalak = utvonalak; createPrototypes(); karakterek = new ArrayList<GyuruSzovetsege>(); ellensegeSzama = 0; for (int x = 0; x < getMezok().length; x++) { for (int y = 0; y < getMezok()[x].length; y++) { getMezok()[x][y].setSzomszedok(1); } } for (int x = 0; x < mezok.length; x++) { for (int y = 0; y < mezok[x].length; y++) { mezok[x][y].setX(x * 60); mezok[x][y].setY(y * 60); view.addNewPaintable(new MezoPaintable(mezok[x][y].getType(), mezok[x][y])); } } Random r = new Random(System.currentTimeMillis()); for (int i = 0; i < 60; i++) { GyuruSzovetsege karakter = null; if (r.nextInt(4) == 3) { karakter = new Ember(utvonalak); } else if (r.nextInt(4) == 3) { karakter = new Torp(utvonalak); } else if (r.nextInt(4) == 3) { karakter = new Hobbit(utvonalak); } else { karakter = new Tunde(utvonalak); } this.view.addNewPaintable(new GyuruSzovetsegePaintable(karakter .getType(), karakter)); karakterek.add(karakter); } Collections.shuffle(karakterek, r); ellenfelekSzamaProgress.setValue(karakterek.size()); ellenfelekSzamaProgress.setString(karakterek.size()+" db"); }
8