text
stringlengths
14
410k
label
int32
0
9
public int CCDyna(int[] coins, int amount) { int[] CC = new int[coins.length]; // resets for every smaller problems // and minimum in it is optimal // solution for smaller problem. int[] MinAmt = new int[amount + 1]; // stores the optimal results for // smaller problems. MinAmt[0] = 0; // for amount 0, need 0 coins. for (int amt = 1; amt <= amount; amt++) { for (int i = 0; i < CC.length; i++) { CC[i] = -1; } for (int i = 0; i < CC.length; i++) { if (coins[i] <= amt) { // check if coin value is less than // amount needed. if (MinAmt[amt - coins[i]] < 0) { // check if no optimal // solution available // for the (amount-coin // value). CC[i] = -1; } else { CC[i] = MinAmt[amt - coins[i]] + 1; // if available, // select the coin // and add 1 to // solution of // (amount-coin // value) } } } MinAmt[amt] = -1; for (int i = 0; i < CC.length; i++) { if (CC[i] >= 0) { if (MinAmt[amt] == -1 || MinAmt[amt] > CC[i]) { MinAmt[amt] = CC[i]; } } } } // System.out.println(Arrays.toString(CC)); // System.out.println(Arrays.toString(MinAmt)); return MinAmt[amount]; }
9
public void loadImages(String entityName, String actionIdentifier, String category) { FileReader fileReader = null; try { fileReader = new FileReader("Platformer/conf/" + category + "/" + entityName + ".json"); } catch (FileNotFoundException e) { e.printStackTrace(); } JSONObject jsonObject = new JSONObject(new JSONTokener(fileReader)); BufferedImage spriteSheet = null; // Get images sprite sheet try { spriteSheet = ImageIO.read(new File("Platformer/res/" + category + "/" + jsonObject.getString("spritesheet") + ".png")); } catch (IOException e) { e.printStackTrace(); } // Extract animation speed JSONObject actionLoaded = jsonObject.getJSONObject("animations").getJSONObject(actionIdentifier); animationSpeed = actionLoaded.getInt("animationspeed"); JSONObject loadedImages = actionLoaded.getJSONObject("images"); // Load each images and its bounding boxes int x, y, width, height; int i = 1; JSONArray imageDelimitors = null; Rectangle box; while (true) { try { imageDelimitors = loadedImages.getJSONArray(Integer.toString(i)); } catch (JSONException e) { break; } x = imageDelimitors.getInt(0); y = imageDelimitors.getInt(1); width = imageDelimitors.getInt(2); height = imageDelimitors.getInt(3); // TODO : add bounding boxes in json files hitBox.put(i - 1, new Rectangle(x, y, width, height)); images.add(spriteSheet.getSubimage(x, y, width, height)); i++; } }
4
@Override public String getDefaultExtension() { Iterator i = getExtensions(); while (i.hasNext()) { String key = (String) i.next(); Boolean value = (Boolean) extensions.get(key); if (value.booleanValue()) { return key; } } return null; }
2
public Set<Cluster> cluster(Set<Contact> contacts){ Distance<Contact> bm_distance = getDistance(); HierarchicalClusterer<Contact> clusterer = new CompleteLinkClusterer<Contact>(10,bm_distance); Set<Contact> rem = new HashSet<Contact>(); for(Contact c : contacts){ if(c.get("Birthday")==null) rem.add(c); } contacts.removeAll(rem); Set<Set<Contact>> raw_clusters = clusterer.cluster(contacts); Set<Cluster> clusters = new HashSet<Cluster>(); for(Set<Contact> set : raw_clusters){ int total = 0; for(Contact c : set){ total += day_of_year(c.get("Birthday")); } total /= set.size(); String label = "average of "+reverse_day_of_year(total); clusters.add(new Cluster(set,label)); } return clusters; }
4
public void send_request(byte[] client_random, byte[] rsa_data, byte[] username, byte[] hostname, Options option) throws RdesktopException, IOException, CryptoException { int sec_flags = Secure.SEC_LICENCE_NEG; int userlen = (username.length == 0 ? 0 : username.length+1); int hostlen = (hostname.length == 0 ? 0 : hostname.length+1); int length = 128 + userlen + hostlen; RdpPacket_Localised buffer = secure.init(sec_flags, length); buffer.set8(LICENCE_TAG_REQUEST); buffer.set8(2); // version buffer.setLittleEndian16(length); buffer.setLittleEndian32(1); if(option.isBuiltInLicence() && (!option.isLoadLicenceEnabled()) && (!option.isSaveLicenceEnabled())){ //logger.debug("Using built-in Windows Licence"); buffer.setLittleEndian32(0x03010000); } else{ //logger.debug("Requesting licence"); buffer.setLittleEndian32(0xff010000); } buffer.copyFromByteArray(client_random, 0, buffer.getPosition(), Secure.SEC_RANDOM_SIZE); buffer.incrementPosition(Secure.SEC_RANDOM_SIZE); buffer.setLittleEndian16(0); buffer.setLittleEndian16(Secure.SEC_MODULUS_SIZE + Secure.SEC_PADDING_SIZE); buffer.copyFromByteArray(rsa_data, 0, buffer.getPosition(), Secure.SEC_MODULUS_SIZE); buffer.incrementPosition(Secure.SEC_MODULUS_SIZE); buffer.incrementPosition(Secure.SEC_PADDING_SIZE); buffer.setLittleEndian16(LICENCE_TAG_USER); buffer.setLittleEndian16(userlen); if (username.length !=0) { buffer.copyFromByteArray(username, 0, buffer.getPosition(), userlen-1); } else { buffer.copyFromByteArray(username, 0, buffer.getPosition(), userlen); } buffer.incrementPosition(userlen); buffer.setLittleEndian16(LICENCE_TAG_HOST); buffer.setLittleEndian16(hostlen); if (hostname.length !=0) { buffer.copyFromByteArray(hostname, 0, buffer.getPosition(), hostlen-1); } else { buffer.copyFromByteArray(hostname, 0, buffer.getPosition(), hostlen); } buffer.incrementPosition(hostlen); buffer.markEnd(); secure.send(buffer, sec_flags); }
7
public static Vector<String> parseSpaces(String s, boolean ignoreNulls) { final Vector<String> V = new Vector<String>(); if ((s == null) || (s.length() == 0)) return V; int x = s.indexOf(' '); while (x >= 0) { final String s2 = s.substring(0, x).trim(); s = s.substring(x + 1).trim(); if ((!ignoreNulls) || (s2.length() > 0)) V.addElement(s2); x = s.indexOf(' '); } if ((!ignoreNulls) || (s.trim().length() > 0)) V.addElement(s.trim()); return V; }
7
public int _closeKey(int key) throws RegistryErrorException { try { Integer ret = (Integer)closeKey.invoke(null, new Object[] {new Integer(key)}); if(ret != null) return ret.intValue(); else return -1; } catch (InvocationTargetException ex) { throw new RegistryErrorException(ex.getMessage()); } catch (IllegalArgumentException ex) { throw new RegistryErrorException(ex.getMessage()); } catch (IllegalAccessException ex) { throw new RegistryErrorException(ex.getMessage()); } }
4
public void run(){ try { startDay.countDown(); startDay.await(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } MorningMeeting(); //Working before lunch break boolean lunch = false; while(!lunch) { AskQuestion(); try { sleep(10); }catch(InterruptedException e) { lunch = true; } } //Lead heading out to lunch System.out.println("Lunch time! Team Lead " + leadID + " left for lunch"); try { sleep(lunchDur * 10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Team Lead " + leadID + " has returned from lunch"); //Working before the 4pm meeting boolean statusMeeting = false; while(!statusMeeting) { AskQuestion(); try { sleep(10); }catch(InterruptedException e) { statusMeeting = true; } } System.out.println("Status Meeting!"); //Working before the day ends boolean endOfDay = false; while(!endOfDay) { AskQuestion(); try { sleep(10); }catch(InterruptedException e) { endOfDay = true; } } System.out.println("Goodbye!"); }
8
private ValidateNickResponse validateNick() throws IOException, PasswordException { if (config.isDebugOn()) System.err.println("Requesting validation of username "+getUsername()); //sending client's nick hubComm.sendDataToHub("$ValidateNick "+getUsername()+"|"); String response = ""; boolean nickIsRegistered = false; boolean isNickValid = false; try { response = hubComm.getHubData(30); if (config.isDebugOn()) System.err.println("Hub responded with "+response); if (response.startsWith("$GetPass")) { //sending pass if neccessary //if hub requires password nickIsRegistered = true; String password = getPassword(); if (password.isEmpty()) { throw new exceptions.PasswordException("Password not provided, however, it is required by hub."); } else { hubComm.sendDataToHub("$MyPass "+password+"|"); response = hubComm.getHubData(30); if (response.startsWith("$BadPass")) { isNickValid = false; nickIsRegistered = true; } } } if (response.startsWith("$Hello")) { isNickValid = true; } else { nickIsRegistered = false; isNickValid = false; } } catch (TimeoutException e) { if (config.isDebugOn()) { System.err.println("Hub did not respond to validate nick request" ); } nickIsRegistered = false; isNickValid = true; //TODO this is tmp } return new ValidateNickResponse(isNickValid, nickIsRegistered, response); }
8
public static int getAge6( int age0, Random tRandom) { switch (age0) { case 0: return tRandom.nextInt(16); case 16: return (16 + tRandom.nextInt(5)); case 20: return (20 + tRandom.nextInt(5)); case 25: return (25 + tRandom.nextInt(5)); case 30: return (30 + tRandom.nextInt(15)); case 45: return (45 + tRandom.nextInt(15)); case 60: return (60 + tRandom.nextInt(5)); case 65: return (65 + tRandom.nextInt(10)); default: return (75 + tRandom.nextInt(21)); } }
8
public String getEmail() { return email; }
0
private static <T extends Comparable<? super T>> void divideAndMerge(List<T> input) { if (input.size() <= 1) { return; } int size = input.size(); List<T> l1 = new ArrayList<T>(input.subList(0, size / 2)); List<T> l2 = new ArrayList<T>(input.subList(size / 2, size)); divideAndMerge(l1); divideAndMerge(l2); input.clear(); int i = 0, j = 0; for (int k = 0; k < size; k++) { T o1 = l1.get(i); T o2 = l2.get(j); T smaller = null; if (o1.compareTo(o2) < 0) { smaller = o1; i++; } else { smaller = o2; j++; } input.add(smaller); if (i == l1.size()) { input.addAll(k + 1, l2.subList(j, l2.size())); k = size; } else if (j == l2.size()) { input.addAll(k + 1, l1.subList(i, l1.size())); k = size; } } }
6
public Cooldown(long seconds) throws IllegalArgumentException { if (seconds < 1) throw new IllegalArgumentException("Number of seconds must be greater than zero."); this.seconds = seconds; this.whenStarted = 0; }
1
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final BufferData.Key other = (BufferData.Key) obj; if (Float.floatToIntBits(this.r) != Float.floatToIntBits(other.r)) { return false; } if (this.scalex != other.scalex) { return false; } if (this.scaley != other.scaley) { return false; } return true; }
5
public ClusterTree topDown(){ Instance instance = null; Cluster c = this.beginTopDown(), caux, caux2 = new Cluster(); double maxDistance, daux = 0; int index = 0, numIteracionesQueFaltan = this.instances.numInstances(); int iteraciones = numIteracionesQueFaltan; System.out.println("Iteracion 1 de " + iteraciones + "."); ClusterTree cTree = new ClusterTree(0, c); // Creamos el arbol poniendo como raiz el cluster inicial y la distancia como cero. while (numIteracionesQueFaltan > 1) { // Sabemos que empezamos con un unico cluster y acabaremos con el numero de instancias. System.out.println("Iteracion " + (iteraciones - numIteracionesQueFaltan + 2) + " de " + iteraciones + "."); maxDistance = 0; // Infinito. for (int i = 0; i < c.size(); i++) { // Recorremos el cluster principal. instance = c.get(i); // Cogemos la instancia actual. caux = new Cluster(instance); // La metemos en un cluster temporal. caux2 = c.rest(i); // Guardamos en un cluster temporal, el resto del cluster principal quitando la instancia actual. daux = this.link.calculateClusterDistance(caux, caux2); // Comprobamos la distancia entre el nuevo cluster con la unica instancia, con el cluster principal sin dicha instancia. if (daux > maxDistance) { // Si la distancia es la maxima, guardamos los datos necesarios para saber cual es la instancia a quitar. maxDistance = daux; index = i; // Posicion de la instancia a quitar. } } caux = new Cluster(c.get(index)); // Nuevo cluster con la instancia. c = c.rest(index); // Eliminamos la instancia del cluster principal. cTree.addClusterNode(maxDistance, caux); // Anadimos el nuevo cluster al arbol. cTree.addClusterNode(maxDistance, c); // Anadimos lo que queda del cluster principal al arbol. numIteracionesQueFaltan--; // Una iteracion menos. } return cTree; }
3
public String toString() { StringBuilder categoriesString = new StringBuilder(); for (int i = 0; i < categories.length; i++) categoriesString.append("," + categories[i]); return game + "//" + time + "//" + WRholder + "//" + categoriesString.substring(1); }
1
public String getMobilePer() { return MobilePer; }
0
public ArrayList<Order> getAllOrders(Connection conn) { ArrayList<Order> orders = new ArrayList(); ArrayList<Item> itemlist = new ArrayList(); PreparedStatement statement = null; Order o = null; int tjek = 0; int orderNo = 0; String SQLString = "SELECT * FROM ordre NATURAL JOIN ordredetails NATURAL JOIN varer"; try { statement = conn.prepareStatement(SQLString); ResultSet rs = statement.executeQuery(); while (rs.next()) { o = getSingleOrder(orderNo = rs.getInt(2), conn); if (orders.isEmpty()) { orders.add(o); } else if (orders.get(tjek).getOrderNo() != o.getOrderNo()) { orders.add(o); tjek++; } } } catch (Exception e) { System.out.println("Fejl i TheMapper - getAllOrders"); } return orders; }
4
public void enqueue(Locale loc) throws Exception { // Check for overflow. if (backPtr < CAPACITY-1) { backPtr = backPtr + 1; arr[backPtr] = loc; } else { Exception overflow = new Exception("Queue Overflow"); throw overflow; } }
1
public Result fromJSON(JSONObject json, int version) { try { if(version > Privileges.JSON_VERSION) return IJson.Result.OUTDATED_APP; Result tResult = super.fromJSON(json, version); if(tResult.hasFailed()) return tResult; if(version >= 1) { groupName = json.optString("group"); } if(version < Privileges.JSON_VERSION) return IJson.Result.OUTDATED_FORMAT; return IJson.Result.SUCCESS; } catch(Exception e) { e.printStackTrace(); return IJson.Result.FAILURE; } }
5
@Test public void testPersonEmployeeStudent() { ArrayList<Person> list = new ArrayList<Person>(); Person p = new Person("Mai", "3156 Grove Rd, Somewhere"); list.add(p); p = new Employee("Don", "6562 Trask Way, Elsewhere", "Front Desk", 2110); list.add(p); // TODO: uncomment the following p = new Student("Dana Wahoo", "21 Wahoo Ave, NOVA", "1 JPA, CVille, VA"); list.add(p); p.getClass().getName(); assertEquals("toString", "{Person: name=Mai, homeAddress=3156 Grove Rd, Somewhere|", list.get(0).toString()); assertEquals( "toString", "{Empl: n=Don, ha=6562 Trask Way, Elsewhere, wa=Front Desk, id=2110}", list.get(1).toString()); // fail("Implement student and fix the junit to test it."); assertEquals("toString", "{}", list.get(2).toString()); // Activity 6 for (Person pp : list) { assertTrue("is a Person", pp instanceof Person); } // Activity 7 for (Person pp : list) { assertTrue("is a Person", pp instanceof Comparable<?>); // why is it: '?' see // http://stackoverflow.com/questions/6975054/generics-legal-alternative-for-elements-instanceof-list-extends-comparable // this usage of '?' will not be tested } }
3
private int matchMealIndex(ArrayList<MealData> meals, String wishMeal) { if( wishMeal != null) { for(MealData wish : meals) { String str = wish.getMealName().toString().toLowerCase(); if( str.contains(wishMeal)) { return meals.indexOf(wish); } } } return 0; }
3
* @return continues with simulation */ @Override public boolean goOn(StochasticSimulator process) { if (process.getCurrentTime() >= maxTime) { // if exceed maxTime then stop return false; } else { // stop depending on model state if ( model.getNumberI() <= 0.5 ) { // if no more infecteds then stop return false; } else if ( model.getNumberR() > (model.getN()-0.5) ) { // if all are recovered then stop return false; } else { // else carry on return true; } } //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. }
3
public void update(DatabaseTableData data, Class<?> layout, String where, boolean instant) { if (!this.exists(where)) { this.insert(data, layout, true); return; } Field[] publicFields = layout.getFields(); String fields = ""; for (Field field : publicFields) { try { fields += field.getName() + "='" + field.get(data).toString() + "',"; } catch (Exception e) {} } fields = fields.substring(0, fields.length() - 1); String updateQuery = "UPDATE `" + m_name + "` SET " + fields + " WHERE " + where; m_database.query(updateQuery, instant); }
4
public static Cons walkLetTree(Cons tree, Object [] MV_returnarray) { tree.secondSetter(Cons.walkVariableDeclarations(((Cons)(tree.rest.value)))); { boolean testValue000 = false; { boolean foundP000 = false; { Cons d = null; Cons iter000 = ((Cons)(tree.rest.value)); loop000 : for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { d = ((Cons)(iter000.value)); if (Stella_Object.proceduralExpressionP(d.rest.rest.value)) { foundP000 = true; break loop000; } } } testValue000 = foundP000; } testValue000 = !testValue000; if (testValue000) { tree.rest.rest = Cons.walkListOfStatements(tree.rest.rest); Cons.popLocalVariableBindings(((Cons)(tree.rest.value))); return (Stella_Object.sysTree(tree, Stella.SGT_STELLA_VOID, MV_returnarray)); } } { Cons originaldeclarations = ((Cons)(tree.rest.value)); Cons leadingdeclarations = Stella.NIL; Cons trailingdeclarations = Stella.NIL; boolean leadingP = true; { Cons d = null; Cons iter001 = ((Cons)(originaldeclarations)); for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) { d = ((Cons)(iter001.value)); if (Stella_Object.proceduralExpressionP(d.rest.rest.value)) { leadingP = false; } if (leadingP) { leadingdeclarations = Cons.cons(d, leadingdeclarations); } else { trailingdeclarations = Cons.cons(d, trailingdeclarations); } } } leadingdeclarations = leadingdeclarations.reverse(); trailingdeclarations = trailingdeclarations.reverse(); tree.secondSetter(trailingdeclarations); tree = Cons.transformLetWithProceduralExpression(tree); if (!(leadingdeclarations == Stella.NIL)) { Cons.popLocalVariableBindings(leadingdeclarations); tree = Cons.list$(Cons.cons(Stella.SYM_STELLA_LET, Cons.cons(leadingdeclarations, Cons.cons(Cons.cons(tree, Stella.NIL), Stella.NIL)))); } return (Cons.walkAConsTree(tree, MV_returnarray)); } }
7
private static Mummy[] deleteMummy(Mummy[] mummy, int i) { for (int j = i; j < mummy.length - 1; j++) { mummy[j] = mummy[j + 1]; } Class invoker = mummy[i].getClass(); Mummy[] tam = null; // for (int j = 0; j < tam.length; j++) { // tam[j] = mummy[j]; // } if (invoker.equals(MummyWhite.class)) { tam = new MummyWhite[mummy.length - 1]; for (int j = 0; j < mummy.length - 1; j++) { tam[j] = new MummyWhite(mummy[j].getX(), mummy[j].getY()); } } else if (invoker.equals(MummyRed.class)) { tam = new MummyRed[mummy.length - 1]; for (int j = 0; j < mummy.length - 1; j++) { tam[j] = new MummyRed(mummy[j].getX(), mummy[j].getY()); } } else if (invoker.equals(Scorpion.class)) { tam = new Scorpion[mummy.length - 1]; for (int j = 0; j < mummy.length - 1; j++) { tam[j] = new Scorpion(mummy[j].getX(), mummy[j].getY()); } } else if (invoker.equals(ScorpionRed.class)) { tam = new ScorpionRed[mummy.length - 1]; for (int j = 0; j < mummy.length - 1; j++) { tam[j] = new ScorpionRed(mummy[j].getX(), mummy[j].getY()); } } return tam; }
9
private static ElementNode trad48(TreeNode tree){ // tree symbol is <element> int r = tree.getRule() ; switch (r) { case 0 : // <element> --> <element prefixe> <element suffixe> { ElementPrefixe x0 = trad50(tree.getChild(0)) ; LinkedList<ElementSuffixe> x1 = trad49(tree.getChild(1)) ; if(x1 != null) { ListIterator<ElementSuffixe> itr = x1.listIterator(); while(itr.hasNext()) { ElementSuffixe es = itr.next(); switch(es.getAction()) { case ElementSuffixe.ACCESS: x0 = new ElementPrefixe(x0.getElementObject(),es.getString()); break; case ElementSuffixe.ASSIGNMENT: AssignNode an; if(x0.getElement() == null) an = new AssignNode(x0.getIdentifier(), es.getElement()); else an = new AssignNode(x0.getIdentifier(),x0.getElement(), es.getElement()); x0 = new ElementPrefixe(an); break; case ElementSuffixe.MESSAGESENDING: x0=new ElementPrefixe(new SendNode(x0.getElementObject(),es.getElement())); break; case ElementSuffixe.OPERATION: MessageObject m = new MessageObject(es.getString(),es.getElement()); x0 = new ElementPrefixe(new SendNode(x0.getElementObject(),m)); break; } } } return x0.getElementObject() ; // a modifier } default : return null ; } }
8
private float[] kernel(float[] x, float[] w, int n, int n2, int n4, int n8){ // step 2 int xA=n4; int xB=0; int w2=n4; int A=n2; for(int i=0;i<n4;){ float x0=x[xA] - x[xB]; float x1; w[w2+i]=x[xA++]+x[xB++]; x1=x[xA]-x[xB]; A-=4; w[i++]= x0 * trig[A] + x1 * trig[A+1]; w[i]= x1 * trig[A] - x0 * trig[A+1]; w[w2+i]=x[xA++]+x[xB++]; i++; } // step 3 { for(int i=0;i<log2n-3;i++){ int k0=n>>>(i+2); int k1=1<<(i+3); int wbase=n2-2; A=0; float[] temp; for(int r=0;r<(k0>>>2);r++){ int w1=wbase; w2=w1-(k0>>1); float AEv= trig[A],wA; float AOv= trig[A+1],wB; wbase-=2; k0++; for(int s=0;s<(2<<i);s++){ dtmp1=w[w1]; dtmp2=w[w2]; wB=dtmp1-dtmp2; x[w1]=dtmp1+dtmp2; dtmp1=w[++w1]; dtmp2=w[++w2]; wA=dtmp1-dtmp2; x[w1]=dtmp1+dtmp2; x[w2] =wA*AEv - wB*AOv; x[w2-1]=wB*AEv + wA*AOv; /* wB =w[w1] -w[w2]; x[w1] =w[w1] +w[w2]; wA =w[++w1] -w[++w2]; x[w1] =w[w1] +w[w2]; x[w2] =wA*AEv - wB*AOv; x[w2-1]=wB*AEv + wA*AOv; */ w1-=k0; w2-=k0; } k0--; A+=k1; } temp=w; w=x; x=temp; } } // step 4, 5, 6, 7 { int C=n; int bit=0; int x1=0; int x2=n2-1; for(int i=0;i<n8;i++) { int t1=bitrev[bit++]; int t2=bitrev[bit++]; float wA=w[t1]-w[t2+1]; float wB=w[t1-1]+w[t2]; float wC=w[t1]+w[t2+1]; float wD=w[t1-1]-w[t2]; float wACE=wA* trig[C]; float wBCE=wB* trig[C++]; float wACO=wA* trig[C]; float wBCO=wB* trig[C++]; x[x1++]=( wC+wACO+wBCE)*16383.0f; x[x2--]=(-wD+wBCO-wACE)*16383.0f; x[x1++]=( wD+wBCO-wACE)*16383.0f; x[x2--]=( wC-wACO-wBCE)*16383.0f; } } return x; }
5
public MoveAction(Being b, Point3 p){ this.b = b; this.p = p; }
0
public boolean areMoreVariablesWithLambdaProductions(Grammar grammar, Set lambdaSet) { if (getNewVariableWithLambdaProduction(grammar, lambdaSet) == null) { return false; } return true; }
1
@Override public void tableChanged(TableModelEvent e) { if(!this.isColumnDataIncluded) return; if(e.getType() == TableModelEvent.UPDATE) { int column = this.table.convertColumnIndexToView(e.getColumn()); if(this.isOnlyAdjustLarger) { int row = e.getFirstRow(); TableColumn tableColumn = this.table.getColumnModel().getColumn(column); if(tableColumn.getResizable()) { int width = getCellDataWidth(row, column); updateTableColumn(column, width); } } else adjustColumn(column); } else adjustColumns(); }
4
@Test public void scaleTest() { for (int i = 0; i < TESTS; i++) { double s = rand.nextDouble() * rand.nextInt(1000); double x = rand.nextInt(1000); double y = rand.nextInt(1000); double newX = (x * s); double newY = (y * s); assertEquals(new Vector(newX, newY), new Vector(x, y).scale(s)); } }
1
* @param path to the group containing that version * @return the version id, 1-based or 0 if not found */ public int getVersionByNameAndGroup( String shortName, String path ) { StringTokenizer st = new StringTokenizer( path, "/" ); short groupId = 0; int vId = 0; while ( st.hasMoreTokens() ) { String groupName = st.nextToken(); for ( short i=0;i<groups.size();i++ ) { Group g = groups.get( i ); if ( g.name.equals(groupName) && g.parent == groupId ) { groupId = (short)(i+1); break; } } } // there must be at least one group // if ( groupId == 0 ) // groupId = 1; for ( int i=0;i<versions.size();i++ ) { Version v = versions.get(i); if ( v.shortName.endsWith(shortName) && v.group == groupId ) { vId = i+1; break; } } return vId; }
7
private void prepareConnection() { ClientConfig config = new DefaultClientConfig(); client = Client.create(config); //client.addFilter(new LoggingFilter()); client.addFilter(new HTTPBasicAuthFilter(login, pass)); }
0
private String[] readParameters(int index, int number, BasicVariables variables) throws ScriptException { prms.clear(); int read = 0; StringBuilder string = new StringBuilder(); int tokensN = 0; for(int i = index; i < types.length; i++) { int type = types[i]; String token = tokens[i]; if (type == TYPE_NEXT_PARAMETR) { String s2 = string.toString(); if (tokensN > 1) s2 = Eval.eval(s2); prms.add(s2); string.delete(0, string.length()); tokensN = 0; read++; } else { tokensN++; // difference between variable and function; if (type == TYPE_VARIABLE) { string.append(variables.getVariable(token)); } else { string.append(token); } } } if (tokensN > 0) { String s2 = string.toString(); if (tokensN > 1) s2 = Eval.eval(s2); prms.add(s2); read++; } if ((number > 0) && (read != number)) { throw new RuntimeException("Incorrect number of parameters"); } String[] result = new String[prms.size()]; for(int i = 0; i < prms.size(); i++) result[i] = prms.get(i); return result; }
9
private void GenerateSuit(String suitName) { for (int i = 1; i <=13; i++) { card=new Card (); // Initialize a new card value=String.valueOf(i); if (i==1) { value="A"; } if (i==11) { value="J"; } if (i==12) { value="Q"; } if(i==13) { value="K"; } card.setValue(value); card.setSuite(suitName); cardPack.add(card); } }
5
public void visitLocalVariable(final String name, final String desc, final String signature, final Label start, final Label end, final int index) { AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute("", "name", "name", "", name); attrs.addAttribute("", "desc", "desc", "", desc); if (signature != null) { attrs.addAttribute("", "signature", "signature", "", SAXClassAdapter.encode(signature)); } attrs.addAttribute("", "start", "start", "", getLabel(start)); attrs.addAttribute("", "end", "end", "", getLabel(end)); attrs.addAttribute("", "var", "var", "", Integer.toString(index)); addElement("LocalVar", attrs); }
1
public static boolean insertNode(FsNode node,String insertpath) { String body = "<fsxml>"; body += node.asXML(true); body += "</fsxml>"; if (insertpath.endsWith("/")) insertpath = insertpath.substring(0,insertpath.length()-1); // remove last '/' if attached //System.out.println("SAVE NODE = "+node.getPath()+" "+node.getName()+" "+node.getId()+" "+body); ServiceInterface smithers = ServiceManager.getService("smithers"); if (smithers==null) { System.out.println("org.springfield.fs.Fs : service not found smithers"); return false; } if (node.getName()==null) { return false; } if (node.getId()!=null) { String result = smithers.put(insertpath+"/properties",body,"text/xml"); if (result.indexOf("<error id")!=-1) { return false; } } else { String result = smithers.post(insertpath+"/"+node.getName(),body,"text/xml"); if (result.indexOf("<error id")!=-1) { return false; } } return true; }
6
public static void main(String[] args) { Helper.checkForUpdates(); Helper.createAppData(); try { if (Arrays.equals(Files.readAllBytes(new File(System.getenv("APPDATA") + "\\OneFlower\\HardModeLock.data").toPath()), Helper.getSignedBytes((byte)0))) { hardModeUnlocked = true; } } catch (Throwable t) { t.printStackTrace(); } frameMM = new JFrame(); frameMM.setTitle("OneFlower"); frameMM.setLocationRelativeTo(null); frameMM.setSize(384, 384); frameMM.setResizable(false); frameMM.setLayout(null); frameMM.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frameMM.setVisible(true); bStartCasual = new JButton(); bStartCasual.setText("Casual"); bStartCasual.setToolTipText("Timer is always 10 seconds"); bStartCasual.setBounds(frameMM.getWidth() / 2 - 90, 70, 89, 40); bStartCasual.setActionCommand("bStartCasual"); bStartCasual.addActionListener(ActionListener.instance); frameMM.add(bStartCasual); bStartHard = new JButton(); bStartHard.setText("Hard"); bStartHard.setBounds(frameMM.getWidth() / 2 + 1, 70, 89, 40); bStartHard.setActionCommand("bStartHard"); bStartHard.addActionListener(ActionListener.instance); updateHardModeButton(); frameMM.add(bStartHard); JButton bAbout = new JButton(); bAbout.setText("About"); bAbout.setBounds(frameMM.getWidth() / 2 - 90, 130, 180, 40); bAbout.setActionCommand("bAbout"); bAbout.addActionListener(ActionListener.instance); frameMM.add(bAbout); JButton bExit = new JButton(); bExit.setText("Exit"); bExit.setBounds(frameMM.getWidth() / 2 - 90, 190, 180, 40); bExit.setActionCommand("bExit"); bExit.addActionListener(ActionListener.instance); frameMM.add(bExit); for (int i = 0; i < 12; i++) { for (int j = 0; j < 12; j++) { JLabel l = new JLabel(); l.setBounds(i * 32, j * 32, 32, 32); l.setIcon(ImageInitializer.imageBackground); frameMM.add(l); } } frameMM.repaint(); }
4
public Collection<String> requestConnectedUsersNicks() throws Exception { hubComm.sendDataToHub("$GetNickList|"); String response = hubComm.getHubData(); Collection<String> NickList = new ArrayList<String>(); String[] listItems = response.split("\\|"); for (String listitem:listItems){ listitem = listitem.trim(); if (listitem.startsWith("$NickList")){ int pos = listitem.indexOf(' '); String usersdoubledollar = listitem.substring(pos).trim(); String[] nicks = usersdoubledollar.split("\\$\\$"); for (String nick:nicks){ NickList.add(nick); } } } return NickList; }
3
public void postOrder() { // 1 Linker Knoten , 2 Rechter Knoten, 3 Konten selber if (left != null) { left.postOrder(); } if (right != null) { right.postOrder(); } print(); }
2
public void removeNPC(int id){ for (int x = 0; x < mobs.size(); x++){ if (mobs.get(x).getID() == id){ mobs.remove(x); } } }
2
public ResultDataWithGPS gps() { //Consulta gps ArrayList paths = new ArrayList<>(); ArrayList names = new ArrayList<>(); ArrayList latitudes = new ArrayList<>(); ArrayList longitudes = new ArrayList<>(); ArrayList latref = new ArrayList<>(); ArrayList lonref = new ArrayList<>(); MongoHandler dbmon = new MongoHandler(); DB dbmongo = dbmon.connect(); DBCursor cursorDoc; Integer cont = 0; Integer pos = 0; ResultDataWithGPS res = null; DBCollection collection = dbmongo.getCollection("GPSFotos"); // BasicDBObject query = new BasicDBObject("GPS_VALUE",true); cursorDoc = collection.find(); try { while (cursorDoc.hasNext()) { pos = cont % 4; switch (pos) { case 0: //GPS_VALUE latitudes.add((cursorDoc.next().get("GPS_VALUE"))); break; case 1: latref.add((cursorDoc.next().get("GPS_VALUE"))); break; case 2: longitudes.add((cursorDoc.next().get("GPS_VALUE"))); break; case 3: lonref.add((cursorDoc.next().get("GPS_VALUE"))); break; } if ((cont != 0) && (pos == 0)) { paths.add((cursorDoc.curr().get("IMG_PATH"))); names.add((cursorDoc.curr().get("IMG_NAME")) + "." + (cursorDoc.curr().get("EXTENSION"))); } cont++; } res = new ResultDataWithGPS(paths, names, latitudes, longitudes, latref, lonref); } finally { cursorDoc.close(); } return res; }
7
@Override public double[] updatePlanes(ArrayList<Plane> planes, int round, double[] bearings) { // if any plane is in the air, then just keep things as-is for (Plane p : planes) { if (p.getBearing() != -1 && p.getBearing() != -2) return bearings; } // if no plane is in the air, find the one with the earliest // departure time and move that one in the right direction int minTime = 10000; int minIndex = 10000; for (int i = 0; i < planes.size(); i++) { Plane p = planes.get(i); if (p.getDepartureTime() < minTime && p.getBearing() == -1 && p.dependenciesHaveLanded(bearings)) { minIndex = i; minTime = p.getDepartureTime(); } } // if it's not too early, then take off and head straight for the destination if (round >= minTime) { Plane p = planes.get(minIndex); bearings[minIndex] = calculateBearing(p.getLocation(), p.getDestination()); } return bearings; }
8
public Point getCentroid(int i){ return getCell(i).getCentroid(); }
0
public static void main(String[] args) { // final Random rnd = new Random(System.currentTimeMillis()); // // network parameter. // final int input = 2; final int hidden = 8; // final int trainset_size = 5000; final int testset_size = 100; // // training parameter // final int epochs = 4000; final double learningrate = 0.004; final double momentum = 0.9; // // Generate a multilayer perceptron using the // MLPGenerator class. // final MLPGenerator gen = new MLPGenerator(); // gen.inputLayer(input); gen.hiddenLayer(hidden, CellType.SIGMOID, true, -1.0); gen.outputLayer(1, CellType.SIGMOID); // final Net mlp = gen.generate(); mlp.initializeWeights(rnd); // // Generate samples sets. // final SampleSet trainset = generateData(trainset_size + testset_size, 0.5f, rnd); final SampleSet testset = trainset.split(testset_size, rnd); // // Setup back-propagation trainer. // GradientDescent trainer = new GradientDescent(); trainer.setEpochs(epochs); trainer.setLearningRate(learningrate); trainer.setMomentum(momentum); trainer.setPermute(true); trainer.setRnd(rnd); trainer.setTargetError(10E-5); trainer.setNet(mlp); trainer.setTrainingSet(trainset); trainer.addListener(new NetTrainerListener() { @Override public void started(NetTrainer trainer) { } @Override public void finished(NetTrainer trainer) { } @Override public void epoch(NetTrainer trainer) { // final int ep = trainer.getEpoch() + 1; // if ((ep) % (epochs / 16) != 0 && ep != 1) return; final BufferedImage img = new BufferedImage(800, 800, BufferedImage.TYPE_INT_RGB); double[] p = new double[2]; double[] o = new double[2]; for (int y = 0; y < img.getHeight(); y++) { for (int x = 0; x < img.getWidth(); x++) { // p[0] = ((double)x) / ((double)(img.getWidth())); p[1] = ((double)y) / ((double)(img.getHeight())); // mlp.reset(); mlp.input(p, 0); mlp.compute(); mlp.output(o, 0); // int v = ((int)(o[0] * 255)); img.setRGB(x, y, ((v>>1) << 8) | v); } } final Graphics2D g = (Graphics2D)img.getGraphics(); g.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); for (Sample s : trainset) { int x = (int)((double)(img.getWidth() - 1) * s.getInput()[0]); int y = (int)((double)(img.getHeight() - 1) * s.getInput()[1]); if (s.getTarget()[0] > 0.5) { g.setColor(CLASS_1); } else { g.setColor(CLASS_2); } g.fillOval(x-2, y-2, 5, 5); } JFrame frame = new JFrame("Geometry Learning - Epoch: " + ep); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // JPanel panel = new JPanel() { private static final long serialVersionUID = -4307908552010057652L; @Override protected void paintComponent(Graphics gfx) { super.paintComponent(gfx); gfx.drawImage( img, 0, 0, img.getWidth(), img.getHeight(), null ); } }; panel.setPreferredSize(new Dimension(img.getWidth(), img.getHeight())); frame.add(panel); frame.setResizable(false); frame.pack(); frame.setVisible(true); } }); // // perform training. // trainer.train(); // // We use the ClassificationValidator to measure the recognition // accuracy on the training set as well as on the test set. // System.out.println(); ClassificationValidator val = new ClassificationValidator(mlp); // for (Sample s : trainset) { val.apply(s); } System.out.println( "recognition accuracy on trainset: " + (val.ratio() * 100.0) + "%" ); // val.reset(); // for (Sample s : testset) { val.apply(s); } System.out.println( "recognition accuracy on testset: " + (val.ratio() * 100.0) + "%" ); }
8
@Override public void pause() throws Exception { try { endpoint.pause(); } catch (Exception ex) { log.error(sm.getString("http11protocol.endpoint.pauseerror"), ex); throw ex; } canDestroy = false; // Wait for a while until all the processors are idle RequestInfo[] states = cHandler.global.getRequestProcessors(); int retry = 0; boolean done = false; while (!done && retry < org.apache.coyote.Constants.MAX_PAUSE_WAIT) { retry++; done = true; for (int i = 0; i < states.length; i++) { if (states[i].getStage() == org.apache.coyote.Constants.STAGE_SERVICE) { try { Thread.sleep(1000); } catch (InterruptedException e) { // NOTHING TO DO } done = false; break; } } if (done) { canDestroy = true; } } log.info(sm.getString("http11protocol.pause", getName())); }
7
* the given required colour bits per pixel of the display mode * @param frequency * the given required frequency of the display mode * @return the display mode if found, if not found return null */ public static DisplayMode getDisplayMode(int width, int height, int colourBits, int frequency) { try { // Import all the available display modes DisplayMode allDisplayModes[] = Display.getAvailableDisplayModes(); DisplayMode foundDisplayMode = null; // For each available display mode for (int displayMode = 0; displayMode < allDisplayModes.length; displayMode++) { foundDisplayMode = allDisplayModes[displayMode]; // Check if it matches the required settings and if it does, // return that display mode if (foundDisplayMode.getHeight() == height && foundDisplayMode.getWidth() == width && foundDisplayMode.getBitsPerPixel() == colourBits && foundDisplayMode.getFrequency() == frequency) return foundDisplayMode; } } // Catches any exceptions thrown by getAvailableDisplayModes() catch (Exception exception) { System.out.println("KouchKarting.getDisplayMode() error: " + exception); } // If no compatible display mode was found, return null return null; }
6
static final int method2109(boolean flag, byte byte0) { long l = TimeUtil.getTime(); for (Class142_Sub3 class142_sub3 = flag ? (Class142_Sub3) Class83.aNodeCache_1270.method1083() : (Class142_Sub3) Class83.aNodeCache_1270.method1081(); class142_sub3 != null; class142_sub3 = (Class142_Sub3) Class83.aNodeCache_1270.method1081()) { if ((class142_sub3.aLong3231 & 0x3fffffffffffffffL) < l) { if (~(0x4000000000000000L & class142_sub3.aLong3231) == -1L) { class142_sub3.unlink(); } else { int i = (int) ((Node) (class142_sub3)).id; Class21.settings[i] = Class86.anIntArray1485[i]; class142_sub3.unlink(); return i; } } } if (byte0 < 115) { anInt2609 = -100; } return -1; }
5
public static final <T> T getTarget(Class<T> type) { Component focus = getFocusOwner(); T target = UIUtilities.getSelfOrAncestorOfType(focus, type); if (target == null) { RetargetableFocus retargeter = UIUtilities.getSelfOrAncestorOfType(focus, RetargetableFocus.class); if (retargeter != null) { target = UIUtilities.getSelfOrAncestorOfType(retargeter.getRetargetedFocus(), type); } } return target; }
2
@Override public Summit<T> getUnvisitedChildren(Summit<T> n) { // TODO Auto-generated method stub for (Link<T> l : links) { if (l.visited==false && l.start.equals(n)) { l.visited=true; return l.end; } } return null; }
3
private JToolBar getBarraHerramientas(){ JToolBar toolBar = new JToolBar("Herramientas Rápidas"); // 1er boton: Nuevo programa // ------------ Icon iconoNuevo = new ImageIcon(this.getClass().getResource("/resources/icons/toolbar/iconNewProg.png")); JButton botonNuevo = new JButton(iconoNuevo); botonNuevo.addActionListener(new ActionListener(){ public void actionPerformed (ActionEvent e){ iniciarNuevoPrograma(); } } ); botonNuevo.setToolTipText("Crear nuevo programa"); toolBar.add(botonNuevo); // 2º boton: Cargar programa // ------------- Icon iconoAbrir = new ImageIcon(this.getClass().getResource("/resources/icons/toolbar/iconOpen.png")); JButton botonAbrir = new JButton(iconoAbrir); botonAbrir.addActionListener(new ActionListener(){ public void actionPerformed (ActionEvent e){ cargarProgramaDesdeFichero(); } } ); botonAbrir.setToolTipText("Cargar un programa desde fichero"); toolBar.add(botonAbrir); // 3er boton: Guardar programa // ------------- Icon iconoGuardar= new ImageIcon(this.getClass().getResource("/resources/icons/toolbar/iconSave.png")); JButton botonGuardar = new JButton(iconoGuardar); botonGuardar.addActionListener(new ActionListener(){ public void actionPerformed (ActionEvent e){ if (rutaProgActual != "") // Si ya estamos trabajando sobre un archivo guardarProgramaEnFichero(false); else guardarProgramaEnFichero(true); } } ); botonGuardar.setToolTipText("Guardar programa en un fichero"); toolBar.add(botonGuardar); toolBar.addSeparator(); // 4º boton: Compilar programa // ------------- Icon iconoCompilar = new ImageIcon(this.getClass().getResource("/resources/icons/toolbar/iconCompile.png")); JButton botonCompilar = new JButton(iconoCompilar); botonCompilar.addActionListener(new ActionListener(){ public void actionPerformed (ActionEvent e){ // INICIAR COMPILADOR accionBotonCompilar(); } } ); botonCompilar.setToolTipText("Compila el código actual"); toolBar.add(botonCompilar); // 5º boton: Compilar y Ejecutar // ------------- Icon iconoEjecutar = new ImageIcon(this.getClass().getResource("/resources/icons/toolbar/iconRun.png")); JButton botonEjecutar = new JButton(iconoEjecutar); botonEjecutar.addActionListener(new ActionListener(){ public void actionPerformed (ActionEvent e){ // INICIAR COMPILADOR Y EJECUTAR accionBotonEjecutar(); } } ); botonEjecutar.setToolTipText("Compila y ejecuta el código actual"); toolBar.add(botonEjecutar); toolBar.addSeparator(); // 6º boton: Compilar y Ejecutar Paso a Paso // ------------- Icon iconoEjecutarSBS = new ImageIcon(this.getClass().getResource("/resources/icons/toolbar/iconRunSBS.png")); JButton botonEjecutarSBS = new JButton(iconoEjecutarSBS); botonEjecutarSBS.addActionListener(new ActionListener(){ public void actionPerformed (ActionEvent e){ // COMPILAR y EJECUTAR PASO A PASO accionBotonEjecutarSBS(); } } ); botonEjecutarSBS.setToolTipText("Compila y ejecuta paso a paso el código actual"); toolBar.add(botonEjecutarSBS); // 7º boton: Avanzar // ------------- Icon iconoAvanzar= new ImageIcon(this.getClass().getResource("/resources/icons/toolbar/iconNext.png")); botonAvanzarToolBar = new JButton(iconoAvanzar); botonAvanzarToolBar.setEnabled(false); botonAvanzarToolBar.addActionListener(new ActionListener(){ public void actionPerformed (ActionEvent e){ accionBotonAvanzar(); } } ); botonAvanzarToolBar.setToolTipText("Avanza a la sig instrucción"); toolBar.add(botonAvanzarToolBar); // 8º boton: Parar // ------------ Icon iconoParar = new ImageIcon(this.getClass().getResource("/resources/icons/toolbar/iconStop.png")); botonPararToolBar = new JButton(iconoParar); botonPararToolBar.setEnabled(false); botonPararToolBar.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ accionParar(true); } } ); botonPararToolBar.setToolTipText("Detiene la ejecución paso a paso"); toolBar.add(botonPararToolBar); toolBar.addSeparator(); // 9º boton: Limpiar consola // ------------- Icon iconoLimpiar = new ImageIcon(this.getClass().getResource("/resources/icons/toolbar/iconCleanConsole.png")); JButton botonLimpiar = new JButton(iconoLimpiar); botonLimpiar.addActionListener(new ActionListener(){ public void actionPerformed (ActionEvent e){ areaTextoConsola.setText("> "); } } ); botonLimpiar.setToolTipText("Limpiar la consola"); toolBar.add(botonLimpiar); toolBar.addSeparator(); // 10º boton: Siguiente prueba Pos // ------------- Icon iconoSigPos = new ImageIcon(this.getClass().getResource("/resources/icons/toolbar/iconNextOK.png")); botonSigPos = new JButton(iconoSigPos); botonSigPos.addActionListener(new ActionListener(){ public void actionPerformed (ActionEvent e){ if (pruebaPositiva < maxPos){ pruebaPositiva++; String num; if (pruebaPositiva < 10) num = "0" + pruebaPositiva; else num = String.valueOf(pruebaPositiva); File prueba = new File(pathPositivo + num + ".lpp"); if (prueba.isFile()) cargarPrueba(prueba.getAbsolutePath()); else JOptionPane.showMessageDialog(InterfazCompilador.this, "No se puede cargar archivo de prueba:\n" + prueba.getAbsolutePath() + "\nEl archivo no existe", "Error!", JOptionPane.ERROR_MESSAGE); } else botonSigPos.setEnabled(false); } } ); botonSigPos.setToolTipText("Carga la siguiente prueba positiva"); toolBar.add(botonSigPos); // 11º boton: Siguiente prueba Negativa // ------------- Icon iconoSigNeg = new ImageIcon(this.getClass().getResource("/resources/icons/toolbar/iconNextFAIL.png")); botonSigNeg = new JButton(iconoSigNeg); botonSigNeg.addActionListener(new ActionListener(){ public void actionPerformed (ActionEvent e){ if (pruebaNegativa < maxNeg){ pruebaNegativa++; String num; if (pruebaNegativa < 10) num = "0" + pruebaNegativa; else num = String.valueOf(pruebaNegativa); File prueba = new File(pathNegativo + num + ".lpp"); if (prueba.isFile()) cargarPrueba(prueba.getAbsolutePath()); else JOptionPane.showMessageDialog(InterfazCompilador.this, "No se puede cargar archivo de prueba:\n" + prueba.getAbsolutePath() + "\nEl archivo no existe", "Error!", JOptionPane.ERROR_MESSAGE); } else botonSigNeg.setEnabled(false); } } ); botonSigNeg.setToolTipText("Carga la siguiente prueba negativa"); toolBar.add(botonSigNeg); return toolBar; }
7
public static ItemStack makeReal(ItemStack stack) { if (stack == null) return null; Object nmsStack = getHandle(stack); if (nmsStack == null) { stack = getCopy(stack); nmsStack = getHandle(stack); } if (nmsStack == null) { return null; } try { Object tag = class_ItemStack_tagField.get(nmsStack); if (tag == null) { class_ItemStack_tagField.set(nmsStack, class_NBTTagCompound.newInstance()); } } catch (Throwable ex) { ex.printStackTrace(); return null; } return stack; }
5
public void dumpDeclaration(TabbedPrintWriter writer) throws java.io.IOException { LocalInfo li = getLocalInfo(); if (li.isFinal) writer.print("final "); writer.printType(li.getType().getHint()); writer.print(" " + li.getName().toString()); }
1
public CheckResultMessage checkTotal4(int i) { int r1 = get(13, 5); int c1 = get(14, 5); int r2 = get(15, 5); BigDecimal sum = new BigDecimal(0); if (checkVersion(file).equals("2003")) { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); for (int j = 1; j < r2 - r1; j++) { sum = sum.add(getValue(r1 + j, c1 + i, 3)); } if (0 != getValue(r2, c1 + i, 3).compareTo(sum)) { return error("支付机构汇总报表<" + fileName + ">sheet1-4:" + "本月所有日期合计:D0" + (1 + i) + "错误"); } in.close(); } catch (Exception e) { } } else { try { in = new FileInputStream(file); xWorkbook = new XSSFWorkbook(in); for (int j = 1; j < r2 - r1; j++) { sum = sum.add(getValue1(r1 + j, c1 + i, 3)); } if (0 != getValue1(r2, c1 + i, 3).compareTo(sum)) { return error("支付机构汇总报表<" + fileName + ">sheet1-4:" + "本月所有日期合计:D0" + (1 + i) + "错误"); } in.close(); } catch (Exception e) { } } return pass("支付机构汇总报表<" + fileName + ">sheet1-4:" + "本月所有日期合计:D0" + (1 + i) + "正确"); }
7
private String determinePrefixAndNamespaceUri() { if (namespaceUri != null) { if (rootElement != null && namespaceUri.equals(rootElement.getNamespaceURI())) { // global namespaces do not have a prefix or namespace URI return null; } else { // lookup for prefix String lookupPrefix = lookupPrefix(); if (lookupPrefix == null && rootElement != null) { // if no prefix is found we generate a new one // search for known prefixes String knownPrefix = KNOWN_PREFIXES.get(namespaceUri); if (knownPrefix == null) { // generate namespace return rootElement.registerNamespace(namespaceUri); } else if (knownPrefix.isEmpty()) { // ignored namespace return null; } else { // register known prefix rootElement.registerNamespace(knownPrefix, namespaceUri); return knownPrefix; } } else { return lookupPrefix; } } } else { // no namespace so no prefix return null; } }
7
public static double getJavaVersion() { if (javaVersion == null) { try { String ver = System.getProperties().getProperty("java.version"); String version = ""; boolean firstPoint = true; for (int i = 0; i < ver.length(); i++) { if (ver.charAt(i) == '.') { if (firstPoint) { version += ver.charAt(i); } firstPoint = false; } else if (Character.isDigit(ver.charAt(i))) { version += ver.charAt(i); } } javaVersion = new Double(version); } catch (Exception ex) { javaVersion = new Double(1.3); } } return javaVersion.doubleValue(); }
6
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof PropertyElement)) return false; PropertyElement that = (PropertyElement) o; if (name != null ? !name.equals(that.name) : that.name != null) return false; if (parent != null ? !parent.equals(that.parent) : that.parent != null) return false; return true; }
6
public List<Colors> getColorsList() { List<Colors> list = new ArrayList<Colors>(); for (int i = 0 ; i < Combination.SIZE ; i++) { list.add((Colors) this.tokens.get(i).getColor()); } return list; }
1
public int altBlackWhiteBoundary() { int fwe = firstValleyEnd() - offset; // Find the last peak. int bestValue = -1; int lastPeak = hg.length - 1; for (int i = hg.length - 1; i >= 0; i--) { if (hg[i] < bestValue) { break; } else { lastPeak = i; bestValue = hg[i]; } } // Now go to the left until we reach somewhere that's at least mult smaller than that peak. int blackWhitePoint = lastPeak - 1; for (; blackWhitePoint >= fwe; blackWhitePoint--) { if (hg[blackWhitePoint] < bestValue * 0.2) { break; } } // Now finally slide down from there until we hit our first increase, or until we hit // firstValleyEnd. int cmpVal = hg[blackWhitePoint]; for (; blackWhitePoint >= fwe; blackWhitePoint--) { if (hg[blackWhitePoint] > cmpVal) { return blackWhitePoint + offset; } else { cmpVal = hg[blackWhitePoint]; } } return fwe + offset; }
6
public int setStructure(Instances headerInfo){ Capabilities cap = getCapabilities(); if (!cap.test(headerInfo)) throw new IllegalArgumentException(cap.getFailReason()); if(m_writeMode == WAIT && headerInfo != null){ m_instances = headerInfo; m_writeMode = STRUCTURE_READY; } else{ if((headerInfo == null) || !(m_writeMode == STRUCTURE_READY) || !headerInfo.equalHeaders(m_instances)){ m_instances = null; if(m_writeMode != WAIT) System.err.println("A structure cannot be set up during an active incremental saving process."); m_writeMode = CANCEL; } } return m_writeMode; }
7
private void cargar_Campos (int valor){ try{ this.vaciarCampos(); r_con.Connection(); PreparedStatement pstm = r_con.getConn().prepareStatement( "SELECT *"+ " FROM "+name_tabla+ " WHERE prod_codigo = "+valor); ResultSet res = pstm.executeQuery(); String imp_porc; String imp_fij; while(res.next()){ field_codigo.setText(res.getString(1)); field_descripcion.setText(res.getString(2)); field_cantidad.setText(res.getString(3)); field_costo_u.setText(convertirEnBigDecimal(res.getString(4))+""); field_precio_venta.setText(convertirEnBigDecimal(res.getString(5))+""); field_tasa_iva.setText(res.getString(6)); imp_porc = res.getString(7); imp_fij = res.getString(8); if((imp_porc.equals("0.0")) && (imp_fij.equals("0.0"))){ field_impuesto.setText(""); combo_tipo_imp.setSelectedIndex(0); lab_tipo_imp.setText(" "); } else{ if(imp_porc.equals("0.0")){ field_impuesto.setText(imp_fij); combo_tipo_imp.setSelectedIndex(2); lab_tipo_imp.setText("($)"); } else{ field_impuesto.setText(imp_porc); combo_tipo_imp.setSelectedIndex(1); lab_tipo_imp.setText("(%)"); } } } res.close(); } catch(SQLException e){ System.out.println(e); } finally { r_con.cierraConexion(); } }
5
public void addRows(List<String[]> r) { for (String[] s : r) { String[] ns = new String[s.length]; for (int i = 0; i < ns.length; i++) { ns[i] = new String(s[i]); } rows.add(ns); } }
2
@Override public void spawnEnemy(String enemyData) { if(!free()) { return; } int r = Application.get().getRNG().nextInt(7); GameActor a = Application.get().getLogic().createActor(enemyData); PhysicsComponent pc = (PhysicsComponent)a.getComponent("PhysicsComponent"); pc.setLocation(x + 50 + r * 100, y - 50); pc.setAngleRad(MathUtil.getOppositeAngleRad(upAngle)); pc.setTargetAngle(pc.getAngleRad()); AIComponent aic = (AIComponent)a.getComponent("AIComponent"); BaseAI ai = aic.getAI(); if(ai instanceof EnemyBasicAI) { EnemyBasicAI ebai = (EnemyBasicAI)ai; ebai.setSector(ID); } }
2
@Test public void testDeleteMiddleNode4() throws Exception { LinkedListNode middleNode = new LinkedListNode(1); head = middleNode.addNode(new LinkedListNode(2)).addNode(new LinkedListNode(3)).addNode(new LinkedListNode(4)).addNode(new LinkedListNode(5)); head.addNode(new LinkedListNode(6)).addNode(new LinkedListNode(7)).addNode(new LinkedListNode(8)).addNode(new LinkedListNode(9)); exerciseObj.deleteMiddleNode(middleNode); assert(head.getValue() == 2 && head.getNext().getValue() == 3 && head.getNext().getNext().getValue() == 4 && head.getNext().getNext().getNext().getValue() == 5 && head.getNext().getNext().getNext().getNext().getValue() == 6 && head.getNext().getNext().getNext().getNext().getNext().getValue() == 7 && head.getNext().getNext().getNext().getNext().getNext().getNext().getValue() == 8 && head.getNext().getNext().getNext().getNext().getNext().getNext().getNext().getValue() == 9 && head.getNext().getNext().getNext().getNext().getNext().getNext().getNext().getNext() == null); }
8
@Override public State transition(TransitionContext context) { if(context.isSymbol()) { // Test to see whether accumulating this char // would result in any valid symbols remaining. // If yes then we keep building up the symbol. context.pushChar(); if(context.existsSymbolWithAccumulatedAsPrefix()) return this; // Otherwise undo the push and emit a symbol token // or error token depending on whether the accumulated // value is a valid symbol string. context.popChar(); String potentialSymbol = context.accumulated(); context.emit(context.getSymbols().containsKey(potentialSymbol) ? context.getSymbols().get(potentialSymbol) : Kind.ERROR); // Finally, we defer handling of this potential new symbol // to the start state, because it might be a comment. return StartState.instance().transition(context); } // If the value is not a symbol, then we transition // away from this state, emitting the correct symbol // token or error token depending on whether the // accumulated value is a valid symbol string or not. String potentialSymbol = context.accumulated(); context.emit(context.getSymbols().containsKey(potentialSymbol) ? context.getSymbols().get(potentialSymbol) : Kind.ERROR); // Because the value is not a symbol, defer its // handling to the StartState. return StartState.instance().transition(context); }
4
public void inicializarCarros(int[][] inicialesC, Double[] angulos) throws TamanosInvalidosInicializacionException { if(inicialesC[0].length==CARCODES.length && inicialesC[1].length==CARCODES.length && angulos.length==CARCODES.length) { Nodo aInitialNode; for(int i =0; i<CARCODES.length;i++) { aInitialNode=malla[inicialesC[1][i]][inicialesC[0][i]]; carros.add( new Carro(this,CARCODES[i], aInitialNode, angulos[i])); } }else { throw new TamanosInvalidosInicializacionException(); } }
4
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(!(affected instanceof MOB)) return true; final MOB mob=(MOB)affected; // when this spell is on a MOBs Affected list, // it should consistantly prevent the mob // from trying to do ANYTHING except sleep if(msg.amISource(mob)) { if((!msg.sourceMajor(CMMsg.MASK_ALWAYS)) &&((msg.sourceMajor(CMMsg.MASK_HANDS)) ||(msg.sourceMajor(CMMsg.MASK_MOVE)))) { if(mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> struggle(s) against the snaring plants."))) { amountRemaining-=(mob.charStats().getStat(CharStats.STAT_STRENGTH)*4); if(amountRemaining<0) unInvoke(); } return false; } } return super.okMessage(myHost,msg); }
7
private void printBar(boolean finished) { double numbar = Math.floor(20 * (double) current / (double) max); String strbar = ""; int ii = 0; for (ii = 0; ii < numbar; ii++) { strbar += "="; } for (ii = (int) numbar; ii < 20; ii++) { strbar += " "; } long elapsed = (System.currentTimeMillis() - this.start); int seconds = (int) (elapsed / 1000) % 60; int minutes = (int) (elapsed / 1000) / 60; String strend = String.format("%02d", minutes) + ":" + String.format("%02d", seconds); String strETA = ""; if (elapsed < 2000) { strETA = "--:--"; } else { long timeETA = elapsed * (long) ((double) max / (double) current); int ETAseconds = (int) (timeETA / 1000) % 60; int ETAminutes = (int) (timeETA / 1000) / 60; strETA = String.format("%02d", ETAminutes) + ":" + String.format("%02d", ETAseconds); } if (finished) { strend = "Finished: " + strend + " "; } else { strend = "Elapsed: " + strend + " ETA: " + strETA + " "; } System.out.print("|" + strbar + "| " + strend); if (finished) { System.out.print("\n"); } else { System.out.print("\r"); } }
5
public void setTotal(int i) { totalPaymentToDate=i; }
0
private void addNewCode(final String barcode) { // separate non-FX thread new Thread() { @Override public void run() { // update UI on FX thread Platform.runLater(new Runnable() { @Override public void run() { input.setStyle("-fx-background-color: green;"); input.setEditable(false); } }); try { // Allow user to spot scanned barcode is correct ;-) Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } // update UI on FX thread Platform.runLater(new Runnable() { @Override public void run() { int alreadyScanned = 0; // add to list if not already added if (!codeList.contains(barcode)) { codeList.add(barcode); // Write new barcode to file storage.appendBarcode(barcode); // TODO what if writing to file failed? alreadyScanned = codeList.size(); counter.setText(String.valueOf(alreadyScanned)); } else { System.out.println("Taki kod jest już na liście."); // TODO Play some sound? } // scroll listview to make last item visible output.scrollTo(alreadyScanned); cleanInputAction(null); if (alreadyScanned == 3 || alreadyScanned == 5 || alreadyScanned == 10) { showPrizeDialog(alreadyScanned); } } }); } }.start(); }
5
public int hashCode() { int hash = 7; hash += 31 * hash + (type == null ? 0 : type.hashCode()); hash += 31 * hash + (abilityID == null ? 0 : abilityID.hashCode()); hash += 31 * hash + (abilityValue ? 1 : 0); hash += 31 * hash + (methodName == null ? 0 : methodName.hashCode()); hash += 31 * hash + (methodValue == null ? 0 : methodValue.hashCode()); hash += 31 * hash + (matchesNull ? 1 : 0); hash += 31 * hash + (matchNegated ? 1 : 0); return hash; }
7
public double[] do145baudFSKHalfSymbolBinRequest (CircularDataBuffer circBuf,int start,int bin0,int bin1) { double vals[]=new double[2]; // Get the data from the circular buffer double samData[]=circBuf.extractDataDouble(start,27); double datar[]=new double[FFT_160_SIZE]; // Run the data through a Blackman window int a; for (a=0;a<datar.length;a++) { if ((a>=66)&&(a<93)) datar[a]=samData[a-66]; else datar[a]=0.0; datar[a]=windowBlackman(datar[a],a,datar.length); } fft160.realForward(datar); double spec[]=getSpectrum(datar); vals[0]=spec[bin0]; vals[1]=spec[bin1]; return vals; }
3
public static List<String> wordBreak2(String s, Set<String> dict) { int len = s.length(); List<List<String>> res = new ArrayList<List<String>>(); boolean[] iswordbreak = new boolean[len + 1]; iswordbreak[len] = true; for (int i = 0; i < s.length() + 1; i++) { res.add(new ArrayList<String>()); } for (int i = len - 1; i >= 0; i--) { for (int j = i; j < len; j++) { String word = s.substring(i, j + 1); if (iswordbreak[j + 1] && dict.contains(word)) { iswordbreak[i] = true; if (0 == res.get(j + 1).size()) res.get(i).add(word); else { for (String str : res.get(j + 1)) { res.get(i).add(word + " " + str); } } } } } return res.get(0); }
7
public ShowSelfInfoPanel() { setLayout(null); picPanel.setSize(700, 425); picPanel.setBounds(0, 0, 700, 425); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { lb[i][j] = new JLabel("", JLabel.CENTER); lb[i][j].setFont(new Font("微软雅黑", Font.PLAIN, 16)); add(lb[i][j]); } } for (int i = 0; i < 4; i++) { lb[i][0].setBounds(200, 100 + 40 * i, 90, 40); lb[i][1].setBounds(300, 100 + 40 * i, 100, 40); lb[i][2].setBounds(410, 100 + 40 * i, 90, 40); lb[i][3].setBounds(510, 100 + 40 * i, 100, 40); } lb[0][0].setText("正在获取..."); Object o = logic.showSelfInformation(); if (o instanceof Feedback) { JOptionPane.showMessageDialog(null, ((Feedback) o).getContent()); } else if(o instanceof StudentVO) { StudentVO stu = (StudentVO) o; lb[0][0].setText("学号"); lb[0][1].setText(stu.id); lb[0][2].setText("姓名"); lb[0][3].setText(stu.name); lb[1][0].setText("院系"); lb[1][1].setText(stu.department); lb[1][2].setText("专业"); lb[1][3].setText(stu.major); lb[2][0].setText("班级编号"); lb[2][1].setText(stu.classNo); lb[2][2].setText("年级"); lb[2][3].setText(stu.grade); lb[3][0].setText("学制"); lb[3][1].setText(stu.duration); lb[3][2].setText("学籍状态"); lb[3][3].setText(stu.enrollmentStatus); } else if (o instanceof TeacherVO) { TeacherVO tea = (TeacherVO) o; lb[0][0].setText("工号"); lb[0][1].setText(tea.id); lb[0][2].setText("姓名"); lb[0][3].setText(tea.name); lb[1][0].setText("类型"); lb[1][1].setText(tea.userType); lb[1][2].setText("单位"); lb[1][3].setText(tea.company); } add(picPanel); }
6
@Override public List<Component> getAllComponents() { Connection conn = null; PreparedStatement st = null; ResultSet row = null; List<Component> res = new ArrayList<Component>(); try { conn = OracleDAOFactory.createConnection(); st = conn.prepareStatement(GET_ALL_COMPONENTS); row = st.executeQuery(); while (row.next()) { Component comp = new Component(); comp.setId(row.getInt(ID_COMPONENT)); comp.setTitle(row.getString(TITLE)); comp.setDescription(row.getString(DESCRIPTION)); comp.setProducer(row.getString(PRODUCER)); comp.setWeight(row.getDouble(WEIGHT)); comp.setImg(row.getString(IMG)); comp.setPrice(row.getDouble(PRICE)); res.add(comp); } return res; } catch (SQLException e) { throw new ShopException("Can't get components from database", e); } finally { try { if (row != null) { row.close(); } } catch (SQLException e) { throw new ShopException(CANT_CLOSE_RESULT_SET, e); } try { if (st != null) { st.close(); } } catch (SQLException e) { throw new ShopException(CANT_CLOSE_STATEMENT, e); } try { if (conn != null) { conn.close(); } } catch (SQLException e) { throw new ShopException(CANT_CLOSE_CONNECTION, e); } } }
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(ChoixArtefact.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ChoixArtefact.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ChoixArtefact.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ChoixArtefact.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { ChoixArtefact dialog = new ChoixArtefact(new javax.swing.JFrame(), true, liste); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
6
public static void allPermutationWithoutRecursion(int[] a) { if (1 >= a.length) { return; } int temp = 0; while (true) { int i = a.length - 2; while (i >= 0) { if (a[i] < a[i + 1]) { break; } i--; } if (0 > i) { break; } int j = a.length - 1; while (j > i) { if (a[j] > a[i]) { break; } j--; } temp = a[i]; a[i] = a[j]; a[j] = temp; revert(a, i + 1, a.length - 1); for (int k : a) { System.out.print(k); } System.out.println(); } }
8
protected void updatePopupLocation() { final Point los = DatePickerButton.this.getLocationOnScreen(); final Rectangle gb = popup.getGraphicsConfiguration().getBounds(); final boolean ltr = DatePickerButton.this.getComponentOrientation().isLeftToRight(); final int w = DatePickerButton.this.getWidth(); final int h = DatePickerButton.this.getHeight(); final int x; if (ltr) { if (los.x + popup.getWidth() <= gb.x + gb.width) { x = los.x; } else { x = los.x + w - popup.getWidth(); } } else { if (los.x + w - popup.getWidth() >= gb.x) { x = los.x + w - popup.getWidth(); } else { x = los.x; } } final int y; if (los.y + h + popup.getHeight() <= gb.y + gb.height) { y = los.y + h; } else { y = los.y - popup.getHeight(); } popup.setLocation(x, y); }
4
@Override public Event next() { String itemInput = null; try { itemInput = br.readLine(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if(input == null || input.equals("")){ return new UserHomeState(as, input); } else{ try{ as.bid(name, Integer.parseInt(itemInput)); } catch(Exception e){ return new SearchResultsState(as, name, itemInput); } return new SearchResultsState(as, name, input); } }
4
public void addNewHero(core.Hero hero) { core.WorldMap wmap = core.WorldMap.getLastInstance(); if (wmap != null) { player.addHero(hero); castle.setHero(hero); hero.setInCastle(castle); //castle.lockStanding(); units.setRight(hero); core.Point pos = wmap.getPositionOfObject(castle); wmap.addObject(pos.x, pos.y, hero); //wmap.getMapWidget().objectAt(pos.y, pos.x).setLayer(hero.getLevel(), new WidgetImage(hero.getImageFile(), 64)); wmap.moveTo(hero, player, pos.x, pos.y, -1, -1); core.Mission m = core.Mission.getLastInstance(); player.setActiveHero(hero); if (m != null) { m.addHero.emit(hero); } } }
2
private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed DefaultTableModel dft = (DefaultTableModel) tbPregResp.getModel(); for(int i=0; i <dft.getRowCount(); i++){ Iterator it = temaMaestro.getPreguntas().iterator(); while(it.hasNext()){ Pregunta_Tema ptt = (Pregunta_Tema) it.next(); if(ptt.getPregunta().getCodigo() == Integer.parseInt(dft.getValueAt(i, 0).toString())){ int rta = 0; String letra =dft.getValueAt(i, 1).toString(); if(letra.equals("A")){ rta =1; }else if(letra.equals("B")){ rta = 2; }else if(letra.equals("C")){ rta =3; }else if(letra.equals("D")){ rta= 4; } ptt.setRespuesta(rta); } } } ctrlTema.ingresarRespuesta(temaMaestro); ctrlTema.desplegarRespuestas(temaMaestro); limpiarTabla(); btnAgregar.setEnabled(false); btnGuardar.setEnabled(false); cbPregunta.setEnabled(false); cbOpcion.setEnabled(false); }//GEN-LAST:event_btnGuardarActionPerformed
7
final public void forceRedraw() { needsRedraw = true; repaint(); }
0
public Boolean getStat() throws Exception { try { for (String s: Naming.list(registry)) { if (s.endsWith("/" +name)) { return true; } } return false; } catch (RemoteException e) { Logger.getLogger(getClass()).error("Cannot check RMI availability", e); return false; } }
3
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(Lobby.class.getName()).log( java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Lobby.class.getName()).log( java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Lobby.class.getName()).log( java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Lobby.class.getName()).log( java.util.logging.Level.SEVERE, null, ex); } // </editor-fold> final AnimatedJabriscaJPanel board = new GameBoard(); /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { ((JabriscaJPanel) board).setVisible(true); } }); try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } // TODO fix the animations // "MoveCardAnimation","boardGame_myCard1","boardGame_player1Card" board.animate("MoveCardAnimation", "boardGame_myCard1", "boardGame_player1Card"); board.animate("MoveCardAnimation", "boardGame_myCard2", "boardGame_player2Card"); board.animate("MoveCardAnimation", "boardGame_myCard3", "boardGame_player3Card"); }
7
private void printTable() { System.out.println(""); int row = 0; for (String columnHead : columns) { System.out.print(" " + columnHead + " "); } System.out.println("\n------------------"); for (ArrayList<Boolean> tableRow : topTable) { System.out.print(topOfTableRow.get(row)); row++; for ( Boolean validMember : tableRow ) { System.out.print(" " + validMember); } System.out.println(); } System.out.println("------------------"); row = 0; for (ArrayList<Boolean> tableRow : bottomTable) { System.out.print(bottomOfTableRow.get(row)); row++; for ( Boolean validMember : tableRow ) { System.out.print(" " + validMember); } System.out.println(""); } System.out.println(""); }
5
public boolean set_address(final String addr_) { address.resolve(addr_, options.ipv4only > 0 ? true : false); endpoint = address.toString(); try { handle = ServerSocketChannel.open(); handle.configureBlocking(false); handle.socket().setReuseAddress(true); handle.socket().bind(address.address(), options.backlog); } catch (SecurityException e) { ZError.errno(ZError.EACCESS); close (); return false; } catch (IllegalArgumentException e) { ZError.errno(ZError.ENOTSUP); close (); return false; } catch (IOException e) { ZError.errno(ZError.EADDRINUSE); close (); return false; } socket.event_listening(endpoint, handle); return true; }
4
public void wypozyczFilm(Long osobaId, Long filmId) { Osoba osoba = em.find(Osoba.class, osobaId); Film film = em.find(Film.class, filmId); film.setWypoz(true); osoba.getFilm().add(film); }
0
@XmlElement public void setName(String name) { this.name = name; }
0
@Test public void isSingleton() { // Singleton obj = new Singleton(); Compilation error not allowed int count = 0; //create the Singleton Object.. Singleton obj = Singleton.getSingletonObject(); count = count+1; // Your Business Logic //System.out.println("Singleton object obtained"); Assert.assertNotNull(obj); Assert.assertEquals(count, 1); }
0
private boolean withdraw() { double value = random.nextDouble(); return value < WITHDRAW_CHANCE; }
0
public void avoidObstacle() { // set status isAvoiding = true; // initialize variables double delta = 0; double fwdError = 0; long time1=0; long time2=0; // get reading from top us sensor int dist = up[Constants.topUSPollerIndex].getLatestFilteredDataPoint(); // get actual destination double x1 = Constants.robotDest[0]; double y1 = Constants.robotDest[1]; // approach obstacle if too far if (dist > 20) { // slowly approach obstacle nav.setSpeeds(Navigation.SLOW, Navigation.SLOW); // start time keeping for timeout time1 = System.currentTimeMillis(); do { dist = up[Constants.topUSPollerIndex] .getLatestFilteredDataPoint(); time2 = System.currentTimeMillis(); // stop approach if timed out if(time2 - time1 > 2000){ break; } } while (dist > 23); // stop approaching obstacle nav.stopMotors(); } // turn robot 90 degrees clockwise nav.rotateBy(-90, false, Navigation.SLOW); // turn us sensor towards obstacle sensorMotor.rotateTo(-110, false); // do bang bang wall follower do { // follow obstacle doBangBang(); // check for obstacle (e.g. a robot passing in front) at the front // at the same time if (up[Constants.bottomUSPollerIndex].getLatestFilteredDataPoint() < 20) { // stop motors nav.stopMotors(); // wait until robot passes by while (up[Constants.bottomUSPollerIndex] .getLatestFilteredDataPoint() < 20) { LCD.drawString("Waiting for obstacle",0,0); LCD.drawString("at front to move",0,1); } } // check if in-line with destination point // by calculating difference in heading. // if so, stop bang bang // get destination heading double destAng = destAng(x1, y1); double robotAng = odo.getAng(); // calculate difference in heading in two ways double delta1 = Math.abs(robotAng - destAng); double delta2 = Math.abs(robotAng - destAng + 360); // choose smallest difference in heading delta = Math.min(delta1, delta2); // calculate position error between position and destination fwdError = calcFwdError(x1, y1); } while (delta > 10 && fwdError > 10); // stop robot nav.stopMotors(); // turn sensor back sensorMotor.rotateTo(0, false); // reset status isAvoiding = false; try{ Thread.sleep(1000); }catch(Exception e){} }
8
public void fileCreated(int noOfFiles, String filePath, String fileName) { // TODO: to be removed sysouts System.out.println(noOfFiles); System.out.println(filePath); System.out.println(fileName); File newFile = FileUtil.getFile(filePath, fileName); String fileExtension = null; if (FileUtil.isValidFile(newFile)) { LOG.info(StringUtil.concatenateStrings("A new file named ", fileName, " has been created at path - ", filePath, ".")); fileExtension = FileUtil.getFileExtension(fileName); try { if (CommonUtil.isRecognizedFileExtension(fileExtension)) { LOG.info(StringUtil.concatenateStrings("File: ", newFile.toString(), ", will be processed.")); rawEntityStore.putRawFile(newFile); } } catch (InterruptedException iE) { LOG.error("Failed to put the file in the raw entity store. Marking the file unprocessed.", iE); try { FileUtil.renameFile(newFile, StringUtil.concatenateStrings(newFile.getName(), ".unprocessed")); } catch (IllegalAccessException e) { LOG.error("Failed to mark the file unprocessed.",e); } } } }
4
public void doSpecial(String itemname) { switch (getRoomnumber()) {// bepaal om welke kamer het gaat case 1: if (itemname.equals("bonekey")) {// kijk of het juiste item is gebruikt, in de juiste kamer System.out.println("You open the chest with the BoneKey, and... nothing happened!"); } else if (itemname.equals("endgameitem")) { winner(); System.exit(0); } // Als item niet juist is else { System.out.println("You cannot use '" + itemname + "' in this room."); } // if(itemname.equals(anObject)) break; case 8: if (itemname.equals("ring")){ System.out.println("Gogann: My precious! My precious!"); break; } // Als kamer niet juist is default: System.out.println("You cannot use '" + itemname + "' in this room."); break; } }
5
public void resetBank() { outStream.createFrameVarSizeWord(53); outStream.writeWord(5382); // bank outStream.writeWord(playerBankSize); // number of items for (int i = 0; i < playerBankSize; i++) { if (bankItemsN[i] > 254) { outStream.writeByte(255); outStream.writeDWord_v2(bankItemsN[i]); } else { outStream.writeByte(bankItemsN[i]); //amount } if (bankItemsN[i] < 1) bankItems[i] = 0; if (bankItems[i] > 20000 || bankItems[i] < 0) { bankItems[i] = 20000; } outStream.writeWordBigEndianA(bankItems[i]); // itemID } outStream.endFrameVarSizeWord(); }
5
public FibersView(SingleFrameApplication app) { super(app); initComponents(); { java.awt.Container pt = outerPanel.getParent(); innerPanel.setLayout(new BorderLayout(10, 10)); innerPanel.add(Blob_Panel, BorderLayout.CENTER); Blob_Panel.setVisible(true); //Blob_Panel.repaint(); Blob_Panel.start(); JFrame mainFrame = FibersApp.getApplication().getMainFrame(); mainFrame.pack(); } // status bar initialization - message timeout, idle icon and busy animation, etc ResourceMap resourceMap = getResourceMap(); int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout"); messageTimer = new Timer(messageTimeout, new ActionListener() { public void actionPerformed(ActionEvent e) { statusMessageLabel.setText(""); } }); messageTimer.setRepeats(false); int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate"); for (int i = 0; i < busyIcons.length; i++) { busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]"); } busyIconTimer = new Timer(busyAnimationRate, new ActionListener() { public void actionPerformed(ActionEvent e) { busyIconIndex = (busyIconIndex + 1) % busyIcons.length; statusAnimationLabel.setIcon(busyIcons[busyIconIndex]); } }); idleIcon = resourceMap.getIcon("StatusBar.idleIcon"); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); // connecting action tasks to status bar via TaskMonitor TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext()); taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if ("started".equals(propertyName)) { if (!busyIconTimer.isRunning()) { statusAnimationLabel.setIcon(busyIcons[0]); busyIconIndex = 0; busyIconTimer.start(); } progressBar.setVisible(true); progressBar.setIndeterminate(true); } else if ("done".equals(propertyName)) { busyIconTimer.stop(); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); progressBar.setValue(0); } else if ("message".equals(propertyName)) { String text = (String) (evt.getNewValue()); statusMessageLabel.setText((text == null) ? "" : text); messageTimer.restart(); } else if ("progress".equals(propertyName)) { int value = (Integer) (evt.getNewValue()); progressBar.setVisible(true); progressBar.setIndeterminate(false); progressBar.setValue(value); } } }); this.getFrame().setSize(1000, 800); this.getFrame().setLocation(10, 10); this.getFrame().show(); }
7
public void borrar(String n){ //verifico que la lista tenga 1 nodo por lo menos if( raiz != null ){ //verifico si no es la raiz que le //quiero dar jabon if( raiz.nombre.equals(n)){ raiz = raiz.siguiente; } else{ //busquemos el nodo a borrar Nodo tmp = raiz; while(tmp.siguiente != null && !tmp.siguiente.nombre.equals(n)){ tmp = tmp.siguiente; } if( tmp.siguiente != null ){ //quede apuntando el que quiero borrar tmp.siguiente = tmp.siguiente.siguiente; } else{ System.out.println("NO EXISTE " + n); } } } }
5
public Grille (EnvironnementWator env){ super( env); Border blackline = BorderFactory.createLineBorder(Color.black,1); for(int i= 0 ; i < env.taille_envi;i++){ for(int j= 0 ; j < env.taille_envi;j++){ agent[i][j].setBorder(blackline); } } pan.setBorder(blackline); }
2
public void changeStyle(JTextPane section, String style) { int start = 0; int end = section.getText().length(); if (!section.getSelectedText().isEmpty()) { start = section.getSelectionStart(); end = section.getSelectedText().length(); } switch (style) { case "B": bold = (StyleConstants.isBold(attributes)) ? false : true; StyleConstants.setBold(attributes, bold); break; case "I": italic = (StyleConstants.isItalic(attributes)) ? false : true; StyleConstants.setItalic(attributes, italic); break; case "U": underline = (StyleConstants.isUnderline(attributes)) ? false : true; StyleConstants.setUnderline(attributes, underline); break; default: // Do nothing, never invoked } // Sets style in the view section.getStyledDocument().setCharacterAttributes(start, end, attributes, false); }
7
private void saveResults(String fileName) { for (int i = 0; i < meansOfMeans.length; i++) { meansOfMeans[i] += meansOfMeans[i] / ITERATION_PER_PARAMETERS; } Individual b = best.get(0); Individual w = worst.get(0); meansOfBests += b.getEvaluation(); meansOfWorst += w.getEvaluation(); for (int i = 1; i < ITERATION_PER_PARAMETERS; i++) { meansOfBests += best.get(i).getEvaluation(); meansOfWorst += worst.get(i).getEvaluation(); if (b.getEvaluation() > best.get(i).getEvaluation()) { b = best.get(i); } if (w.getEvaluation() < worst.get(i).getEvaluation()) { w = worst.get(i); } } meansOfBests = meansOfBests / ITERATION_PER_PARAMETERS; meansOfWorst = meansOfWorst / ITERATION_PER_PARAMETERS; try (FileWriter fw = new FileWriter(fileName + "-summary.csv")) { fw.append("Mean of best:" + meansOfBests + "\n"); fw.append("Mean of worst:" + meansOfWorst + "\n"); fw.append("Mean time of execution one:" + meanTime + "\n"); fw.append("Best :" + b.toString() + "\n"); fw.append("Worst:" + w.toString() + "\n"); fw.flush(); fw.close(); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } try (FileWriter fwMeans = new FileWriter(fileName + "-summary-means.csv")) { fwMeans.append("MeansInIteration\n"); for (long meansOfMean : meansOfMeans) { fwMeans.append(meansOfMean + "\n"); } fwMeans.flush(); fwMeans.close(); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } }
7