method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
65b720b4-1a49-4fb7-b351-aa40b0991786
6
public void negate() { boolean doneZeros = false; boolean doneFirst = false; for (int i = digits.size() - 1; i >= 0; i--) { if ((digits.get(i)) > 0) { doneZeros = true; } if (!doneFirst && doneZeros) { int temp = 10 - digits.get(i); digits.set(i, temp); // System.out.println("made it"); doneFirst = true; } else if (doneFirst && doneZeros) { int temp = 9 - digits.get(i); digits.set(i, temp); } } }
4625d327-deb7-4e32-8805-9b316aea4c7a
0
private boolean sendHandshake(Socket socket, byte[] remotePeerId, boolean obfuscate) throws IOException { OutputStream os = socket.getOutputStream(); Handshake hs = Handshake.craft(this.torrent.getInfoHash(),this.id, remotePeerId, obfuscate); os.write(hs.getBytes()); logger.debug("Send Handshake to " + this.socketRepr(socket) + ": " + Torrent.byteArrayToHexString(hs.getBytes())); return hs.isObfuscated(); }
2d86f244-76a1-4c2a-9e46-d5aaaed395f0
9
public List<RefactoringSuggestion> call(String[] args) { Options options = new Options(); options.addOption("cceor", true, "Consolidate Conditional Expression Or"); options.addOption("cceand", true, "Consolidate Conditional Expression And"); options.addOption("cdcf", false, "Consolidate Duplicate Conditional Fragments"); options.addOption("dc", true, "Decompose Conditional"); options.addOption("iev", true, "Introduce Explaining Variable"); @SuppressWarnings("static-access") Option fileOption = OptionBuilder.withArgName("file").hasArg() .withDescription("File to analyze").create("file"); fileOption.setRequired(true); options.addOption(fileOption); HelpFormatter formatter = new HelpFormatter(); try { CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); List<RefactoringSuggestionVisitor> visitors = new ArrayList<>(); if (cmd.hasOption("dc")) { visitors.add(new DecomposeConditional(Integer.parseInt(cmd .getOptionValue("dc")))); } if (cmd.hasOption("iev")) { visitors .add(new IEVVisitor(Integer.parseInt(cmd.getOptionValue("iev")))); } if (cmd.hasOption("cdcf")) { visitors.add(new CDCFVisitor()); } if (cmd.hasOption("cceand")) { visitors.add(new ConsolidateAndVisitor(Integer.parseInt(cmd .getOptionValue("cceand")))); } if (cmd.hasOption("cceor")) { visitors.add(new ConsolidateOrVisitor(Integer.parseInt(cmd .getOptionValue("cceor")))); } File inputFile = new File(cmd.getOptionValue("file")); if (inputFile.exists()) { JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager javaFileManager = javaCompiler .getStandardFileManager(null, null, null); JavacTask javacTaskImpl = (JavacTask) javaCompiler.getTask( null, javaFileManager, null, null, null, javaFileManager.getJavaFileObjects(inputFile)); try { Iterable<? extends CompilationUnitTree> l = javacTaskImpl.parse(); CompilationUnitTree t = l.iterator().next(); Context context = new Context(); context.compilationUnitTree = t; context.trees = Trees.instance(javacTaskImpl); context.sourcePositions = context.trees.getSourcePositions(); List<RefactoringSuggestion> refsList = runRefactoringSuggestions( visitors, t, context); return refsList; } catch (IOException e) { e.printStackTrace(); } } else { System.err.println("Input file does not exist."); System.exit(-1); } } catch (ParseException e1) { formatter.printHelp("Goose", options); } return new ArrayList<>(); }
74021a6a-c084-40a2-afb1-48917b0b654d
5
public static String colorize(String in) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < in.length(); i++) { if (in.charAt(i) == '&' && i < in.length() - 1) { char ctrl = in.charAt(i + 1); ChatColor cc = ChatColor.getByChar(ctrl); if (cc != null) { sb.append(cc); i++; } else if (ctrl == '&') { sb.append('&'); i++; } else { sb.append('&'); } } else { sb.append(in.charAt(i)); } } return sb.toString(); }
583e28d9-4f2e-4a19-887d-3b117f2f4b6d
9
@Override public void onUpdate(World apples) { if (!apples.inBounds(X, Y)||life--<0) { alive = false; //apples.explode(X, Y, 32, 8, 16); } if (!apples.isSolid(X, Y-10)) { Y-=10; } for (int i = 1; i < 10; i++) { if (!apples.isSolid(X, Y+i)) { Y+=i; } } if (apples.x>X-48&&apples.x<X+48) { if (apples.y>Y-48&&apples.y<Y+48) { apples.status |= World.ST_SHOCKED; } } /*if (yspeed<12) { yspeed++; }*/ }
d026a82b-a2a1-49b8-b2b8-4bc07e83704b
3
private <T extends Comparable> boolean search(T value, BinaryTree root) { boolean result = false; if (root == null) { result = false; } else { if (value == root.getValue()) result = true; else { if (value.compareTo(root.getValue()) < 0) { result = search(value, root.left); } else { result = search(value, root.right); } } } return result; }
3d1120a6-15f2-4b36-ba3f-4a970b4a743f
5
private boolean noCopy() { Iterator<Point> it = pointIterator(); while(it.hasNext()) { Point a = it.next(); int count = 0; Iterator<Point> et = pointIterator(); while(et.hasNext()) { Point b = et.next(); if (a.x == b.x && a.y == b.y) ++count; } if (count != 1) return false; } return true; }
67e1de55-a133-461f-b646-7914fae001f4
4
protected void slice_check() { if (bra < 0 || bra > ket || ket > limit || limit > current.length()) // this line could be removed { System.err.println("faulty slice operation"); // FIXME: report error somehow. /* fprintf(stderr, "faulty slice operation:\n"); debug(z, -1, 0); exit(1); */ } }
41807b18-21f1-4f94-8f33-ca329f4e1215
5
public final void setFrame() { try { if (icons.size() == 0) icons.add(ImageIO.read(Frame.class.getResource("/logo.png"))); } catch (IOException e) { System.out.println("LOGO not located"); } addComponentListener(TCode.input); if (TCode.frameWidth == 0) TCode.frameWidth = TCode.screenWidth; if (TCode.frameHeight == 0) TCode.frameHeight = TCode.screenHeight; setTitle(); setBounds((TCode.screenWidth / 2) - (TCode.frameWidth / 2), (TCode.screenHeight / 2) - (TCode.frameHeight / 2), TCode.frameWidth, TCode.frameHeight); super.setIconImages(icons); setUndecorated(!framed); // Manage WindowEvents setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { // Open an exit dialogue box if the user tries to exit public void windowClosing(WindowEvent event) { int answer = JOptionPane.showConfirmDialog(null, "Are you sure you want to quit?", "Exit program?", JOptionPane.YES_NO_OPTION); if (answer == JOptionPane.YES_OPTION) { System.exit(0); } } }); setResizable(resizable); setVisible(true); TCode.canvasWidth = getWidth() - getInsets().left - getInsets().right; TCode.canvasHeight = getHeight() - getInsets().top - getInsets().bottom; }
388da7a8-4f48-4d32-9d3c-1b0249e10fb7
1
public List<Row> getChildren() { return canHaveChildren() ? Collections.unmodifiableList(mChildren) : null; }
b00fbe75-0114-44ce-9fef-bd0b94e4d7d6
4
public void sendUpdates() { if(connection.isClosed()) { System.out.println("Why are you updating a closed socket?"); return; } try { //write each queued event to output while(queuedEvents.size()>0) { UpdateEvent event = queuedEvents.poll(); if(event!=null){ event.writeTo(connection.getOutputStream()); } } //flush the data connection.getOutputStream().flush(); } catch (IOException e) { System.out.println("Error writing data to "+id+"'s socket."); e.printStackTrace(); } }
c247f7b5-72e8-491b-acce-149b9e420522
6
public IntegerWrapper integerUpperBound() { { IntervalCache interval = this; { Stella_Object ub = interval.upperBound; if (ub != null) { { Surrogate testValue000 = Stella_Object.safePrimaryType(ub); if (Surrogate.subtypeOfIntegerP(testValue000)) { { IntegerWrapper ub000 = ((IntegerWrapper)(ub)); if (interval.strictUpperBoundP) { return (IntegerWrapper.wrapInteger(IntegerWrapper.unwrapInteger(ub000) - 1)); } else { return (ub000); } } } else if (Surrogate.subtypeOfFloatP(testValue000)) { { FloatWrapper ub000 = ((FloatWrapper)(ub)); if (interval.strictUpperBoundP) { if (Stella.integerValuedP(FloatWrapper.unwrapFloat(ub000))) { return (IntegerWrapper.wrapInteger(Native.floor(FloatWrapper.unwrapFloat(ub000)) - 1)); } else { return (IntegerWrapper.wrapInteger(Native.floor(FloatWrapper.unwrapFloat(ub000)))); } } else { return (IntegerWrapper.wrapInteger(Native.floor(FloatWrapper.unwrapFloat(ub000)))); } } } else { return (null); } } } return (null); } } }
5acd7e3a-2d27-419e-bebf-9f902fa7c0ab
0
public static void main(String[] args) { double d = 257.234; int i = (int) d; System.out.println(i); // 257 byte b = (byte) d; System.out.println(b); // 1 (257%256) }
62d108f2-d938-4b53-a91a-42d124fb8ff4
7
@Override public void onUpstreamMessageEvent(ChannelMessageEvent event, PipelineHandlerContext context) throws Exception { if( !(event.getMessage() instanceof IOBuffer) || errorState ) { context.sendUpstream(event); return; } IOBuffer buffer = (IOBuffer) event.getMessage(); bufferChain.getLock().lock(); try { bufferChain.addBuffer(buffer); event.getFuture().onSuccess(); while( bufferChain.hasReadableBytes() ) { Object result; try { result = decode(state, bufferChain, event.getChannel()); } catch(BufferUnderflowException e) { bufferChain.setReadPosition(readPos); break; } catch(Exception e) { errorState = true; context.sendUpstream(new ChannelMessageEvent(event.getChannel(), new PipelineDecoderErrorMessage(this, e))); return; } if( result == null ) continue; context.sendUpstream(new ChannelMessageEvent(event.getChannel(), result)); } if( !bufferChain.hasReadableBytes() ) { readPos = 0; bufferChain.clear(); } } finally { bufferChain.getLock().unlock(); } }
f1de9b60-77df-46a2-bbd1-6bcf9f14bd4a
8
private static Case directionOptimaleEchappee(Grille grille, Case caseMission) { Monstre monstres = grille.getNbVampires(caseMission) != 0 ? Monstre.VAMPIRES : Monstre.LOUPS; ArrayList<Case> toutesCasesAdjacentes = grille.getToutesCasesAdjacentes(caseMission); ArrayList<Case> casesDisponibles = new ArrayList<Case>(); ArrayList<Case> casesDangereuses = new ArrayList<Case>(); for (Case caseAdjacente : toutesCasesAdjacentes) { if (monstres == Monstre.LOUPS) { if (grille.getNbVampires(caseAdjacente) == 0) { casesDisponibles.add(caseAdjacente); } else { casesDangereuses.add(caseAdjacente); } } else { if (grille.getNbLoups(caseAdjacente) == 0) { casesDisponibles.add(caseAdjacente); } else { casesDangereuses.add(caseAdjacente); } } } int meilleureDistance = 0; Case meilleureCase = null; for (Case caseDispo : casesDisponibles) { int distanceTotale = 0; for (Case caseDangereuse : casesDangereuses) { distanceTotale += Utils.distance(caseDangereuse, caseDispo); } if (distanceTotale > meilleureDistance) { meilleureDistance = distanceTotale; meilleureCase = caseDispo; } } return meilleureCase; }
81893418-2387-45f7-803d-58cc54fdcf9e
0
public List findByActive(Object active) { return findByProperty(ACTIVE, active); }
d7cd1e9b-b1f1-4b9a-b2df-91e4b24a0c8b
8
public void setInstances(Instances inst) { m_Instances = inst; String [] attribNames = new String [m_Instances.numAttributes()]; for (int i = 0; i < attribNames.length; i++) { String type = ""; switch (m_Instances.attribute(i).type()) { case Attribute.NOMINAL: type = "(Nom) "; break; case Attribute.NUMERIC: type = "(Num) "; break; case Attribute.STRING: type = "(Str) "; break; case Attribute.DATE: type = "(Dat) "; break; case Attribute.RELATIONAL: type = "(Rel) "; break; default: type = "(???) "; } attribNames[i] = type + m_Instances.attribute(i).name(); } m_ClassCombo.setModel(new DefaultComboBoxModel(attribNames)); if (attribNames.length > 0) { if (inst.classIndex() == -1) m_ClassCombo.setSelectedIndex(attribNames.length - 1); else m_ClassCombo.setSelectedIndex(inst.classIndex()); m_ClassCombo.setEnabled(true); m_StartBut.setEnabled(m_RunThread == null); m_StopBut.setEnabled(m_RunThread != null); } else { m_StartBut.setEnabled(false); m_StopBut.setEnabled(false); } }
6f769cf7-48df-4828-8237-88c3290fe865
9
public static String possibleQueenMoves(int i) { String list="", oldPiece; int r=i/8, c=i%8; int temp=1; for (int j=-1; j<=1; j++) { for (int k=-1; k<=1; k++) { if(j!=0 || k!=0) { try { while("_".equals(MoveGen.chessBoard[r+temp*j][c+temp*k])) { oldPiece=MoveGen.chessBoard[r+temp*j][c+temp*k]; MoveGen.chessBoard[r][c]="_"; MoveGen.chessBoard[r+temp*j][c+temp*k]="Q"; if (King.kingSafe()) { list=list+r+c+(r+temp*j)+(c+temp*k)+oldPiece; } MoveGen.chessBoard[r][c]="Q"; MoveGen.chessBoard[r+temp*j][c+temp*k]=oldPiece; temp++; } if (Character.isLowerCase(MoveGen.chessBoard[r+temp*j][c+temp*k].charAt(0))) { oldPiece=MoveGen.chessBoard[r+temp*j][c+temp*k]; MoveGen.chessBoard[r][c]="_"; MoveGen.chessBoard[r+temp*j][c+temp*k]="Q"; if (King.kingSafe()) { list=list+r+c+(r+temp*j)+(c+temp*k)+oldPiece; } MoveGen.chessBoard[r][c]="Q"; MoveGen.chessBoard[r+temp*j][c+temp*k]=oldPiece; } } catch (Exception e) { } temp=1; } } } return list; }
d40fab68-0eb2-4cf9-bd7a-870b634377a7
1
private static List<Integer> generate() { List<Integer> list = new LinkedList<Integer>(); for (int i = 0; i < 10; i++) { int num = new Random().nextInt(100); list.add(num); } Collections.shuffle(list); return Collections.unmodifiableList(list); }
2e571e45-e82c-4feb-a170-08d2ac9bd89e
0
public SetModeRainbowDanceParty(){ super(colors,1.0/20); }
a0db1c58-8dd2-4c82-88b7-2c9c9e47e36d
1
private void getCountryCollection(AbstractDao dao, List<Direction> directions) throws DaoException { for (Direction dir : directions) { Criteria crit = new Criteria(); crit.addParam(DAO_ID_DIRECTION, dir.getIdDirection()); List<LinkDirectionCountry> links = dao.findLinkDirectionCountry(crit); dir.setCountryCollection(getCountryInfo(dao, links)); } }
c3879fc8-ad67-4829-9d75-feddfc0e1ca5
6
public void activate(){ activated = true; //set activated boolean allActive; //have all the parents been activated? time = 0; //find the longest time from parents (critical time) for(Connection g:input){ if(time < g.getParent().time) time = g.getParent().time; } //add current gate's propagation delay to critical time time += Circuit.propagationTimes.get(type.toString()); //calculate the gate's output depending on inputs and gate type processGateLogic(); //iterate through all the inputs of each child to check if they're ready to be activated for(Connection g : output){ // Cycle through all outputs allActive = true; // variable to check if all inputs are activated for(Connection j : g.getChild().input){ // iterate through all the inputs if(j.getParent().activated == false) // if one of the inputs on the child aren't activated, don't activate it allActive = false; } if(allActive == true) g.getChild().activate(); // if all of the inputs on this child are active, then activate that child (yay recursion) } }
e9878e3d-63e4-446f-a9c8-f000b35bc682
7
private void initBlocks(){ blocks.clear(); blocks.add(new Block(180,120,16,16)); blocks.add(new Block(50,120,16,16)); blocks.add(new Block(88,160,16,16)); blocks.add(new Block(88+16,160,16,16)); blocks.add(new Block(88+32,160,16,16)); int y=208; for(int i=0;i<31;i++){ blocks.add(new Floor(i*16,y,16,16)); blocks.add(new Floor(i*16,y+16,16,16)); } int x=34*16; for(int i=0;i<16;i++){ blocks.add(new Floor(i*16+x,y,16,16)); blocks.add(new Floor(i*16+x,y+16,16,16)); } x+=(16+7)*16; for(int i=0;i<38;i++){ blocks.add(new Floor(i*16+x,y,16,16)); blocks.add(new Floor(i*16+x,y+16,16,16)); } x+=(38+4)*16; for(int i=0;i<32;i++){ blocks.add(new Floor(i*16+x,y,16,16)); blocks.add(new Floor(i*16+x,y+16,16,16)); } x+=(32+4)*16; for(int i=0;i<20;i++){ blocks.add(new Floor(i*16+x,y,16,16)); blocks.add(new Floor(i*16+x,y+16,16,16)); } x=39*16; for(int i=0;i<4;i++){ blocks.add(new Block(i*16+x,208-4*16,16,16)); } x+=4*16; for(int i=0;i<8;i++){ blocks.add(new Block(i*16+x,208-7*16,16,16)); } }
c7eff4e8-3ffe-4412-96e2-1e25d9a0db7e
3
public void deregister(final Region region) { this.regions.remove(region); this.references.remove(region); this.catalog.deregisterOptions(region); // unload region from any loaded chunk index entries final Iterator<Entry<Long, Set<Region>>> it = this.cache.entrySet().iterator(); while (it.hasNext()) { final Entry<Long, Set<Region>> next = it.next(); if (next.getValue().remove(region)) if (next.getValue().size() == 0) it.remove(); } }
7109754c-1b10-4bb8-9601-e19951404593
5
@Override protected void channelRead0(ChannelHandlerContext ctx, HttpObject obj) throws Exception { if (obj instanceof HttpRequest) { HttpRequest req = (HttpRequest) obj; if (shouldBlock(req)) { logger.info("Blocking black-listed request: " + req.getUri()); sendForbidden(ctx, req); blockingRequest = true; } else { ctx.fireChannelRead(obj); } } if (obj instanceof HttpContent && blockingRequest) { if (obj instanceof LastHttpContent) { blockingRequest = false; } return; } ctx.fireChannelRead(obj); }
b6c25c9c-5df4-41a0-9bcd-e8c1de664822
3
private void tick() { if (index == 4) { System.exit(ERROR); } menus.get(index).tick(); for (int i = 0; i < timers.size(); i++) { timers.get(i).tick(); } for (Animation a : anims) { a.tick(); } }
cfea9e07-0f2e-4be9-b900-f3a869deb1ab
3
public int getEdgeNumber(){ int counter = 0; for(int i = 0; i < number; i++){ for(int j = 0; j < number; j++){ if(matrix[i][j] == 1){ counter++; } } } return counter / 2; }
85ffa3a3-286d-4426-9d0b-d70898adb743
7
private void addInteraction(ThreatClass threatClass, AbstractInsnNode abstractInsnNode) { AbstractInsnNode previousNode = abstractInsnNode.getPrevious(); if (previousNode instanceof VarInsnNode) { int var = ((VarInsnNode) previousNode).var; previousNode = previousNode.getPrevious(); while (previousNode != null) { if (previousNode instanceof VarInsnNode) { VarInsnNode varInsnNode = (VarInsnNode) previousNode; if (varInsnNode.getOpcode() > 53 && varInsnNode.getOpcode() < 87 && varInsnNode.var == var) { previousNode = varInsnNode.getPrevious(); break; } } previousNode = previousNode.getPrevious(); } } if (previousNode instanceof LdcInsnNode) threatClass.addInteraction("" + ((LdcInsnNode) previousNode).cst); }
69298797-d596-47b6-80d4-112beb5267a3
6
private boolean checkAuthURL(String action, String... params) { // if there isn't at least one parameter OR // if params length is not an even number if (params.length < 2 || ((params.length % 2) != 0)) return false; try { //HttpURLConnection.setFollowRedirects(false); HttpURLConnection uc = (HttpURLConnection) new URL(plugin.getConfig().getString("authurl.url")).openConnection(); uc.setRequestMethod("POST"); uc.setDoInput(true); uc.setDoOutput(true); uc.setUseCaches(false); uc.setAllowUserInteraction(false); uc.setInstanceFollowRedirects(false); uc.setRequestProperty("User-Agent", "Mozilla/5.0 authURL/" + version); uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream(uc.getOutputStream()); // first lets write the authurl_version we are working with out.writeBytes("authurl_version=" + version); // now write the IP if it is set writeParam(out, "ip", this.ipAddress); writeParam(out, "action", action); for (int x = 0; x < params.length; ++x) writeParam(out, params[x], params[++x]); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String line = in.readLine(); boolean success = line != null && line.equals("YES"); response = in.readLine(); if (plugin.getConfig().getBoolean("authurl.groups")) group = in.readLine(); in.close(); return success; } catch (Exception e) { //response = e.getMessage(); xAuthLog.severe("Failed to process AuthURL script during action: " + action, e); return false; } }
2af28d5a-18cb-4165-a876-3cd4f1430e14
3
public static String extractChars(String s) { if (s == null) { return StringPool.BLANK; } StringBuilder sb = new StringBuilder(); char[] c = s.toCharArray(); for (int i = 0; i < c.length; i++) { if (Validator.isChar(c[i])) { sb.append(c[i]); } } return sb.toString(); }
2c0d65d4-96c3-4317-99aa-b6aa092012b8
5
protected Map<String, Object> postProcessCellStyle(Map<String, Object> style) { if (style != null) { String key = mxUtils.getString(style, mxConstants.STYLE_IMAGE); String image = getImageFromBundles(key); if (image != null) { style.put(mxConstants.STYLE_IMAGE, image); } else { image = key; } // Converts short data uris to normal data uris if (image != null && image.startsWith("data:image/")) { int comma = image.indexOf(','); if (comma > 0) { image = image.substring(0, comma) + ";base64," + image.substring(comma + 1); } style.put(mxConstants.STYLE_IMAGE, image); } } return style; }
5d92b33d-272e-472c-9dc0-17ecd5d807ea
2
public List<Vector3f> getHotSpotsFor(String key){ List<Vector3f> modelHotSpots = getModel().getHotSpotFor(key); List<Vector3f> transformedSpots = new ArrayList<Vector3f>(); Matrix4f transform = getTransformInverse(); if(modelHotSpots != null) for(Vector3f vec : modelHotSpots) transformedSpots.add(transform.times(vec)); return transformedSpots; }
c75d62a5-bef7-42dd-a31c-8845f9345053
5
private static boolean closeFrames(boolean significant) { for (Frame frame : Frame.getFrames()) { if (frame instanceof SignificantFrame == significant && frame.isShowing()) { try { if (!CloseCommand.close(frame)) { return false; } } catch (Exception exception) { Log.error(exception); } } } return true; }
dbfb4e5b-e85c-4e4b-9e7c-697ee407d35b
5
public Position getNextPos(Node n){ Map map = Tools.getBackgroundMap(); Position newPos = new Position(); boolean inLake = false; if(Configuration.useMap){ inLake = !map.isWhite(n.getPosition()); //we are already standing in the lake } if(inLake){ Main.fatalError("A node is standing in a lake. Cannot find a step outside."); } do{ inLake = false; newPos = super.getNextPos(n); if(Configuration.useMap){ if(!map.isWhite(newPos)) { inLake = true; super.remaining_hops = 0;//this foces the node to search for an other target... } } } while(inLake); return newPos; }
80994343-1cfa-415e-92ad-5f845d3ad38f
3
public int getIdByData(String name, String shortDescription, String version, LanguageTypeEnum language){ int result = -1; try { PreparedStatement statement = connection.prepareStatement(GET_ID_BY_DATA); statement.setString(1, name); statement.setString(2, shortDescription); statement.setString(3, version); statement.setString(4, language.name()); ResultSet set = statement.executeQuery(); if(set.next() == false) return -1; result = Integer.parseInt(set.getString("idlibrary")); if(set.next() == true) { throw new IllegalArgumentException("Database has more that one libraries by these data"); } } catch (SQLException e) { e.printStackTrace(); } return result; }
cf234ef9-7660-4abe-868b-e3fe5aa618fb
2
public byte[] process(byte[] srcBytes, boolean encrypt) { try { Cipher cipher = Cipher.getInstance("DES"); cipher.init(encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, key); return cipher.doFinal(srcBytes); } catch (Exception e) { throw new IllegalArgumentException(e); } }
1e1080ee-14e9-4fc7-8b54-892ac2f037c7
3
private static void addStartButtonListener(JButton Start){ // <editor-fold defaultstate="collapsed" desc="MBO Start Button"> Start.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fromMBO = true; schedule = mbo.getSchedule(); int numTrainsToSpawn = schedule.get(0).getTime().size(); numStations = schedule.size(); StringBuffer s = new StringBuffer(); for(ScheduleNode n : schedule){ s.append(n.getStop()); s.append(n.getTimes()); } office.textSchedule.setText(s.toString()); if(!timer.isRunning()) timer.start(); System.out.println("TRAINS: " + numTrainsToSpawn); for(int i=0; i<numTrainsToSpawn; i++){ spawnTrain(); } } }); }// </editor-fold>
3b1c589d-dcc6-4dc0-a9e2-80ad301465bb
4
@Override public List<Player> selectPlayerOfMatchByDayHour(int heure, int day) throws SQLException, IOException { connexionDB = ConnexionMysqlFactory.getInstance(); ResultSet rs = null; List<Player> lp = new ArrayList<>(); Statement st = connexionDB.createStatement(); try (PreparedStatement ps = connexionDB.prepareStatement("select * from pulp.player where playerId in (select idP1 from pulp.attribmatch where matchId in " + "(select matchId from pulp.match where matchtrancheHoraire=? and matchDate=?))")) { ps.setInt(1, heure); ps.setInt(2, day); try { rs = ps.executeQuery(); while (rs.next()) { lp.add(new Player(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getInt(5))); } } catch (SQLException e) { System.err.println(e.getMessage()); } } try (PreparedStatement ps = connexionDB.prepareStatement("select * from pulp.player where playerId in (select idP2 from pulp.attribmatch where matchId in " + "(select matchId from pulp.match where matchTrancheHoraire=? and matchDate=?))")) { ps.setInt(1, heure); ps.setInt(2, day); try { rs = ps.executeQuery(); while (rs.next()) { lp.add(new Player(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getInt(5))); } } catch (SQLException e) { System.err.println(e.getMessage()); } } connexionDB.close(); return lp; }
526d1058-236f-4ad0-9b68-0d5bf0b85147
6
public static void main(String[] args) { System.out.println("Enter # of Rows"); int rows = in.nextInt(); for (int column = 1; column <= rows; column++) { for (int row = 1; row <= column; row++) { if (row == 1 && column == 1) { for (int i = 1; i <= rows; i++) { System.out.print(decFormat.format(i) + " "); } } else { if (column == 1) { System.out.print(decFormat.format(row) + " "); } else { System.out.print(decFormat.format(column * row) + " "); } } } System.out.println(""); } BlockLetters.TONY_PAPPAS.outputBlockName(); }
f9ec079d-bfb2-4079-aac0-83e58db20231
5
public boolean existWhiteForest(){ for(int i=0;i<getDim();i++) for(int j=0;j<getDim();j++) if(!damiera[i][j].isFree() && damiera[i][j].getPezzo().getColore()==Color.WHITE) if(!damiera[i][j].getPezzo().getAlberoMosse().isSAMNull()) return true; return false; }
6e940893-7628-4851-9267-324b0ae8c546
8
public Object nextValue() throws JSONException { char c = nextClean(); String s; switch (c) { case '"': case '\'': return nextString(c); case '{': back(); return new JSONObject(this); case '[': case '(': back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = next(); } back(); s = sb.toString().trim(); if (s.equals("")) { throw syntaxError("Missing value"); } return JSONObject.stringToValue(s); }
4c599fe7-1f6c-44bd-a080-9be88181f927
3
public void setFullScreen(JFrame w, DisplayMode dm) { w.dispose(); w.setUndecorated(true); //display mode support if (vc.isDisplayChangeSupported()) { try { vc.setDisplayMode(dm); } catch (Exception ex) { vc.setDisplayMode(vc.getDisplayModes()[0]); //use first available display mode } } //fullscreen support if (vc.isFullScreenSupported()) { vc.setFullScreenWindow(w); fullScreen=true; } //ScreenDimension.setScreenDimension(window, new Dimension(1280,800)); }
aae639fa-93cc-485d-8cea-83b4754f5e57
5
public Snake(Vector2f head, int length, int direction, ReadableColor color) { this.initialSnake = new ArrayList<Vector2f>(); for (int i = 0; i < length; i++) { if (direction == 0) initialSnake.add(initialSnake.size(), new Vector2f(head.x - i, head.y)); else if (direction == 1) initialSnake.add(initialSnake.size(), new Vector2f(head.x, head.y - i)); else if (direction == 2) initialSnake.add(initialSnake.size(), new Vector2f(head.x + i, head.y)); else if (direction == 3) initialSnake.add(initialSnake.size(), new Vector2f(head.x, head.y + i)); } initialDirection = direction; this.reset(); scoreText = new Text(null, ""); scoreText.setFontSize(16); scoreText.position = new Vector2f(10 + Game.snakes.size() * 100, Game.resY - scoreText.getHeight() - 10); highscoreText = new Text(null, ""); highscoreText.setFontSize(16); highscoreText.position = new Vector2f(scoreText.position.x, scoreText.position.y - scoreText.getHeight()); hitSound = new Sound("res/sounds/hit.wav"); loseSound = new Sound("res/sounds/lose.wav"); this.color = color; useAI = false; }
fb847e3f-3ec9-47da-a692-c287ba6e7b63
3
public static long unsortedExperiment(){ startTime = (new Date()).getTime(); int choice; Long number; for(int i = 0; i < NUMBER_OF_CHOICES; i++) { choice = choices[i]; number = numbers[choice]; if(!linearSearch(number)) { System.out.println("Not found"); break; } else if(linearSearch(123L)) { System.out.println("123L found"); break; } } return (new Date()).getTime() - startTime; }
13890f2b-1a49-44f3-b037-801919fdf451
5
private boolean gatherKeyPointers(){ String keys; try{ keys = fileToString(pointerStorage); } catch (RuntimeException e){ System.out.println("Can't read pointer storage, perhaps it's empty"); return false; } String key = ""; String position = ""; boolean keyFLG = true; for (char ch : keys.toCharArray()){ if (ch == '-'){ keyFLG = false; continue; } else if (ch == ';'){ keyFLG = true; keyPointers.put(key, Long.parseLong(position)); key = ""; position = ""; continue; } if (keyFLG){ key += ch; } else { position += ch; } } return true; }
4d209bdd-2671-4a70-95bf-f18188fd4d64
0
@OneToMany(mappedBy="event1") public List<Car> getCars() { return cars; }
18b82f41-d614-45b6-9045-f6b5329d689f
5
public int getNumber(String colors) { if (colors.length() == 0) return 0; int result = 1; int i = 0; while (i < colors.length()) { int max = 1; i++; while ((i < colors.length()) && (colors.charAt(i) == colors.charAt(i - 1)) ) { i++; max++; } if (max > result) result = max; } return colors.length() - result; }
f51d44ad-c101-4210-82c2-05d5b3beea78
8
@Override public void run() { // First time through the while loop we do the merge // that we were started with: MergePolicy.OneMerge merge = this.startMerge; try { if (verbose()) message(" merge thread: start"); while(true) { setRunningMerge(merge); doMerge(merge); // Subsequent times through the loop we do any new // merge that writer says is necessary: merge = writer.getNextMerge(); if (merge != null) { writer.mergeInit(merge); if (verbose()) message(" merge thread: do another merge " + merge.segString(dir)); } else break; } if (verbose()) message(" merge thread: done"); } catch (Throwable exc) { // Ignore the exception if it was due to abort: if (!(exc instanceof MergePolicy.MergeAbortedException)) { if (!suppressExceptions) { // suppressExceptions is normally only set during // testing. anyExceptions = true; handleMergeException(exc); } } } finally { synchronized(ConcurrentMergeScheduler.this) { ConcurrentMergeScheduler.this.notifyAll(); boolean removed = mergeThreads.remove(this); assert removed; } } }
bcbecd73-fa93-4996-8b10-44cd00e5f4f5
8
public Stardata Fk425(Stardata s1950) { double r, d, ur, ud, px, rv, sr, cr, sd, cd, w, wd, x, y, z, xd, yd, zd, rxysq, rxyzsq, rxy, rxyz, spxy, spxyz; int i, j; /* Star position and velocity vectors */ double r0[] = new double[3], rd0[] = new double[3]; /* Combined position and velocity vectors */ double v1[] = new double[6], v2[] = new double[6]; /* Radians per year to arcsec per century */ final double pmf = 100.0 * 60.0 * 60.0 * 360.0 / D2PI; /* * Canonical constants (see references) */ /* * Km per sec to AU per tropical century = 86400 * 36524.2198782 / * 1.49597870e8 */ double vf = 21.095; /* Constant vector and matrix (by rows) */ final double a[] = {-1.62557e-6, -0.31919e-6, -0.13843e-6}; final double ad[] = {1.245e-3, -1.580e-3, -0.659e-3}; final double em[][] = {{0.9999256782, /* em[0][0] */ -0.0111820611, /* em[0][1] */ -0.0048579477, /* em[0][2] */ 0.00000242395018, /* em[0][3] */ -0.00000002710663, /* em[0][4] */ -0.00000001177656}, /* em[0][5] */ {0.0111820610, /* em[1][0] */ 0.9999374784, /* em[1][1] */ -0.0000271765, /* em[1][2] */ 0.00000002710663, /* em[1][3] */ 0.00000242397878, /* em[1][4] */ -0.00000000006587}, /* em[1][5] */ {0.0048579479, /* em[2][0] */ -0.0000271474, /* em[2][1] */ 0.9999881997, /* em[2][2] */ 0.00000001177656, /* em[2][3] */ -0.00000000006582, /* em[2][4] */ 0.00000242410173}, /* em[2][5] */ {-0.000551, /* em[3][0] */ -0.238565, /* em[3][1] */ 0.435739, /* em[3][2] */ 0.99994704, /* em[3][3] */ -0.01118251, /* em[3][4] */ -0.00485767}, /* em[3][5] */ {0.238514, /* em[4][0] */ -0.002667, /* em[4][1] */ -0.008541, /* em[4][2] */ 0.01118251, /* em[4][3] */ 0.99995883, /* em[4][4] */ -0.00002718}, /* em[4][5] */ {-0.435623, /* em[5][0] */ 0.012254, /* em[5][1] */ 0.002117, /* em[5][2] */ 0.00485767, /* em[5][3] */ -0.00002714, /* em[5][4] */ 1.00000956} /* em[5][5] */}; TRACE("Fk425"); /* Pick up B1950 data (units radians and arcsec/tc) */ AngleDR rd = s1950.getAngle(); r = rd.getAlpha(); d = rd.getDelta(); double pm[] = s1950.getMotion(); ur = pm[0] * pmf; ud = pm[1] * pmf; px = s1950.getParallax(); rv = s1950.getRV(); /* Spherical to Cartesian */ sr = Math.sin(r); cr = Math.cos(r); sd = Math.sin(d); cd = Math.cos(d); r0[0] = cr * cd; r0[1] = sr * cd; r0[2] = sd; w = vf * rv * px; rd0[0] = (-sr * cd * ur) - (cr * sd * ud) + (w * r0[0]); rd0[1] = (cr * cd * ur) - (sr * sd * ud) + (w * r0[1]); rd0[2] = (cd * ud) + (w * r0[2]); /* Allow for e-terms and express as position+velocity 6-vector */ w = (r0[0] * a[0]) + (r0[1] * a[1]) + (r0[2] * a[2]); wd = (r0[0] * ad[0]) + (r0[1] * ad[1]) + (r0[2] * ad[2]); for (i = 0; i < 3; i++) { v1[i] = r0[i] - a[i] + w * r0[i]; v1[i + 3] = rd0[i] - ad[i] + wd * r0[i]; } /* Convert position+velocity vector to Fricke system */ for (i = 0; i < 6; i++) { w = 0.0; for (j = 0; j < 6; j++) { w += em[i][j] * v1[j]; } v2[i] = w; } /* Revert to spherical coordinates */ x = v2[0]; y = v2[1]; z = v2[2]; xd = v2[3]; yd = v2[4]; zd = v2[5]; rxysq = (x * x) + (y * y); rxyzsq = (rxysq) + (z * z); rxy = Math.sqrt(rxysq); rxyz = Math.sqrt(rxyzsq); spxy = (x * xd) + (y * yd); spxyz = spxy + (z * zd); r = (x != 0.0 || y != 0.0) ? Math.atan2(y, x) : 0.0; if (r < 0.0) { r += D2PI; } d = Math.atan2(z, rxy); if (rxy > VERYTINY) { ur = ((x * yd) - (y * xd)) / rxysq; ud = ((zd * rxysq) - (z * spxy)) / (rxyzsq * rxy); } if (px > VERYTINY) { rv = spxyz / (px * rxyz * vf); px = px / rxyz; } /* Return results */ AngleDR ang = new AngleDR(r, d); double pm1[] = {ur / pmf, ud / pmf}; ENDTRACE("Fk425"); return new Stardata(ang, pm1, px, rv); }
44a9de19-6778-4898-8b8f-ab4bd7af2b00
3
public static void main(String args[]) { if (args.length > 0) { if(args[0].length() <= 8 ) { if (isNum(args[0])) { Conver cv = new Conver(); cv.converStart(args[0]); } else { System.out.println("用户输入的字符不都为数,无法转换 !"); } } else { System.out.println("请输入八位以内的数字 !"); } } else{ System.out.println("请输入八位以内的数字 !"); } }
f37bb011-d73d-4542-8f27-289e86c0745b
7
void print(){ int i=s.length; int j=t.length; int newi = i-1; int newj = j-1; for(int k=ed;k>=0;k--){ if(i-1>=0) newi = i-1; else newi=i; if(j-1>=0) newj = j-1; else newj = j; if((j-1)>=0 && m[i][j-1]<m[newi][newj]){ newj = j-1; } if((i-1)>=0 && m[i-1][j]<m[newi][newj]){ newi = i-1; } i=newi;j=newj; System.out.println("("+i+":"+j+")"); System.out.println(" "+s[i]+" "+t[j]); } }
6fbbbd5e-6a06-440a-8bd4-9f2823c1a343
2
@Override public void process(SimEvent event) { NodeReachedEvent _event = (NodeReachedEvent) event; // Casts the event. //int _oldPosition = getPosition(); // Saves the old position (Where the agent came from). setPosition(_event.getPosition()); // Sets the actual position to the reached node. System.out.println(getName() + "@" + getEngine().getCurrentTime() + ": reached node (" + getPosition().getX() + "," + getPosition().getY() + ")"); getLog().addNode(getPosition(), getEngine().getCurrentTime()); // Save the reached Node to the log. if(getLabyrinth().isEndpoint(getPosition())){ // Checks if the current position is the endpoint of the labyrinth. System.out.println(getName() + ": finished"); getEngine().stop(); } else{ // Select a random angle with no wall ahead. int _angle = _random.nextInt(4) * 90; while(getLabyrinth().isWallAhead(getPosition(), _angle)){ _angle = _random.nextInt(4) * 90; } Position _newNode = getLabyrinth().getNodeAhead(getPosition(), _angle); // Get the position of the next node in direction. // Create a new NodeReachedEvent with the new target node and schedule it. NodeReachedEvent _newEvent = new NodeReachedEvent(_newNode, _event.getOccurringTime() + getTicksPerLength(), 1, this); getEngine().insertEvent(_newEvent); } }
0b5c7c96-b770-48cb-a94b-2da92652dc25
7
public synchronized void move(){ //choose the direction Location temp = new Location(loc.getX(), loc.getY()); this.chooseDirection(); //makes and checks temporary location switch(dir){ case 'L': temp.setX(temp.getX() - 1); break; case 'R': temp.setX(temp.getX() + 1); break; case 'U': temp.setY(temp.getY() - 1); break; case 'D': temp.setY(temp.getY() + 1); break; case ' ': this.setLocation(loc); break; } //checks if location is blocked if(graphics.isBlocked(temp, true)){ this.setLocation(loc); } else{ this.setLocation(temp); } if(graphics.isTarget(temp)){ this.addPoints(); graphics.checkForPoint(temp); } }
28d5a119-7c1c-4099-86e4-29b5496fa1ce
1
public static Sequence loadMidi(String fileName) { Sequence sequence = null; try { sequence = MidiSystem.getSequence(new File("./res/midi/" + fileName)); } catch (Exception e) { e.printStackTrace(); System.exit(1); } return sequence; }
e4254eb0-0951-40b9-87af-857fa8a5b4b4
4
private void setupAccessibility() { getAccessibleContext().setAccessibleDescription("Application for learning the CECIL machine language (English). Press ALT to tab between the menu bar and the main application."); menuBar.getAccessibleContext().setAccessibleName("Menu bar"); menuBar.getAccessibleContext().setAccessibleDescription("Press ALT to focus the menu bar"); menuBar.setFocusable(true); menuBar.setFocusTraversalKeysEnabled(true); fileMenu.getAccessibleContext().setAccessibleName("File"); fileMenu.getAccessibleContext().setAccessibleDescription("Opens the file options"); fileMenu.setFocusTraversalKeysEnabled(true); menuNew.getAccessibleContext().setAccessibleName("New"); menuNew.getAccessibleContext().setAccessibleDescription("Creates a new Cecil program"); menuOpen.getAccessibleContext().setAccessibleName("Open"); menuOpen.getAccessibleContext().setAccessibleDescription("Opens a file chooser window"); menuSave.getAccessibleContext().setAccessibleName("Save"); menuSave.getAccessibleContext().setAccessibleDescription("Opens a file saver window"); menuExit.getAccessibleContext().setAccessibleName("Exit"); menuExit.getAccessibleContext().setAccessibleDescription("Exits the application"); settingsMenu.getAccessibleContext().setAccessibleName("Settings"); settingsMenu.getAccessibleContext().setAccessibleDescription("Opens the settings options"); settingsMenu.setFocusTraversalKeysEnabled(true); menuPreferences.getAccessibleContext().setAccessibleName("Preferences"); menuPreferences.getAccessibleContext().setAccessibleDescription("Opens a preferences window"); helpMenu.getAccessibleContext().setAccessibleName("Help"); helpMenu.getAccessibleContext().setAccessibleDescription("Opens the help options"); helpMenu.setFocusTraversalKeysEnabled(true); menuUserManual.getAccessibleContext().setAccessibleName("User manual"); menuUserManual.getAccessibleContext().setAccessibleDescription("Opens the user manual in a new window"); menuAbout.getAccessibleContext().setAccessibleName("About CECIL"); menuAbout.getAccessibleContext().setAccessibleDescription("Opens the about page in a new window"); ioMenu.getAccessibleContext().setAccessibleName("IO port checkbox"); ioMenu.getAccessibleContext().setAccessibleDescription("Press to allow output to physical ports (only available on Raspberry Pi"); ioMenu.setFocusTraversalKeysEnabled(true); btnCompile.getAccessibleContext().setAccessibleName("Compile"); btnCompile.getAccessibleContext().setAccessibleDescription("Compiles the program"); btnRun.getAccessibleContext().setAccessibleName("Run"); btnRun.getAccessibleContext().setAccessibleDescription("Runs the compiled program"); btnStepThrough.getAccessibleContext().setAccessibleName("Step through"); btnStepThrough.getAccessibleContext().setAccessibleDescription("Steps through one line of the compiled program at the selected line"); xRegister.getAccessibleContext().setAccessibleName("X register"); xRegister.getAccessibleContext().setAccessibleDescription("Displays the history of values in the x register newest to oldest"); yRegister.getAccessibleContext().setAccessibleName("Y register"); yRegister.getAccessibleContext().setAccessibleDescription("Displays the history of values in the y register newest to oldest"); accRegister.getAccessibleContext().setAccessibleName("Accumulator"); accRegister.getAccessibleContext().setAccessibleDescription("Displays the history of values in the accumulator newest to oldest"); lblCarry.setFocusable(true); lblCarry.getAccessibleContext().setAccessibleDescription("Switches on when the value at any of the registers exceeds the max buffer size"); lblZero.setFocusable(true); lblZero.getAccessibleContext().setAccessibleDescription("Switches on when the value at any of the registers is equal to 0"); lblNegative.setFocusable(true); lblNegative.getAccessibleContext().setAccessibleDescription("Switches on when the value at any of the registers is less than 0"); txtConsole.setFocusable(true); txtConsole.getAccessibleContext().setAccessibleName("Output console"); txtConsole.getAccessibleContext().setAccessibleDescription("Displays output results or errors"); tblInput.getAccessibleContext().setAccessibleName("Program editor"); tblInput.getAccessibleContext().setAccessibleDescription("A table where the program code can be entered. The instructions column consists of a dropdown list of instructions. Ctrl+Tab to exit the table."); tblInput.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() { /** * Serial version UID to stop the warning. */ private static final long serialVersionUID = 1L; public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) { Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column); if (column != 0) { cell.getAccessibleContext().setAccessibleName("Row "+(row+1)+", "+table.getColumnName(column)+" column"); } else { cell.getAccessibleContext().setAccessibleName("Row "+(row+1)+", row number column"); } if (column == 0 && obj != null && !obj.toString().isEmpty()) { cell.getAccessibleContext().setAccessibleDescription("Value is "+obj.toString()); } else { cell.getAccessibleContext().setAccessibleDescription(""); } return cell; } }); tblMemory.getAccessibleContext().setAccessibleName("Memory values"); tblMemory.getAccessibleContext().setAccessibleDescription("A table where each cell is a memory address." + " Addresses between 0-905 store user input data and 906-1028 store other housekeeping data like registers, ports etc. Ctrl+Tab to exit the table."); //Compile button gets default focus addWindowFocusListener(new WindowAdapter() { public void windowGainedFocus(WindowEvent e) { btnCompile.requestFocusInWindow(); } }); }
c29bd0f5-ee8d-4652-a122-c1628df17cd1
5
public Iterator<MedicineXmlTO> read() throws InterruptedException{ ArrayList<MedicineXmlTO> medTo = new ArrayList<MedicineXmlTO>(); try { Connection connection = DbPool.getInstance().getConnection(); Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM medicine m JOIN consistence c ON c.id=m.consistence_id JOIN dosage d ON d.id=dosage_id JOIN frequency f ON f.id = d.frequency_id JOIN package p ON p.id=m.package_id"); while(rs.next()){ MedicineXmlTO to = new MedicineXmlTO(); to.medicineId = rs.getString("m.id"); to.medicineName = rs.getString("m.name"); to.medicineGroup = rs.getString("m.groupp"); to.medicineCompany = rs.getString("m.company"); to.dosageId = rs.getString("m.dosage_id"); to.consistence = rs.getString("c.name"); to.isAfterFood = rs.getBoolean("d.is_after_food"); to.numberPerPeriod = rs.getInt("d.number"); to.frequency = rs.getString("f.name"); to.packageId = rs.getString("p.id"); to.packageType = rs.getString("p.type"); to.numberPerPackage = rs.getInt("p.number"); to.packagePrice = rs.getFloat("p.price"); medTo.add(to); } for(int i = 0; i < medTo.size(); ++i){ MedicineXmlTO to = medTo.get(i); to.analogs = new ArrayList<MedicineXmlTO>(); rs = st.executeQuery("SELECT * FROM analog WHERE analog_medicine_id="+i+" OR medicine_id="+i); while(rs.next()){ int n = rs.getInt("analog_medicine_id"); if(n != i) to.analogs.add(medTo.get(n)); else to.analogs.add(medTo.get(rs.getInt("medicine_id"))); } } DbPool.getInstance().putConnection(connection); } catch (SQLException ex) { Logger.getLogger(MySQLReader.class.getName()).log(Level.SEVERE, null, ex); } return medTo.iterator(); }
730bbb3d-583b-442e-aee6-f85e2f5aeacd
5
protected void mapChildrenValues(Map<String, Object> output, ConfigurationSection section, boolean deep) { if (section instanceof MemorySection) { MemorySection sec = (MemorySection) section; for (Map.Entry<String, Object> entry : sec.map.entrySet()) { output.put(createPath(section, entry.getKey(), this), entry.getValue()); if (entry.getValue() instanceof ConfigurationSection) { if (deep) { mapChildrenValues(output, (ConfigurationSection) entry.getValue(), deep); } } } } else { Map<String, Object> values = section.getValues(deep); for (Map.Entry<String, Object> entry : values.entrySet()) { output.put(createPath(section, entry.getKey(), this), entry.getValue()); } } }
5f772fde-a4c6-44dc-9bc8-792107e4ccee
8
public void run() { Server server = Bukkit.getServer(); ChatColor purple = ChatColor.DARK_PURPLE; Plugin larvikGaming = server.getPluginManager().getPlugin("LarvikGaming"); int delay = larvikGaming.getConfig().getInt("RestartTimeInHours", 6) * 3600000; if (delay < 1) { return; } try { Thread.sleep(20000); } catch (InterruptedException e) { } while (go) { try { Thread.sleep(delay - 300000); if (go) { server.broadcastMessage(purple + "**Server-Restart in 5min**"); } Thread.sleep(240000); if (go) { server.broadcastMessage(purple + "**Server-Restart in 1min**"); } Thread.sleep(60000); if (go) { server.broadcastMessage(purple + "**Server-Restart NOW**"); } Thread.sleep(1000); } catch (InterruptedException e) { } if (go) { StopServer.stopServer(); } } }
7ada10e0-6ebb-4e21-9092-102ed4518090
5
static final void method1935(int i, int i_10_, Class30 class30, AnimatableToolkit class64, boolean bool, int i_11_) { try { anInt3270++; if (class64 != null) { if (bool != false) method1929((byte) 106); class30.method320(class64.EA(), class64.fa(), (byte) -4, i_11_, class64.na(), i, class64.V(), class64.G(), class64.HA(), i_10_, class64.RA()); } } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("ub.H(" + i + ',' + i_10_ + ',' + (class30 != null ? "{...}" : "null") + ',' + (class64 != null ? "{...}" : "null") + ',' + bool + ',' + i_11_ + ')')); } }
d6bb2cea-ed86-40ae-8750-b1bc3fa9d0fd
1
@AfterTest public void tearDown() throws Exception { driver.quit(); String verificationErrorString = verificationErrors.toString(); if (!"".equals(verificationErrorString)) { fail(verificationErrorString); } }
ef36d6df-6751-40e8-9002-598fa1ede57a
0
public int countBins(){ return this.bins.size(); }
236e2a61-9f5f-43af-a702-08a54766dd27
5
public static String[] getParagraphs(String article ){ String[] ret=null; try { int pFromIndex=0; int pToIndex=0; ArrayList<Integer> startPIndexs=new ArrayList<Integer>(); ArrayList<Integer> endPIndexs=new ArrayList<Integer>(); while(-1!= article.indexOf("<P>", pFromIndex)){ int t = article.indexOf("<P>", pFromIndex); startPIndexs.add(t); pFromIndex=t+1; t=article.indexOf("</P>", pToIndex); endPIndexs.add(t); pToIndex=t+1; } //如果没有用<P></P>分隔则返回整个段落 if(startPIndexs.size()==0 || endPIndexs.size()==0){ return new String[]{article}; } ArrayList<String> paragraphs=new ArrayList<String>(); for(int i=0;i<startPIndexs.size();i++){ String tStr=article.substring(startPIndexs.get(i), endPIndexs.get(i)); paragraphs.add(tStr); } ret=new String[paragraphs.size()]; ret = paragraphs.toArray(ret); }catch (Exception e) { // TODO: handle exception } return ret; }
73850695-0ce6-4fe0-8714-9bd5492a4579
7
public static void main(String[] args) { try { svm_model svmModel = svm.svm_load_model("SvmModel.eye"); FaceFeaturesFinder faceFeaturesFinder = new FaceFeaturesFinder(svmModel); if (args.length != 1) { throw new IOException("invalid images path"); } String imagesPath=args[0] ; File file = new File(imagesPath); File directory; if (file.isDirectory()) { directory = new File(file.getCanonicalPath()); } else { throw new IOException(file.toString( ) + " is not a directory"); } String filesList[] = directory.list(new PgmFileFilter()); FileWriter fw = new FileWriter("test.cvs"); for (int i=0; i<filesList.length; i++) { System.out.print("."); String absImageFilePath=imagesPath+filesList[i]; String absEyesFilePath=imagesPath+filesList[i].replaceAll(".pgm", ".eye"); ReadCoordinatesBioID rc = new ReadCoordinatesBioID(absEyesFilePath); BytePixmap p = new BytePixmap(absImageFilePath); int[] pixels = new int[p.size]; for (int j = 0; j < pixels.length; j++) pixels[j] = 0xFF000000 + Pixmap.intValue(p.data[j]) * 0x010101; MemoryImageSource source = new MemoryImageSource(p.width,p.height,pixels, 0, p.width); Image img = Toolkit.getDefaultToolkit().createImage(source); int coordinates[] = faceFeaturesFinder.findFaceFeatures(img); if (coordinates != null) { int c[]=rc.getCoord(); if ((c != null)) { fw.write(coordinates[0]+" , "+coordinates[1]+" , " +coordinates[2]+" , "+coordinates[3]+" , " +c[0]+" , "+c[1]+" , " +c[2]+" , "+c[3]+"\n"); fw.flush(); } } } fw.close(); } catch (Exception e) { System.err.println(e.getMessage()); } System.out.println("End."); }
3257820a-e86f-4d53-ba62-605a0bc6bc87
3
public int numberOfPersonsWhoOrderedTheSameMeal(){ int i = 0; int timesTheSameMealIsOrdered = 0; for(Command command: this.commands){ if(command.compareCommandTo(commands.get(i))==-1){ if(command.orderTheSameMeal(command)==1){ timesTheSameMealIsOrdered++; } } i++; } return timesTheSameMealIsOrdered; }
d09ce15a-bc05-4b52-b8af-63adf8e087e9
9
@Override public String dismountString(Rider R) { switch(rideBasis) { case Rideable.RIDEABLE_AIR: case Rideable.RIDEABLE_LAND: case Rideable.RIDEABLE_WATER: return "disembark(s) from"; case Rideable.RIDEABLE_TABLE: case Rideable.RIDEABLE_SIT: case Rideable.RIDEABLE_SLEEP: case Rideable.RIDEABLE_WAGON: case Rideable.RIDEABLE_LADDER: case Rideable.RIDEABLE_ENTERIN: return "get(s) out of"; } return "disembark(s) from"; }
3519983e-c8c0-43f9-8627-ba4dbe357348
8
public Worker[] list () { Connection con = null; PreparedStatement statement = null; ResultSet rs = null; List<Worker> workers = new ArrayList<Worker>(); try { con = ConnectionManager.getConnection(); String searchQuery = "SELECT * FROM workers WHERE status != 'terminated'"; statement = con.prepareStatement(searchQuery); rs = statement.executeQuery(); while (rs.next()) { Worker worker = new Worker(); worker.setId( rs.getInt("id") ); worker.setStatus( rs.getString("status") ); worker.setLocalIp( rs.getString("local_ip") ); worker.setPublicIp( rs.getString("public_ip") ); worker.setInstanceId( rs.getString("instance_id") ); worker.setManager( rs.getBoolean("is_manager") ); worker.setLastTimeWorked( rs.getTimestamp("last_time_worked")); worker.setLastTimeAlive( rs.getTimestamp("last_time_alive")); workers.add(worker); } } catch (SQLException e) { e.printStackTrace(); error = e.toString(); } finally { if (rs != null) { try { rs.close(); } catch (Exception e) { System.err.println(e); } rs = null; } if (statement != null) { try { statement.close(); } catch (Exception e) { System.err.println(e); } statement = null; } if (con != null) { try { con.close(); } catch (Exception e) { System.err.println(e); } con = null; } } return workers.toArray( new Worker [workers.size()] ); }
389e05e2-bd68-48e9-a56d-9546c8bc8cbc
8
public static GameState readCSV(String filename){ int superzahl = 0; CSVReader reader = null; try { reader = new CSVReader(new FileReader(filename), ';'); } catch (IOException e){ System.out.println(e.toString()); } String [] nextLine; ArrayList<int[]> parsedList = new ArrayList<int[]>(); try { while ((nextLine = reader.readNext()) != null) { if(!nextLine[1].equals("Freies Teil")) { int[] intLine = new int[nextLine.length]; for(int i = 0; i<nextLine.length; i++) { intLine[i] = Integer.parseInt(nextLine[i]); } parsedList.add(intLine); } else{ superzahl = Integer.parseInt(nextLine[0]); } } } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int spielfeld[][] = new int[parsedList.size()][parsedList.get(0).length]; for(int i = 0; i<parsedList.size(); i++){ spielfeld[i] = parsedList.get(i); } GameState input = new GameState(spielfeld, superzahl, 0, null); try { reader.close(); } catch (IOException e) { e.printStackTrace(); } return input; }
3438da60-fa86-4494-be4e-44e9c7ec4bb3
8
public Investment getChild(int id) { for (Investment i : this.children) { if (i instanceof Bond) { if (i.getUniqueId() == id) return i; } else if (i instanceof Stock) { if (i.getUniqueId() == id) return i; } else if (i instanceof MoneyMarket) { if (i.getUniqueId() == id) return i; } else if (i instanceof Portfolio) return i.getChild(id); else { throw new NoSuchElementException("Object of class " + i.getClass() + " is unknown"); } } throw new NoSuchElementException("This portfolio does not contain a portfolio or account with id : " + id); }
c87ce5f9-1b26-4239-920f-8003c171d78f
1
public AnnotationVisitor visitAnnotation(String desc, boolean visible) { AnnotationVisitor av = mv.visitAnnotation(remapper.mapDesc(desc), visible); return av == null ? av : new RemappingAnnotationAdapter(av, remapper); }
09c08cc1-8986-423a-b259-3b5524dd969c
3
public void setIdentificador(TIdentificador node) { if(this._identificador_ != null) { this._identificador_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._identificador_ = node; }
094b3cf6-90a3-4642-b112-47413def21b9
7
private String getNewTheoryInList() { StringBuffer theories = new StringBuffer( ); for(int i=0;i<theoriesSplittedsRead.length;i++){ if(theoriesSplittedsRead[i].contains("THEORY User_Pass IS")) continue; if(i+1 != theoriesSplittedsRead.length) //if space after the last end theories.append(theoriesSplittedsRead[i]+"END\n"); else if (theoriesSplittedsRead[i].contains("THEORY ")) theories.append(theoriesSplittedsRead[i]+"END\n"); } if(theoryRuleList.size()>0) theories.append(" &\n"); for(int i = 0; i< theoryRuleList.size(); i++){ if(theoryRuleList.size()==i+1){ // The last element theories.append(theoryRuleList.get(i)); }else{ theories.append(theoryRuleList.get(i)+"\n&\n"); } } return theories.toString(); }
ab8304e0-1e2c-4f39-ad7c-7244bd9ab12c
3
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void visitMethod(ClassNode c, MethodNode m) { FlowGraph fg = m.graph(); for(Iterator it = new HashSet(fg.handlersMap().entrySet()).iterator(); it.hasNext();) { Map.Entry<Block, Handler> handlerEntry = (Entry<Block, Handler>) it.next(); Handler handler = handlerEntry.getValue(); if(handler.catchType().equals(Type.getType(RuntimeException.class))) { final AtomicBoolean flag = new AtomicBoolean(true); Block block = ((GotoStmt) handler.catchBlock().tree().lastStmt()).target(); /*block.tree().visitChildren(new TreeVisitor() { @Override public void visitStmt(Stmt s) { s.visitChildren(this); } @Override public void visitNewExpr(NewExpr n) { if(n.objectType().equals(Type.getType(StringBuilder.class))) { flag.set(true); } } });*/ if(flag.get()) { it.remove(); fg.removeNode(handler.catchBlock().label()); fg.removeNode(block.label()); count++; } } } }
4bbd5fe1-048e-4331-8ed8-348577514ded
4
private void DeleteInstanceButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeleteInstanceButtonActionPerformed if (!InstanceComboBox.getSelectedItem().toString().equals("<None>")) { String instanceToBeRemoved = InstanceComboBox.getSelectedItem().toString(); //Delete instance try { FileUtils.deleteDirectory(new File("./users/" + getFriendlyName(Auth.AccountName) + "/" + InstanceComboBox.getSelectedItem().toString())); } catch (IOException ex) { return; } //Clear the instance ComboBoc InstanceComboBox.removeAllItems(); InstanceComboBox.addItem("<None>"); //Populate instance ComboBox for (File f : new File("./users/" + getFriendlyName(Auth.AccountName)).listFiles()) { if (f.isDirectory()) { InstanceComboBox.addItem(f.getName()); } } InstanceComboBox.setSelectedIndex(0); Logger.info("MainForm.DeleteInstanceButtonActionPerformed", "Removed instance '" + instanceToBeRemoved + "'."); } }//GEN-LAST:event_DeleteInstanceButtonActionPerformed
fd9c16d4-b04e-48cc-a6d7-b67c02799fca
6
public void GAstep_selection() { /* провести селекцию*/ /** * все сложить в одну кучу отсортировать по фитнесу удалить все лишние */ Map<Integer, Species> typeByOrganism = new HashMap<Integer, Species>(); List<Organism> allOrganisms = new ArrayList<Organism>(); for (int i = 0; i < species.size(); i++) { for (int j = 0; j < species.get(i).getNumberOrganisms(); j++) { typeByOrganism.put(species.get(i).getOrganism(j).getOrganism_id(), species.get(i)); allOrganisms.add(species.get(i).getOrganism(j)); } } Collections.sort(allOrganisms, new Comparator<Organism>() { @Override public int compare(Organism o1, Organism o2) { return o2.getFitness() > o1.getFitness() ? 1 : o2.getFitness() < o1.getFitness() ? -1 : 0; } }); // … … … … … … … … … … … … … … for (int i = getSize(); i < allOrganisms.size(); i++) { Species type = typeByOrganism.get(allOrganisms.get(i).getOrganism_id()); type.removeOrganism(allOrganisms.get(i)); //if Species is empty, delete it if (type.getOrganisms().isEmpty()) { removeSpecies(type); } } }
0f3e0a45-dee8-447e-8fa2-c82bc5a1ce29
2
public byte[] getByteArray(String key) { try { if(hasKey(key)) return ((NBTReturnable<byte[]>) get(key)).getValue(); return new byte[]{}; } catch (ClassCastException e) { return new byte[]{}; } }
22aee149-65aa-4eae-af80-96e845622a8a
0
public DDALine(Excel ex1, Excel ex2) { begin = ex1; end = ex2; this.setColoredExes(); }
64493ad1-c655-4970-a663-95c9f0e6e94c
3
private boolean jj_3R_70() { if (jj_scan_token(LEFTBRACKET)) return true; if (jj_3R_61()) return true; if (jj_scan_token(RIGHTBRACKET)) return true; return false; }
b029ff9e-e766-4127-8deb-4bf16a226746
4
private void showAddItemWizard() { System.out.println("\n---------------------------------------"); System.out.println("- New item wizard - Step 1 -"); System.out.println("---------------------------------------"); System.out.println("Please select an option :"); System.out.println("1. Add new book."); System.out.println("2. Add new comic."); System.out.println("3. Add new magazine."); System.out.println("4. Show main menu."); int result = readInt(1, 4); switch (result) { case 1: showAddBookWizard(); break; case 2: showAddComicWizard(); break; case 3: showAddMagazineWizard(); break; case 4: showMainMenu(); break; } }
94ac73dc-64ce-4233-b1a2-dde0d34d1d23
4
@Test public void testKlusToevoegen() throws Exception { File f = new File("C:/Users/Jacky/Dropbox/Themaopdracht 4/CSVTestdata/KlusToevoegenTest.csv"); if (f.exists() && f.isFile()) { String klusnaam; String klusomschrijving; String datumdag; String datummaand; String datumjaar; FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { Scanner sc = new Scanner(line); sc.useDelimiter(";"); while (sc.hasNext()) { klusnaam = sc.next(); klusomschrijving = sc.next(); datumdag = sc.next(); datummaand = sc.next(); datumjaar = sc.next(); driver.get(baseUrl + "/ATD-Windows/index.jsp"); driver.findElement(By.name("naam")).clear(); driver.findElement(By.name("naam")).sendKeys("admin@ikbendeadmin.nl"); driver.findElement(By.name("wachtwoord")).clear(); driver.findElement(By.name("wachtwoord")).sendKeys("admin"); Thread.sleep(2000L); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); Thread.sleep(2000L); WebElement mnuElement; mnuElement = driver.findElement(By.id("onderhoudsbeurt")); mnuElement.click(); Actions builder = new Actions(driver); builder.moveToElement(mnuElement).perform(); Thread.sleep(2000L); driver.findElement(By.id("klus toevoegen")).click(); driver.get("http://localhost:8080/ATD-Windows/klus_toevoegen.jsp"); Thread.sleep(2000L); driver.findElement(By.name("klusNaam")).clear(); driver.findElement(By.name("klusNaam")).sendKeys(klusnaam); Thread.sleep(2000L); driver.findElement(By.name("klusOmschrijving")).clear(); driver.findElement(By.name("klusOmschrijving")).sendKeys(klusomschrijving); Thread.sleep(2000L); driver.findElement(By.name("dag")).clear(); driver.findElement(By.name("dag")).sendKeys(datumdag); Thread.sleep(2000L); driver.findElement(By.name("maand")).clear(); driver.findElement(By.name("maand")).sendKeys(datummaand); Thread.sleep(2000L); driver.findElement(By.name("jaar")).clear(); driver.findElement(By.name("jaar")).sendKeys(datumjaar); Thread.sleep(2000L); driver.findElement(By.cssSelector("div.content > form > input[type=\"submit\"]")).click(); Thread.sleep(2000L); WebElement mnuElement1; mnuElement1 = driver.findElement(By.id("onderhoudsbeurt")); mnuElement1.click(); Thread.sleep(2000L); Actions builder1 = new Actions(driver); builder1.moveToElement(mnuElement1).perform(); Thread.sleep(2000L); driver.findElement(By.id("weekplanning")).click(); driver.get("http://localhost:8080/ATD-Windows/weekplanning.jsp"); Thread.sleep(4000L); driver.findElement(By.cssSelector("div.content > form > input[type=\"submit\"]")).click(); Thread.sleep(4000L); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); Thread.sleep(4000L); } line = br.readLine(); sc.close(); } br.close(); } }
c81e5768-5740-45b3-9e8d-88cdfe1d013b
3
@Override public Vector4D multiply(MatrixS4 matrix) { double[] result = new double[4]; double suma; try { for (int i = 0; i < 4; i++) { suma = 0; for (int j = 0; j < 4; j++) { suma += this.getElementAt(j + 1) * matrix.getElementAt(j + 1, i + 1); } result[i] = suma; } } catch (OutOfBoundsException e) { // TODO Auto-generated catch block e.printStackTrace(); } setX(result[0]); setY(result[1]); setZ(result[2]); setW(result[3]); return this; }
2a86b39a-76c7-4332-95f4-88734047a910
8
@Override public Solution runAlgorithm() { for (int iter = 0; iter < maxiter; iter++) { best = determineBest(population); System.out.println((iter + 1) + ": " + best.getFitness()); if (best.getFitness() >= minFit) { return best; } List<Solution> newSols = new ArrayList<>(popSize); newSols.add(best); for (int i = 1; i < popSize; i++) { double perc = rand.nextDouble(); if (perc <= 0.01) { // reprodukcija Solution sol = selection.select(population.getSols()); sol.punish(plagiaryPunishment); newSols.add(sol); } else if (perc <= 0.15) { // mutacija Solution sol = selection.select(population.getSols()).duplicate(); int oldFit = sol.getFitness(); sol = mutation.mutate(sol); int newFit = evaluator.evaluate(sol); if (oldFit == newFit) { sol.punish(plagiaryPunishment); } newSols.add(sol); } else { // križanje Solution parent1 = selection.select(population.getSols()); Solution parent2 = selection.select(population.getSols()); Solution[] solArray = crossover.cross(parent1, parent2); Solution child1 = solArray[0]; evaluator.evaluate(child1); if (parent1.getFitness() == child1.getFitness()) { child1.punish(plagiaryPunishment); } Solution child2 = solArray[1]; evaluator.evaluate(child2); if (parent2.getFitness() == child2.getFitness()) { child2.punish(plagiaryPunishment); } newSols.add(child1); newSols.add(child2); } } population = new Population(newSols); } return best; }
3a3588bd-9360-4318-b41c-e70b2232d374
8
public static void main(String[] args) { final int TOP_LIMIT = 10000; int[] divisorTotals = new int[TOP_LIMIT + 1]; int totalSum = 0; //store divisor totals in array for (int i = 1; i <= TOP_LIMIT; i++) { //1 is divisible by every number, don't need to check int sum = 1; for (int j = 2; j <= Math.sqrt(i); j++) { if (i % j == 0) { int other = i / j; if (j == other) { other = 0; } sum += other; sum += j; } } divisorTotals[i] = sum; } //find all amicable numbers, keep a sum for (int k = 1; k <= TOP_LIMIT; k++) { if (divisorTotals[k] <= TOP_LIMIT) { int temp = divisorTotals[k]; if (divisorTotals[temp] == k && k != temp) { totalSum += k; } } } System.out.println("Sum is " + totalSum); }
7b7affb5-36cb-4c1b-aaa0-b7b34deed6fe
2
public void testWithers() { DateMidnight test = new DateMidnight(1970, 6, 9, GJ_DEFAULT); check(test.withYear(2000), 2000, 6, 9); check(test.withMonthOfYear(2), 1970, 2, 9); check(test.withDayOfMonth(2), 1970, 6, 2); check(test.withDayOfYear(6), 1970, 1, 6); check(test.withDayOfWeek(6), 1970, 6, 13); check(test.withWeekOfWeekyear(6), 1970, 2, 3); check(test.withWeekyear(1971), 1971, 6, 15); check(test.withYearOfCentury(60), 1960, 6, 9); check(test.withCenturyOfEra(21), 2070, 6, 9); check(test.withYearOfEra(1066), 1066, 6, 9); check(test.withEra(DateTimeConstants.BC), -1970, 6, 9); try { test.withMonthOfYear(0); fail(); } catch (IllegalArgumentException ex) {} try { test.withMonthOfYear(13); fail(); } catch (IllegalArgumentException ex) {} }
15688e44-0a30-4a5a-8eca-b4561ee8991c
2
public void testWithers() { YearMonth test = new YearMonth(1970, 6); check(test.withYear(2000), 2000, 6); check(test.withMonthOfYear(2), 1970, 2); try { test.withMonthOfYear(0); fail(); } catch (IllegalArgumentException ex) {} try { test.withMonthOfYear(13); fail(); } catch (IllegalArgumentException ex) {} }
519c38f5-3fe0-421a-8970-274759f94dde
3
@Test public void testPutGetMessagesInOrder() { try { int noOfMessages = 5; final CountDownLatch gate = new CountDownLatch(noOfMessages); final ArrayList<Message> list = new ArrayList<Message>(noOfMessages); for (int i = 0; i < noOfMessages; i++) { Message msg = new MockMessage("TestMessage"); list.add(i, msg); } AsyncMessageConsumer testSubscriber = new MockQueueReceiver() { int cnt = 0; @Override public void onMessage(Message received) { assertNotNull("Received Null Message", received); assertEquals("Message values are not equal", list.get(cnt), received); cnt++; gate.countDown(); } }; destination.addSubscriber(testSubscriber); for (Message message : list) { destination.put(message); } boolean messageReceived = gate.await(100, TimeUnit.MILLISECONDS); assertTrue("Did not receive message in 100ms", messageReceived); } catch (Throwable e) { fail("Error while putting message in topic" + e.getMessage()); } }
b987d602-aca1-4728-949a-9feb0f33e112
8
char processAmpersand() throws XMLMiddlewareException, IOException, EOFException { char c; switch (entityState) { case STATE_DTD: throwXMLMiddlewareException("Invalid general entity reference or character reference."); case STATE_ATTVALUE: if (getChar() == '#') { getCharRef(); } else { restore(); getGeneralEntityRef(); } return nextChar(); case STATE_ENTITYVALUE: if (getChar() == '#') { getCharRef(); return nextChar(); } else { restore(); return '&'; } case STATE_OUTSIDEDTD: case STATE_COMMENT: case STATE_IGNORE: return '&'; default: throw new IllegalStateException("Internal error: invalid entity state: " + entityState); } }
342a8f87-a038-4e6a-bd17-76aacef2e222
6
public void testTextToTerm2() { String text1 = "fred(?,2,?)"; String text2 = "[first(x,y),A]"; Term plist = Util.textToTerm(text2); Term[] ps = plist.toTermArray(); Term t = Util.textToTerm(text1).putParams(ps); assertTrue("fred(?,2,?) .putParams( [first(x,y),A] )", t.hasFunctor("fred", 3) && t.arg(1).hasFunctor("first", 2) && t.arg(1).arg(1).hasFunctor("x", 0) && t.arg(1).arg(2).hasFunctor("y", 0) && t.arg(2).hasFunctor(2, 0) && t.arg(3).isVariable() && t.arg(3).name().equals("A")); }
906aa3c7-1b66-486a-90b4-4cb8605a6461
5
public final void writeNewSongbookData(final File masterPluginData) { final OutputStream outMaster; outMaster = this.io.openOut(masterPluginData); try { // head this.io.write(outMaster, "return\r\n{\r\n"); // section dirs this.io.write(outMaster, "\t[\"Directories\"] =\r\n\t{\r\n"); final Iterator<Path> dirIterator = this.tree.dirsIterator(); if (dirIterator.hasNext()) { this.io.write(outMaster, "\t\t[1] = \"/\""); for (int dirIdx = 2; dirIterator.hasNext(); dirIdx++) { this.io.writeln(outMaster, ","); this.io.write(outMaster, "\t\t[" + dirIdx + "] = \"/" + dirIterator.next() .relativize(this.tree.getRoot()) + "/\""); } this.io.writeln(outMaster, ""); } this.io.writeln(outMaster, "\t},"); // section songs this.io.writeln(outMaster, "\t[\"Songs\"] ="); int songIdx = 0; final Iterator<Path> songsIterator = this.tree.filesIterator(); while (songsIterator.hasNext()) { final Path path = songsIterator.next(); final SongDataEntry song = this.tree.get(path); if (songIdx++ == 0) { this.io.writeln(outMaster, "\t{"); } else { this.io.writeln(outMaster, "\t\t},"); } this.io.writeln(outMaster, "\t\t[" + songIdx + "] ="); this.io.writeln(outMaster, "\t\t{"); final String name; name = path.getFilename().substring(0, path.getFilename().lastIndexOf(".")); this.io.write(outMaster, "\t\t\t[\"Filepath\"] = \"/"); if (path.getParent() != this.tree.getRoot()) { this.io.write(outMaster, path.getParent().relativize(this.tree.getRoot())); this.io.write(outMaster, "/"); } this.io.writeln(outMaster, "\","); this.io.writeln(outMaster, "\t\t\t[\"Filename\"] = \"" + name + "\","); this.io.writeln(outMaster, "\t\t\t[\"Tracks\"] = "); this.io.write(outMaster, song.toPluginData()); this.io.updateProgress(); } // tail this.io.writeln(outMaster, "\t\t}"); this.io.writeln(outMaster, "\t}"); this.io.write(outMaster, "}"); } finally { this.io.close(outMaster); } }
ad6beb5d-631a-44d3-b85a-a7ebd58f0198
0
private static synchronized int getCounter() { return counter++; }
e5ef4679-b4fd-45a7-8850-67246f129f4e
3
public String getImportFileFormatNameForExtension(String extension) { String lowerCaseExtension = extension.toLowerCase(); for (int i = 0, limit = importers.size(); i < limit; i++) { OpenFileFormat format = (OpenFileFormat) importers.get(i); if (format.extensionExists(lowerCaseExtension)) { return (String) importerNames.get(i); } } int index = importers.indexOf(getDefaultImportFileFormat()); if (index == -1) { index = importers.indexOf(getDefaultOpenFileFormat()); } return (String) importerNames.get(index); }
dfe54b1a-5355-468f-a1ff-13a34aff954b
3
@SuppressWarnings("unchecked") public String getTeamData() { PreparedStatement st = null; ResultSet rs = null; JSONArray json = new JSONArray(); try { conn = dbconn.getConnection(); st = conn.prepareStatement("SELECT id, match_number, auton_top*6 + auton_middle*4 + auton_bottom*2 as auton, teleop_top*3 + teleop_middle*2 + teleop_bottom + teleop_pyramid*5 as teleop, pyramid_level*10 as climb, auton_top*6 + auton_middle*4 + auton_bottom*2 + teleop_top*3 + teleop_middle*2 + teleop_bottom + teleop_pyramid*5 + pyramid_level*10 as total FROM match_record_2013 where event_id = ? AND team_id = ? GROUP BY match_number"); st.setInt(1, getSelectedEvent()); st.setInt(2, getSelectedTeam()); rs = st.executeQuery(); while (rs.next()) { JSONObject o = new JSONObject(); o.put("id", rs.getInt("id")); o.put("match_id", rs.getInt("match_number")); o.put("autonomous", rs.getInt("auton")); o.put("teleop", rs.getInt("teleop")); o.put("climb", rs.getInt("climb")); o.put("total_points", rs.getInt("total")); json.add(o); } } catch (SQLException e) { e.printStackTrace(); } finally { try{ conn.close(); st.close(); rs.close(); }catch (SQLException e) { System.out.println("Error closing query"); } } return json.toString(); }
618ed6ca-7243-48d5-bb42-fe3e68881654
0
@Test public void testTimes() { calculator.pushOperand(3.0); calculator.pushOperand(2); calculator.pushTimesOperator(); calculator.evaluateStack(); assertEquals(6.0, calculator.popOperand(), 0); }
ce173433-4626-406f-882c-b0b5676d34a4
6
@EventHandler(priority=EventPriority.LOW) public void preCraftEvent(PrepareItemCraftEvent event) { if(event.getViewers() == null || event.getRecipe() == null) return; Material mat = event.getRecipe().getResult().getType(); if(event.isRepair()) { for(HumanEntity he: event.getViewers()) { if(he.getName() != null) { Player play = (Player)he; if(event.isRepair()) hRepair.put(play, mat); else hCraft.put(play, mat); } } } }
449b9148-ebff-47e4-8127-60d1cee74e9b
3
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Json other = (Json) obj; if (!Objects.equals(this.json, other.json)) { return false; } return true; }
6388418b-ad21-4713-95c5-2ef856b65a53
9
public static void extractArguments(String[] args, String argumentPrefix, Map<String, String> _arguments, List<String> _nonArguments) throws InvalidArgumentException { if (null == args || args.length == 0) return; Map<String, String> arguments = new TreeMap<String, String>(); List<String> nonArguments = new ArrayList<String>(); int prefLen = argumentPrefix.length(); for (String arg : args) { String s = arg.trim(); if (s.startsWith(argumentPrefix)) { s = s.substring(prefLen).trim(); if (s.length() > 0) { int l = s.indexOf("="); String name = ""; String value = ""; if (l > 0) { name = s.substring(0, l); value = s.substring(l + 1); } else if (l == 0) { throw new InvalidArgumentException("invalid argument [" + arg.trim() + "] - argument name not found!"); } else { name = s; } arguments.put(name, value); } } else { nonArguments.add(s); } } if (null != _arguments) { _arguments.clear(); _arguments.putAll(arguments); } if (null != _nonArguments) { _nonArguments.clear(); _nonArguments.addAll(nonArguments); } }
1b4cd7c9-d918-4365-b3dd-fd7c9120570a
7
private String trimStr(String str,char ch) { if(str == null) return null; str = str.trim(); int count = str.length(); int len = str.length(); int st = 0; char[] val = str.toCharArray(); while ((st < len) && (val[st] == ch)) { st++; } while ((st < len) && (val[len - 1] == ch)) { len--; } return ((st > 0) || (len < count)) ? str.substring(st, len) : str; }
682c5e41-e98d-41f5-ba3a-24b4ac17ecb8
8
private Vector<Integer> getIdList(String csv[], boolean parent) { Vector<Integer> results = new Vector<Integer>(this.ruleList.size()); results.setSize(this.ruleList.size()); for (int j = 0; j < this.ruleList.size(); j++) { results.set(j, j); } for (int j = 0; j < csv.length; j++) { int k = 0; for (int n = 0; n < results.size(); n++) { int i = results.get(n); String rl_ij = this.ruleList.get(i)[j]; if ( ((!parent) && (csv[j].charAt(0) == '*')) || ((parent) && (rl_ij.charAt(0) == '*')) || rl_ij.equals(csv[j]) ) { results.set(k++, results.get(n)); } } results.setSize(k); } return results; }
604db415-7e7c-47c2-aaed-1caf26ef579f
1
private Class getClassObject(String name) throws ClassNotFoundException { if (useContextClassLoader) return Thread.currentThread().getContextClassLoader() .loadClass(name); else return Class.forName(name); }
d977a905-cf56-43a8-8576-c3497dd1932a
9
@Override public boolean equals(Object obj) { if(this == obj) { return true; } if(obj instanceof Build) { Build that = (Build)obj; return this.id == that.id && this.name != null ? this.name.equals(that.name) : this.name == that.name && this.milestone != null ? this.milestone.equals(that.milestone) : this.milestone == that.milestone && this.description != null ? this.description.equals(that.description) : this.description == that.description && this.isActive == that.isActive; } return false; }
8fc15565-224c-49d4-aa0f-354a977cd1ec
2
private void resaveParamsSaveCity(SessionRequestContent request) { String currCountry = request.getParameter(JSP_CURR_ID_COUNTRY); if (currCountry != null && !currCountry.isEmpty()) { request.setAttribute(JSP_CURR_ID_COUNTRY, currCountry); } createCurrCity(request); }