text
stringlengths
14
410k
label
int32
0
9
protected int getVersionIndex(String romId) { switch (romId) { case "BRBJ0": return 0; case "BRKJ0": return 1; case "BRBE0": case "BRBP0": return 2; case "BRKE0": case "BRKP0": return 3; default: throw new IllegalArgumentException("Unknown ROM ID \"" + romId + "\"."); } }
6
public static void main(String[] args) { Scanner number = new Scanner(System.in); System.out.println("Enter number to check Prime : "); int chk = number.nextInt(); int i; if( chk == 2){ System.out.println(chk +" Number is prime "); }else{ for( i=2; i<=chk-1; i++){ if (chk % i == 0 ) break; } if(chk != i){ System.out.println(chk + " Number is not Prime \n" ); }else{ System.out.println(chk + " Number is prime"); } } }
4
@Override public void resize(BufferedImage srcImage, BufferedImage destImage) throws NullPointerException { super.performChecks(srcImage, destImage); int currentWidth = srcImage.getWidth(); int currentHeight = srcImage.getHeight(); final int targetWidth = destImage.getWidth(); final int targetHeight = destImage.getHeight(); // If multi-step downscaling is not required, perform one-step. if ((targetWidth * 2 >= currentWidth) && (targetHeight * 2 >= currentHeight)) { Graphics2D g = destImage.createGraphics(); g.drawImage(srcImage, 0, 0, targetWidth, targetHeight, null); g.dispose(); return; } // Temporary image used for in-place resizing of image. BufferedImage tempImage = new BufferedImage( currentWidth, currentHeight, destImage.getType() ); Graphics2D g = tempImage.createGraphics(); g.setRenderingHints(RENDERING_HINTS); g.setComposite(AlphaComposite.Src); /* * Determine the size of the first resize step should be. * 1) Beginning from the target size * 2) Increase each dimension by 2 * 3) Until reaching the original size */ int startWidth = targetWidth; int startHeight = targetHeight; while (startWidth < currentWidth && startHeight < currentHeight) { startWidth *= 2; startHeight *= 2; } currentWidth = startWidth / 2; currentHeight = startHeight / 2; // Perform first resize step. g.drawImage(srcImage, 0, 0, currentWidth, currentHeight, null); // Perform an in-place progressive bilinear resize. while ( (currentWidth >= targetWidth * 2) && (currentHeight >= targetHeight * 2) ) { currentWidth /= 2; currentHeight /= 2; if (currentWidth < targetWidth) { currentWidth = targetWidth; } if (currentHeight < targetHeight) { currentHeight = targetHeight; } g.drawImage( tempImage, 0, 0, currentWidth, currentHeight, 0, 0, currentWidth * 2, currentHeight * 2, null ); } g.dispose(); // Draw the resized image onto the destination image. Graphics2D destg = destImage.createGraphics(); destg.drawImage(tempImage, 0, 0, targetWidth, targetHeight, 0, 0, currentWidth, currentHeight, null); destg.dispose(); }
8
private void generatePrimitiveWriter(CodeVisitor cw, Method method, String className) { String fieldName = makeFieldName(method); Class type = getClassOfMethodSubject(method); cw.visitVarInsn(ALOAD, 0); if (type == int.class || type == boolean.class || type == char.class || type == short.class || type == byte.class) { cw.visitVarInsn(ILOAD, 1); } else if (type == long.class) { cw.visitVarInsn(LLOAD, 1); } else if (type == float.class) { cw.visitVarInsn(FLOAD, 1); } else if (type == double.class) { cw.visitVarInsn(DLOAD, 1); } cw.visitFieldInsn(PUTFIELD, className, fieldName, Type.getDescriptor(type)); cw.visitInsn(RETURN); cw.visitMaxs(0, 0); }
8
public static String plumpColumnName(final String kin, final Set<String> seen) { String k = kin.toUpperCase(); final int colonIndex = k.indexOf(':'); if(colonIndex>0) { // get rid of any trailing : type info k = k.substring(0,colonIndex); } k = stompMarks(k).replaceAll("\\W+"," ").trim().replaceAll("\\s+","_"); if((k.length()<=0)||invalidColumnNames.contains(k.toUpperCase())||(!Character.isLetter(k.charAt(0)))) { k = columnPrefix + k; } if(seen.contains(k.toUpperCase())) { int i = 2; while(true) { String kt = k + "_" + i; if(!seen.contains(kt.toUpperCase())) { k = kt; break; } else { ++i; } } } seen.add(k.toUpperCase()); return k; }
7
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (response.isCommitted()) { return; } String uri = request.getRequestURI(); String context = request.getContextPath(); if (uri.endsWith("/favicon.ico")) { uri = "/favicon.ico"; } else if (context != null && ! "/".equals(context)) { uri = uri.substring(context.length()); } if (! uri.startsWith("/")) { uri = "/" + uri; } File file = new File(rootDirectory, uri); if (! file.exists()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } long lastModified = file.exists() ? file.lastModified() : start; long since = request.getDateHeader("If-Modified-Since"); if (since >= lastModified) { response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } byte[] data; InputStream input = new FileInputStream(file); try { ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } data = output.toByteArray(); } finally { input.close(); } response.setDateHeader("Last-Modified", lastModified); OutputStream output = response.getOutputStream(); output.write(data); output.flush(); }
9
@SuppressWarnings("unchecked") @Override public void refreshView(Map<String, Map<String, Object>> state) { // Extract the maps from the state // Map<String, Object> mapState = state.get("mapState"), dayState = state .get("dayState"); LinkedList<Map<String, Object>> elementList = (LinkedList<Map<String, Object>>) mapState .get("elements"); Map<String, Integer> count = new HashMap<String, Integer>(); Iterator<Map<String, Object>> elementIterator = elementList.iterator(); Map<String, Object> element; Integer x = (Integer) mapState.get("x"), y = (Integer) mapState .get("y"); for (int i = 0; i < y; i++) { for (int j = 0; j < x; j++) { element = elementIterator.next(); if (element != null) { if(count.get(element.get("type")) == null){ count.put((String)element.get("type"), 0); } if(element.get("state") != "Dead"){ count.put((String)element.get("type"), count.get(element.get("type"))+1); } } } } graph.update((int)(dayState == null ? 0 : dayState.get("day")), count); }
6
public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int inpay=sc.nextInt(); int iapay=sc.nextInt(); if(iapay < inpay){ System.out.println("null"); return; } if((iapay-inpay)>100){ System.out.println("null"); return; } if(iapay == inpay){ System.out.println("00000"); return; } else{ int ilpay=iapay-inpay; int i50=ilpay/50; int i20=(ilpay-50*i50)/20; int i10=(ilpay-50*i50-20*i20)/10; int i5=(ilpay-50*i50-20*i20-10*i10)/5; int i1=ilpay-50*i50-20*i20-10*i10-5*i5; System.out.println(i50+""+i20+""+i10+""+i5+""+i1); } }
3
@Override public void setNegativeFlag(boolean flagIsOn) { try { Image img; if (flagIsOn) { img = ImageIO.read(getClass().getResource("/resources/vdk-light-colour.png")); if (!CECIL_RESOLUTION.equals(CECIL_RESOLUTION_HIGH)) { img = img.getScaledInstance(ICON_SMALL.width, ICON_SMALL.height, Image.SCALE_SMOOTH); } lblNegative.getAccessibleContext().setAccessibleName("Negative flag on"); } else { img = ImageIO.read(getClass().getResource("/resources/vdk-light.png")); if (!CECIL_RESOLUTION.equals(CECIL_RESOLUTION_HIGH)) { img = img.getScaledInstance(ICON_SMALL.width, ICON_SMALL.height, Image.SCALE_SMOOTH); } lblNegative.getAccessibleContext().setAccessibleName("Negative flag off"); } lblNegative.setIcon(new ImageIcon(img)); } catch (IOException e) { System.out.println("Error creating buttons: could not set button icon"); } }
4
public void printInfos(Graphics g) { if (inEditor) level.printInfo(g, player.getPos(), player.getVisibility()); }
1
static void dradf4(int ido,int l1,float[] cc, float[] ch, float[] wa1, int index1, float[] wa2, int index2, float[] wa3, int index3){ int i,k,t0,t1,t2,t3,t4,t5,t6; float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4; t0=l1*ido; t1=t0; t4=t1<<1; t2=t1+(t1<<1); t3=0; for(k=0;k<l1;k++){ tr1=cc[t1]+cc[t2]; tr2=cc[t3]+cc[t4]; ch[t5=t3<<2]=tr1+tr2; ch[(ido<<2)+t5-1]=tr2-tr1; ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4]; ch[t5]=cc[t2]-cc[t1]; t1+=ido; t2+=ido; t3+=ido; t4+=ido; } if(ido<2)return; if(ido!=2){ t1=0; for(k=0;k<l1;k++){ t2=t1; t4=t1<<2; t5=(t6=ido<<1)+t4; for(i=2;i<ido;i+=2){ t3=(t2+=2); t4+=2; t5-=2; t3+=t0; cr2=wa1[index1+i-2]*cc[t3-1]+wa1[index1+i-1]*cc[t3]; ci2=wa1[index1+i-2]*cc[t3]-wa1[index1+i-1]*cc[t3-1]; t3+=t0; cr3=wa2[index2+i-2]*cc[t3-1]+wa2[index2+i-1]*cc[t3]; ci3=wa2[index2+i-2]*cc[t3]-wa2[index2+i-1]*cc[t3-1]; t3+=t0; cr4=wa3[index3+i-2]*cc[t3-1]+wa3[index3+i-1]*cc[t3]; ci4=wa3[index3+i-2]*cc[t3]-wa3[index3+i-1]*cc[t3-1]; tr1=cr2+cr4; tr4=cr4-cr2; ti1=ci2+ci4; ti4=ci2-ci4; ti2=cc[t2]+ci3; ti3=cc[t2]-ci3; tr2=cc[t2-1]+cr3; tr3=cc[t2-1]-cr3; ch[t4-1]=tr1+tr2; ch[t4]=ti1+ti2; ch[t5-1]=tr3-ti4; ch[t5]=tr4-ti3; ch[t4+t6-1]=ti4+tr3; ch[t4+t6]=tr4+ti3; ch[t5+t6-1]=tr2-tr1; ch[t5+t6]=ti1-ti2; } t1+=ido; } if((ido&1)!=0)return; } t2=(t1=t0+ido-1)+(t0<<1); t3=ido<<2; t4=ido; t5=ido<<1; t6=ido; for(k=0;k<l1;k++){ ti1=-hsqt2*(cc[t1]+cc[t2]); tr1=hsqt2*(cc[t1]-cc[t2]); ch[t4-1]=tr1+cc[t6-1]; ch[t4+t5-1]=cc[t6-1]-tr1; ch[t4]=ti1-cc[t1+t0]; ch[t4+t5]=ti1+cc[t1+t0]; t1+=ido; t2+=ido; t4+=t3; t6+=ido; } }
7
@Override public void run() { try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Waiter "); }
2
public static void addFriendship(String username1, String username2) { User user1 = getUserByUsername(username1.trim()); if (user1 == null) { System.out.println("User " + username1 + " NOT FOUND"); } User user2 = getUserByUsername(username2.trim()); if (user2 == null) { System.out.println("User " + username2 + " NOT FOUND"); } user1.addFriend(user2); }
2
public void run() { for (int id : Equipment.getAppearanceIds()) if (id != -1) equipIds.add(new PkItem(id, 1, false)); for (Item item : Inventory.getItems()) { if (item == null || item.getId() == -1) continue; PkItem pkItem = get(invItems, item.getId()); if (pkItem == null) invItems.add(new PkItem(item.getId(), item.getStackSize(), true)); else { pkItem.stacks = false; pkItem.amt += item.getStackSize(); } } }
6
public static Object getField(Field field, Object target) { try { return field.get(target); } catch (IllegalAccessException ex) { handleReflectionException(ex); throw new IllegalStateException( "Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage()); } }
1
@Override public int indexOf( Object elem ) { if( elem == null ) { for( int i = 0; i < size; i++ ) { if( elementData[i] == null ) { return i; } } } else { for( int i = 0; i < size; i++ ) { if( elem.equals( elementData[i] ) ) { return i; } } } return -1; }
5
@Override public void actionPerformed(ActionEvent e) { GuiThreatSelection guiThreatSelection = GuiThreatSelection.getInstance(this); List<ThreatClass> threats = guiThreatSelection.getSelectedThreats(); if (guiThreatSelection.getComponentMenuItem() instanceof MenuItemApplet) { String url = JOptionPane.showInputDialog("Enter URL below."); if (url != null) { List<Archive> archives = new WebPage(url).getArchives(); if (archives.size() > 0) for (Archive archive : archives) guiThreatSelection.getJScannerInstance().print( new ArchiveScanner(archive, threats) .getResults()); else guiThreatSelection.getJScannerInstance().print( "Could not find any archives on: " + url); } } else { Archive archive = new FileChooserArchive(this).getSelectedArchive(); if (archive != null) guiThreatSelection.getJScannerInstance().print( new ArchiveScanner(archive, threats).getResults()); } guiThreatSelection.dispose(); System.gc(); }
5
public void draw(Point point){ switch (selectedTool) { case IMAGE: createImage(point); break; case TEXT: createText(point); break; case LINE: drawLine(point); break; case RECTANGLE: drawRect(point); break; case ELLIPSE: drawEllipse(point); break; case MOVE: hand(point); break; case RESIZE: hand(point); break; case DELETE: delete(point); break; default: break; } }
8
public KeyPair generate() { BigInteger p, q, n, d; // 1. Generate a prime p in the interval [2**(M-1), 2**M - 1], where // M = CEILING(L/2), and such that GCD(p, e) = 1 int M = (L+1)/2; BigInteger lower = TWO.pow(M-1); BigInteger upper = TWO.pow(M).subtract(ONE); byte[] kb = new byte[(M+7)/8]; // enough bytes to frame M bits step1: while (true) { nextRandomBytes(kb); p = new BigInteger(1, kb).setBit(0); if ( p.compareTo(lower) >= 0 && p.compareTo(upper) <= 0 && Prime.isProbablePrime(p) && p.gcd(e).equals(ONE)) { break step1; } } // 2. Generate a prime q such that the product of p and q is an L-bit // number, and such that GCD(q, e) = 1 step2: while (true) { nextRandomBytes(kb); q = new BigInteger(1, kb).setBit(0); n = p.multiply(q); if ( n.bitLength() == L && Prime.isProbablePrime(q) && q.gcd(e).equals(ONE)) { break step2; } // TODO: test for p != q } // TODO: ensure p < q // 3. Put n = pq. The public key is (n, e). // 4. Compute the parameters necessary for the private key K (see // Section 2.2). BigInteger phi = p.subtract(ONE).multiply(q.subtract(ONE)); d = e.modInverse(phi); // 5. Output the public key and the private key. PublicKey pubK = new GnuRSAPublicKey(n, e); PrivateKey secK = new GnuRSAPrivateKey(p, q, e, d); return new KeyPair(pubK, secK); }
9
@Override public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException { if (!"/remoteConsole".equals(request.getPathInfo())) { // Not for us return false; } int contentLength = request.getContentLength(); if (contentLength <= 0) { throw new IOException("Content lenght required"); } InputStream inputStream = request.getInputStream(); byte[] buffer = new byte[contentLength]; int totalRead = 0; while (totalRead < contentLength) { int read = inputStream.read(buffer, totalRead, contentLength - totalRead); if (read == -1) { // More data was expected throw new EOFException(); } totalRead += read; } try { JSONArray messages = new JSONArray(new String(buffer, Charset.forName("UTF-8"))); for (int i = 0; i < messages.length(); i++) { JSONObject message = messages.getJSONObject(i); boolean error = message.optBoolean("isError"); String text = message.getString("message"); long time = message.getLong("time"); messageProcessor.processMessage(time, text, error); } } catch (JSONException e) { throw new IOException(e); } response.setStatus(200); response.getWriter().close(); return true; }
6
@Test public void shaMethodTest() throws IOException { String result = null; TeleSignRequest tr; if(!timeouts && !isHttpsProtocolSet) tr = new TeleSignRequest("https://rest.telesign.com", "/v1/phoneid/standard/" + PHONE_NUMBER, "GET", CUSTOMER_ID, SECRET_KEY); else if(timeouts && !isHttpsProtocolSet) tr = new TeleSignRequest("https://rest.telesign.com", "/v1/phoneid/standard/" + PHONE_NUMBER, "GET", CUSTOMER_ID, SECRET_KEY, connectTimeout, readTimeout); else if(!timeouts && isHttpsProtocolSet) tr = new TeleSignRequest("https://rest.telesign.com", "/v1/phoneid/standard/" + PHONE_NUMBER, "GET", CUSTOMER_ID, SECRET_KEY, HTTPS_PROTOCOL); else tr = new TeleSignRequest("https://rest.telesign.com", "/v1/phoneid/standard/" + PHONE_NUMBER, "GET", CUSTOMER_ID, SECRET_KEY, connectTimeout, readTimeout, HTTPS_PROTOCOL); tr.setSigningMethod(AuthMethod.SHA256); assertNotNull(tr); result = tr.executeRequest(); assertNotNull(result); Gson gson = new Gson(); PhoneIdStandardResponse response = gson.fromJson(result, PhoneIdStandardResponse.class); assertTrue(response.errors.length == 0); }
6
public void setCity(String city) { this.city = city; }
0
@Override public void deserialize(Buffer buf) { int limit = buf.readUShort(); positionsForChallengers = new short[limit]; for (int i = 0; i < limit; i++) { positionsForChallengers[i] = buf.readShort(); } limit = buf.readUShort(); positionsForDefenders = new short[limit]; for (int i = 0; i < limit; i++) { positionsForDefenders[i] = buf.readShort(); } teamNumber = buf.readByte(); if (teamNumber < 0) throw new RuntimeException("Forbidden value on teamNumber = " + teamNumber + ", it doesn't respect the following condition : teamNumber < 0"); }
3
public void testUnmatchedOpenParenthesis() throws Exception { String openParenString = "(3 + 5"; try { new Expression(openParenString); fail("Did not throw exception"); } catch (MalformedParenthesisException mpe) {} }
1
public void setUpComparisonBars() { overBars.clear(); underBars.clear(); float toScale = 0.05f; for (int i = 0; i < nbars; i++) { int over = beatMarket.histogram[i]; int under = marketBeat.histogram[i]; int absDiff = Math.abs(over - under); int top = (int) (frameH - SIDE_BUFFER - (int) (toScale * absDiff + 2)); int left = SIDE_BUFFER + BAR_BUFFER * i + ((int) barwidth) * i; int width = (int) (barwidth); int height = (int) (toScale * absDiff + 2); Rectangle2D.Float diff = new Rectangle2D.Float(left, top, width, height); if (over > under) { // green bar overBars.add(diff); } else if (under > over) { // red bar underBars.add(diff); } } }
3
public void setEntityDead(Entity var1) { if (var1.riddenByEntity != null) { var1.riddenByEntity.mountEntity((Entity) null); } if (var1.ridingEntity != null) { var1.mountEntity((Entity) null); } var1.setEntityDead(); if (var1 instanceof EntityPlayer) { this.playerEntities.remove((EntityPlayer) var1); this.updateAllPlayersSleepingFlag(); } }
3
public void setRefreshing(boolean refreshing) { if(refreshJob == null) { refreshJob = new RefreshJob(); } boolean prev = isRefreshing; isRefreshing = refreshing; if(refreshing && !prev) { Thread t = new Thread(refreshJob); t.start(); } }
3
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Perifericos)) { return false; } Perifericos other = (Perifericos) object; if ((this.idPeriferico == null && other.idPeriferico != null) || (this.idPeriferico != null && !this.idPeriferico.equals(other.idPeriferico))) { return false; } return true; }
5
@Test public void testGetDescriptionFirstPhone() { Map<String, Object> descriptionFirstPhone = new HashMap<String, Object>(); descriptionFirstPhone.put("name", "Cink Five"); descriptionFirstPhone.put("brandName", "Wiko"); descriptionFirstPhone.put("screenSize", 5); descriptionFirstPhone.put("screenType", ScreenType.RESISTIV); descriptionFirstPhone.put("version", AndroidPhoneVersion.ECLAIR); descriptionFirstPhone.put("id", firstPhone.getId()); descriptionFirstPhone.put("state", State.GOOD); Map<String, Map<Class<? extends IUser>, Integer>> limitsDescription = new HashMap<String, Map<Class<? extends IUser>, Integer>>(); Map<Class<? extends IUser>, Integer> copyLimitsForFirstPhone = new HashMap<Class<? extends IUser>, Integer>(); copyLimitsForFirstPhone.put(Student.class, new Integer(2)); copyLimitsForFirstPhone.put(Teacher.class, new Integer(10)); Map<Class<? extends IUser>, Integer> delayLimitsForFirstPhone = new HashMap<Class<? extends IUser>, Integer>(); delayLimitsForFirstPhone.put(Student.class, new Integer(2)); delayLimitsForFirstPhone.put(Teacher.class, new Integer(14)); Map<Class<? extends IUser>, Integer> durationLimitsForFirstPhone = new HashMap<Class<? extends IUser>, Integer>(); durationLimitsForFirstPhone.put(Student.class, new Integer(14)); durationLimitsForFirstPhone.put(Teacher.class, new Integer(30)); limitsDescription.put(Material.KEY_LIMIT_COPY, copyLimitsForFirstPhone); limitsDescription.put(Material.KEY_LIMIT_DELAY, delayLimitsForFirstPhone); limitsDescription.put(Material.KEY_LIMIT_DURATION, durationLimitsForFirstPhone); descriptionFirstPhone.put("limits", limitsDescription); assertEquals(descriptionFirstPhone, firstPhone.getDescription()); }
8
public static boolean distanciaUnaLetra (final String cad1, final String cad2){ if (cad1.length() == cad2.length() ){ final String cadena1 = cad1.toUpperCase(LOCALE_ES); final String cadena2 = cad2.toUpperCase(LOCALE_ES); for (int i = 0; i < cad1.length(); i++){ final StringBuilder test1 = new StringBuilder(); final StringBuilder test2 = new StringBuilder(); test1.append(cadena1); test2.append(cadena2); test1.setCharAt(i, 'X'); test2.setCharAt(i, 'X'); if (test1.toString().equals(test2.toString())){ return true; } } } else if (Math.abs(cad1.length() - cad2.length()) == 1){ String mayor = cad1.toUpperCase(LOCALE_ES); String menor = cad2.toUpperCase(LOCALE_ES); if (mayor.length() < menor.length()){ final String tmp = mayor; mayor = menor; menor = tmp; } for (int i = 0; i < mayor.length(); i++){ final StringBuilder test1 = new StringBuilder(); final StringBuilder test2 = new StringBuilder(); test1.append(mayor); test2.append(menor); test1.setCharAt(i, 'X'); test2.insert(i, 'X'); if (test1.toString().equals(test2.toString())){ return true; } } } return false; }
7
public void fill(byte[] b) { int coordinate = 0; storagePointer = NumberUtils.byteArrayToInt(Arrays.copyOfRange(b, coordinate, coordinate + 4)); coordinate += 4; int parent_storagePointer = NumberUtils.byteArrayToInt(Arrays.copyOfRange( b, coordinate, coordinate + 4)); coordinate += 4; if (parent_storagePointer > 0) { parent = new Node(storage); parent.storagePointer = parent_storagePointer; } count = b[coordinate]; coordinate += 1; isLeaf = b[coordinate] == 1 ? true : false; coordinate += 1; for (int i = 0; i < DATAITEMS_COUNT; i++) { if (i < count) { if (dataItems[i] == null) dataItems[i] = new DataItem(); dataItems[i].fill(Arrays.copyOfRange(b, coordinate, coordinate + DataItem.BYTE_LENGTH)); } coordinate += DataItem.BYTE_LENGTH; } for (int i = 0; i <= DATAITEMS_COUNT; i++) { if (!isLeaf && i <= count) { if (child[i] == null) child[i] = new Node(this.storage); child[i].storagePointer = NumberUtils.byteArrayToInt(Arrays.copyOfRange(b, coordinate, coordinate + 4)); } coordinate += 4; } }
9
public SampleResult runTest(JavaSamplerContext context) { SampleResult sampleResult = new SampleResult(); sampleResult.sampleStart(); String key = null ; if(keyRondom){ key = String.valueOf(String.valueOf(new Random().nextInt(keyNumLength)).hashCode()); }else{ key = String.valueOf(SequenceKey.getsequenceKey()); } try { if (methedType.equals("put")) { put = new Put(Bytes.toBytes(key)); put.setWriteToWAL(writeToWAL); for (int j = 0; j < cfs.length; j++) { for (int n = 0; n < qualifiers.length; n++) { put.add(Bytes.toBytes(cfs[j]), Bytes.toBytes(qualifiers[n]), Bytes.toBytes(values)); table.put(put); } } } else if (methedType.equals("get")) { get = new Get((key ).getBytes()); Result rs = table.get(get); } sampleResult.setSuccessful(true); } catch (Throwable e) { sampleResult.setSuccessful(false); } finally { sampleResult.sampleEnd(); } // // 返回是否处理成功 return sampleResult; }
6
public void save(Map map){ File f = new File("assets/maps/" + map.getName()); try { biEx.save(map, f); } catch (IOException ex) { Logger.getLogger(MapLoader.class.getName()).log(Level.SEVERE, null, ex); } }
1
* @return Returns true if the cell is bendable. */ public boolean isCellBendable(Object cell) { mxCellState state = view.getState(cell); Map<String, Object> style = (state != null) ? state.getStyle() : getCellStyle(cell); return isCellsBendable() && !isCellLocked(cell) && mxUtils.isTrue(style, mxConstants.STYLE_BENDABLE, true); }
3
@Override protected Class<?> loadClass(String name, boolean resolve) { try { if ("outpost.sim.Player".equals(name) || "outpost.sim.Point".equals(name) || "outpost.sim.Pair".equals(name) || "outpost.sim.movePair".equals(name)) return parent.loadClass(name); else return super.loadClass(name, resolve); } catch (ClassNotFoundException e) { return null; } }
6
@Override public void initialise() { for (int client = 0; client < 8; client++ ) { int arrival = masterAgent.agent.getClientPreference(client, TACAgent.ARRIVAL); int departure = masterAgent.agent.getClientPreference(client, TACAgent.DEPARTURE); int cheapAuctionNo = TACAgent.getAuctionFor(TACAgent.CAT_HOTEL, TACAgent.TYPE_CHEAP_HOTEL, arrival); int goodAuctionNo = TACAgent.getAuctionFor(TACAgent.CAT_HOTEL, TACAgent.TYPE_GOOD_HOTEL, departure); masterAgent.agent.setAllocation(cheapAuctionNo, masterAgent.agent.getAllocation(cheapAuctionNo)+1); masterAgent.agent.setAllocation(goodAuctionNo, masterAgent.agent.getAllocation(goodAuctionNo)+1); } // Initialize the bid arrays for (int i = 1 ; i <= 4; i++) { int expensiveAuctionID = TACAgent.getAuctionFor(TACAgent.CAT_HOTEL, TACAgent.TYPE_GOOD_HOTEL, i); Bid expensiveBid = new Bid(expensiveAuctionID); int cheapAuctionID = TACAgent.getAuctionFor(TACAgent.CAT_HOTEL, TACAgent.TYPE_CHEAP_HOTEL, i); Bid cheapBid = new Bid(cheapAuctionID); expensiveHotelBids[i] = expensiveBid; cheapHotelBids[i] = cheapBid; } // Bid the price and Assign type of hotel to the customer for (int i = 0; i < 8 ; i++) { Client client = masterAgent.clientList.get(i); int hotelval = masterAgent.agent.getClientPreference(i, TACAgent.HOTEL_VALUE); // If customer's value is more than 70, we will try to buy expensive hotel rooms if (hotelval > 70) { client.hotelAssignment = hotelType.expensiveHotel; System.out.println("Expensive hotel requested by client"+ i); } else { client.hotelAssignment = hotelType.cheapHotel; System.out.println("Cheap hotel requested by client"+ i); } // Assign Hotel for each night for (int j = client.arrivalDay; j < client.departureDay; j++) { //int auctionID; if (client.hotelAssignment == hotelType.expensiveHotel) { //auctionID = TACAgent.getAuctionFor(TACAgent.CAT_HOTEL, TACAgent.TYPE_GOOD_HOTEL, j); // calculate the price per room for this customer (add the hotel bonus if booking expensive hotel) float budgetPerNight = (HOTEL_BUDGET + client.hotelvalue) / (client.departureDay - client.arrivalDay); //Bid bidToAdd = new Bid(expensiveHotelBids[j]); expensiveHotelBids[j].addBidPoint(1, budgetPerNight); System.out.println("Submitted bid for expensive hotel on day " + j); } else { //auctionID = TACAgent.getAuctionFor(TACAgent.CAT_HOTEL, TACAgent.TYPE_CHEAP_HOTEL, j); // calculate the price per room for this customer float budgetPerNight = HOTEL_BUDGET / (client.departureDay - client.arrivalDay); //Bid bidToAdd = new Bid(cheapHotelBids[j]); cheapHotelBids[j].addBidPoint(1, budgetPerNight); System.out.println("Submitted bid for cheap hotel on day " + j); } } } // Submit the completed bids for (int i = 1 ; i <= 4; i++) { masterAgent.agent.submitBid(expensiveHotelBids[i]); masterAgent.agent.submitBid(cheapHotelBids[i]); // System.out.println(expensiveHotelBids[i].getQuantity()); // System.out.println(cheapHotelBids[i].getQuantity()); } //Allocation // for (int i = 0; i < 5; i++) // { // int alloc = masterAgent.agent.getAllocation(i) - masterAgent.agent.getOwn(i); // System.out.println("alloc"+ alloc); // } // // System.out.println("I am There"); // // Check for number of rooms about to win // Quote[] CH = new Quote[90]; // Quote[] EH = new Quote[90]; // int[] hqCheaphotel = new int[4]; // int[] hqGoodhotel = new int[4]; // System.out.println("I am here"); // for (int day = 1; day <5; day++) // { // CH[day] = new Quote(TACAgent.getAuctionFor(TACAgent.CAT_HOTEL, TACAgent.TYPE_CHEAP_HOTEL, day)); // hqCheaphotel[day] = CH[day].getHQW(); // System.out.println("Number of cheapHotels about to win : "+ hqCheaphotel[day] +"on day"+ day); // EH[day] = new Quote(TACAgent.getAuctionFor(TACAgent.CAT_HOTEL, TACAgent.TYPE_GOOD_HOTEL, day)); // hqGoodhotel[day] = EH[day].getHQW(); // System.out.println("Number of cheapHotels about to win : "+ hqGoodhotel[day] +"on day"+ day ); // } // int day = 1; // System.out.println("I am somewhere"); // while (day < 5) // { // int auctionID = TACAgent.getAuctionFor(TACAgent.CAT_HOTEL, TACAgent.TYPE_CHEAP_HOTEL, day); // Bid B = new Bid(auctionID); // while(CH[day].getHQW() < hqCheaphotel[day]) // { // System.out.println("increase the bid for cheap hotels"); // float bidprice = CH[day].getBidPrice(); // B.addBidPoint(1, bidprice + 10); // masterAgent.agent.submitBid(B); // } // while (EH[day].getHQW() < hqGoodhotel[day]) // { // System.out.println("increase the bid for good hotels"); // float bidprice = EH[day].getBidPrice(); // B.addBidPoint(1, bidprice + 10); // masterAgent.agent.submitBid(B); // } // } }
7
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(FormCadastrarTurmas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FormCadastrarTurmas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FormCadastrarTurmas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FormCadastrarTurmas.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 FormCadastrarTurmas().setVisible(true); } }); }
6
private void initToolbar(JToolBar toolBar) { //NEW BUTTON - creates a new simulation with a new turing machines JButton btnNew = createIconButton("/icons/ic_new.png", TOOLBAR_BUTTONSIZE); btnNew.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TuringMachineCreationDialog creationDialog = new TuringMachineCreationDialog(); creationDialog.setVisible(true); if (!creationDialog.canceled) { addSimulation(creationDialog.name, creationDialog.type, creationDialog.alphabet); } } }); toolBar.add(btnNew); //LOAD BUTTON - loads the current simulation JButton btnLoad = createIconButton("/icons/ic_open.png", TOOLBAR_BUTTONSIZE); btnLoad.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { loadRoutine(); } }); toolBar.add(btnLoad); //SAVE BUTTON - saves the current simulation JButton btnSave = createIconButton("/icons/ic_save.png", TOOLBAR_BUTTONSIZE); btnSave.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveRoutine(); } }); toolBar.add(btnSave); //ZOOM IN BUTTON - zooms into the tape JButton btnZoomIn = createIconButton("/icons/ic_zoom_in.png", TOOLBAR_BUTTONSIZE); btnZoomIn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ContentPanel content = (ContentPanel) tpSimTabs.getSelectedComponent(); content.getTuringPanel().zoomIn(); update(null, "zoomIn"); } }); toolBar.add(btnZoomIn); //ZOOM OUT BUTTON - zooms out of the tape JButton btnZoomOut = createIconButton("/icons/ic_zoom_out.png", TOOLBAR_BUTTONSIZE); btnZoomOut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ContentPanel content = (ContentPanel) tpSimTabs.getSelectedComponent(); content.getTuringPanel().zoomOut(); update(null, "zoomOut"); } }); toolBar.add(btnZoomOut); //ADD STATE BUTTON - creates and adds a new state JButton btnAddState = createIconButton("/icons/ic_addState.png", TOOLBAR_BUTTONSIZE); btnAddState.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { //Create Dialog. Add State, if dialog has not been cancelled StateCreationDialog dialog = new StateCreationDialog(); dialog.setVisible(true); if (!dialog.canceled) { TuringEditor editor = main.getSimulationController().getSimulation(foregroundID).getEditor(); try { editor.addState(dialog.name); } catch (DuplicateStateException e) { JOptionPane.showMessageDialog(main, "There already exists a state with this name"); } } } }); toolBar.add(btnAddState); //REMOVE STATE BUTTON - removes the selected state JButton btnRemoveState = createIconButton("/icons/ic_removeState.png", TOOLBAR_BUTTONSIZE); btnRemoveState.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { ContentPanel content = (ContentPanel) tpSimTabs.getSelectedComponent(); State selected = content.getStatePanel().getSelectedState(); if (selected != null) { try { main.getSimulationController().getSimulation(foregroundID).getEditor().removeState(selected.getID()); content.getStatePanel().hideButton(); } catch (UnresolvedReferenceException e) { JOptionPane.showMessageDialog(main, "Cannot delete: this state is referenced in another state's transition table"); } } } }); toolBar.add(btnRemoveState); //ABOUT BUTTON - opens a dialog for various simulation-related information JButton btnAbout = createIconButton("/icons/ic_settings.png", TOOLBAR_BUTTONSIZE); btnAbout.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { AboutDialog dialog = new AboutDialog(); dialog.setVisible(true); } }); toolBar.add(btnAbout); }
5
public void read() throws IOException { if (!cached) { next(); } cached = false; }
1
@Post public Representation accept(Representation entity) throws IOException { try { host = (getRequestAttributes().get("host") == null) ? host : ((String) getRequestAttributes().get("host")).trim(); port = (getRequestAttributes().get("port") == null) ? port : Integer.parseInt(((String) getRequestAttributes().get("port")).trim()); option = (getRequestAttributes().get("option") == null) ? "" : ((String) getRequestAttributes().get("option")).trim(); strXml = (entity == null) ? null : ((String) entity.getText()).trim(); if(option.equals("saveAndRun")) { if(IpcClient.getService(host, port, "Firewall").saveAndRun(strXml, null)) return new StringRepresentation("<message>Firewall saved and running</message>", MediaType.TEXT_XML); else return new StringRepresentation("<error>Error: Firewall saved and running</error>", MediaType.TEXT_XML); } else if(option.equals("save")) { if(IpcClient.getService(host, port, "Firewall").save(strXml)) return new StringRepresentation("<message>Firewall saved</message>", MediaType.TEXT_XML); else return new StringRepresentation("<error>Error: firewall saving</error>", MediaType.TEXT_XML); } else return new StringRepresentation("<error>Invalid Option POST</error>", MediaType.TEXT_XML); } catch(Exception e) { e.printStackTrace(); return new StringRepresentation("<error>Firewall Error Exception</error>", MediaType.TEXT_XML); } }
9
private String createUserList() { FilmothekModel model = new FilmothekModel(); ArrayList<UserBean> users = model.getUsers(); String userList = "<select name='userID' size='1'>"; for (Iterator<UserBean> it = users.iterator(); it.hasNext();) { UserBean userBean = it.next(); if(userBean.getRole().equals(UserBean.ROLE_USER)){ userList += " <option value='"+userBean.getId()+"'>"+userBean.getName()+"</option>"; } } userList += "</select>"; return userList; }
2
public Image[] getCells(ImageRetriever paramImageRetriever, int paramInt1, int paramInt2) { Integer localInteger = new Integer(paramInt1); if (this.animationList == null) this.animationList = new Hashtable(); Object localObject = this.animationList.get(localInteger); Image[] arrayOfImage; if (localObject == null) { Vector localVector = new Vector(); localVector.addElement(paramImageRetriever.getImage("com/templar/games/stormrunner/media/images/robot/assembly/" + getID() + "/0_" + paramInt1 + ".gif")); if (paramInt1 % 90 == 0) for (int i = 1; i < getAnimationFrames(); i++) localVector.addElement(paramImageRetriever.getImage("com/templar/games/stormrunner/media/images/robot/assembly/" + getID() + "/" + i + "_" + paramInt1 + ".gif")); arrayOfImage = new Image[localVector.size()]; localVector.copyInto(arrayOfImage); this.animationList.put(localInteger, arrayOfImage); } else { arrayOfImage = (Image[])localObject; }return arrayOfImage; }
4
@Override public String toString(){ StringBuilder sb = new StringBuilder(); // start line String name = this.getNameAndupspace(); if(null!=name){ sb.append(name); }else{ // please set directiveName return null; } for(int i=0;i<listParam.size();i++){ if(null != listParam.get(i)){ String sbin = listParam.get(i).toString(); // System.out.println(i+" Elements:" + myElements.get(i).toString()); if(null == listParam.get(i).getUpSpace()){ sb.append(" "); }else{ sb.append(listParam.get(i).getUpSpace()); } sb.append(sbin); } } //end directive sb.append(";"); sb.append("\n"); // System.out.println("sb.toString():" + sb.toString()); return sb.toString(); }
4
@Override public void executeMsg(final Environmental myHost, final CMMsg msg) { super.executeMsg(myHost,msg); if((affected instanceof Item) &&(((Item)affected).owner() instanceof Room) &&(((Room)((Item)affected).owner()).isContent((Item)affected)) &&(msg.sourceMinor()==CMMsg.TYP_SPEAK) &&(invoker!=null) &&(invoker.location()!=((Room)((Item)affected).owner())) &&(msg.othersMessage()!=null)) invoker.executeMsg(invoker,msg); }
7
private void treeClicked(MouseEvent e) { TreePath selPath = this.tree.getPathForLocation(e.getX(), e.getY()); if (selPath == null) return; DefaultMutableTreeNode node = (DefaultMutableTreeNode) selPath .getLastPathComponent(); Object userObj = node.getUserObject(); if (e.getClickCount() == 2 && e.getModifiers() == InputEvent.BUTTON1_MASK) { if (userObj instanceof FileItem) { FileItem ca =(FileItem)userObj; if (ca.getFullNameA().endsWith(".class") && ca.getFullNameB().endsWith(".class") && ca.getStyle() != Style.RED && ca.getStyle() != Style.YELLOW) { this.selectedItem = ca; try { byte[] dataA = this.filesetA.getData(ca.getFullNameA()); byte[] dataB = this.filesetB.getData(ca.getFullNameB()); ClassFile cfA = Disassembler.readClass(dataA); ClassFile cfB = Disassembler.readClass(dataB); this.comparePanel.setClassFiles(cfA, cfB); this.tabbedPane.setSelectedComponent(this.comparePanel); } catch (Exception ex) { SystemFacade.getInstance().handleException(ex); } } } } }
9
public static int priority(String operator) { if (operator.equals("+") || operator.equals("-")) return 1; else if (operator.equals("*") || operator.equals("/")) return 2; else if (operator.equals("^")) return 3; else return 0; }
5
public int minCut(String s) { // Start typing your Java solution below // DO NOT write main() function int n = s.length(); if (n <= 1) return 0; boolean[][] res = new boolean[n][n]; int[] dp = new int[n]; for (int i = 0; i < n; i++) res[i][i] = true; // 第一层初始化 for (int i = 1; i < n; i++) { int min = Integer.MAX_VALUE; for (int j = i; j >= 0; j--) { if (s.charAt(j) == s.charAt(i) && (i - j < 2 || res[i - 1][j + 1])) { // key_condition res[i][j] = true; if (j == 0) min = 0; else min = Math.min(min, 1 + dp[j - 1]); } } dp[i] = min; } return dp[n - 1]; }
8
@Test public void testInvert() { /* * Test with constant values. */ gf = new GF2N(283); PolynomialGF2N polyGF = new PolynomialGF2N(gf); Polynomial polynomial1 = new Polynomial(3); polynomial1.setElement(0, 195); polynomial1.setElement(1, 103); polynomial1.setElement(2, 117); Polynomial polynomial2 = new Polynomial(6); polynomial2.setElement(0, 163); polynomial2.setElement(1, 221); polynomial2.setElement(2, 7); polynomial2.setElement(3, 51); polynomial2.setElement(4, 197); polynomial2.setElement(5, 172); Polynomial resultPolynomial = new Polynomial(5); resultPolynomial.setElement(0, 32); resultPolynomial.setElement(1, 142); resultPolynomial.setElement(2, 85); resultPolynomial.setElement(3, 232); resultPolynomial.setElement(4, 71); assertEquals("Inverse of polynomials with constant values failed.", resultPolynomial, polyGF.invert(polynomial1, polynomial2)); polynomial1.setElement(0, 180); polynomial1.setElement(1, 222); polynomial1.setElement(2, 52); polynomial2.setElement(0, 106); polynomial2.setElement(1, 164); polynomial2.setElement(2, 241); polynomial2.setElement(3, 37); polynomial2.setElement(4, 108); polynomial2.setElement(5, 123); resultPolynomial.setElement(0, 205); resultPolynomial.setElement(1, 59); resultPolynomial.setElement(2, 72); resultPolynomial.setElement(3, 255); resultPolynomial.setElement(4, 128); assertEquals("Inverse of polynomials with constant values failed.", resultPolynomial, polyGF.invert(polynomial1, polynomial2)); /* * Basic test. */ gf = new GF2N(4194307l); polyGF = new PolynomialGF2N(gf); for (int x = 0; x < 128; x++) { try { int length1 = rn.nextInt(128) + 1; int length2 = rn.nextInt(128) + 1 + length1; polynomial1 = new Polynomial(length1, gf.getFieldSize()); polynomial2 = new Polynomial(length2, gf.getFieldSize()); //Test: inverse(a) % x = b => ( a * b ) % x = 1 Polynomial inverse = polyGF.invert(polynomial1, polynomial2); Polynomial remainder = new Polynomial(length1); Polynomial result = polyGF.divide(polyGF.multiply(polynomial1, inverse), polynomial2, remainder); remainder.clearZeroValues(); assertEquals("Inverse result is wrong.", new Polynomial(1, 1), remainder); try { polyGF.invert(polynomial2, polynomial1); fail("MathArithmeticException should be thrown, " + "when moduloPolynomial is shorter than polynomial"); } catch (MathArithmeticException ex) { //OK } } catch (MathArithmeticException ex) { //OK, some polynomials cannot be inverted with some modulos } } //Tests in binary finite field polyGF = new PolynomialGF2N(3); for (int x = 0; x < 128; x++) { try { int length1 = rn.nextInt(128) + 1; int length2 = rn.nextInt(128) + 1 + length1; polynomial1 = new Polynomial(length1, 1); polynomial2 = new Polynomial(length2, 1); //Test: inverse(a) % x = b => ( a * b ) % x = 1 Polynomial inverse = polyGF.invert(polynomial1, polynomial2); Polynomial remainder = new Polynomial(length1); Polynomial result = polyGF.divide(polyGF.multiply(polynomial1, inverse), polynomial2, remainder); remainder.clearZeroValues(); assertEquals("Inverse result is wrong.", new Polynomial(1, 1), remainder); try { polyGF.invert(polynomial2, polynomial1); fail("MathArithmeticException should be thrown, " + "when moduloPolynomial is shorter than polynomial"); } catch (MathArithmeticException ex) { //OK } } catch (MathArithmeticException ex) { //OK, some polynomials cannot be inverted with some modulos } } }
6
private void connectForest() { List forest = new ArrayList(); Stack stack = new Stack(); NodeList tree; graph.nodes.resetFlags(); for (int i = 0; i < graph.nodes.size(); i++) { Node neighbor, n = graph.nodes.getNode(i); if (n.flag) continue; tree = new NodeList(); stack.push(n); while (!stack.isEmpty()) { n = (Node) stack.pop(); n.flag = true; tree.add(n); for (int s = 0; s < n.incoming.size(); s++) { neighbor = n.incoming.getEdge(s).source; if (!neighbor.flag) stack.push(neighbor); } for (int s = 0; s < n.outgoing.size(); s++) { neighbor = n.outgoing.getEdge(s).target; if (!neighbor.flag) stack.push(neighbor); } } forest.add(tree); } if (forest.size() > 1) { // connect the forest graph.forestRoot = new Node("the forest root"); //$NON-NLS-1$ graph.nodes.add(graph.forestRoot); for (int i = 0; i < forest.size(); i++) { tree = (NodeList) forest.get(i); graph.edges.add(new Edge(graph.forestRoot, tree.getNode(0), 0, 0)); } } }
9
public static void listMembers(){ ArrayList<beansMiembro> listaMembers = null; listaMembers = ManejadorMiembros.getInstancia().getLista(); if(listaMembers.size() >= 0){ for(beansMiembro miembro : listaMembers){ mostrarMiembro(miembro, 0); verAdentro(miembro,1); } }else{ System.out.println("No hay miembros ingresados."); } }
2
private static void test(String input, String output, int v, String dir) { int n = input.length(); boolean[] voters = new boolean[n]; int i; /* convert the string into an array of booleans */ for (i = 0; i < n; i++) { voters[i] = (input.charAt(i) == 'A'); } Opinion.update(voters, v); /* check the output */ for (i = 0; i < n; i++) { if ((output.charAt(i) == 'A') && (!voters[i])) { error(input, output, v, voters, dir); break; } else if ((output.charAt(i) == 'B') && (voters[i])) { error(input, output, v, voters, dir); break; } } if (i == n) System.out.printf("Success: %s @ %d %s => %s\n", input, v, dir, output); System.out.println(); }
7
public void doGet(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html");//设置服务器响应的内容格式 // response.setCharacterEncoding("gb2312");//设置服务器响应的字符编码格式。 DButil ab = new DButil(); try { PrintWriter pw = response.getWriter(); String tep=new String(request.getParameter("tid").getBytes("ISO-8859-1")); String name = new String(request.getParameter("name").getBytes("ISO-8859-1")); int id=Integer.valueOf(tep); System.out.println("update id"+id); if(ab.update(id,name)) { request.getRequestDispatcher("succ.jsp?info='update success'").forward(request, response); } } catch (Exception e) { } }
2
public Type getType(Environment<Type> env) throws TypeIllegalException, TypeEnvironmentException { Token op = getChild(1).jjtGetFirstToken(); Type left = getChild(0).getType(env); Type right = getChild(2).getType(env); if (op.kind == PseuCoParserConstants.PLUSASSIGN) { if (right.getKind() == Type.STRING) { if (left.getKind() != Type.STRING) throw new TypeIllegalException(left, "You tried to assign " + right + " to " + left, getChild(2) .jjtGetFirstToken()); } else if (right.getKind() == Type.INT) { if (left.getKind() != Type.INT && left.getKind() != Type.STRING) throw new TypeIllegalException(left, "You tried to assign " + right + " to " + left, getChild(2) .jjtGetFirstToken()); } else throw new TypeIllegalException(left, "Operator \"+=\" is only allowed with integers and strings, but not " + right, jjtGetFirstToken()); return left; } else if (op.kind != PseuCoParserConstants.ASSIGN) { if (left.getKind() != Type.INT) throw new TypeIllegalException(left, "Operator \"" + op.image + "\" is only allowed with integers, but not " + left, jjtGetFirstToken()); } if (!right.isAssignableTo(left)) throw new TypeIllegalException(right, "You tried to assign " + right + " to " + left, getChild(2).jjtGetFirstToken()); return left; }
9
public static String guessEmotion(String s) { int sad = 0; int happy = 0; int angry = 0; String v = s.toLowerCase().trim(); String result = "I cant guess your emotion."; File file = new File("help/emo.txt"); ArrayList<String> emoTXT = IOTools.readFile(file); for (String n : emoTXT) { String args[] = n.split(";"); System.out.println(args[0] + " " + args[1]); if (v.contains(args[0])) { switch (args[1]) { case "s": sad++; System.out.println("sad"); break; case "h": happy++; break; case "a": angry++; break; } } } int emos[] = {sad, happy, angry}; int emoti = IOTools.getLargest(emos); if (emoti == 0) { return result; } if (emoti == sad) { result = "Sad"; }else if (emoti == happy) { result = "Happy"; }else if (emoti == angry) { result = "Angry"; } return result; }
9
@Override public ZemObject eval(Interpreter interpreter) { if(arguments.size() < 1){ return null; } Node node = arguments.get(0); UserFunction fun = null; if(node instanceof VariableNode){ fun = (UserFunction) interpreter.getSymbolTable().get(((VariableNode)node).getName()); } if(node instanceof LambdaNode){ fun = (UserFunction)((LambdaNode)node).eval(interpreter); } if(fun == null){ return null; } if(fun.getParameterCount() != 1){ return null; } String continuationName = fun.getParameterName(0); List<ZemObject> args = new ArrayList<ZemObject>(1); args.add(new ZemNumber("99")); Interpreter localInterpreter = new Interpreter(); localInterpreter.setSymbolTable(fun.getEnv()); return localInterpreter.callFunction(continuationName, args, getPosition()); }
5
public static byte[] Kinverse(byte[] t, BigInteger n, int L) { byte[] output = new byte[L]; for (int i = 0; i < L; i++) { output[i] = t[(int) kappa(t.length, n, i + 1)]; } return output; }
1
@Override public void parseXML(String xml) { final List<XMLLibrary.XMLTag> V=CMLib.xml().parseAllXML(xml); if((V==null)||(V.size()==0)) return; final List<XMLLibrary.XMLTag> xV=CMLib.xml().getContentsFromPieces(V,"AREAS"); root.clear(); String ID=null; String NUMS=null; if((xV!=null)&&(xV.size()>0)) for(int x=0;x<xV.size();x++) { final XMLTag ablk=xV.get(x); if((ablk.tag().equalsIgnoreCase("AREA"))&&(ablk.contents()!=null)) { ID=ablk.getValFromPieces("ID").toUpperCase(); NUMS=ablk.getValFromPieces("NUMS"); if((NUMS!=null)&&(NUMS.length()>0)) root.put(ID,new LongSet().parseString(NUMS)); else root.put(ID,null); } } }
9
public void doTraining(Team team) { // with injuries int nofPlayers = team.getNofPlayers(); for (int i = 0; i < nofPlayers; i++) { Player player = team.getPlayer(i); int ranRange; if (getEffort() == Effort.EASY) { ranRange = 230; } else if (getEffort() == Effort.NORMAL) { ranRange = 200; } else { assert (getEffort() == Effort.FULL); ranRange = 170; } if (player.getHealth().getInjury() == 0 && Util.random(ranRange) == 0) { if (Util.random(2) > 0) { // injury String s = Util.getModelResourceBundle().getString("L_INJURY_TRAINING"); player.getHealth().setInjury(); player.getHealth().setHurt(0); s += player.getLastName(); team.getMessages().add(s); } else { // condition necessary for lineup injured players (!) // hurt player.getHealth().setHurt(); } } } }
6
public String getName() { return name; }
0
@Override protected boolean shouldBlock(Entity e) { if (e instanceof Bullet) return false; if ((e instanceof Mob) && !(e instanceof RailDroid) && !((Mob) e).isNotFriendOf(owner)) return false; return e != owner; }
4
@Override public void deserialize(Buffer buf) { alignmentSide = buf.readByte(); alignmentValue = buf.readByte(); if (alignmentValue < 0) throw new RuntimeException("Forbidden value on alignmentValue = " + alignmentValue + ", it doesn't respect the following condition : alignmentValue < 0"); alignmentGrade = buf.readByte(); if (alignmentGrade < 0) throw new RuntimeException("Forbidden value on alignmentGrade = " + alignmentGrade + ", it doesn't respect the following condition : alignmentGrade < 0"); dishonor = buf.readUShort(); if (dishonor < 0 || dishonor > 500) throw new RuntimeException("Forbidden value on dishonor = " + dishonor + ", it doesn't respect the following condition : dishonor < 0 || dishonor > 500"); characterPower = buf.readInt(); if (characterPower < 0) throw new RuntimeException("Forbidden value on characterPower = " + characterPower + ", it doesn't respect the following condition : characterPower < 0"); }
5
private static void createStone(int width, int height) { for(int x = 0; x < width; x++) { for(int y = stoneBoundary; y < height; y++) { blockSheet[x][y] = World.STONE; } } }
2
public void printArray(PrintableStringWriter stream) { { two_D_array self = this; { int nofRows = self.nofRows; int nofColumns = self.nofColumns; int limit = 9; stream.print("|i|["); { int row = Stella.NULL_INTEGER; int iter000 = 0; int upperBound000 = nofRows - 1; loop000 : for (;iter000 <= upperBound000; iter000 = iter000 + 1) { row = iter000; stream.print("["); { int column = Stella.NULL_INTEGER; int iter001 = 0; int upperBound001 = nofColumns - 1; loop001 : for (;iter001 <= upperBound001; iter001 = iter001 + 1) { column = iter001; stream.print((self.theArray)[((row * self.nofColumns) + column)]); if (column > limit) { stream.print(" ...]"); break loop001; } else if (column < (nofColumns - 1)) { stream.print(" "); } else { stream.print("]"); } } } if (row > limit) { stream.print(" ...]"); break loop000; } else if (row < (nofRows - 1)) { stream.print(" "); } else { stream.print("]"); } } } } } }
6
int afterRoot() throws IOException { int n = in.next(); switch (n) { case ' ': case '\t': case '\r': case '\n': in.back(); String ws = parseWhitespace(in); if (!isIgnoreWhitespace()) { set(JSONEventType.WHITESPACE, ws, false); } return AFTER_ROOT; case -1: return -1; case '{': case '[': if (isInterpretterMode()) { in.back(); return BEFORE_ROOT; } default: throw createParseException(in, "json.parse.UnexpectedChar", (char)n); } }
9
@Override public void setDataObject(IRemoteCallObjectData data) { this.data = data; }
0
public void setOptions(String[] options) throws Exception { String numFolds = Utils.getOption('F', options); if (numFolds.length() != 0) { setNumFolds(Integer.parseInt(numFolds)); } else { setNumFolds(0); } String numRuns = Utils.getOption('R', options); if (numRuns.length() != 0) { setNumRuns(Integer.parseInt(numRuns)); } else { setNumRuns(1); } String thresholdString = Utils.getOption('P', options); if (thresholdString.length() != 0) { setWeightThreshold(Integer.parseInt(thresholdString)); } else { setWeightThreshold(100); } String precisionString = Utils.getOption('L', options); if (precisionString.length() != 0) { setLikelihoodThreshold(new Double(precisionString). doubleValue()); } else { setLikelihoodThreshold(-Double.MAX_VALUE); } String shrinkageString = Utils.getOption('H', options); if (shrinkageString.length() != 0) { setShrinkage(new Double(shrinkageString). doubleValue()); } else { setShrinkage(1.0); } setUseResampling(Utils.getFlag('Q', options)); if (m_UseResampling && (thresholdString.length() != 0)) { throw new Exception("Weight pruning with resampling"+ "not allowed."); } super.setOptions(options); }
7
private void toPixel(int[][] matrix, int h, int w) { for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { double re = fd[j * h + i].re(); double im = fd[j * h + i].im(); int ii = 0, jj = 0; int temp = (int) (Math.sqrt(re * re + im * im) / 100); if (temp > 255) temp = 255; if (i < h / 2) { ii = i + h / 2; } else { ii = i - h / 2; } if (j < w / 2) { jj = j + w / 2; } else { jj = j - w / 2; } matrix[ii][jj] = temp; } } }
5
public Board boardEquiv() { Board b = new Board(); for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { DerpyPiece p = arr[x][y]; boolean pieceColor = p.getColor(); Piece db = null; if (p instanceof DerpyBishop) { db = new Bishop(pieceColor); } else if (p instanceof DerpyBlank) { db = new Blank(true); } else if (p instanceof DerpyKing) { db = new King(pieceColor); } else if (p instanceof DerpyKnight) { db = new Knight(pieceColor); } else if (p instanceof DerpyPawn) { db = new Pawn(pieceColor); } else if (p instanceof DerpyQueen) { db = new Queen(pieceColor); } else if (p instanceof DerpyRook) { db = new Rook(pieceColor); } else { System.out.println("boardEquiv did something dumb."); } b.getBoardArray()[x][y] = db; } } return b; }
9
int evaluateState(Checker[][] state) { int whiteNumber = 0; int blackNumber = 0; for (int row = 0; row < 8; row++) { for (int col = 0; col < 4; col++) { if (state[row][col] != null) { if (state[row][col].getColor() == 1) { whiteNumber++; if (state[row][col].isKing()) { whiteNumber += 2; } } if (state[row][col].getColor() == -1) { blackNumber++; if (state[row][col].isKing()) { blackNumber += 2; } } } } } if (whiteNumber == 0) { return -100; } else if (blackNumber == 0) { return 100; } else { return whiteNumber - blackNumber; } }
9
public void setPrice(double price) { if (price <= 0) { throw new IllegalArgumentException("Price should be bigger than zero"); } this.price = price; }
1
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DataStructure that = (DataStructure) o; if (calibrationKey != that.calibrationKey) return false; if (implementedChannels != that.implementedChannels) return false; if (majorVersion != that.majorVersion) return false; if (standartFamily != that.standartFamily) return false; return true; }
7
public boolean deathChecker() { if (state == GestureState.LIFE || state == GestureState.DEATH) { // If hand is below shoulder if (usingLeftArm) { if ((GestureInfo.gesturePieces[GestureInfo.LEFT_ARM_ANGLE_DECREASING]) || (!GestureInfo.gesturePieces[GestureInfo.LEFT_HAND_NEAR_HEAD] && GestureInfo.gesturePieces[GestureInfo.LEFT_HAND_STILL])) { final PVector diffHand = PVector.sub(joints[GestureInfo.LEFT_HAND], prevJoints[GestureInfo.LEFT_HAND]); usingLeftArm = true; tempo += diffHand.mag(); duration++; return true; } } else if ((GestureInfo.gesturePieces[GestureInfo.RIGHT_ARM_ANGLE_DECREASING]) || (!GestureInfo.gesturePieces[GestureInfo.RIGHT_HAND_NEAR_HEAD] && GestureInfo.gesturePieces[GestureInfo.RIGHT_HAND_STILL])) { final PVector diffHand = PVector.sub(joints[GestureInfo.RIGHT_HAND], prevJoints[GestureInfo.RIGHT_HAND]); usingLeftArm = false; tempo += diffHand.mag(); duration++; return true; } } return false; }
9
private void endAudio(String to) { if (to.equals("slide")) slide.addEntity(audio); else if (to.equals("quizslide")) quizSlide.addEntity(audio); else if (to.equals("scrollpane")) scrollPane.addEntity(audio); else if (to.equals("feedback")) quizSlide.addFeedback(audio); }
4
public Rectangle getSecondCorner() { return secondCorner; }
0
@Override public void execute() { Socket s = null; try { while (!stop && !runningThread.isInterrupted()) { try { s = serverSocket.accept(); } catch (SocketException se) { log.info("Received a shutdown request: " + se); stop = true; } catch (IOException ioe) { log.error("IO-error while waiting for new socket connection.", ioe); // TODO: Check if server-socket should be restarted, see also // http://stackoverflow.com/questions/3028543/what-to-do-when-serversocket-throws-ioexception-and-keeping-server-running } if (s == null) continue; socketExchanger.offer(s); s = null; } } catch (InterruptedException ie) { // Can happen when socketExchanger.offer(s) is blocking. log.info("Socket server interrupted."); } catch (Throwable t) { // Should this be fatal? log.error("Unexpected error encountered, socket server stopping!", t); runtimeError = t; } finally { closeServerSocket(); // if an InterruptedException occurred a new socket might have been left dangling. closeSocket(s); socketExchanger.close(); if (exitOnError && runtimeError != null) { runningThread = null; System.exit(1); } } }
9
public boolean login() { if(!loaded || username.isEmpty() || password.isEmpty()) return false; Users.addUser(this); logins++; loggedIn = true; save(); System.out.println(username+" has logged in."); return true; }
3
public int longestValidParentheses(String s) { // Start typing your Java solution below // DO NOT write main() function char[] c = s.toCharArray(); Stack<Integer> store = new Stack<Integer>(); int[] right = new int[c.length]; int res = 0; for (int i = 0; i < c.length; i++) { if (c[i] == '(') { store.push(i); } else { if (!store.isEmpty()) { right[i] = store.pop() + 1; int temp = right[i] - 2; if (temp >= 0 && right[temp] > 0) { right[i] = right[temp]; } res = Math.max(i - right[i] + 2, res); } } } return res; }
5
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Employee employee = (Employee) o; if (id != employee.id) return false; if (firstName != null ? !firstName.equals(employee.firstName) : employee.firstName != null) return false; if (lastName != null ? !lastName.equals(employee.lastName) : employee.lastName != null) return false; return true; }
8
public static Object[] isSignatureOK(Map<String, String> docEndorserInfo, Node node) { try { DOMValidateContext context = createContext(node); XMLSignature signature = extractXmlSignature(context); boolean coreValidation = signature.validate(context); if (coreValidation) { KeyInfo keyInfo = signature.getKeyInfo(); X509Certificate cert = extractX509CertFromKeyInfo(keyInfo); Map<String, String> certEndorserInfo = extractEndorserInfoFromCert(cert); String errorString = isEndorserInfoConsistent(certEndorserInfo, docEndorserInfo); if (errorString == null) { return new Object[] { Boolean.TRUE, cert.toString() }; } else { return new Object[] { Boolean.FALSE, errorString }; } } else { StringBuilder sb = new StringBuilder(); boolean sv = signature.getSignatureValue().validate(context); sb.append("signature validation: " + sv); List<?> refs = signature.getSignedInfo().getReferences(); for (Object oref : refs) { Reference ref = (Reference) oref; boolean refValid = ref.validate(context); sb.append("content (ref='" + ref.getURI() + "') validity: " + refValid); } return new Object[] { Boolean.FALSE, sb.toString() }; } } catch (MarshalException e) { return new Object[] { Boolean.FALSE, e.getMessage() }; } catch (XMLSignatureException e) { return new Object[] { Boolean.FALSE, e.getMessage() }; } }
6
public ArrayList<AbstractCookie> populateCookies(){ cookies = new ArrayList<AbstractCookie>(); for (int i = 0; i < this.getSize(); i++){ for(int k = 0; k < this.getSize(); k++) if(i == 0 && k == 0){ cookies.add(new PoisonCookie(i, k)); } else if(i == 0 && k == 1){ cookies.add(new BlueCookie(i, k)); } else if (i == 1 && k == 0){ cookies.add(new RedCookie(i, k)); } else{ int l = (int) (Math.random()*2+1); if(l==2){ cookies.add(new BlueCookie(i, k)); }else{ cookies.add(new RedCookie(i, k)); } } } return cookies; }
9
public void simulateBullyBotAttack(){ Planet source = null; Planet dest = null; // (1) Apply your strategy double sourceScore = Double.MIN_VALUE; double destScore = Double.MAX_VALUE; for (Planet planet : planets) { if(planet.Owner() == 2) {// skip planets with only one ship if (planet.NumShips() <= 1) continue; //This score is one way of defining how 'good' my planet is. double scoreMax = (double) planet.NumShips(); if (scoreMax > sourceScore) { //we want to maximize the score, so store the planet with the best score sourceScore = scoreMax; source = planet; } } // (2) Find the weakest enemy or neutral planet. if(planet.Owner() != 2){ double scoreMin = (double) (planet.NumShips()); //if you want to debug how the score is computed, decomment the System.err.instructions // System.err.println("Planet: " +notMyPlanet.PlanetID()+ " Score: "+ score); // System.err.flush(); if (scoreMin < destScore) { //The way the score is defined, is that the weaker a planet is, the higher the score. //So again, we want to select the planet with the best score destScore = scoreMin; dest = planet; } } } // (3) Simulate attack if (source != null && dest != null) { simulateAttack(2, source, dest); } }
8
public String execute(DeleteCalendarObject deleteCalendarObject) throws SQLException{ String answer = ""; resultSet = queryBuilder.selectFrom("Calendars").where("CalendarName", "=", deleteCalendarObject.getCalendarToDelete()).ExecuteQuery(); resultSet.next(); String calendarID = resultSet.getString("calendarID"); //TODO Strings here but integer in database? resultSet = queryBuilder.selectFrom("Users").where("UserName", "=", deleteCalendarObject.getuserID()).ExecuteQuery(); resultSet.next(); int userID = resultSet.getInt("userID"); boolean author = false; boolean imported = true; resultSet = queryBuilder.selectFrom("Calendars").where("calendarID", "=", calendarID).ExecuteQuery(); if(resultSet.next()){ if(resultSet.getInt("imported") == 0){ imported = false; } } if(imported == false){ resultSet = queryBuilder.selectFrom("AutherRights").where("CalendarID", "=", calendarID).ExecuteQuery(); while(resultSet.next()){ //TODO Check if resultset is used correctly if(resultSet.getInt("userID") == userID){ author = true; } } if(author){ resultSet = queryBuilder.selectFrom("Events").where("CalendarID", "=", calendarID).ExecuteQuery(); while(resultSet.next()){ String eventID = resultSet.getString("eventID"); try{ queryBuilder.deleteFrom("Notes").where("eventID", "=", eventID); }catch(Exception e){ System.err.print(e.getStackTrace()); } } queryBuilder.deleteFrom(dbConfig.getEvents()).where("CalendarID", "=", calendarID).Execute(); queryBuilder.deleteFrom("subscription").where("CalendarID", "=", calendarID).Execute(); queryBuilder.deleteFrom("autherrights").where("CalendarID", "=", calendarID).Execute(); queryBuilder.deleteFrom(dbConfig.getCalendar()).where("CalendarID", "=", calendarID).Execute(); answer = String.format("Calendar " + deleteCalendarObject.getCalendarToDelete() + " has been deleted, along with all associated events and notes."); }else{ answer = "You do not have the rights to delete this calendar."; } }else{ answer = "This is an imported calendar and cannot be deleted."; } return answer; }
8
public static void showMessageDialog(Component parentComponent, String htmlContent, String title, int messageType, Icon icon) { // for copying style JLabel label = new JLabel(); Font font = label.getFont(); // create some css from the label's font StringBuffer style = new StringBuffer("font-family:" + font.getFamily() + ";"); style.append("font-weight:" + (font.isBold() ? "bold" : "normal") + ";"); style.append("font-size:" + font.getSize() + "pt;"); // html content JEditorPane editorPane = new JEditorPane("text/html", "<html><body style=\"" + style + "\">" + //+ "some text, and <a href=\"http://google.com/\">a link</a>" htmlContent + "</body></html>"); // handle link events editorPane.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) //ProcessHandler.launchUrl(e.getURL().toString()); // roll your own link launcher or use Desktop if J6+ // java.awt.Desktop requires Java 1.6 or later. try { Desktop.getDesktop().browse(e.getURL().toURI()); } catch(java.net.URISyntaxException e1) { System.err.println(e1.getMessage()); } catch(java.io.IOException e2) { System.err.println(e2.getMessage()); } } }); editorPane.setEditable(false); editorPane.setBackground(label.getBackground()); // show JOptionPane.showMessageDialog(parentComponent, editorPane, title, messageType, icon); }
4
private int getInt(String test) { int page; try { page = Integer.parseInt(test); if (page < 1) { page = 1; } } catch (NumberFormatException e) { page = 1; } return page; }
2
private void destruction() { System.out.println("TestTesT"); if (!connectionSocket.isClosed()) { try { connectionSocket.close(); } catch (IOException e) { } } }
2
public void setWireSeparation(double separation){ if(separation<=0.0D)throw new IllegalArgumentException("The wire separation, " + separation + ", must be greater than zero"); if(this.wireRadius!=-1.0D && separation<=2.0D*this.wireRadius)throw new IllegalArgumentException("The wire separation distance, " + separation + ", must be greater than the sum of the two wire radii, " + 2.0D*this.wireRadius); this.wireSeparation = separation; if(this.wireRadius!=-1.0)this.distancesSet = true; if(this.distancesSet)this.calculateDistributedCapacitanceAndInductance(); }
5
public void addfromIndex(String file){ try{ Scanner readFrom =new Scanner(new InputStreamReader (new FileInputStream(file))); if(file.equals("yourindex.txt")){ if(readFrom.hasNextLine()==false){ JOptionPane.showMessageDialog(null, "The file is probably empty.\nPlease click on \"Add to Your Index\" menu","Error",0); return ; } } int id=0; while(readFrom.hasNextLine()){ String gg=readFrom.nextLine(); if(mywords.containsValue(gg.toLowerCase())){ continue; } listModel.add(id,gg.toLowerCase()); mywords.put(id, gg.toLowerCase()); linkl.add(new Word()); id++; } this.sortWords(); gf.setAdd(false); gf.setAddIndex(false); gf.setmakeIndex(false); //this.printLines(); //this.printWords(); JOptionPane.showMessageDialog(null, "Words from "+file+" are added to a hashtable successfully :)","Successfully added",1); //System.out.println("Words are added to a hashtable successfylly :)"); readFrom.close(); } catch (IOException e){ JOptionPane.showMessageDialog(null, "No such file","Error",0); //System.out.println("No such file"); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Something went wrong on read","Error",0); //System.out.println("Something went wrong on read"); } }
6
public void advice(String msg) { System.out.println("Called ..." + LoggerUtils.getSig() + "; msg:" + msg); }
0
private String whichBinary(String type) { for (int i = 0; i < Expression.binaryTypes.length; i++) { if (type.equals (Expression.binaryTypes[i])) { if(type.equals("plus")||type.equals("minus")||type.equals("times") ||type.equals("divided by")) { return "operator"; } else if(type.equals("or")||type.equals("and")) { return "logic"; } else { //"equals", "greater than", "less than" return "compare"; } } } return null; }
8
public boolean equals(Object otherO) { if (otherO == null) { return false; } if (!(otherO instanceof Picture)) { return false; } Picture other = (Picture) otherO; if (image == null || other.image == null) { return image == other.image; } if (image.getWidth() != other.image.getWidth() || image.getHeight() != other.image.getHeight()) { return false; } for (int i = 0; i < image.getWidth(); i++) { for (int j = 0; j < image.getHeight(); j++) { if (image.getRGB(i, j) != other.image.getRGB(i, j)) { return false; } } } return true; }
9
@EventHandler public void onClick(PlayerInteractEvent e) { Action action = e.getAction(); if (action == Action.RIGHT_CLICK_BLOCK) { Player player = e.getPlayer(); Location loc = e.getClickedBlock().getLocation(); if (e.getClickedBlock().getType() == Material.SIGN || e.getClickedBlock().getType() == Material.SIGN_POST || e.getClickedBlock().getType() == Material.WALL_SIGN) { Sign sign = (Sign) e.getClickedBlock().getState(); World world = player.getWorld(); int x = loc.getBlockX(); int y = loc.getBlockY(); int z = loc.getBlockZ(); if (MainClass.ports.contains("Signs.Warp." + world.getName() + "/" + x + "/" + y + "/" + z)) { String line = new String(); line = ChatColor.stripColor(sign.getLine(2)); List<String> warps = MainClass.players.getStringList(player .getUniqueId() + ".Warps"); if (warps.contains(line)) { player.sendMessage(ChatColor.BLUE + "You already have this warp."); } else { warps.add(line); MainClass.players.set(player .getUniqueId() + ".Warps", warps); MainClass.savePlayers(); player.sendMessage(ChatColor.GREEN + "The warp " + ChatColor.AQUA + sign.getLine(2) + ChatColor.GREEN + " has been added to your warp list!"); e.setCancelled(true); } } } } }
6
private void createObjectSpawnRequest(int delayUntilRespawn, int id2, int face2, int type, int y, int type2, int z, int x, int delayUntilSpawn) { GameObjectSpawnRequest request = null; for (GameObjectSpawnRequest request2 = (GameObjectSpawnRequest) spawnObjectList .peekLast(); request2 != null; request2 = (GameObjectSpawnRequest) spawnObjectList .reverseGetNext()) { if (request2.z != z || request2.x != x || request2.y != y || request2.objectType != type) continue; request = request2; break; } if (request == null) { request = new GameObjectSpawnRequest(); request.z = z; request.objectType = type; request.x = x; request.y = y; configureSpawnRequest(request); spawnObjectList.insertHead(request); } request.id2 = id2; request.type2 = type2; request.face2 = face2; request.delayUntilSpawn = delayUntilSpawn; request.delayUntilRespawn = delayUntilRespawn; }
6
@Override public String toString() { if(getVariableType() == VariableType.STRING) { return (String) variable; } else if(getVariableType() == VariableType.INTEGER) { return variable+ ""; } else { return "function"; } }
2
public JSONWriter array() throws JSONException { if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { this.push(null); this.append("["); this.comma = false; return this; } throw new JSONException("Misplaced array."); }
3
private void doCollision(int pin1, int pin2, Vector3f distance, boolean clatter) { Debug.println("PhysicsEngine.doCollision()"); MovableObject[] pins = model.getPins(); MovableObject p1 = pins[pin1]; MovableObject p2 = pins[pin2]; Vector3f p1v = p1.getVelocity(); Vector3f p2v; float m1 = p1.getMass(); float m2 = p2.getMass(); if (!clatter) { sound.doIt(Sound.CLATTER); } if (moving[pin2]) { p2v = p2.getVelocity(); p1v.sub(p2v); } else { p2v = new Vector3f(); } // Debug.println("p1v: " + p1v + " p2v: " + p2v); float[] p1Array= new float[3]; p1v.get(p1Array); float x1 = p1Array[0]; float y1 = p1Array[1]; float z1 = p1Array[2]; float[] p2Array = new float[3]; p2v.get(p2Array); float x2 = 0; float y2 = 0; float z2 = 0; float[] distArray = new float[3]; distance.get(distArray); float xd = distArray[0]; float yd = distArray[1]; float zd = distArray[2]; float theta = (float)Math.atan(zd / xd); float alpha = (float)Math.atan(yd / xd); float dx = p1v.length() * (float)Math.cos(theta); float dz = p1v.length() * (float)Math.sin(theta); x2 = dx * (m1 / m2); y2 = 0; z2 = dz * (m1 / m2); x1 = x1 - dx * (m2 / m1); y1 = 0; z1 = z1 - dz * (m2 / m1); p1Array[0] = x1; p1Array[1] = y1; p1Array[2] = z1; p2Array[0] = x2; p2Array[1] = y2; p2Array[2] = z2; Vector3f p1v2 = new Vector3f(p1Array); Vector3f p2v2 = new Vector3f(p2Array); p1v2.add(p2v); p2v2.add(p2v); // Debug.println("p1v2: " + p1v2 + " p2v2: " + p2v2); p1.setVelocity(p1v2); p2.setVelocity(p2v2); if (moving[pin2]) { p2.setThetaV(p2.getTheta() - theta); p1.setThetaV(p1.getTheta() - theta); } else { p2.setTheta(theta); p2.setAlphaV(0.05f); } moving[pin2] = true; }
3
public int getIndex(ArrayList<Person> list) { String[] values = null; if (supplierComboBox.getSelectedItem() != null) { values = ((String) supplierComboBox.getSelectedItem()).split("\\t"); int index = 0; for (Person person : list) { if (person.getId() == Integer.parseInt(values[1].trim())) break; index++; } return index; } return -1; }
3
public Path() { movement = new int[Game.map.width][Game.map.height]; pathColor = new Color(0, 75, 255, 128); attColor = new Color(255, 0, 0, 128); walkColor = new Color(0, 255, 144, 128); font = new Font("Arial", Font.PLAIN, 15); }
0
@Override public Data execute(Data data) { String[] strings = data.getText().split(" "); Color color = Color.black; if (strings.length >= 1) { try { color = stringToColor(strings[1]); } catch (NoSuchFieldException e) { return null; } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } for (User u : Server.getUsers()) { if (u.getIP().equals(data.getAddress())) { u.setColor(color); } } return null; }
7
public void placeCollectableBlock(Player p, Color c){ //do check for collision with other world items String path = null; if(c == Color.red){ path = COLLLECTABLEBLOCK_RED_PATH; }else if(c == Color.green){ path = COLLLECTABLEBLOCK_GREEN_PATH; }else if(c == Color.blue){ path = COLLLECTABLEBLOCK_BLUE_PATH; }else if(c == Color.yellow){ path = COLLLECTABLEBLOCK_YELLOW_PATH; } System.out.println("path = " + path); CollectableBlock cb = new CollectableBlock(this, p.getX() + (p.getWidth() - blockWidth)/2, p.getY() + p.getWidth() - blockHeight, path); p.setY(p.getY() - (cb.width + 15)); placedCollectableBlocks.add(cb); pManager.checkPattern(placedCollectableBlocks, p); //check if the placed pattern double mdist = 9999999; int saveIndex = -1; Pattern pattern = null; for(int i = 0; i < patterns.size(); i++){ pattern = patterns.get(i); double temp = Math.sqrt(Math.pow(p.getX() - pattern.x, 2) + Math.pow(p.getY() - pattern.y, 2)); if(temp < mdist){ mdist = temp; saveIndex = i; } } if(saveIndex != -1 && patterns.size() > saveIndex && pManager.matchPatternArray(patterns.get(saveIndex).pArr)) patterns.remove(saveIndex); else{ System.out.println("fail"); } }
9
public T pop() { if(nodes.size() == 0) return null; T t = nodes.get(0); nodes.remove(0); return t; }
1