text
stringlengths
14
410k
label
int32
0
9
final void assertAllTestCasesHaveRequiredElements(final Xpp3Dom results) { new ForAllTestCases(results) { @Override void apply(Xpp3Dom each) { for (final String requiredElement : REQUIRED_ELEMENTS) { assertHasExactlyOneNamedNonEmptyElement(each, requiredElement); } } }.run(); }
1
public double getDirectionLength(String dir, double minPathLength) { int xDiff = coordX - targetX; int yDiff = coordY - targetY; int tempDiff = 0; double pathLength = 0; if(dir.equals("up")) { tempDiff = yDiff-1; pathLength = Math.sqrt(xDiff*xDiff + tempDiff*tempDiff); if(minPathLength > pathLength) { desiredVelX = 0; desiredVelY = -1; minPathLength = pathLength; } } else if(dir.equals("down")) { tempDiff = yDiff+1; pathLength = Math.sqrt(xDiff*xDiff + tempDiff*tempDiff); if(minPathLength > pathLength) { desiredVelX = 0; desiredVelY = 1; minPathLength = pathLength; } } else if(dir.equals("left")) { tempDiff = xDiff-1; pathLength = Math.sqrt(tempDiff*tempDiff + yDiff*yDiff); if(minPathLength > pathLength) { desiredVelX = -1; desiredVelY = 0; minPathLength = pathLength; } } else if(dir.equals("right")) { tempDiff = xDiff+1; pathLength = Math.sqrt(tempDiff*tempDiff + yDiff*yDiff); if(minPathLength > pathLength) { desiredVelX = 1; desiredVelY = 0; minPathLength = pathLength; } } return minPathLength; }
8
public static double estimateGoalFanout(Proposition goal) { { Keyword testValue000 = goal.kind; if (testValue000 == Logic.KWD_ISA) { return (NamedDescription.estimateCardinalityOfExtension(Logic.getDescription(((Surrogate)(goal.operator))))); } else if ((testValue000 == Logic.KWD_FUNCTION) || (testValue000 == Logic.KWD_PREDICATE)) { return (Proposition.estimatePredicateGoalFanout(goal)); } else if (testValue000 == Logic.KWD_IMPLIES) { return (Logic.ESTIMATED_CARDINALITY_OF_SUBSET_OF); } else if (testValue000 == Logic.KWD_EQUIVALENT) { if (Logic.argumentBoundP((goal.arguments.theArray)[0]) || Logic.argumentBoundP((goal.arguments.theArray)[1])) { return (1.0); } else { return (Stella.NULL_FLOAT); } } else if ((testValue000 == Logic.KWD_NOT) || (testValue000 == Logic.KWD_FAIL)) { return (Stella.NULL_FLOAT); } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + testValue000 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } } }
9
public int countStars(String[] result) { int n = result.length; int ans = 0; for(int i = 0;i < n;i++){ if(result[i].equals("ooo")){ ans += 3; }else if(result[i].equals("oo-")){ ans += 2; }else if(result[i].equals("o--")){ ans += 1; } } return ans; }
4
public Bundle worthAtLeast(double maximumPrice) { double value = getValue(); if (value < maximumPrice) return null; //I want to cause null pointers if this ever happens. Bundle divvy = this.times(maximumPrice/value); //good starting guess. Bundle leftover = this.minus(divvy);//What I have left to allocate. int n = 0; while(n < leftover.contents.size() && divvy.getValue() < maximumPrice){ ResourcePile nth = leftover.getNthMostExpensive(n); if (divvy.getValue() + nth.getValue() < maximumPrice){ divvy.insert(nth); } else{ divvy.insert(new ResourcePile(nth.type,nth.amount*(City.economy.prices[nth.type.ordinal()]/(maximumPrice-divvy.getValue())))); } n++; } leftover = this.minus(divvy);//updated for stuffs shoved in. n = leftover.contents.size() - 1; while(n >= 0 && divvy.getValue() < maximumPrice){ divvy.insert(leftover.getNthMostExpensive(n));//give it all leftovers until we have enough. Last ditch effort. n--; } if (divvy.getValue() < maximumPrice) return null; //This should not be possible. extract(divvy); return divvy; }
7
public static void calculateTLZScore(ArrayList<Song> songs) { for(Song song: songs) { song.setTimeLength(); } double sum=0; double mean; double var; double sd; double zScore; int count=0; for(int i=0; i<songs.size(); i++) { if(songs.get(i).getTimeLength()>0) sum=sum+songs.get(i).getTimeLength(); else count++; } mean=sum/(songs.size()-(0.9*count)); sum=0; for(int i=0;i<songs.size(); i++) { if(songs.get(i).getTimeLength()>0) sum=sum+((songs.get(i).getTimeLength()-mean)*(songs.get(i).getTimeLength()-mean)); else sum=sum+((songs.get(i).getTimeLength()-mean)*(songs.get(i).getTimeLength()-mean))*0.1; } double denominator= (songs.size()-0.9*count); // double divisor= songs.size()-1; //not sure what is going on here, but it fixed the problem // divisor=divisor/(songs.size()); // denominator= denominator*divisor; var=sum/denominator; sd=Math.pow(var, 0.5); for(int i=0;i<songs.size();i++) { zScore= ((songs.get(i).getTimeLength()-mean)/sd); // songs.get(i).setTimeLengthZScore(zScore); } }
6
@Override public void actionPerformed(ActionEvent event) { if(isAddComputer(event)){ String profile = view.getProfileName(); String computer = view.getNickName(); String homeFolder = view.getHomeFolder(); String serverName = view.getServerName(); String userName = view.getUserName(); String password = charToString(view.getPassword()); if(isBlank(profile)){ blankWarning("Profile Name"); }else if(isBlank(computer)){ blankWarning("Computer Name"); }else if(isBlank(homeFolder)){ blankWarning("Home Folder"); }else if(isBlank(serverName)){ blankWarning("Server Name"); }else if(isBlank(userName)){ blankWarning("User Name"); }else if(isBlank(password)){ blankWarning("Password"); }else{ LogInInfo logInInfo = new LogInInfo(userName, password); SmbPath smdPath = new SmbPath(serverName, homeFolder); model.addWinShareComp(profile, userName, logInInfo, smdPath); ViewReset.resetView(); view.dispose(); } } }
7
private static void addCatchPhiOperands(final SSAConstructionInfo info, final Block block, final LocalExpr def) { final Iterator handlers = block.graph().handlers().iterator(); // Iterate over all of the exception handlers in the CFG. If // the block we are dealing with is a protected block (that is, // is inside a try block), then the variable represented by info // becomes an operand to the PhiCatchStmt residing at the // beginning of the protected block's handler. while (handlers.hasNext()) { final Handler handler = (Handler) handlers.next(); if (handler.protectedBlocks().contains(block)) { final PhiCatchStmt phi = (PhiCatchStmt) info.phiAtBlock(handler .catchBlock()); if ((phi != null) && !phi.hasOperandDef(def)) { final LocalExpr operand = (LocalExpr) info.prototype .clone(); operand.setDef(def); // ??? phi.addOperand(operand); } } } }
4
private void executeIteration(int[] rgb, Mask mask, int width, int height) { int[][] offsets = { { -1, -1 }, { 0, -1 }, { 1, -1 }, { -1, 0 }, { 1, 0 }, { -1, 1 }, { 0, 1 }, { 1, 1 } }; MaskIterator iterator = mask.iterator(); while (iterator.hasNext()) { int pixelIndex = iterator.next(); int x = pixelIndex % width; int y = pixelIndex / width; int r = 0; int g = 0; int b = 0; int cant = 0; for (int i = 0; i < offsets.length; i++) { int[] offset = offsets[i]; int column = x + offset[0]; int row = y + offset[1]; if (column < 0 || column >= width || row < 0 || row >= height) continue; int currentPixelIndes = getPixelIndex(width, column, row); // System.out.println("" + column + "," + row); int pixelData = rgb[currentPixelIndes]; simpleColor.setRGB(pixelData); if (mask.getMask(currentPixelIndes) == REALDATA) { r += simpleColor.getRed(); g += simpleColor.getGreen(); b += simpleColor.getBlue(); cant++; } } if (cant != 0) { simpleColor.setRGB(r / cant, g / cant, b / cant, 0); rgb[pixelIndex] = simpleColor.getRGB(); iterator.markAsInProgress(); } } iterator.reset(); }
8
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { System.out.println("#####################################################"); System.out.println("start generating code ..."); for(TypeElement typeElement : annotations){ GeneratorType type = getTypeByName(typeElement.getQualifiedName().toString()); if(type==null){ continue; } Class<? extends AbstractGenerator> cls = type.getClazz(); try { Constructor<? extends AbstractGenerator> ct = cls.getConstructor( TypeElement.class, RoundEnvironment.class, ProcessingEnvironment.class ); try { AbstractGenerator generator = ct.newInstance(typeElement, roundEnv, processingEnv); generator.execute(); } catch (InstantiationException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (IllegalAccessException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (InvocationTargetException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } catch (NoSuchMethodException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } return false; }
9
private static LongSet getIPBlocks() { LongSet group = (LongSet)Resources.getResource("SYSTEM_IP_BLOCKS"); if(group == null) { group = new LongSet(); final String filename = CMProps.getVar(CMProps.Str.BLACKLISTFILE); final List<String> ipList = Resources.getFileLineVector(Resources.getFileResource(filename, false)); for(String ip : ipList) { if(ip.trim().startsWith("#")||(ip.trim().length()==0)) { continue; } final int x=ip.indexOf('-'); if(x<0) { final long num = makeIPNumFromInetAddress(ip.trim()); if(num > 0) { group.add(num); } } else { final long ipFrom = makeIPNumFromInetAddress(ip.substring(0,x).trim()); final long ipTo = makeIPNumFromInetAddress(ip.substring(x+1).trim()); if((ipFrom > 0) && (ipTo >= ipFrom)) { group.add(ipFrom,ipTo); } } } Resources.submitResource("SYSTEM_IP_BLOCKS", group); Resources.removeResource(filename); } return group; }
8
private boolean claimRegion(Player player){ //Make sure we have a worldguard instance if (plugin.wg != null){ // Get WorldGuards Region Manager RegionManager rm = plugin.getRegionManager(player); // Make sure a RegionManager was found if (rm != null) { List<String> regionIds = plugin.getCurrentRegions(player, rm); if(regionIds == null){ player.sendMessage("It seems as if you're not in a claimable region."); return true; } List<String> regions = plugin.getUnownedRegions(regionIds, rm); if(!plugin.getDbc().canPlayerClaim(player.getName(), regionIds)){ for(String region : regions){ if(plugin.getDbc().isRegionClaimable(region)){ player.sendMessage("That region isn't claimable."); return true; }else{ player.sendMessage("You can't claim this plot, perhaps not enough claim points?"); return true; } } } for(String region : regions){ if (setOwner(player, rm, region)) { plugin.getDbc().claimRegion(player.getName(), region); } } } } // No region found at players position return true; }
8
public JSONObject getFullFile() throws ReaderException { if (this.json_obj instanceof JSONObject) { return (JSONObject) this.json_obj; } else { throw new ReaderException("JSON file is not formatted properly."); } }
1
private void updateStatistics() { numPink = numBlue = numGreen = numMale = numFemale = numTotal = 0; synchronized (world) { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { Organism o = world[i][j].visitor; if (o == null) continue; if (o.getBaseColor().equals(Color.MAGENTA.brighter())) { numPink++; numFemale++; } else if (o.getBaseColor().equals(Color.MAGENTA.darker())) { numPink++; numMale++; } else if (o.getBaseColor().equals(Color.BLUE.brighter())) { numBlue++; numFemale++; } else if (o.getBaseColor().equals(Color.BLUE.darker())) { numBlue++; numMale++; } else if (o.getBaseColor().equals(Color.GREEN.brighter())) { numGreen++; numFemale++; } else if (o.getBaseColor().equals(Color.GREEN.darker())) { numGreen++; numMale++; } numTotal++; } } } }
9
@SuppressWarnings("static-access") private void ROUND6() { enemises.clear(); System.out.println("Round6!!!!!!"); for (int i = 0; i < level.getWidth(); i++) { for (int j = 0; j < level.getHeight(); j++) { if ((level.getPixel(i, j) & 0x0000FF) == 2) { Transform monsterTransform = new Transform(); monsterTransform.setTranslation((i + 0.5f) * Game.getLevel().SPOT_WIDTH, 0.4375f, (j + 0.5f) * Game.getLevel().SPOT_LENGTH); enemises.add(new Enemies(monsterTransform)); } } } }
3
private void chooseFormat(BufferedImage image) { switch (image.getType()) { case BufferedImage.TYPE_4BYTE_ABGR : case BufferedImage.TYPE_INT_ARGB : imageComponentFormat = ImageComponent.FORMAT_RGBA; textureFormat = Texture.RGBA; break; case BufferedImage.TYPE_3BYTE_BGR : case BufferedImage.TYPE_INT_BGR: case BufferedImage.TYPE_INT_RGB: imageComponentFormat = ImageComponent.FORMAT_RGB; textureFormat = Texture.RGB; break; case BufferedImage.TYPE_CUSTOM: if (is4ByteRGBAOr3ByteRGB(image)) { SampleModel sm = image.getSampleModel(); if (sm.getNumBands() == 3) { //System.out.println("ChooseFormat Custom:TYPE_4BYTE_ABGR"); imageComponentFormat = ImageComponent.FORMAT_RGB; textureFormat = Texture.RGB; } else { imageComponentFormat = ImageComponent.FORMAT_RGBA; //System.out.println("ChooseFormat Custom:TYPE_3BYTE_BGR"); textureFormat = Texture.RGBA; } } break; default : // System.err.println("Unoptimized Image Type "+image.getType()); imageComponentFormat = ImageComponent.FORMAT_RGBA; textureFormat = Texture.RGBA; break; } }
8
public static void main(String[] args) { // fill distances with max value at the beginning Arrays.fill(distances, Integer.MAX_VALUE); // set distances to direct children of the node for (int i = 0; i < GRAPH_SIZE; i++) { if (graph[NODE][i] > 0) { // set the distance to children distances[i] = graph[NODE][i]; } } // initialization phase finished for (int k = 0; k < GRAPH_SIZE - 2; k++) { // repeat triangle inequality GRAPH_SIZE - 2 times in order to reach // the longest possible distance for (int i = 0; i < GRAPH_SIZE; i++) { if (i == NODE) { // do not want to find a path to itself continue; } for (int j = 0; j < GRAPH_SIZE; j++) { if (distances[j] < Integer.MAX_VALUE && graph[j][i] > 0 // there is a path to i through j && distances[i] > distances[j] + graph[j][i]) { // there is a path through j which is shorter distances[i] = distances[j] + graph[j][i]; } } } } System.out.println(Arrays.toString(distances)); }
9
public static void main(String[] args) { Display display = new Display(); final Shell shell = new Shell(display); shell.setLayout(new FillLayout()); Image originalImage = null; // FileDialog dialog = new FileDialog(shell, SWT.OPEN); // dialog.setText("Open an image file or cancel"); // String string = dialog.open(); // if (string != null) { // originalImage = new Image(display, string); // } if (originalImage == null) { int width = 150, height = 200; originalImage = new Image(display, width, height); GC gc = new GC(originalImage); gc.fillRectangle(0, 0, width, height); gc.drawLine(0, 0, width, height); gc.drawLine(0, height, width, 0); gc.drawText("Default Image", 10, 10); gc.dispose(); } final Image image = originalImage; final Point origin = new Point(0, 0); final Canvas canvas = new Canvas(shell, SWT.NO_BACKGROUND | SWT.NO_REDRAW_RESIZE | SWT.V_SCROLL | SWT.H_SCROLL); final ScrollBar hBar = canvas.getHorizontalBar(); final ScrollBar vBar = canvas.getVerticalBar(); hBar.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { int hSelection = hBar.getSelection(); int destX = -hSelection - origin.x; Rectangle rect = image.getBounds(); canvas.scroll(destX, 0, 0, 0, rect.width, rect.height, false); origin.x = -hSelection; } }); vBar.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { int vSelection = vBar.getSelection(); int destY = -vSelection - origin.y; Rectangle rect = image.getBounds(); canvas.scroll(0, destY, 0, 0, rect.width, rect.height, false); origin.y = -vSelection; } }); canvas.addListener(SWT.Resize, new Listener() { public void handleEvent(Event e) { Rectangle rect = image.getBounds(); Rectangle client = canvas.getClientArea(); hBar.setMaximum(rect.width); vBar.setMaximum(rect.height); hBar.setThumb(Math.min(rect.width, client.width)); vBar.setThumb(Math.min(rect.height, client.height)); int hPage = rect.width - client.width; int vPage = rect.height - client.height; int hSelection = hBar.getSelection(); int vSelection = vBar.getSelection(); if (hSelection >= hPage) { if (hPage <= 0) hSelection = 0; origin.x = -hSelection; } if (vSelection >= vPage) { if (vPage <= 0) vSelection = 0; origin.y = -vSelection; } canvas.redraw(); } }); canvas.addListener(SWT.Paint, new Listener() { public void handleEvent(Event e) { GC gc = e.gc; gc.drawImage(image, origin.x, origin.y); Rectangle rect = image.getBounds(); Rectangle client = canvas.getClientArea(); int marginWidth = client.width - rect.width; if (marginWidth > 0) { gc.fillRectangle(rect.width, 0, marginWidth, client.height); } int marginHeight = client.height - rect.height; if (marginHeight > 0) { gc.fillRectangle(0, rect.height, client.width, marginHeight); } } }); shell.setSize(200, 150); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } originalImage.dispose(); display.dispose(); }
9
public static MavenVersion parse(String version) throws ParseException { version = version.trim(); if (version.isEmpty()) { throw new ParseException("Empty string", 0); } String[] dotSplit = version.split("\\."); if (dotSplit.length > 3) { throw new ParseException("A maven version cannot contain more than 2 dots (.)", -1); } if (dotSplit.length == 0) { // No dots dotSplit = new String[]{version}; } boolean snapshot = false; String majorVersion = ""; String featureVersion = null; String bugfixVersion = null; for (int i = 0; i < dotSplit.length; i++) { String string = dotSplit[i]; // System.out.println(i + " " + string); if (i + 1 == dotSplit.length) { // We need to check for snapshot on the last split, - is allowed before this if (string.toLowerCase().endsWith(SNAPSHOT)) { snapshot = true; string = string.substring(0, string.length() - SNAPSHOT.length()); } } if (i == 0) { majorVersion = string; } if (i == 1) { featureVersion = string; } if (i == 2) { bugfixVersion = string; } } return new MavenVersion(majorVersion, featureVersion, bugfixVersion, snapshot); }
9
public void zeroLessThan(float cutOff) { for(int i=0; i < data.length; i++) { double[] block = data[i]; for(int j=0; j < block.length; j++) { if (block[j] != 0.0f && block[j] < cutOff) block[j] = 0.0f; } } }
4
public Distance(double conversionFactor, String name) { super(conversionFactor, name); }
0
public double getPesoLlaveEntera(int capa, int neurona, int llave){ double peso = 0; switch (llave) { case 0: peso = this.getPeso(capa, neurona, THRESHOLD); break; case 1: peso = this.getPeso(capa, neurona, EMBARAZOS); break; case 2: peso = this.getPeso(capa, neurona, CONCENTRACION_GLUCOSA); break; case 3: peso = this.getPeso(capa, neurona, PRESION_ARTERIAL); break; case 4: peso = this.getPeso(capa, neurona, GROSOR_TRICEPS); break; case 5: peso = this.getPeso(capa, neurona, INSULINA); break; case 6: peso = this.getPeso(capa, neurona, MASA_CORPORAL); break; case 7: peso = this.getPeso(capa, neurona, FUNCION); break; case 8: peso = this.getPeso(capa, neurona, EDAD); break; } return peso; }
9
private int checkForMultiple(List<Card> hand) //TODO bugs bugs bugs { List<Card> newHand = new ArrayList<Card>(); for(int i = 0 ; i < 5 ; i++) { newHand.add(null); } int multipleReturn = 1; int multipleCheck = 1; int startValue = 0; for (int i = 0 ; i < hand.size()-1 ; i++) { multipleCheck = 1; startValue = hand.get(i).getValue(); for (int j = i ; j < hand.size()-1 ; j++) { if(hand.get(j).getValue() == startValue) multipleCheck++; else break;//sorted, therefore won't have ANY more multiples if the next one is not } if(multipleCheck > multipleReturn) multipleReturn = multipleCheck;//checking the card that appears the most } int sizeIndex = 0; for (int i = 0 ; i < hand.size()-1 ; i++) { if(hand.get(i).getValue() == multipleReturn) { newHand.set(i, hand.remove(i).clone()); sizeIndex++;//add to the new hand each card that equals the most occurring card } } while(sizeIndex < 5) { newHand.set(sizeIndex, hand.remove(hand.size()-1).clone()); sizeIndex++;//keep adding highest cards until the new hand is 5 cards long } hand = newHand; return multipleReturn; }
8
public void setSource(File file) throws IOException { File original = file; m_structure = null; setRetrieval(NONE); if (file == null) throw new IOException("Source file object is null!"); // try { String fName = file.getPath(); try { if (m_env == null) { m_env = Environment.getSystemWide(); } fName = m_env.substitute(fName); } catch (Exception e) { // ignore any missing environment variables at this time // as it is possible that these may be set by the time // the actual file is processed //throw new IOException(e.getMessage()); } file = new File(fName); // set the source only if the file exists if (file.exists()) { if (file.getName().endsWith(getFileExtension() + FILE_EXTENSION_COMPRESSED)) { setSource(new GZIPInputStream(new FileInputStream(file))); } else { setSource(new FileInputStream(file)); } } // } /* catch (FileNotFoundException ex) { throw new IOException("File not found"); } */ if (m_useRelativePath) { try { m_sourceFile = Utils.convertToRelativePath(original); m_File = m_sourceFile.getPath(); } catch (Exception ex) { // System.err.println("[AbstractFileLoader] can't convert path to relative path."); m_sourceFile = original; m_File = m_sourceFile.getPath(); } } else { m_sourceFile = original; m_File = m_sourceFile.getPath(); } }
7
private static char lookupEntity(String val){ Character v=(Character)htmlEntities.get(val); if(v==null) return (char)0; return v.charValue(); }
1
public final void setRange(double minValue, double maxValue) { // Check for unusual values if (minValue == Double.NaN) minValue = 0; if (maxValue == Double.NaN) maxValue = 0; // conserve slider value double[] sliderValues = new double[sliders.size()]; for (int i = 0; i < sliderValues.length; i++) { sliderValues[i] = getValue(i); } sliderMin = minValue; sliderMax = maxValue; // re-apply slider value to set slider percent and position for (int i = 0; i < sliderValues.length; i++) { setValue(sliderValues[i]); } for (TButton slider : sliders) { int intWidth = (int) slider.tLabel.font.getStringBounds("0", ((Graphics2D) (new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB).getGraphics())).getFontRenderContext()) .getWidth(); int labelWidth = Math.max(String.valueOf(sliderMin).length() * intWidth, String.valueOf(sliderMax).length() * intWidth); slider.tLabel.setBackgroundColour(Color.WHITE); slider.tLabel.setDimensions(labelWidth, 15); slider.tLabel.fixedSize = true; } }
5
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final CidadeOrigem other = (CidadeOrigem) obj; if (this.IdCidadeOrigem != other.IdCidadeOrigem && (this.IdCidadeOrigem == null || !this.IdCidadeOrigem.equals(other.IdCidadeOrigem))) { return false; } return true; }
5
public void parsercommand(String componentType,String componentName, String command) { Component component= engine.getPowerPlantComponent(componentName); if(component.getName() =="valve") { InfoPacket i = new InfoPacket(); i.namedValues.add(new Pair<String>(Pair.Label.cNme, component.getName())); if(command=="open") { i.namedValues.add(new Pair<Boolean>(Pair.Label.psit, true)); } else { i.namedValues.add(new Pair<Boolean>(Pair.Label.psit, false)); } } else if(component.getName() =="pump") { InfoPacket i = new InfoPacket(); i.namedValues.add(new Pair<String>(Pair.Label.cNme, component.getName())); if(command=="on") { i.namedValues.add(new Pair<Boolean>(Pair.Label.psit, true)); } else { i.namedValues.add(new Pair<Boolean>(Pair.Label.psit, false)); } } else if(component.getName() =="rods") { InfoPacket i = new InfoPacket(); i.namedValues.add(new Pair<String>(Pair.Label.cNme, component.getName())); if(command=="lower") { i.namedValues.add(new Pair<Boolean>(Pair.Label.psit, true)); } else { i.namedValues.add(new Pair<Boolean>(Pair.Label.psit, false)); } } else { System.out.println("wrong command entered"); } }
6
private void linearize_recursive_single(ArrayList<LUSTree> seq, boolean use_combos){ //This is the end of a sequence if (branches.isEmpty()) seqs.add(seq); //Otherwise, branch else{ int len = branches.size(), i = 0; for (LUSTree node: branches){ //We need to copy the sequence, so it isn't overriden if (len != ++i) node.linearize_recursive(new ArrayList(seq), use_combos); //We can pass along the original list to one child else node.linearize_recursive(seq, use_combos); } } }
3
private Token scaenOpCodeOrLiteral(final CharStream line) throws AssemblerSyntaxException { if (!CharUtils.isAlpha(line.getCurrentChar())) { throw new AssemblerSyntaxException( String.format("Opcodes or literals must start with alpha character at column %d!", line.getIndex()), line.getLineNumber()); } final StringBuilder value = new StringBuilder(); value.append(line.getCurrentChar()); TokenType type = null; do { final char peek = line.peekChar(); if (CharUtils.isAlpha(peek)) { line.nextChar(); value.append(line.getCurrentChar()); } else if (CharUtils.isNumeric(peek)) { line.nextChar(); value.append(line.getCurrentChar()); type = TokenType.LITERAL; // Memonics can not contain numbers. } else { break; } } while (line.hasNextChar()); if (null == type) { if (OpCode.lokup(value.toString()) == OpCode.UNKWONN) { type = TokenType.LITERAL; } else { type = TokenType.OPCODE; } } return new Token(type, value.toString()); }
6
public int findKiller() { int killer = c.playerId; int damage = 0; for (int j = 0; j < Config.MAX_PLAYERS; j++) { if (PlayerHandler.players[j] == null) continue; if (j == c.playerId) continue; if (c.goodDistance(c.absX, c.absY, PlayerHandler.players[j].absX, PlayerHandler.players[j].absY, 40) || c.goodDistance(c.absX, c.absY + 9400, PlayerHandler.players[j].absX, PlayerHandler.players[j].absY, 40) || c.goodDistance(c.absX, c.absY, PlayerHandler.players[j].absX, PlayerHandler.players[j].absY + 9400, 40)) if (c.damageTaken[j] > damage) { damage = c.damageTaken[j]; killer = j; } } return killer; }
7
public String getSignatureAndPermissions(){ String s = getSignature(); for (String perm : permissions) s += " " + perm; return s; }
1
public <T extends Sprite<?>> Set<T> getSpritesOfType(Class<T> type) { Set<T> result = new HashSet<T>(); for (Sprite<?> sprite : sprites) { if (type.isInstance(sprite)) { result.add(type.cast(sprite)); } } return result; }
4
private boolean QueryCompareFormatTwo(LinkedHashMap<String, List<String>> queryvalue, LinkedHashMap<String,List<String>> borrowlistvalue){ if( (borrowlistvalue.containsKey("name") && borrowlistvalue.get("name").equals((queryvalue.get("name")))) && (borrowlistvalue.containsKey("birthday") && borrowlistvalue.get("birthday").equals((queryvalue.get("birthday")))) && borrowlistvalue.containsKey("booklist")){ return true; } return false; }
5
final public String string(boolean requireEOF) throws ParseException { Token t = null; t = jj_consume_token(STRING); eof(requireEOF); {if (true) return t.image.substring(1, t.image.length()-1);} throw new Error("Missing return statement in function"); }
1
@Override public AnnotationVisitor visitParameterAnnotation(final int parameter, final String desc, final boolean visible) { AnnotationNode an = new AnnotationNode(desc); if (visible) { if (visibleParameterAnnotations == null) { int params = Type.getArgumentTypes(this.desc).length; visibleParameterAnnotations = (List<AnnotationNode>[]) new List<?>[params]; } if (visibleParameterAnnotations[parameter] == null) { visibleParameterAnnotations[parameter] = new ArrayList<AnnotationNode>( 1); } visibleParameterAnnotations[parameter].add(an); } else { if (invisibleParameterAnnotations == null) { int params = Type.getArgumentTypes(this.desc).length; invisibleParameterAnnotations = (List<AnnotationNode>[]) new List<?>[params]; } if (invisibleParameterAnnotations[parameter] == null) { invisibleParameterAnnotations[parameter] = new ArrayList<AnnotationNode>( 1); } invisibleParameterAnnotations[parameter].add(an); } return an; }
7
private void loadFromFile() { JFileChooser jfc = new JFileChooser(); if( jfc.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; if( jfc.getSelectedFile() == null) return; File chosenFile = jfc.getSelectedFile(); try { BufferedReader reader = new BufferedReader(new FileReader(chosenFile)); String line = reader.readLine(); if( line == null || reader.readLine() != null) throw new Exception("Unexpected file format"); StringTokenizer sToken = new StringTokenizer(line); if( sToken.countTokens() != 1) throw new Exception("Unexpected file format"); try { this.numDollars = Integer.parseInt(sToken.nextToken()); } catch(Exception ex) { throw new Exception("Unexpected file format"); } updateTextField(); } catch(Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(this, ex.getMessage(), "Could not read file", JOptionPane.ERROR_MESSAGE); } }
7
private void processKey(KeyEvent e) { int keyCode = e.getKeyCode(); System.out.println("Key press:"+keyCode); // termination keys // listen for esc, q, end, ctrl-c on the canvas to // allow a convenient exit from the full screen configuration if ((keyCode == KeyEvent.VK_ESCAPE) || (keyCode == KeyEvent.VK_Q) || (keyCode == KeyEvent.VK_END) || ((keyCode == KeyEvent.VK_C) && e.isControlDown())) running = false; // help controls if (keyCode == KeyEvent.VK_H) { if (showHelp) { // help being shown showHelp = false; // switch off isPaused = false; } else { // help not being shown showHelp = true; // show it isPaused = true; // isPaused may already be true } } // game-play keys /*if (!isPaused && !gameOver) { // move the player based on the numpad key pressed if (keyCode == KeyEvent.VK_NUMPAD7) player.move(TiledSprite.NW); // move north west else if (keyCode == KeyEvent.VK_NUMPAD9) player.move(TiledSprite.NE); // north east else if (keyCode == KeyEvent.VK_NUMPAD3) player.move(TiledSprite.SE); // south east else if (keyCode == KeyEvent.VK_NUMPAD1) player.move(TiledSprite.SW); // south west else if (keyCode == KeyEvent.VK_NUMPAD5) player.standStill(); // stand still else if (keyCode == KeyEvent.VK_NUMPAD2) player.tryPickup(); // try to pick up from this tile }*/ } // end of processKey()
7
public static The5zigMod getInstance() { return instance; }
0
private void newPixelRun() { final Thread current = Thread.currentThread(); //if(animated) DjVuOptions.err.println("bcr newPixelRun "+this); if (source != null) { for (int i = 0;;) { if (threadArray[NEWPIXEL_THREAD] != current) { break; } if (flags[NEWPIXELS_FLAG]) { i = 0; flags[NEWPIXELS_FLAG] = false; // if(animated) DjVuOptions.err.println("bcr call source.newPixels"); source.newPixels(); try { Thread.sleep(20L); } catch (final Throwable ignored) { } } else { // final long lockTime=System.currentTimeMillis(); synchronized (mapArray) { if (flags[NEWPIXELS_FLAG]) { continue; } if (i++ > 0) { threadArray[NEWPIXEL_THREAD] = null; break; } try { source.wait(200L); } catch (final Throwable ignored) { } // DjVuObject.checkLockTime(lockTime,10000); } } } } }
8
private void initLayout() { this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); this.add(Box.createRigidArea(new Dimension((FRAME_WIDTH / 100) * 2, FRAME_HEIGHT / 5))); for (JLabel label : labels) { setLabelParam(label); this.add(label); this.add(Box.createRigidArea(new Dimension((FRAME_WIDTH / 100) * 2, (FRAME_HEIGHT / 100) * 4))); } }
1
public static void init(String Db){ if(StringHelper.isNullOrEmpty(Db) || Db.equalsIgnoreCase("Oracle")) { IdentityCurrVal = "SELECT {0}.currval FROM DUAL"; IdentityNextVal = "{0}.nextval"; SelectVal = "SELECT * FROM {0}"; AppendWhereVal = "new Operation(\"ROWNUM\", \"<=\", count).toString() + \" AND \" + "; AppendVal = ""; } else if(Db.equalsIgnoreCase("Postgres")){ IdentityCurrVal = "SELECT currval(\'{0}\')"; IdentityNextVal = "nextval(\'{0}\')"; SelectVal = "SELECT * FROM {0}"; AppendWhereVal = ""; AppendVal = " LIMIT {0}"; } else if(Db.equalsIgnoreCase("MySQL")) { IdentityCurrVal = ""; IdentityNextVal = ""; SelectVal = "SELECT * FROM {0}"; AppendWhereVal = ""; AppendVal = " LIMIT {0}"; } else if(Db.equalsIgnoreCase("Sybase")) { IdentityCurrVal = ""; IdentityNextVal = ""; SelectVal = "SELECT TOP {1} * FROM {0}"; AppendWhereVal = ""; AppendVal = ""; } else if(Db.equalsIgnoreCase("MSSQL")) { IdentityCurrVal = ""; IdentityNextVal = ""; SelectVal = "SELECT TOP {1} * FROM {0}"; AppendWhereVal = ""; AppendVal = ""; } else if(Db.equalsIgnoreCase("Firebird")) { IdentityCurrVal = ""; IdentityNextVal = ""; SelectVal = "SELECT FIRST {1} * FROM {0}"; AppendWhereVal = ""; AppendVal = ""; } }
7
public static LineNumberReader getPositionFileReader(String fileName) throws PositionFileException { LineNumberReader reader = null; String name = null; if(fileName == null) { JFileChooser fc = new JFileChooser(AppConfig.getAppConfig().getLastSelectedFileDirectory()); fc.setDialogTitle("Select input file"); SingleFileFilter posFf = new PositionFileFilter(); fc.setAcceptAllFileFilterUsed(true); fc.setFileFilter(posFf); if(fc.showOpenDialog(Tools.getGUI()) != JFileChooser.APPROVE_OPTION){ throw new PositionFileException("Aborted file selection"); } name = fc.getSelectedFile().getPath(); String p = name; p = p.substring(0, p.length() - fc.getSelectedFile().getName().length()); // remember the selected path AppConfig.getAppConfig().lastSelectedFileDirectory = p; } else { name = fileName; } try { reader = new LineNumberReader(new FileReader(new File(name))); } catch (FileNotFoundException e) { throw new PositionFileException(e.getMessage()); } try { // skip the first lines String numNodes = reader.readLine(); while(numNodes != null && !numNodes.equals(separator)) { numNodes = reader.readLine(); } } catch (IOException e) { throw new PositionFileException(e.getMessage()); } return reader; }
6
@Override public Intersection findIntersect(Ray r) { Vector o = r.getOrigin(); Vector d = r.getDirection(); Vector local_z = p2.sub(p1).norm(); Vector local_x = d.cross(local_z).norm(); Vector local_y = local_z.cross(local_x).norm(); Vector w = o.sub(p1); Vector o_local = new Vector(w.dot(local_x), w.dot(local_y), w.dot(local_z)); Vector d_local = new Vector(d.dot(local_x), d.dot(local_y), d.dot(local_z)); double a = d_local.getY() * d_local.getY(); double b = 2 * d_local.getY() * o_local.getY(); double c = o_local.getY() * o_local.getY() + o_local.getX() * o_local.getX() - R * R; if (a == 0) { return null; } double e = b * b - 4 * a * c; if (e < 0) { return null; } e = Math.sqrt(e); double t1 = (-b - e) / (2 * a); double t2 = (-b + e) / (2 * a); if (t1 > getTol()) { Vector i = r.position(t1); double f = i.sub(p1).dot(local_z); if (f > 0 && f < p2.sub(p1).length()) { Vector q = p1.add(local_z.mult(f)); Vector n = i.sub(q).norm(); return new Intersection(t1, r, i, n, material); } } if (t2 > getTol()) { Vector i = r.position(t2); double f = i.sub(p1).dot(local_z); if (f > 0 && f < p2.sub(p1).length()) { Vector q = p1.add(local_z.mult(f)); Vector n = q.sub(i).norm(); return new Intersection(t2, r, i, n, material); } } return null; }
8
void loadTemplatesSimple() { Templates.addElement(loadTemplate("circle CCW", TemplateData.circlePointsCCW)); Templates.addElement(loadTemplate("circle CW", TemplateData.circlePointsCW)); Templates.addElement(loadTemplate("rectangle CCW", TemplateData.rectanglePointsCCW)); Templates.addElement(loadTemplate("rectangle CW", TemplateData.rectanglePointsCW)); Templates.addElement(loadTemplate("caret CCW", TemplateData.caretPointsCCW)); Templates.addElement(loadTemplate("caret CW", TemplateData.caretPointsCW)); }
0
public ClassroomPanel(DataStore ds) { super(); this.cp = this; this.dataStore = ds; this.classrooms = dataStore.getClassrooms(); this.treenodes = new HashMap<ClassType, DefaultMutableTreeNode>(); this.addComponentListener(new ComponentAdapter() { public void componentShown(ComponentEvent e) { initializeTree(); } public void componentHidden(ComponentEvent e) { dataStore.setClassrooms(classrooms); } }); this.setLayout(new GridLayout(0, 1, 0, 0)); this.splitPane = new JSplitPane(); add(splitPane); this.tree = new JTree(); this.scrollPane = new JScrollPane(tree); splitPane.setLeftComponent(this.scrollPane); this.panel = new JPanel(); panel.setBorder(new EmptyBorder(23, 23, 23, 23)); splitPane.setRightComponent(panel); panel.setLayout(new GridLayout(7, 2, 46, 16)); JLabel label_1 = new JLabel(""); panel.add(label_1); JLabel label = new JLabel(""); panel.add(label); JLabel lblNom = new JLabel("Nom"); lblNom.setHorizontalAlignment(SwingConstants.RIGHT); panel.add(lblNom); this.tfName = new JTextField(); tfName.setHorizontalAlignment(SwingConstants.LEFT); tfName.addInputMethodListener(new InputMethodListener() { @Override public void inputMethodTextChanged(InputMethodEvent event) { checkEnableBtn(); } @Override public void caretPositionChanged(InputMethodEvent event) {} }); panel.add(tfName); tfName.setColumns(10); JLabel lblType = new JLabel("Type"); lblType.setHorizontalAlignment(SwingConstants.RIGHT); panel.add(lblType); this.cbType = new JComboBox(); panel.add(cbType); JLabel lblEffectif = new JLabel("Effectif"); lblEffectif.setHorizontalAlignment(SwingConstants.RIGHT); panel.add(lblEffectif); spEff = new JSpinner(); spEff.setModel(new SpinnerNumberModel(new Integer(0), new Integer(0), null, new Integer(1))); spEff.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { checkEnableBtn(); } }); panel.add(spEff); this.btnPosition = new JButton("Position"); btnPosition.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { new PositionFrame(ImageIO.read(new File("img/Plan Campus.jpg")), cp); } catch(Exception e){ e.printStackTrace(); } checkEnableBtn(); } }); panel.add(btnPosition); this.btnAjouter = new JButton("Ajouter"); btnAjouter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String name = tfName.getText(); ClassType type = (ClassType)cbType.getSelectedItem(); int eff = (Integer)spEff.getValue(); //System.out.println("ClassroomPanel.btnAjouter() : " + name + " " + type + " " + eff + " " + position); Classroom cr = new Classroom(type, name, eff, position); classrooms.add(cr); DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel().getRoot(); root = (DefaultMutableTreeNode) root.getChildAt(root.getIndex(treenodes.get(type))); DefaultMutableTreeNode node = new DefaultMutableTreeNode(cr.getName()); root.insert(node, root.getChildCount()); tree = new JTree((DefaultMutableTreeNode)tree.getModel().getRoot()); tree.setRootVisible(false); tree.makeVisible(new TreePath(node.getPath())); scrollPane = new JScrollPane(tree); splitPane.setLeftComponent(scrollPane); splitPane.setDividerLocation(0.25); //On redimensione la fenêtre, ça permet (va savoir pourquoi) d'actualiser //l'affichage du JTree et de faire apparraître le nouveau node. // setSize(getSize().width + 1, getSize().height); // setSize(getSize().width - 1, getSize().height); position = null; tfName.setText(""); cbType.setSelectedIndex(-1); spEff.setValue(0); checkEnableBtn(); } }); panel.add(btnAjouter); btnPreview = new JButton("Preview"); btnPreview.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFrame fr = new JFrame(); fr.add(new MapPanel(classrooms)); fr.pack(); fr.setVisible(true); checkEnableBtn(); } }); panel.add(btnPreview); this.initializeTree(); this.checkEnableBtn(); }
1
public String[] getCMD() { if (!connected) return null; if (stability == NO_CONNECTION) { return buildCMD(CMD.CONNECTION_LOST); } try { String[] cmd = inFromClient.readLine().trim().split(SPLITTER); if (stability != STABLE) { stability++; log("stability: " + stability); } if (cmd[0].equals(CMD.PING)) { pingReceived = true; return null; } return cmd; } catch (IOException | NullPointerException e) { return null; } }
5
public static boolean isReservedClosedParen(String candidate) { int START_STATE = 0; int TERMINAL_STATE = 1; char next; if (candidate.length()!=1){ return false; } int state = START_STATE; for (int i = 0; i < candidate.length(); i++) { next = candidate.charAt(i); switch (state) { case 0: switch ( next ) { case ')': state++; break; default : state = -1; } break; } } if ( state == TERMINAL_STATE ) return true; else return false; }
5
private void displayTiles(Terminal term, int left, int top) { for (int x = 0; x < this.screenWidth; x++) { for (int y = 0; y < this.screenHeight; y++) { int wx = x+left; int wy = y+top; if (Game.game.world.getDiscovered(wx, wy)) { if (Game.game.player.canSee(wx, wy)) term.write(Game.game.world.getTile(wx, wy).getGlyph(), wx, wy, Game.game.world.getColor(wx, wy), Color.lightGray); else term.write(Game.game.world.getTile(wx, wy).getGlyph(), wx, wy, Color.darkGray, Color.gray); } if (Game.game.player.canSee(wx, wy)) { ArrayList<Item> itm = Game.game.world.getItems(wx, wy); if (itm.size() > 0) term.write(itm.get(0).getGlyph(), itm.get(0).x-left, itm.get(0).y-top, itm.get(0).getColor(), Color.lightGray); Creature creature = Game.game.world.getCreature(wx, wy); if (creature != null) { term.write(creature.getGlyph(), creature.x - left, creature.y - top, creature.getColor(), Color.lightGray); } } } } }
7
protected static Ptg calcNormdist( Ptg[] operands ) { if( operands.length < 4 ) { return new PtgErr( PtgErr.ERROR_VALUE ); } try { //If mean or standard_dev is nonnumeric, NORMDIST returns the #VALUE! error value. double x = operands[0].getDoubleVal(); double mean = operands[1].getDoubleVal(); // if standard_dev ≤ 0, NORMDIST returns the #NUM! error value. double stddev = operands[2].getDoubleVal(); if( stddev <= 0 ) { return new PtgErr( PtgErr.ERROR_NUM ); } boolean cumulative = PtgCalculator.getBooleanValue( operands[3] ); // If mean = 0, standard_dev = 1, and cumulative = TRUE, NORMDIST returns the standard normal distribution, NORMSDIST. if( (mean == 0) && (stddev == 1.0) && cumulative ) { return calcNormsdist( operands ); } if( !cumulative ) { // return the probability mass function. *** definite excel algorithm double a = Math.sqrt( 2 * Math.PI * Math.pow( stddev, 2 ) ); a = 1.0 / a; double exp = Math.pow( x - mean, 2 ); exp = exp / (2 * Math.pow( stddev, 2 )); double b = Math.exp( -exp ); return new PtgNumber( a * b ); } // When cumulative = TRUE, the formula is the integral from negative infinity to x of the given formula. // = the cumulative distribution function Ptg[] o = { new PtgNumber( (x - mean) / (stddev * Math.sqrt( 2 )) ) }; Ptg erf = EngineeringCalculator.calcErf( o ); double cdf = 0.5 * (1 + erf.getDoubleVal()); return new PtgNumber( cdf ); /* // try this: Ptg[] o= { new PtgNumber((x-mean)/(stddev))}; return calcNormsdist(o); */ } catch( Exception e ) { return new PtgErr( PtgErr.ERROR_VALUE ); } }
7
private void checkActionsInContent() { if (mInput.up() && currentSectionNumber > 0) { changeSelectedSection(-1); } else if (mInput.down() && currentSectionNumber < sections.length - 1) { changeSelectedSection(1); } else if (mInput.action()) { mSection = new Section(sections[currentSectionNumber]); addPagesToStage(); flipPage(0); mSectionText.setText(sections[currentSectionNumber]); content[currentSectionNumber].setStyle(mButtonStyle); inContent = false; } else if (mInput.right()) { content[currentSectionNumber].setStyle(mButtonStyle); currentSectionNumber = 0; mSection = new Section(sections[currentSectionNumber]); currentPageNumber = 0; addPagesToStage(); flipPage(0); mSectionText.setText(sections[currentSectionNumber]); inContent = false; } }
6
@Override public void mouseWheelMoved(MouseWheelEvent e) { incrementStroke(e.getPreciseWheelRotation()); int size = getStrokeSize(); if (size < 0) { stroke = 0; } detailsPanel.getStrokeSize().setText("Stroke size: " + stroke); }
1
private int getSelected(double x, double y) { for (int i = selindex+1; i < shapeList.size(); i++) { if (shapeList.get(i).contains(x, y)) { shapeList.get(i).highlight(true); return i; } } return -1; }
2
public void countAnswers() { countA = 0; countB = 0; countC = 0; countD = 0; for (int key : database.keySet()) { if(database.get(key).equals('A')) { countA += 1; } if(database.get(key).equals('B')) { countB += 1; } if(database.get(key).equals('C')) { countC += 1; } if(database.get(key).equals('D')) { countD += 1; } } }
5
public static void main(String[] args) { String usage = "java org.apache.lucene.demo.IndexFiles" + " [-index INDEX_PATH] [-docs DOCS_PATH] [-update]\n\n" + "This indexes the documents in DOCS_PATH, creating a Lucene index" + "in INDEX_PATH that can be searched with SearchFiles"; String indexPath = "index"; String docsPath = null; boolean create = true; for(int i=0;i<args.length;i++) { if ("-index".equals(args[i])) { indexPath = args[i+1]; i++; } else if ("-docs".equals(args[i])) { docsPath = args[i+1]; i++; } else if ("-update".equals(args[i])) { create = false; } } if (docsPath == null) { System.err.println("Usage: " + usage); System.exit(1); } final File docDir = new File(docsPath); if (!docDir.exists() || !docDir.canRead()) { System.out.println("Document directory '" +docDir.getAbsolutePath()+ "' does not exist or is not readable, please check the path"); System.exit(1); } Date start = new Date(); try { System.out.println("Indexing to directory '" + indexPath + "'..."); Directory dir = FSDirectory.open(new File(indexPath)); Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_41); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_41, analyzer); if (create) { // Create a new index in the directory, removing any // previously indexed documents: iwc.setOpenMode(OpenMode.CREATE); } else { // Add new documents to an existing index: iwc.setOpenMode(OpenMode.CREATE_OR_APPEND); } // Optional: for better indexing performance, if you // are indexing many documents, increase the RAM // buffer. But if you do this, increase the max heap // size to the JVM (eg add -Xmx512m or -Xmx1g): // iwc.setRAMBufferSizeMB(256.0); IndexWriter writer = new IndexWriter(dir, iwc); indexDocs(writer, docDir); // NOTE: if you want to maximize search performance, // you can optionally call forceMerge here. This can be // a terribly costly operation, so generally it's only // worth it when your index is relatively static (ie // you're done adding documents to it): // // writer.forceMerge(1); writer.close(); Date end = new Date(); System.out.println(end.getTime() - start.getTime() + " total milliseconds"); } catch (IOException e) { System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage()); } }
9
@Override public Value evaluate(Value... arguments) throws Exception { if (arguments.length != 2) { throw new EvalException("add support only two argument!"); } Value arr = new Value(arguments[0]); Value val = arguments[1]; if (arr.getType() == ValueType.ARRAY) { if (val.getType() == ValueType.ARRAY) { for (Value v : val.getValues()) { arr.getArray().add(v); } } else { arr.getArray().add(val); } return new Value(arr); } throw new EvalException("add support only array and values!"); }
4
@Override public boolean isApplicable(Integer current, Integer target) { for (Conditional condition : conditions) { if (!condition.isApplicable(current, target)) return false; } return true; }
2
public final void terminarPara() throws RecognitionException { try { // fontes/g/CanecaSemantico.g:862:2: ( ^( PARA_ . . . . ) ) // fontes/g/CanecaSemantico.g:862:4: ^( PARA_ . . . . ) { match(input,PARA_,FOLLOW_PARA__in_terminarPara2358); if (state.failed) return ; match(input, Token.DOWN, null); if (state.failed) return ; matchAny(input); if (state.failed) return ; matchAny(input); if (state.failed) return ; matchAny(input); if (state.failed) return ; matchAny(input); if (state.failed) return ; match(input, Token.UP, null); if (state.failed) return ; if ( state.backtracking==1 ) { mostrar("terminarPara"); escopoAtual = escopoAtual.fornecerEscopoPai(); } } } catch (RecognitionException erro) { throw erro; } finally { // do for sure before leaving } return ; }
9
public static void affineMatrixFill(AlignmentGraphBasic d) { AlignmentGraphBasic e = new AlignmentGraphBasic(d); AlignmentGraphBasic f = new AlignmentGraphBasic(d); int x,y; d.setMatrix(0,0,0); for(x=1;x<d.getMatrixXLength();x++) { e.setMatrix(0, x,(e.getEffort()[0]+x*e.getEffort()[1])); d.setMatrix(0, x, e.getMatrix(0, x)); } for(y=1;y<d.getMatrixYLength();y++) { f.setMatrix(y, 0,(f.getEffort()[0]+y*f.getEffort()[1])); d.setMatrix(y, 0, f.getMatrix(y, 0)); } for(y=1;y<d.getMatrixYLength();y++) { for(x=1;x<d.getMatrixXLength();x++) { e.setMatrix(y,x,calcAfineCostsE(y,x,e,f,d)); f.setMatrix(y,x,calcAfineCostsF(y,x,e,f,d)); d.setMatrix(y,x,calcAfineCostsD(y,x,e,f,d)); //Berechne Wert für stelle matrix[y][x]); } } e.print(); f.print(); d.print(); }
4
public ArrayList<Product> getProducts(String filter) { ArrayList<Product> products = new ArrayList<Product>(); try { Connection conn = openConnection(); Statement stat = conn.createStatement(); Statement stat2 = conn.createStatement(); ResultSet rs = stat.executeQuery("select * from " + DB_PRODUCT_TABLE + ";"); int category_id; while (rs.next()) { category_id = rs.getInt("category_id"); ResultSet categorySet = stat2.executeQuery("select name from " + DB_CATEGORY_TABLE + " where rowid = " + category_id + ";"); categorySet.next(); String category = categorySet.getString("name"); if (filter == null || category.equals(filter)) { products.add(new Product(rs.getRow(), rs.getString("name"), rs.getInt("price"), category, rs.getInt("inventory"))); } } rs.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } return products; }
4
private void calculatePath() { Shape rectangle = new RoundRectangle2D.Float( x, y, width, height, arc, arc ); Triangle triangle = null; AffineTransform at = new AffineTransform(); switch( tabLocation ) { case TAB_AT_RIGHT: if( anglePosition == NONE ) { triangle = new Triangle( 0f, 0f, tabWidth, 270f, tabHeight ); } else { triangle = new Triangle( 0f, 0f, tabWidth, 270f, calculateAnglePosition(), tabHeight ); } float a = (tabWidth + arc - height) * tabDisplacement; at = AffineTransform.getTranslateInstance( x + width, y + height - tabWidth - (arc / 2) + a ); break; case TAB_AT_LEFT: if( anglePosition == NONE ) { triangle = new Triangle( 0, 0, tabWidth, 90, tabHeight ); } else { triangle = new Triangle( 0, 0, tabWidth, 90, calculateAnglePosition(), tabHeight ); } float b = (height - arc - tabWidth) * tabDisplacement; at = AffineTransform.getTranslateInstance( x, y + tabWidth + (arc / 2) + b ); break; case TAB_AT_TOP: if( anglePosition == NONE ) { triangle = new Triangle( 0, 0, tabWidth, 0, tabHeight ); } else { triangle = new Triangle( 0, 0, tabWidth, 0, calculateAnglePosition(), tabHeight ); } float c = (tabWidth + arc - width) * tabDisplacement; at = AffineTransform.getTranslateInstance( x + width - tabWidth - (arc / 2) + c, y ); break; default: if( anglePosition == NONE ) { triangle = new Triangle( 0, 0, tabWidth, 180, tabHeight ); } else { triangle = new Triangle( 0, 0, tabWidth, 180, calculateAnglePosition(), tabHeight ); } float d = (width - arc - tabWidth) * tabDisplacement; at = AffineTransform.getTranslateInstance( x + tabWidth + (arc / 2) + d, y + height ); } balloon = new Area( rectangle ); ((Area) balloon).add( new Area( at.createTransformedShape( triangle ) ) ); }
7
private JSONWriter append(String string) throws JSONException { if (string == null) { throw new JSONException("Null pointer"); } if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { this.writer.write(','); } this.writer.write(string); } catch (IOException e) { throw new JSONException(e); } if (this.mode == 'o') { this.mode = 'k'; } this.comma = true; return this; } throw new JSONException("Value out of sequence."); }
7
@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 Redirects)) { return false; } Redirects other = (Redirects) object; if ((this.url == null && other.url != null) || (this.url != null && !this.url.equals(other.url))) { return false; } return true; }
5
void close () throws USBException { if (fd < 0) return; try { // make sure this isn't usable any more int status = closeNative (fd); if (status < 0) throw new USBException ( "error closing device", -status); } finally { // make sure nobody else sees the device usb.removeDev (this); hub = null; fd = -1; } }
2
public static int lengthOfLongestSubstring(String s) { int max = 0; int len = s.length(); int[] hash = new int[256]; int[] first = new int[len+1]; int[] next = new int[len]; first[len] = len; for (int i = len - 1; i >= 0; i--) { int index = hash[s.charAt(i)]; next[i] = index == 0 ? len : index; hash[s.charAt(i)] = i; if (first[i + 1] > next[i]) { first[i] = next[i]; } else { first[i] = first[i + 1]; } } for (int i = 0; i < len; i++) { if (first[i] - i > max) max = first[i] - i; } return max; }
5
private void detached() { // Transient session self-destructs after peer disconnects. if (!connect) { terminate (); return; } // For delayed connect situations, terminate the pipe // and reestablish later on if (pipe != null && options.delay_attach_on_connect == 1 && addr.protocol () != "pgm" && addr.protocol () != "epgm") { pipe.hiccup (); pipe.terminate (false); terminating_pipes.add (pipe); pipe = null; } reset (); // Reconnect. if (options.reconnect_ivl != -1) start_connecting (true); // For subscriber sockets we hiccup the inbound pipe, which will cause // the socket object to resend all the subscriptions. if (pipe != null && (options.type == ZMQ.ZMQ_SUB || options.type == ZMQ.ZMQ_XSUB)) pipe.hiccup (); }
9
private Point getPointFromMyo(double pitch, double yaw) { Point point = new Point(); double x, y; if (topGreater) { y = HEIGHT - (((pitch - info.getPitchBottom()) / (info.getPitchTop() - info.getPitchBottom())) * HEIGHT); } else { y = ((pitch - info.getPitchTop()) / (info.getPitchBottom() - info.getPitchTop()) * HEIGHT); } if (rightGreater) { x = ((yaw - info.getYawLeft()) / (info.getYawRight() - info.getYawLeft())) * WIDTH; } else { x = WIDTH - (((yaw - info.getYawRight()) / (info.getYawLeft() - info.getYawRight())) * WIDTH); } if (x > (double)WIDTH) x = (double)WIDTH - 14.0; if (y > (double)HEIGHT) y = (double)HEIGHT - 42.0; if (x < 0.0) x = 0.0; if (y < 0.0) y = 0.0; point.setLocation(x, y); //System.out.println(x + ", " + y); return point; }
6
public static Object ungz(String string) { //DetectRight.checkPoint("base64"); if (string == null) return null; if (PHPSerializer.isSerialized(string)) return Functions.unserialize(string); byte[] byt; //DetectRight::checkPoint("GZDecode"); try { byt = Functions.base64_decode(string); byt = Functions.gzdecode(byt); //objStr = new String(byt,"ISO-8859-1"); } catch (Throwable e) { return ""; } if (byt == null) return null; if (byt.length < 2 ) return null; String dcmp; try { dcmp = new String(byt,"UTF-8"); } catch (UnsupportedEncodingException e1) { // This should never happen return null; } //DetectRight::checkPoint("Unserialize"); if (!PHPDeserializer.isSerialized(dcmp)) return dcmp; Object newObj = Functions.unserialize(byt); if (newObj instanceof PhpObject) { PhpObject phpo = (PhpObject) newObj; newObj = phpo.getRealObject(); } if (newObj == null) { return dcmp; } return newObj; }
9
private void thisMouseClicked(MouseEvent e) { x = e.getX(); y = e.getY(); repaint(); }
0
public Identifier getIdentifier(String fieldName, String typeSig) { for (Iterator i = getChilds(); i.hasNext();) { Identifier ident = (Identifier) i.next(); if (ident.getName().equals(fieldName) && ident.getType().startsWith(typeSig)) return ident; } if (superName != null) { ClassIdentifier superident = Main.getClassBundle() .getClassIdentifier(superName); if (superident != null) { Identifier ident = superident.getIdentifier(fieldName, typeSig); if (ident != null) return ident; } } return null; }
6
public static int[] GetUser(String username, String password){ try { String query = String.format("SELECT * FROM APPUSERS WHERE USERNAME = '%s' AND PASSWORD ='%s'", username, password); int[] udetails = new int[2]; ResultSet rs = getQueryResults(query); while (rs.next()) { udetails[0] = rs.getInt("USERTYPE"); udetails[1] = rs.getInt("USERID"); } //con.close(); //might need to close the connection at another point, doing it here throws and excepction with the resultset. return udetails; } catch (SQLException se) { return new int[]{-1,-1}; //Login FAILED! } }
2
public Network() { stations = new ArrayList<String>(); }
0
static final String method1273(int[] is, boolean bool) { anInt2161++; StringBuffer stringbuffer = new StringBuffer(); int i = Class239_Sub1.anInt5850; for (int i_24_ = 0; is.length > i_24_; i_24_++) { Class321 class321 = Class348_Sub23_Sub2.aClass187_9036.method1408(-12637, is[i_24_]); if ((((Class321) class321).anInt4000 ^ 0xffffffff) != 0) { RasterToolkit class105 = ((RasterToolkit) Class34.aClass60_463.method583((long) (((Class321) class321) .anInt4000), -74)); if (class105 == null) { ImageSprite class207 = ImageSprite.getSprite(Class21.indexLoader8, ((Class321) class321).anInt4000, 0); if (class207 != null) { class105 = Class348_Sub8.currentToolkit.createRasterForSprite(class207, true); Class34.aClass60_463.method582(class105, (long) (((Class321) class321) .anInt4000), (byte) -127); } } if (class105 != null) { Class341.aClass105Array4234[i] = class105; stringbuffer.append(" <img=").append(i).append(">"); i++; } } } if (bool != true) aBooleanArray2162 = null; return stringbuffer.toString(); }
6
public void launchNext(final int wexp, final int ah) { Thread subExpThread; subExpThread = new Thread() { public void run() { m_remoteHostsStatus[ah] = IN_USE; m_subExpComplete[wexp] = TaskStatusInfo.PROCESSING; RemoteExperimentSubTask expSubTsk = new RemoteExperimentSubTask(); expSubTsk.setExperiment(m_subExperiments[wexp]); String subTaskType = (getSplitByDataSet()) ? "dataset :" + ((File)m_subExperiments[wexp].getDatasets(). elementAt(0)).getName() : "run :" + m_subExperiments[wexp].getRunLower(); try { String name = "//" +((String)m_remoteHosts.elementAt(ah)) +"/RemoteEngine"; Compute comp = (Compute) Naming.lookup(name); // assess the status of the sub-exp notifyListeners(false,true,false,"Starting " +subTaskType +" on host " +((String)m_remoteHosts.elementAt(ah))); Object subTaskId = comp.executeTask(expSubTsk); boolean finished = false; TaskStatusInfo is = null; while (!finished) { try { Thread.sleep(2000); TaskStatusInfo cs = (TaskStatusInfo)comp. checkStatus(subTaskId); if (cs.getExecutionStatus() == TaskStatusInfo.FINISHED) { // push host back onto queue and try launching any waiting // sub-experiments notifyListeners(false, true, false, cs.getStatusMessage()); m_remoteHostsStatus[ah] = AVAILABLE; incrementFinished(); availableHost(ah); finished = true; } else if (cs.getExecutionStatus() == TaskStatusInfo.FAILED) { // a non connection related error---possibly host doesn't have // access to data sets or security policy is not set up // correctly or classifier(s) failed for some reason notifyListeners(false, true, false, cs.getStatusMessage()); m_remoteHostsStatus[ah] = SOME_OTHER_FAILURE; m_subExpComplete[wexp] = TaskStatusInfo.FAILED; notifyListeners(false,true,false,subTaskType +" "+cs.getStatusMessage() +". Scheduling for execution on another host."); incrementFailed(ah); // push experiment back onto queue waitingExperiment(wexp); // push host back onto queue and try launching any waiting // sub-experiments. Host is pushed back on the queue as the // failure may be temporary---eg. with InstantDB using the // RMI bridge, two or more threads may try to create the // experiment index or results table simultaneously; all but // one will throw an exception. These hosts are still usable // however. availableHost(ah); finished = true; } else { if (is == null) { is = cs; notifyListeners(false, true, false, cs.getStatusMessage()); } else { if (cs.getStatusMessage(). compareTo(is.getStatusMessage()) != 0) { notifyListeners(false, true, false, cs.getStatusMessage()); } is = cs; } } } catch (InterruptedException ie) { } } } catch (Exception ce) { m_remoteHostsStatus[ah] = CONNECTION_FAILED; m_subExpComplete[wexp] = TaskStatusInfo.TO_BE_RUN; System.err.println(ce); ce.printStackTrace(); notifyListeners(false,true,false,"Connection to " +((String)m_remoteHosts.elementAt(ah)) +" failed. Scheduling " +subTaskType +" for execution on another host."); checkForAllFailedHosts(); waitingExperiment(wexp); } finally { if (isInterrupted()) { System.err.println("Sub exp Interupted!"); } } } }; subExpThread.setPriority(Thread.MIN_PRIORITY); subExpThread.start(); }
9
public GroupCommand(TotalPermissions p) { plugin = p; }
0
public List<ClassObj> getClassTable(PreparedStatement pre) { List<ClassObj> items = new LinkedList<ClassObj>(); try { ResultSet rs = pre.executeQuery(); if (rs != null) { while (rs.next()) { ClassObj item = new ClassObj(); item.setClassname(rs.getString("classname")); item.setStaffId(rs.getString("staff_id")); item.setObjId(rs.getInt("obj_id")); items.add(item); } } } catch (Exception ex) { ex.printStackTrace(); } return items; }
3
public String removeTags(String str) { //str.replaceAll("<+[^>]+>", ""); int index = 0; String finalString = ""; while(index < str.length()) { if(str.charAt(index) == '<') { while(str.charAt(index) != '>') { index++; } index++; finalString += '\n'; } else { finalString += str.substring(index, index+1); index++; } } return finalString; //return str; }
3
private static ArrayList<Object> getWFIPathRec(mxAnalysisGraph aGraph, Object[][] paths, Object startVertex, Object targetVertex, ArrayList<Object> currPath, mxCostFunction cf, mxGraphView view) throws StructuralException { Double sourceIndexD = cf.getCost(view.getState(startVertex)); Object[] parents = paths[sourceIndexD.intValue()]; Double targetIndexD = cf.getCost(view.getState(targetVertex)); int tIndex = targetIndexD.intValue(); if (parents[tIndex] != null) { currPath = getWFIPathRec(aGraph, paths, startVertex, parents[tIndex], currPath, cf, view); } else { if (mxGraphStructure.areConnected(aGraph, startVertex, targetVertex) || startVertex == targetVertex) { currPath.add(targetVertex); } else { throw new StructuralException("The two vertices aren't connected"); } } return currPath; }
3
@Override public <T> ValueParser<? extends T> getParser(Class<T> clazz) throws ParserFactoryException { Class<? extends ValueParser<?>> parserCls = parserClasses.get(clazz); if (parserCls != null) { try { @SuppressWarnings("unchecked") ValueParser<? extends T> parser = (ValueParser<? extends T>) parserCls.newInstance(); return parser; } catch (InstantiationException e) { throw new ParserFactoryException(e); } catch (IllegalAccessException e) { throw new ParserFactoryException(e); } } else if (parent != null) { return parent.getParser(clazz); } else { throw new MissingParserException(clazz); } }
9
@Override public MidiChannel[] getChannels() { MidiChannel[] oldC = super.getChannels(); ArrayList<MidiChannel> rem = new ArrayList<MidiChannel>(); int ordinal = 1; for (MidiChannel m : oldC) { if (ordinal == Values.DRUMCHANNEL) { ordinal++; continue; } else { rem.add(m); ordinal++; if (ordinal > Values.MIDICHANNELS) ordinal = 1; } } MidiChannel[] ret = new MidiChannel[rem.size()]; for (int i = 0; i < rem.size(); i++) ret[i] = rem.get(i); return ret; }
4
public void dumpExpression(TabbedPrintWriter writer) throws java.io.IOException { Type flat = type.getCanonic(); int depth = 0; while (flat instanceof ArrayType) { flat = ((ArrayType) flat).getElementType(); depth++; } writer.print("new "); writer.printType(flat.getHint()); for (int i = 0; i < depth; i++) { writer.breakOp(); writer.print("["); if (i < subExpressions.length) subExpressions[i].dumpExpression(writer, 0); writer.print("]"); } }
3
private boolean r_verb_suffix() { int among_var; int v_1; int v_2; int v_3; int v_4; // (, line 175 // setlimit, line 176 v_1 = limit - cursor; // tomark, line 176 if (cursor < I_pV) { return false; } cursor = I_pV; v_2 = limit_backward; limit_backward = cursor; cursor = limit - v_1; // (, line 176 // [, line 176 ket = cursor; // substring, line 176 among_var = find_among_b(a_8, 96); if (among_var == 0) { limit_backward = v_2; return false; } // ], line 176 bra = cursor; limit_backward = v_2; switch(among_var) { case 0: return false; case 1: // (, line 179 // try, line 179 v_3 = limit - cursor; lab0: do { // (, line 179 // literal, line 179 if (!(eq_s_b(1, "u"))) { cursor = limit - v_3; break lab0; } // test, line 179 v_4 = limit - cursor; // literal, line 179 if (!(eq_s_b(1, "g"))) { cursor = limit - v_3; break lab0; } cursor = limit - v_4; } while (false); // ], line 179 bra = cursor; // delete, line 179 slice_del(); break; case 2: // (, line 200 // delete, line 200 slice_del(); break; } return true; }
8
public String convertToString() { String word = ""; for (Letter letter : letterChain) { word += letter.getLetter(); } return word; }
1
public String[] getCategories() { return categories; }
0
public int getMaxFilledBlock(){ int max = 1; for (int step = 2; step < block.size(); step *= 2){ boolean stepIsReasonable = false; for (int i = 0; i < block.size(); i += step){ boolean noDifference = true; for (int k = i; k < i + step - 1; ++k){ if (block.get(k) != block.get(k + 1)){ noDifference = false; break; } } if (noDifference){ ++max; stepIsReasonable = true; break; } } if (!stepIsReasonable){ break; } } return max; }
6
private String bindResourceAndEstablishSession(String resource) throws XMPPException { // Wait until server sends response containing the <bind> element synchronized (this) { if (!resourceBinded) { try { wait(30000); } catch (InterruptedException e) { // Ignore } } } if (!resourceBinded) { // Server never offered resource binding throw new XMPPException("Resource binding not offered by server"); } Bind bindResource = new Bind(); bindResource.setResource(resource); PacketCollector collector = connection .createPacketCollector(new PacketIDFilter(bindResource.getPacketID())); // Send the packet connection.sendPacket(bindResource); // Wait up to a certain number of seconds for a response from the server. Bind response = (Bind) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); collector.cancel(); if (response == null) { throw new XMPPException("No response from the server."); } // If the server replied with an error, throw an exception. else if (response.getType() == IQ.Type.ERROR) { throw new XMPPException(response.getError()); } String userJID = response.getJid(); if (sessionSupported) { Session session = new Session(); collector = connection.createPacketCollector(new PacketIDFilter(session.getPacketID())); // Send the packet connection.sendPacket(session); // Wait up to a certain number of seconds for a response from the server. IQ ack = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); collector.cancel(); if (ack == null) { throw new XMPPException("No response from the server."); } // If the server replied with an error, throw an exception. else if (ack.getType() == IQ.Type.ERROR) { throw new XMPPException(ack.getError()); } } else { // Server never offered session establishment throw new XMPPException("Session establishment not offered by server"); } return userJID; }
8
public int getRosterAvailabilityCode (Date date) { // check roster's availability code for the date. Default is non available for (RosterAvailability ra : rosterAvailability) { if (ra.getDate().compareTo(date) == 0) return ra.getAvailabilityCode(); } return RosterAvailability.ROSTER_ABSENT; }
2
public static void main(String[] args) throws Exception { print("Memory allocated: " + memory + " MB"); if (Debug.splashlogo == true) { JFrame preload = new JFrame("Loading..."); com.sun.awt.AWTUtilities.setWindowOpacity(preload, 0.8f); preload.setBounds(450, 300, 528, 319); preload.add(new PreloadImg("load.png")); preload.setUndecorated(true); preload.setVisible(true); Thread.sleep(1500); preload.setVisible(false); } float heapSizeMegs = (float)(Runtime.getRuntime().maxMemory() / 1024L / 1024L); print("Starting Minecraft ZeTRiX's Launcher"); if (heapSizeMegs > 511.0F) { BuildGui.main(args); } else { try { ArrayList<String> params = new ArrayList<>(); if (ru.zetrix.settings.Util.getPlatform() == ru.zetrix.settings.Util.OS.windows) { params.add("javaw"); // для Windows (Хотя у меня всё нормально работает и при запуске через java, как и на лине) } else { params.add("java"); // для Linux/Mac/остальных } if (Debug.debug == true) { params.add("-Xdebug"); } params.add("-Xms512m"); params.add("-Xmx" + memory + "m"); params.add("-XX:+UseConcMarkSweepGC"); params.add("-XX:+CMSIncrementalPacing"); params.add("-XX:+AggressiveOpts"); params.add("-Dsun.java2d.noddraw=true"); params.add("-classpath"); params.add(BuildGui.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); params.add("ru.zetrix.engine.BuildGui"); print(params.toString()); ProcessBuilder McZEngine = new ProcessBuilder(params); Process process = McZEngine.start(); if (process == null) throw new Exception("!"); System.exit(0); } catch (Exception e) { print("Error: " + e); BuildGui.main(args); } } }
6
static void unzip(File targetDir, File zipFile) { int BUFFER = 4096; try { FileInputStream fis = new FileInputStream(zipFile); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; int count; byte data[] = new byte[BUFFER]; while ((entry = zis.getNextEntry()) != null) { System.out.println("Extracting: " + entry); FileOutputStream fos = new FileOutputStream(new File(targetDir, entry.getName())); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } zis.close(); } catch (Exception e) { e.printStackTrace(System.err); } }
3
public void runLogic(){ checkAces(); hitMe(); bust =checkBust(); }
0
public synchronized void addEntry(int cashpointNr,double price, int abgKunden, String productNames, String pricelist, int queuesize){ BalanceEntry balanceEntry = null; if(getBalanceEntry(cashpointNr) != null){ balanceEntry = getBalanceEntry(cashpointNr); balanceEntry.addPrice(price); balanceEntry.setAbKunden(abgKunden); balanceEntry.setProductNames2(productNames); balanceEntry.setPricelist(pricelist); balanceEntry.setQueuesize(queuesize); } else { balanceEntry = new BalanceEntry(cashpointNr,price,abgKunden,productNames,pricelist,queuesize); balances.add(balanceEntry); } Collections.sort(balances); Runnable changeUi = new Runnable() { @Override public void run() { while(tmodel.getRowCount() > 0){ tmodel.removeRow(0); } Vector<String> balancVector; synchronized (Balance.this) { for (BalanceEntry balanceentry : balances) { balancVector = new Vector<>(); balancVector.add(Integer.toString(balanceentry.getCashpointNr())); balancVector.add(Double.toString(balanceentry.getPrice())); balancVector.add(Integer.toString(balanceentry.getAbKunden())); balancVector.add(Integer.toString(balanceentry.getQueuesize())); balancVector.add(balanceentry.getProductNames2()); balancVector.add(balanceentry.getPricelist()); tmodel.addRow(balancVector); } } } }; SwingUtilities.invokeLater(changeUi); }
3
public NormalMove(Player player, Board board, Piece piece, Field from, Field to) { super(player, board, piece, from, to); }
0
final public SimpleNode Start() throws ParseException { /*@bgen(jjtree) Start */ SimpleNode jjtn000 = new SimpleNode(JJTSTART); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { Expression(); jj_consume_token(LF); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; {if (true) return jjtn000;} } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } throw new Error("Missing return statement in function"); }
9
@XmlTransient public Collection<Observacion> getObservacionCollection() { return observacionCollection; }
0
public static String getJRobinHomeDirectory() { String className = Util.class.getName().replace('.', '/'); String uri = Util.class.getResource("/" + className + ".class").toString(); if(uri.startsWith("file:/")) { uri = uri.substring(6); File file = new File(uri); // let's go 5 steps backwards for(int i = 0; i < 5; i++) { file = file.getParentFile(); } uri = file.getAbsolutePath(); } else if(uri.startsWith("jar:file:/")) { uri = uri.substring(10, uri.lastIndexOf('!')); File file = new File(uri); // let's go 2 steps backwards for(int i = 0; i < 2; i++) { file = file.getParentFile(); } uri = file.getAbsolutePath(); } else { uri = null; } return uri; }
4
String readLabel() { return label; }
0
private void persist(PersistAction persistAction, String successMessage) { if (selected != null) { this.setEmbeddableKeys(); try { if (persistAction != PersistAction.DELETE) { this.ejbFacade.edit(selected); } else { this.ejbFacade.remove(selected); } JsfUtil.addSuccessMessage(successMessage); } catch (EJBException ex) { Throwable cause = JsfUtil.getRootCause(ex.getCause()); if (cause != null) { if (cause instanceof ConstraintViolationException) { ConstraintViolationException excp = (ConstraintViolationException) cause; for (ConstraintViolation s : excp.getConstraintViolations()) { JsfUtil.addErrorMessage(s.getMessage()); } } else { String msg = cause.getLocalizedMessage(); if (msg.length() > 0) { JsfUtil.addErrorMessage(msg); } else { JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } } } catch (Exception ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/PaquetesTuristicos").getString("PersistenceErrorOccured")); } } }
8
public static void act(Unit unit) { // NOT cloaked. if (!unit.isCloaked()) { if (unit.getEnergy() > 10 && TechnologyManager.isWraithCloakingFieldResearched()) { unit.cloak(); UnitActions.useTech(unit, TechnologyManager.CLOAKING_FIELD); } } // CLOAKED. else { double nearestEnemyDist = xvr.getNearestEnemyDistance(unit, true, true); boolean isEnemyNear = nearestEnemyDist < -0.1 && nearestEnemyDist > 11; boolean isDetectedByEnemy = unit.isDetected(); if (isEnemyNear || isDetectedByEnemy) { unit.decloak(); } } }
6
public World getLoadedWorld() { return loadedWorld; }
0
public int checkPTW() { if(cornerMap.get("P").equals("P") && cornerMap.get("T").equals("T") && cornerMap.get("W").equals("W")) { return SOLVED; } if(cornerMap.get("P").equals("W") && cornerMap.get("T").equals("P") && cornerMap.get("W").equals("T")) { return CW; } if(cornerMap.get("P").equals("T") && cornerMap.get("T").equals("W") && cornerMap.get("W").equals("P")) { return CCW; } return UNSOLVED; }
9