text
stringlengths
14
410k
label
int32
0
9
public Object opt(String key) { return key == null ? null : this.map.get(key); }
1
public static void renderSpecialCases(Shape s, Texture tex, Graphics2D g) { if (s instanceof Rectangle) { Rectangle r = (Rectangle) s; if (tex.getStyle() == TextureFactory.INSULATION) { g.setColor(new Color(tex.getForeground())); int m = 20; // default number of repeats int minLength = 20; Arc2D...
7
public boolean isLesser(int i, int j) { //E[] arrEs = new E[10]; assert i > 0 && j > 0; this.arrayAccess += 2; this.comparisions++; if (this.array[i - 1].compareTo(this.array[j - 1]) < 0) { return true; } else return false; }
2
public int getSavedFunctionAddress() { return savedFunctionAddress; }
0
private int readFully(byte[] b, int offs, int len) throws BitstreamException { int nRead = 0; try { while (len > 0) { int bytesread = source.read(b, offs, len); if (bytesread == -1) { while (len-->0) { b[offs++] = 0; } break; //throw newBitstreamException(UNEX...
4
public void onEvent(Event event) { if (event instanceof ScannedRobotEvent) { onScannedRobot((ScannedRobotEvent) event); } else if (event instanceof RobotDeathEvent) { onRobotDeath((RobotDeathEvent) event); } }
2
public static void setOpenOrRead(boolean b) { openOrRead = b; }
0
public boolean hasDatumName(String datumName){ for (TileObjectDisplayDatum datum : displayData){ if (datum.getName().equals(datumName)){ return true; } } return false; }
2
public void run() { try { userInfo = new UserInfo(); Packet pc[]; userInfo.sendMessage("Send Info"); userInfo.setUser("Mahi"); oos.writeObject(userInfo); oos.flush(); System.out.println("Connection established"); w...
4
public String toString(){ StringBuffer sb = new StringBuffer(); switch(type){ case TYPE_VALUE: sb.append("VALUE(").append(value).append(")"); break; case TYPE_LEFT_BRACE: sb.append("LEFT BRACE({)"); break; case TYPE_RIGHT_BRACE: sb.append("RIGHT BRACE(})"); break; case TYPE_LEFT_SQUARE: ...
8
public void loadPlanetImages(){ planetImages = new ArrayList(); int i = 0; while(true){ String name = "planets/p_" + i + ".png"; File file = new File("images/" + name); if(!file.exists()){ break; } //System.out.println(i + " : " + file); planetImages.add(getSmal...
2
public Flyweight factory(String data) { if (flies.containsKey(data)) {// files.containsKey是如果此映射包含对于指定 // 键的映射关系,则返回 true return flies.get(data);// 返回指定键所映射的值;如果对 // 于该键来说,此映射不包含任何映射关系,则返回 null } else { Flyweight fly = new ConcreteFlyweight(data); flies.put(data, fly); return fly; } }
1
public static void main(String[] args) { Graph G = null; try { G = new Graph(new In(args[0])); } catch (Exception e) { System.out.println(e); System.exit(1); } int s = Integer.parseInt(args[1]); IPaths paths = new Paths(G, s); for (int v = 0; v < G.V(); v++) { System.out.print(s ...
5
protected void handleControlPropertyChanged(final String PROPERTY) { if ("RESIZE".equals(PROPERTY)) { resize(); } else if ("SELECTED".equals(PROPERTY)) { getSkinnable().fireSelectEvent(getSkinnable().isSelected() ? new TButton.SelectEvent(getSkinnable(), getSkinnable(), TButton.S...
6
@Override public void close() { if (isNotReady()) { return; } for (Client c : clients) { c.close(); } try { onClose(); } catch (Exception e) { // ignore } ...
3
public static void main(String[] args) { long start = System.nanoTime(); int max = 0; for (int i = 100; i < 1000; i++) { for (int j = 100; j < 1000; j++) { int current = i * j; if (isPalindromic(current) && current > max) { max = current; } } } System.out.println(max); System.out.prin...
4
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://down...
6
static boolean checkIfMove(String cmd) { for (int i = 2; i < 10; i++) { for (int j = 2; j < 10; j++) { for (int k = 2; k < 10; k++) { for (int l = 2; l < 10; l++) { if (cmd.indexOf(Board.boardOfMoves[i][j] + Board.boardOfMoves[k][l]) != -1)...
5
public static void Seed_cycle(Network net, int stop) { int i, j, k, n; double h_err, delta, e; double mse = 0.0F; double err[] = new double[Config.NUM_OUTPUTS]; Neuron h; for(i=0; i<stop; ++i) { System.out.println("Cycle " + i + ", MSE " + mse/600); mse = 0.0; for(j=0; j<Co...
9
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); while ((line = in.readLine()) != null && line.length() != 0) { int[] ab = readInts(line); int a = ab[0], b = ab[1...
9
public int getPage() { return page; }
0
public void onMessage( Message msg ) { //deal with message from server try { msg.acknowledge(); // acknowledge to know that it is already received String received = ((TextMessage)msg).getText(); if( registerInProgress ) { registerInProgress = false; System.out.pr...
5
public void setData(GameData gd) { // the towers for (Entry<int[], Tower> entry : gd.getTowers().entrySet()) { int[] pos = entry.getKey(); Tower tower = entry.getValue(); Tile t = map.get(pos[0] * size + pos[1]); Field f = (Field) t; tower.setField(f); tower.addListener(listener); towers.add...
5
public static List<Couleur> selectCouleur(String libelle) throws SQLException { String query; List<Couleur> couleurs = new ArrayList<Couleur>(); Couleur couleur; ResultSet resultat; query = "SELECT * from COULEUR"; PreparedStatement pStatement = Connectio...
1
public boolean updatePassword(Token t, User u, Map<String,String> parameters) { if (!parameters.containsKey("current_password") || !parameters.containsKey("password")) { GoCoin.log(new Exception("Invalid parameters for resetPasswordWithToken!")); return false; } //TODO: pull out map keys as c...
3
private void read(SocketSessionImpl session) { ByteBuffer buf = ByteBuffer.allocate(session.getReadBufferSize()); SocketChannel ch = session.getChannel(); try { int readBytes = 0; int ret; try { while ((ret = ch.read(buf.buf())) > 0) { ...
8
public boolean searchMatrix(int[][] matrix, int target) { int len = matrix.length; int i; for(i=0;i<len;i++) { if(matrix[i][0] == target) { return true; }else if(matrix[i][0] > target) { break; } } if(i==0) { return false; } if(matrix[i-1][matrix[...
7
public void setStatustextZoomedFontstyle(Fontstyle fontstyle) { if (fontstyle == null) { this.statustextZoomedFontStyle = UIFontInits.STATUSZOOMED.getStyle(); } else { this.statustextZoomedFontStyle = fontstyle; } somethingChanged(); }
1
public void actionPerformed(ActionEvent event) { Object target = event.getSource(); if (target instanceof JMenuItem) { JMenuItem item = (JMenuItem)target; int[] indexes = fOnlineList.getSelectedIndexes(); if (indexes == null |...
8
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((col == null) ? 0 : col.hashCode()); result = prime * result + ((row == null) ? 0 : row.hashCode()); return result; }
2
@Override public boolean equals(Object o) { if(o == null) return false; if(!(o instanceof Stueckliste)) return false; Stueckliste stl = (Stueckliste)o; if(!stl.getBauteil().equals(this.getBauteil())) return false; if(!stl.getGueltigAb()...
8
public void setLastName(String lastName) { this.lastName = lastName; }
0
public void transferHeatToParticles(List list, double amount) { if (list == null || list.isEmpty()) return; double k0 = getKEOfParticles(list); if (k0 < ZERO) assignTemperature(list, 1); Atom a = null; Object o = null; for (Iterator it = list.iterator(); it.hasNext();) { o = it.next(); if (o ins...
7
@Override public String toString() { return "Value: " + value + " Unit: " + unit; }
0
public void TakeCape(String god, int reqSkillNum, int lvlReq, int XPSkillNum, int XPamount, int item, int itemAmount, int delay, int emote) { if(theifTimer == 0) { if(playerLevel[reqSkillNum] >= lvlReq) { setAnimation(emote); sendMessage("You bow down to "+god); sendMessage("You recieve the cape of "+god+"."...
3
@Override public void run() { if(TreasureHunt.getInstance().started) TreasureManager.getInstance().startTreasureHunt(); else TreasureHunt.getInstance().started = true; }
1
private GameStatus MapSpielZustand(Spielzustaende spielzustaende) { switch (spielzustaende) { case Armeen_hinzufuegen: return GameStatus.PlacingUnits; case Angriff: return GameStatus.Attack; case Verschieben: return GameStatus.M...
4
public void testPropertySetWeekOfWeekyear() { DateTime test = new DateTime(2004, 6, 7, 0, 0, 0, 0); DateTime copy = test.weekOfWeekyear().setCopy(4); assertEquals("2004-06-07T00:00:00.000+01:00", test.toString()); assertEquals("2004-01-19T00:00:00.000Z", copy.toString()); ...
2
public void allow() { try { if (process != null) process.exitValue(); process = Runtime.getRuntime().exec(BROWSER_BINARY); } catch (IllegalThreadStateException e) { /* process is still running */ } catch (IOException e) { e.printStackTrace(); } }
3
private boolean isKColorable(int k) { for(HashSet<Value> edges : adjacencyList.values()) { if(edges.size() >= k) { return false; } } return true; }
2
public void setReadings (List<Reading> readings) { XModel model = null; try { model = As.XModel (this.textDocument); model.lockControllers(); this.paragraphCursor.gotoStartOfParagraph (false); this.paragraphCursor.gotoEndOfParagraph (true); this.viewCursor.gotoRange (this.paragraphCursor, false...
9
public void printWall(){ for (Message m : this.wall) { System.out.println(m); } }
1
private Vector extractViewCommentFromHTML(String scriptName) { if (lastHTMLReply == null) { if (debugLevel>0) System.err.println("Thread "+this.getName()+": There is no previous HTML reply<br>"); return null; } int[] pos = randomComputeLastIndex(scriptName, true); if (pos == n...
8
public int find(int x) { checkValidElement(x); int root = x; while (root >= 0 && up[root] >= 0) // find element root = up[root]; if (x != root) { // if x not a root, do path compression int oldParent = up[x]; // prime loop while (oldParent != root) { up[x] = root; // point directly at your root;...
4
public String toString() { String ret; switch (ttype) { case TT_EOF: ret = "EOF"; break; case TT_EOL: ret = "EOL"; break; case TT_WORD: ret = sval; break; case TT_NUMBER: ret = "n=" + nval; break; case TT_NOTHING: ...
7
public boolean isMesmoDia(Calendar dia){// nao vai funcionar com compareTo nem equls por causa das horas if(this.data.get(Calendar.YEAR) == dia.get(Calendar.YEAR) ){ if(this.data.get(Calendar.MONTH) == dia.get(Calendar.MONTH) ){ if(this.data.get(Calendar.DAY_OF_MONTH) == dia.get(Calendar.DAY_OF_MON...
3
*/ @Override public LegendItemCollection getLegendItems() { if (this.fixedLegendItems != null) { return this.fixedLegendItems; } LegendItemCollection result = new LegendItemCollection(); int count = this.datasets.size(); for (int datasetIndex = 0; datasetIndex...
9
public static double sqrt(double a) throws IllegalArgumentException { if(a == 0) { return 0; } if (a < 0) { throw new IllegalArgumentException("Can not sqrt a negative number!"); } // write a as m * 10^2n where 1 < m < 100 // then sqrt(a) is around 1.8 * 10^n or 5.6 * 10^n depending on ...
9
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://down...
6
public static byte[] toByteArray(Serializable object) { ByteArrayOutputStream bOS = null; ObjectOutput oOS = null; byte[] bytes = null; try { // Write object to a byte[] using ByteArrayOutputStream and ObjectOutputStream bOS = new ByteArrayOutputStream (); oOS = new ObjectOutputStream (bOS); oOS...
5
public static String readFileUtf8(String path) throws IOException { return readFile(path, Charset.forName("UTF8")); }
0
public static TreePath getNextMatch(JTree tree, String prefix) { int max = tree.getRowCount(); if (prefix == null) { throw new IllegalArgumentException(); } // start search from the next/previous element froom the selected element int row = 0; do { TreePath path = tree.getPathForRow(row); ...
3
Type getType() { return type; }
0
public static ArrayList<String> createTagPool(Map imagesTags) { if (PRINT == 1) System.out.println("Creating tagpool...\n"); ArrayList<String> tagpool = new ArrayList<String>(); /* Iterate through the map */ Iterator itMap = imagesTags.entrySet().iterator(); while...
5
public Object saveState(FacesContext context) { if (context == null) { throw new NullPointerException(); } if (attachedObjects == null) { return null; } if (initialState) { Object[] attachedObjects = new Object[this.attachedObjects.size()]; ...
9
public static void main(String[] args) throws IOException, InterruptedException { Controller appli = null; //System.out.println(System.getProperty("os.version")); System.exit(0); try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { ...
4
private Path nearestPath(String s){ List<Path> potential = new ArrayList<Path>(); List<Path> next = new ArrayList<Path>(); TrieNode node = getNode(s); //That node doesn't exist. if(node == null) return null; Path top = new Path(node); potential.add(top); while(!potential.isEmpty()){ fo...
5
public void commit(Transaction t) { for(int i: t.getWriteVars()) { if(hasVariable(i)) { variablesSnapshot.put(i, variables.get(i)); } } accessTransactionLog.remove(t); }
2
@Override public Types.MOVEMENT activeMovement(VGDLSprite sprite, Direction action, double speed) { if(speed == 0) { if(sprite.speed == 0) speed = 1; else speed = sprite.speed; } if(speed != 0 && action != null && !(action....
8
public static int maxDepth(TreeNode root) { if(root==null) return 0; Stack<TreeNode> stack = new Stack<TreeNode>(); HashMap<TreeNode, Integer> depthTable = new HashMap<TreeNode, Integer>(); stack.add(root); depthTable.put(root,1); int maxDepth = 1; while(!stack.isEmpty()) { TreeNode node = stack.pop();...
9
public void allocatePartPERanges(int partId, PERangeList selected, double startTime, double finishTime) { if(partId >= partitions.length || partId < 0) { throw new IndexOutOfBoundsException("Partition " + partId + " does not exist."); } Iterator<ProfileEntry> it = avail.itValuesFromPrec(startTime...
7
public void incrementFood() { this.food++; }
0
public void removeAdmin(String name) { String delete = "DELETE FROM ADMIN WHERE NAME=?"; try { PreparedStatement ps = conn.prepareStatement(delete); ps.setString(1, name); ps.executeUpdate(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } }
1
public void previousQuestion() { if(i == 0) { i = QuestionCount -1; } else { // Current Question Id incremented by 1 i--; } // Display question in form this.setUp(); }
1
public INISection getSection(String name){ for(INISection section : sections){ if(section.getName().equals(name)){ return section; } } Debug.error("Section '" + name + "' does not exist!"); return null; }
2
@Override public void run() { if (bot.hasMessage()) { message = bot.getMessage(); channel = bot.getChannel(); } if (this.message.startsWith("~kick")) { Vote.voteYes = 0; Vote.voteNo = 0; Vote.voters.clear(); ...
5
public void renderPlayer(int xp, int yp, Sprite sprite) { for (int y = 0; y < 32; y++) { int ya = yp + y; for (int x = 0; x < 32; x++) { int xa = xp + x; int color = sprite.pixels[x + y * 32]; if (color != 0xFFFF00FF) { ...
3
public static final long pow(long x, long n) throws Exception { if(n < 0) return div (1, pow (x, (0 - n))); long r = 1; while (n != 0) { if ((n & 1L) != 0) r = mul(r, x); n >>= 1; x = mul(x, x); } return r; }
3
public Boolean book(User currentUser, Integer borrowableId, Integer quantity, Integer borrowerId, Date start, Date end, String reason) { // Date verifications // Time before the beggining of the booking (reservation) DateInterval reservationStartInterval = new DateInterv...
5
public double[][] getArrayCopy(){ double[][] c = new double[this.numberOfRows][this.numberOfColumns]; for(int i=0; i<numberOfRows; i++){ for(int j=0; j<numberOfColumns; j++){ c[i][j]=this.matrix[i][j]; } } return c; }
2
public synchronized void actualiza(long tiempoTranscurrido) { if (cuadros.size() > 1) { tiempoDeAnimacion += tiempoTranscurrido; if (tiempoDeAnimacion >= duracionTotal) { tiempoDeAnimacion = tiempoDeAnimacion % duracionTotal; indiceCuadroActual = 0; ...
3
public String rechercher() throws IOException { InputStreamReader isr=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(isr); String inputLine; System.out.println(recherche()); inputLine = br.readLine(); String[] part = inputLine.split(" "); switch(Integer.decode(part[0])) { ...
8
private Point yBinarySearch(Point bottom, Point top) { int x = bottom.x; // the same for right and left Point mid; while (true) { if (abs(bottom.y - top.y) == 1) { if (abs(bottom.dF) <= abs(top.dF)) { return bottom; } else { ...
8
public static boolean isdni(String dni){ boolean aux=false; if(dni.length()!=9){//tiene que tener 9 caracteres aux=false; }else if((dni.charAt(dni.length()-1))>90 ||(dni.charAt(dni.length()-1))<65){//mirar si el ultimo es letra aux=false; }else{//mirar que los 8 primeros sean numeros int i=0; do...
6
private boolean colorExists(P p, int x, int y) { for (int i = 0; i < this.tabSizeX; i++) { for (int j = 0; j < this.tabSizeY; j++) { if (x==i && y==j && x>=0 && y>=0) continue; // nie sprawdzam sama siebie bo sie zapetle ;) if (this.P[i][j].colorMatch(p)) return true; }//j }//i return false; }
7
@Override public Description select(int id) { Description description = null; ResultSet result; try { result = this .connect .createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_...
4
public long computeHashValueForPattern(String pattern, int patternLength) { long hash = 0; for(int index = 0; index < patternLength; index++) { hash = (hash * alphabet + pattern.charAt(index)) % primeNumber; comparisons++; } return hash; }
1
private void generateCampo() { window.getContentPane().removeAll(); // rimuovo tutti gli oggetti dentro al jpanel quindi bottoni e tutto boolean b = false; // necessario per stampare il colore del background dei bottoni che fa da sfondo scacchiera for (int i = 0; i < 8; i++) { for ...
7
public YamlPermissionGroup(String n, ConfigurationSection config) { super(n, config); }
0
@Override public int attack(double agility, double luck) { if(random.nextInt(100) < luck) { System.out.println("I just stabbed the enemy in the back!"); return random.nextInt((int) agility) * 4; } return 0; }
1
private void addAccount() { String name = nameField.getText().trim(); try { Account account = new Account(name.trim()); account.setType((AccountType) type.getSelectedItem()); String text = defaultAmountField.getText(); if (text != null && !text.trim().equa...
5
public boolean dig(Tile t, Dude dude) { if (dude.isAt(t.getX() - 1, t.getY()) || dude.isAt(t.getX() + 1, t.getY()) || dude.isAt(t.getX(), t.getY() + 1) || dude.isAt(t.getX() + 1, t.getY() - 1)) { // finish building tile if (t.getStructure() != null) { removeStructure(t.getStructure()); } ...
6
@Override public List<Loja> listAll() { Connection conn = null; PreparedStatement pstm = null; ResultSet rs = null; List<Loja> lojas = new ArrayList<>(); try{ conn = ConnectionFactory.getConnection(); pstm = conn.prepareStatement(LIST); rs ...
3
public List<Edge> getEdges() { if (this.allEdges.isEmpty()) { return Collections.emptyList(); } else { return this.allEdges; } }
1
public static void main(String args[]){ Scanner lea = new Scanner(System.in); FileWriter fw = null; char resp = 's'; do{ System.out.println("Ingrese dir de Arch Texto: "); String path = lea.next(); System.out.println("Lo quiere append?...
7
@EventHandler public void CreeperMiningFatigue(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.getCreeperConfig().getDouble("Creepe...
6
@Override protected EntityManager getEntityManager() { return em; }
0
public void tickDownUnitStatuses(int currentPlayerIndex) { for (Unit unit : units) { unit.tickDownStatuses(currentPlayerIndex); } }
1
public boolean onCommand(Player player, String[] args) { File fichier_language = new File(OneInTheChamber.instance.getDataFolder() + File.separator + "Language.yml"); FileConfiguration Language = YamlConfiguration.loadConfiguration(fichier_language); if(player.hasPermission(getPermission())){ if(args.length...
4
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + aantalDeelnames; result = prime * result + id; result = prime * result + ((leerjaar == null) ? 0 : leerjaar.hashCode()); result = prime * result + ((leraar == null) ? 0 : leraar.hashCode()); result = pri...
5
public final void convertStringToCalendar(final String dateString) throws NullPointerException, EmptyException{ if(dateString == null || dateString.isEmpty()){ throw new RuntimeException("String date not be null"); } if(dateString.isEmpty()){ throw new EmptyException("Str...
4
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!plugin.hasPerm(sender, "mute", true)) { sender.sendMessage(ChatColor.YELLOW + "You do not have permission to use /" + label); return true; } if (args.length == 0) return false; if (plugin.playe...
4
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://down...
6
static public ArrayList<Cuenta> getAll(){ return cuentas; }
0
public JFreeChart MakeChart() { DefaultPieDataset chartDataSet = new DefaultPieDataset(); Object[] column1Data = super.getDataset().GetColumnData(super.getAttribute1()); Object[] column2Data = super.getDataset().GetColumnData(super.getAttribute2()); boolean addDataset = true; ...
9
public static double readHashTopValue(HashMap<String, Integer> scores, int k) { List list = new LinkedList(scores.entrySet()); int count = 0; int value = 0; double res = 0; for (Iterator it = list.iterator(); count < k && it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); value = (Integer) entry....
2
public void makeDeclaration(Set done) { for (int i = 0; i < subExpressions.length; i++) subExpressions[i].makeDeclaration(done); }
1
public static void main(String[] args) { Ex4 x = new Ex4(); }
0
void processItemResponseMessage(Event event) { String itemName = (String)_itemHandles.get(event.getHandle()); OMMItemEvent ie = (OMMItemEvent)event; OMMMsg ommMsg = ie.getMsg(); short ommMsgType = ommMsg.getMsgType(); String ommMsgTypeStr = OMMMsg.MsgType.toString((byte)ommM...
7
public double getAggregate( String dsName, String consolFun ) throws RrdException { Source src = getSource( dsName ); if( consolFun.equalsIgnoreCase("MAX") ) return src.getAggregate( Source.AGG_MAXIMUM ); else if ( consolFun.equalsIgnoreCase("MIN") ) return src.getAggregate( Source.AGG_MINIMUM ); else i...
6