method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
f18e2601-f0a4-4966-b10e-15a942c46043
2
public void setMinCount(int newMin) { if (headCount < newMin) { GlobalOptions.err .println("WARNING: something got wrong with scoped class " + clazzAnalyzer.getClazz() + ": " + newMin + "," + headCount); new Throwable().printStackTrace(GlobalOptions.err); headMinCount = headCount; } else if (newMin > headMinCount) headMinCount = newMin; }
0f40d2a4-b249-4338-8e18-14fdf71885f5
6
@SuppressWarnings("unchecked") @Override protected boolean canRun(ClassNode node) { if (node.superName.isEmpty()) { return false; } int string = 0, model = 0; ListIterator<FieldNode> fnIt = node.fields.listIterator(); while (fnIt.hasNext()) { FieldNode fn = fnIt.next(); if ((fn.access & Opcodes.ACC_STATIC) == 0) { if (fn.desc.equals("Ljava/lang/String;")) { string++; } if (fn.desc.equals("Ldk;")) { model++; } } } return string == 1 && model == 1; }
aa5dfc2d-da9b-481a-99fe-626c8d1764e9
4
private void redTeamWin() { for (String n : this.getPlayers()) { if (this.getBlueTeam().getPlayers().contains(n)) { PlayerStats s = plugin.getPlayerStats().get(n); if (s != null) { s.setLosses(s.getLosses() + 1); } else { s = new PlayerStats(n, 0, 1, 0, 0); } plugin.getPlayerStats().put(n, s); } else { PlayerStats s = plugin.getPlayerStats().get(n); if (s != null) { s.setWins(s.getWins() + 1); } else { s = new PlayerStats(n, 1, 0, 0, 0); } plugin.getPlayerStats().put(n, s); } } }
29a8b545-b85e-4db6-b55c-ff85015a2df2
8
static String getUnitText(double v, String u) { double va = Math.abs(v); if (va < 1e-14) return "0 " + u; if (va < 1e-9) return showFormat.format(v*1e12) + " p" + u; if (va < 1e-6) return showFormat.format(v*1e9) + " n" + u; if (va < 1e-3) return showFormat.format(v*1e6) + " " + CirSim.muString + u; if (va < 1) return showFormat.format(v*1e3) + " m" + u; if (va < 1e3) return showFormat.format(v) + " " + u; if (va < 1e6) return showFormat.format(v*1e-3) + " k" + u; if (va < 1e9) return showFormat.format(v*1e-6) + " M" + u; return showFormat.format(v*1e-9) + " G" + u; }
6d37764f-afe5-4fdd-b698-9b1f315d8451
5
public static void main(String[] args) { String name = AdjustFileNotice.class.getSimpleName(); Attributes attributes = new Attributes(); attributes.putValue(BundleInfo.BUNDLE_NAME, name); attributes.putValue(BundleInfo.BUNDLE_VERSION, VERSION); attributes.putValue(BundleInfo.BUNDLE_COPYRIGHT_OWNER, COPYRIGHT_OWNER); attributes.putValue(BundleInfo.BUNDLE_COPYRIGHT_YEARS, COPYRIGHT_YEARS); attributes.putValue(BundleInfo.BUNDLE_LICENSE, LICENSE); BundleInfo.setDefault(new BundleInfo(attributes, name)); CmdLine cmdline = new CmdLine(); cmdline.addOptions(PATH_OPTION, TEMPLATE_OPTION); cmdline.processArguments(args); if (!cmdline.isOptionUsed(PATH_OPTION)) { System.err.printf(PATH_MUST_BE_SPECIFIED, PATH_OPTION); System.exit(1); } if (!cmdline.getArguments().isEmpty()) { for (String one : cmdline.getArguments()) { System.err.print(UNEXPECTED_ARGUMENT); System.err.println(one); } System.exit(1); } int count = process(new File(cmdline.getOptionArgument(PATH_OPTION)), cmdline.isOptionUsed(TEMPLATE_OPTION) ? loadTemplate(cmdline.getOptionArgument(TEMPLATE_OPTION)) : loadDefaultTemplate()); System.out.printf(RESULT, Integer.valueOf(count), count == 1 ? FILE : FILES); }
234d27f5-fbba-4ddb-8e78-383f1f49d2df
0
public int getS1() { return s1; }
2eac401c-7ec3-4321-9eea-1866cc68f083
1
public static StringBuilder grabVal() throws IOException { String genLine = ""; while((genLine = input.readLine())!= null) { sb.append(genLine); } return sb; }
0e790845-5c04-48d7-96e8-3c37e62b3ada
7
public Instances getDataSet() throws IOException { Instances result; Vector<Double> row; double[] data; int i; int n; if (m_sourceReader == null) throw new IOException("No source has been specified"); if (getRetrieval() == INCREMENTAL) throw new IOException("Cannot mix getting Instances in both incremental and batch modes"); setRetrieval(BATCH); if (m_structure == null) getStructure(); result = new Instances(m_structure, 0); // create instances from buffered data for (i = 0; i < m_Buffer.size(); i++) { row = m_Buffer.get(i); if (row.size() == 0) continue; data = new double[row.size()]; for (n = 0; n < row.size(); n++) data[n] = row.get(n); result.add(new Instance(1.0, data)); } // close the stream try { m_sourceReader.close(); } catch (Exception ex) { // ignored } return result; }
9a451dc0-6e2e-43f1-b522-fd19ae4858c3
6
public static int[] rotateBilinear(int[] pix, float beta, int iw, int ih, int owh) { int[] opix = new int[owh * owh]; double t = beta / 180; float cos_beta = (float) Math.cos(t * Math.PI); float sin_beta = (float) Math.sin(t * Math.PI); for (int i = 0; i < owh-1; i++) { for (int j = 0; j < owh-1; j++) { float u = (j - owh / 2) * cos_beta + (i - owh / 2) * sin_beta; float v = (i - owh / 2) * cos_beta + (j - owh / 2) * sin_beta; u += iw / 2; v += ih / 2; float dy = v; int iy = (int)dy; float d_y = dy-iy; float dx = u; int ix = (int)dx; float d_x = dx -ix; if (ix >= 0 && ix < iw - 1 && iy >= 0 && iy < ih - 1) { int g = (int)( (1-d_x) *(1-d_y) *pix[iy*iw+ix]+ (d_x) *(1-d_y) *pix[iy*iw+ix+1]+ (1-d_x) *(d_y) *pix[(iy+1)*iw+ix]+ (d_x) *(d_y) *pix[(iy+1)*iw+ix+1] ); opix[i*owh+j] = g; } } } return opix; }
e9309f44-ce28-4e15-97a4-f4273589b3a2
5
@Override public void setValueAt(Object obj, int rowIndex, int columnIndex){ if(rowIndex > customers.size()) throw new IllegalArgumentException("Row index greater than customers size"); Customer c = customers.get(rowIndex); switch(columnIndex){ case 1: c.setFirstname((String) obj); break; case 2: c.setLastname((String) obj); break; case 3: c.setBirth((Date) obj); break; case 4: c.setEmail((String) obj); break; default: throw new IllegalArgumentException("column index"); } }
4091a5d1-8e8d-420e-93b7-1b2f809bafa5
0
void increaseRightScore(int score) { setRightScore(getRightScore() + score); }
d3335bcc-540d-49f9-9073-98488f010428
6
public static <T> ObserverMethod<T> create(ForkJoinPool pool, BeanManager bm, AnnotatedType<?> type, AnnotatedMethod<?> method, AnnotatedParameter<?> param) { ObserverMethodHolder<T> objectMethodHolder = new ObserverMethodHolder<>(); objectMethodHolder.pool = pool; objectMethodHolder.beanManager = bm; objectMethodHolder.type = type; objectMethodHolder.method = method; objectMethodHolder.param = param; objectMethodHolder.qualifiers = new HashSet<>(); for (Annotation annotation : param.getAnnotations()) { if (bm.isQualifier(annotation.getClass()) && !annotation.annotationType().equals(Async.class)) { objectMethodHolder.qualifiers.add(annotation); } } return objectMethodHolder; }
9c380d0f-6249-4ef1-9a31-6b5a4498ed16
9
public static boolean isConnected(Board board, BoardNode node1, BoardNode node2){ //vertically aligned if(isVerticallyAligned(node1, node2) && node1.getColor() == node2.getColor() && notBlocked(board, node1, node2)){ return true; } //horizontally aligned if(isHorizontallyAligned(node1, node2) && node1.getColor() == node2.getColor() && notBlocked(board, node1, node2)){ return true; } //diagonally aligned if(isDiagonallyAligned(node1, node2) && node1.getColor() == node2.getColor() && notBlocked(board, node1, node2)){ return true; } return false; }
c1cdabce-4aa2-46d7-a9f3-c1e1e6319087
1
public void addColumn(ColumnAttributes attributes) { if (!data.isEmpty()) { throw new MLException("Cannot add a column to a matrix that contains rows"); } columnAttributes.add(attributes); }
709da5cc-5acd-4a81-b24f-145e211e3fc1
1
public static boolean isFileURL(URL url) { String protocol = url.getProtocol(); return (URL_PROTOCOL_FILE.equals(protocol) || protocol.startsWith(URL_PROTOCOL_VFS)); }
72dd6608-c7c7-48c0-a129-e423d360c478
0
private void initLargerView() { table = new GrammarTable(model); table.getTableHeader().setReorderingAllowed(false); TableColumn lhs = table.getColumnModel().getColumn(0); TableColumn arrows = table.getColumnModel().getColumn(1); TableColumn rhs = table.getColumnModel().getColumn(2); lhs.setHeaderValue("LHS"); table.getTableHeader().resizeAndRepaint(); rhs.setHeaderValue("RHS"); table.getTableHeader().resizeAndRepaint(); table.getColumnModel().getColumn(0).setPreferredWidth(100); //lhs.setMaxWidth(400); //lhs.setMinWidth(100); //arrows.setMaxWidth(30); //arrows.setMinWidth(30); // table.getColumnModel().getColumn(1).setPreferredWidth(30); table.setShowGrid(true); table.setGridColor(Color.lightGray); // Put the table in this pane. setLayout(new BorderLayout()); add(new JScrollPane(table), BorderLayout.CENTER); }
0b9fbbb7-d9c6-48f5-b9d7-68b840f2f8a4
3
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path p = file.getFileName(); if (attrs.isRegularFile() && p != null) { Pattern pat = Pattern.compile(combineRegex(), Pattern.CASE_INSENSITIVE); Matcher m = pat.matcher(p.toString()); while (m.find()) { System.out.println("Movie matched: " + m.group(1)); this.movies.addMovie(file.toFile(), m.group(1), m.group(2)); } } return FileVisitResult.CONTINUE; }
c23154a1-4828-45d7-b568-4ff6a96a0dd9
1
public void setName(String name) { if (StringUtils.isBlank(name)) { throw new IllegalArgumentException("Name shouldn't be NULL or empty."); } this.name = name; }
2c04cf00-1fb0-4b5a-b7bc-be1a94bbeffb
2
public GenericNode getOther(GenericNode node) { // TODO Auto-generated method stub if(node == nodeOne) return nodeTwo; else if(node == nodeTwo) return nodeOne; else return null; }
6ce71db5-f264-42ae-972c-d56ba174997a
6
@EventHandler public void onInventoryClick(InventoryClickEvent event) { if (event.getWhoClicked() instanceof Player) { ClickType clickType = event.getClick(); Player player = (Player) event.getWhoClicked(); String uuid = player.getUniqueId().toString(); ShopIdentifier shop = getShopIdentifier(uuid); if (shop != null) { if (shop.getShopType() == ShopType.BUY) { event.setCancelled(true); SellShop sellShop = Config.getSellShop(shop.getName()); if (sellShop != null) { Value value = Utils.calculateValue(sellShop.getBuyPrices(), event.getCurrentItem()); double amount = value.getValue(); int number; if (clickType == ClickType.SHIFT_LEFT) { number = 64; } else { number = event.getCurrentItem().getAmount(); } if (amount > 0.0) { VaultHandler.withdrawPlayer(player, amount, event.getCurrentItem(), number); } } } } } }
895d985a-1046-48bf-b417-d7df1689ecac
2
public static void setTypeInfoOption(int opt){ switch(opt){ case 1: Db.inputTypeInfo = true; break; case 2: Db.inputTypeInfo = false; break; default: throw new IllegalArgumentException("Option " + opt + " not recognised"); } }
dd6ae606-d8b6-48c5-a352-7d4c4d12154b
9
private void createMidi(Attributes attrs) { midi = new Midi(midiDef); // loop through all attributes, setting appropriate values for (int i = 0; i < attrs.getLength(); i++) { if (attrs.getQName(i).equals("x")) midi.getStartPoint().setX(Integer.valueOf(attrs.getValue(i))); else if (attrs.getQName(i).equals("y")) midi.getStartPoint().setY(Integer.valueOf(attrs.getValue(i))); else if (attrs.getQName(i).equals("starttime")) midi.setStartTime(Integer.valueOf(attrs.getValue(i))); else if (attrs.getQName(i).equals("endtime")) midi.setEndTime(Integer.valueOf(attrs.getValue(i))); else if (attrs.getQName(i).equals("loop")) midi.setLoop(Boolean.valueOf(attrs.getValue(i))); else if (attrs.getQName(i).equals("path")) { // ensure unix type file path String path = attrs.getValue(i).replace('\\', '/'); if (isLocal(path)){ int directoryPathEnd = xmlPath.lastIndexOf('/'); String directoryPath = xmlPath.substring(0, directoryPathEnd + 1); midi.setPath(directoryPath + path); }else { // if remote download file and insert local path try { midi.setPath(RemoteFileRetriever.downloadFile(path)); } catch (MalformedURLException e) { System.out.println("Could not download remote midi" + e.getMessage()); } } } } }
3cd20cf7-595b-4ef7-aa32-bca2486fd53b
7
private void setUp() { File tmpUser = null; File tmpMusic = null; try{ tmpUser = new File("res/users.data"); tmpMusic = new File("res/musics.data"); this.setuserFileOut(new FileOutputStream(tmpUser)); this.setUserFileIn(new FileInputStream(tmpUser)); this.setMusicFileOut(new FileOutputStream(tmpMusic)); this.setMusicFileIn(new FileInputStream(tmpMusic)); } catch (FileNotFoundException e) { if(!tmpUser.exists()) try { tmpUser.createNewFile(); this.setuserFileOut(new FileOutputStream(tmpUser)); this.setUserFileIn(new FileInputStream(tmpUser)); } catch (IOException e1) { e1.printStackTrace(); } else if(!tmpMusic.exists()) try { tmpMusic.createNewFile(); this.setMusicFileOut(new FileOutputStream(tmpMusic)); this.setMusicFileIn(new FileInputStream(tmpMusic)); } catch (IOException e2) { e.printStackTrace(); } } catch (Exception eof) { this.setMusicBuffer(new HashMap<String, MusicPersisted>()); this.setUserBuffer(new HashMap<Email, UserPersisted>()); } try { setUserDbOut(new ObjectOutputStream(userFileOut)); setUserDbIn(new ObjectInputStream(userFileIn)); setMusicDbOut(new ObjectOutputStream(this.getMusicFileOut())); setMusicDbIn(new ObjectInputStream(this.getMusicFileIn())); } catch (IOException e) { e.printStackTrace(); } }
38979133-bf6c-4564-a6c2-b4238ac3d8a8
0
public void setIdDiagnostico(Integer idDiagnostico) { this.idDiagnostico = idDiagnostico; }
935530ae-61db-4f5a-bcc9-d70a425cff31
4
protected Behaviour getNextStep() { final Profile p = actor.base().profiles.profileFor(actor) ; if (p.daysSinceWageEval(actor.world()) < 1) return null ; if (pays instanceof AuditOffice) { final AuditOffice office = (AuditOffice) pays ; if (office.assessRelief(actor, false) <= 0) return null ; } else if (p.paymentDue() <= 0) return null ; final Action getPaid = new Action( actor, pays, this, "actionGetPaid", Action.TALK_LONG, "Getting Paid" ) ; return getPaid ; }
2adeee31-dcd1-47bc-a731-da37462dabd4
1
public String getString(int index) throws JSONException { Object object = this.get(index); if (object instanceof String) { return (String) object; } throw new JSONException("JSONArray[" + index + "] not a string."); }
69b9149b-6a22-45a7-a562-c6ed486da3e2
7
void smbFft(float[] fftBuffer, int fftFrameSize, int sign) /* FFT routine, (C)1996 S.M.Bernsee. Sign = -1 is FFT, 1 is iFFT (inverse) Fills fftBuffer[0...2*fftFrameSize-1] with the Fourier transform of the time domain data in fftBuffer[0...2*fftFrameSize-1]. The FFT array takes and returns the cosine and sine parts in an interleaved manner, ie. fftBuffer[0] = cosPart[0], fftBuffer[1] = sinPart[0], asf. fftFrameSize must be a power of 2. It expects a complex input signal (see footnote 2), ie. when working with 'common' audio signals our input signal has to be passed as {in[0],0.,in[1],0.,in[2],0.,...} asf. In that case, the transform of the frequencies of interest is in fftBuffer[0...fftFrameSize]. */ { float wr, wi, arg, temp; float tr, ti, ur, ui; int i, bitm, j, le, le2, k; int p1, p2, p1r, p1i, p2r, p2i; for (i = 2; i < 2*fftFrameSize-2; i += 2) { for (bitm = 2, j = 0; bitm < 2*fftFrameSize; bitm <<= 1) { if ((i & bitm)!=0) j++; j <<= 1; } if (i < j) { //p1 = fftBuffer+i; p1=i; //p2 = fftBuffer+j; p2=j; //temp = *p1; temp = fftBuffer[p1]; //*(p1++) = *p2; fftBuffer[p1++]=fftBuffer[p2]; //*(p2++) = temp; fftBuffer[p2++] = temp; //temp = *p1; temp = fftBuffer[p1]; //*p1 = *p2; fftBuffer[p1]=fftBuffer[p2]; //*p2 = temp; fftBuffer[p2]=temp; } } for (k = 0, le = 2; k < (long)(Math.log(fftFrameSize)/Math.log(2.)+.5); k++) { le <<= 1; le2 = le>>1; ur = 1.0f; ui = 0.0f; arg = (float) (M_PI / (le2>>1)); wr = (float) Math.cos(arg); wi = (float) (sign*Math.sin(arg)); for (j = 0; j < le2; j += 2) { //p1r = fftBuffer+j; p1r = j; p1i = p1r+1; p2r = p1r+le2; p2i = p2r+1; for (i = j; i < 2*fftFrameSize; i += le) { tr = fftBuffer[p2r] * ur - fftBuffer[p2i] * ui; ti = fftBuffer[p2r] * ui + fftBuffer[p2i] * ur; fftBuffer[p2r] = fftBuffer[p1r] - tr; fftBuffer[p2i] = fftBuffer[p1i] - ti; fftBuffer[p1r] += tr; fftBuffer[p1i] += ti; p1r += le; p1i += le; p2r += le; p2i += le; } tr = ur*wr - ui*wi; ui = ur*wi + ui*wr; ur = tr; } } }
02549ddc-9e45-4654-bb06-570813bb2f4f
1
@Override public void documentRemoved(DocumentRepositoryEvent e) { // local vars int whichOne = isThisOneOfOurs(PropertyContainerUtil.getPropertyAsString(e.getDocument().getDocumentInfo(), DocumentInfo.KEY_PATH)); // if it's one of ours ... if (whichOne != DOCUMENT_NOT_FOUND) { // mark it closed docOpenStates[whichOne] = false; // decrement ourDocsOpen counter ourDocsOpen--; // do other document closing stuff docClosingChores(e.getDocument()); } }
96b13b15-ecfb-4a9e-b7e3-efbba7281f3f
6
@Override public boolean equals(Object obj) { if (null == obj) { return false; } if (this == obj) { return true; } if (obj instanceof PostParameter) { PostParameter that = (PostParameter) obj; if (file != null ? !file.equals(that.file) : that.file != null) return false; return this.name.equals(that.name) && this.value.equals(that.value); } return false; }
756908d0-6043-47ad-b250-a601ae4163a3
5
public void draw(Graphics2D g) { if (!visible) return; Rectangle rect = shape.getBounds(); int bx = (int)rect.getX(); int by = (int)rect.getY(); int bw = (int)rect.getWidth(); int bh = (int)rect.getHeight(); /* if (checked) { g.setColor(Color.GRAY); } g.setPaint( new GradientPaint( bx, by, LIGHT_GRAY, bx, by + bh, GRAY)); g.fill(shape); g.setColor(DARK_GRAY); g.setStroke(STROKE1); g.draw(shape); */ // g.drawRect(bx, by, bw, bh); if (image != null) { int iw = image.getWidth(); int ih = image.getHeight(); g.drawImage(image, bx + bw/2 - iw/2, by + bh/2 - ih/2, null); } else if (icon != null) { g.setColor(enabled ? Color.BLACK : Color.GRAY); g.fill(icon); } if (down) { g.setPaint(new Color(0x99ffffff, true)); g.fill(shape); } }
9ff87389-c58a-48db-9e2f-0e67b9c1d941
3
void workerStop() { if (workerThread == null) return; synchronized(workerLock) { workerCancelled = true; workerStopped = true; workerLock.notifyAll(); } while (workerThread != null) { if (! display.readAndDispatch()) display.sleep(); } }
98f48e0a-484f-4a30-bd7b-1a0aa105a3fa
8
@Override public Object visitUnary(unary_AST node, ScopeElement data) { if (node.primary != null) { if (node.primary instanceof primaryExisting_AST) { primaryExisting_AST p = (primaryExisting_AST) node.primary; p.jjtAccept(this, data); node.typeObj = p.typeObj; } else if (node.primary instanceof newArray_AST){ newArray_AST n = (newArray_AST) node.primary; n.jjtAccept(this, data); node.typeObj = n.typeObj; } } else { Token sign = node.sign; binaryExpression_AST exp = node.expr; exp.jjtAccept(this, data); if (sign.image.equals("!") && (!exp.typeObj.name.equals("boolean"))) { decafError.numErrors++; decafError.error("Expression does not evaluate to a boolean" , new Position(0, 0, 0, 0)); } else if ((sign.image.equals("+")||sign.image.equals("-")) && (!exp.typeObj.name.equals("int"))) { decafError.numErrors++; decafError.error("Expression does not evaluate to a int" , new Position(0, 0, 0, 0)); } node.typeObj = exp.typeObj; } return null; }
506dafed-ca83-4411-9ec5-ef9212bf21fd
7
public static void main(String[] args){ for(int a=1;a<1000;a++){ for(int b=1;b<1000;b++){ for(int c=1;c<1000;c++){ if(a<b && b<c && a+b+c==1000 && Math.pow(a,2) + Math.pow(b,2) == Math.pow(c,2)){ System.out.println("a:" + String.valueOf(a) + " b:" + String.valueOf(b) +" c:"+ String.valueOf(c)); } } } } }
22817b05-4ecf-4494-98ff-259d764d3fc3
2
public void mouseClicked(MouseEvent e) { TableColumnModel colModel = table.getColumnModel(); int columnModelIndex = colModel.getColumnIndexAtX(e.getX()); int modelIndex = colModel.getColumn(columnModelIndex) .getModelIndex(); if (modelIndex < 0) return; TerminalTableRowEntry.sorting = modelIndex; TerminalTableRowEntry.isSortAsc = !TerminalTableRowEntry.isSortAsc; for (int i = 0; i < columnsCount; i++) { TableColumn column = colModel.getColumn(i); column.setHeaderValue(getColumnName(column.getModelIndex())); } table.getTableHeader().repaint(); Collections.sort(current); table.tableChanged(new TableModelEvent(TerminalOutputTable.this)); table.repaint(); }
abb6fd1d-b957-4d65-b8dd-5178090f275d
4
public void setConstructorParameters (Class type, Class[] parameterTypes, String[] parameterNames) { if (type == null) throw new IllegalArgumentException("type cannot be null."); if (parameterTypes == null) throw new IllegalArgumentException("parameterTypes cannot be null."); if (parameterNames == null) throw new IllegalArgumentException("parameterNames cannot be null."); ConstructorParameters parameters = new ConstructorParameters(); try { parameters.constructor = type.getConstructor(parameterTypes); } catch (Exception ex) { throw new IllegalArgumentException("Unable to find constructor: " + type.getName() + "(" + Arrays.toString(parameterTypes) + ")", ex); } parameters.parameterNames = parameterNames; constructorParameters.put(type, parameters); }
ed3cb00d-7f6d-4a31-b066-e52f49dab0ab
5
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Student other = (Student) obj; if (!Objects.equals(this.stuName, other.stuName)){ return false; } if (!Objects.equals(this.stuID, other.stuID)){ return false; } return true; }
208a03be-43e9-46dd-9bd0-c495956283cc
9
private Set floodFill(int x, int y) { Set group = new HashSet(); LinkedList points = new LinkedList(); points.add(new int[] {x, y}); while (!points.isEmpty()) { int[] point = (int[]) points.removeFirst(); group.add(point); for (int dx = -1; dx <= 1; dx++) { inner: for (int dy = -1; dy <= 1; dy++) { if ((dx+dy != 1) && (dx+dy != -1)) continue; if (getPoint(point[0]+dx, point[1]+dy) != getPoint(point[0], point[1])) continue; Iterator it = group.iterator(); while (it.hasNext()) { int[] p = (int[]) it.next(); if ((p[0] == point[0] + dx) && (p[1] == point[1] + dy)) { continue inner; } } points.addLast(new int[] {point[0]+dx, point[1]+dy}); } } } return group; }
a3981742-190b-47a5-9746-864e6f525436
4
public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] A = new int[n]; int[] l = new int[n]; for(int i=0;i<n;i++){ A[i]=in.nextInt(); } l[0]=1; int result = 1; int prev = A[0]; for(int i=1;i<n;i++){ if(A[i]>prev){ l[i]=l[i-1]+1; prev = A[i]; } else { int leng = findDecBack(A, i); l[i]=leng; if(!canDecrease(A, i, leng)) prev=A[i-1]+1; else prev=A[i]; } result = Math.max(result, l[i]); } System.out.println(result); }
e898a59e-74f9-4db3-bf95-8f042500a988
0
public String getServer() { return serverVersion; }
f96c8af5-76b9-4125-8136-dd614d0bad5c
1
private List<IArticle> parseArticles(String[] args) throws IOException { List<IArticle> result = new ArrayList<>(args.length); String[] postIds = Arrays.copyOfRange(args, 1, args.length); for (String postId : postIds) { UrlWrapper url = new UrlWrapper(format(URL_TEMPLATE, postId)); result.add(ArticleFactory.getArticle(url)); } return result; }
e678c7a6-8f53-439f-bb95-379bf2203088
0
private void retrieveAllProducts() { this.allProducts = this.userFacade.retrieveAllProducts(); this.sizeOfProducts = this.allProducts.size(); }
7d5357dd-e8fc-4d20-957d-7e281ccabeff
8
public CompareImagesWindow(String imageFile1, String imageFile2) throws IOException { super("Compare images"); this.imageFile1 = imageFile1; this.imageFile2 = imageFile2; setDefaultCloseOperation(DISPOSE_ON_CLOSE); setLocationRelativeTo(null); addWindowListener(new WindowListener() { @Override public void windowOpened(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowIconified(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowDeiconified(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowDeactivated(WindowEvent e) { // mainWindow.setEnabled(true); } @Override public void windowClosing(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowClosed(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowActivated(WindowEvent e) { // mainWindow.setEnabled(false); } }); setSize(400, 400); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); int w = getSize().width; int h = getSize().height; int x = (dim.width - w) / 2; int y = (dim.height - h) / 2; setLocation(x, y); setResizable(false); // Prima imagine int width = 250; int height = 250; Image image = ImageViewer.buildImage(imageFile1); image = ImageViewer.resize(image, width, height); ImageIcon sizedIcon1 = new ImageIcon(image); // A doua imagine width = 250; height = 250; image = ImageViewer.buildImage(imageFile2); image = ImageViewer.resize(image, width, height); ImageIcon sizedIcon2 = new ImageIcon(image); final JLabel labelImg1 = new JLabel(sizedIcon1); final JLabel labelImg2 = new JLabel(sizedIcon2); // Prima imagine mica din stanga width = 70; height = 70; image = ImageViewer.buildImage(imageFile1); image = ImageViewer.resize(image, width, height); ImageIcon smallIcon1 = new ImageIcon(image); // A doua imagine mica din stanga width = 70; height = 70; image = ImageViewer.buildImage(imageFile2); image = ImageViewer.resize(image, width, height); ImageIcon smallIcon2 = new ImageIcon(image); // Bucata de cod pentru constructia de imagini tiff pentru overlayImage width = 250; height = 250; image = ImageViewer.buildImage(imageFile1); final Image overlayImage = ImageViewer.resize(image, width, height); // Bucata de cod pentru constructia de imagini tiff pentru // backgroundImage width = 250; height = 250; image = ImageViewer.buildImage(imageFile2); final Image backgroundImage = ImageViewer.resize(image, width, height); buttonsPanel = new JPanel(); imagePanel = new JPanel(); JPanel imagesPanel = new JPanel(); Container myPanel = getContentPane(); imagesPanel.setBorder(BorderFactory.createEtchedBorder()); imagesPanel.setLayout(new BoxLayout(imagesPanel, BoxLayout.Y_AXIS)); imagesPanel.add(Box.createVerticalStrut(30)); JLabel l1 = new JLabel(smallIcon1); l1.setBorder(BorderFactory.createTitledBorder("Image 1")); imagesPanel.add(l1); l1.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseClicked(MouseEvent arg0) { // if compare button was pressed, none of the images are // selected // same for the other icon if (!img1Selected && !img2Selected) { img2Selected = true; } if (img2Selected && !img1Selected) { imagePanel.remove(imagePanel.getComponent(1)); FadeOut fo = new FadeOut(backgroundImage, overlayImage); fo.setSize(250, 250); labelImg1.add(fo); fo.start(); imagePanel.add(labelImg1, 1); revalidate(); repaint(); img2Selected = false; img1Selected = true; } } }); imagesPanel.add(Box.createVerticalStrut(30)); JLabel l2 = new JLabel(smallIcon2); l2.setBorder(BorderFactory.createTitledBorder("Image 2")); imagesPanel.add(l2); l2.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseClicked(MouseEvent arg0) { if (!img1Selected && !img2Selected) { img1Selected = true; } if (img1Selected && !img2Selected) { imagePanel.remove(imagePanel.getComponent(1)); FadeOut fo = new FadeOut(overlayImage, backgroundImage); fo.setSize(250, 250); fo.start(); labelImg2.add(fo); imagePanel.add(labelImg2, 1); revalidate(); repaint(); img1Selected = false; img2Selected = true; } } }); imagesPanel.add(Box.createVerticalStrut(30)); imagePanel.add(imagesPanel, BorderLayout.WEST); imagePanel.add(labelImg2); imagePanel.add(Box.createVerticalGlue()); img2Selected = true; myPanel.add(imagePanel, BorderLayout.NORTH); buttonsPanel.setLayout(new FlowLayout()); buttonsPanel.setBorder(BorderFactory.createMatteBorder(2, 1, 1, 1, Color.GRAY)); JButton compareButton = new JButton("Compare"); // to do : add functionalities to bottons compareButton.addMouseListener(diffListener); buttonsPanel.add(compareButton); myPanel.add(buttonsPanel, BorderLayout.SOUTH); }
10ff6583-f678-44b7-85fb-f8eeee2e8bfc
9
@Override public CharSequence subSequence(int start, int end) { if (start >= length || end >= length) { throw new IllegalArgumentException("start or end cannot be greater than length"); } Integer startOfSubMap = sequences.lowerKey(start); NavigableMap<Integer, CharSequence> slice = sequences.subMap(startOfSubMap, true, end, true); // if there's only one CharSequence involved, then it's easy... if (slice.size() == 1) { Map.Entry<Integer, CharSequence> chunk = slice.firstEntry(); Integer startOfChunk = chunk.getKey(); return chunk.getValue().subSequence(start - startOfChunk, end - startOfChunk); } else if (slice.size() > 1) { // ...otherwise, we'll build up another one of our own kind AppendableCharSequence result = new AppendableCharSequence(); for (Map.Entry<Integer, CharSequence> chunk : slice.entrySet()) { Integer startOfChunk = chunk.getKey(); CharSequence charSequence = chunk.getValue(); int endOfChunk = startOfChunk + charSequence.length(); int startOfSubSeq = start > startOfChunk ? start - startOfChunk : 0; int endOfSubSeq = (end < endOfChunk ? end : endOfChunk) - startOfChunk; if (startOfSubSeq == 0 && endOfSubSeq == charSequence.length()) { result.append(charSequence); } else { result.append(charSequence.subSequence(startOfSubSeq, endOfSubSeq)); } } return result; } else { throw new IllegalArgumentException("Requested sub-sequence did not fall within contained bounds"); } }
0ff7e108-72b4-4785-a35a-61414a671757
3
@Override public void update() throws IOException { if (isNotReady()) { readyToSend = false; return; } long startTime = System.nanoTime(); long currentTime = System.currentTimeMillis(); readyToSend = (currentTime >= nextTime); if (readyToSend) { while (nextTime <= currentTime) { nextTime += updateRate; } } onUpdate(); durationUpdate = System.nanoTime() - startTime; }
c45ab1cf-119e-4ef2-8eab-a25fc6df19d7
9
@Override public void trainOnInstanceImpl(Instance inst) { double d = 1.0; int[] m = new int[this.ensemble.length]; for (int j = 0; j < this.ensemble.length; j++) { int j0 = 0; //max(0,j-K) pipos[j] = 1.0; pineg[j] = 1.0; m[j] = -1; if (this.ensemble[j].correctlyClassifies(inst)) { m[j] = 1; } for (int k = j0; k <= j - 1; k++) { pipos[j] *= wpos[j][k] / wpos[j][j] * Math.exp(-alphainc[k]) + (1.0 - wpos[j][k] / wpos[j][j]) * Math.exp(alphainc[k]); pineg[j] *= wneg[j][k] / wneg[j][j] * Math.exp(-alphainc[k]) + (1.0 - wneg[j][k] / wneg[j][j]) * Math.exp(alphainc[k]); } for (int k = 0; k <= j; k++) { wpos[j][k] = wpos[j][k] * pipos[j] + d * (m[k] == 1 ? 1 : 0) * (m[j] == 1 ? 1 : 0); wneg[j][k] = wneg[j][k] * pineg[j] + d * (m[k] == -1 ? 1 : 0) * (m[j] == -1 ? 1 : 0); } alphainc[j] = -alpha[j]; alpha[j] = 0.5 * Math.log(wpos[j][j] / wneg[j][j]); alphainc[j] += alpha[j]; d = d * Math.exp(-alpha[j] * m[j]); if (d > 0.0) { Instance weightedInst = (Instance) inst.copy(); weightedInst.setWeight(inst.weight() * d); this.ensemble[j].trainOnInstance(weightedInst); } } }
7fc0511e-1cf8-4008-9160-091aa047a17d
4
public void write_multiple(short address, byte[] msg) throws IOException { if ((this.mode==0) || (this.mode==SET_MODE_I2C_SERIAL)) this.set_mode(SET_MODE_I2C_100); byte[] data=new byte[msg.length+2]; data[0]=(byte)RW_MULTIPLE; data[1]=(byte)address; System.arraycopy(msg, 0, data, 2, msg.length); byte[] result = this.sendAndReceive(data, COM_TIMEOUT, 1); if (result.length==0) throw new IOException("no answer from device"); if (result[0]!=0) throw new IOException("device error: "+result[0]); }
a88ecda1-b184-453c-afa2-11ea9d69b86b
0
public void setUpdateExisting(boolean updateExisting) { this.updateExisting = updateExisting; }
1a61ceae-3dd3-42dc-a84c-9f9be49f364a
5
public boolean check_Status(String status){ String book_Status=status.toLowerCase(); if (book_Status.equals("lost") || book_Status.equals("checked-in")|| book_Status.equals("in-queue") || book_Status.equals("available")) return true; else if (book_Status.isEmpty()) return true; else return false; }
e1a5cace-47cf-49c5-9eae-3bb351af70d4
9
@Override public Object execute() throws OperationNotSupportedException { Object result; switch (operation) { // facebook specific actions case ADD_COMMENT: result = FacebookActionImplementation.sendComment("resource", "text"); break; case LIKE_AS: result = FacebookActionImplementation.likeAs("resource", "userId"); break; case SHARE_AS: result = FacebookActionImplementation.shareAs("resource", "userId"); break; case SEND_PRIVATE_MESSAGE: result = FacebookActionImplementation.sendPrivateMessage("userId", "text"); break; // general actions case ASSIGN_TO: result = FacebookActionImplementation.assignTo(); break; case SET_STATUS_AS: result = FacebookActionImplementation.setStatusAs(); break; case LINK_TO_CRM: result = FacebookActionImplementation.LinkToCRM(); break; case EMAIL_POST_TO: result = FacebookActionImplementation.EmailPostTo(); break; case REMOVE_POST: result = FacebookActionImplementation.RemovePost(); break; default: throw new OperationNotSupportedException("Not supported operation:" + operation); } return result; }
9beef453-7e2f-4fb2-b6ec-b70e6db57aeb
4
@Override public void mouseClicked(MouseEvent event) { Iterator<MouseClickedListener> it = mouseListeners.iterator(); while(it.hasNext()) { try { MouseClickedListener listener = it.next(); if(listener.isFinished()) { //TODO: gets removed next time the mouse is clicked... it.remove(); } else { listener.onClick(event.getX(), event.getY()); if (listener instanceof PlayAgainButton) { return; } } } catch (ConcurrentModificationException e) { System.out.println("CAUGHT IT!!"); } } // for(MouseClickedListener listener : mouseListeners) // { // listener.onClick(event.getX(), event.getY()); // } }
2d59c1ab-97ce-4ffe-9d29-79760ca99be4
9
public List<List<Integer>> threeSum(int[] num) { final int len = num.length; List<List<Integer>> list = new LinkedList<List<Integer>>(); if(len < 3) return list; Set<String> set = new HashSet<String>(); Arrays.sort(num); for(int i=0; i<len-2; i++){ if(num[i]>0) break; if(i == 0 || num[i] > num[i - 1] ){ for(int j=i+1; j<len-1; j++){ for(int k=j+1; k<len; k++){ if(num[i] + num[j] + num[k] == 0){ List<Integer> triplet = new LinkedList<Integer>(); String str = String.valueOf(num[i]) + String.valueOf(num[j]) + String.valueOf(num[k]); if(!set.contains(str)){ list.add(triplet); set.add(str); } triplet.add(num[i]); triplet.add(num[j]); triplet.add(num[k]); } } } } } return list; }
834bff6a-4b72-4d72-abdf-babda379bb29
2
@Override public void writeToSave(DataTag data) { super.writeToSave(data); DataList list = new DataList(); for(int slot = 0; slot < getMaxSlots(); slot++){ ItemStack stack = getStackInSlot(slot); if(stack != null){ DataTag tag = new DataTag(); stack.writeToSave(tag); tag.writeInt("slot", slot); list.write(tag); } } data.writeList("items", list); data.writeInt("timer", timer); data.writeInt("fueltimer", currentFuelTimer); }
67f59247-30d0-4f96-890c-b075305306a4
1
public ShieldMinigame(int level, Vector2 chunk, LD ld) { Util.clearBodies(); this.level = level; if (level == 0) { new IllegalArgumentException("0 isn't a valid level").printStackTrace(); } // TODO: clear bodies Objects.world.setContactListener(new ShieldMinigameContactManager(this)); life = 20 - level; runnableManager = new RunnableManager(); this.chunk = chunk; //TODO FIX countdown = new CountDown(20); this.ld = ld; }
6b8a0e53-e1f4-428c-99c1-01a79d3343eb
0
@Override public void undo() { node.setCommentState(oldState); }
b501e982-8cc0-4b9c-8b14-3402fa9129c6
7
public boolean processCommand(Terminal terminal, List<String> words) { boolean leave = false; leave = super.processCommand(terminal, words); if (!words.isEmpty()) { switch (words.get(0)) { case "add": terminal.add(); break; case "display": terminal.display(); break; case "remove": terminal.remove(); break; case "repair": terminal.repair(); break; case "stats": terminal.stats(); break; case "validate": terminal.validate(); break; } } return leave; }
7c1cfb02-b572-4678-9b6d-86aea8692649
3
private Vector<byte[]> segmentFile(String f) throws Exception { Vector<byte[]> sequenceList = new Vector<byte[]>(); try { //Open the input and out files for the streams FileInputStream file= new FileInputStream(f); while (file.available() > PAYLOADLENGTH) { byte[] b = new byte[PAYLOADLENGTH]; file.read(b); sequenceList.add(b); } byte[] b = new byte[file.available()]; file.read(b); sequenceList.add(b); file.close(); } catch (FileNotFoundException e) { System.err.println("Erreur : le fichier "+f+" est introuvable"); } catch (Exception e) { System.err.println("Erreur : " + e); } nbSequence = sequenceList.size(); return sequenceList; }
e0257e2b-9042-43ff-9e47-3e070d6cd234
1
public Date getNextDate() { Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, h); c.set(Calendar.MINUTE, m); if (c.before(Calendar.getInstance())) { c.add(Calendar.DATE, 1); } return c.getTime(); }
4827ef5f-3bc1-4eda-bc0c-1b524ddb5d70
3
@Override public BufferedImage getImage(int pageNumber) { Logger.getLogger(PdfHandler.class.getName()).entering(PdfHandler.class.getName(), "getImage", pageNumber); if (!isImageInRange(pageNumber)) { Logger.getLogger(PdfHandler.class.getName()).exiting(PdfHandler.class.getName(), "getImage", null); return null; } BufferedImage bufferedImage; try { bufferedImage = (BufferedImage) pdfDocument.getPageImages(--pageNumber).get(0); } catch (ClassCastException ex) { Image image = (Image) pdfDocument.getPageImages(pageNumber).get(0); bufferedImage = new ImageReader(image).convertImageToBufferedImage(); } catch (ArrayIndexOutOfBoundsException ex) { Logger.getLogger(PdfHandler.class.getName()).exiting(PdfHandler.class.getName(), "getImage", null); return null; } Logger.getLogger(PdfHandler.class.getName()).exiting(PdfHandler.class.getName(), "getImage", bufferedImage); return bufferedImage; }
5083baed-62f1-441b-8ff7-e51936496d3b
0
public Throwable getCause() { return this.cause; }
3c384d15-f68b-4dd9-a98a-a3228001cbd5
6
private void search(int i,int target,int[] cand, ArrayList<Integer> tmp,ArrayList<ArrayList<Integer>> rst) { if (cand[i] > target) return; if (cand[i] == target) { ArrayList<Integer> element = new ArrayList<Integer>(); element.addAll(tmp); element.add(cand[i]); rst.add(element); return; } if (target -cand[i] >= cand[i]) { tmp.add(cand[i]); target -= cand[i]; int j = i +1; while (j < cand.length) { search(j,target,cand,tmp,rst); while (j< cand.length -1 && cand[j+1] == cand[j]) j++; j++; } target += cand[i]; tmp.remove(tmp.size() -1); } }
3310f61e-d151-4f66-b7a5-21e8f3081e9e
5
public Boolean isNewGameOk() { if (this.height != 0 && this.width != 0 && this.nbMines != 0 && this.nbFlags != 0 && cells[8][9] != null) { return true; } else { return false; } }
572763c4-1978-4cf0-980e-e5db209e3f2f
0
public void setSpNum(String spNum) { this.spNum = spNum; }
f14155fd-9d6e-4994-9712-604267f1acc7
0
public CheckResultMessage checkG(int day) { return checkReport.checkG(day); }
3a4734e2-e3ea-4253-b76d-a03a49cb846e
5
private void updateTabla(){ //** pido los datos a la tabla Object[][] vcta = this.getDatos(); //** se colocan los datos en la tabla DefaultTableModel datos = new DefaultTableModel(); tabla.setModel(datos); datos = new DefaultTableModel(vcta,colum_names_tabla); tabla.setModel(datos); //ajustamos tamaño de la celda Fecha Alta /*TableColumn columna = tabla.getColumn("Fecha Alta"); columna.setPreferredWidth(100); columna.setMinWidth(100); columna.setMaxWidth(100);*/ if (!field_codigo.getText().equals("")){ posicionarAyuda(field_codigo.getText()); } else{ if ((fila_ultimo_registro-1 >= 0)&&(fila_ultimo_registro-1 < tabla.getRowCount())){ tabla.setRowSelectionInterval(fila_ultimo_registro-1,fila_ultimo_registro-1); scrollCellToView(this.tabla,fila_ultimo_registro-1,fila_ultimo_registro-1); cargar_ValoresPorFila(fila_ultimo_registro-1); } else{ if ((fila_ultimo_registro+1 >= 0)&&(fila_ultimo_registro+1 <= tabla.getRowCount())){ tabla.setRowSelectionInterval(fila_ultimo_registro,fila_ultimo_registro); scrollCellToView(this.tabla,fila_ultimo_registro,fila_ultimo_registro); cargar_ValoresPorFila(fila_ultimo_registro); } } } }
68107b78-5dbe-4900-9b31-7ee842d24744
5
public Model getDialogueModel(int gender) { int dialogueModelId = maleDialogueModelId; int dialogueHatModelId = maleDialogueHatModelId; if (gender == 1) { dialogueModelId = femaleDialogueModelId; dialogueHatModelId = femaleDialogueHatModelId; } if (dialogueModelId == -1) return null; Model dialogueModel = Model.getModel(dialogueModelId); if (dialogueHatModelId != -1) { Model dialogueHatModel = Model.getModel(dialogueHatModelId); Model dialogueModels[] = { dialogueModel, dialogueHatModel }; dialogueModel = new Model(2, dialogueModels); } if (modifiedModelColors != null) { for (int c = 0; c < modifiedModelColors.length; c++) dialogueModel.recolour(modifiedModelColors[c], originalModelColors[c]); } return dialogueModel; }
c4e301ac-a3b6-4dec-aa8c-17c33a63fc22
0
public String getCode_lab() { return code_lab; }
5b731eff-0cef-4814-ba27-1f59e142308f
2
@Override public boolean filter(String url) { if (null == url || "".equals(url)) { return false; } Pattern pattern = Pattern.compile("^(http|https)://.+$"); Matcher matcher = pattern.matcher(url); return matcher.matches(); }
6f3c5350-6e70-40cb-997c-0a595ca929fb
5
private void trHeapSort (final int ISA, final int ISAd, final int ISAn, final int sa, final int size) { final int[] SA = this.SA; int i, m; int t; m = size; if ((size % 2) == 0) { m--; if (trGetC (ISA, ISAd, ISAn, SA[sa + (m / 2)]) < trGetC (ISA, ISAd, ISAn, SA[sa + m])) { swapElements (SA, sa + m, SA, sa + (m / 2)); } } for (i = m / 2 - 1; 0 <= i; --i) { trFixdown (ISA, ISAd, ISAn, sa, i, m); } if ((size % 2) == 0) { swapElements (SA, sa + 0, SA, sa + m); trFixdown (ISA, ISAd, ISAn, sa, 0, m); } for (i = m - 1; 0 < i; --i) { t = SA[sa + 0]; SA[sa + 0] = SA[sa + i]; trFixdown (ISA, ISAd, ISAn, sa, 0, i); SA[sa + i] = t; } }
6e789310-b15a-41cd-beab-b967def47334
7
public static void main(String[] args) { Reader.init(System.in); try { int numCasos = Reader.nextInt(); for(int i=0;i<numCasos;i++) { int n = Reader.nextInt(); int p = Reader.nextInt(); int q = Reader.nextInt(); W = new int[n]; val = new int[n + 1][q + 1][p + 1]; for(int x = 0; x < n+1; x++) { for(int y = 0; y <q+1; y++) { for(int z = 0; z < p+1; z++) { val[x][y][z] = -1; } } } for(int j = 0;j<n;j++) { W[j] = Reader.nextInt(); } int result = knapsack(q, p); System.out.println(result); } } catch (NullPointerException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
0d730f4a-9e22-4777-b376-8c58d75e460b
4
public void print() { System.out.println("*** Draw Deck ***"); if ( draw_.isEmpty() ) System.out.print("No Cards Available"); else for ( Card c : draw_ ) System.out.print(c.toString() + ", "); System.out.println("\n*** Discard Deck *** "); if ( discard_.isEmpty() ) System.out.print("No Cards Available"); else for ( Card c : discard_ ) System.out.print(c.toString() + ", "); System.out.print("\n"); }
6d53804d-6e75-40e2-ad31-96c12d209e9e
9
public void update(User u) throws InvalidFieldException { if (u.getFirstName() != null) { setFirstName(u.getFirstName()); } if (u.getLastName() != null) { setLastName(u.getLastName()); } if (u.getID() != null) { setID(u.getID()); } if (u.getPoints() != getPoints()) { setPoints(u.getPoints()); } if (u.getWeeklyPick() != null && !u.getWeeklyPick().isNull()) { setWeeklyPick(u.getWeeklyPick()); } if (u.getUltimatePick() != null && !u.getUltimatePick().isNull()) { setUltimatePickNoSetPts(u.getUltimatePick()); } if (u.getUltimatePoints() != getUltimatePoints()) { setUltimatePoints(u.getUltimatePoints()); } }
43480f62-d6a9-40e3-aa0e-335bf6d9a8fb
3
public ShapeElemtex(SimpleFeature f, String tipo) { super(f, tipo); shapeId = "ELEMTEX" + super.newShapeId(); // Elemtex trae la geometria en formato MultiLineString if ( f.getDefaultGeometry().getClass().getName().equals("com.vividsolutions.jts.geom.MultiLineString")){ MultiLineString l = (MultiLineString) f.getDefaultGeometry(); LineString line = new LineString(l.getCoordinates(),null , 0); coor = line.getEnvelopeInternal().centre(); } else { System.out.println("["+new Timestamp(new Date().getTime())+"] Formato geometrico "+ f.getDefaultGeometry().getClass().getName() +" desconocido dentro del shapefile ELEMTEX"); } // Los demas atributos son metadatos y de ellos sacamos ttggss = (String) f.getAttribute("TTGGSS"); // try { // rotulo = new String(f.getAttribute("ROTULO").toString().getBytes(), "UTF-8"); // rotulo = eliminarComillas(rotulo); // } catch (UnsupportedEncodingException e) {e.printStackTrace();} rotulo = eliminarComillas(f.getAttribute("ROTULO").toString()); if (rotulo.equals(rotulo.toUpperCase())) { char[] delim = {' ','.'}; rotulo = WordUtils.capitalizeFully(rotulo, delim); } // Se agregan tags dependientes del rotulo tags.addAll(Rules.getTags(rotulo)); // Dependiendo del ttggss se usa o no if (ttggss != null){ tags.addAll(ttggssParser(ttggss)); } // Para agrupar geometrias segun su codigo de masa que como en este caso no existe se // asigna el del nombre del fichero shapefile codigoMasa = "ELEMTEX-" + ttggss; // Si queremos coger todos los atributos del .shp // this.atributos = new ArrayList<ShapeAttribute>(); // for (int x = 1; x < f.getAttributes().size(); x++){ // atributos.add(new ShapeAttribute(f.getFeatureType().getDescriptor(x).getType(), f.getAttributes().get(x))); // } }
4ee46845-8237-48f1-8832-0adfe8c6f399
4
float func_526_b(int var1) { return var1 >= 0 && var1 < this.leafDistanceLimit?(var1 != 0 && var1 != this.leafDistanceLimit - 1?3.0F:2.0F):-1.0F; }
afd6e0cd-18fb-4d79-b339-97d2193ba03c
6
public static String javaPackagePrefix(Module module, String separator) { { String result = ""; char separatorChar = separator.charAt(0); String packagePrefix = module.javaPackage(); if (packagePrefix != null) { if (separatorChar == '.') { result = packagePrefix; } else { result = Native.string_substitute(packagePrefix, separatorChar, '.'); } return (result + separator); } result = Stella.javaTranslateNamestring(Native.stringDowncase(module.name())) + separator; { Context mod = null; Iterator iter000 = module.parentContexts(); loop000 : while (iter000.nextP()) { mod = ((Context)(iter000.value)); if (Stella_Object.isaP(mod, Stella.SGT_STELLA_MODULE) && (!(mod == Stella.$ROOT_MODULE$))) { result = Module.javaPackagePrefix(((Module)(mod)), separator) + result; break loop000; } } } if (separatorChar == '.') { KeyValueList.setDynamicSlotValue(module.dynamicSlots, Stella.SYM_STELLA_JAVA_PACKAGE, StringWrapper.wrapString(Native.string_subsequence(result, 0, result.length() - 1)), Stella.NULL_STRING_WRAPPER); } return (result); } }
e2559a01-975b-47f0-875d-ee1f9b756b18
0
public AttributesImageIconCellEditor(AbstractAttributesPanel panel) { super(new JCheckBox(), OutlineEditableIndicator.ICON_IS_PROPERTY, OutlineEditableIndicator.ICON_IS_NOT_PROPERTY); this.panel = panel; }
ca65e21c-eb30-43e4-884a-ce110ae55b8b
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Window().setVisible(true); } }); }
140496bc-af57-4085-9910-ff86e26e3749
3
@Override public void render(Drawer drawer) { for (int x = 0; x < map.length; x++) { for (int y = 0; y < map[x].length; y++) { int drawX = (x * tileSize) + offsetX; int drawY = (y * tileSize) + offsetY; if (map[x][y] == 0) { drawer.draw(floor, drawX, drawY); drawer.drawString("" + manhattenScoreMap[x][y], drawX + 20, drawY + 10); } else { drawer.draw(solid, drawX, drawY); } } } }
bb1f2b77-9a54-412c-8908-e413d436402a
2
void renderOffscreen() { do { if (vImg.validate(getGraphicsConfiguration()) == VolatileImage.IMAGE_INCOMPATIBLE) { // old vImg doesn't work with new GraphicsConfig; re-create it vImg = this.getGraphicsConfiguration() .createCompatibleVolatileImage(workingImage.getWidth(), workingImage.getHeight()); } Graphics2D g = vImg.createGraphics(); g.drawImage(workingImage.getBufferedImage(), workingImage.getWidth(), workingImage.getHeight(), null); g.dispose(); } while (vImg.contentsLost()); }
c2eb14ec-e559-429e-a3ef-1b87dd36c20d
2
private void reduce(){ int[] primeNumbers = getPrimeNumbers(); for (int primeNumber: primeNumbers){ while (isReducible(primeNumber)){ numerator /= primeNumber; denominator /= primeNumber; } } }
d521583e-0620-40cb-bd00-d7ee43afab87
7
private void validateTileDimension(String targetPath, String tilePath) throws IOException { try { // Create a buffer of target image. BufferedImage targetBuffer = ImageIO.read(new File(targetPath)); // Creating a new file instance. File tileDirectory = new File(tilePath); // Total number of tiles in directory int totalFile = tileDirectory.list().length; boolean isDimensionSet = false; // Check if the tile width and height are divisible by // target width and height. for (int i = 0; i < totalFile; i++) { BufferedImage tileBuffer = ImageIO.read(new File(tilePath + "/" + tileDirectory.list()[i])); //Check that tile width is a divisor of the target image width. //Check that tile height is a divisor of the target image height. if (((targetBuffer.getWidth() % tileBuffer.getWidth()) != 0) || (targetBuffer.getHeight() % tileBuffer.getHeight() != 0)) { System.out .println("Incorrect Tile Dimensions: The width of each tile " + "must be a divisor of the width of the target image, " + "and the height of each tile must be a divisor of the " + "height of the target image."); tileBuffer.flush(); System.exit(0); } else { //If dimensions of tiles are not yet initialized, //then set the tile dimensions. if (!isDimensionSet) { Main.setTILEDIMENSION(0, tileBuffer.getWidth()); Main.setTILEDIMENSION(1, tileBuffer.getHeight()); isDimensionSet = true; } //Condition that checks if all the tiles have //same dimensions. else if (Main.getTILEDIMENSION(0) != tileBuffer .getWidth() && Main.getTILEDIMENSION(1) != tileBuffer .getHeight()) { System.out .println("All the tiles should be of same dimensions"); System.exit(0); } tileBuffer.flush(); } } targetBuffer.flush(); } catch (Exception e) { System.out.println("All Tile images should have same dimensions."); System.exit(0); } }
7d90867f-31d7-4bab-93f2-4a0caaea5f00
8
public void FullBack_findBall() throws UnknownHostException, InterruptedException { //Pos origin = new Pos(0,0); //System.out.println("in FullBack_findBall"); if(mem.isObjVisible("ball")) { ObjBall ball = mem.getBall(); if((ball.getDirection() > 5.0 || ball.getDirection() < -5.0)) { rc.turn(ball.getDirection()); Thread.sleep(100); } if((ball.getDistance() > 15) && (mem.isHome == false)) { goHome(); } else if((ball.getDistance() <= 15.0) && (ball.getDistance() > 0.7)){ interceptBall(ball); } else if(ball.getDistance() <= 0.7) { //kickToPoint(ball, origin); passBall(ball, closestPlayer()); } } else rc.turn(30); }
23280cb6-2bab-445c-9efb-0eef1b3200dd
5
public Collection<String> getMainGroops() { // A Map of groopName --> Count Map<String, Integer> mainGroopMap = new TreeMap<String, Integer>(); Collection<String> mainGroops = new Vector<String>(); Iterator<Track> tIt = tracks.iterator(); while (tIt.hasNext()) { // Increment the count for each groop Collection<LineUp> groops = (tIt.next()).getLineUps(); Iterator<LineUp> gIt = groops.iterator(); while (gIt.hasNext()) { Groop grp = gIt.next().getGroop(); String groopName = grp.getSortName(); Integer intVal; if (mainGroopMap.containsKey(groopName)) { intVal = mainGroopMap.get(groopName); intVal = intVal.intValue() + 1; } else intVal = 1; mainGroopMap.put(groopName, intVal); } } // Select only groops who appear on the right number of tracks for (Entry<String, Integer> ent : mainGroopMap.entrySet()) if (((ent.getValue()).doubleValue() / tracks.size()) > GROOP_RATIO) mainGroops.add(ent.getKey()); System.err.println("GROOPS = " + mainGroops); return mainGroops; }
429e91c3-5f87-4eb7-b6c2-23a754710da1
5
@Override public int analyse(LexicalAnalyser analyser, int beginIndex) throws AnalyseException { String content = analyser.getSentence(); char character = content.charAt(beginIndex); char characterNext = beginIndex + 1 == content.length() ? ' ' : content .charAt(beginIndex + 1); // if (!WordTable.isDelimiter(character) && // !WordTable.isDelimiterPart(character)) { // throw new AnalyseException(String.format( // "Error: Undefined character [%c]", character)); // } // if (WordTable.isDelimiterPart(character) // || (WordTable.isDelimiter(characterNext) || WordTable // .isDelimiterPart(characterNext))) { // String delimiter = String.valueOf(character) // + String.valueOf(characterNext); // if (WordTable.isDelimiter(delimiter)) { // return addResultToAnalyerAndGetResult(analyser, beginIndex, // beginIndex + 2); // } else { // throw new AnalyseException(String.format( // "Error: Undefined character [%c]", character)); // } // } if (WordTable.isDelimiter(character) && (WordTable.isDigit(characterNext) || WordTable.isOverableLetter(characterNext) || WordTable .isLetter(characterNext))) { return addResultToAnalyerAndGetResult(analyser, beginIndex, beginIndex + 1); } throw new AnalyseException(String.format( "Error: Undefined character [%c]", character)); }
1ee3a67c-0bd7-4055-8b58-0f4b25d54b5d
6
public boolean getBoolean(int index) throws JSONException { Object object = this.get(index); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object) .equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String) object) .equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a boolean."); }
0ce53954-b47c-4f7d-b489-978b1c718460
3
private void jButton1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButton1KeyReleased if (evt.getKeyChar() == evt.VK_ENTER) { i++; if (i == 1) { jButton1.doClick(); } else if (i == 2) { i = 0; } } }//GEN-LAST:event_jButton1KeyReleased
c4a712c6-efd1-45de-874c-e4d117e643a7
1
public static void main(String[] args) { try { EntityUi dialog = new EntityUi(); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); } catch (Exception e) { e.printStackTrace(); } }
31ab5951-db42-4557-86b6-508a1c20d0f1
9
private void updateSelectionLocation(final MouseEvent _event, final boolean _applyChanges) { if (pnt_start == null || _event == null) { //print error message. State.getLogger().severe("the pnt_start or the _event is null" + "\n\tpnt_start: \t" + pnt_start + "\n\t_event: \t" + _event); return; } // compute the difference between the location of the mouse press // event (on screen) and the current mouse location (on screen). int dX = (int) (_event.getXOnScreen() - pnt_start.getX()), dY = (int) (_event.getYOnScreen() - pnt_start.getY()); // shift the selection - background JLabel and the label which // contains the painted selection by the above-calculated values. if (pnt_startLocationLabel != null) { getPage().getJlbl_selectionBG().setLocation( (int) pnt_startLocationLabel.getX() + dX, (int) pnt_startLocationLabel.getY() + dY); getPage().getJlbl_selectionPainting().setLocation( (int) pnt_startLocationLabel.getX() + dX, (int) pnt_startLocationLabel.getY() + dY); } else { // otherwise print an error message. State.getLogger().severe("The pnt_startLocationLabel is null"); } // Shift the Buttons for moving and stretching. if (pnt_startLocationButton != null) { for (int x = 0; x < pnt_startLocationButton.length; x++) { for (int y = 0; y < pnt_startLocationButton.length; y++) { // if either // (1) there is no selection but x + y >== 2 (meaning // they are visible) or // // (2) there is a selection (then each button is // visible) // shift the buttons. // // Case (1) should never occur because if the entire image // is selected, there is nothing to shift. if (x + y >= 2 || !wholeImageSelected) { getPage().getJbtn_resize()[x][y].setLocation( (int) pnt_startLocationButton[x][y].getX() + dX, (int) pnt_startLocationButton[x][y].getY() + dY); } } } } else { // otherwise print error. State.getLogger().severe( "The pnt_startLocationButton is null."); } // Shift the rectangle which contains the current location of the // selection. r_selection.x = (int) pnt_rSelectionStart.getX() + dX; r_selection.y = (int) pnt_rSelectionStart.getY() + dY; // Adapt the border to the selection's new calculated location getPage().getJlbl_border().setBounds(r_selection); // if "apply changes" is selected, the shifting is applied to the // paintObjects. if (_applyChanges) { //compute the current zoom - factor final double cZoomFactorWidth = 1.0 * State.getImageSize().width / State.getImageShowSize().width; final double cZoomFactorHeight = 1.0 * State.getImageSize().height / State.getImageShowSize().height; cv.getPicture().moveSelected( (int) (1.0 * dX * cZoomFactorWidth), (int) (1.0 * dY * cZoomFactorHeight)); cv.getControlPic().paintEntireSelectionRect( r_selection); getPage().getJlbl_selectionPainting().repaint(); // reset the pnt_start and the point for which contains the start // of the selection. pnt_start = null; pnt_rSelectionStart = null; // change the point which is maintained inside the controlPaintgit // which is used for (not) shifting the selected stuff while // the user scrolls. cv.getPnt_startLocation().x -= dX; cv.getPnt_startLocation().y -= dY; } }
fe20ed71-c2d6-4f45-a63b-a56b262564b4
9
public void getMails(MailAccount account) { List<String> mailContent; sTrace.debug("getting Mails"); List<Integer> mailNumberList = new ArrayList<Integer>(); error = false; /* Ab Java 7: try-with-resources mit automat. close benutzen! */ // Socket, inklusive Streams, einrichten openSocket(account); if (!error) { login(account); if (!error) { mailNumberList = getMailNumberList(); for (int i = 0; !error && i < mailNumberList.size(); i++) { mailContent = getMail(mailNumberList.get(i)); if (!error) { try { String fileName = Long.toString(System .currentTimeMillis()); // Die letzten 20 Ziffern der aktuellen Zeit in // milisekunden. // fileName = // fileName.substring(fileName.length()-21); saveMail(mailContent, fileName); } catch (IOException e) { sTrace.debug("Mail konnte nicht gespeichert werden"); } } deleteMail(mailNumberList.get(i)); } //QUIT Senden try { sTrace.debug("Try Quit Command"); writeToServer("QUIT"); if(!readFromServer().startsWith("+OK")){ sTrace.error("Quit Command failure"); } } catch (IOException e) { sTrace.error("Connection aborted by server!"); } } } /* Socket-Streams schlie�en --> Verbindungsabbau */ try { error = true; clientSocket.close(); } catch (IOException e) { sTrace.error("Connection aborted by server!"); } sTrace.debug("TCP Client stopped!"); }
857d1d93-ebbb-463a-823d-33437faa038e
8
protected List<Section> loadDataFromInternet() throws IOException { File tmpFile = File.createTempFile("uas", ".txt"); try { // Download file to temp location BufferedReader reader = null; FileWriter writer = null; try { URL url = new URL(DATA_RETRIVE_URL); reader = new BufferedReader(new InputStreamReader(url.openStream())); writer = new FileWriter(tmpFile); String line = null; while ((line = reader.readLine()) != null) { writer.write(line); writer.write(System.getProperty("line.separator")); } } finally { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } } // Try to parse it try { PHPFileParser fp = new PHPFileParser(tmpFile); List<Section> sections = fp.getSections(); // now that we've finished parsing, we can save the temp copy if (cacheFile.exists()) { cacheFile.delete(); } if (!tmpFile.renameTo(cacheFile)) { // was across filesystems or target exists, or something else. // Try other another way // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4017593 copyFile(tmpFile, cacheFile); } return sections; } catch (Throwable t) { if (t instanceof IOException) { throw (IOException) t; } throw new IOException(t); } } finally { if (tmpFile.compareTo(cacheFile) != 0) { tmpFile.delete(); } } }
594132f6-0e36-4d86-ad91-1b0069f7a324
3
public static void back(int index, int cur) { if (totalLength - cur < dif) { dif = totalLength - cur; sum = cur; ans = taken; } if (index + 1 >= tracks.length) return; if (cur + tracks[index + 1] <= totalLength) { taken |= 1 << (index); back(index + 1, cur + tracks[index + 1]); taken ^= 1 << (index); } back(index + 1, cur); }
80f98b4f-c1f1-4353-b793-b86c0ef16dda
8
public void dotBrowserChanged(String newText) { setErrorMessage(null); setMessage(null); if (newText == null) { newText = dotBrowser.getText(); } if (specifyDotButton.getSelection()) { if (newText.length() == 0) { setErrorMessage("Please enter a path."); setValid(false); return; } File dotFile = new File(newText); String fileName = dotFile.getName(); int extensionPos; while ((extensionPos = fileName.lastIndexOf('.')) > 0) fileName = fileName.substring(0, extensionPos); if (!dotFile.exists()) { setErrorMessage(newText + " doesn't exist"); setValid(false); return; } else if (dotFile.isDirectory()) { setErrorMessage(newText + " is a directory"); setValid(false); return; } else if (!GraphVizActivator.isExecutable(dotFile)) setMessage(newText + " is not executable!", IMessageProvider.WARNING); else if (!GraphVizActivator.DOT_FILE_NAME.equalsIgnoreCase(fileName)) setMessage("The file name should be " + GraphVizActivator.DOT_FILE_NAME, IMessageProvider.WARNING); } setValid(true); }
b84678f0-486d-4e04-867d-4c18ff1ab0af
9
public boolean deleteDirectory(String sPath) { //如果sPath不以文件分隔符结尾,自动添加文件分隔符 if (!sPath.endsWith(File.separator)) { sPath = sPath + File.separator; } File dirFile = new File(sPath); //如果dir对应的文件不存在,或者不是一个目录,则退出 if (!dirFile.exists() || !dirFile.isDirectory()) { return false; } flag = true; //删除文件夹下的所有文件(包括子目录) File[] files = dirFile.listFiles(); for (int i = 0; i < files.length; i++) { //删除子文件 if (files[i].isFile()) { flag = deleteFile(files[i].getAbsolutePath()); if (!flag) break; } //删除子目录 else { flag = deleteDirectory(files[i].getAbsolutePath()); if (!flag) break; } } if (!flag) return false; //删除当前目录 if (dirFile.delete()) { return true; } else { return false; } }
5773dc92-a126-4e67-ad46-47f5dde37cb8
6
public static String trimTextWithWidth(String text, int width) { if (null == text || "".equals(text.trim()) || width <= 0) return ""; StringBuilder sb = new StringBuilder(); String[] textList = text.replace("\r", "").split("\n"); int c = 0; for (String t : textList) { String trimedText = trimLineTextWithWidth(t, width); if (!"".equals(trimedText)) { if (c++ > 0) sb.append(LINE_SEPARATOR); sb.append(trimedText); } } return sb.toString(); }
11203cc3-9493-4c08-80b7-dde6a0efec47
9
public boolean cooking() { if (playerLevel[playerCooking] >= cooking[1]) { if (actionTimer == 0 && cooking[0] == 1 && playerEquipment[playerWeapon] >= 0) { actionAmount++; actionTimer = 4; OriginalShield = playerEquipment[playerShield]; OriginalWeapon = playerEquipment[playerWeapon]; playerEquipment[playerShield] = -1; playerEquipment[playerWeapon] = -1; setAnimation(0x380); cooking[0] = 2; } if (actionTimer == 0 && cooking[0] == 2) { deleteItem(cooking[5], GetItemSlot(cooking[5]), 1); int Discount = 0; if (playerEquipment[playerHands] == 775) { //Cooking hauntlets Discount = 10; } int StopBurnLevel = ((cooking[1] + 35) - Discount); if (StopBurnLevel > playerLevel[playerCooking] && misc.random2(StopBurnLevel) <= misc.random2(StopBurnLevel)) { addItem(cooking[6], 1); sendMessage("You burned the "+GetItemName(cooking[5])+"."); } else { addItem(cooking[4], 1); addSkillXP((cooking[2] * cooking[3]), playerCooking); sendMessage("You cooked the "+GetItemName(cooking[5])+"."); } playerEquipment[playerWeapon] = OriginalWeapon; playerEquipment[playerShield] = OriginalShield; OriginalWeapon = -1; OriginalShield = -1; resetAnimation(); resetCO(); } } else { sendMessage("You need "+cooking[1]+" "+statName[playerCooking]+" to cook this "+GetItemName(cooking[5])+"."); resetCO(); return false; } return true; }
b5e562a8-81e7-46de-8d8d-3a69a923def0
7
private void addSolutionModifiers(Query arq, Resource query) { long limit = arq.getLimit(); if(limit != Query.NOLIMIT) { query.addProperty(SP.limit, query.getModel().createTypedLiteral(limit)); } long offset = arq.getOffset(); if(offset != Query.NOLIMIT) { query.addProperty(SP.offset, query.getModel().createTypedLiteral(offset)); } List<SortCondition> orderBy = arq.getOrderBy(); if(orderBy != null && !orderBy.isEmpty()) { List<RDFNode> criteria = new LinkedList<RDFNode>(); for(SortCondition sortCondition : orderBy) { Expr expr = sortCondition.getExpression(); RDFNode node = createExpression(expr); if(sortCondition.getDirection() == Query.ORDER_ASCENDING) { Resource asc = query.getModel().createResource(SP.Asc); asc.addProperty(SP.expression, node); criteria.add(asc); } else if(sortCondition.getDirection() == Query.ORDER_DESCENDING) { Resource desc = query.getModel().createResource(SP.Desc); desc.addProperty(SP.expression, node); criteria.add(desc); } else { criteria.add(node); } } query.addProperty(SP.orderBy, query.getModel().createList(criteria.iterator())); } }
0753db28-7799-427b-8f27-bf62fa5cd150
9
Option(boolean hasArg, String... aliases) { this.hasArg = hasArg; this.aliases = aliases; }
0a081263-8ce3-44d4-b5db-18a9e71d493d
2
public void initTableModel(JTable table, List<CreditProgram> list) { //Формируем массив программ для модели таблицы Object[][] crProgArr = new Object[list.size()][table.getColumnCount()]; int i = 0; for (CreditProgram prog : list) { //Создаем массив для кредитной программы Object[] row = new Object[table.getColumnCount()]; //Заполняем массив данными row[0] = prog.getName(); row[1] = prog.getMinAmount(); row[2] = prog.getMaxAmount(); row[3] = prog.getDuration(); row[4] = prog.getStartPay(); row[5] = prog.getPercent(); row[6] = prog.getDescription(); //Получаем статус кредитной программы String crProgStatus; int status = prog.getCreditProgStatus(); switch (status) { case 1: { crProgStatus = activeStatus; break; } default: { crProgStatus = nonActiveStatus; break; } } row[7] = crProgStatus; crProgArr[i++] = row; } table.setModel(new DefaultTableModel( crProgArr, CreditProgramDAO.getFieldsName()) { public Class getColumnClass(int columnIndex) { return types[columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit[columnIndex]; } }); table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF); table.getColumnModel().getColumn(0).setPreferredWidth(140); table.getColumnModel().getColumn(1).setPreferredWidth(140); table.getColumnModel().getColumn(2).setPreferredWidth(140); table.getColumnModel().getColumn(4).setPreferredWidth(120); table.getColumnModel().getColumn(6).setPreferredWidth(160); table.getColumnModel().getColumn(7).setPreferredWidth(140); }
094dd069-0526-4d98-a80e-1f55b9cda875
6
public final void updatePath(boolean aquireTargetImeediately) { if ((path == null) || (pathTarget == null)) { path = GameCtrl.get().getCurrentPathingGraph(def.size).iterator(); nextPathTarget(); } else { PointI p1 = path.getLastPoint(); if (aquireTargetImeediately) { path = GameCtrl.get().getCurrentPathingGraph(def.size).iterator(getPointI()); if (path != null) { PointI p2 = path.next(); if ((p2 != null) && !p2.equals(p1)) { pathTarget = p2.getPointD(def.size, WALK_RANDOM_COMPONENT); updateRotation(); } } } else { path = GameCtrl.get().getCurrentPathingGraph(def.size).iterator(pathTarget.getPointI(def.size)); } } }
f7a54689-0bc0-46d4-b6c2-bb988d5b1e1b
5
@Override public void actionPerformed(ActionEvent e) { if (e.getSource() == exit) { System.exit(1); } else if (e.getSource() == createMaster) { CreateMasterFrame.getInstance().setVisible(true); parent.dispose(); } else if (e.getSource() == measurePath) { MeasurePathFrame.getInstance().start(); parent.dispose(); } else if (e.getSource() == runWorld) { WorldFrame.getInstance().setVisible(true); parent.dispose(); } else if (e.getSource() == settings) { // open settings pop-up new SettingsDialog(); } }
7338de99-e632-4391-8cc6-526c0dd1bd18
7
public boolean executeDistributedQuery(String keyRegExp, String valRegExp, String unitTestName) { System.out.println("Executing Distributed query for unit test cast : " + unitTestName); ProcessBuilder pb = null; try { if(keyRegExp != "" && valRegExp != "") pb = new ProcessBuilder("./dgrep", "-key", keyRegExp, "-value", valRegExp); else if(keyRegExp != "") pb = new ProcessBuilder("./dgrep", "-key", keyRegExp); else if(valRegExp != "") pb = new ProcessBuilder("./dgrep", "-value", valRegExp); //pb.redirectOutput(new File("unit_tests/" + unitTestName + "/output_dist.txt")); Process ps = pb.start(); BufferedReader is = new BufferedReader(new InputStreamReader(ps.getInputStream())); String outputFileName = "unit_tests/" + unitTestName + "/output_dist.txt"; BufferedWriter os = new BufferedWriter(new FileWriter(outputFileName)); String line; while ((line = is.readLine()) != null) { os.write(line + "\n"); } if(ps.waitFor() != 0) { System.out.println("ERROR : Error executing distributed query for : " + unitTestName); is.close(); os.close(); return false; } else { is.close(); os.close(); return true; } } catch(Exception e) { System.out.println("ERROR : Exeception executing distributed query for : " + unitTestName); e.printStackTrace(); return false; } }