method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
9fb0166e-52b9-4016-8597-1a80381c45ad
2
List<Compound> list() { if (p == null) { p = new ArrayList<Compound>(); for (T el : list) { p.add(create(el)); } } return p; }
715880d1-0e86-4183-8284-ee0c29c77f00
4
public String diff_prettyHtml(LinkedList<Diff> diffs) { StringBuilder html = new StringBuilder(); for (Diff aDiff : diffs) { String text = aDiff.text.replace("&", "&amp;").replace("<", "&lt;") .replace(">", "&gt;").replace("\n", "&para;<br>"); switch (aDiff.operation) { case INSERT: html.append("<ins style=\"background:#e6ffe6;\">").append(text) .append("</ins>"); break; case DELETE: html.append("<del style=\"background:#ffe6e6;\">").append(text) .append("</del>"); break; case EQUAL: html.append("<span>").append(text).append("</span>"); break; } } return html.toString(); }
8cd034e9-fabf-4857-a12e-a82b65283181
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Tache)) { return false; } Tache other = (Tache) object; if ((this.num == null && other.num != null) || (this.num != null && !this.num.equals(other.num))) { return false; } return true; }
246b0477-274d-43bb-928f-de8b37695a25
6
public boolean httpPostWithFile(String url, String queryString, List<QParameter> files, QAsyncHandler callback, Object cookie) { if (url == null || url.equals("")) { return false; } url += '?' + queryString; PostMethod httpPost = new PostMethod(url); List<QParameter> listParams = QHttpUtil.getQueryParameters(queryString); int length = listParams.size() + (files == null ? 0 : files.size()); Part[] parts = new Part[length]; int i = 0; for (QParameter param : listParams) { parts[i++] = new StringPart(param.mName, QHttpUtil.formParamDecode(param.mValue), "UTF-8"); } try { for (QParameter param : files) { File file = new File(param.mValue); parts[i++] = new FilePart(param.mName, file.getName(), file, QHttpUtil.getContentType(file), "UTF-8"); } } catch (FileNotFoundException e) { e.printStackTrace(); return false; } httpPost.setRequestEntity(new MultipartRequestEntity(parts, httpPost .getParams())); mThreadPool.submit(new AsyncThread(httpPost, callback, cookie)); return true; }
476307af-56d4-4243-9e79-454f960047fc
5
@Override public Polynomial<Double, Double, Double> setCoefficient(final int degree, final Double value) { if (degree < 0) throw new IllegalArgumentException("The specified degree must be " + "non-negative."); if (this.getDegree() < degree) throw new IllegalArgumentException("The specified degree must be " + "less than or equal to the degrees of this polynomial."); if (!this._validator.isValid(value)) throw new IllegalArgumentException( this._validator.message(value, "Value")); double[] coefficients = new double[this._coefficients.length]; for (int d = 0; d < this._coefficients.length; d++) if (d == degree) coefficients[d] = value; else coefficients[d] = this._coefficients[d]; return new PolynomialReal(coefficients); }
aa7d8fbe-4867-4b07-acdd-76b205c9b161
4
private static void sortStudents(ArrayList<Student> studentArray2) { //Student top = studentArray2.get(0); int j, first; for(int i=studentArray2.size() - 1; i > 0; i--) { first = 0; for(j = 1; j <= i; j++) { if((studentArray2.get(j).getLength()) < (studentArray2.get(first).getLength())) first = j; } Student temp = studentArray2.get(first); studentArray2.set(first, studentArray2.get(i)); studentArray2.set(i, temp); } for(int i=0; i < studentArray2.size(); i++) { System.out.println(studentArray2.get(i)); } }
7257fee1-573b-4260-b8f9-b6cc99a3a454
4
public void treeNodesInserted(TreeModelEvent e) { TreePath path = e.getTreePath(); Object root = tree.getModel().getRoot(); TreePath pathToRoot = new TreePath(root); if (path != null && path.getParentPath() != null && path.getParentPath().getLastPathComponent().equals(root) && !tree.isExpanded(pathToRoot)) { TreeUtils.expandPathOnEdt(tree, new TreePath(root)); } }
7d416e1f-15b8-4e6f-b574-4194756ae05b
5
private String sendDataOut(String key, String data) throws TimeoutException { ClientInfo ci = new ClientInfo(); ci.setClientKey(key); PooledBlockingClient pbc = null; try { pbc = blockingClientPool.getBlockingClient(ci); if (pbc == null) { throw new TimeoutException("sdo: we do not have any client[pbc] to connect to server!"); } BlockingClient bc = pbc.getBlockingClient(); if (bc == null) { throw new TimeoutException("we do not have any client[bc] to connect to server!"); } bc.sendBytes(data, charset); return bc.readCRLFLine(); } catch (IOException e) { if (pbc != null) { logger.log(Level.WARNING, "We had an ioerror will close client! " + e, e); pbc.close(); } throw new TimeoutException("We had ioerror " + e); } finally { if (pbc != null) { blockingClientPool.returnBlockingClient(pbc); } } }
5d8b0302-3a17-4d84-a552-29111658b8ac
2
private void jj_save(int index, int xla) { JJCalls p = jj_2_rtns[index]; while (p.gen > jj_gen) { if (p.next == null) { p = p.next = new JJCalls(); break; } p = p.next; } p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla; }
ea111a4f-4b8f-406a-bb56-6a7b6e1e9c47
2
static void rotate(int[][] matrix) { int n = matrix.length; int tmp; for (int offset = 0; offset < n/2; offset++) { for (int i = offset; i<offset+n-2*offset-1; i++) { tmp = matrix[offset][i]; matrix[offset][i] = matrix[n-1-i][offset]; matrix[n-1-i][offset] = matrix[n-1-offset][n-1-i]; matrix[n-1-offset][n-1-i] = matrix[i][n-1-offset]; matrix[i][n-1-offset] = tmp; } } }
a2bfbddd-3b97-4aaa-9381-3bcaf6e0e51e
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Dokument)) { return false; } Dokument other = (Dokument) object; if ((this.dokumentid == null && other.dokumentid != null) || (this.dokumentid != null && !this.dokumentid.equals(other.dokumentid))) { return false; } return true; }
4e8f472f-04d9-451a-b5ff-ccb87ea2eef9
7
@Override public int compareTo(Version o) { if (o == null) { throw new NullPointerException(); } if (super.compareTo(o) != 0) { return super.compareTo(o); } if (!(o instanceof BigVersion)) { // TODO Is this necessary? } if (patch != ((BigVersion) o).patch) { return patch < ((BigVersion) o).patch ? -1 : 1; } if (build != ((BigVersion) o).build) { return build < ((BigVersion) o).build ? -1 : 1; } return 0; }
4fd67ce3-f84c-4258-9a21-10f1ff3282e7
1
public void suspend() throws InterruptedException { suspending = true; while(suspending) { Thread.sleep(10); } }
31bde575-312f-4a6c-bf40-71b817922304
4
public void alterar(Paciente pacienteAnt) throws Exception { if(pacienteAnt.getNome().isEmpty()){ throw new Exception("Nome esta invalido !!"); }else{ this.verificaNome(pacienteAnt.getNome()); } if(pacienteAnt.getCpf().equals(" . . - ")){ throw new Exception("CPF esta invalido !!"); }else{ this.verificaCPF(pacienteAnt.getCpf()); } if(pacienteAnt.getTelefone().isEmpty()){ throw new Exception("Telefone invalido !!"); } if(pacienteAnt.getEndereco().isEmpty()){ throw new Exception("Endereço invalido !!"); } PacienteDao.obterInstancia().alterar(pacienteAnt); }
4cc1dd06-b377-4524-9c61-9f9d78a2d53a
1
private static void showAllRoles() throws Exception { RoleDAO dao = new RoleDAO(); ArrayList users = (ArrayList) dao.findAll(); Role o; System.out.println("Listing roles..."); for (int i = 0; i < users.size(); i++) { o = (Role) users.get(i); System.out.println("ID: " + o.getId() + " - " + "Role: " + o.getName()); } Role admin = (Role) dao.getNewInstance(); }
2749f6a1-d5c3-4c8f-acbb-9025806f29b9
5
public static byte linear2alaw(short pcm_val) /* 2's complement (16-bit range) */ { byte mask; byte seg=8; byte aval; if (pcm_val >= 0) { mask = (byte) 0xD5; /* sign (7th) bit = 1 */ } else { mask = 0x55; /* sign bit = 0 */ pcm_val = (short) (-pcm_val - 8); } /* Convert the scaled magnitude to segment number. */ for (int i = 0; i < 8; i++) { if (pcm_val <= seg_end[i]) { seg=(byte) i; break; } } /* Combine the sign, segment, and quantization bits. */ if (seg >= 8) /* out of range, return maximum value. */ return (byte) ((0x7F ^ mask) & 0xFF); else { aval = (byte) (seg << SEG_SHIFT); if (seg < 2) aval |= (pcm_val >> 4) & QUANT_MASK; else aval |= (pcm_val >> (seg + 3)) & QUANT_MASK; return (byte) ((aval ^ mask) & 0xFF); } }
0db393bc-ba54-4c4c-a515-d875965b29e2
2
public boolean isKeysOpen() { HUD hud = null; for (int i = (huds.size() - 1); i >= 0; i--) { hud = huds.get(i); if (hud.getName().equals("ScreenKeys")) { return hud.getShouldRender(); } } return false; }
145c13cd-68a1-4c28-9d25-b2c77848743b
8
void handleLeaderDisconnection() { String [] disMessagePieces= backupAccumulatorString.split(DELIM, 3); //wait until new backupString is updated since it might take time while (disMessagePieces.length < 2) disMessagePieces= backupAccumulatorString.split(DELIM, 3); currentLeaderInfo = disMessagePieces[1]; String[] nextLeader = currentLeaderInfo.split(DELIM2); if (disMessagePieces.length == 3) backupAccumulatorString = "b " + disMessagePieces[2]; else if (disMessagePieces.length == 2) backupAccumulatorString = "b"; Boolean resolved = false; while (!resolved) { try { if (isMyIpPort(nextLeader[0], nextLeader[1])) { System.out.println("I'm the leader!"); isLeader = true; String [] slistMessagePieces = backupAccumulatorString.split(DELIM); accumulatorList.clear(); for (int i = 1; i != slistMessagePieces.length; ++i) { accumulatorList.add(slistMessagePieces[i]); } resolved = true; } else { connectToLeader(nextLeader[0], nextLeader[1]); resolved = true; } } catch (UnknownHostException e) { System.err.println("Resolution bug!"); } } //connect to master only if is leader if (isLeader) { connectToMaster(); } }
cf5fe1c8-1b39-4bc4-8727-1f7bab8af35e
3
@Test public void testCreateQueueSender() { QueueSender pub; try { pub = BrokerFactoryImpl.createSender("TestQueue"); assertNotNull("TopicPublisher is null", pub); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokerError e) { fail("Unexpected exception while creating publisher"); } catch (Exception e) { logger.error("Error while creating publisher", e); } }
a98ec8cc-0abf-4aae-a8b7-d1656debf50d
4
@Override public String getColumnName(int c) { String result; switch (c) { case 0: result = "Name"; break; case 1: result = "Registration date"; break; case 2: result = "Last log-in date"; break; case 3: result = "Id"; break; default: result = "Other column"; break; } return result; }
6bc78784-cd16-4d3c-b0e0-44fc1f2255a8
7
@Override public void onUpdate(World apples) { if (!apples.inBounds(X, Y)) { alive = false; //apples.explode(X, Y, 32, 8, 16); } if (!apples.isSolid(X, Y-10)) { Y-=10; } for (int i = 1; i < 10; i++) { if (!apples.isSolid(X, Y+i)) { Y+=i; //life-=i/2; } } near = false; if (Math.abs(apples.x-X)<64) { if (Math.abs(apples.y-Y)<64) { near = true; if (apples.keys[KeyEvent.VK_C]) { alive = false; APPLET.unlocks.set(0, 1, true); APPLET.CTD.postRSSfeed(APPLET.username + " found a rare item!","A Viking Helmet!"); } } } /*if (yspeed<12) { yspeed++; }*/ }
36196de9-a259-4498-9d9d-e30659b433c9
3
private int finishReservations() { int resFinished = 0; Iterator<ServerReservation> iterRes = reservTable.values().iterator(); while(iterRes.hasNext()) { ServerReservation sRes = iterRes.next(); if(sRes.getActualFinishTime() <= GridSim.clock()) { sRes.setStatus(ReservationStatus.FINISHED); resFinished++; iterRes.remove(); expiryTable.put(sRes.getID(), sRes); } } //------------- USED FOR DEBUGGING PURPOSES ONLY ------------------ if(resFinished > 0) { visualizer.notifyListeners(this.get_id(), ActionType.SCHEDULE_CHANGED, true); } return resFinished; }
ca5f422f-ece0-40ec-89a9-db765f57d819
9
private void parseLine(ContainerSqlFragment container, Line line) { String trimmed = line.lineTrimmed(); if (trimmed.length() == 0) { return; } if (trimmed.contains("@INCLUDE")) { parseIncludeTag(container, line); } else if (trimmed.contains("@LIKE")) { parseOperatorTag(container, line, "@LIKE"); } else if (trimmed.contains("@EQUALS")) { parseOperatorTag(container, line, "@EQUALS"); } else if (trimmed.contains("@OFFSETFETCH")) { parseOffsetFetchTag(container, line); } else if (trimmed.contains("@FETCH")) { parseFetchTag(container, line); } else if (trimmed.contains("@VALUE")) { parseValueTag(container, line); } else if (trimmed.contains("@LOOPJOIN")) { TextSqlFragment textFragment = new TextSqlFragment(trimmed, line.endOfLine()); container.addFragment(textFragment); } else if (trimmed.startsWith("@")) { throw new IllegalArgumentException("Unknown tag at start of line: " + line); } else { TextSqlFragment textFragment = new TextSqlFragment(trimmed, line.endOfLine()); container.addFragment(textFragment); } }
09b8535b-340f-49f3-adae-c3e607e93352
7
@Test public void testGetPositions() { RosterDefinition roster = new RosterDefinition(); Set<FantasyPosition> fantasyPositions = roster.getFantasyPositions(); Assert.assertNotNull("Failed to retrieve fantasy position set", fantasyPositions); Assert.assertEquals("Incorrect initial fantasy position set size", 0, fantasyPositions.size()); Set<Position> positions = roster.getPositions(); Assert.assertNotNull("Failed to retrieve position set", positions); Assert.assertEquals("Incorrect initial position set size", 0, positions.size()); for ( int i = 0; i < Position.values().length; i++ ) { roster = new RosterDefinition(); Position p1 = Position.values()[i]; FantasyPosition fp1 = new FantasyPosition(p1); roster.setStarters(fp1, 1); if ( i > 0 ) { FantasyPosition slash = new FantasyPosition(p1, Position.values()[i-1]); roster.setStarters(slash, 1); } for ( int j = 0; j < Position.values().length; j++ ) { if ( j == i || ( i > 0 && j == i - 1 ) ) { continue; } fantasyPositions = roster.getFantasyPositions(); positions = roster.getPositions(); Position p2 = Position.values()[j]; FantasyPosition fp2 = new FantasyPosition(p2); Assert.assertFalse("Roster should not contain fantasy position: " + fp2, fantasyPositions.contains(fp2)); Assert.assertFalse("Roster should not contain position: " + p2, positions.contains(p2)); if ( j > 0 ) { FantasyPosition slash = new FantasyPosition(p2, Position.values()[j-1]); Assert.assertFalse("Roster should not contain position: " + slash, fantasyPositions.contains(slash)); } } } }
00590ef4-1eff-4b1e-8f4f-3c62498f4708
5
public void savePattern(Pattern pattern, String fn) { try { fn = "recordings/" + fn; FileWriter fw = new FileWriter(new File(fn)); System.out.println("Saving pattern"); fw.write(pattern.rightHanded + "\n"); //for each frame in the pattern for (int i=0; i<pattern.length; i++) { if (i > 20) fw.flush(); //write palm Vector[] palm = pattern.palmData.get(i); String s = "p "; //position s += palm[0].getX() + " "; s += palm[0].getY() + " "; s += palm[0].getZ() + " "; //direction s += palm[1].getX() + " "; s += palm[1].getY() + " "; s += palm[1].getZ(); fw.write(s + "\n"); //write fingers for (Vector[] finger : pattern.fingerData.get(i)) { if (finger[0] != null) { s = "1 "; //position s += finger[0].getX() + " "; s += finger[0].getY() + " "; s += finger[0].getZ() + " "; //direction s += finger[1].getX() + " "; s += finger[1].getY() + " "; s += finger[1].getZ(); } else { s = "-1 "; } fw.write(s + "\n"); } fw.write("\n"); } } catch (IOException e) { e.printStackTrace(); } }
de96d175-bbd9-4ca7-a02c-9993ee53374e
5
public double score(StringWrapper s,StringWrapper t) { BagOfTokens sBag = asBagOfTokens(s); BagOfTokens tBag = asBagOfTokens(t); double lambda = 0.5; int iterations = 0; while (true) { double newLamba = 0.0; // E step: compute prob each token is draw from T for (Iterator i = sBag.tokenIterator(); i.hasNext(); ) { Token tok = (Token)i.next(); double sWeight = sBag.getWeight(tok); double tWeight = tBag.getWeight(tok); double probTokGivenT = tWeight/tBag.getTotalWeight(); double probTokGivenCorpus = ((double)getDocumentFrequency(tok))/totalTokenCount; double probDrawnFromT = lambda * probTokGivenT; double probDrawnFromCorpus = (1.0-lambda) * probTokGivenCorpus; double normalizingConstant = probTokGivenT + probTokGivenCorpus; probDrawnFromT /= normalizingConstant; probDrawnFromCorpus /= normalizingConstant; newLamba += probDrawnFromT * sWeight; } // M step: find best value of lambda newLamba /= sBag.getTotalWeight(); // halt if converged double change = newLamba - lambda; if (iterations>maxIterate || (change>= -minChange && change<=minChange)) break; else lambda = newLamba; } return lambda; }
68d59202-1e01-483c-925d-5c19f00f145a
9
public PlayerClass(String configPath) { effects = new ArrayList<PotionEffect>(); items = new ArrayList<ItemStack>(); armor = new ArrayList<ItemStack>(); if (config.contains(configPath + ".Items")) { List<Integer> itemIds = config.getIntegerList(configPath + ".Items"); for (int id : itemIds) items.add(new ItemStack(id)); } if (config.contains(configPath + ".Armor")) { List<Integer> armorIds = config.getIntegerList(configPath + ".Armor"); for (int id : armorIds) armor.add(new ItemStack(id)); } if (config.contains(configPath + ".DefaultEquiped")) defaultEquiped = new ItemStack(config.getInt(configPath + ".DefaultEquiped")); if (config.contains(configPath + ".Effects")) { List<String> effectList = config.getStringList(configPath + ".Effects"); for (String effectOptions : effectList) { String[] options = effectOptions.split(":"); PotionEffectType effectType = PotionEffectType.getByName(options[0].toUpperCase()); PotionEffect potionEffect; if (options.length == 2) { try { potionEffect = new PotionEffect(effectType, 2147483647, Integer.valueOf(options[1])); }catch(NumberFormatException e) { potionEffect = new PotionEffect(effectType, 2147483647, 1); } }else potionEffect = new PotionEffect(effectType, 2147483647, 1); effects.add(potionEffect); } } }
d37f93d9-0061-4687-98e1-e97599f69744
1
private void setStackNumElem(StackNum stackNum, Object...obj){ for(Object o : obj){ stackNum.add(o); } }
e1c9275f-748b-4022-9eec-5b551f4664ae
2
public <C extends StatefulContext> void callOnStateLeaved(StateEnum state, C context) throws Exception { Handler h = handlers.get(new HandlerType(EventType.STATE_LEAVE, null, state)); if (h != null) { ContextHandler<C> contextHandler = (ContextHandler<C>) h; contextHandler.call(context); } h = handlers.get(new HandlerType(EventType.ANY_STATE_LEAVE, null, null)); if (h != null) { StateHandler<C> stateHandler = (StateHandler<C>) h; stateHandler.call(state, context); } }
2556a6fc-1b01-42fc-ae97-eee0d1b13745
9
protected synchronized final void addTComponent(TComponent component) { if (component != null && !getTComponents().contains(component)) { /* * Only initiates the TComponent if it has not been * initiated already and this class has had it's own * parent set. */ if (component.tComponentContainer != this && parentComponent != null) { if (component.tComponentContainer != null) component.tComponentContainer.removeTComponent(component); ActionListener[] listeners = getEventListeners(); for (ActionListener listener : listeners) component.addActionListener(listener); if (component.getClass() == TScrollBar.class || component.getClass() == TSlider.class || component.getClass() == TMultiSlider.class) component.addTScrollListener(this); component.setTComponentContainer(this); } tComponents.add(component); } }
eae9e359-c7fb-4acd-be8b-9cb7ff485239
4
public void stats() { // Sort by start markers.sort(false, false); Marker prev = null; for( Marker m : markers ) { lengthStats.sample(m.size()); // Distance to previous interval if( (prev != null) // && (m.getChromosome().getId().equals(prev.getChromosome().getId())) // Same chromosome? ) { if( m.intersects(prev) ) distanceStats.sample(0); // Intersect? => Distance is zero else distanceStats.sample(m.getStart() - prev.getEnd()); // Perform distance stats } prev = m; } }
1dcc1332-b14b-4c59-9c8b-6e7c54e11d78
1
public static void closeSession() throws HibernateException { if (session != null) session.close(); session = null; }
1abd233b-ec01-46b5-b8de-d02a98747c17
5
public String deleteSpaces(String ligne){ int i; StringBuilder sb = new StringBuilder(); for(i=0;i<ligne.length();i++){ if(ligne.charAt(i) == ' '){ if(i!=0) sb.append(ligne.charAt(i)); while(i+1<ligne.length() && ligne.charAt(i+1) == ' ') i++; } else sb.append(ligne.charAt(i)); } return sb.toString(); }
5711b3e2-bb8f-446c-9c8a-f8c7f0762ab4
2
public void open() { Display display = Display.getDefault(); createContents(); shlPscDatabase.open(); shlPscDatabase.layout(); while (!shlPscDatabase.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } }
f6aca38d-a401-4321-81ba-ba909d9a8653
0
public CastlingMove(Player player, Board board, Piece piece, Field from, Field to) { super(player, board, piece, from, to); }
2fdecbf5-e65e-4fd3-afa7-c8c6c136e787
3
private boolean validPosition(int[][] temp,int x, int y) { return !(x < 0 || y < 0 || x >= temp.length || y >= temp[0].length); }
72ba5541-f81f-4522-84f2-9d11282db241
2
private void addMethod(Method method) { Deploy deploy = (Deploy) method.getAnnotation(Deploy.class); if (deploy != null) { for (String path : deploy.value()) { addMethodPath(path, method); } } }
5c4299b0-85e7-4f77-9e9f-5aebda4052fc
6
public List<RanglistenEintrag> getTeamRangliste() { List<Team> alleTeams = eloPersistence.createQuery("select distinct t from Team t join fetch t.punktzahlHistorie", Team.class) .getResultList(); Collections.sort(alleTeams, new Comparator<Team>() { public int compare(Team o1, Team o2) { return (o1.getPunktzahl().getPunktzahl() - o2.getPunktzahl().getPunktzahl()) * -1; } }); /* Nur aktive Spieler */ for (Iterator<Team> i = alleTeams.iterator(); i.hasNext();) { Team team = i.next(); if (!team.getSpieler1().isVisible() || !team.getSpieler2().isVisible()) { i.remove(); } } List<RanglistenEintrag> rangliste = new ArrayList<RanglistenEintrag>(); int rang = 1; for (Team team : alleTeams) { int anzahlSpiele = team.getPunktzahlHistorie().size() - 1; int anzahlSiege = 0; for (EloPunktzahl punktzahl : team.getPunktzahlHistorie()) { if (punktzahl.getZuwachs() > 0) { anzahlSiege++; } } RanglistenEintrag eintrag = new RanglistenEintrag(team.getId(), rang, team.getSpieler1().getName() + "/" + team.getSpieler2().getName(), team.getPunktzahl().getPunktzahl(), anzahlSpiele, anzahlSiege); rangliste.add(eintrag); rang++; } return rangliste; }
a471dd47-a8e4-49f5-a763-105cc89d5261
2
public GenericNode getOther(GenericNode node) { if(node1 == node) return node2; if(node2 == node) return node1; return null; }
d17cbde2-16a6-44a8-b1c3-bf80abac2ce0
6
static final void method2060(byte i, boolean bool) { if (i > -4) method2059(-6); anInt3484++; Class5_Sub3.anInt8374++; BufferedPacket class348_sub47 = Class286_Sub3.createBufferedPacket(Class348_Sub34.aClass351_6970, Class348_Sub23_Sub2.outgoingGameIsaac); Class348_Sub42_Sub14.queuePacket(37, class348_sub47); for (Class348_Sub41 class348_sub41 = (Class348_Sub41) Class125.aClass356_4915.method3484(0); class348_sub41 != null; class348_sub41 = (Class348_Sub41) Class125.aClass356_4915.method3482(0)) { if (!class348_sub41.method2712((byte) 4)) { class348_sub41 = (Class348_Sub41) Class125.aClass356_4915.method3484(0); if (class348_sub41 == null) break; } if ((((Class348_Sub41) class348_sub41).anInt7053 ^ 0xffffffff) == -1) Class127_Sub1.method1118(true, bool, class348_sub41, 2533); } if (BufferedRasterizer.aClass46_4730 != null) { Class251.method1916(-9343, BufferedRasterizer.aClass46_4730); BufferedRasterizer.aClass46_4730 = null; } }
f94bae19-1832-4e33-beaf-0149318077d5
3
public void vitesseMoins(int $param_int_1) throws java.rmi.RemoteException { try { ref.invoke(this, $method_vitesseMoins_0, new java.lang.Object[] {new java.lang.Integer($param_int_1)}, 4692753105378022573L); } catch (java.lang.RuntimeException e) { throw e; } catch (java.rmi.RemoteException e) { throw e; } catch (java.lang.Exception e) { throw new java.rmi.UnexpectedException("undeclared checked exception", e); } }
1c673475-d918-4df6-9ca9-1c0547855328
9
private void read(FileInput fin){ this.nAnalyteConcns = fin.numberOfLines()-1; this.titleZero = fin.readLine(); this.nResponses = this.nAnalyteConcns; this.analyteConcns = new double[this.nAnalyteConcns]; this.responses = new double[this.nAnalyteConcns]; this.weights = new double[this.nAnalyteConcns]; int weightCheck = 0; String line = null; String word = null; int wL = 0; int pos1 = -1; int pos2 = -1; int pos3 = -1; for(int i=0; i<this.nAnalyteConcns; i++){ line = (fin.readLine()).trim(); // analyte concn pos1 = this.separatorPosition(line); if(pos1==-1){ throw new IllegalArgumentException("Input file line " + (i+1) + ": analyte concentration and response value required for all data points"); } else{ word = line.substring(0, pos1); this.analyteConcns[i] = Double.parseDouble(word); line = (line.substring(pos1+1)).trim();; wL = line.length(); if(wL<1)throw new IllegalArgumentException("Input file line " + (i+1) + ": response value required for all data points"); // response pos2 = this.separatorPosition(line); if(pos2==-1){ word = line; } else{ word = line.substring(0, pos2); } this.responses[i] = Double.parseDouble(word); if(pos2!=-1){ line = (line.substring(pos2+1)).trim(); wL = line.length(); // weight if(wL>0){ pos3 = this.separatorPosition(line); if(pos3==-1){ word = line.trim(); } else{ word = (line.substring(0, pos3)).trim(); } this.weights[i] = Double.parseDouble(word); if(this.weights[i]==1.0)weightCheck++; } } } } this.analyteConcnFlag = 0; this.analyteEntered = true; this.responsesEntered = true; if(weightCheck!=this.nAnalyteConcns){ this.nWeights = this.nAnalyteConcns; this.weights = this.checkWeights(Conv.copy(this.weights)); this.weightsEntered = true; } this.dataRead = true; }
441b69f0-e6d5-4097-a5fa-731e28d25676
9
public static void addPerson(Role subRole) { if (subRole instanceof CwagonerHostRole) { host = (CwagonerHostRole)subRole; host.setNumTables(numTables); for (CwagonerWaiter iWaiter : Waiters) { host.addWaiter(iWaiter); } } else if (subRole instanceof CwagonerCashierRole) { cashier = (CwagonerCashierRole)subRole; } else if (subRole instanceof CwagonerCookRole) { cook = (CwagonerCookRole)subRole; cook.setCashier(cashier); } else if (subRole instanceof CwagonerCustomerRole) { Customers.add((CwagonerCustomerRole) subRole); ((CwagonerCustomerRole)subRole).setHost(host); ((CwagonerCustomerRole) subRole).setCashier(cashier); } else if (subRole instanceof CwagonerSharedWaiterRole) { Waiters.add((CwagonerSharedWaiterRole)subRole); if (host != null) host.addWaiter((CwagonerWaiter)subRole); } else if (subRole instanceof CwagonerWaiterRole) { Waiters.add((CwagonerWaiterRole) subRole); ((CwagonerWaiterRole)subRole).setHost(host); if (host != null) host.addWaiter((CwagonerWaiter)subRole); } }
3fe73598-08ff-437f-be0d-5b5478ed4fa9
8
@Override public boolean equals(Object anObject) { if (this == anObject) return true; if (anObject == null || getClass() != anObject.getClass()) return false; Element element = (Element) anObject; if (emptyElementTag != element.emptyElementTag) return false; if (!attributeNames.equals(element.attributeNames)) return false; if (!name.equals(element.name)) return false; for(String an : attributeNames) { if(! this.attributeValue(an).equals(element.attributeValue(an))) { return false; } } return true; }
5089b27a-feba-428c-b7c6-b1e7a8cca18d
9
public String parseCommand(String inputCommand) { if(inputCommand.equals("")) { return "No command entered!"; } ArrayList<String> commands = new ArrayList<String>(); for(String command : inputCommand.split(" ")) { commands.add(command); } if(commands.size() == 0) { return "Empty commands are invalid!"; } String keyword = commands.get(0); if(!commandWords.commandExists(keyword)) { return "The command entered does not exist!"; } if(gameData.hasGameStarted() == false && !commandWords.isPreGameCommand(keyword)) { return "Invalid pre-game command!"; } if(!commandWords.isValidCommand(commands)) { return "The command entered has an incorrect syntax. Please refer to the commands manual."; } if(commands.size() > 1) { commands.remove(0); if(commands.size() == 1) { return commandActions.invokeAction(keyword, commands.get(0)); } return commandActions.invokeAction(keyword, commands); } return commandActions.invokeAction(keyword); }
3ca3262b-b56b-4bfd-bcf3-1b6ce00dc99d
8
@Override public boolean tick(Tickable ticking, int tickID) { if((affected!=null)&&(affected instanceof Room)) { final Room R=(Room)affected; DeadBody B=null; for(int i=0;i<R.numItems();i++) { final Item I=R.getItem(i); if((I instanceof DeadBody) &&(I.container()==null) &&(!((DeadBody)I).isPlayerCorpse()) &&(((DeadBody)I).getMobName().length()>0)) { B=(DeadBody)I; break; } } if(B!=null) { new Prayer_AnimateSkeleton().makeSkeletonFrom(R,B,null,level); B.destroy(); level+=3; } } return super.tick(ticking,tickID); }
9a1e7d15-126b-4ebe-9139-dd99fe80968a
7
@Override public void performClassification( HashMap<Integer, RawImageInstance> rawInstances, HashMap<Integer, Instances> entireData, Instances trainData, HashMap<Integer, Instances> testData) throws Exception { System.err.println("Evalutating accuracy..."); int numClassifiers = classifiers.length; // get starting accuracy float[] accuracies = new float[numClassifiers]; int numLabelRequest = 0, numImgSeen = 0; for (int i = 0; i < numClassifiers; i++) { HashMap<Integer, Double> predictionResults = predictor .makeBatchPredictions(classifiers[i], entireData); accuracies[i] = evaluator.getPredictionAccuracy(rawInstances, predictionResults); } evaluator .printEvaluationResult(numImgSeen, numLabelRequest, accuracies); System.err.println("Active learning..."); // begin active learning for (int id : testData.keySet()) { numImgSeen++; System.err.println("input image: " + id); Instances curInstances = testData.get(id); if (shouldRequestLable(curInstances)) { // request label String labelStr = Integer.toString(rawInstances.get(id) .getLabel()); numLabelRequest++; for (int i = 0; i < curInstances.numInstances(); i++) { Instance inst = curInstances.get(i); double[] oldValues = inst.toDoubleArray(); Instance newInst = new DenseInstance( DataPreprocessor.FEATURE_LENTH + 1); for (int j = 0; j < DataPreprocessor.FEATURE_LENTH; j++) { newInst.setValue(curInstances.attribute(j), oldValues[j]); } newInst.setValue(curInstances .attribute(DataPreprocessor.FEATURE_LENTH), labelStr); trainData.add(newInst); } System.err.println("Train again the classifiers..."); // train again for (int i = 0; i < numClassifiers; i++) { classifiers[i] = ImageLabelPredictor.createRandomForest(i); classifiers[i].buildClassifier(trainData); } System.err.println("Reevaluating the classifiers..."); // reevaluate accuracies Arrays.fill(accuracies, 0f); for (int i = 0; i < numClassifiers; i++) { HashMap<Integer, Double> predictionResults = predictor .makeBatchPredictions(classifiers[i], entireData); accuracies[i] = evaluator.getPredictionAccuracy( rawInstances, predictionResults); } evaluator.printEvaluationResult(numImgSeen, numLabelRequest, accuracies); } } }
1b043462-74cf-4f75-aaa8-8fdc9d038b84
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PackageMetaResource other = (PackageMetaResource) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; }
cb1ae12e-18d4-438d-815f-dba427602bd3
5
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pos other = (Pos) obj; if (x != other.x) return false; if (y != other.y) return false; return true; }
88937513-1b23-4f71-aa2b-c3572b571d7d
6
public static SampleSet generateData( final int samples, final float rel, final Random rnd ) { // final SampleSet result = new SampleSet(); // int size1 = (int)(samples * rel); int size2 = samples - size1; // int size = size1 + size2; while (size > 0) { Vector2f v = new Vector2f(rnd.nextFloat(), rnd.nextFloat()); Vector2f l1 = Vector2f.sub(c1, v); Vector2f l2 = Vector2f.sub(c2, v); Vector2f l3 = Vector2f.sub(c3, v); if (l1.length() > r1 && l2.length() > r2 && l3.length() > r3) { // // outer point // if (size2 > 0) { result.add(new Sample( new double[]{v.x, v.y}, new double[]{0.0}) ); size2--; } } else { // // inner point // if (size1 > 0) { result.add( new Sample(new double[]{v.x, v.y}, new double[]{1.0}) ); size1--; } } size--; } return result; }
a9600e56-0f2e-47fc-a3f3-9822c81c59be
9
private boolean r_mark_suffix_with_optional_s_consonant() { int v_1; int v_2; int v_3; int v_4; int v_5; int v_6; int v_7; // (, line 143 // or, line 145 lab0: do { v_1 = limit - cursor; lab1: do { // (, line 144 // (, line 144 // test, line 144 v_2 = limit - cursor; // literal, line 144 if (!(eq_s_b(1, "s"))) { break lab1; } cursor = limit - v_2; // next, line 144 if (cursor <= limit_backward) { break lab1; } cursor--; // (, line 144 // test, line 144 v_3 = limit - cursor; if (!(in_grouping_b(g_vowel, 97, 305))) { break lab1; } cursor = limit - v_3; break lab0; } while (false); cursor = limit - v_1; // (, line 146 // (, line 146 // not, line 146 { v_4 = limit - cursor; lab2: do { // (, line 146 // test, line 146 v_5 = limit - cursor; // literal, line 146 if (!(eq_s_b(1, "s"))) { break lab2; } cursor = limit - v_5; return false; } while (false); cursor = limit - v_4; } // test, line 146 v_6 = limit - cursor; // (, line 146 // next, line 146 if (cursor <= limit_backward) { return false; } cursor--; // (, line 146 // test, line 146 v_7 = limit - cursor; if (!(in_grouping_b(g_vowel, 97, 305))) { return false; } cursor = limit - v_7; cursor = limit - v_6; } while (false); return true; }
48f5593d-3ed9-40fe-b2fe-fcac0a39fd63
2
private byte[] makeHeader(int number) { byte[] header = new byte[HEADER_SIZE]; if(number >= (1 << (8* HEADER_SIZE))) { throw new InputMismatchException("The round number " + number + " exceeds the bound of " + (1 << (8*HEADER_SIZE))); } int i = 0; do { header[i] = (byte) (number % 256); number >>= 8; i++; } while(number != 0); return header; }
307ec392-ee28-4933-8e07-4ba0479bb3e1
4
@Override public List<ConcertInfo> getConcertsForArtist(String artist) throws LastFmConnectionException { if(artist==null) throw new IllegalArgumentException("artist"); SimpleDateFormat simpleDate = new SimpleDateFormat("EEE, dd MMM YYYY", Locale.US); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder; Document configuration; XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); XPathExpression expr; Object result; try { builder = domFactory.newDocumentBuilder(); configuration = builder.parse(baseDir+ "events_" + artist.toLowerCase() +".xml"); expr = xpath.compile("//event"); result = expr.evaluate(configuration, XPathConstants.NODESET); } catch (Exception e) { throw new LastFmConnectionException("Could not load Events XML file", e); } NodeList nodes = (NodeList) result; ArrayList<ConcertInfo> events = new ArrayList<ConcertInfo>(); String venue; String name; String dateStr; String geoLat; String geoLon; for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); try { venue = (String) xpath.compile("venue/location/city/text()").evaluate(node, XPathConstants.STRING); name = (String) xpath.compile("venue/name/text()").evaluate(node, XPathConstants.STRING); dateStr = (String) xpath.compile("startDate/text()").evaluate(node, XPathConstants.STRING); Date date = simpleDate.parse(dateStr); geoLat = (String) xpath.compile("venue/location/point/lat/text()").evaluate(node, XPathConstants.STRING); geoLon = (String) xpath.compile("venue/location/point/long/text()").evaluate(node, XPathConstants.STRING); GeoPoint point = new GeoPoint(geoLat, geoLon); ConcertInfo info = new ConcertInfo(artist, venue, name, date, point); events.add(info); } catch (Exception e){ throw new LastFmConnectionException("Could not parse XML data",e); } } return events; }
c36c86e7-dee0-423f-9342-2a00a09a2413
4
@Test public void TestAll() throws IOException, SyntaxFormatException { for (File file : new File("src/test/resources/testprogs/").listFiles()) { if (file.isFile()) { if (file.getPath().indexOf(StatementTest.simpleFuncTest4) >= 0) { continue; } if (!file.getPath().endsWith(".txt")) { continue; } TouchDataHelper.resetAll(); System.out.println(file.getPath()); checkGraph(file.getPath(), "interference"); } } }
36430ec8-ed5d-4a1a-9f9f-b2097f9ae8a4
2
protected void addBlockToArea(final Block block, final Player player, final PlanArea area, final Material type, final short durability) { if (area.isCommitted()) { // If committed area, means that we're changing the structure underlying the plan, so // replace the original. area.addOriginalBlock(block, true); } else { if (type != null) { // 'Refund' the item when placed in a planning area. ItemStack newItem = new ItemStack(type, 1, durability); player.getInventory().addItem(newItem); } area.addPlanBlock(block); } }
b5583425-715e-4e51-a792-13d7eae4b0f8
3
@Override public boolean isMine(String command) { Iterable<String> ans = Splitter.on(' ').omitEmptyStrings().split(command); arguments.clear(); CollectionUtils.addAll(arguments, ans.iterator()); if (arguments.get(0).equals(commandName)) { if (argumentNumber != 0 && arguments.size() != argumentNumber) { error = "Invalid argument number."; return false; } return true; } return false; }
8af652fb-b628-452b-8949-59de438a37dc
7
public static void figureOutConnect(PrintStream w, Object... comps) { // add all the components via Proxy. List<ComponentAccess> l = new ArrayList<ComponentAccess>(); for (Object c : comps) { l.add(new ComponentAccess(c)); } // find all out slots for (ComponentAccess cp_out : l) { w.println("// connect " + objName(cp_out)); // over all input slots. for (Access fout : cp_out.outputs()) { String s = " out2in(" + objName(cp_out) + ", \"" + fout.getField().getName() + "\""; for (ComponentAccess cp_in : l) { // skip if it is the same component. if (cp_in == cp_out) { continue; } // out points to in for (Access fin : cp_in.inputs()) { // name equivalence enought for now. if (fout.getField().getName().equals(fin.getField().getName())) { s = s + ", " + objName(cp_in); } } } w.println(s + ");"); } w.println(); } }
1c6e91e5-33a5-49eb-ae88-d7c57fb0e3f9
7
private void resetPosition(Tile current, int row, int col) { if (current == null) return; int x = getTileX(col); int y = getTileY(row); int distX = current.getX() - x; int distY = current.getY() - y; if (Math.abs(distX) < Tile.SLIDE_SPEED) { current.setX(current.getX() - distX); } if (Math.abs(distY) < Tile.SLIDE_SPEED) { current.setY(current.getY() - distY); } if (distX < 0) { current.setX(current.getX() + Tile.SLIDE_SPEED); } if (distY < 0) { current.setY(current.getY() + Tile.SLIDE_SPEED); } if (distX > 0) { current.setX(current.getX() - Tile.SLIDE_SPEED); } if (distY > 0) { current.setY(current.getY() - Tile.SLIDE_SPEED); } }
c024d732-7f1f-4287-a54a-d8f1dea77704
2
public MenuBar() { // FILE JMenu menuFile = new JMenu("File"); this.add(menuFile); JMenuItem itemOpenSource = new JMenuItem("Open source file"); itemOpenSource.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileFilter(new FileFilter() { @Override public boolean accept(File file) { return !file.isDirectory() && file.getAbsolutePath().endsWith(".xml"); } @Override public String getDescription() { return null; } }); fileChooser.showOpenDialog(MenuBar.this.getParent()); CHOOSEN_FILE_PATH = fileChooser.getSelectedFile().getAbsolutePath(); } }); menuFile.add(itemOpenSource); JMenuItem itemExit = new JMenuItem("Exit"); itemExit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Integer reply = JOptionPane.showConfirmDialog(null, "Are you sure ?"); if (JOptionPane.YES_OPTION == reply) { System.exit(0); } } }); menuFile.add(itemExit); }
c2bf0647-167c-4f9f-bcc0-e8fb5d90192a
3
public int get_bits(int number_of_bits) { int returnvalue = 0; int sum = bitindex + number_of_bits; // E.B // There is a problem here, wordpointer could be -1 ?! if (wordpointer < 0) wordpointer = 0; // E.B : End. if (sum <= 32) { // all bits contained in *wordpointer returnvalue = (framebuffer[wordpointer] >>> (32 - sum)) & bitmask[number_of_bits]; // returnvalue = (wordpointer[0] >> (32 - sum)) & bitmask[number_of_bits]; if ((bitindex += number_of_bits) == 32) { bitindex = 0; wordpointer++; // added by me! } return returnvalue; } // E.B : Check that ? //((short[])&returnvalue)[0] = ((short[])wordpointer + 1)[0]; //wordpointer++; // Added by me! //((short[])&returnvalue + 1)[0] = ((short[])wordpointer)[0]; int Right = (framebuffer[wordpointer] & 0x0000FFFF); wordpointer++; int Left = (framebuffer[wordpointer] & 0xFFFF0000); returnvalue = ((Right << 16) & 0xFFFF0000) | ((Left >>> 16)& 0x0000FFFF); returnvalue >>>= 48 - sum; // returnvalue >>= 16 - (number_of_bits - (32 - bitindex)) returnvalue &= bitmask[number_of_bits]; bitindex = sum - 32; return returnvalue; }
5f2dcb7a-5d34-4c88-89c0-4a401ca692bc
4
Module getSubModule(String name) { if (StringUtils.isEmpty(name) || !hasSubModules()) { return null; } for (Module module : this.subModules) { if (name.equals(module.name)) { return module; } } return null; }
05bfb7b7-6b31-491d-a643-77d172bc0db2
1
public void setBtn_Std_Fontstyle(Fontstyle fontstyle) { if (fontstyle == null) { this.buttonStdFontStyle = UIFontInits.STDBUTTON.getStyle(); } else { this.buttonStdFontStyle = fontstyle; } somethingChanged(); }
e4279067-9622-44e1-b978-8a32eb1a643a
8
public void update() { if (fireRate > 0) fireRate--; int xa = 0, ya = 0; if (anim < 7500) anim++; else anim = 0; if (input.up) ya--; if (input.down) ya++; if (input.left) xa--; if (input.right) xa++; if (xa != 0 || ya != 0) { move(xa, ya); moving = true; } else { moving = false; } clear(); updateShooting(); }
52e80727-0ef7-43d0-b33d-71ad64a9b986
8
public static DCLayer createLayer(ConstantProvider cp, int sector, int superlayer, int layer) { if(!(0<=sector || sector<6)) { System.err.println("Error: sector should be 0...5"); return null; } if(!(0<=superlayer || superlayer<6)) { System.err.println("Error: superlayer should be 0...6"); return null; } if(!(0<=layer || layer<6)) { System.err.println("Error: layer should be 0...5"); return null; } int region = superlayer/2; // Load constants double dist2tgt = cp.getDouble("/geometry/dc/region/dist2tgt", region); double midgap = cp.getDouble("/geometry/dc/region/midgap", region); double thtilt = Math.toRadians(cp.getDouble("/geometry/dc/region/thtilt", region)); double thopen = Math.toRadians(cp.getDouble("/geometry/dc/region/thopen", region)); double xdist = cp.getDouble("/geometry/dc/region/xdist", region); double d_layer = cp.getDouble("/geometry/dc/superlayer/wpdist", superlayer); double thmin = Math.toRadians(cp.getDouble("/geometry/dc/superlayer/thmin", superlayer)); double thster = Math.toRadians(cp.getDouble("/geometry/dc/superlayer/thster", superlayer)); int numWires = cp.getInteger("/geometry/dc/layer/nsensewires", 0); // Calculate the midpoint (gx, 0, gz) of the guard wire nearest to the // beam in the first guard wire layer of the current superlayer double gz = dist2tgt; if (superlayer%2 == 1) { gz += midgap + 21*cp.getDouble("/geometry/dc/superlayer/wpdist", superlayer-1); } double gx = -gz*Math.tan(thtilt-thmin); // Calculate the distance between the line of intersection of the two // end-plate planes and the z-axis double xoff = dist2tgt*Math.tan(thtilt) - xdist/Math.sin(Math.PI/2-thtilt); // Construct the "left" end-plate plane Point3D p1 = new Point3D(-xoff, 0, 0); Vector3D n1 = new Vector3D(0, 1, 0); n1.rotateZ(-thopen*0.5); Plane3D lPlane = new Plane3D(p1, n1); // Construct the "right" end-plate plane Point3D p2 = new Point3D(-xoff, 0, 0); Vector3D n2 = new Vector3D(0, -1, 0); n2.rotateZ(thopen*0.5); Plane3D rPlane = new Plane3D(p2, n2); // Calculate the distance between wire midpoints in the current layer double w_layer = Math.sqrt(3)*d_layer/Math.cos(thster); // Calculate the point the midpoint (mx, 0, mz) of the first sense wire // of the current layer double mx = gx + midpointXOffset(layer, w_layer); double mz = gz + (layer + 1)*(3*d_layer); // Iterate through all of the sense wires and store them as detector // paddles in a list ArrayList<DetectorPaddle> paddles = new ArrayList(); for(int wire=0; wire<numWires; wire++) { // The point given by (wx, 0, wz) is the midpoint of the current // wire. double wx = mx + wire*2*w_layer; double wz = mz; Point3D wMid = new Point3D(wx, 0, wz); // System.out.println((layer+1)+" "+(wire+1)+" "+wx+"\t"+wz); // Find the interesection of the current wire with the end-plate // planes by construciting a long line that passes through the // the midpoint and which incorporates the wire's angle (thster) Line3D line = new Line3D(0, 1000, 0, 0, -1000, 0); line.rotateZ(thster); line.translateXYZ(wx, 0, wz); Point3D lPoint = new Point3D(); Point3D rPoint = new Point3D(); Plane3D.intersection(lPlane, line, lPoint); Plane3D.intersection(rPlane, line, rPoint); // Construct a line from one end point to the other to aid in the // construction and positioning of the current wire's detector // paddle object Line3D wireLine = new Line3D(lPoint, rPoint); // Construct the current wire's detector paddle object DetectorPaddle paddle = new DetectorPaddle(wire, small, wireLine.length(), small); // Rotate the paddle to account for the wire's angle paddle.rotateZ(thster); // Translate the paddle into position Point3D geometricMid = wireLine.middle(); paddle.translateXYZ(geometricMid.x(), geometricMid.y(), geometricMid.z()); // Overwrite the paddle's default midpoint, which is the geometric // midpoint, with the wire's point of intersection with the midplane paddle.getMidpoint().copy(wMid); // Add wire's paddle object to the list paddles.add(paddle); } Plane3D plane = new Plane3D(0, 0, mz, 0, 0, -1); Shape3D boundary = new Shape3D(); Point3D pLL = new Point3D( paddles.get(0).getLine().origin().x(), paddles.get(0).getLine().origin().y(), mz); Point3D pLR = new Point3D( paddles.get(0).getLine().end().x(), paddles.get(0).getLine().end().y(), mz); Point3D pUL = new Point3D( paddles.get(numWires-1).getLine().origin().x(), paddles.get(numWires-1).getLine().origin().y(), mz); Point3D pUR = new Point3D( paddles.get(numWires-1).getLine().end().x(), paddles.get(numWires-1).getLine().end().y(), mz); boundary.addFace(new Face3D(pLL, pLR, pUL)); boundary.addFace(new Face3D(pUR, pUL, pLR)); // System.out.println(boundary.face(0)); // System.out.println(boundary.face(1)); Plane3D midplane = new Plane3D(0, 0, mz, 0, 1, 0); return new DCLayer(sector, superlayer, layer, paddles, plane, boundary, midplane); }
0c035843-1e8f-4209-b629-52dbc9484c1f
6
public static String checkKeys(final String keyName, final String[] keyNames) { String result = null; if (keyNames != null && keyNames.length > 0 && keyName != null) { for (int i = 0; i < keyNames.length; i++) { if (keyName == keyNames[i]) { result = keyNames[i]; break; } } if (result == null) { result = "error"; } } return result; }
fd8cf8f3-31cc-46e3-8f3c-75e9c1b50ada
4
private void setPreferredClasses() { if (!_classLocked) { _classBox.removeActionListener(_classListener); _classBox.removeAllItems(); Vector<BaseClass> preferred = _character.getRankedClasses(16); Vector<BaseClass> average = _character.getRankedClasses(15); Vector<BaseClass> poor = _character.getRankedClasses(14); for (BaseClass item : preferred) { _classBox.addItem(item.getName()); } _classBox.addItem(SEPARATOR); for (BaseClass item : average) { _classBox.addItem(item.getName()); } for (BaseClass item : poor) { _classBox.addItem(item.getName()); } _character.setClass(preferred.elementAt(0)); _classBox.addActionListener(_classListener); } }
c7918b6f-cf2e-483a-b35e-8e59d3d55165
1
public OptionsMenu() { try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { e.printStackTrace(); } frame.setResizable(false); frame.setTitle("OptionsMenu"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(width, 380); frame.setLocationRelativeTo(null); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); frame.setContentPane(contentPane); contentPane.setLayout(null); config.loadConfigForOptions("settings",".xml"); config.loadConfigForOptionsforWidthHeight("settings", ".xml"); drawButtons(); }
7a77b61c-cb59-49f1-bcba-e66cbfede755
2
public void OpenFile(int primary) throws FileNotFoundException{ JFileChooser fileChooser = new JFileChooser("C:\\Users\\Aishwarya\\Documents\\NetBeansProjects\\NewVideoPlayer"); int status = fileChooser.showOpenDialog(this); if(status == 0) { try { ReadVideo(fileChooser.getSelectedFile().getPath(),primary); } catch (IOException ex) { Logger.getLogger(VideoAuthoringTool.class.getName()).log(Level.SEVERE, null, ex); } } }
aa047485-8a2a-4e42-ab11-589e39ad873c
5
public void populate(){ tiles = new Tile[Map.CHUNK_SIZE][Map.CHUNK_SIZE]; SimplexNoise noise = new SimplexNoise(7, 0.1); double xStart = chunkXPos * Map.CHUNK_SIZE; double yStart = chunkYPos * Map.CHUNK_SIZE; double xEnd = xStart + Map.CHUNK_SIZE; double yEnd = yStart + Map.CHUNK_SIZE; int xResolution = Map.CHUNK_SIZE; int yResolution = Map.CHUNK_SIZE; double[][] data = new double[xResolution][yResolution]; for(int i = 0; i < xResolution; i++){ for(int j = 0; j < yResolution; j++){ int x = (int)(xStart+(i * (xEnd - xStart)/xResolution)); int y = (int)(yStart+(j * (yEnd - yStart)/yResolution)); double dNoise = (1+noise.getNoise(x, y))/2; int type = 0; if(dNoise < 0.495){ type = Tile.WATER; }else if(dNoise < 0.5){ type = Tile.GRASS; }else if(dNoise < 0.525){ type = Tile.DIRT; }else{ type = Tile.ROCK; } tiles[i][j] = new Tile(type); data[i][j] = dNoise; } } }
c5c95c8c-4398-467f-907e-51cabf9a49c4
6
private void addPlayerBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addPlayerBtnActionPerformed String playerName = playerNameText.getText(); playerNameText.setText(""); try { DBController.addPlayer(playerName); } catch (ClassNotFoundException ex) { Logger.getLogger(WelcomeScreen.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(WelcomeScreen.class.getName()).log(Level.SEVERE, null, ex); } NewPlayerPlanel.setVisible(false); playBtn.setVisible(true); // String spcomboSel = (String) singlePlayerNameCombo.getSelectedItem(); // String p1combo1Sel = (String) player1Combo.getSelectedItem(); // String p2combo1Sel = (String) player2Combo.getSelectedItem(); singlePlayerNameCombo.removeAllItems(); player1Combo.removeAllItems(); player2Combo.removeAllItems(); String[] names = null; try { names = DBController.getPlayers(); } catch (ClassNotFoundException ex) { Logger.getLogger(WelcomeScreen.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(WelcomeScreen.class.getName()).log(Level.SEVERE, null, ex); } for (String name : names) { singlePlayerNameCombo.addItem(name); player1Combo.addItem(name); player2Combo.addItem(name); } if (isSinglePlayer) { singlePlayerPanel.setVisible(true); // singlePlayerNameCombo.setSelectedItem(singlePlayerNameCombo.getItemCount() - 1); } else { twoPlayerPanel1.setVisible(true); // // if (isPlayer == 1) { // player1Combo.setSelectedItem(player1Combo.getItemCount() - 1); // } // if (isPlayer == 2) { // player2Combo.setSelectedItem(player2Combo.getItemCount() - 1); // } } }//GEN-LAST:event_addPlayerBtnActionPerformed
ac11e3cc-3a34-42e4-96fd-c7fe7064f87e
0
@Override public boolean supportsEditability() {return false;}
ef0eae74-8a68-496a-9ac4-0e6aab2c0ffa
1
public boolean Apagar(Telefone obj){ try{ PreparedStatement comando = banco .getConexao().prepareStatement("UPDATE telefones SET ativo = 0 WHERE id = ?"); comando.setInt(1, obj.getId()); comando.executeUpdate(); comando.getConnection().commit(); return true; }catch(SQLException ex){ ex.printStackTrace(); return false; } }
aa90ecd2-a288-4cce-81ed-b520dd563302
6
public void hurt(Entity var1, int var2) { if(!this.level.creativeMode) { if(this.health > 0) { this.ai.hurt(var1, var2); if((float)this.invulnerableTime > (float)this.invulnerableDuration / 2.0F) { if(this.lastHealth - var2 >= this.health) { return; } this.health = this.lastHealth - var2; } else { this.lastHealth = this.health; this.invulnerableTime = this.invulnerableDuration; this.health -= var2; this.hurtTime = this.hurtDuration = 10; } this.hurtDir = 0.0F; if(var1 != null) { float var3 = var1.x - this.x; float var4 = var1.z - this.z; this.hurtDir = (float)(Math.atan2((double)var4, (double)var3) * 180.0D / 3.1415927410125732D) - this.yRot; this.knockback(var1, var2, var3, var4); } else { this.hurtDir = (float)((int)(Math.random() * 2.0D) * 180); } if(this.health <= 0) { this.die(var1); } } } }
9147b79a-1e5e-4f96-83c5-e963eb21c93d
3
@Override public void processKeyEvent(Component c, KeyEvent e) { try { if (c instanceof OutlinerCellRendererImpl) { OutlinerCellRendererImpl renderer = (OutlinerCellRendererImpl) c; JoeTree tree = renderer.node.getTree(); if (renderer.node != tree.getEditingNode()) { tree.getDocument().panel.layout.getUIComponent(tree.getEditingNode()).fireKeyEvent(e); e.consume(); return; } } } catch (NullPointerException npe) { // Document may have been destroyed in the interim, so let's abort. return; } super.processKeyEvent(c,e); }
48d9bb72-d567-4469-9994-dc599101486a
2
@Override public String toString() { if (meetings.size() == 0) { return "{}"; } StringBuilder sb = new StringBuilder(); sb.append(meetings.size()); sb.append("\\{"); for (Integer key : meetings.keySet()) { sb.append(key); sb.append(":"); sb.append(meetings.get(key)); sb.append(","); } sb.deleteCharAt(sb.length() - 1); sb.append(")"); return sb.toString(); }
096c0308-3be0-4e16-8f24-e3cdefc3f0af
8
public void add(byte[] packedValue, int docID) throws IOException { if (packedValue.length != packedBytesLength) { throw new IllegalArgumentException("packedValue should be length=" + packedBytesLength + " (got: " + packedValue.length + ")"); } if (pointCount >= maxPointsSortInHeap) { if (offlinePointWriter == null) { spillToOffline(); } offlinePointWriter.append(packedValue, pointCount, docID); } else { // Not too many points added yet, continue using heap: heapPointWriter.append(packedValue, pointCount, docID); } // TODO: we could specialize for the 1D case: if (pointCount == 0) { System.arraycopy(packedValue, 0, minPackedValue, 0, packedBytesLength); System.arraycopy(packedValue, 0, maxPackedValue, 0, packedBytesLength); } else { for(int dim=0;dim<numDims;dim++) { int offset = dim*bytesPerDim; if (StringHelper.compare(bytesPerDim, packedValue, offset, minPackedValue, offset) < 0) { System.arraycopy(packedValue, offset, minPackedValue, offset, bytesPerDim); } if (StringHelper.compare(bytesPerDim, packedValue, offset, maxPackedValue, offset) > 0) { System.arraycopy(packedValue, offset, maxPackedValue, offset, bytesPerDim); } } } pointCount++; if (pointCount > totalPointCount) { throw new IllegalStateException("totalPointCount=" + totalPointCount + " was passed when we were created, but we just hit " + pointCount + " values"); } docsSeen.set(docID); }
89bbc3e1-8bec-429c-893e-f4c3c7ce235c
9
protected void optimize2() throws Exception { //% main routine for modification 2 procedure main int nNumChanged = 0; boolean bExamineAll = true; // while (numChanged > 0 || examineAll) // numChanged = 0; while (nNumChanged > 0 || bExamineAll) { nNumChanged = 0; // if (examineAll) // loop I over all the training examples // numChanged += examineExample(I) // else // % The following loop is the only difference between the two // % SMO modifications. Whereas, modification 1, the type II // % loop selects i2 fro I.0 sequentially, here i2 is always // % set to the current i.low and i1 is set to the current i.up; // % clearly, this corresponds to choosing the worst violating // % pair using members of I.0 and some other indices // inner.loop.success = 1; // do // i2 = i.low // alpha2, alpha2' = Lagrange multipliers for i2 // F2 = f-cache[i2] // i1 = i.up // inner.loop.success = takeStep(i.up, i.low) // numChanged += inner.loop.success // until ( (b.up > b.low - 2*tol) || inner.loop.success == 0) // numChanged = 0; // endif if (bExamineAll) { for (int i = 0; i < m_nInstances; i++) { nNumChanged += examineExample(i); } } else { boolean bInnerLoopSuccess = true; do { if (takeStep(m_iUp, m_iLow, m_alpha[m_iLow], m_alphaStar[m_iLow], m_error[m_iLow]) > 0) { bInnerLoopSuccess = true; nNumChanged += 1; } else { bInnerLoopSuccess = false; } } while ((m_bUp <= m_bLow - 2 * m_fTolerance) && bInnerLoopSuccess); nNumChanged = 0; } // // if (examineAll == 1) // examineAll = 0 // elseif (numChanged == 0) // examineAll = 1 // endif // endwhile //endprocedure // if (bExamineAll) { bExamineAll = false; } else if (nNumChanged == 0) { bExamineAll = true; } } }
0da0f36c-c2d2-454b-8966-3d9335766e0d
4
public static Fst<Pair<Character, Character>> fromString(CharSequence string) { Fst<Pair<Character, Character>> bla = new Fst<>(); if (string.length() == 0) { bla.addState(StateFlag.ACCEPT, StateFlag.INITIAL); return bla; } State previous = null; for (int i = 0; i < string.length(); i++) { State source = previous == null ? bla.addStateInitial() : previous; State target = i + 1 == string.length() ? bla.addStateAccept() : bla.addState(); char charAt = string.charAt(i); Transition<Pair<Character, Character>> transition = bla .addTransition( Pair.of(Character.toLowerCase(charAt), charAt), source, target); previous = target; } return bla; }
7696ddcc-7818-478a-9dca-1fcce01ad3db
0
public int getStudentId() { return studentId; }
ef9ff144-b96c-47dc-b6a8-71f33b1082e6
7
private boolean ValidPetNameChars(String inputStr,int HardCodedLen) { for(int i=0;i<HardCodedLen;i++) { if(i==0) { if(inputStr.charAt(0) == ' ') { return false; } } if((inputStr.charAt(i) < 'a' || inputStr.charAt(i) > 'z') && (inputStr.charAt(i) < '0' || inputStr.charAt(i) > '9')) { return false; } } return true; }
4548e1f6-476b-4707-95fe-a4ea8116fa3e
9
public static void parse(String filename, int n) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); String line = null; // drop the header line line = br.readLine(); int abs_min = Integer.MAX_VALUE, abs_max = Integer.MIN_VALUE, tmp0, tmp1; double avg_min = Double.MAX_VALUE, avg_max = Double.MIN_VALUE, avg_avg = 0, tmp2; String tab[]; int counter = 0; LinkedList<Integer> max_times = new LinkedList<Integer>(); LinkedList<Integer> min_times = new LinkedList<Integer>(); LinkedList<Double> avg_times = new LinkedList<Double>(); while ((line = br.readLine()) != null) { if (line.matches("\\s*")) { continue; } counter++; tab = line.split("\\s+"); // Max tmp0 = Integer.parseInt(tab[0]); max_times.add(tmp0); // Min tmp1 = Integer.parseInt(tab[1]); min_times.add(tmp1); // Avg tmp2 = Double.parseDouble(tab[2]); avg_times.add(tmp2); // Update the absolute maximum if (abs_max < tmp0) { abs_max = tmp0; } // Update the absolute minimum if (abs_min > tmp1) { abs_min = tmp1; } // Update the average sum avg_avg += tmp2; // Update the maximum average if (tmp2 > avg_max) { avg_max = tmp2; } // Update the minimum average if (tmp2 < avg_min) { avg_min = tmp2; } } br.close(); // sort lists Collections.sort(max_times); Collections.sort(min_times); Collections.sort(avg_times); double avg = 0; int toRemove = 12 * counter / 100; for (int i = 0; i < toRemove; i++) { max_times.removeFirst(); max_times.removeLast(); min_times.removeFirst(); min_times.removeLast(); avg_times.removeFirst(); avg_times.removeLast(); } avg_avg /= counter; FileWriter fw = new FileWriter(filename + "_merge.txt"); int size = min_times.size(); fw.write("max \t min \t avg\n"); for (int i = 0; i < size; i++) { int x_max = max_times.get(i); int x_min = min_times.get(i); double x_avg = avg_times.get(i); avg += x_avg; fw.write(x_max + " \t " + x_min + " \t " + x_avg + "\n"); } avg /= size; fw.write("-------------- STATS --------------\n"); fw.write("ABS MAX: " + max_times.getLast() + " ms\n"); fw.write("ABS MIN: " + min_times.getFirst() + " ms\n"); fw.write("AVG MAX: " + avg_times.getLast() + " ms\n"); fw.write("AVG MIN: " + avg_times.getFirst() + " ms\n"); fw.write("AVG AVG: " + avg + " ms\n"); fw.flush(); fw.close(); // --------------------------- String homeDir = System.getProperty("user.home"); File file = new File(homeDir + File.separatorChar + "stats.txt"); FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); FileLock lock = null; try { lock = channel.lock(); ByteBuffer buffer = ByteBuffer.allocateDirect(1024); buffer.put((n + "\t" + avg + "\n").getBytes()).flip(); long pos = channel.size(); channel.write(buffer, pos); } catch (Exception exp) { exp.printStackTrace(); } finally { lock.release(); } channel.close(); // Print out the average max, min and avg System.err.println("\n\nAVG MAX: " + avg_times.getLast() + " ms"); System.err.println("AVG MIN: " + avg_times.getFirst() + " ms"); System.err.println("AVG AVG: " + avg + " ms\n\n"); }
ad1e529d-54be-4f0e-9495-57cfac1eae29
7
@Override public Polynomial gcd(Polynomial polynomial1, Polynomial polynomial2) { if (!isZero(polynomial1) && isZero(polynomial2)) { return polynomial1; } if (isZero(polynomial1) && !isZero(polynomial2)) { return polynomial2; } if (isZero(polynomial1) && isZero(polynomial2)) { return new Polynomial(0); } Polynomial result = new Polynomial(polynomial2.getSize()); Polynomial remainder = polynomial2; Polynomial numerator = polynomial1; Polynomial denumerator = polynomial2; //find greatest greatest common divisor, last positive remainder while (!(remainder.getSize() == 0)) { result = remainder; remainder = new Polynomial(Math.max(numerator.getSize(), denumerator.getSize())); divide(numerator, denumerator, remainder); remainder.clearZeroValues(); numerator = denumerator; denumerator = remainder; } //make gcd monic Polynomial monicDiv = new Polynomial(1); monicDiv.setElement(0, result.getElement(result.getSize() - 1)); return divide(result, monicDiv); }
21894da4-c68e-4dcc-b1e8-ff2f9f677379
9
public static String decode(String text) { if (text == null) return null; StringBuilder buf = new StringBuilder(text.length()); final int limit = text.length(); for (int i = 0; i < limit; i++) { char ch = text.charAt(i); // Handle unescaped characters if (ch != '\\') { buf.append(ch); continue; } // Get next char if (++i >= limit) throw new IllegalArgumentException( "illegal trailing '\\' in encoded string"); ch = text.charAt(i); // Check for backslash escape if (ch == '\\') { buf.append(ch); continue; } // Must be unicode escape if (ch != 'u') throw new IllegalArgumentException( "illegal escape sequence '\\" + ch + "' in encoded string"); // Decode hex value int value = 0; for (int j = 0; j < 4; j++) { if (++i >= limit) throw new IllegalArgumentException( "illegal truncated '\\u' escape sequence in encoded string"); int nibble = Character.digit(text.charAt(i), 16); if (nibble == -1) { throw new IllegalArgumentException( "illegal escape sequence '" + text.substring(i - j - 2, i - j + 4) + "' in encoded string"); } // assert nibble >= 0 && nibble <= 0xf; value = (value << 4) | nibble; } // Append decodec character buf.append((char) value); } return buf.toString(); }
32fd4ba5-00b7-41ff-bb82-068bb64bdb80
6
@Override public void run() { String data = this.plugin.getFileMan().read(this.plugin.chatFile()); JSONArray jArray; try { jArray = (JSONArray) new JSONParser().parse(data); for(int i=0;i<jArray.size();i++){ JSONObject json = (JSONObject) jArray.get(i); String time = (String) json.get("time"); try { Date date = this.fmt.parse(time); String source = (String) json.get("source"); if(date.after(lastCheck) && !source.equals("in")){ lastCheck = date; String player = (String) json.get("player"); String message = (String) json.get("message"); this.plugin.getServer().broadcastMessage(ChatColor.DARK_PURPLE+"["+player+"] "+ChatColor.WHITE+message); } } catch (ParseException ex) { this.plugin.logMessage("Invalid date format: "+ex.getMessage()); } } } catch (org.json.simple.parser.ParseException ex) { if(ex.getMessage()!=null){ this.plugin.logMessage("Error while parsing JSON: "+ex.getMessage()); } } }
87d343a7-492b-448b-859b-c0eac49ff3ce
8
private static void generateParameterReifierCode(String[] paramTypes, boolean isStatic, final CodeVisitor cv) { cv.visitIntInsn(SIPUSH, paramTypes.length); cv.visitTypeInsn(ANEWARRAY, "java/lang/Object"); int localVarIndex = isStatic ? 0 : 1; for (int i = 0; i < paramTypes.length; ++i) { String param = paramTypes[i]; cv.visitInsn(DUP); cv.visitIntInsn(SIPUSH, i); if (isPrimitive(param)) { int opcode; if (param.equals("F")) { opcode = FLOAD; } else if (param.equals("D")) { opcode = DLOAD; } else if (param.equals("J")) { opcode = LLOAD; } else { opcode = ILOAD; } String type = "bsh/Primitive"; cv.visitTypeInsn(NEW, type); cv.visitInsn(DUP); cv.visitVarInsn(opcode, localVarIndex); String desc = param; // ok? cv.visitMethodInsn(INVOKESPECIAL, type, "<init>", "(" + desc + ")V"); } else { // Technically incorrect here - we need to wrap null values // as bsh.Primitive.NULL. However the This.invokeMethod() // will do that much for us. // We need to generate a conditional here to test for null // and return Primitive.NULL cv.visitVarInsn(ALOAD, localVarIndex); } cv.visitInsn(AASTORE); localVarIndex += ((param.equals("D") || param.equals("J")) ? 2 : 1); } }
5dda23af-d1c5-438e-9525-4adc6523f1b4
3
private static Token matchOperator(String word, int line, int position){ // Try building a symbol for (Operator testOp: Operator.values()) { String testOpStr = testOp.getValue(); int testOpLen = testOpStr.length(); if (testOpLen <= word.length()){ String testWord = word.substring(0, testOpLen); if (testOpStr.equals(testWord)) { return new Token(testOp, line, position); } } } return null; }
1be0c707-5f5b-40bf-8567-f54f54e18803
2
public void testWeekdayNames() { DateTimeFormatter printer = DateTimeFormat.forPattern("EEEE"); for (int i=0; i<ZONES.length; i++) { MutableDateTime mdt = new MutableDateTime(2004, 1, 1, 1, 20, 30, 40, ZONES[i]); for (int day=1; day<=366; day++) { mdt.setDayOfYear(day); int weekday = mdt.getDayOfWeek(); String weekdayText = printer.print(mdt); assertEquals(WEEKDAYS[weekday], weekdayText); } } }
a84bfaea-14fb-4ea0-affb-2eb8a6827242
5
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((hausnummer == null) ? 0 : hausnummer.hashCode()); result = prime * result + ((land == null) ? 0 : land.hashCode()); result = prime * result + ((ort == null) ? 0 : ort.hashCode()); result = prime * result + ((plz == null) ? 0 : plz.hashCode()); result = prime * result + ((strasse == null) ? 0 : strasse.hashCode()); return result; }
b6bca02b-cbce-49c5-ad75-8715c5386269
7
private void drawHeliostats(Graphics2D g) { List<Heliostat> heliostats = model.getHeliostats(); if (heliostats.isEmpty()) return; Stroke oldStroke = g.getStroke(); Color oldColor = g.getColor(); Symbol.HeliostatIcon heliostatIcon = new Symbol.HeliostatIcon(Color.GRAY, Color.BLACK, false); synchronized (heliostats) { for (Heliostat hs : heliostats) { if (hs.isVisible()) { Rectangle2D r = hs.getShape().getBounds2D(); int x = convertPointToPixelX((float) r.getX()); int y = convertPointToPixelY((float) r.getY()); int w = convertLengthToPixelX((float) r.getWidth()); int h = convertLengthToPixelY((float) r.getHeight()); heliostatIcon.setIconWidth(w); heliostatIcon.setIconHeight(h); heliostatIcon.setAngle(hs.getAngle()); heliostatIcon.setStroke(moderateStroke); heliostatIcon.setBorderColor(hs == selectedManipulable ? Color.YELLOW : Color.BLACK); heliostatIcon.paintIcon(this, g, x, y); Shape s = hs.getShape(); if (s instanceof Rectangle2D.Float) { Rectangle2D.Float r2 = (Rectangle2D.Float) s; x = convertPointToPixelX(r2.x); y = convertPointToPixelY(r2.y); w = convertLengthToPixelX(r2.width); h = convertLengthToPixelY(r2.height); String label = hs.getLabel(); if (label != null) drawLabelWithLineBreaks(g, label, x + 0.5f * w, y + 0.5f * h, w < h * 0.25f); if (selectedManipulable == hs) { g.setStroke(longDashed); g.drawRect(x, y, w, h); } } } } } g.setStroke(oldStroke); g.setColor(oldColor); }
f7c70eae-f4f3-4eb5-9577-cd4047abdf75
5
@SuppressWarnings("unchecked") public T removeEnd() { ListNode<T> before = null; ListNode<T> after = front; T tempData; if (isEmpty()) return null; tempData = tail.getData(); if (size() == 2){ front.setNext(null); tail = front; numberOfNodes--; return tempData; } else if (size() == 1){ front = null; tail = null; numberOfNodes--; return tempData; } // Traverse the list while (after != null){ if (after.getNext() == null){ break; } else { before = after; } after = after.getNext(); } before.setNext(null); tail = before; numberOfNodes--; return tempData; }
43115be5-a4f5-4cbf-a6a4-ca5189746186
4
private String cardName(int number) { String name = ""; name += cardRank(number); name += " of "; switch(number / 13) { case(0): name += "Clubs"; break; case(1): name += "Diamonds"; break; case(2): name += "Hearts"; break; case(3): name += "Spades"; break; } return name; }
df911b98-5382-44bd-a1e2-af6d37589fdf
1
@Override public int attack(double agility, double luck) { if(random.nextInt(100) < luck) { System.out.println("I just created a thunder storm!"); return random.nextInt((int) agility) * 2; } return 0; }
12a4a648-e48e-4af6-9955-1445d4c1acae
5
private static void DownloadNewLauncher( ) { try { //progressCurr.setValue(0); String strPath = Utils.getWorkingDirectory() + File.separator+GlobalVar.LauncherFileName; File AppPath = new File(URLDecoder.decode(LauncherUpdater.class.getProtectionDomain().getCodeSource().getLocation().getPath(),"UTF-8")); URL connection = new URL(GlobalVar.DownloadClientRootURL+"/"+GlobalVar.LauncherFileName); HttpURLConnection urlconn; urlconn = (HttpURLConnection) connection.openConnection(); urlconn.setRequestMethod("GET"); urlconn.connect(); int fileSize = urlconn.getContentLength(); //Сверяем размер файла на сервере и локальную запись, не совпали? качаем новую версию if(urlconn.getResponseCode() != 404) { if(fileSize != readMD5File(strPath)) { JOptionPane.showMessageDialog( null, "Лаунчер будет автоматически обновлен", "Обновлене", JOptionPane.WARNING_MESSAGE); InputStream in = null; in = urlconn.getInputStream(); OutputStream writer = new FileOutputStream(AppPath.getAbsolutePath()); byte buffer[] = new byte[55000]; int c = in.read(buffer); int dwnloaded =0; while (c > 0) { writer.write(buffer, 0, c); dwnloaded +=c; try{ //progressCurr.setValue((int)((dwnloaded/1024)*100/fileSize)); //progressCurr.setString("Скачивается "+GlobalVar.LauncherFileName + " "+progressCurr.getValue()+"% " +(dwnloaded/1024)+"/"+(fileSize/1024)+"Kb"); }catch(ArithmeticException ae){ //И такое тоже бывает } c = in.read(buffer); } writer.flush(); writer.close(); in.close(); JOptionPane.showMessageDialog( null, "Лаунчер успешно обновлен\nПосле закрытия этого окна лаунчер будет закрыт", "Обновлене успешно", JOptionPane.INFORMATION_MESSAGE); writeMD5File(strPath, fileSize); //Записываем новый размер лаунчера т.к. обновились успешно System.exit(1); } }else{ } } catch (IOException e) { JOptionPane.showMessageDialog( null, "Ошибка обновления лаунчера\nПосле закрытия этого окна будет запущена текущая версия лаунчера", "Обновлене не удалось", JOptionPane.ERROR_MESSAGE); System.out.println(e); } }
e7dae66b-3ba4-4112-a505-7b866bb1f3c7
6
public boolean onStack(final LocalExpr expr) { if (expr.isDef()) { return false; } final UseInformation UI = (UseInformation) useInfoMap.get(expr); if (UI == null) { if (StackOptimizer.DEBUG) { System.err .println("Error in StackOptimizer.onStack: parameter not found in useInfoMap"); } return false; } if (UI.type == 0) { return true; } if ((UI.type == 1) && !shouldStore((LocalExpr) expr.def())) { return true; } return false; }
14cd4024-7a36-40e6-aa30-e678b5eedeb6
8
@Override public void write(ICTMC ctcm, String pathname) throws Exception { BufferedWriter outputStrm = new BufferedWriter(new FileWriter(pathname)); Matrix tmpM; List<Matrix> tmpTra; int i = -1; int max = -1; int j = -1; int maxT = -1; try { if(ctcm.isIrreducible()) { tmpM = ctcm.getStazionario(); max = tmpM.getColumnDimension(); for (i = 0;i<max;++i) { if(i>0) { outputStrm.write(";"); } outputStrm.write(String.format("%.16e", tmpM.get(0, i))); } } outputStrm.newLine(); outputStrm.write("**********"); outputStrm.newLine(); tmpTra = ctcm.getTransitorio(); maxT = tmpTra.size(); for(j=0;j<maxT;++j) { if((j%ctcm.getK())==0) { if(j>0) { outputStrm.newLine(); } outputStrm.write("t="+j+"*h"); outputStrm.newLine(); tmpM = tmpTra.get(j); max = tmpM.getColumnDimension(); for (i = 0;i<max;++i) { if(i>0) { outputStrm.write(";"); } outputStrm.write(String.format("%.16e", tmpM.get(0, i))); } } } } finally { outputStrm.close(); } }
e152ecf8-08f7-4e14-80b6-7cb68d6f796e
5
public char[][] transpose_square(int[] key,char[][] square, boolean col_flag) { int row=square.length; int col=square[0].length; char[][] result=new char[row][col]; if(!col_flag) { for(int i=0;i<key.length;i++) { for(int j=0;j<row;j++) { result[j][i]=square[j][key[i]-1]; } } } else { for(int i=0;i<key.length;i++) { for(int j=0;j<col;j++) { result[i][j]=square[key[i]-1][j]; } } } return result; }
ef06505d-51d5-46de-a60d-c0f29dabd3d0
7
public void tick() { if (queueTiles.size() == 0) { if (owner.cities.size() == 0) { //settle(); return; } Tile t = settleLocation(); //System.out.println(t.owner); waddleToExact(t.row,t.col); } else { while (action > 0) { if (queueTiles.size() == 0) { Tile t = settleLocation(); waddleToExact(t.row,t.col); return; } if (queueTiles.get(0).equals(location)) { settle(); return; } //super.recordPos(); passiveWaddle(queueTiles.get(queueTiles.size()-1).row - location.row, queueTiles.get(queueTiles.size()-1).col - location.col); //location.grid.move(this,queueTiles.get(queueTiles.size()-1).row - location.row, queueTiles.get(queueTiles.size()-1).col - location.col); queueTiles.remove(queueTiles.size()-1); //If it reaches the destination if (queueTiles.size() == 0) { if (location.owner == null) { settle(); return; } else { queueTiles.clear(); Tile t = settleLocation(); waddleToExact(t.row,t.col); } } /*else if (queueTiles.get(0).owner != null) { if (!queueTiles.get(0).owner.equals(owner)) { queueTiles.clear(); } }*/ } } /**/ }
81a3f788-33b5-4a64-9cde-d8e6a49c55c1
4
public void defineObjects(){ CharacterManager.character = CharacterManager.defineChar(); PlatformManager.defineFloors(level); LivingEntityManager.defineEnemies(level); EntityManager.initialize(); EntityManager.setupEntities(); // define star locations for (int i = 0; i < CharacterManager.starNumber; i++){ int x = 0 + (int)(Math.random() * ((WindowManager.width - 0) + 1)); int y = 0 + (int)(Math.random() * ((WindowManager.height - 0) + 1)); CharacterManager.starX.add(x); CharacterManager.starY.add(y); } for (int i = 0; i < CharacterManager.starNumber; i++){ int x = 0 + (int)(Math.random() * ((WindowManager.width - 0) + 1)); int y = 0 + (int)(Math.random() * ((WindowManager.height - 0) + 1)); menuStarX.add(x); menuStarY.add(y); } // define custom fonts try { font = Font.createFont(Font.TRUETYPE_FONT, GameManager.class.getClassLoader().getResourceAsStream("fonts/dr.ttf")).deriveFont(45f); smallFont = Font.createFont(Font.TRUETYPE_FONT, GameManager.class.getClassLoader().getResourceAsStream("fonts/dr.ttf")).deriveFont(20f); titleFont = Font.createFont(Font.TRUETYPE_FONT, GameManager.class.getClassLoader().getResourceAsStream("fonts/dr.ttf")).deriveFont(85f); btnFont = Font.createFont(Font.TRUETYPE_FONT, GameManager.class.getClassLoader().getResourceAsStream("fonts/dr.ttf")).deriveFont(25f); } catch (Exception ex){ ex.printStackTrace(); } objectsDefined = true; repaint(); if (CharacterManager.aniFrame == 0) CharacterManager.aniFrame = 1; else CharacterManager.aniFrame = 0; }
6d827db5-7cfd-4971-9526-770802ec9e07
4
private String getPlayer() { Player[] bufferPlayer = manager.getAllPlayer(); String s = ""; int counter = 0; if(bufferPlayer[bufferPlayer.length -1] != null&&bufferPlayer[bufferPlayer.length -1].name.contentEquals("Bot")){ counter = 1; } for (int i = 0; i < bufferPlayer.length - counter;i++){ if (bufferPlayer[i] != null){ s += "Player name: " + bufferPlayer[i].name + "<br>" + bufferPlayer[i].getCashAccount().toString() + "<br>"; s += bufferPlayer[i].getShareDeposit().toString() + "<br>"; } } return s; }
985f9ba8-6880-42c3-9e19-b8d72053bcb0
3
@Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return isJsonType(mediaType) && filteringEnabled(type, genericType, annotations, mediaType) && getJsonProvider().isWriteable(type, genericType, annotations, mediaType); }