method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
e59f8bf3-3c42-4ce2-b163-3f3c6861d2c4
8
@Override public double calculateFractalWithoutPeriodicity(Complex pixel) { iterations = 0; Complex tempz = new Complex(pertur_val.getPixel(init_val.getPixel(pixel))); Complex tempz2 = new Complex(init_val2.getPixel(pixel)); Complex[] complex = new Complex[3]; complex[0] = tempz;//z complex[1] = new Complex(pixel);//c complex[2] = tempz2;//z2 Complex zold = new Complex(); if(parser.foundS()) { parser.setSvalue(new Complex(complex[0])); } if(parser2.foundS()) { parser2.setSvalue(new Complex(complex[0])); } if(parser.foundP()) { parser.setPvalue(new Complex()); } if(parser2.foundP()) { parser2.setPvalue(new Complex()); } for(; iterations < max_iterations; iterations++) { if(bailout_algorithm.escaped(complex[0], zold)) { Object[] object = {iterations, complex[0], zold}; return out_color_algorithm.getResult(object); } zold.assign(complex[0]); function(complex); if(parser.foundP()) { parser.setPvalue(new Complex(zold)); } if(parser2.foundP()) { parser2.setPvalue(new Complex(zold)); } } Object[] object = {complex[0], zold}; return in_color_algorithm.getResult(object); }
fd07ef6b-77b1-4360-ab7b-89770b1347fc
9
public void rotateTo(int x, int y, int handle) { if (savedCenter == null) savedCenter = getCenterOfMass2D(); double dx = x - savedCenter.getX(); double dy = y - savedCenter.getY(); double distance = Math.hypot(dx, dy); if (distance < 1.0) return; double sintheta0 = 0, costheta0 = 0; boolean b = savedHandleX != 0 && savedHandleY != 0; if (b) { costheta0 = savedHandleX - savedCenter.getX(); sintheta0 = savedHandleY - savedCenter.getY(); double r = Math.hypot(costheta0, sintheta0); costheta0 /= r; sintheta0 /= r; } double costheta = dx / distance; double sintheta = dy / distance; double x2 = savedCenter.getX() + 60.0 * costheta; double y2 = savedCenter.getY() + 60.0 * sintheta; rotateRect.setRect(x2 - 4, y2 - 4, 8, 8); rotateCrossLine[0].setLine(savedCenter.getX(), savedCenter.getY(), x2, y2); rotateCrossLine[1].setLine(x2 - 10.0 * sintheta, y2 + 10.0 * costheta, x2 + 10.0 * sintheta, y2 - 10.0 * costheta); if (b) { // delta = theta - theta0 dx = costheta * costheta0 + sintheta * sintheta0; dy = sintheta * costheta0 - costheta * sintheta0; costheta = dx; sintheta = dy; } Point2D oldPoint; double oldX, oldY; synchronized (atoms) { for (Atom at : atoms) { if (savedCRD == null || savedCRD.isEmpty()) { oldX = at.rx; oldY = at.ry; } else { oldPoint = savedCRD.get(at); oldX = oldPoint.getX(); oldY = oldPoint.getY(); } dx = oldX - savedCenter.getX(); dy = oldY - savedCenter.getY(); distance = Math.hypot(dx, dy); if (distance > 0.1) { costheta0 = dx / distance; sintheta0 = dy / distance; // theta0 + delta at.rx = savedCenter.getX() + distance * (costheta * costheta0 - sintheta * sintheta0); at.ry = savedCenter.getY() + distance * (sintheta * costheta0 + costheta * sintheta0); } } } }
922c6df5-1138-4e90-acff-d9f09876fbfd
4
protected Upgrade bonusFor(int state) { switch (state) { case (DRILL_MELEE ) : return Garrison.MELEE_TRAINING ; case (DRILL_RANGED ) : return Garrison.MARKSMAN_TRAINING ; case (DRILL_ENDURANCE) : return Garrison.ENDURANCE_TRAINING ; case (DRILL_AID ) : return Garrison.AID_TRAINING ; } return null ; }
38fa91d0-3126-415c-a4cd-46cf08a90e8e
5
@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 Cotizacion)) { return false; } Cotizacion other = (Cotizacion) object; if ((this.idCotizacion == null && other.idCotizacion != null) || (this.idCotizacion != null && !this.idCotizacion.equals(other.idCotizacion))) { return false; } return true; }
a2204dfd-ea11-445c-bb70-b75cc26a4c26
0
public int tapes() { return toRead.size(); }
2b141d27-e94c-4b1d-91f0-5dd03d7af602
1
public ArrayList<BEPlaylist> getAllPlaylists() throws SQLException { ArrayList<BEPlaylist> result = new ArrayList<BEPlaylist>(); Statement stm = DBConnection.getConnection().createStatement(); stm.execute("Select * From Playlist"); ResultSet res = stm.getResultSet(); while (res.next()) { int id = res.getInt("ID"); String name = res.getString("Name"); result.add(new BEPlaylist(id, name)); } return result; }
d0b41e93-9ebb-4a4a-b66f-c0de0bc7b515
2
private void var_decl_id() { if( is(TK.ID) ) { if (symtab.add_entry(tok.string, tok.lineNumber, TK.VAR)) { gcprint("int "); gcprintid(tok.string); gcprint("="+initialValueEVariable+";"); } scan(); } else { parse_error("expected id in var declaration, got " + tok); } }
87fe6d18-393e-40cb-9c57-4b1da468e302
8
public Game(JavaPlugin plugin, int gameid, int maxPlayers, Location signLoc, String gameName, GameStage gamestage, ArrayList<Location> teamspawns, long delay, long period) { if (plugin == null) { throw new IllegalArgumentException("Plugin cannot be null!"); } if (!plugin.isEnabled()) { throw new IllegalArgumentException(plugin.getName() + " is not enabled and is trying to setup games!"); } if (gameid < 1) { throw new IllegalArgumentException("Game ID cannot be less than 1, given: " + gameid); } if (maxPlayers < 1) { throw new IllegalArgumentException("Max players cannot be less than 1, given: " + maxPlayers); } if (gameName == null || gameName == "") { throw new IllegalArgumentException("The game's name cannot be null or blank!"); } if (teamspawns == null || teamspawns.isEmpty()) { throw new IllegalArgumentException("The game's spawn points cannot be null or empty!"); } this.plugin = plugin; this.gameid = gameid; this.maxPlayers = maxPlayers; this.signLoc = signLoc; this.gameName = gameName; this.gamestage = gamestage; this.defaultStage = gamestage; this.teamspawns = teamspawns; taskID = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, this, delay, period); }
7b72e318-05fe-4d47-8ef4-f55a519de0e7
0
@Override public void setInvokeHandler(Object invokeHandler) { this.invokeHandler = invokeHandler; }
8d6f1305-0e0e-403a-97eb-7ced95de5cce
3
private static ArrayList<Fact> getNonAnswers(ArrayList<Fact> list) { ArrayList<Fact> newList = new ArrayList(); for (Fact f : list) { if (!f.isAnswer() && !f.isMiddle()) { newList.add(f); } } Collections.sort(newList); return newList; }
7349054b-ada4-487d-9c74-23e5549e5a6a
7
public void mouseDragged(MouseEvent e) { if (dragCallback != null) { int mask = e.getModifiers(); int index = 0; if ((mask & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) { index = MouseEvent.BUTTON1; } else if ((mask & InputEvent.BUTTON2_MASK) == InputEvent.BUTTON2_MASK) { index = MouseEvent.BUTTON2; } else if ((mask & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK) { index = MouseEvent.BUTTON3; } lastDragEvents[index] = e; // ignore small frag amounts if (firstPressEvents[index] == null) { return; } int dx = Math.abs(e.getX() - firstPressEvents[index].getX()); int dy = Math.abs(e.getY() - firstPressEvents[index].getY()); if (dx > MIN_DRAG_THRESHOLD || dy > MIN_DRAG_THRESHOLD) { //Classify it as a drag dragCallback.doDragCallback(firstPressEvents[index], e, resultsModel); } } }
badd7f3c-95e1-4e1b-999d-95b672755628
3
public static void main(String args[]) { int portnumber = 0; if (args.length > 0) { portnumber = Integer.parseInt(args[0]); } else { System.out.println("The portnumber to listen to is: "); Scanner scanner = new Scanner(System.in); String line = scanner.nextLine(); if(!line.isEmpty()) { portnumber = Integer.parseInt(line); } else { portnumber = HTTPSettings.PORT_NUM; } scanner.close(); } try { System.out.println("Server started"); HTTPListener listener = new HTTPListener(portnumber); listener.startUp(); } catch (Exception e) { e.printStackTrace(); } }
7a1082b6-873c-4be0-9de1-501b8e276247
2
void parseLocation(String loc) { loc = loc.replaceAll("[<>()]", ""); if (loc.startsWith("complement")) { complement = true; loc = loc.substring(COMPLEMENT_STRING.length()); } String se[] = loc.split("[\\.]+"); if (se.length > 1) { start = Gpr.parseIntSafe(se[0]); end = Gpr.parseIntSafe(se[1]); } }
474d11c9-7bbb-43ca-b1e3-24def4fbe905
8
private static List<OtuHolder> getOTUList(HashMap<Integer, Holder> map, OtuWrapper wrapper) throws Exception { List<OtuHolder> list = new ArrayList<OtuHolder>(); List<Integer> keys = new ArrayList<Integer>(); int numOTUS =wrapper.getOtuNames().size(); for( Integer key : map.keySet()) { Holder h = map.get(key); if( h.ad != null && h.dis != null) { keys.add(key); if( h.ad.size() != numOTUS || h.dis.size() != numOTUS) throw new Exception("Logic error"); } } Collections.sort(keys); for( int x=0; x <numOTUS; x++) { OtuHolder o = new OtuHolder(); o.otuName = wrapper.getOtuNames().get(x); list.add(o); for( Integer i : keys) { Holder h = map.get(i); o.adSamples.add(h.ad.get(x)); o.disSamples.add(h.dis.get(x)); } try { o.pValue = TTest.pairedTTest(o.adSamples, o.disSamples).getPValue(); } catch(Exception ex) { } } Collections.sort(list); return list; }
60c27fb2-a8b9-4432-a740-df6aea10605e
0
public void removeServiceListener(IServiceListener listener) { this._listeners.remove(listener); }
d84c1a56-8069-4728-b77d-69744d9fcb09
5
public void print(Graphics g, int x, int lag){ g.drawImage(bg.getImg(), 0, 0, null); int j0 = (x-lag)/genObstacle.sWidth -1; // part of the grid to draw the obstacles (j0<0 special case) int j1 = j0 + Stubi.WINDX/genObstacle.sWidth + 2; for (int i = 0; i<obstacles.length;++i){ // i = y coord for (int j = j0; j<obstacles[i].length && j<=j1; ++j) { // j = x coord Obstacle tmp; int xx = lag - x; // Position of printing if (j<0) { // Print the beginning of the level (a wall ? a repeat of the first sequence ?) tmp = obstacles[i][0]; xx += tmp.getX() + genObstacle.getWidth()*j; } else { tmp = obstacles[i][j]; xx += tmp.getX(); } if (tmp.visible()) { int y = tmp.getY(); g.drawImage(tmp.getImg(),xx, y, null); // Buffered Image, x coord, y coord, no Image observer } } } }
0371f1ce-85b2-4c08-8628-9acf9c3d7359
9
default WorldCoord getSubassemblySize(Entity excluding, Entity part) { WorldCoord s = part.getSize(); double x = s.x, y = s.y, z = s.z; if (getJoints().has(part)) { EnumMap<JointType, Double> extents = new EnumMap<>(JointType.class); for (Joint j : getJoints().get(part)) { if (j.to != excluding) { switch (j.type) { case LEFT: case RIGHT: { extents.put(j.type, Math.max(extents.getOrDefault(j.type, 0.0), getSubassemblySize(part, j.to).x)); break; } case TOP: case BOTTOM: { extents.put(j.type, Math.max(extents.getOrDefault(j.type, 0.0), getSubassemblySize(part, j.to).y)); break; } case FRONT: case BACK: { extents.put(j.type, Math.max(extents.getOrDefault(j.type, 0.0), getSubassemblySize(part, j.to).z)); break; } default: {} } } } x = extents.getOrDefault(JointType.LEFT, 0.0) + x + extents.getOrDefault(JointType.RIGHT, 0.0); y = extents.getOrDefault(JointType.TOP, 0.0) + y + extents.getOrDefault(JointType.BOTTOM, 0.0); z = extents.getOrDefault(JointType.FRONT, 0.0) + z + extents.getOrDefault(JointType.BACK, 0.0); } return new WorldCoord(x, y, z); }
2ca799eb-993f-43c3-bbcd-a6bc84377178
2
public static RoadGraph findNearestForStation(Point p) { RoadGraph nearestPoint = null; double minDistance = Double.POSITIVE_INFINITY; double dist; for (RoadGraph i : JMaps.getRoadGraphList()) { dist = Math.sqrt((i.getPoint().x - p.x) * (i.getPoint().x - p.x) + (i.getPoint().y - p.y) * (i.getPoint().y - p.y)); if (dist < minDistance) { minDistance = (int) dist; nearestPoint = i; i.setImportant(true); } } return nearestPoint; }
279132d2-c8a0-4042-afa1-c5241f75639d
5
public boolean doesNotSurpassGrid(){ int moveable = 0; if(this.vehicle.isHorizontal()){ moveable = this.vehicle.position.x; } else { moveable = this.vehicle.position.y; } if(moveable + this.steps + (this.vehicle.length-1) < this.gridSize && steps > 0){ return true; } else if (moveable + this.steps >= 0 && steps < 0){ return true; } else { return false; } }
adffaba4-82ab-488f-b958-f2a9afab3afe
6
@EventHandler public void EnderDragonHunger(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getEnderDragonConfig().getDouble("EnderDragon.Hunger.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getEnderDragonConfig().getBoolean("EnderDragon.Hunger.Enabled", true) && damager instanceof EnderDragon && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.HUNGER, plugin.getEnderDragonConfig().getInt("EnderDragon.Hunger.Time"), plugin.getEnderDragonConfig().getInt("EnderDragon.Hunger.Power"))); } }
576d8296-e7b6-49c8-9c83-c65f3ab258bc
0
public PdbTMReaderWriter () { super() ; // if (Outliner.DEBUG) { System.out.println("\tStan_Debug:\tPdbTMReaderWriter:constructor:DLL is loaded? " + bNativeInterfaceCodeLoaded); } // if (Outliner.DEBUG) { System.out.println("\tStan_Debug:\tPdbTMReaderWriter:constructor:DLL is initialized? " + bNativeInterfaceCodeInitialized); } } // end constructor
a06aa10c-47d5-4407-9e2b-7c50ff311fd1
3
public ReleaseType getLatestType() { this.waitForThread(); if (this.versionType != null) { for (ReleaseType type : ReleaseType.values()) { if (this.versionType.equals(type.name().toLowerCase())) { return type; } } } return null; }
0799a801-72d2-46cc-8cba-7b0d0a1fa07f
5
protected void remove(TileObjectDisplayData displayData){ //check if any of the three categories has the displayData, and remove it. if (displayData == characterData){ clearCharacterData(); notifyDataRemoved(displayData); return; } if (itemData.contains(displayData)){ itemData.remove(displayData); notifyDataRemoved(displayData); return; } Direction dataDirection = null; for (Direction d : activeTile.getAllDirections()){ if (edgeData.get(d) == displayData){ dataDirection = d; break; } } if (dataDirection != null){ //indicates it was found edgeData.remove(dataDirection); notifyDataRemoved(displayData); return; } }
c0c01d30-10d1-4e90-9058-5b92bd8987e7
6
HashMap<Character,Integer> generate_map(String k, int[] num) { //int num_size=num.length; int cur_num=0; HashMap<Character,Integer> m=new HashMap<Character,Integer>(); boolean[] filled=new boolean[26]; for(int i=0;i<k.length();i++) { char cur_char=k.charAt(i); int pos=cur_char-'A'; if(!filled[pos]) { m.put(Character.valueOf(cur_char), Integer.valueOf(num[cur_num])); filled[pos]=true; } else { continue; } if(cur_num==8) { cur_num=0; } else { cur_num++; } } for(int i=0;i<26;i++) { char cur_char=(char)('A'+i); //int pos=cur_char-'A'; if(!filled[i]) { m.put(Character.valueOf(cur_char), Integer.valueOf(num[cur_num])); filled[i]=true; } else { continue; } if(cur_num==8) { cur_num=0; } else { cur_num++; } } m.put(' ', Integer.valueOf(num[9])); return m; }
691e9629-4f05-4f99-a8d5-f03ce0a86095
3
public ScrambleDataInfo getScrambleInfo() { if (this.mStream == null) throw new AssertionError(); if (this.mDataInfo != null) throw new AssertionError(); this.mDataInfo = new ScrambleDataInfo(); try { byte[] hdrArr = new byte[2]; this.mStream.read(hdrArr, 0, 2); this.mDataInfo.header = BytewiseHelper.getIntFrom2(unscramble(hdrArr)); byte[] lenArr = new byte[8]; this.mStream.read(lenArr, 0, 8); this.mDataInfo.dataLength = BytewiseHelper.getLongFrom8(unscramble(lenArr)); } catch (IOException e) { // snap } return this.mDataInfo; }
be04e901-4ab9-4bb3-9f45-3a7e2e962bc9
0
public String toString() { String affiche = "message actionneur"; return affiche; }
d091269b-da7d-4f53-b9c3-4354fd663fb7
7
private SubField[] parseSubFields(String name, int ior, String desc) { int totalbits = 0; int count = 0; SubField[] sfs = new SubField[8]; StringCharacterIterator i = new StringCharacterIterator(desc); int ior_hbit = 7; while ( ior_hbit >= 0 && i.current() != CharacterIterator.DONE ) { if ( i.current() == '.') { ior_hbit = readUnusedField(i, sfs, count, ior_hbit); totalbits += sfs[count].length; } else if ( i.current() == 'x') { ior_hbit = readReservedField(i, sfs, count, ior_hbit); totalbits += sfs[count].length; } else { ior_hbit = readNamedField(i, ior, sfs, count, ior_hbit); totalbits += sfs[count].length; } count++; StringUtil.peekAndEat(i, ','); StringUtil.skipWhiteSpace(i); } // check that there are exactly 8 bits if ( totalbits != ioreg_length ) { throw new Util.Error("Layout Error", "expected "+ioreg_length+" bits, found: "+totalbits+" in "+StringUtil.quote(name)); } // resize the array to be smaller SubField[] subFields = new SubField[count]; System.arraycopy(sfs, 0, subFields, 0, count); // calculate the commit points (i.e. last write to the field) HashSet fs = new HashSet(); for ( int cntr = subFields.length - 1; cntr >= 0; cntr-- ) { SubField subField = subFields[cntr]; if ( !fs.contains(subField.field) ) subField.commit = true; fs.add(subField.field); } return subFields; }
2d46d49f-60b9-4c45-a1b1-be497b0f206f
9
private void LoadAllLists() { ResultSet tasksOnAssetListResultSet = null; Statement statement; try { statement = connection.createStatement(); tasksOnAssetListResultSet = statement.executeQuery("SELECT * FROM Task WHERE projectID = " + projectID + ";"); randSQL.loadAllUsers(); SetOfUsers allusers = randSQL.getAllUsers(); while (tasksOnAssetListResultSet.next()){ int taskID; int projectID; User responsibleUser = null ; int taskPriority; String status; String taskName; String taskType; taskID = tasksOnAssetListResultSet.getInt("taskID"); projectID = tasksOnAssetListResultSet.getInt("projectID"); int userResponsible = tasksOnAssetListResultSet.getInt("responsiblePerson"); for(int i=0; i<allusers.size();i++) { int userID = allusers.get(i).getUserID(); if(userResponsible == userID) { responsibleUser = allusers.get(i); break; } } taskPriority = tasksOnAssetListResultSet.getInt("taskPriority"); status = tasksOnAssetListResultSet.getString("status"); taskName = tasksOnAssetListResultSet.getString("taskName"); taskType = tasksOnAssetListResultSet.getString("type"); Task newTask = new Task(taskID, responsibleUser,taskName, taskPriority , status,projectID, null, taskType); if (responsibleUser == null ) { //add to waiting waitingTasks.add(newTask); } else if (newTask.getStatus().equals("Not Started") && newTask.getResponsiblePerson() != null) { //Allocated allocatedTasks.add(newTask); } else if (newTask.getStatus().equals("In Progress")) { //add to inprogress tasksInProgress.add(newTask); } else if (newTask.getStatus().equals("Completed")) { //add to completed completedTasks.add(newTask); } allocatedTaskList.setListData(allocatedTasks);; completedTaskList.setListData(completedTasks);; tIPList.setListData(tasksInProgress);; waitTaskList.setListData(waitingTasks);; OverviewTaskCellRenderer renderer = new OverviewTaskCellRenderer(); //custom cell renderer to display property rather than useless object.toString() allocatedTaskList.setCellRenderer(renderer); completedTaskList.setCellRenderer(renderer); tIPList.setCellRenderer(renderer); waitTaskList.setCellRenderer(renderer); } } catch (SQLException ex) { Logger.getLogger(ManagerUI.class.getName()).log(Level.SEVERE, null, ex); } }
cb56271b-2235-41ac-82ad-7772c5085fbd
8
public void generation(GameField currentField, GameField generateTo) { if(currentField.width!=generateTo.width || currentField.height!=generateTo.height) { //what the holy fuck are you trying to do? throw new RuntimeException(); } this.currentField=currentField; this.nextField=generateTo; synchronized(generateTo.lock){ synchronized(currentField.lock) { for(int ix=0;ix<currentField.width;ix++) { for(int iy=0;iy<currentField.height;iy++) { byte numNeighbours=getNumOfNeighbours(currentField, ix, iy); if(currentField.aliveCells[ix][iy]) { //i'm alive! if(numNeighbours<2) { generateTo.aliveCells[ix][iy]=false; //alive, less than 2 neighbours --> DEATH } else if(numNeighbours<=3) { generateTo.aliveCells[ix][iy]=true; // alive, 2/3 neighbours --> lives on } else { generateTo.aliveCells[ix][iy]=false; // alive, 4+ neighbours --> overcrowding } } else { //i'm dead! if(numNeighbours==3) { generateTo.aliveCells[ix][iy]=true; // dead, 3 neighbours -> new life! } else { generateTo.aliveCells[ix][iy]=false; // anything else won't do nothing. } } } } generateTo.generation=currentField.generation+1; } } }
d1c16c47-4bac-4e5a-a73d-9377fed6a1da
3
@Override public void insert(Matrix matrix, int matrix_id) throws SQLException { deleteMatrix(matrix_id); int rows = matrix.getRowsCount(); int cols = matrix.getColsCount(); long startTime = System.currentTimeMillis(); statement = connection.prepareStatement(insertMatrixString); for (int i = 1; i <= rows; i++) { for (int j = 1; j <= cols; j++) { try { statement.setInt(1, matrix_id); statement.setInt(2, i); statement.setInt(3, j); statement.setDouble(4, matrix.getValue(i - 1, j - 1)); statement.addBatch(); //statement.executeUpdate(); } catch (Exception ex) { System.out.println("Error: " + ex); } } } statement.executeBatch(); statement.close(); //run time long endTime = System.currentTimeMillis(); long time = endTime - startTime; System.out.println("Recording of the data base lasted " + time + " ms."); }
d3aed4e8-50c9-4de6-8742-656a90339502
2
public ContentBody toContentBody() { if (file != null) { return new FileBody(file) { @Override public String getFilename() { return fileName; } }; } else if (data != null) { return new ByteBufferBody(data) { @Override public String getFilename() { return fileName; } }; } else { // never happens throw new IllegalStateException("no upload data"); } }
7e6e25bb-ce18-4608-9898-b9c3df645824
8
public static final void FormatTable2() { final File readFile = new File("printerfriendly.htm"); final File writeFile = new File("Table2.txt"); try { writeFile.createNewFile(); // create write file final FileWriter outStream = new FileWriter(writeFile); // open filewriter stream final BufferedWriter out = new BufferedWriter(outStream); final FileReader readStream = new FileReader(readFile); final BufferedReader br = new BufferedReader(readStream); String input; while((input = br.readLine()) != null) { if(input.contains("> +") || input.contains("> -") || input.contains("NEEDS") || input.contains(VAR.DARS_TITLE_KEY)) { input = input.replaceAll(VAR.WHITE_SPACE_REGEX, " ").replaceAll(VAR.REGEX, ""); System.out.println(input); out.write(input + "\n"); } if(input.contains("a href=")) { String[] courses = input.split("\">"); for (int i = 1; i < courses.length; i++) { courses[i] = courses[i].substring(0, courses[i].indexOf('<')); System.out.println(courses[i]); out.write(courses[i] + "\n"); } } } out.close(); br.close(); } catch (Exception e) { e.printStackTrace(); } }
d2c2133a-2a7d-4384-9b99-9bfabc712c14
0
public boolean isRunning(){ return this.running; }
3b8ce406-b4aa-4702-9317-27b8eb77f377
4
public void addAgent(String key, GenericAgent agent) { try { if (agent instanceof Organization) return; AgentRole role = agent.getAllAgentRoles().values().iterator().next(); AgentController control = role.getOwner().getContainerController().acceptNewAgent(key, agent); //control.start(); if( !control.getState().getName().equals("Active") ) control.start(); agents.put(key, agent); } catch(ControllerException exception) { exception.printStackTrace(); } catch(RuntimeException exception) { exception.printStackTrace(); } }
65bdfb4d-78b3-4f20-b789-5edb3411b145
0
@Override public Address getAddress() { return super.getAddress(); }
50b0f2d1-8a90-4d6e-8781-b80961f35c8e
5
@Override protected String crearTextoRespuesta() { StringBuilder sb = new StringBuilder("***Resultados del algoritmo de inducción***\n\n"); sb = sb.append("Explicación:\n"); sb = sb.append("Objetivo: ").append(objetivo).append('\n'); for (Regla r : reglasDisparadas) { sb = sb.append("Se disparó la regla ").append(r.getIndiceDeRegla()).append(" y se agregó: ").append(r.getProducto()); sb = sb.append('\n'); sb = sb.append("Porque: \n"); sb = sb.append(r.toString()).append('\n'); } sb = sb.append('\n'); sb = sb.append("Hechos de inicio: \n"); for (String s : hechosDeInicio) { sb = sb.append(s).append('\n'); } sb = sb.append('\n'); sb = sb.append("Hechos preguntados: \n"); for (String s : hechosPreguntados) { sb = sb.append(s).append('\n'); } sb = sb.append('\n'); sb = sb.append("Hechos inferidos: \n"); for (String s : hechosInferidos) { sb = sb.append(s).append('\n'); } sb = sb.append(seEncontroObjetivo ? "Se encontró el objetivo!\n" : "No se encontró el objetivo :(\n"); return sb.toString(); }
97815ed5-e2e8-4225-b990-ce68384d8225
2
public void update(long deltaMs) { GameActor a = Application.get().getLogic().getActor(actor); if(a != null) { PhysicsComponent pc = (PhysicsComponent)a.getComponent("PhysicsComponent"); x = pc.getX(); y = pc.getY(); z = pc.getZ(); setRotation(pc.getAngleRad()); } if(animation != null) { animation.update(deltaMs); } }
083c1a26-f226-4965-957a-9b7786718e63
5
@Test public void testRemoveArgs() { System.out.println("removeArgs"); NodeVariable.resetIds(); NodeFunction.resetIds(); NodeArgument.resetIds(); COP_Instance cop = null; try { cop = Cerberus.getInstanceFromFile("bounded_arity5.cop2"); } catch (InvalidInputFileException ex) { ex.printStackTrace(); } for (NodeFunction f : cop.getNodefunctions()) { if (f.id() == 4){ System.out.println("Found f: "+f); instance = f.getFunction(); } } System.out.println("Function selected:\n"+instance); LinkedList<NodeVariable> args = new LinkedList<NodeVariable>(); args.add(NodeVariable.getNodeVariable(1)); args.add(NodeVariable.getNodeVariable(5)); args.add(NodeVariable.getNodeVariable(2)); args.add(NodeVariable.getNodeVariable(2)); args.add(NodeVariable.getNodeVariable(13)); instance.removeArgs(args); NodeArgument[] arguments = { NodeArgument.getNodeArgument("0"), NodeArgument.getNodeArgument("0") }; assertEquals(instance.evaluate(arguments), 2.0, 0.0); arguments[0]=NodeArgument.getNodeArgument("0"); arguments[1]=NodeArgument.getNodeArgument("1"); assertEquals(instance.evaluate(arguments), 3.0, 0.0); arguments[0]=NodeArgument.getNodeArgument("1"); arguments[1]=NodeArgument.getNodeArgument("0"); assertEquals(instance.evaluate(arguments), 43.0, 0.0); arguments[0]=NodeArgument.getNodeArgument("1"); arguments[1]=NodeArgument.getNodeArgument("1"); assertEquals(instance.evaluate(arguments), 15.0, 0.0); for (NodeFunction f : cop.getNodefunctions()) { if (f.id() == 2){ System.out.println("Found f: "+f); instance = f.getFunction(); } } System.out.println("Function selected:\n"+instance); args = new LinkedList<NodeVariable>(); args.add(NodeVariable.getNodeVariable(1)); args.add(NodeVariable.getNodeVariable(5)); args.add(NodeVariable.getNodeVariable(2)); args.add(NodeVariable.getNodeVariable(2)); args.add(NodeVariable.getNodeVariable(13)); instance.removeArgs(args); NodeArgument[] arguments2 = { NodeArgument.getNodeArgument("0") }; assertEquals(instance.evaluate(arguments2), 8.0, 0.0); arguments2[0]=NodeArgument.getNodeArgument("1"); assertEquals(instance.evaluate(arguments2), 2.0, 0.0); }
4527cb0f-c36e-48cd-b839-f6f1a39b9f14
4
public ThePanel(String name, String imgPath) { setBackground(BG_COLOR); setLayout(new BorderLayout()); label.setForeground(FG_COLOR); label.setFont(new Font("Sans", Font.BOLD, 90)); label.setVerticalAlignment(SwingConstants.CENTER); label.setHorizontalAlignment(SwingConstants.CENTER); label.setText(name); try { bgImg = ImageIO.read(new File(imgPath)); } catch (IOException ex) { System.err.println("[error] cannot read image path '" + imgPath + "'"); add(label, BorderLayout.CENTER); } addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { hover = true; if (actionEnabled) showBorder(); } @Override public void mouseExited(MouseEvent e) { hover = false; hideBorder(); } @Override public void mouseReleased(MouseEvent e) { if (action != null && actionEnabled) action.run(); } }); }
fe149beb-8a85-44c4-88ee-5deac551dd1c
1
public Object put(Object key, Object value) { processQueue(); Object rtn = hash.put(key, SoftValueRef.create(key, value, queue)); if (rtn != null) rtn = ((SoftReference)rtn).get(); return rtn; }
7df098bf-e98e-4129-b0da-1c0a2b63a3db
1
public boolean InsertarTipoCultivo(TipoCultivo p){ if (p!=null) { cx.Insertar(p); return true; }else { return false; } }
6c66f4e1-d857-409d-b502-66f3c238b059
4
@Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof DateSimple)) { return false; } DateSimple d = (DateSimple) obj; return year == d.year && month == d.month && day == d.day; }
f08b0994-2d79-4bf9-b752-2dcb4d9b62ec
1
public Boolean isLastCoffer(Player player){ if(player==null) return null; return (getTotalCoffers(player)==1); }
3fd7f627-71cc-4c78-964f-4a5278cb0be9
5
public void CreateAccount(RequestPacket request, DBCollection coll, User user) { try { if(!(paramValidator.validate(request.getUser_name(), "username") && paramValidator.validate(request.getEmail(), "email"))) { user.sendMessage(msgTransformer.writeMessage(new ResponsePacket().setResponse("response").setMessage("Invalid username or email"))); return; } // Check if username or email is already taken if(!coll.find(new BasicDBObject("user_name", request.getUser_name())).hasNext()) { if(!coll.find(new BasicDBObject("email", request.getEmail())).hasNext()) { // Save user to db BasicDBObject doc = new BasicDBObject() .append("user_name", request.getUser_name()) .append("email", request.getEmail()) .append("hash_password", request.getHash_password()) .append("salt", salt); coll.insert(doc); user.sendMessage(msgTransformer.writeMessage(new ResponsePacket().setResponse("create_success").setMessage("account created"))); sendUUID(user); String user_name = request.getUser_name(); user.setUser_name(user_name); UserManager.getInstance().addAuthenticatedUser(user); System.out.println("User " + user_name + " created account & authenticated"); GameManager.getInstance().sendLobbyInfo(); } else { user.sendMessage(msgTransformer.writeMessage(new ResponsePacket().setResponse("response").setMessage("email already taken"))); } } else { user.sendMessage(msgTransformer.writeMessage(new ResponsePacket().setResponse("response").setMessage("username already taken"))); } }catch(Exception e) { user.sendMessage(msgTransformer.writeMessage(new ResponsePacket().setResponse("response").setMessage("Invalid username or email"))); } }
c2d226e3-cb80-4e89-9544-b19b924f7eaa
8
public int Finder(int start, int end, int elementToFind) { int mid; System.out.println("start:"+start+ " "+"end:"+end); if(start > end) { return -1; } mid = (start+end)/2; System.out.println("mid : "+number[mid] + " " + elementToFind); if(number[mid] == elementToFind) { return mid; } if(number[start] < number[mid]) { System.out.println("start is lesser than mid"); if(elementToFind > number[mid]) { return Finder(mid+1, end, elementToFind); } else if((elementToFind < number[mid])&&(elementToFind < number[start])) { return Finder(mid+1, end, elementToFind); }else { return Finder(start, mid-1, elementToFind); } } else { System.out.println("start is greater than mid"); if(elementToFind > number[end]) { return Finder(start, mid-1, elementToFind); } else if(elementToFind <= number[end]) { return Finder(mid+1, end, elementToFind); } } return -1; }
0d275276-6770-4929-b2bc-c40572918577
4
static void returnConnection(Connection conn) throws DaoConnectException { try { if (conn == null || !conn.isValid(DB_ISVALID_TIMEOUT)) { throw new DaoConnectException("Can't return: null or unvalid connection."); } } catch (SQLException ex) { throw new DaoConnectException("Error in check valid connection.", ex); } try { queue.offer((ProxyConnection) conn); } catch (Exception ex) { throw new DaoConnectException("Can't return unknown connection.", ex); } }
e3e546f8-bf18-497a-a468-3c865a5fc78a
5
public void doAction(String value) { char choice = value.toUpperCase().charAt(0); while (choice != 'A' && choice != 'B' && choice != 'C' && choice != 'D') { System.out.println("Invalid selection"); value = getInput(); choice = value.toUpperCase().charAt(0); } if (choice == 'B') { System.out.println("Congratulations, that is the correct answer!"); } else { System.out.println("Sorry, that is the wrong answer."); } }
5228f072-75ec-4997-9995-18113a8e7964
7
private SubFrameResidual(int partitionOrder, int bits, int escapeCode, BitsReader data) throws IOException { this.partitionOrder = partitionOrder; numPartitions = 1<<partitionOrder; riceParams = new int[numPartitions]; int numSamples = 0; if (partitionOrder > 0) { numSamples = blockSize >> partitionOrder; } else { numSamples = blockSize - predictorOrder; } for (int pn=0; pn<numPartitions; pn++) { int riceParam = data.read(bits); int partitionSamples = 0; if (partitionOrder == 0 || pn > 0) { partitionSamples = numSamples; } else { partitionSamples = numSamples - predictorOrder; } if (riceParam == escapeCode) { // Partition holds un-encoded binary form riceParam = data.read(5); for (int i=0; i<partitionSamples; i++) { data.read(riceParam); } } else { // Partition holds Rice encoded data for (int sn=0; sn<numSamples; sn++) { // Q value stored as zero-based unary data.bitsToNextOne(); // R value stored as truncated binary data.read(riceParam); } } // Record the Rice Parameter for use in unit tests etc riceParams[pn] = riceParam; } }
510fd319-af90-45a9-b6d9-1e3fd79684e8
1
public Character fetchAbbr() { if(!hasAbbArg()) { throw new InputMismatchException("There is no abbreviation at the head of ArgSet."); } else { String s = pop(); return s.charAt(1); } }
5e68b1c0-9edb-4699-bcc4-1e1d13b9ed2b
7
private static <T> Entry<T> mergeLists(Entry<T> one, Entry<T> two) { /* There are four cases depending on whether the lists are null or not. * We consider each separately. */ if (one == null && two == null) { // Both null, resulting list is null. return null; } else if (one != null && two == null) { // Two is null, result is one. return one; } else if (one == null && two != null) { // One is null, result is two. return two; } else { // Both non-null; actually do the splice. /* This is actually not as easy as it seems. The idea is that we'll * have two lists that look like this: * * +----+ +----+ +----+ * | |--N->|one |--N->| | * | |<-P--| |<-P--| | * +----+ +----+ +----+ * * * +----+ +----+ +----+ * | |--N->|two |--N->| | * | |<-P--| |<-P--| | * +----+ +----+ +----+ * * And we want to relink everything to get * * +----+ +----+ +----+---+ * | |--N->|one | | | | * | |<-P--| | | |<+ | * +----+ +----+<-\ +----+ | | * \ P | | * N \ N | * +----+ +----+ \->+----+ | | * | |--N->|two | | | | | * | |<-P--| | | | | P * +----+ +----+ +----+ | | * ^ | | | * | +-------------+ | * +-----------------+ * */ Entry<T> oneNext = one.mNext; // Cache this since we're about to overwrite it. one.mNext = two.mNext; one.mNext.mPrev = one; two.mNext = oneNext; two.mNext.mPrev = two; /* Return a pointer to whichever's smaller. */ return one.mPriority < two.mPriority? one : two; } }
997973d1-77d5-44d4-9004-3e98b73c8473
0
@Override public void keyTyped(KeyEvent arg0) { // TODO Auto-generated method stub }
99615151-2d01-40bf-8ac7-09d8202faa1d
4
@Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Combination that = (Combination)o; if (!Arrays.equals(coins, that.coins)) { return false; } return true; }
c50d1647-0cf5-44d2-ac9c-7a37e1bb3245
5
private boolean isDiagonallyOccupied(HantoCell from, HantoCell to){ boolean isOccupied = false; if (to.getX() > from.getX()){ for (int i = from.getX() + 1; i < to.getX(); i++){ if (findCell(i, -i) == null){ isOccupied = false; break; } } } else { for (int i = to.getX() - 1; i < from.getX(); i++){ if (findCell(i, -i) == null){ isOccupied = false; break; } } } return isOccupied; }
95c7ec70-db52-4a11-b9c8-e2fc059ce328
8
private void readIndex() throws IOException { // read the index entirely into memory if (this.keys != null) { return; } this.count = 0; this.keys = new WritableComparable[1024]; this.positions = new long[1024]; try { int skip = INDEX_SKIP; LongWritable position = new LongWritable(); WritableComparable lastKey = null; while (true) { WritableComparable k = comparator.newKey(); if (!index.next(k, position)) { break; } // check order to make sure comparator is compatible if (lastKey != null && comparator.compare(lastKey, k) > 0) { throw new IOException("key out of order: " + k + " after " + lastKey); } lastKey = k; if (skip > 0) { skip--; continue; // skip this entry } else { skip = INDEX_SKIP; // reset skip } if (count == keys.length) { // time to grow arrays int newLength = (keys.length * 3) / 2; WritableComparable[] newKeys = new WritableComparable[newLength]; long[] newPositions = new long[newLength]; System.arraycopy(keys, 0, newKeys, 0, count); System.arraycopy(positions, 0, newPositions, 0, count); keys = newKeys; positions = newPositions; } keys[count] = k; positions[count] = position.get(); count++; } } catch (EOFException e) { LOG.warn("Unexpected EOF reading " + index + " at entry #" + count + ". Ignoring."); } finally { indexClosed = true; index.close(); } }
1a91457f-54f4-4211-995d-f9c2530e5f14
7
public synchronized boolean put(String key, String value) throws Exception { if (key != null) { key = key.replaceAll("[\n|\r]+","").trim(); if (key.length() > 0) { key = new String(key.getBytes()); //if (!this.contains(key)) { value = new String(value.getBytes()); value= value.replaceAll("[\n|\r]+", RETURN_TAG).trim(); if (DEBUG) System.out.println("PUT " + key +", " + value + " ("+newkeys.size()+")"); try { rafile.seek(rafile.length()); rafile.writeBytes(key + SEPARATOR + value +"\n"); writeUnsortedSize(++unsortedSize); } catch (IOException e) { return false; } cache[0] = key; cache[1] = value; try { newkeys.put(key,value); if (newkeys.size() % 1000 == 0 && Runtime.getRuntime().freeMemory() < availableMemory / 2) { merge(); } } catch(Exception e) { System.err.println("newkeys.size() = "+newkeys.size() ); } return true; //} } } return false; }
057ce4bb-8d1c-4102-b7b2-476cf33521a9
6
private void setBackgroundColor(int r, int g, int b) { if (r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255) this.view.color.setBackground(new Color(r,g,b)); }
9f13fef4-c0bc-436d-a1f4-f6ce1d0cf59b
8
public static void putResult(String barrierServer, LinkedList<Record> records, Map<Long, LinkedList<Long>> edgeListMap, int blockSize){ BServer server; try { server = (BServer) Naming.lookup(barrierServer); Result [] results = new Result[blockSize]; int remainLen = records.size(); ListIterator<Record> cursorIterator = records.listIterator(); while(remainLen > 0){ if(remainLen >= blockSize){ for(int i=0; i<blockSize; i++){ Record node = cursorIterator.next(); results[i] = new Result( node, edgeListMap.get(node.userid)); } server.putResults(results); remainLen -= blockSize; } else if(remainLen > 0){ results = new Result[remainLen]; for(int i=0; i<remainLen; i++){ Record node = cursorIterator.next(); results[i] = new Result( node, edgeListMap.get(node.userid)); } server.putResults(results); remainLen = 0; } } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NotBoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
aead0156-6fcd-45e7-8024-db5a43b66f80
2
public FlowBlock getNextFlowBlock(StructuredBlock subBlock) { if (subBlock == subBlocks[0]) { if (subBlocks[1].isEmpty()) return subBlocks[1].getNextFlowBlock(); else return null; } return getNextFlowBlock(); }
3a64002d-7dad-41fe-805e-84f882eb3037
3
public SingleTreeNode uct() { SingleTreeNode selected = null; double bestValue = -Double.MAX_VALUE; for (SingleTreeNode child : this.children) { double hvVal = child.totValue; double childValue = hvVal / (child.nVisits + this.epsilon); childValue = Utils.normalise(childValue, bounds[0], bounds[1]); double uctValue = childValue + K * Math.sqrt(Math.log(this.nVisits + 1) / (child.nVisits + this.epsilon)); // small sampleRandom numbers: break ties in unexpanded nodes uctValue = Utils.noise(uctValue, this.epsilon, this.m_rnd.nextDouble()); //break ties randomly // small sampleRandom numbers: break ties in unexpanded nodes if (uctValue > bestValue) { selected = child; bestValue = uctValue; } } if (selected == null) { throw new RuntimeException("Warning! returning null: " + bestValue + " : " + this.children.length); } return selected; }
13bc5c78-acdb-4830-a837-37162654c84a
2
public static Boolean dateIncrense(Date staticsDate){ Date d = new Date(); Date d1 = new Date(); Date d2 = new Date(); d1.setHours(0); d1.setMinutes(0); d1.setSeconds(0); d2.setHours(23); d2.setMinutes(59); d2.setSeconds(59); if(staticsDate.after(d1) && staticsDate.before(d2)){ return false; } return true; }
de736e97-dd5f-47b2-91e8-718b9a132935
7
public String calculateGrade() { double totalMarks = (quiz1 + quiz2 + quiz3 + quiz4) * .10; totalMarks += (midTerm1) * .20; totalMarks += (midTerm2) * .15; totalMarks += finalTerm * .25; double percentage = totalMarks; //because total maximum marks are 100 hence totalMarks would be equal to the percentage if(percentage >= 90) { grade = "A"; } else if(percentage >=80 && percentage <= 89) { grade = "B"; } else if(percentage >=70 && percentage <= 79) { grade = "C"; } else if(percentage >=60 && percentage <= 69) { grade = "D"; } else { grade = "F"; } return grade; }
82cc30a9-8d5c-4a2c-b780-32e3c98c32d5
5
public void deliverMode(Player p){ if(this == PREVOTE){ p.setMaxHealth(20); for(Objective o : p.getScoreboard().getObjectives()){ o.unregister(); } }else if(this == VOTE){ p.setScoreboard(Vote.output); MenuManager.sendPlayerVoteMenu(p); }else if(this == POSTVOTE){ }else if(this == GAME){ } }
d94c1ecd-a754-4bdd-ba57-ae52f9183215
9
public synchronized void bestowBlessings(MOB mob) { norecurse=true; try { if((!alreadyBlessed(mob))&&(numBlessings()>0)) { mob.location().show(this,mob,CMMsg.MSG_OK_VISUAL,L("You feel the presence of <S-NAME> in <T-NAME>.")); if((mob.charStats().getCurrentClass().baseClass().equals("Cleric")) ||(CMSecurity.isASysOp(mob))) { for(int b=0;b<numBlessings();b++) { final Ability Blessing=fetchBlessing(b); if(Blessing!=null) bestowBlessing(mob,Blessing); } } else { final int randNum=CMLib.dice().roll(1,numBlessings(),-1); final Ability Blessing=fetchBlessing(randNum); if((Blessing!=null)&&(!fetchBlessingCleric(randNum))) bestowBlessing(mob,Blessing); } } } catch(final Exception e) { Log.errOut("StdDeity",e); } norecurse=false; }
6652e199-750b-48aa-aab9-58ba655ae3b1
2
public BufferedImage render() { BufferedImage res = new BufferedImage(MainPanel.GAME_WIDTH,MainPanel.GAME_HEIGHT,BufferedImage.TYPE_INT_ARGB); Graphics g = res.getGraphics(); g.setFont(MainPanel.font); // black background for in case of g.setColor(Color.black); g.fillRect(0, 0, MainPanel.GAME_WIDTH, MainPanel.GAME_HEIGHT); // image background g.drawImage(this.level.getBackground(),(int)this.posX,(int)this.posY,null); // mobs g.setColor(Color.yellow); for (int i=0; i<this.level.getMobs().length;i++) { g.fillRect((int)(this.level.getMobs()[i].getPosX()+this.posX),(int)(this.level.getMobs()[i].getPosY()+this.posY),this.level.getMobs()[i].getWidth(),this.level.getMobs()[i].getHeight()); } g.setColor(Color.red); g.fillRect((int)(this.player.getPosX()+this.posX),(int)(this.player.getPosY()+this.posY),this.player.getWidth(),this.player.getHeight()); // we display the timeBonus g.setColor(Color.blue); for (int i=0; i<this.level.getTimeBonus().size();i++) { g.fillRect((int)(this.level.getTimeBonus().get(i).getPosX()+this.posX),(int)(this.level.getTimeBonus().get(i).getPosY()+this.posY),this.level.getTimeBonus().get(i).getWidth(),this.level.getTimeBonus().get(i).getHeight()); } // timer display; g.drawString(String.valueOf((double) this.timer/1000), 10, 10); return res; }
fa7a276b-0b77-4220-ac13-e72a75d48ba1
5
@Override /** * @see IPlayer#bid(int, Pile) * * Return an integer of our bid. The bid must be higher than the current highest bid. * Use the cards in our hand to determine how high we want to bid. */ public boolean bid(int currentHighestBid,Pile hand,boolean canMatch) { if(maxBid==-1) { /* First time called before a game. */ /* Calculate the bid and set it. */ calculateHighestBid(hand); } if((currentHighestBid<maxBid)&&(canMatch==false)) { /* We must increase from the current highest bid. */ return true; } else if((currentHighestBid<=maxBid)&&(canMatch==true)) { /* We are able to match the current highest bid. */ return true; } /* If we get here, then the bidding is too high, so pass. */ return false; }
5f002dc6-0efc-4448-bf3a-3a579ab834d6
9
public static void main(String args[]) { String cfgPath = "sephiabot.xml"; boolean greet = true; final String usage = "\nUsage: sephiabot [-c config file] [--nogreet]\n" + " Default config file: ./sephiabot.xml"; if (args != null && args.length > 0) { for (int i = 0; i < args.length; i++) { if (args[i].equals("--help")) { System.out.println(usage); System.exit(0); } else if (args[i].equals("-c")) { if (args.length > i+1 && !args[i+1].startsWith("-")) cfgPath = args[i+1]; else { System.out.println("You must specify the path of your config file with -c" + usage); System.exit(0); } i++; //Skip the next argument } else if (args[i].equals("--nogreet")) { greet = false; } else { System.out.println("Invalid argument: " + args[i] + usage); System.exit(0); } } } SephiaBot sephiaBot = new SephiaBot(cfgPath, greet); sephiaBot.connect(); while (sephiaBot.hasConnections()) { sephiaBot.poll(); } sephiaBot.log("All connections have been closed. Exiting."); }
c5c17a25-45ff-46ae-bb1b-27d37dbd34f4
2
private void addHardwareSystemIfNew(HardwareSystem hardwareSystem) { for(HardwareSystem hardwareSystemPresent : project.getHardwareSystemsCalculated()) if(hardwareSystemPresent.getId().equals(hardwareSystem.getId())) return; project.getHardwareSystems().add(hardwareSystem); }
eecc5732-4b18-49bb-811c-cd2271f633f5
7
private void updateStateEntry(List<Keyword> keywords, List<String> terms, boolean inAden, boolean askPrice) { if(keywords.isEmpty()) { DialogManager.giveDialogManager().setInErrorState(true); return; } int k_count = 0; int t_count = 0; for( Keyword kw : keywords) { if(kw.getKeywordData().getWord().contains("price")){ k_count ++; } } for( String str : terms) { if( str.equals("price")){ t_count ++; } } if( k_count == keywords.size() && ( t_count == terms.size())) { return; // this means the previous dialog state was error handling } CanteenInfo subState = matchSubState(keywords, terms, inAden, askPrice); CanteenInformationState nextState = new CanteenInformationState(); nextState.setCurrentState(subState); setCurrentDialogState(nextState); }
e1242070-e6d8-4061-8dc6-477f581544cc
7
@Override public int castingQuality(MOB mob, Physical target) { if(mob!=null) { if(mob.fetchEffect(this.ID())!=null) return Ability.QUALITY_INDIFFERENT; final Room R=mob.location(); if(R!=null) { for(int r=0;r<R.numInhabitants();r++) { final MOB M=R.fetchInhabitant(r); if((M!=null)&&(M!=mob)&&(CMLib.flags().isHidden(M))) return super.castingQuality(mob, target,Ability.QUALITY_BENEFICIAL_SELF); } } } return super.castingQuality(mob,target); }
1c72c451-d9fa-42a5-a873-b82db9fa03ea
6
public void validaCampos(String dataInicio, String dataFim, boolean pendencia, String probInformado, String probDetectado, String probSolucao, String probPendencia) { if (dataInicio.equals(" / / : ") == true) { JOptionPane.showMessageDialog(null, "Data Início inválida!"); txt_dataInicio.requestFocus(); } else { if (dataFim.equals(" / / : ") == true) { JOptionPane.showMessageDialog(null, "Data Fim inválida!"); txt_dataFim.requestFocus(); } else { if ((pendencia == true) && (txt_pendencia.getText().isEmpty())) { JOptionPane.showMessageDialog(null, "O motivo da Pendência informada é inválida!"); txt_pendencia.requestFocus(); } else { if (txt_problemaDetectado.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Problema Detectado inválido!"); txt_problemaDetectado.requestFocus(); } else { if (txt_problemaSolucao.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Solução do problema inválida!"); txt_problemaSolucao.requestFocus(); } else { salvar(); } } } } } }
36697af8-0a03-4d2e-a0c0-da9c0dcc894b
8
public static AbstractEvento manutencaoParseEvento(FuncionarioModel funcionario, ManutencaoModel model, EnumEtapasManutencao enumEM) { if (enumEM.equals(EnumEtapasManutencao.RANQUEAMENTO)) { return new EventoRanqueamento(model, funcionario); } else if (enumEM.equals(EnumEtapasManutencao.ANALISE)) { return new EventoAnalise(model, funcionario); } else if (enumEM.equals(EnumEtapasManutencao.PROJETO)) { return new EventoProjeto(model, funcionario); } else if (enumEM.equals(EnumEtapasManutencao.IMPLEMENTACAO)) { return new EventoImplementacao(model, funcionario); } else if (enumEM.equals(EnumEtapasManutencao.TESTE_REGRESSAO)) { return new EventoTesteRegressao(model, funcionario); } else if (enumEM.equals(EnumEtapasManutencao.TESTE_ACEITACAO)) { return new EventoTesteAceitacao(model, funcionario); } else if (enumEM.equals(EnumEtapasManutencao.ENTREGA)) { return new EventoEntrega(model, funcionario); } else { try { throw new Exception("Erro ao dar parse"); } catch (Exception ex) { Logger.getLogger(ControleEventos.class.getName()).log(Level.SEVERE, null, ex); } return null; } }
e900ef7d-d0c5-4f2c-b586-02558e07f7af
2
public static String unicode2String(String unicodeStr) { StringBuffer sb = new StringBuffer(); String str[] = unicodeStr.toUpperCase().split("U"); for (int i = 0; i < str.length; i++) { if (str[i].equals("")) continue; char c = (char) Integer.parseInt(str[i].trim(), 16); sb.append(c); } return sb.toString(); }
1bce9235-f723-4c22-bff2-a01490dbbfd3
7
public static void main(String[] args) { if (args.length != 2) { greska(); } int algNum = -1; try { algNum = Integer.parseInt(args[0]); } catch (NumberFormatException ex) { greska(); } File file = new File(args[1]); if (!file.exists()) { greska(); } List<String> lines = null; try { lines = filterFile(file); } catch (IOException e) { greska(); } SATFormula formula = SATFormula.getClauses(lines); if (algNum == 1) { algoritam1(formula); } else if (algNum == 2) { algoritam2(formula); } else if (algNum == 3) { algoritam3(formula); } }
f6446c6d-0955-4030-b5da-1adb8c3b8d84
2
private void deleteBall(int x, int y) { for(int i=0; i<Balls.size(); i++) { if(Math.sqrt(((x-Balls.elementAt(i).getPosition()[0])*(x-Balls.elementAt(i).getPosition()[0])) + ((y-Balls.elementAt(i).getPosition()[1])*(y-Balls.elementAt(i).getPosition()[1]))) <= Balls.elementAt(i).getRadius()) { Balls.elementAt(i).stop(); Balls.remove(i); return; } } }
adbc4cfb-5f78-4c5e-a44c-37946a21d9bb
5
@Override public MapConnector<String, Long> forceSynchronization() throws Exception { try (Connection con = getConnectorInfo().getConnection()) { forceClear(); int n = 0; StringBuilder values = new StringBuilder(); String stm; for (String s : getMap().keySet()) { values = values.append("(").append("'").append(s).append("'").append(",").append(getMap().get(s)).append(")"); if (n + 1 != BLOCK_INSERT_COUNT && n + 1 != getMap().size() - 1) { values = values.append(","); } n++; if (n == BLOCK_INSERT_COUNT || n == getMap().size() - 1) { stm = "INSERT INTO " + getConnectorInfo().getTableName() + "(key,value) VALUES " + values.toString() + ";"; try (PreparedStatement prepStm = con.prepareStatement(stm)) { prepStm.execute(); } values = new StringBuilder(); n = 0; } } } return this; }
1991b4ce-77f0-42ba-84c0-466db4c7e60e
1
public synchronized void put(T message) { for (MessageQueue<T> q : outputs) { q.put(message); } }
9d095ae2-b528-4424-92ca-68c8a1f02cd9
2
public static void main(String[] args) { try { Date dt = new Date(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); //System.err.println("DBThread Runs"); Class.forName("com.mysql.jdbc.Driver"); connect = DriverManager.getConnection("jdbc:mysql://localhost/cdr_data?user=root&password=root"); preparedStatement = connect.prepareStatement("insert into timetable (timeTablecol) values (TIMESTAMP(?))"); String st = df.format(dt).substring(0, 11) + "14:05:22.650"; System.err.println(st); preparedStatement.setString(1, df.format(dt).substring(0, 11) + "14:20:22.650"); preparedStatement.executeUpdate(); } catch (SQLException e) { Logger.getLogger(ConcurrentDataInsertTest.class.getName()).log(Level.SEVERE, null, e); } catch (ClassNotFoundException ex) { Logger.getLogger(DBInsert.class.getName()).log(Level.SEVERE, null, ex); } }
8df3822d-63fd-469d-9cf5-11164c2d1a8e
7
public ArrayList<Auction> searchWinnerByUsername(String username, String winner) { try { ArrayList<Auction> auctions = new ArrayList<Auction>(); String[] keywords = username.split(" "); String[] usernames = winner.split(" "); String sql = "select * from (select * from " + tableName + " where "; for (int i = 0; i < usernames.length; i++) { if (i != 0) sql = sql + "OR "; sql = sql + "WINNER = " + "'" + usernames[i] + "' "; } sql = sql + ") as t WHERE "; for (int i = 0; i < keywords.length; i++) { if (i != 0) sql = sql + "OR "; sql = sql + "USERNAME LIKE " + "'% " + keywords[i] + " %' OR "; sql = sql + "USERNAME LIKE " + "'" + keywords[i] + " %' OR "; sql = sql + "USERNAME LIKE " + "'% " + keywords[i] + "' OR "; sql = sql + "USERNAME LIKE " + "'% " + keywords[i] + " %' OR "; sql = sql + "USERNAME LIKE " + "'" + keywords[i] + "' "; } s = conn.createStatement(); rs = s.executeQuery(sql); if (!rs.next()) return null; do { Auction auction = new Auction(); auction.setID(rs.getInt("ID")); auction.setName(rs.getString("NAME")); auction.setDescription(rs.getString("DESCRIPTION")); auction.setReserver(rs.getInt("RESERVER")); auction.setBuyOut(rs.getInt("BUYOUT")); auction.setStartPrice(rs.getInt("STARTINGPRICE")); auction.setCurrentPrice(rs.getInt("CURRENTPRICE")); auction.setStartTime(rs.getTimestamp("STARTTIME")); auction.setAuctionTime(rs.getTimestamp("AUCTIONTIME")); auction.setUserName(rs.getString("USERNAME")); auction.setWinner(rs.getString("WINNER")); auction.setSold(rs.getInt("SOLD")); auctions.add(auction); } while (rs.next()); return auctions; } catch (Exception e) { System.out.print("error SQL"); return null; } }
bcd41507-3dd9-49ef-a51e-a415041fe780
8
public int characterAt(int at) throws JSONException { int c = get(at); if ((c & 0x80) == 0) { return c; } int character; int c1 = get(at + 1); if ((c1 & 0x80) == 0) { character = ((c & 0x7F) << 7) | c1; if (character > 0x7F) { return character; } } else { int c2 = get(at + 2); character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2; if ((c2 & 0x80) == 0 && character > 0x3FFF && character <= 0x10FFFF && (character < 0xD800 || character > 0xDFFF)) { return character; } } throw new JSONException("Bad character at " + at); }
e24fcec1-bbac-472c-b444-7a9cee457667
6
private static void exportNode(final Node node, final BufferedWriter writer, final boolean force) throws IOException{ if (!node.isModified() && !force) { return; } final StringBuilder nodeString = new StringBuilder(); nodeString.append(" "); nodeString.append("<node"); nodeString.append(" id='").append(node.getId()).append("'"); if (node.isModified()){ nodeString.append(" action='").append("modify").append("'"); } final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH); nodeString.append(" timestamp='").append(sdf.format(new Date(node.getTimestamp()))).append("'"); if (node.getUser() != null) { nodeString.append(" uid='").append(node.getUser().getId()).append("'"); nodeString.append(" user='").append(StringEscapeUtils.escapeXml(node.getUser().getName())).append("'"); } nodeString.append(" visble='true'"); nodeString.append(" version='").append(node.getVersion()).append("'"); nodeString.append(" changeset='").append(node.getChangeset()).append("'"); nodeString.append(" lat='").append(node.getLat()).append("'"); nodeString.append(" lon='").append(node.getLon()).append("'"); if (node.getNumTags() > 0){ nodeString.append(">\n"); final Set<String> tags = node.getTagKeys(); for (String key: tags){ nodeString.append(" "); nodeString.append("<tag"); nodeString.append(" k='").append(StringEscapeUtils.escapeXml(key)).append("'"); nodeString.append(" v='").append(StringEscapeUtils.escapeXml(node.getTag(key))).append("'"); nodeString.append("/>\n"); } nodeString.append(" </node>\n"); } else { nodeString.append("/>\n"); } writer.write(nodeString.toString()); }
36106d47-0b9a-4506-a390-d16cbaeb611d
6
public void mainMenu() { do { System.out.println(); MenuActions action = userInputManager.showMenu("QUIZ PLAYER MENU", playerMenu); try { switch (action) { case SELECT_QUIZ_FROM_LIST: try { playQuiz(selectQuizToPlay()); } catch (NoQuizException ex) { System.out.println(UserDialog.NO_QUIZZES_AVAILABLE); } break; case VIEW_HIGH_SCORES: viewHighScores(); break; case QUIT: closeDownProgram(); break; default: System.out.print(ExceptionMsg.CHOOSE_VALID_OPTION); } } catch (ChangedMyMindException ex) { //do nothing-just return to menu } } while (true); }
ed836572-a5a0-4ddf-8c93-cd41a1c4bca4
8
private Component luoAsetukset() { JPanel panel = new JPanel(new GridLayout(4, 2)); JLabel pelaaja1Teksti = new JLabel("Pelaaja X: "); final JTextField pelaaja1 = new JTextField(); JLabel pelaaja2Teksti = new JLabel("Pelaaja 0: "); final JTextField pelaaja2 = new JTextField(); JLabel suoranPituusTeksti = new JLabel("Voittosuoran pituus (2-9): "); final JTextField suoranPituus = new JTextField(); JButton tallennusNappi = new JButton("Tallenna"); tallennusNappi.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent a) { if (!peliKaynnissa) { String pelaajaX = "pelaajaX"; String pelaajaO = "pelaajaO"; if (!pelaaja1.getText().isEmpty()) { pelaajaX = pelaaja1.getText(); } if (!pelaaja2.getText().isEmpty()) { pelaajaO = pelaaja2.getText(); } if (!tilasto.onkoPelaaja(pelaajaX)) { tilasto.lisaaPelaaja(pelaajaX); } if (!tilasto.onkoPelaaja(pelaajaO)) { tilasto.lisaaPelaaja(pelaajaO); } lauta.uudetPelaajat(pelaajaX, pelaajaO); if (!suoranPituus.getText().isEmpty() && suoranPituus.getText().length() == 1 && Character.isDigit(suoranPituus.getText().charAt(0))) { lauta.muutaVoittosuoraa(Integer.parseInt(suoranPituus.getText())); } asetukset.setVisible(false); } else { asetukset.setVisible(false); } } }); panel.add(pelaaja1Teksti); panel.add(pelaaja1); panel.add(pelaaja2Teksti); panel.add(pelaaja2); panel.add(suoranPituusTeksti); panel.add(suoranPituus); panel.add(new JLabel("")); panel.add(tallennusNappi); return panel; }
d7a25aa6-15de-498a-9956-b2abcc8c95d1
7
public double calculateSimilarity(float[] value1, float[] value2) { float sum = 0.0f; float sum1 = 0.0f; float sum2 = 0.0f; for (int i = 0; i < value1.length; i++) { float v1 = value1[i]; float v2 = value2[i]; if ((!Float.isNaN(v1)) && (!Float.isNaN(v2))) { sum += v2 * v1; sum1 += v1 * v1; sum2 += v2 * v2; } } if ((sum1 > 0) && (sum2 > 0)) { double result = sum / (Math.sqrt(sum1) * Math.sqrt(sum2)); // result can be > 1 (or -1) due to rounding errors for equal vectors, but must be between -1 and 1 return Math.min(Math.max(result, -1d), 1d); //return result; } else if (sum1 == 0 && sum2 == 0) { return 1d; } else { return 0d; } }
9d3a6f96-7b7e-4e52-a941-d8b752f1d341
3
void startUp() { try { updateProgress("Unpacking archives...", 25); titleArchive = getArchive(1); small = new RSFont(false, "p11_full", titleArchive); regular = new RSFont(false, "p12_full", titleArchive); bold = new RSFont(false, "b12_full", titleArchive); fancy = new RSFont(true, "q8_full", titleArchive); interfaces = getArchive(3); if (interfaces == null) { System.out.println("Interface archive is null."); return; } media = getArchive(4); if (media == null) { System.out.println("Media archive is null."); return; } mediaArchive = new MediaArchive(media); updateProgress("Unpacking media...", 50); scrollBar1 = new RSImage(media, "scrollbar", 0); scrollBar2 = new RSImage(media, "scrollbar", 1); updateProgress("Unpacking interfaces...", 75); RSFont fonts[] = { small, regular, bold, fancy }; RSInterface.load(interfaces, media, fonts); RSInterface.createBackup(); mediaArchive.updateKnown(); updateProgress("Complete!", 100); } catch(Exception e) { e.printStackTrace(); } }
fdee34f9-303b-4835-a978-62a5634be93d
9
public static RNASecStr loadSecStrCT(String path) { RNASecStr res = null; try { BufferedReader fr = new BufferedReader(new FileReader(path)); String line = fr.readLine(); String seqTmp = ""; Vector<Integer> strTmp = new Vector<Integer>(); while(line!= null) { line = line.trim(); String[] tokens = line.split("\\s+"); if (tokens.length>=6) { try { int bpFrom = (Integer.parseInt(tokens[0]))-1; char base = tokens[1].charAt(tokens[1].length()-1); int bpTo = (Integer.parseInt(tokens[4]))-1; Integer.parseInt(tokens[2]); Integer.parseInt(tokens[3]); Integer.parseInt(tokens[5]); System.err.print("("+bpFrom+","+base+","+bpTo+")"); if (bpFrom!=seqTmp.length()) { System.err.println("Discontinuity detected between nucleotides "+(seqTmp.length())+" and "+(bpFrom+1)+"!"); System.err.println("Filling in missing portions with unpaired unknown 'X' nucleotides ..."); while(bpFrom!=seqTmp.length()) { seqTmp += 'X'; strTmp.add(-1); } } seqTmp += base; strTmp.add(bpTo); } catch(Exception e3) {} } line = fr.readLine(); } if (strTmp.size()!=0) { char[] seq = seqTmp.toCharArray(); int[] str = new int[strTmp.size()]; for(int i=0;i<strTmp.size();i++) {str[i] = strTmp.elementAt(i).intValue();} res = new RNASecStr(seq,str); } } catch(IOException e) { System.err.println("Loading failed!\n File '"+path+"' cannot be read !"); } catch(Exception egen) { System.err.println("Permission denied for security reason !\nConsider using the VARNA panel class in a signed context."); } return res; }
6490f377-668e-43d8-bea9-ceb493fa15a7
2
public boolean deleteAllSongs() { try { if (connection == null) { connection = getConnection(); } String sql = "delete from org.music"; Statement stmt = connection.createStatement(); return stmt.executeUpdate(sql) > -1; } catch (Exception e) { log.log(Level.SEVERE,e.getMessage(),e); } return false; }
f412f8a7-1747-4d2e-9fe5-00585ea49c29
5
public void doPrint() { List<String> nodes = this.graph.getVertexes(); for (String node : nodes) { List<String> edges = this.graph.getIncident(node); for (String edge : edges) { if (this.graph.getSource(edge).equals(node)) { System.out.format("%4s (%3s,%3s) %4s", node, this.graph.getValE(edge, this.attrEdgeCapacity), this.graph.getValE(edge, this.attrEdgeFlow), this.graph.getTarget(edge)); System.out.println(); } } System.out.println("---------------"); } System.out.println("Es wurde über " + ((backtracks == 0) ? "keine": backtracks) + " Rückswärtskante" + ((backtracks == 1)?"":"n") + " gegangen."); System.out.println("#######################"); }
692baf73-8d70-4ace-b2cf-5eb127459a78
7
public String woundTaken(int épDamage, int fpDamage) { if (épDamage != 0) { épDamage -= armor.getSfé(); Ép -= épDamage; Fp -= épDamage * 2; } else { fpDamage -= armor.getSfé(); Fp -= fpDamage; } if (Fp < 0) { Ép -= Fp * -1; Fp = 0; } if (Ép < 0) { Ép = 0; } if (Fp == 0) { conscious = false; } if (Ép < 1) { alive = false; } if (!alive) { return "dead"; } else if (!conscious) { return "unconscious"; } else { return "ready"; } }
0fb44684-6d7d-4543-85c9-411b7cbc70e1
9
public Object[][] getMultipleRows(String testcase) { String testSheetName = getTestSheetName(testcase); if(testSheetName.equalsIgnoreCase("TestSheet Not Found")){ return null; } HSSFSheet testSheet = workBook.getSheet(testSheetName); String cellData; int totalRows = testSheet.getPhysicalNumberOfRows(); // Total rows in sheet. int totalCols = testSheet.getRow(0).getLastCellNum(); int startIndex = 0; int endIndex = 0; boolean foundStartIndex = false; for(int row=1; row<totalRows; row++){ if(foundStartIndex == false && testcase.equalsIgnoreCase(testSheet.getRow(row).getCell(0).toString())) { startIndex = row; foundStartIndex = true; } if(foundStartIndex == true && !testcase.equalsIgnoreCase(testSheet.getRow(row).getCell(0).toString())){ endIndex = row; break; } endIndex = totalRows; //if bottom reached. } totalRows = endIndex-startIndex; // total rows contains same scenario String[][] testData = new String[totalRows][totalCols - 1]; int index = 0 ; for(int row=startIndex; row<endIndex ; row++) { for (int col = 1; col < totalCols; col++) { if (testSheet.getRow(row).getCell(col) == null) { cellData = ""; } else { cellData = testSheet.getRow(row).getCell(col).toString(); } testData[index][col - 1] = cellData; } index++; } return testData; }
7565917c-6683-4276-adff-07a1c38f6604
9
@Override public boolean getNGramsFromService(String context, int maxResults) throws NGramException { try { NgramServiceFactory factory = NgramServiceFactory .newInstance(NGramStore.Key); if (factory == null) { // NGramException if the service fails to connect throw new NGramException( "ERROR: fail to connect to the service"); } if ((context == null) || (context.isEmpty())) { throw new NGramException("ERROR: context is null or empty!"); } GenerationService service = factory.newGenerationService(); if (service == null) { // NGramException if the service fails to connect throw new NGramException( "ERROR: fail to connect to the service"); } TokenSet tokenSet = service.generate(NGramStore.Key, "bing-body/2013-12/5", context, maxResults, null); if ((tokenSet == null) || (tokenSet.getWords() == null) || (tokenSet.getWords().isEmpty())) { HAVERESULT.add(false); return false; } // get the predictions List<String> predictionsList = tokenSet.getWords(); // get the probabilities List<Double> probabilitiesList_pre = tokenSet.getProbabilities(); // Calculate the real probabilities List<Double> probabilitiesList = new ArrayList<Double>(); for (double p : probabilitiesList_pre) { // change the formation of the probabilities probabilitiesList.add(Math.pow(10.0, p)); } String[] predictions = (String[]) predictionsList .toArray(new String[0]); Double[] probabilities = (Double[]) probabilitiesList .toArray(new Double[0]); NGramNode ngramContainer = new NGramNode(context, predictions, probabilities); this.addNGram(ngramContainer); return true; } catch (Exception e) { throw new NGramException( "ERROR: the NGramContainer cannot be created"); } }
8c0aeb82-05de-492a-a523-d1cc7b65dd88
1
public void setUserlistImageOverlay_Height(int height) { if (height <= 0) { this.userlistImgOverlay_Height = UISizeInits.USERLIST_IMAGEOVERLAY.getHeight(); } else { this.userlistImgOverlay_Height = height; } somethingChanged(); }
78fbd9af-bd5f-481c-8851-f8336f4b33df
0
public void setCatched() { catched = true; }
d2c1626c-90a6-400f-beea-e40d4ff8faa2
1
public void drawHighlight(Graphics2D g) { if (needsRefresh) refreshCurve(); Graphics2D g2 = (Graphics2D) g.create(); g2.setStroke(new java.awt.BasicStroke(6.0f)); g2.setColor(HIGHLIGHT_COLOR); g2.draw(curve); g2.transform(affineToText); g2.fill(bounds); g2.dispose(); }
d0fda837-df1c-4e0f-8d58-6cb7077c3a69
8
public byte mixWt(String fileName) throws IOException { initialize(fileName); FileOutputStream fos = null; DataOutputStream dos = null; try{ // create file output stream fos = new FileOutputStream("mixWt_bin"); // create data output stream dos = new DataOutputStream(fos); String[] params = list.get(0).split("\\s"); if(!(params[0].equals("mixw"))){ System.out.println("Incorrect mixture weight file given as argument"); System.exit(0); } int c = (int)(Float.parseFloat(params[3])/8); //writing the senones dos.writeFloat(Float.parseFloat(params[1])); //writing the gaussians dos.writeFloat(Float.parseFloat(params[3])); for (int i = 1; i < list.size(); i++) { if(!(i % (c+2) == 1 || i % (c+2) == 2) ) { String str = list.get(i).replaceAll("\\s+$",""); String[] result = str.split("\\s"); for (int j = 0; j < result.length; j++) dos.writeFloat(Float.parseFloat(result[j])); } } }catch(Exception e){ // if any I/O error occurs e.printStackTrace(); return 0; }finally{ if(dos != null) dos.close(); if(fos!=null) fos.close(); } return 1; }
b6a8f390-cd34-4d7b-9c3e-abc9e567d140
0
public void setTitle(String title) { this.title = title; }
88f42acf-c99f-44cf-98fe-0060b2bd467c
9
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(!(affected instanceof MOB)) return true; final MOB mob=(MOB)affected; if((msg.amITarget(mob)) &&(!mob.amDead()) &&((mob.fetchAbility(ID())==null)||proficiencyCheck(mob,0,false))) { boolean yep=(msg.targetMinor()==CMMsg.TYP_MIND); if((!yep) &&(msg.tool() instanceof Ability)) { final Ability A=(Ability)msg.tool(); if(((A.classificationCode()&Ability.ALL_DOMAINS)==Ability.DOMAIN_ILLUSION) ||((A.classificationCode()&Ability.ALL_DOMAINS)==Ability.DOMAIN_ENCHANTMENT)) yep=true; } return !yep; } return true; }
9c8032e2-6ab0-47fb-89e5-fbc115d27a10
6
public Component getTableCellRendererComponent (JTable table, Object value, boolean selected, boolean focused, int row, int column){ super.getTableCellRendererComponent(table, value, selected, focused, row, column); if (column == 0 || column == 6){ //Week-end setBackground(new Color(255, 220, 220)); } else{ //Week setBackground(new Color(255, 255, 255)); } if (value != null){ if (Integer.parseInt(value.toString()) == realDay && currentMonth == realMonth && currentYear == realYear){ //Today setBackground(new Color(220, 220, 255)); } } setBorder(null); setForeground(Color.black); return this; }
0a0f8017-67b1-40b6-8bb3-0603675c7737
8
public void poistaPieni() { if (tyhja()) { return; } boolean jarjVaihtoOk = false; BinomiNode prev = null; BinomiNode prevMin = null; BinomiNode current = root; BinomiNode currentMin = root; BinomiKeko keko; while (current != null) { if (current.arvo < currentMin.arvo) { currentMin = current; prevMin = prev; } prev = current; current = current.sisar; } if (prevMin == null) { root = root.sisar; } else { prevMin.sisar = currentMin.sisar; } if (currentMin.lapsi != null) { prev = null; current = currentMin.lapsi; BinomiNode next = currentMin.lapsi.sisar; while (next != null) { current.sisar = prev; prev = current; current = next; next = current.sisar; } current.sisar = prev; jarjVaihtoOk = true; } if (jarjVaihtoOk) { keko = new BinomiKeko(1, current); } else { keko = new BinomiKeko(0, null); } current = keko.root; while (current != null) { current.parent = null; current = current.sisar; } keko = union(this, keko); root = keko.root; keonKoko--; }
b3ae9554-04a2-4057-b182-394ee0ffc33f
6
public static void main(String[] args) { FileInputStream fis=null; ObjectInputStream ois = null; try { fis = new FileInputStream("MyBinaryFile.g"); ois =new ObjectInputStream(fis); int x = ois.readInt(); double y = ois.readDouble(); Circle obj = (Circle)ois.readObject(); int radius=obj.getRadius(); System.out.println("Integer: "+ x +" Double:"+y+" Radius: "+radius); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if( fis != null) fis.close(); // is this a good code. if(ois != null) ois.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); // welcome to fate. } } }
83e4eecd-8822-43d3-af09-94fa5ac2ecb9
2
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: try { String nome = jTextField1.getText(); long tel = Long.parseLong(jTextField2.getText()); String email = jTextField3.getText(); Fachada f = Sistema.getInstance(); if (f.cadastrarFornecedor(nome, email, tel)) { JOptionPane.showMessageDialog(null, "Cadastro efetuado com sucesso!"); dispose(); } else { JOptionPane.showMessageDialog(null, "Cadastro não realizado!"); } } catch (NumberFormatException | HeadlessException e) { JOptionPane.showMessageDialog(null, "O campo telefone precisa ser número!"); } }//GEN-LAST:event_jButton1ActionPerformed