text
stringlengths
14
410k
label
int32
0
9
private static TIntIntHashMap getWidthMap(Font font) { TIntIntHashMap map = WIDTH_MAP.get(font); if (map == null) { map = new TIntIntHashMap(); WIDTH_MAP.put(font, map); FontMetrics fm = Fonts.getFontMetrics(font); for (int i = 32; i < 127; i++) { map.put(i, fm.charWidth((char) i)); } } return map; }
2
public List<FormasPagamento> ListarTodos(){ try{ PreparedStatement comando = banco.getConexao() .prepareStatement("SELECT * FROM tipos_pagamento WHERE ativo " + "= 1"); ResultSet rs = comando.executeQuery(); List<FormasPagamento> formasPagamento = new LinkedList<>(); while(rs.next()){ FormasPagamento temp = new FormasPagamento(); temp.setId(rs.getInt("id")); temp.setNome(rs.getString("nome")); temp.setAtivo(rs.getInt("ativo")); formasPagamento.add(temp); } return formasPagamento; }catch(SQLException ex){ ex.printStackTrace(); return null; } }
2
@Override public int getAlignMedianFacValue(Faction.Align eq) { int bottom=Integer.MAX_VALUE; int top=Integer.MIN_VALUE; final Enumeration<FRange> e = getRanges(AlignID()); if(e==null) return 0; for(;e.hasMoreElements();) { final Faction.FRange R=e.nextElement(); if(R.alignEquiv()==eq) { if(R.low()<bottom) bottom=R.low(); if(R.high()>top) top=R.high(); } } switch(eq) { case GOOD: return top; case EVIL: return bottom; case NEUTRAL: return (int)Math.round(CMath.div((top+bottom),2)); default: return 0; } }
8
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(DummyInputFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(DummyInputFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(DummyInputFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(DummyInputFrame.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 DummyInputFrame().setVisible(true); } }); }
6
public double[] getLocalGrid(long density) { int numberOfDots = (int) (density * getWidth()); double gridStep = 1 / (double) density; double[] grid = new double[numberOfDots]; for (int i = 0; i < numberOfDots; i++) { grid[i] = ((double) i + 0.5) * gridStep; } return grid; }
1
public void readFromNBT(NBTTagList par1NBTTagList) { this.mainInventory = new ItemStack[36]; this.armorInventory = new ItemStack[4]; for (int var2 = 0; var2 < par1NBTTagList.tagCount(); ++var2) { NBTTagCompound var3 = (NBTTagCompound)par1NBTTagList.tagAt(var2); int var4 = var3.getByte("Slot") & 255; ItemStack var5 = ItemStack.loadItemStackFromNBT(var3); if (var5 != null) { if (var4 >= 0 && var4 < this.mainInventory.length) { this.mainInventory[var4] = var5; } if (var4 >= 100 && var4 < this.armorInventory.length + 100) { this.armorInventory[var4 - 100] = var5; } } } }
6
public boolean method195(int j) { int k = maleEquip1; int l = maleEquip2; int i1 = anInt185; if (j == 1) { k = femaleEquip1; l = femaleEquip2; i1 = anInt162; } if (k == -1) return true; boolean flag = true; if (!Model.method463(k)) flag = false; if (l != -1 && !Model.method463(l)) flag = false; if (i1 != -1 && !Model.method463(i1)) flag = false; return flag; }
7
protected void parse(PDFObject obj) throws IOException { // read the size array (required) PDFObject sizeObj = obj.getDictRef("Size"); if (sizeObj == null) { throw new PDFParseException("Size required for function type 0!"); } PDFObject[] sizeAry = sizeObj.getArray(); int[] size = new int[sizeAry.length]; for (int i = 0; i < sizeAry.length; i++) { size[i] = sizeAry[i].getIntValue(); } setSize(size); // read the # bits per sample (required) PDFObject bpsObj = obj.getDictRef("BitsPerSample"); if (bpsObj == null) { throw new PDFParseException("BitsPerSample required for function type 0!"); } setBitsPerSample(bpsObj.getIntValue()); // read the order (optional) PDFObject orderObj = obj.getDictRef("Order"); if (orderObj != null) { setOrder(orderObj.getIntValue()); } // read the encode array (optional) PDFObject encodeObj = obj.getDictRef("Encode"); if (encodeObj != null) { PDFObject[] encodeAry = encodeObj.getArray(); float[] encode = new float[encodeAry.length]; for (int i = 0; i < encodeAry.length; i++) { encode[i] = encodeAry[i].getFloatValue(); } setEncode(encode); } // read the decode array (optional) PDFObject decodeObj = obj.getDictRef("Decode"); if (decodeObj != null) { PDFObject[] decodeAry = decodeObj.getArray(); float[] decode = new float[decodeAry.length]; for (int i = 0; i < decodeAry.length; i++) { decode[i] = decodeAry[i].getFloatValue(); } setDecode(decode); } // finally, read the samples setSamples(readSamples(obj.getStreamBuffer())); }
8
private static void addFile(File source, JarOutputStream target) throws IOException { BufferedInputStream in = null; try{ if (source.isDirectory()) { String name = source.getPath().replace("\\", "/"); if (!name.isEmpty()) { if (!name.endsWith("/")) name += "/"; JarEntry entry = new JarEntry(name); entry.setTime(source.lastModified()); target.putNextEntry(entry); target.closeEntry(); } for (File nestedFile: source.listFiles()) addFile(nestedFile, target); return; } String path = source.getPath().replace("\\", "/").replaceAll("out/", ""); JarEntry entry = new JarEntry(path.toString()); entry.setTime(source.lastModified()); target.putNextEntry(entry); in = new BufferedInputStream(new FileInputStream(source)); byte[] buffer = new byte[1024]; while (true) { int count = in.read(buffer); if (count == -1) break; target.write(buffer, 0, count); } target.closeEntry(); } finally{ if (in != null) in.close(); } }
7
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ColorBean colorBean = (ColorBean) o; if (b != null ? !b.equals(colorBean.b) : colorBean.b != null) return false; if (g != null ? !g.equals(colorBean.g) : colorBean.g != null) return false; if (r != null ? !r.equals(colorBean.r) : colorBean.r != null) return false; return true; }
9
public boolean isSelected() { for(int i=0;i<markers;i++) { if(marker[i].isSelected()) { return true; } } return false; }
2
public void updateTropes() { // Clear the trope lists narrativeTropes.clear(); genreTropes.clear(); topicTropes.clear(); ArrayList<NarrativeType> _narrative = new ArrayList<NarrativeType>(Arrays.asList(NarrativeType.values())); ArrayList<GenreType> _genre = new ArrayList<GenreType>(Arrays.asList(GenreType.values())); ArrayList<TopicType> _topic = new ArrayList<TopicType>(Arrays.asList(TopicType.values())); for(Trope t : allTropes) { TropeType type = t.getTropeType(); if(type == TropeType.Narrative && narrativeTypes.contains(_narrative.get(t.getSubtype()))) { narrativeTropes.add(t); } else if (type == TropeType.Genre && genreTypes.contains(_genre.get(t.getSubtype()))) { genreTropes.add(t); } else if (type == TropeType.Topic && topicTypes.contains(_topic.get(t.getSubtype()))) { topicTropes.add(t); } } // We now have a list containing all the tropes allowed by the settings // COUNT NEWS TROPES for(Trope t : genreTropes) { if(GenreType.News.ordinal() == t.getSubtype()) System.out.println("FOUND NEWS"); } }
9
public void printAnalysisResults() { String string = ""; for (int i = 0; i < bestSequenceAlternativesEnergyPoint.size(); i++) string += i + ": " + bestSequenceAlternativesEnergyPoint.get(i) + "CONSUMPTION:" + consumptionEnergyPoints[i] + "EP\n"; for (int i = 0; i < bestSequenceAlternativesWatt.size(); i++) string += i + ": " + bestSequenceAlternativesWatt.get(i) + "CONSUMPTION:" + consumptionWatt[i] + "KW\n"; System.out.println(string); }
2
private void init ( ) { updateLogDate = ""; tempSensors = new NumberWithLabel[MAX_TEMP_SENSORS]; int i; for ( i = 0; i < MAX_TEMP_SENSORS; i++ ) { tempSensors[i] = new NumberWithLabel( (byte) 1 ); } pH = new NumberWithLabel( (byte) 2 ); pHExp = new NumberWithLabel( (byte) 2 ); atoLow = false; atoHigh = false; pwmA = new ShortWithLabel(); pwmD = new ShortWithLabel(); pwmExpansion = new ShortWithLabel[MAX_PWM_EXPANSION_PORTS]; for ( i = 0; i < MAX_PWM_EXPANSION_PORTS; i++ ) { pwmExpansion[i] = new ShortWithLabel(); } waterlevel = new ShortWithLabel(); salinity = new NumberWithLabel( (byte) 1 ); orp = new NumberWithLabel(); main = new Relay(); expansionRelays = new Relay[MAX_EXPANSION_RELAYS]; for ( i = 0; i < MAX_EXPANSION_RELAYS; i++ ) { expansionRelays[i] = new Relay(); } qtyExpansionRelays = 0; expansionModules = 0; relayExpansionModules = 0; ioChannels = 0; ioChannelsLabels = new String[MAX_IO_CHANNELS]; for ( i = 0; i < MAX_IO_CHANNELS; i++ ) { ioChannelsLabels[i] = ""; } aiChannels = new short[MAX_AI_CHANNELS]; for ( i = 0; i < MAX_AI_CHANNELS; i++ ) { aiChannels[i] = 0; } radionChannels = new short[MAX_RADION_LIGHT_CHANNELS]; for ( i = 0; i < MAX_RADION_LIGHT_CHANNELS; i++ ) { radionChannels[i] = 0; } customVariables = new ShortWithLabel[MAX_CUSTOM_VARIABLES]; for ( i = 0; i < MAX_CUSTOM_VARIABLES; i++ ) { customVariables[i] = new ShortWithLabel(); } vortechValues = new short[MAX_VORTECH_VALUES]; for ( i = 0; i < MAX_VORTECH_VALUES; i++ ) { vortechValues[i] = 0; } }
8
@EventHandler(priority = EventPriority.NORMAL) public void onProjectileLaunch (ProjectileLaunchEvent event) { Projectile projectile = event.getEntity(); if (projectile.getType() != EntityType.THROWN_EXP_BOTTLE || ! (projectile.getShooter() instanceof Player)) return; Player player = (Player) projectile.getShooter(); ItemStack item = player.getInventory().getItemInHand(); if (item.getType() != Material.EXP_BOTTLE) return; ItemMeta meta = item.getItemMeta(); if ( !meta.hasLore()) return; for (String s : meta.getLore()) { if (s == null) return; if (s.startsWith("Level ")) { projectile.setMetadata("expbottlelevel", new LevelMetadata( Integer.parseInt(s.substring(s.indexOf(' ') + 1)))); } } }
7
public JSONObject append(String key, Object value) throws JSONException { testValidity(value); Object object = opt(key); if (object == null) { put(key, new JSONArray().put(value)); } else if (object instanceof JSONArray) { put(key, ((JSONArray) object).put(value)); } else { throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); } return this; }
2
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof PointData)) return false; PointData pointData = (PointData) o; if (!category.equals(pointData.category)) return false; if (!id.equals(pointData.id)) return false; if (!Arrays.equals(location, pointData.location)) return false; if (!title.equals(pointData.title)) return false; return true; }
6
@Override public List<Account> findAccountByRoleId(int roleId) { List<Account> list = new ArrayList<Account>(); Connection cn = null; PreparedStatement ps = null; ResultSet rs = null; try { cn = ConnectionHelper.getConnection(); ps = cn.prepareStatement(QTPL_SELECT_BY_ROLE_ID); ps.setInt(1, roleId); rs = ps.executeQuery(); while (rs.next()) { list.add(processResultSet(rs)); } } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } try { cn.close(); } catch (SQLException e) { e.printStackTrace(); } } return list; }
5
private static Image getImage(String filename) { // to read from file ImageIcon icon = new ImageIcon(filename); // try to read from URL if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) { try { URL url = new URL(filename); icon = new ImageIcon(url); } catch (Exception e) { /* not a url */ } } // in case file is inside a .jar if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) { URL url = StdDraw.class.getResource(filename); if (url == null) throw new IllegalArgumentException("image " + filename + " not found"); icon = new ImageIcon(url); } return icon.getImage(); }
6
public void visitVarExpr(final VarExpr expr) { if(!(expr.isDef() || (expr.def() != null) || (expr.parent() instanceof PhiStmt))) { System.out.println(expr.getClass()); } Assert.isTrue(expr.isDef() || (expr.def() != null) || (expr.parent() instanceof PhiStmt), "Null def for variable " + expr); visitDefExpr(expr); }
5
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); b = (String)stream.readObject(); }
0
public boolean addShow(Show show){ if (show instanceof Movie){ if (showExists(show)){ return false; }else { Movie tmp = new Movie((Movie) show); shows.add(tmp); } }else{ if (showExists(show)){ return false; }else { Theatrical tmp = new Theatrical((Theatrical) show); shows.add(tmp); } } return true; }
3
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final TOutlet other = (TOutlet) obj; if (!Objects.equals(this.scyOutCode, other.scyOutCode)) { return false; } return true; }
3
public void setSymbols(final Hashtable<K, String> symbols) { this.symbols = symbols; }
0
public static void main(String[] args) { final Count count = new Count(); for (int i = 0; i < 2; i++) { new Thread() { public void run() { count.get(); } }.start(); } for (int i = 0; i < 2; i++) { new Thread() { public void run() { count.put(); } }.start(); } }
2
public ArrayList<MealData> mealsForCategory(MealCategoryData category) { ArrayList<MealData> meals = new ArrayList<MealData>(); for (LineData canteenLine : canteenData.getLines()) { for (MealData meal : canteenLine.getTodayMeals()) { if (meal.getMealCategory().equals(category)) { meals.add(meal); } } } return meals; }
3
public String execute() { String returnVal = SUCCESS; if (getSubmit() != null && SUBMIT.equals(getSubmit())) { LibraryManagementFacade facade = new LibraryManagementFacade(); try { Calendar calendar = Calendar.getInstance(); if ("issue".equals(getAction())) { Date issueDate = calendar.getTime(); getIssueBookVO().setIssueDate(issueDate); facade.issueBook(getIssueBookVO()); addActionMessage("Book " + issueBookVO.getBookID() + " is issued to " + issueBookVO.getStudentID()); } else if ("receive".equals(getAction())) { Date receiveDate = calendar.getTime(); getIssueBookVO().setReceiveDate(receiveDate); facade.receiveBook(getIssueBookVO()); addActionMessage("Book " + issueBookVO.getBookID() + " is received by " + issueBookVO.getStudentID()); } } catch (LibraryManagementException e) { addActionError(e.getExceptionCategory().getMessage()); returnVal = ERROR; } } else { returnVal = "issuebook"; // when comes first time } return returnVal; }
5
@SuppressWarnings("unchecked") @Override public final boolean equals(Object o) { if (o == this) return true; if (o == null) return false; /* Here we assume final classes, and comparisons only * between leaf (final) classes */ if (o.getClass() != getClass()) return false; return _equals((T) o); }
3
public void movement() { if (body == null) return; Vector3D oldPosition = getLocation(); body.updateBodyEuler(0.1); if (body.getX() > getArenaWidth() - getWidth() || body.getY() > getArenaHeight() - getHeight() || body.getX() < 0 || body.getY() < 0 || getArena().isBlockedByTerrain((int)body.getX(), (int)body.getY(), getWidth(), getHeight())) { body.setPosition(oldPosition); // Shut down all velocities, etc. body.reset(); // Notify interested parties. blockedByTerrain(); } setLocation(body.getPosition()); BlockageInfo blockage = isMovementBlocked(); if (blockage != null) { body.reset(); body.setPosition(oldPosition); setLocation(body.getPosition()); // Notify interested parties movementIsBlocked(blockage); } }
7
double isApproxEqual(MembershipFunction mf, InnerOperatorset op) { if(mf instanceof FuzzySingleton) { return op.moreorless(isEqual( ((FuzzySingleton) mf).getValue())); } if((mf instanceof OutputMembershipFunction) && ((OutputMembershipFunction) mf).isDiscrete() ) { double[][] val = ((OutputMembershipFunction) mf).getDiscreteValues(); double deg = 0; for(int i=0; i<val.length; i++){ double mu = op.moreorless(isEqual(val[i][0])); double minmu = (mu<val[i][1] ? mu : val[i][1]); if( deg<minmu ) deg = minmu; } return deg; } double mu1,mu2,minmu,degree=0; for(double x=min; x<=max; x+=step){ mu1 = mf.compute(x); mu2 = op.moreorless(isEqual(x)); minmu = (mu1<mu2 ? mu1 : mu2); if( degree<minmu ) degree = minmu; } return degree; }
9
public void propertyChange(PropertyChangeEvent evt) { if (calendar != null) { Calendar c = (Calendar) calendar.clone(); if (evt.getPropertyName().equals("day")) { c.set(Calendar.DAY_OF_MONTH, ((Integer) evt.getNewValue()).intValue()); setCalendar(c, false); } else if (evt.getPropertyName().equals("month")) { c.set(Calendar.MONTH, ((Integer) evt.getNewValue()).intValue()); setCalendar(c, false); } else if (evt.getPropertyName().equals("year")) { c.set(Calendar.YEAR, ((Integer) evt.getNewValue()).intValue()); setCalendar(c, false); } else if (evt.getPropertyName().equals("date")) { c.setTime((Date) evt.getNewValue()); setCalendar(c, true); } } }
5
public ArrayList<Integer> getRow(int rowIndex) { ArrayList<Integer> res = new ArrayList<Integer>(); if(rowIndex < 0) return res; res.add(1); if(rowIndex == 0) return res; res.add(1); if(rowIndex == 1) return res; for(int i = 1; i <= rowIndex-1; ++i){ for(int j = 0; j < res.size()-1; ++j){ res.set(j, res.get(j) + res.get(j+1)); } res.set(res.size()-1, 1); res.add(0, 1); } return res; }
5
private static int partition(int[] array, int start, int end) { int center = (start + end) / 2; //mediaan van 3 if (array[center] < array[start]) { swap(array, center, start); } if (array[end] < array[start]) { swap(array, start, end); } if (array[end] < array[center]) { swap(array, center, end); } int pivotIndex = center; //spil achteraan swap(array, pivotIndex, end - 1); int pivot = array[end - 1]; int left = start; int right = end - 1; while (array[++left] < pivot); while (pivot < array[--right]); while (left < right) { swap(array, left, right); while (array[++left] < pivot); while (pivot < array[--right]); } pivotIndex = left; swap(array, pivotIndex, end - 1); return pivotIndex; }
8
public ReceptKompDTO getReceptKomp(int receptId, int raavareId) throws DALException { ResultSet rs = Connector.doQuery("SELECT * FROM receptkomponent WHERE recept_id = " + receptId + " AND raavare_id = " + raavareId); try { if (!rs.first()) throw new DALException("Receptkomponenten " + receptId + ", " + raavareId + " findes ikke"); return new ReceptKompDTO (rs.getInt(1), rs.getInt(2), rs.getDouble(3), rs.getDouble(4)); } catch (SQLException e) {throw new DALException(e); } }
2
public Window(GraphCanvas canvas) { this.canvas = canvas; }
0
protected Pair<Item,String> makeItemContainer(String data) { int x=data.indexOf(';'); if(x<0) return null; Item I=null; if(data.substring(0,x).equals("COINS")) I=CMClass.getItem("StdCoins"); else I=CMClass.getItem(data.substring(0,x)); if(I!=null) { String container=""; String xml = data.substring(x+1); if(xml.startsWith("CONTAINER=")) { x=xml.indexOf(';'); if(x>0) { container=xml.substring(10,x); xml=xml.substring(x+1); } } CMLib.coffeeMaker().setPropertiesStr(I,xml,true); if((I instanceof Coins) &&(((Coins)I).getDenomination()==0.0) &&(((Coins)I).getNumberOfCoins()>0)) ((Coins)I).setDenomination(1.0); I.recoverPhyStats(); I.text(); return new Pair<Item,String>(I,container); } return null; }
8
* @return String */ public static String getShortName(Stella_Object obj) { { Surrogate testValue000 = Stella_Object.safePrimaryType(obj); if (Surrogate.subtypeOfP(testValue000, Logic.SGT_LOGIC_SKOLEM)) { { Skolem obj000 = ((Skolem)(obj)); return (null); } } else if (Surrogate.subtypeOfP(testValue000, Logic.SGT_LOGIC_LOGIC_OBJECT)) { { LogicObject obj000 = ((LogicObject)(obj)); return (Logic.objectNameString(obj000)); } } else if (Surrogate.subtypeOfKeywordP(testValue000)) { { Keyword obj000 = ((Keyword)(obj)); return (":" + obj000.symbolName); } } else if (Surrogate.subtypeOfP(testValue000, Logic.SGT_STELLA_GENERALIZED_SYMBOL)) { { GeneralizedSymbol obj000 = ((GeneralizedSymbol)(obj)); return (obj000.symbolName); } } else if (Surrogate.subtypeOfP(testValue000, Logic.SGT_STELLA_CONTEXT)) { { Context obj000 = ((Context)(obj)); return (obj000.contextName()); } } else if (Surrogate.subtypeOfP(testValue000, Logic.SGT_LOGIC_COMPUTED_PROCEDURE)) { { ComputedProcedure obj000 = ((ComputedProcedure)(obj)); return (obj000.surrogateValueInverse.symbolName); } } else { return (null); } } }
6
public void showDialog() { org.i4qwee.chgk.trainer.new_brain.actionlisteners.MouseListener.setHandle(false); super.showDialog(); org.i4qwee.chgk.trainer.new_brain.actionlisteners.MouseListener.setHandle(true); }
0
public static ComboBoxModel getAllParameters() { if(parameterModel==null) { checkParameterList(); parameterModel = new DefaultComboBoxModel(); for(String v:parameters.keySet()) { if(v.equals("Neighbore")|| v.equals("Datapoint")) continue; parameterModel.addElement(v); } } System.out.println(parameterModel.getSize()); return parameterModel; }
4
private String getAbbreviatedName(String name) { if (!isTooLarge(name)) { return name; } String[] partNames = name.split(" "); // Abbreviate middle names: for (int i = 1; i < partNames.length - 1 && isTooLarge(Utils.join(" ", partNames)); i++) { partNames[i] = partNames[i].charAt(0) + "."; } // Remove middle names: while (partNames.length > 2 && isTooLarge(Utils.join(" ", partNames))) { String[] newPartNames = new String[partNames.length - 1]; newPartNames[0] = partNames[0]; for (int i = 1; i < newPartNames.length; i++) { newPartNames[i] = partNames[i + 1]; } partNames = newPartNames; } if (!isTooLarge(Utils.join(" ", partNames))) { return Utils.join(" ", partNames); } else if (!isTooLarge(partNames[0].charAt(0) + ". " + partNames[1])) { return partNames[0].charAt(0) + ". " + partNames[1]; } else if (!isTooLarge(partNames[0] + " " + partNames[1].charAt(0) + ".")) { return partNames[0] + " " + partNames[1].charAt(0) + "."; } else { return partNames[0].charAt(0) + ". " + partNames[1].charAt(0) + "."; } }
9
@Test public void testNoAgregarTodasEntidades() { Object[][] entidades = new Object[4][4]; entidades[0][0] = new Long(2000); entidades[0][1] = "Tuercas"; entidades[0][2] = new Double(250); try { entidades[1][0] = new Long(100); entidades[1][1] = "Llave 14"; entidades[1][2] = new Double("Llave 14"); } catch (NumberFormatException numberFormatException) { System.out.println("Ha ocurrido una o varias excepciones de NullPointerException"); } entidades[2][0] = new Long(100); entidades[2][1] = "Tuerca"; entidades[2][2] = new Double(1200); try { entidades[3][0] = new Long(2); entidades[3][1] = "Taladro"; entidades[3][2] = new Double("Taladro"); } catch (NumberFormatException numberFormatException) { System.out.println("Ha ocurrido una o varias excepciones de NullPointerException"); } Sistema sistema = Sistema.getInstance(); int tamAnterior = sistema.getEntidades().size(); CONTROL.agregarEntidades(entidades); int tamSiguiente = sistema.getEntidades().size(); assertEquals(tamAnterior + entidades.length, tamSiguiente); }
2
public static UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { List<UndirectedGraphNode> nodes = new ArrayList<UndirectedGraphNode>(); UndirectedGraphNode headnode = null; int index = 0; if (null == node) return null; nodes.add(node); while (index != nodes.size()) { UndirectedGraphNode n = nodes.get(index); UndirectedGraphNode newNode = new UndirectedGraphNode(n.label); if (null == headnode) headnode = newNode; n.neighbors.add(newNode); int size = n.neighbors.size(); for (int i = 0; i < size - 1; i++) { UndirectedGraphNode neighbor = n.neighbors.get(i); if (!(nodes.contains(neighbor))) nodes.add(neighbor); } index = index + 1; } for (UndirectedGraphNode rawnode : nodes) { int size = rawnode.neighbors.size(); UndirectedGraphNode newNode = rawnode.neighbors.get(size - 1); for (int i = 0; i < rawnode.neighbors.size() - 1; i++) { UndirectedGraphNode neighbor = rawnode.neighbors.get(i); int neighborlen = neighbor.neighbors.size(); newNode.neighbors.add(neighbor.neighbors.get(neighborlen - 1)); } } for (UndirectedGraphNode rawnode : nodes) { int size = rawnode.neighbors.size(); rawnode.neighbors.remove(size - 1); } return headnode; }
8
private void searchRentacars() { if (dateFieldReturnDate.getDate() < dateFieldPickUp.getDate()) { Dialog.alert("Return date should be greater or equals to Pick up date"); return; } if (rentalcarSearchParameters.getFromAirportId() == null || rentalcarSearchParameters.getToAirportId() == null) { Dialog.alert("Select pick up and drop of"); return; } // set search parameters rentalcarSearchParameters.setDepartureDate(dateFieldPickUp.getDate()); rentalcarSearchParameters.setReturnDate(dateFieldReturnDate.getDate()); // create process object to handle response ProcessSearchRentacars processSearchRentalcars = new ProcessSearchRentacars(rentalcarSearchParameters) { public void onComplete() { UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { if(getErrorCode() != null) { Dialog.alert("Error: " + errorCode); return; } if (getResult().getTotal() == 0) { Dialog.alert("No results found for requested data"); return; } UiApplication.getUiApplication().pushScreen(new RentacarSearchResultsScreen(getResult())); } }); } public String getLoadingMessage() { return "Searching ... Please wait."; } }; // Call search rentacars WS TravelSDK.INSTANCE.searchRentacars(processSearchRentalcars); }
5
public static void main(String[] args) { // ConcreteClassの実装次第で独自ロジックを切り替える。共通処理は親クラスで実装。 AbstractClass c1 = new ConcreteClass(); c1.templateMethod(); System.out.println("--------------------"); // 無名クラスを使ってみたり。 AbstractClass c2 = new AbstractClass() { @Override void method() { System.out.println("独自処理:" + LoggerUtils.getSig()); } }; c2.templateMethod(); }
0
public void renderShipMorphBehaviors(int glMode, RenderStyle renderStyle, Ship ship, boolean preMorphRendering) { for (Morph morph : ship.getMorphsByIds().values()) { if (glMode == GL11.GL_RENDER) { for (Behavior<?> behavior : morph.getAlwaysActiveBehaviorList()) { renderBehavior(glMode, renderStyle, behavior, preMorphRendering); } for (Behavior<?> behavior : morph.getActivationLinkedBehaviorList()) { renderBehavior(glMode, renderStyle, behavior, preMorphRendering); } for (Behavior<?> behavior : morph.getActivationIsolatedBehaviorList()) { renderBehavior(glMode, renderStyle, behavior, preMorphRendering); } } } }
8
protected int getKnownAttributeCount() { int count = 0; if (lvt != null) count++; if (lnt != null) count++; return count; }
2
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { // Entering a sub-command without parameters is assumed to be a request // for information. So display some detailed help. if (args.length == 0) { sender.sendMessage(plugin.translate(sender, "menu-open-usage-extended", "/menu open ([player]) [id] - Opens the menu with the given id for use. If a player is specified, the menu will open for this player instead of the command sender. Clicking an icon will not pick it up, but instead run all commands listed in the lore")); return true; } // Expecting 1 or 2 parameters, depending on whether player is provided if (args.length > 2) { return false; } Player target; int i = 0; if (args.length == 1) { // No player provided, target the sender if (sender instanceof Player) { target = (Player) sender; // If the command is self-targetted, also check specific-menu permissions if (!sender.hasPermission("cyom.commands.menu.open") && !sender.hasPermission("cyom.menu." + args[0])) { sender.sendMessage(plugin.translate(sender, "no-menu-perms", "You do not have permission to open this menu")); return true; } } else { sender.sendMessage(plugin.translate(sender, "console-no-target", "The console must specify a player")); return true; } } else { // You must have full permissions to target another player if (!sender.hasPermission("cyom.commands.menu.open")) { sender.sendMessage(plugin.translate(sender, "command-no-perms", "You do not have permission to use this command")); return true; } // Player is provided, so target the named player String targetName = args[i++]; target = plugin.getServer().getPlayerExact(targetName); if (target == null) { sender.sendMessage(plugin.translate(sender, "player-not-online", "{0} is not online", targetName)); return true; } } // Ensure the menu id is valid String id = args[i++]; Menu menu = plugin.getMenu(id); if (menu == null) { sender.sendMessage(plugin.translate(sender, "unknown-menu-id", "There is no menu with id {0}", id)); return true; } // Open the menu for the target menu.open(target); return true; }
9
@Override public void run() { if (!mNoFurtherWrites) { try { // Wait for any pending writes to finish, but not forever long maxWait = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(1, TimeUnit.MINUTES); while (mServer.hasPendingWrite(mChannel) && System.currentTimeMillis() < maxWait) { Thread.sleep(50); } } catch (InterruptedException exception) { // Even if interrupted, we still want to try and close the channel } } try { mChannel.close(); } catch (IOException ioe) { Log.error(this, ioe); } mServer.sessionClosed(this); }
5
private V active(){ //we know at the start, we clearly aren't done //and we also know the params are also set rec.get().req.done = false; while(true){ boolean locked = true; if(!lock.lock()){ //NOT the combiner while(!rec.get().req.done && rec.get().active && (locked = lock.isLocked())); } else{//AM the combiner //run through the publication list and complete all the operations amLockholder(); lock.unlock(); //don't worry about locked. } //if we've been set inactive, we need to fix that and continue again if(!rec.get().active){ set_active(); continue; } //if lockholder, won't enter. if came unlocked, and spinning, //we try to grab it else if(!locked){ continue; } else{//returned return rec.get().req.retval; } } }
7
@Test public void SpeakerToTopicWriterTest() { String theSpeaker = "Cameron Thomas"; String topic = "CS 246"; String base = "CS 246"; String content = "This is the content"; //HashMap<String, List<Session>> topicMap = new HashMap<>(); ArrayList<Speaker> listOfSpeakers = new ArrayList(); // Loop to add new speakers to hasmap for (int i = 0; i < 10; i++) { listOfSpeakers.add(new Speaker(theSpeaker)); // Loop to add new topics for (int j = 0; j < 10; j++) { listOfSpeakers.get(i).getTopics().put(topic, new ArrayList<Content>()); // Loop to add session to each topic for (int k = 0; k < 3; k++) { listOfSpeakers.get(i).getTopics().get(topic).add(new Content()); } // Loop to set content and date in each session for (Content testSession: listOfSpeakers.get(i).getTopics().get(topic)) { testSession.setContent(content); testSession.setDate(2012, 12, 4); } topic = "topic" + j; } theSpeaker = "Cameron Thomas" + i; } new WriteFile().PersonXmlWriter(listOfSpeakers); new WriteFile().writeDataFile("This is the content", "Cameron Thomas", "War"); }
4
public static void main(String[] args) { String filename = args[0]; String separator = args[1]; In in = new In(filename); ST<String, Queue<String>> st = new ST<String, Queue<String>>(); ST<String, Queue<String>> ts = new ST<String, Queue<String>>(); while (in.hasNextLine()) { String line = in.readLine(); String[] fields = line.split(separator); String key = fields[0]; for (int i = 1; i < fields.length; i++) { String val = fields[i]; if (!st.contains(key)) st.put(key, new Queue<String>()); if (!ts.contains(val)) ts.put(val, new Queue<String>()); st.get(key).enqueue(val); ts.get(val).enqueue(key); } } StdOut.println("Done indexing"); // read queries from standard input, one per line while (!StdIn.isEmpty()) { String query = StdIn.readLine(); if (st.contains(query)) for (String vals : st.get(query)) StdOut.println(" " + vals); if (ts.contains(query)) for (String keys : ts.get(query)) StdOut.println(" " + keys); } }
9
public static Configuration loadConfiguration( InputStream input ) throws Exception { Configuration config = new Configuration(); config.delays = Tries.forInsensitiveStrings( 0 ); config.inclusion = Tries.forInsensitiveStrings( Boolean.FALSE ); config.mode = AgentMode.CSV; Element root = XmlUtility.read( input ); validateTagName( root, TAG_ROOT ); /* INCLUSIONS */ Element inclusionGroup = findElement( root, TAG_INCLUSION_GROUP ); XmlFilter<Element> inclusions = createFilter( inclusionGroup, TAG_INCLUSION, true ); for (Element e : inclusions) { String pattern = getAttribute( e, ATTR_PATTERN, null ); Integer delay = Integer.parseInt( getAttribute( e, ATTR_DELAY, 0 ) ); config.inclusion.put( pattern, Boolean.TRUE ); config.delays.put( pattern, delay ); } /* EXCLUSIONS */ Element exclusionGroup = findElement( root, TAG_EXCLUSION_GROUP ); XmlFilter<Element> exclusions = createFilter( exclusionGroup, TAG_EXCLUSION, false ); for (Element e : exclusions) { String pattern = getAttribute( e, ATTR_PATTERN, null ); config.inclusion.put( pattern, Boolean.FALSE ); } /* PROPERTIES */ Element propertyGroup = findElement( root, TAG_PROPERTY_GROUP ); XmlFilter<Element> properties = createFilter( propertyGroup, TAG_PROPERTY, false ); for (Element e : properties) { String name = getAttribute( e, ATTR_NAME, null ); String value = getAttribute( e, ATTR_VALUE, null ); if (name.equalsIgnoreCase( CONFIG_MODE )) { config.mode = AgentMode.valueOf( value ); } else { throw new IOException( "'" + name + "' is an unknown property" ); } } return config; }
4
@Override public void start(Character player) { System.out.println("Starting Treasure Event..."); int randomizedEvent = generator.nextInt(100) + 1; if(randomizedEvent > 75){ //Drop gold randomGold = generator.nextInt(10) + 1; System.out.println("You opened the chest and found " + this.getGold() + " Gold!"); player.pickUpGold(this.getGold()); } else{ //Drop potion //randomize chance for health/mana pot int randPotion; randPotion = generator.nextInt(2) + 1; if(randPotion == 1){ int randNumOfPotions = generator.nextInt(2) + 1; if(randNumOfPotions == 1){ System.out.println("You found " + randNumOfPotions + " Health Potion!"); player.setHealthPotions(1); System.out.println("You now have " + player.getHealthPotionSize() + " Health Potions"); } else{ System.out.println("You found " + randNumOfPotions + " Health Potions!"); player.setHealthPotions(2); System.out.println("You now have " + player.getHealthPotionSize() + " Health Potions"); } } else{ int randNumOfPotions = generator.nextInt(2) + 1; if(randNumOfPotions == 1){ System.out.println("You found " + randNumOfPotions + " Mana Potion!"); player.setManaPotions(1); System.out.println("You now have " + player.getManaPotionSize() + " Mana Potions"); } else{ System.out.println("You found " + randNumOfPotions + " Mana Potions!"); player.setManaPotions(2); System.out.println("You now have " + player.getManaPotionSize() + " Mana Potions"); } } } }
4
@Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub double amount; boolean isLent = false; String description; String dateString; Date date = null; SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy-MM-dd"); if(e.getSource() instanceof JButton){ if(e.getSource()==jbtSave){ if(jrbBorrow.isSelected()){ isLent=false; } else if(jrbLend.isSelected()){ isLent=true; } amount = Double.parseDouble(jtfAmount.getText()); description=jtfDescription.getText(); dateString = jtfDate.getText(); try { date = dateFormate.parse(dateString); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if(date.after(Calendar.getInstance().getTime())){ String error = "current date is :"+dateFormate.format(Calendar.getInstance().getTime())+". New Transaction cannot be created after this date!"; JOptionPane.showMessageDialog(null,error,"Error",JOptionPane.ERROR_MESSAGE); setVisible(false); dispose(); openUI(); } else{ //---new transfer created, then how to save it? Transfer newTransfer = new Transfer(amount,date,description,isLent); Repository.Add(newTransfer); Repository.Save(); if(!SummaryController.GetAlert().equals("")){ JOptionPane.showMessageDialog(null,SummaryController.GetAlert(),"Alert",JOptionPane.WARNING_MESSAGE); } setVisible(false); dispose(); WelcomeGUI welcomeGUI = new WelcomeGUI(); welcomeGUI.openUI(); } } else if(e.getSource()==jbtSelectDate){ jtfDate.setText(new DatePicker(this).setPickedDate()); } else if(e.getSource()==jbtCancel){ setVisible(false); dispose(); WelcomeGUI welcomeGUI = new WelcomeGUI(); welcomeGUI.openUI(); } } }
9
public void setLeafIcons(String menuName, ImageIcon normal, ImageIcon selected) { for (AccordionRootItem menu : getMenus()) { if (menu.getName().equals(menuName)) { if (normal != null) { for (AccordionLeafItem leaf : getLeafsOf(menuName)) { leaf.setNormalIcon(normal); } } if (selected != null) { for (AccordionLeafItem leaf : getLeafsOf(menuName)) { leaf.setSelectedIcon(selected); } } } } updateLeafs(); }
6
public static void initScore() { int[][] moviercount = new int[DataInfo.numItems][DataInfo.softmax]; Function.zero(moviercount, DataInfo.numItems, DataInfo.softmax); for(int user = 0; user < DataInfo.numUsers; user++) { int num = DataInfo.TrainSet[user].length; for(int j = 0; j < num; j++) { int m = DataInfo.TrainSet[user][j] / 10; int r = DataInfo.TrainSet[user][j] % 10; moviercount[m][r]++; } } Random randn = new Random(); /** Set initial weights */ for(int i = 0; i < DataInfo.numItems; i++) { for(int j = 0; j < DataInfo.totalFeatures; j++) { for(int k = 0; k < DataInfo.softmax; k++) { /** Normal Distribution */ DataInfo.Weights[i][k][j] = 0.02 * randn.nextDouble() - 0.01; } } } /** Set initial biases */ Function.zero(DataInfo.hidbiases, DataInfo.totalFeatures); for(int i = 0; i < DataInfo.numItems; i++) { int mtot = 0; for(int k = 0; k < DataInfo.softmax; k++) { mtot += moviercount[i][k]; } for(int k = 0; k < DataInfo.softmax; k++) { DataInfo.visbiases[i][k] = Math.log(((double)moviercount[i][k])/((double)mtot)); } } }
8
public long getTimestamp() { System.out.println("getTimestamp():"); if (timestamp==null) return 0; long ts=0; if ( timestamp == null ) timestamp = ""; else { // timestamp=timestamp.trim(); if ( timestamp.length()>0 ) { try { ts = new Long(timestamp).longValue(); } catch(Throwable t){ts=0;} } } if ( ts < 1 ) { boolean udate = true; String dt = getDate(); if (dt.trim().length()<8) udate = false; String time = getTime(); if ( udate ) { String yr="0"; String mnth="0"; String dy="0"; String hr = "0"; String min = "0"; if (!(dt.trim().length()<8)) { yr = dt.substring(0, 4); mnth = dt.substring(4, 6); dy = dt.substring(6, 8); } if ( !(time.trim().length()<4)) { hr = time.substring(0, 2); min = time.substring(2, 4); } int y = new Integer(yr).intValue(); int m = new Integer(mnth).intValue()-1; int d = new Integer(dy).intValue(); int h = new Integer(hr).intValue(); int mn = new Integer(min).intValue(); java.util.Calendar cal = java.util.Calendar.getInstance(); cal.set(y, m, d, h, mn); ts = cal.getTimeInMillis(); } } return ts; }
9
void launchThreads(final int numIter) { for(int i=0;i<NUM_THREADS;i++) { threads[i] = new Thread() { @Override public void run() { try { final Directory[] dirs = new Directory[NUM_COPY]; for(int k=0;k<NUM_COPY;k++) dirs[k] = new MockRAMDirectory(dir); int j=0; while(true) { // System.out.println(Thread.currentThread().getName() + ": iter j=" + j); if (numIter > 0 && j == numIter) break; doBody(j++, dirs); } } catch (Throwable t) { handle(t); } } }; } for(int i=0;i<NUM_THREADS;i++) threads[i].start(); }
7
public void UpdateLayout() { for(GuiField button :displayedFields) { button.UpdateLayout(); } }
1
public void fuseTimeAndStylo(List info) { List tempInfo = new ArrayList(); tempInfo.addAll(info); // System.out.println("List: "); // for (Object a : info) { // System.out.println(a); // } List sortedStyloList = new ArrayList(); List sortedTimeList = new ArrayList(); sortedStyloList = getsortedStylo(tempInfo); sortedTimeList = getsortedTime(tempInfo); // System.out.println("Stylo List"); // for (Object a : sortedStyloList) { // System.out.println(a); // } // System.out.println("Time List"); // for (Object a : sortedTimeList) { // System.out.println(a); // } Iterator<List> itr = tempInfo.iterator(); while (itr.hasNext()) { List secondList = itr.next(); String tempUser = secondList.get(1).toString(); int foundStylo = -1; int foundTime = -1; Iterator<List> styloItr = sortedStyloList.iterator(); Iterator<List> timeItr = sortedTimeList.iterator(); int counter = 1; while (styloItr.hasNext() && foundStylo == -1) { List tempStyloList = styloItr.next(); String tempStyloUser = tempStyloList.get(1).toString(); if (tempStyloUser.equals(tempUser)) { foundStylo = counter; } counter++; } int timeCounter = 1; while (timeItr.hasNext() && foundTime == -1) { List tempTimeList = timeItr.next(); String tempTimeUser = tempTimeList.get(1).toString(); if (tempTimeUser.equals(tempUser)) { foundTime = timeCounter; } timeCounter++; } int fusionValue = 0; fusionValue = (foundStylo + foundTime) / 2; secondList.add(fusionValue); } sortListWithFusionValue(sortedTimeList); }
7
public Parser build(Grammar grammar, boolean useHeadSet) { NontermTable nontermTable = new NontermTable(); // Construct automation. State.StateGenerator stateGenerator = new State.StateGenerator(); State startState = stateGenerator.generate(); for (Grammar.Production production: grammar.getProductions()) { Nonterm head = nontermTable.get(production.head.name()); State current = startState; int len = production.body.length; for (int i = 0; i < len; i ++) { Grammar.ISymbol symbol = production.body[i]; if (symbol instanceof Grammar.Nonterm) { Nonterm n = nontermTable.get(symbol.name()); if (i == 0) { // For left-most nonterm situation current = n.addLeftMostRule(head.id, stateGenerator); } else { current = current.addNontermTransition(n.id, head.id, stateGenerator); } } else if (symbol instanceof Grammar.Term) { current = current.addTermTransition(symbol.name(), head.id, stateGenerator); } else { throw new ParseException("Unknown symbol type: " + symbol.getClass()); } } // Set accepting state current.setAcceptedNonterm(head.id); } // Extend transitions' head set. if (useHeadSet) { extendTransitionHeadSet(stateGenerator, nontermTable); } // Top head Grammar.Nonterm topHead = grammar.getTopHead(); int topHeadId = topHead == null ? Nonterm.ANY : nontermTable.get(topHead.name()).id; // Build parser. Nonterm[] table = new Nonterm[nontermTable.size()]; for (Nonterm n: nontermTable.getAll()) { table[n.id] = n; } return new Parser(table, startState, topHeadId, useHeadSet); }
8
public boolean addElement(T element) throws InterruptedException { lock.lock(); try { while (isFull()) { emptyCondition.await(); } boolean result = tasksQueue.add(element); fullCondition.signalAll(); return result; } finally { lock.unlock(); } }
1
public void close(){ try { ps.close(); } catch (SQLException e){ if( debug ) System.out.println("Error in DBComm.close(): "+e.getMessage()); } }
2
public Integer pop() throws EmptyException { counter -= 1; if (counter < 0) { counter = 0; throw new EmptyException(); } return table[counter]; }
1
public static TheoraPacket create(OggPacket packet) { byte type = packet.getData()[0]; // Special header types detection if(isTheoraSpecial(packet)) { switch(type) { case (byte)TYPE_IDENTIFICATION: return new TheoraInfo(packet); case (byte)TYPE_COMMENTS: return new TheoraComments(packet); case (byte)TYPE_SETUP: return new TheoraSetup(packet); } } return new TheoraVideoData(packet); }
4
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; }
9
private List<Trade> auctionOrderList() { List<Trade> tra = new ArrayList<Trade>(); while ( buyOrderQueue.size() != 0 && sellOrderQueue.size() != 0 && buyOrderQueue.get(0).getPrice() >= sellOrderQueue.get(0).getPrice() ) { Order buyOrder = buyOrderQueue.get(0); Order sellOrder = sellOrderQueue.get(0); Trade tempTrade = new Trade(); // set the price of tradeOrder if ( buyOrder.getCreateTime() <= sellOrder.getCreateTime() ) { tempTrade.setTradePrice(buyOrder.getPrice()); synchronized (stockPrice) { stockPrice = buyOrder.getPrice(); } } else { tempTrade.setTradePrice(sellOrder.getPrice()); synchronized (stockPrice) { stockPrice = sellOrder.getPrice(); } } // set the Ids of tradeOrder tempTrade.setBuyId(buyOrder.getAgentId()); tempTrade.setBuyOrderId(buyOrder.getId()); tempTrade.setSellId(sellOrder.getAgentId()); tempTrade.setSellOrderId(sellOrder.getId()); tempTrade.setTradeTime(System.currentTimeMillis()); // set the volume of tradeOrder if (buyOrder.getVolume() == sellOrder.getVolume()) { tempTrade.setTradeVolume(buyOrder.getVolume()); tra.add(tempTrade); sellOrderQueue.remove(0); buyOrderQueue.remove(0); } else if (buyOrder.getVolume() > sellOrder.getVolume()) { tempTrade.setTradeVolume(sellOrder.getVolume()); tra.add(tempTrade); sellOrderQueue.remove(0); buyOrderQueue.get(0).setVolume( buyOrder.getVolume() - sellOrder.getVolume() ); } else { tempTrade.setTradeVolume(buyOrder.getVolume()); tra.add(tempTrade); sellOrderQueue.get(0).setVolume( sellOrder.getVolume() - buyOrder.getVolume() ); buyOrderQueue.remove(0); } } return tra; }
6
private Expr factor() throws IOException { Expr e; switch (token) { case '(': token = tokenizer.nextToken(); e = expr(); if (token != ')') throw new XLException("expecting \")\", found: " + token); token = tokenizer.nextToken(); return e; case StreamTokenizer.TT_NUMBER: double x = tokenizer.nval; token = tokenizer.nextToken(); return new Num(x); case StreamTokenizer.TT_WORD: String address = tokenizer.sval.toUpperCase(); if (!Pattern.matches("[A-Z][0-9]+", address)) throw new XLException("illegal address: " + address); token = tokenizer.nextToken(); return new Variable(address); case StreamTokenizer.TT_EOF: throw new XLException("unexpected end of text"); default: throw new XLException("unexpected " + (char) token); } }
6
public static DenseMatrix64F handleV(DenseMatrix64F V, boolean transpose, boolean compact, int m , int n , int min ) { int w = n > m ? min + 1 : min; if( compact ) { if( transpose ) { if( V == null ) { V = new DenseMatrix64F(w,n); } else V.reshape(w,n, false); } else { if( V == null ) { V = new DenseMatrix64F(n,w); } else V.reshape(n,w, false); } } else { if( V == null ) { V = new DenseMatrix64F(n,n); } else V.reshape(n,n, false); } return V; }
6
public void tick() { if(dmgLen > 0) { dmgTick++; if(dmgTick > 120) //120 = 2 seconds { dmgLen = dmgTick = 0; } } if(moving) { walkTick++; if(count >= walkList.size()) { walkList.clear(); listButtons(true); moving = false; moved = true; count = 0; //System.out.println("Finished moving"); } else { xOff += 4 * (walkList.get(count)[0] - this.dX / Game.TILESIZE); yOff += 4 * (walkList.get(count)[1] - this.dY / Game.TILESIZE); if(walkTick >= 8) { xOff = yOff = walkTick = 0; this.dX = walkList.get(count)[0] * Game.TILESIZE; this.dY = walkList.get(count)[1] * Game.TILESIZE; //System.out.println("x: " + x + " y: " + y); count++; } } } else if(walkList.size() > 1) { listButtons(false); moving = true; //System.out.println("Started moving"); } /*if(Game.map.count > 0) { xOff2 = Game.map.mX * Game.map.count + Game.xOff * Game.TILESIZE; yOff2 = Game.map.mY * Game.map.count + Game.yOff * Game.TILESIZE; } else { xOff2 = yOff2 = 0; }*/ }
6
RGBImage magnify(int n) { RGBImage m = new RGBImage(n * width, n * height); for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { int c = image.getRGB(col, row); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { m.image.setRGB(n * col + j, n * row + i, c); } } } } return m; }
4
public void print(Byte[] jeu){ for (int i=0; i < 37; i++){ if (i==4 || i==9 || i==15 || i==22 || i==28 || i==33) System.out.println(); System.out.print(jeu[i]); } System.out.println(); }
7
public String XAuth(String username, String password) { URL url; try { url = new URL("http://fanfou.com/oauth/access_token"); } catch (MalformedURLException e) { setLog(e.getMessage()); return null; } long timestamp = System.currentTimeMillis() / 1000; long nonce = System.nanoTime(); String params; String authorization; params = "oauth_consumer_key=" + consumer_key + "&oauth_nonce=" + String.valueOf(nonce) + "&oauth_signature_method=HMAC-SHA1" + "&oauth_timestamp=" + String.valueOf(timestamp) + "&x_auth_username=" + username + "&x_auth_password=" + password + "&x_auth_mode=client_auth"; try { params = "GET&" + URLEncoder.encode(url.toString(),"UTF-8") + "&" + URLEncoder.encode(params,"UTF-8"); } catch (UnsupportedEncodingException e) { setLog("编码错误"); } String sig = generateSignature(params); authorization = "OAuth realm=\"Fantalker\",oauth_consumer_key=\"" + consumer_key + "\",oauth_signature_method=\"HMAC-SHA1\"" + ",oauth_timestamp=\"" + String.valueOf(timestamp) + "\"" + ",oauth_nonce=\"" + String.valueOf(nonce) + "\"" + ",oauth_signature=\"" + sig + "\"" + ",x_auth_username=\"" + username + "\"" + ",x_auth_password=\"" + password + "\"" + ",x_auth_mode=\"client_auth\""; try { HttpURLConnection connection; connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.addRequestProperty("Authorization",authorization); connection.connect(); String line; if(connection.getResponseCode() == 200) { } else if(connection.getResponseCode() == 401) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String log = Main.txtLog.getText(); line = reader.readLine(); while(line != null) { log = log + "\r\n" + line; line = reader.readLine(); } Main.txtLog.setText(log); JOptionPane.showMessageDialog(null, "用户id或密码错误", "错误", JOptionPane.ERROR_MESSAGE); return null; } else { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String log = Main.txtLog.getText(); line = reader.readLine(); while(line != null) { log = log + "\r\n" + line; line = reader.readLine(); } setLog(log); JOptionPane.showMessageDialog(null, "未知错误,请重试", "错误", JOptionPane.ERROR_MESSAGE); return null; } BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); line = reader.readLine(); return line; } catch (SocketTimeoutException e) { setLog("连接超时,请重试:" + e.getMessage()); return null; } catch (IOException e) { setLog("创建输入流时发生 I/O错误:" + e.getMessage()); return null; } }
8
private String CheckIfUpdate(String modFolder, String mod) { boolean foundit=false; File oldMod = new File(modFolder+"/"+mod); if(oldMod.isDirectory()){ con.log("Log","IS DIRECTORY"); foundit=true; } else con.log("Log","NOT DIRECTORY ... " + oldMod); if(foundit){ if(McLauncher.tglbtnDeleteBeforeUpdate.isSelected()){ //If we delete the old mod before extracting. if(oldMod.delete()){ con.log("Log","Successfully deleted old mod for update."); } } return "&update=true"; } return "&update=false"; }
4
public static boolean isAPageTag(String str, boolean state) { if (state == true) { StringUtility.pattern = OPEN_PAGE_TAG; } else { StringUtility.pattern = CLOSE_PAGE_TAG; } StringUtility.matcher = pattern.matcher(str); return StringUtility.matcher.matches(); }
1
private void miLoadCourseMousePressed(java.awt.event.MouseEvent evt) { Object[] courseNames = Manager.getInstance().getCourseNames().toArray(); String selectedCourse = (String) JOptionPane.showInputDialog(this, "Select a course.", "Course Select", JOptionPane.QUESTION_MESSAGE, null, courseNames, courseNames[0]); if (selectedCourse == null) { return; } currentCourse = Manager.getInstance().getCourses().get(selectedCourse); loadCourse(Manager.getInstance().getCourses().get(selectedCourse)); }
1
public void histogrammeBruit() { Iterator<Float> itr = valeursBruit.iterator(); float vb; Integer val; while (itr.hasNext()) { vb = itr.next(); // regard de l'occurence d'un élément vb = (float) (Math.round((vb * 100.0)) / 100.0); val = mapHisto.get(vb); if (val != null) { mapHisto.put(vb, val + 1); } else { mapHisto.put(vb, 0); } } // créer une liste triée en fonction des valeursBruit de la hashmap LinkedList<Float> triHisto = new LinkedList<Float>(mapHisto.keySet()); Collections.sort(triHisto); // création information occurence occHisto = new Information<Float>(); Iterator<Float> itrHisto = triHisto.iterator(); Float keyValeursBruit; float occValeursBruit; while (itrHisto.hasNext()) { keyValeursBruit = itrHisto.next(); occValeursBruit = mapHisto.get(keyValeursBruit); occHisto.add(occValeursBruit); } }
3
public Ingredient getIngredient() { if (ingredient == null) { ingredient = new Ingredient(); } return ingredient; }
1
public void waitForConnection() { if (!server.isConnecting() && !server.isConnected()) { if (server.isConnectedToNetwork()) { new Thread(new Runnable() { @Override public void run() { updateStatus(WAITING); while (!server.waitForConnection()) { if (server.isAbortRequestSent()) return; } updateStatus(RUNNING); server.sendCMD(CMD.INTRODUCE, getName()); startSendingSensorsData(); startProceedingCommands(); } }).start(); } else { log("no network"); updateStatus(ERROR); } } else { log("already connecting"); updateStatus(ERROR); } }
5
@Override public boolean execute(MOB mob, List<String> commands, int metaFlags) throws java.io.IOException { final PlayerStats pstats=mob.playerStats(); if(pstats==null) return false; final StringBuffer buf=new StringBuffer(L("Available channels: \n\r")); int col=0; final String[] names=CMLib.channels().getChannelNames(); final int COL_LEN=CMLib.lister().fixColWidth(24.0,mob); for(int x=0;x<names.length;x++) { if(CMLib.masking().maskCheck(CMLib.channels().getChannel(x).mask(),mob,true)) { if((++col)>3) { buf.append("\n\r"); col=1; } final String channelName=names[x]; final boolean onoff=CMath.isSet(pstats.getChannelMask(),x); buf.append(CMStrings.padRight("^<CHANNELS '"+(onoff?"":"NO")+"'^>"+channelName+"^</CHANNELS^>"+(onoff?" (OFF)":""),COL_LEN)); } } if(names.length==0) buf.append("None!"); else buf.append("\n\rUse NOCHANNELNAME (ex: NOGOSSIP) to turn a channel off."); mob.tell(buf.toString()); return false; }
7
public static void writeArxFile(HashMap<String, String> map, File dest) { try { if (!dest.exists()) { dest.mkdirs(); dest.createNewFile(); } String output = ""; Set<String> keySet = map.keySet(); String[] keys = keySet.toArray(new String[0]); System.out.println(keys.toString()); for (String key : keys) { output += key + ": " + map.get(key) + "\n"; } FileWriter fw = new FileWriter(dest); fw.write(output); fw.close(); } catch (IOException ioe) { Log.error("Cannot write Arx file: '" + dest.getName() + "'\nReason: " + ioe.getMessage()); } }
3
private Raum[] getNachbarn(String[] richtungen, Raum raum) { Raum nordNachbar = null; Raum ostNachbar = null; Raum suedNachbar = null; Raum westNachbar = null; for(String s : richtungen) { if(s.equals(TextVerwalter.RICHTUNG_NORDEN)) { nordNachbar = raum.getAusgang(s); } else if(s.equals(TextVerwalter.RICHTUNG_OSTEN)) { ostNachbar = raum.getAusgang(s); } else if(s.equals(TextVerwalter.RICHTUNG_SUEDEN)) { suedNachbar = raum.getAusgang(s); } else if(s.equals(TextVerwalter.RICHTUNG_WESTEN)) { westNachbar = raum.getAusgang(s); } } Raum[] result = { nordNachbar, ostNachbar, suedNachbar, westNachbar }; return result; }
5
private void load() throws FileNotFoundException { Scanner in = new Scanner(new File(FILE_NAME)); while (in.hasNextLine()) { String line = in.nextLine(); if (!line.startsWith("#")) { String[] bisect = line.split("="); // If the field was defined; if (bisect.length > 1) { if (line.startsWith("ProtocolPort")) { setPort(Integer.parseInt(bisect[1])); } else if (line.startsWith("UserMotto")) { setMotto(bisect[1]); } else if (line.startsWith("UserID")) { setID(bisect[1]); } else if (line.startsWith("UserURL")) { setURL(bisect[1]); } else if (line.startsWith("UserName")) { setName(bisect[1]); } else if (line.startsWith("DNNSDServiceName")) { setServiceName(bisect[1]); } } } } in.close(); }
9
private void acao123() throws SemanticError { if (tipoLimiteInferior != tipoConstante) throw new SemanticError( "Constantes de intervalo de tipos diferentes"); int valorLimiteSuperior = tipoConstante == Tipo.INTEIRO ? Integer .parseInt(valorConstante) : valorConstante.charAt(0); if (valorLimiteSuperior <= valorLimiteInferior) throw new SemanticError( "Limite superior menor ou igual ao limite inferior do vetor"); }
3
@Override public void run(){ try{ if(!window.IsFull()){ socket.setName(recvStringMsg()); window.socket.getLast().setName(socket.getName()); window.sendStringMsg(socket.getName()+" entrou na sala...", window); while(socket.getSocket().isConnected()){ user = recvStringMsg(); msg = recvStringMsg(); if(user.equals("@logout")){ window.sendStringMsg(msg+" Saiu da sala... ", window); window.deleteSocket(window, msg); this.interrupt(); } else{ if(!window.searchUserInList(user, window)){ window.sendStringMsg(socket.getName()+" disse para <TODOS>: "+msg, window); } else{ window.sendString(socket.getName()+" disse para <"+user+">: " +msg, window, user); } } } } }catch(Exception e){ this.interrupt(); } }
5
public void borrarRegistros(String nombreTabla, int id) { try { this.bd.open(); this.table = this.bd.getTable(nombreTabla); this.bd.beginTransaction(SqlJetTransactionMode.WRITE); // Esta función busca por calve primaria aquel id que concuerde con el pasado por el usuario this.cursor = table.lookup(this.table.getPrimaryKeyIndexName(),id); // Mientras no sea fin del cursor while (!this.cursor.eof()) { // Elimina la clave buscada y sus datos asociados this.cursor.delete(); } this.cursor.close(); this.bd.commit(); this.bd.close(); } catch (SqlJetException ex) { Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex); } }
2
public void runGameTimedSpeedOptimised(Controller<MOVE> pacManController,Controller<EnumMap<GHOST,MOVE>> ghostController,boolean fixedTime,boolean visual) { Game game=new Game(0); GameView gv=null; if(visual) gv=new GameView(game).showGame(); if(pacManController instanceof HumanController) gv.getFrame().addKeyListener(((HumanController)pacManController).getKeyboardInput()); new Thread(pacManController).start(); new Thread(ghostController).start(); while(!game.gameOver()) { pacManController.update(game.copy(),System.currentTimeMillis()+DELAY); ghostController.update(game.copy(),System.currentTimeMillis()+DELAY); try { int waited=DELAY/INTERVAL_WAIT; for(int j=0;j<DELAY/INTERVAL_WAIT;j++) { Thread.sleep(INTERVAL_WAIT); if(pacManController.hasComputed() && ghostController.hasComputed()) { waited=j; break; } } if(fixedTime) Thread.sleep(((DELAY/INTERVAL_WAIT)-waited)*INTERVAL_WAIT); game.advanceGame(pacManController.getMove(),ghostController.getMove()); } catch(InterruptedException e) { e.printStackTrace(); } if(visual) gv.repaint(); } pacManController.terminate(); ghostController.terminate(); }
9
public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getName() != null) { _hashCode += getName().hashCode(); } if (getCurrency() != null) { _hashCode += getCurrency().hashCode(); } if (getAmount() != null) { _hashCode += getAmount().hashCode(); } __hashCodeCalc = false; return _hashCode; }
4
public DateFormat getTimeFormat() { return timeFormat; }
0
public static boolean checkForClick(int button){ while(Mouse.next()){ if(Mouse.getEventButtonState()){ if(Mouse.getEventButton() == button) return true; } } return false; }
3
public static List readWatchableObjects(DataInputStream par0DataInputStream) throws IOException { ArrayList arraylist = null; for (byte byte0 = par0DataInputStream.readByte(); byte0 != 127; byte0 = par0DataInputStream.readByte()) { if (arraylist == null) { arraylist = new ArrayList(); } int i = (byte0 & 0xe0) >> 5; int j = byte0 & 0x1f; WatchableObject watchableobject = null; switch (i) { case 0: watchableobject = new WatchableObject(i, j, Byte.valueOf(par0DataInputStream.readByte())); break; case 1: watchableobject = new WatchableObject(i, j, Short.valueOf(par0DataInputStream.readShort())); break; case 2: watchableobject = new WatchableObject(i, j, Integer.valueOf(par0DataInputStream.readInt())); break; case 3: watchableobject = new WatchableObject(i, j, Float.valueOf(par0DataInputStream.readFloat())); break; case 4: watchableobject = new WatchableObject(i, j, Packet.readString(par0DataInputStream, 64)); break; case 5: short word0 = par0DataInputStream.readShort(); byte byte1 = par0DataInputStream.readByte(); short word1 = par0DataInputStream.readShort(); watchableobject = new WatchableObject(i, j, new ItemStack(word0, byte1, word1)); break; case 6: int k = par0DataInputStream.readInt(); int l = par0DataInputStream.readInt(); int i1 = par0DataInputStream.readInt(); watchableobject = new WatchableObject(i, j, new ChunkCoordinates(k, l, i1)); break; } arraylist.add(watchableobject); } return arraylist; }
9
public void falling() { if(!isBlocked(x, y + velY + 1f)){ timer += delta; if(velY < 16){ if(timer > 100){ velY = velY += 1f; timer = 0; } } mapY += velY; isOnGround = false; }else if(velY < 16){ velY = 0; isOnGround = true; }else{ velY = 0; isOnGround = true; isDead = true; causeOfDeath = "You fell too fast"; } }
4
@Override public boolean addGroup(String group) { if (groups.contains(group)) { return false; } return groups.add(group); }
1
public static int sqrt(int x) { if (0 == x) return 0; long bit = 1l << 16; long res = 0; while (bit != 0) { res = res | bit; if (res * res > x) res = res ^ bit; bit = bit >> 1; } return (int) res; }
3
public void Run() { // Рестарт при повторном вызове. Зарпет на две копии одного скрипта при // одновременном выполнии if (isScriptRunning()) { Stop(); } Update(); scrThread = new JSThread(this) { @Override public void OnStart() { super.OnStart(); AddStopMenuElement(); } @Override public void OnStop() { super.OnStop(); RemoveStopMenuElement(); } }; scrThread.start(); }
1
public void mouseDown(org.eclipse.swt.events.MouseEvent e) { // TODO Auto-generated method stub if (e.getSource() == buttonOk) { String host = comboHost.getText(); String user = comboUser.getText(); String password = textPassword.getText(); // String protocol = comboProtocol.getText(); Protocol protocol = Protocol.values()[comboProtocol.getSelectionIndex()]; String file = textkey.getText().trim(); ConfigSession session = new ConfigSession(host, "22", user, protocol,file, password); if (!host.trim().equals("") && !user.trim().equals("") && !protocol.equals("")) { dialog.dispose(); MainFrame.dbm.insertCSession(session); if (sessionDialog != null) sessionDialog.loadTable(); if (mainFrame != null) mainFrame.addSession(null, session); } else { MessageDialog.openInformation(dialog, "Warning", "Must set Host, User and Protocol"); } } else if (e.getSource() == buttonCancel) { dialog.dispose(); } else if (e.getSource() == buttonFile) { FileDialog fileDlg = new FileDialog(dialog, SWT.OPEN); fileDlg.setText("Select SSH key"); String filePath = fileDlg.open(); if (null != filePath) { textkey.setText(filePath); } } }
9
@BeforeClass public static void setUp() { bmTestManager = BmTestManager.getInstance(); plan = new Plan("HV40KOD", 40000, 40, true, 1000, 0); users = new Users("1689", "dzmitrykashlach", "dzmitry.kashlach@blazemeter.com", "1394008114", "1392730300", "1324748306", true, plan, null); bmTestManager.setUsers(users); String str = Utils.getFileContents(LOCATIONS); JSONArray locations = null; try { locations = new JSONArray(str); } catch (JSONException e) { BmLog.error("Failed to construct LOCATIONS from locations.txt: " + e); } users.setLocations(locations); }
1
@Override protected void controlUpdate(float tpf) { if(GameStarted.gameStart){ if(!init){ if(comboNumber == 1){ // currentComboNo = animationToInt(((Node)spatial.getParent().getChild("Model")).getChild("Player1").getControl(ComboSetupControl.class).getCombo1_1()); currentComboNo = animationToInt(StoredInfo.combo1_1); }else if(comboNumber == 2){ currentComboNo = animationToInt(StoredInfo.combo2_1); }else if(comboNumber == 3){ currentComboNo = animationToInt(StoredInfo.combo3_1); }else if(comboNumber == 4){ currentComboNo = animationToInt(StoredInfo.combo4_1); }else if(comboNumber == 5){ currentComboNo = animationToInt(StoredInfo.combo5_1); }else if(comboNumber == 6){ currentComboNo = animationToInt(StoredInfo.combo6_1); } spatial.getControl(LabelControl.class).changeText(comboList()); init = true; } checkMoveAvailability(); } }
8
static int checkAck(InputStream in) throws IOException { int b = in.read(); // b may be 0 for success, // 1 for error, // 2 for fatal error, // -1 if (b == 0) return b; if (b == -1) return b; if (b == 1 || b == 2) { StringBuffer sb = new StringBuffer(); int c; do { c = in.read(); sb.append((char) c); } while (c != '\n'); if (b == 1) { // error System.out.print(sb.toString()); } if (b == 2) { // fatal error System.out.print(sb.toString()); } } return b; }
7
public void init() { if (CollectionUtils.isEmpty(messageConverters)) { StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(); stringHttpMessageConverter.setWriteAcceptCharset(false); // See SPR-7316 this.messageConverters = new ArrayList<HttpMessageConverter<?>>(); this.messageConverters.add(new MappingJacksonHttpMessageConverter()); this.messageConverters.add(stringHttpMessageConverter); this.messageConverters.add(new SourceHttpMessageConverter()); this.messageConverters.add(new XmlAwareFormHttpMessageConverter()); } }
2