method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
0f977a80-062d-42b3-a6ad-ccdb0126cb2a
3
private void sendPublicKey(short crt, APDU apdu) { RSAPublicKey key = null; short len, l; switch(crt) { case (short)0xb600: key = (RSAPublicKey)keySign.getPublic(); break; case (short)0xb800: key = (RSAPublicKey)keyDecrypt.getPublic(); break; case (short)0xa400: key = (RSAPublicKey)keyAuth.getPublic(); break; default: ISOException.throwIt(ISO7816.SW_DATA_INVALID); } tmpData[0] = (byte)0x7f; tmpData[1] = (byte)0x49; tmpData[2] = (byte)0x82; tmpData[5] = (byte)0x81; len = 6; // len = 5; l = key.getModulus(tmpData, (short)(len + 3)); tmpData[len++] = (byte)0x82; Util.setShort(tmpData, len, l); len += 2; // tmpData[len++] = (byte)l; len += l; tmpData[len++] = (byte)0x82; l = key.getExponent(tmpData, (short)(len + 1)); tmpData[len++] = (byte)l; len += l; Util.setShort(tmpData, (short)3, (short)(len - 5)); // tmpData[3] = (byte)(len - 4); sendData(apdu, tmpData, len); }
2328f514-392f-45c4-9b62-f2ffc130ea1f
3
public void updateViewRegisters() { if(memory[XREG_ADDRESS] != xReg.get(xReg.size() - 1)) xReg.add(memory[XREG_ADDRESS]); if(memory[YREG_ADDRESS] != yReg.get(yReg.size() - 1)) yReg.add(memory[YREG_ADDRESS]); if(memory[ACCUMULATOR_ADDRESS]!= acc.get(acc.size() - 1)) acc.add(memory[ACCUMULATOR_ADDRESS]); }
fc61de89-db75-4af6-9886-afe179adc211
6
private void getFlipInstruction() { currentState = new BrainState(BrainState.INSTRUCTION_FLIP); char read = (char) readAhead; readNext(); if(checkCharacter(read, 'l')) { read = (char) readAhead; readNext(); if(checkCharacter(read, 'i')) { read = (char) readAhead; readNext(); if(checkCharacter(read, 'p')) { if(checkWhitespace()) { currentState.setFlipNumber(getFlipNumber()); if(checkWhitespace()) { int nextState = getStateNumber(); highestReferencedState = Math.max(nextState, highestReferencedState); currentState.setNextState(nextState); if(checkWhitespace()) { int nextStateOnFail = getStateNumber(); highestReferencedState = Math.max(nextStateOnFail, highestReferencedState); currentState.setNextStateOnFail(nextStateOnFail); finishInstruction(); } } } } } } }
0008b7c0-bbea-44ba-b2c1-0853eea2a21e
5
private ArrayList<ArrayList<E>> getPossibleCombos(List<Node> nodes) { ArrayList<ArrayList<E>> toReturn = new ArrayList<ArrayList<E>>(); for (Node n : nodes.get(nodes.size() - 1)) { ArrayList<Node> newFoundTiles = new ArrayList<Node>(); for (int i = 0; i < nodes.size(); i++) newFoundTiles.add(nodes.get(i)); newFoundTiles.add(n); if (n.isEmpty()) { ArrayList<E> toAdd = new ArrayList<E>(); for (Node nf : newFoundTiles) { toAdd.add(nf.getElement()); } toReturn.add(toAdd); } for (ArrayList<E> s : getPossibleCombos(newFoundTiles)) { toReturn.add(s); } } return toReturn; }
c2afe1b1-5ffe-47e1-875b-500b919f51b3
0
public double getX(){ return x; }
1e0eea1b-b7f8-4dfc-99e2-902a67302545
6
public static void run(RobotController myRC) { rc = myRC; RobotType t = rc.getType(); try { if (t == RobotType.SOLDIER) { Soldier.soldierCode(rc); } else if(t == RobotType.HQ) { HQ.hqCode(rc); } else if(t == RobotType.GENERATOR || t == RobotType.SUPPLIER) { Supplier.supplierCode(rc); } else { while(true) { rc.yield(); } } } catch (Exception e) { System.out.println("caught exception before it killed us:"); e.printStackTrace(); } }
ca5b0780-50ee-4a63-89cd-1b3692a3c80b
4
public void sort1(List<Integer> list) { if (list.size() < 2) return; int count = 0; // double for-loop and both are related with variable "end" // O(n^2) int end = list.size(); boolean swapped; do { swapped = false; for (int idx = 0; idx < end - 1; ++idx) { int left = list.get(idx); int right = list.get(idx + 1); if (left > right) { list.set(idx + 1, left); list.set(idx, right); swapped = true; } ++count; // loop time } } while (swapped); LH_.checkNaive(list); System.out.println("Looped " + count + " times"); }
3d226ed9-b6ca-41e7-80bb-c81a0c609697
7
public static void startupGuiServerApi() { { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/POWERLOOM-SERVER/GUI-SERVER", Stella.$STARTUP_TIME_PHASE$ > 1)); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); if (Stella.currentStartupTimePhaseP(2)) { _StartupGuiServerApi.helpStartupGuiServerApi1(); } if (Stella.currentStartupTimePhaseP(4)) { GuiServer.$SERVER_DISPATCH_TABLE$ = StringHashTable.newStringHashTable(); } if (Stella.currentStartupTimePhaseP(6)) { Stella.finalizeClasses(); } if (Stella.currentStartupTimePhaseP(7)) { _StartupGuiServerApi.helpStartupGuiServerApi2(); _StartupGuiServerApi.helpStartupGuiServerApi3(); _StartupGuiServerApi.helpStartupGuiServerApi4(); Stella.defineFunctionObject("TEST-SERVER-GET-EXPLANATION-FOR-QUERY", "(DEFUN (TEST-SERVER-GET-EXPLANATION-FOR-QUERY |PLString|) ())", Native.find_java_method("edu.isi.powerloom.server.gui.GuiServer", "testServerGetExplanationForQuery", new java.lang.Class [] {}), null); Stella.defineFunctionObject("TEST-SERVER-GET-INFO", "(DEFUN (TEST-SERVER-GET-INFO |PLServerInfo|) ())", Native.find_java_method("edu.isi.powerloom.server.gui.GuiServer", "testServerGetInfo", new java.lang.Class [] {}), null); Stella.defineFunctionObject("STARTUP-GUI-SERVER-API", "(DEFUN STARTUP-GUI-SERVER-API () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.server.gui._StartupGuiServerApi", "startupGuiServerApi", new java.lang.Class [] {}), null); { MethodSlot function = Symbol.lookupFunction(GuiServer.SYM_GUI_SERVER_STARTUP_GUI_SERVER_API); KeyValueList.setDynamicSlotValue(function.dynamicSlots, GuiServer.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupGuiServerApi"), Stella.NULL_STRING_WRAPPER); } } if (Stella.currentStartupTimePhaseP(8)) { Stella.finalizeSlots(); Stella.cleanupUnfinalizedClasses(); } if (Stella.currentStartupTimePhaseP(9)) { Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("GUI-SERVER"))))); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *ALLOW-REMOTE-FILEBROWSING* BOOLEAN FALSE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *SERVER-LOG-FILE* STRING \"PL:logs;powerloom-server.log\")"); Stella.setLoggingParameters("PL-Server", Cons.cons(GuiServer.KWD_LOG_LEVELS, Cons.cons(Stella.getQuotedTree("((:NONE :LOW :MEDIUM :HIGH) \"/POWERLOOM-SERVER/GUI-SERVER\")", "/POWERLOOM-SERVER/GUI-SERVER"), Cons.cons(GuiServer.KWD_LEVEL, Cons.cons(((Logic.$POWERLOOM_EXECUTION_MODE$ == GuiServer.KWD_DEVELOPMENT) ? GuiServer.KWD_HIGH : GuiServer.KWD_LOW), Cons.cons(GuiServer.KWD_PREFIX, Cons.cons(StringWrapper.wrapString("PL-Server"), Cons.cons(GuiServer.KWD_MAX_WIDTH, Cons.cons(IntegerWrapper.wrapInteger(2000), Cons.cons(GuiServer.KWD_STREAM, Cons.cons(StringWrapper.wrapString(GuiServer.$SERVER_LOG_FILE$), Stella.NIL))))))))))); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *QUERY-SESSION-TIMEOUT* INTEGER 86400)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *KB-FILENAME-INDEX* STRING \"PL:kbs;kbs.ste\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *KB-DIRECTORY* STRING \"PL:kbs;\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *DEFAULT-KB-DIRECTORY* STRING \"/nfs/topaz/melz/\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *SERVER-DISPATCH-TABLE* (STRING-HASH-TABLE OF STRING FUNCTION-CODE-WRAPPER) (NEW (STRING-HASH-TABLE OF STRING FUNCTION-CODE-WRAPPER)) :DOCUMENTATION \"Hash Table for used for dispatching server API methods.\")"); GuiServer.initializeDispatchTable(); } } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } }
82ca0776-e783-40bf-916e-1248fae8fc6f
0
public static String getJdbcString() { return "jdbc:postgresql://" + host + ":" + port + "/" + database; }
9416ed3d-347e-4231-ae12-7ee3cc7cfe21
7
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final MOB target=this.getTarget(mob,commands,givenTarget); if(target==null) return false; if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSK_MALICIOUS_MOVE|CMMsg.TYP_PARALYZE|(auto?CMMsg.MASK_ALWAYS:0),auto?"":L("^S<S-NAME> paralyze(s) <T-NAMESELF>.^?")); if(target.location().okMessage(target,msg)) { target.location().send(target,msg); if(msg.value()<=0) { success=maliciousAffect(mob,target,asLevel,5,-1)!=null; mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> can't move!")); } } } else return maliciousFizzle(mob,target,L("<S-NAME> attempt(s) to paralyze <T-NAMESELF>, but fail(s)!")); // return whether it worked return success; }
20e4a1e8-be0a-4c7f-bef9-b5345e474bec
2
public void calculate_pcm_samples(Obuffer buffer) { compute_new_v(); compute_pcm_samples(buffer); actual_write_pos = (actual_write_pos + 1) & 0xf; actual_v = (actual_v == v1) ? v2 : v1; // initialize samples[]: //for (register float *floatp = samples + 32; floatp > samples; ) // *--floatp = 0.0f; // MDM: this may not be necessary. The Layer III decoder always // outputs 32 subband samples, but I haven't checked layer I & II. for (int p=0;p<32;p++) samples[p] = 0.0f; }
d566dcf4-b9e2-4f41-b116-60fd359c8c8d
1
private void processMoveFromAcePile(MouseEvent e) { int index = (int) (e.getY() / (CARD_Y_GAP + CARD_HEIGHT)); if (index < 4) { activeMove = new CardMoveImpl(index, CardMoveImpl.MOVE_TYPE_FROM.FROM_ACE_PILES); } }
2aa59d28-3b3e-4576-9d9d-ccbb3fc6d86c
3
public static byte[] gzip(String input) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzos = null; try { gzos = new GZIPOutputStream(baos); gzos.write(input.getBytes("UTF-8")); } catch (IOException e) { e.printStackTrace(); } finally { if (gzos != null) try { gzos.close(); } catch (IOException ignore) { } } return baos.toByteArray(); }
c7ade068-2830-43b0-aa5a-76c69410d28f
2
public static void debug(int level, String format, Object... args) { if (level > 0 && level <= _messageLevel) { System.err.printf(format, args); System.err.println(); } }
4d029f0f-136b-4395-8858-cd2d058c41be
4
private void createViewPanel() { viewContent.removeAll(); JPanel viewPanel = new JPanel(); viewPanel.setBorder(BorderFactory.createTitledBorder("View")); viewPanel.setLayout(new BoxLayout(viewPanel, BoxLayout.Y_AXIS)); viewContent.add(viewPanel, JLayeredPane.DEFAULT_LAYER); JButton viewPanelMinimizeButton; if(appConfig.guiControlPanelShowFullViewPanel) { viewPanelMinimizeButton = createFrameworkIconButton("minimizeView", "minimize.gif", "Minimize"); } else { viewPanelMinimizeButton = createFrameworkIconButton("maximizeView", "maximize.gif", "Maximize"); } viewPanelMinimizeButton.setPreferredSize(new Dimension(21, 11)); viewContent.add(viewPanelMinimizeButton, JLayeredPane.PALETTE_LAYER); viewPanelMinimizeButton.setBounds(controlPanelWidth - 26, 3, 21, 11); addToDisabledButtonList(viewPanelMinimizeButton); // disable while simulating // .... add zoom view if(appConfig.guiControlPanelShowFullViewPanel) { if(parent.getTransformator().supportReverseTranslation()) { // only show the coordinate if it can be mapped from GUI to logic coordinates JPanel mousePos = new JPanel(); JLabel mousePosLabel = new JLabel("Mouse Position:"); mousePosLabel.setFont(mousePositionField.getFont()); mousePos.add(mousePosLabel); mousePos.add(mousePositionField); mousePositionField.setText(""); mousePositionField.setEditable(false); mousePositionField.setBorder(BorderFactory.createEmptyBorder()); viewPanel.add(mousePos); } zoomPanel = new ZoomPanel(parent, parent.getTransformator()); zoomPanel.setPreferredSize(new Dimension(controlPanelWidth, zoomPanel.getPreferredHeight(controlPanelWidth))); viewPanel.add(zoomPanel); } JPanel buttonPanel = new JPanel(); FlowLayout buttonLayout = new FlowLayout(FlowLayout.CENTER, 2, 0); buttonPanel.setLayout(buttonLayout); // create the buttons JButton button = createFrameworkIconButton("zoomIn", "zoominimage.png", "Zoom In"); buttonPanel.add(button); addToDisabledButtonList(button); button = createFrameworkIconButton("zoomOut", "zoomoutimage.png", "Zoom Out"); buttonPanel.add(button); addToDisabledButtonList(button); button = createFrameworkIconButton("zoomToFit", "zoomtofit.gif", "Zoom To Fit"); buttonPanel.add(button); addToDisabledButtonList(button); if(parent.getTransformator() instanceof Transformation3D) { button = createFrameworkIconButton("zoomToFit3D", "zoomtofit3d.gif", "Default View"); buttonPanel.add(button); addToDisabledButtonList(button); } viewPanel.add(buttonPanel); // Finally set the size of the viewPanel Dimension dim = viewPanel.getPreferredSize(); viewPanel.setBounds(0, 0, controlPanelWidth, dim.height); viewContent.setPreferredSize(dim); }
c59dbcad-8997-418b-940e-9da1c8c2d24e
7
public void paint(Component component, Graphics g, int x, int y, int width, int height, Direction direction, boolean horizontalFlip, boolean verticalFlip) { Color xc = null; g.setColor(color.getColor(component)); if (xorColor != null) { xc = xorColor.getColor(component); if (xc != null) g.setXORMode(xc); } Insets i = InsetsUtil.rotate(direction, new Insets(verticalFlip ? insets.bottom : insets.top, horizontalFlip ? insets.right : insets.left, verticalFlip ? insets.top : insets.bottom, horizontalFlip ? insets.left : insets.right)); g.fillRect(x + i.left, y, width - i.left - i.right, i.top); g.fillRect(x + i.left, y + height - i.bottom, width - i.left - i.right, i.bottom); g.fillRect(x, y, i.left, height); g.fillRect(x + width - i.right, y, i.right, height); if (xc != null) g.setPaintMode(); }
1726c73c-6b94-4aff-a818-d79ba4003e79
6
public void infoFile(){ try{ if( file.exists() ){ System.out.println("Ver Nombre: " + file.getName()); System.out.println("Ver Path: " + file.getPath()); System.out.println("Ver Absoluta: " + file.getAbsolutePath()); if( file.isFile() ) System.out.println("<==ES UN ARCHIVO==>"); else if( file.isDirectory()) System.out.println("<== ES DIRECTORIO ==>"); if( file.isHidden() ) System.out.println("ESTA OCULTO"); if( file.isAbsolute() ) System.out.println("Direccion Absoluta"); else System.out.println("Direccion Abstracta"); System.out.println("BYTES: " + file.length()); System.out.println("Ultima fecha de Modif: " + new Date(file.lastModified()) ); } else System.out.println("DIRECCION NO EXISTE"); } catch(NullPointerException e){ System.out.println("COnfigure el archivo primero"); } }
cbb4d057-cfe9-48d9-83de-2b0b74d8a6fc
8
public int recurSearch(int[] A, int target, int start, int end){ if(start == end && A[start] == target) return start; if(start > end) return -1; int center = (start + end)/2; if(A[center] >= A[start]){ if(A[start] <= target && target <= A[center]){ return recurSearch(A, target, start, center); }else { return recurSearch(A, target, center+1, end); } }else{ if(A[center] <= target && target <= A[end]){ return recurSearch(A, target, center, end); }else { return recurSearch(A, target, start, center-1); } } }
0542ce79-91e9-4449-a413-28c3cef2f457
1
@SuppressWarnings("unchecked") public Book combineBooks(String newBookName, Book... books) { List<Contact> contacts = Lists.newArrayList(); for (Book book : books) { contacts = ListUtils.sum(contacts, book.getListOfAllContacts()); } return new Book(newBookName, contacts); }
f2f7a198-6c8e-4c9b-8a55-1c034fc08416
3
public Menu(HtmlMidNode parent, HtmlAttributeToken[] attrs){ super(parent, attrs); for(HtmlAttributeToken attr:attrs){ String v = attr.getAttrValue(); switch(attr.getAttrName()){ case "label": label = Label.parse(this, v); break; case "type": type = Type.parse(this, v); break; } } }
b8ee5219-6e7f-41c5-961b-2d5f7627ea41
9
private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed try { parameter.setName(txfName.getText()); } catch (CantSetException e) {} try { parameter.setDescription(txfDescription.getText()); } catch (CantSetException e) {} try { parameter.setYear((int)spnYear.getValue()); } catch (CantSetException e) {} try { parameter.setMonth((int)spnMonth.getValue()); } catch (CantSetException e) {} try { parameter.setDay((int)spnDay.getValue()); } catch (CantSetException e) {} try { parameter.setHour((int)spnHour.getValue()); } catch (CantSetException e) {} try { parameter.setMinute((int)spnMinute.getValue()); } catch (CantSetException e) {} try { parameter.setPrefix((String)cbxPrefix.getSelectedItem()); } catch (CantSetException e) {} try { parameter.setSuffix((String)cbxSuffix.getSelectedItem()); } catch (CantSetException e) {} dispose(); }//GEN-LAST:event_btnOKActionPerformed
7ae857d8-834c-4c0a-9893-90c1e3f40676
6
@Override public boolean mutate(Mutation.Type type) { switch (type) { case SWAP: case REPLICATE: return false; case REMOVE: Mutation.replaceExpr(this, expr); return true; case COPY_TREE: return Mutation.copyExprTree(this); case COPY: return unaryCopy(); case CREATE_PARENT: Mutation.createExprParent(this); return true; default: throw new AssertionError(); } }
c7f9d1c5-4bcc-48b8-8aa4-752718e04c14
8
public void paintLineHighlights(Graphics g) { int count = lineHighlights==null ? 0 : lineHighlights.size(); if (count>0) { int docLen = textArea.getDocument().getLength(); Rectangle vr = textArea.getVisibleRect(); int lineHeight = textArea.getLineHeight(); try { for (int i=0; i<count; i++) { LineHighlightInfo lhi =(LineHighlightInfo) lineHighlights.get(i); int offs = lhi.getOffset(); if (offs>=0 && offs<=docLen) { int y = textArea.yForLineContaining(offs); if (y>vr.y-lineHeight) { if (y<vr.y+vr.height) { g.setColor(lhi.getColor()); g.fillRect(0,y, textArea.getWidth(),lineHeight); } else { break; // Out of visible rect } } } } } catch (BadLocationException ble) { // Never happens ble.printStackTrace(); } } }
fb3b181e-43a8-4559-9115-b98dd13d918f
3
private static <T> Map<String, Object> serializeArray(Class<?> type, T[] arr) { Map<String, Object> data = new HashMap<String, Object>(); data.put("T", type.getComponentType().isPrimitive() ? type.getName() : ("[L")); data.put("class", arr.getClass().getComponentType().getName()); data.put("length", arr.length); List<Object> list = new ArrayList<Object>(arr.length); for (Object o : arr) { list.add(serialize(o)); } data.put("data", list); return data; }
6e02df95-1030-4373-ada9-428dea08870b
7
private static ArrayList<Monster> initiative(ArrayList<Monster> monsters, Player p, boolean atRange, boolean faster) { int target = 0; if(atRange) { target = p.getSpeed() + utils.random(0, 7); } else { target = p.getSpeed() + utils.random(-3, 4); } ArrayList<Integer> speeds = new ArrayList<Integer>(); for(int i = 0; i < monsters.size(); i++) { speeds.add(monsters.get(i).getSpeed() + utils.random(-3, 4)); } ArrayList<Monster> returnMonsters = new ArrayList<Monster>(); for(int i = 0; i < speeds.size(); i++) { if(speeds.get(i) >= target && faster) { returnMonsters.add(monsters.get(i)); } if(speeds.get(i) < target && !faster) { returnMonsters.add(monsters.get(i)); } } return returnMonsters; }
837564bf-f5f1-4636-92da-9215520f2405
8
public static void showReportsTable(ResultSet rs, String reportsQuery, String subject) { int numCols; ResultSetMetaData rsmd; JTextArea tableTitle = null; JTable table = null; try { rsmd = rs.getMetaData(); numCols = rsmd.getColumnCount() + 1; String columnNames[] = new String[numCols]; for (int i = 0; i < numCols - 1; i++) { columnNames[i] = rsmd.getColumnName(i + 1); } columnNames[numCols - 1] = "OVERDUE"; // For creating the size of the table PreparedStatement ps1 = Library.con.prepareStatement(reportsQuery); if (subject.isEmpty() == false) { ps1.setString(1, subject); } ps1.executeQuery(); ResultSet count = ps1.getResultSet(); List<String> books = new ArrayList<String>(); while (count.next()) { books.add(count.getString("callNumber")); } // Get current date java.util.Date currentDate = new java.util.Date(); Object data[][] = new Object[books.size()][numCols]; count.close(); String callNumber; int copyNo; Date inDate; Date outDate; String overdue = "NO"; int j = 0; // Fill table while (rs.next()) { callNumber = rs.getString("callNumber"); copyNo = rs.getInt("copyNo"); inDate = rs.getDate("inDate"); outDate = rs.getDate("outDate"); try { if (currentDate.after(inDate)) { overdue = "YES"; } } catch (NullPointerException e) { overdue = "N/A"; } Object tuple[] = { callNumber, copyNo, inDate, outDate, overdue }; data[j] = tuple; j++; overdue = "NO"; } rs.close(); tableTitle = new JTextArea("Checked out Books Report"); table = new JTable(data, columnNames); if (data.length == 0) { new ErrorMessage("No books found."); } table.setEnabled(false); JScrollPane scrollPane = new JScrollPane(table); table.setAutoCreateRowSorter(true); // Display table table.setFillsViewportHeight(true); tablePane.removeAll(); tablePane.updateUI(); tableTitle.setEditable(false); tablePane.add(tableTitle); tablePane.add(scrollPane); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
c9189bc4-7bcd-41aa-a68f-d147e43d1438
3
public String execute() throws Exception { if(addListStore != 0 && addListItem != 0) if(!add()) return "inputError" ; return SUCCESS; }
a96c256b-ab9e-4941-8bbb-7fc7e9fb59b8
3
@Override public FileSequenceWriter createWriter(OutputStream out, OutputStream... out2) { if (out == null || out2 == null || out2.length == 0) throw new IllegalArgumentException( "You must declare two valid input streams"); return new FastaQualitySequenceWriter(out, out2[0]); }
f5cda877-1e1e-4599-bf63-94a688045e42
9
public static NumericDocValues wrap(SortedNumericDocValues sortedNumeric, Type selector, SortField.Type numericType) { if (numericType != SortField.Type.INT && numericType != SortField.Type.LONG && numericType != SortField.Type.FLOAT && numericType != SortField.Type.DOUBLE) { throw new IllegalArgumentException("numericType must be a numeric type"); } final NumericDocValues view; NumericDocValues singleton = DocValues.unwrapSingleton(sortedNumeric); if (singleton != null) { // it's actually single-valued in practice, but indexed as multi-valued, // so just sort on the underlying single-valued dv directly. // regardless of selector type, this optimization is safe! view = singleton; } else { switch(selector) { case MIN: view = new MinValue(sortedNumeric); break; case MAX: view = new MaxValue(sortedNumeric); break; default: throw new AssertionError(); } } // undo the numericutils sortability switch(numericType) { case FLOAT: return new NumericDocValues() { @Override public long get(int docID) { return NumericUtils.sortableFloatBits((int) view.get(docID)); } }; case DOUBLE: return new NumericDocValues() { @Override public long get(int docID) { return NumericUtils.sortableDoubleBits(view.get(docID)); } }; default: return view; } }
de85e255-865b-4311-b03e-b526b18b38d9
5
private void loginAndSaveCookie(){ HttpPost loginpost = new HttpPost(loginUrl); List<NameValuePair> params = null; try { String html = this.GetPageContent(loginUrl); params = getFormParams(html,"htsdeploy@gmail.com","hsbc123456"); } catch (UnsupportedEncodingException e2) { e2.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } // params.add(new BasicNameValuePair("Email", "select.zhenyu.from@gmail.com")); // params.add(new BasicNameValuePair("Passwd", "scholes616")); // params.add(new BasicNameValuePair("PersistentCookie", "yes")); // params.add(new BasicNameValuePair("service", "googleplay")); // params.add(new BasicNameValuePair("continue", "https://play.google.com/store")); // add header loginpost.setHeader("Host", "accounts.google.com"); loginpost.setHeader("User-Agent", USER_AGENT); loginpost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*;q=0.8"); loginpost.setHeader("Accept-Language", "en-US,en;q=0.5"); loginpost.setHeader("Cookie", getCookies()); loginpost.setHeader("Connection", "keep-alive"); loginpost.setHeader("Referer", "https://accounts.google.com/ServiceLoginAuth"); loginpost.setHeader("Content-Type", "application/x-www-form-urlencoded"); try { loginpost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse hr = httpClient.execute(loginpost); System.out.println(hr); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ loginpost.releaseConnection(); } }
10f22e53-7fd9-4085-9882-6ba327657b0a
6
private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed // TODO add your handling code here: String textoCorreo = tfIdCorreo.getText().trim(); if (!textoCorreo.equals("")) { try { if (rbtnCorreo.isSelected()) { correoActual = new RegistraCorreo().getCorreoByNombre(textoCorreo); } else if (rbtnId.isSelected()) { Pattern patron = Pattern.compile("[0-9]+"); if (patron.matcher(textoCorreo).matches()) { correoActual = new RegistraCorreo().getCorreoByID(textoCorreo); } else { JOptionPane.showMessageDialog(this, "Solo se aceptan dígitos como ID", "Escribe números", JOptionPane.WARNING_MESSAGE); } } if (correoActual != null) { this.habilitarEdicion(); tfCorreo.setText(correoActual.getNombre()); selectOrigen.setSelectedItem(correoActual.getOrigen().getNombre()); selectGrupo.setSelectedItem(correoActual.getGrupo().getNombre()); cbxHabilitado.setSelected(correoActual.isHabilitado()); } else { JOptionPane.showMessageDialog(this, "No se encontraron resulados", "No existe correo", JOptionPane.WARNING_MESSAGE); } } catch (SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { Logger.getLogger(VistaEditar.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(this, "Error: " + ex, "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Escriba un ID o correo", "Campo vacío", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_btnBuscarActionPerformed
3c8493de-8a22-426f-aed8-515c467c578a
5
public static void main(String argv[]) { if (argv.length == 0) { System.out.println("Usage : java MyScanner <inputfile>"); } else { for (int i = 0; i < argv.length; i++) { String fileName = null; try { fileName = argv[i]; Parser parser = new Parser(new Scanner(new java.io.FileReader(fileName)), fileName); AbstractNode abstractTree = parser.parse(); SymbolTable syms = new SymbolTable(); System.out.println(abstractTree); System.out.println(abstractTree.compile(syms)); System.out.println(syms); PrintWriter w = new PrintWriter("codetxt"); w.print(abstractTree.code()); w.close(); } catch (java.io.FileNotFoundException e) { System.err.println("File not found : \"" + fileName + "\""); } catch (ParserException e) { System.err.println(e); } catch (Exception e) { System.err.println("Unexpected exception:"); e.printStackTrace(); } } } }
1144f4d3-b0f9-44e2-89d5-88f2109887b9
7
public int _offsetToX(int line, int offset) { TokenMarker tokenMarker = getTokenMarker(); /* Use painter's cached info for speed */ FontMetrics fm = painter.getFontMetrics(); getLineText(line,lineSegment); int segmentOffset = lineSegment.offset; int x = horizontalOffset; /* If syntax coloring is disabled, do simple translation */ if(tokenMarker == null) { lineSegment.count = offset; return x + Utilities.getTabbedTextWidth(lineSegment, fm,x,painter,0); } /* If syntax coloring is enabled, we have to do this because * tokens can vary in width */ else { Token tokens; if(painter.currentLineIndex == line && painter.currentLineTokens != null) tokens = painter.currentLineTokens; else { painter.currentLineIndex = line; tokens = painter.currentLineTokens = tokenMarker.markTokens(lineSegment,line); } Toolkit toolkit = painter.getToolkit(); Font defaultFont = painter.getFont(); SyntaxStyle[] styles = painter.getStyles(); for(;;) { byte id = tokens.id; if(id == Token.END) { return x; } if(id == Token.NULL) fm = painter.getFontMetrics(); else fm = styles[id].getFontMetrics(defaultFont); int length = tokens.length; if(offset + segmentOffset < lineSegment.offset + length) { lineSegment.count = offset - (lineSegment.offset - segmentOffset); return x + Utilities.getTabbedTextWidth( lineSegment,fm,x,painter,0); } else { lineSegment.count = length; x += Utilities.getTabbedTextWidth( lineSegment,fm,x,painter,0); lineSegment.offset += length; } tokens = tokens.next; } } }
2f1da820-305b-4acb-95bd-c929b6c503c3
8
@Override public int writeString(String encoding, String val, int length) throws IOException { Charset charset = Charset.forName(encoding); CharsetEncoder enc = charset.newEncoder(); CharBuffer bin = CharBuffer.allocate(1); ByteBuffer bout = ByteBuffer.allocate(8); int len = 0; for (int i = 0; i < ((length > 0) ? length : val.length()); i++) { bin.put(val.charAt(i)); bin.rewind(); CoderResult res = enc.encode(bin, bout, false); if (res != CoderResult.UNDERFLOW) throw new IOException("Error while writing string"); int bytesize = bout.position(); len += bytesize; for (int j = 0; j < bytesize; j++) file.writeByte(bout.get(j)); bin.clear(); bout.clear(); } if (length == 0 || val.length() < length) { bin.put('\0'); bin.rewind(); CoderResult res = enc.encode(bin, bout, false); if (res != CoderResult.UNDERFLOW) throw new IOException("Error while writing string"); int bytesize = bout.position(); len += bytesize; for (int j = 0; j < bytesize; j++) file.writeByte(bout.get(j)); } return len; }
14918fc8-a8d0-4e68-8653-a2fc91da1f33
0
public static Animation bulletAnimationLeft(){ Animation anim = new Animation(); anim.addFrame(loadImage("bullet1.png"), 50); anim.addFrame(loadImage("bullet2.png"), 50); anim.addFrame(loadImage("bullet3.png"), 50); return anim; }
4aca9a79-a082-4692-aa14-e4b00b2b2b20
1
public String readLine() throws IOException { if (_acceptable) { throw new IOException("You must call the accept() method of the DccChat request before you can use it."); } return _reader.readLine(); }
964082b1-39ba-4df1-be33-bd72561885fc
2
private String getSessionId(URLConnection con){ for(String data:con.getHeaderFields().get("Set-Cookie")){ if(data.indexOf("JSESSIONID")!=-1){ return data.substring(0,data.indexOf(";")); } } return null; }
219857bb-81e7-4925-86c4-7f3643dda00f
2
public static boolean areTerminalsOnRHS(Production production) { String rhs = production.getRHS(); for (int k = 0; k < rhs.length(); k++) { char ch = rhs.charAt(k); if (isTerminal(ch)) return true; } return false; }
ece02f96-551a-4edd-94d9-2bcfaeab5683
1
public void DrawGameOver(Graphics2D g2d, Point mousePosition, long gameTime) { Draw(g2d, mousePosition); //draws the text to restart //g2d.drawString("Press space or enter to restart.", Framework.frameWidth / 2 - 100, Framework.frameHeight / 3 + 70); //draw text to say whether you won or lost if (playerCar.raceWin) { g2d.drawString("You have successfully won the race!", Framework.frameWidth / 2 - 100, Framework.frameHeight / 3); g2d.drawString("You have won in " + gameTime / Framework.secInNanosec + " seconds.", Framework.frameWidth / 2 - 100, Framework.frameHeight / 3 + 20); } else { g2d.setColor(Color.red); g2d.drawString("You have crashed the car!", Framework.frameWidth / 2 - 95, Framework.frameHeight / 3); g2d.drawImage(redBorderImg, 0, 0, Framework.frameWidth, Framework.frameHeight, null); } }
1b7a832e-4d98-4f66-a112-596e2bbf1deb
2
public String toString() { if (id != null) { if (dataId > 0) { return id.toString() + ":" + dataId; } return id.toString(); } return name; }
276cb579-2779-407b-afd4-4bbf88c05bde
9
public synchronized ZePlayoutElement<E> get() { /* sample current absolute time. */ now = playoutToSystem(); leftInterval = now-playoutHalfPer; rightInterval = now+playoutHalfPer; /* sample it once from the master and use * the same value for the whole playout request * to avoid inconsistencies (mpo can be changed by * the master at any time) */ long mpo = master.mpo; //System.out.println(Long.toString(mpo+first().wallclock)+ // " interval:"+Long.toString(leftInterval)+":"+Long.toString(rightInterval)); while ( !isEmpty() ) { if ((first().wallclock+mpo) < leftInterval) { E s = pollFirst(); System.out.println(Long.toString(mpo+s.wallclock)+ " interval:"+Long.toString(leftInterval)+":"+Long.toString(rightInterval)+" -> "+ "late skipped from sensor "+s.sensorId); skipped++; if (s.duplicate) duplicatesSkipped++; } else if ( (first().wallclock+mpo) >= leftInterval && (first().wallclock+mpo) <= rightInterval ) { resetHoldCount(); current = pollFirst(); ZePlayoutElement<E> elem = new ZePlayoutElement<E>(); elem.element = current; elem.meaning = Registry.PLAYOUT_VALID; System.out.println(Long.toString(mpo+current.wallclock)+ " interval:"+Long.toString(leftInterval)+":"+Long.toString(rightInterval)+" -> "+ "played from sensor "+current.sensorId); played++; return elem; } else { //samples to be played in the future is at queue head if (current != null) { //playout started if (now < current.expiry+mpo) { //current not expired //current still valid: hold it holdcount++; ZePlayoutElement<E> elem = new ZePlayoutElement<E>(); elem.element = null; elem.meaning = Registry.PLAYOUT_HOLD; return elem; } else { resetHoldCount(); ZePlayoutElement<E> elem = new ZePlayoutElement<E>(); elem.element = null; elem.meaning = Registry.PLAYOUT_INVALID; return elem; } } else { //System.out.println("Giving invalidate"); resetHoldCount(); ZePlayoutElement<E> elem = new ZePlayoutElement<E>(); elem.element = null; elem.meaning = Registry.PLAYOUT_INVALID; return elem; } } } //nothing found in the queue if (current != null) { //playout started if (now < current.expiry+mpo) { //current not expired //found empty but current still valid: holding holdcount++; ZePlayoutElement<E> elem = new ZePlayoutElement<E>(); elem.element = null; elem.meaning = Registry.PLAYOUT_HOLD; return elem; } else { //found empty and current expired: underflow underflowCount++; ZePlayoutElement<E> elem = new ZePlayoutElement<E>(); elem.element = null; elem.meaning = Registry.PLAYOUT_INVALID; return elem; } } //Found empty but playout not yet started ZePlayoutElement<E> elem = new ZePlayoutElement<E>(); elem.element = null; elem.meaning = Registry.PLAYOUT_NOTSTARTED; return elem; }
62b9b369-588b-42b8-8685-4fbaed07b5eb
8
@Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ if (cmd.getName().equalsIgnoreCase("getmute")){ if (args.length <= 0) { sender.sendMessage(Msg.$("getmute-usage")); return true; } MuteManager.getMute(sender, args[0]); } else if (cmd.getName().equalsIgnoreCase("mymute")){ if (sender instanceof Player){ Player p = (Player) sender; MuteManager.getMute(sender, p.getName()); } else sender.sendMessage("Only player can access this command!"); } else if (cmd.getName().equalsIgnoreCase("reloadmute")){ if (Access.canReload(sender)) { try { config.load(configFile); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (InvalidConfigurationException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } Msg.setupMsg(getDataFolder()); MuteManager.setupMuteManager(getDataFolder()); Swear.setupSwear(getDataFolder(), this); sender.sendMessage(Msg.$("reloaded")); } else { sender.sendMessage(Msg.$("not-permitted")); } } return true; }
28301c56-81a8-486d-a90f-ca9f75375d47
8
public TheDocument(String htmlFile) { file = new File(htmlFile); isWrapped = false; isIndented = true; isSaved = true; setFilepath(htmlFile); reader = new DocumentReader(); care = new DocCaretaker(); if(!file.exists()){ try { domDoc = reader.newDocument(file); } catch (IOException e) { System.out.println("Cannot create new file."); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block isWellFormed = false; e.printStackTrace(); } } else{ //Testing stream try{ domDoc = reader.buildDocument(file); tree = reader.buildTree(domDoc); }catch(Exception e){ this.isWellFormed = false; } } FileInputStream stream = null; MappedByteBuffer bb = null; try { stream = new FileInputStream(file); FileChannel fc = stream.getChannel(); bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); if(this.isWellFormed()){ xml = reader.parseAndPretty(Charset.defaultCharset().decode(bb).toString(),"2"); } else{ xml = Charset.defaultCharset().decode(bb).toString(); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e){ isWellFormed = false; } finally { try { stream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.createMomento(); care.storeState(momento); }
b3606ed8-329b-4940-88da-8d47e7bca4dd
5
public void chooseOption() { switch (cursorLoc) { case 1: game.startSetup(); break; case 2: break; case 3: try { java.awt.Desktop.getDesktop().browse( new URI("http://www.signalytical.com/")); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } break; } }
874ee483-8932-43d2-afbd-ec6797a6c7a4
9
@Override public List<Map<String, ?>> List_Plazo(String tipo) { List<Map<String, ?>> lista = new ArrayList<Map<String, ?>>(); try { this.conn = FactoryConnectionDB.open(FactoryConnectionDB.ORACLE); String sql = ""; sql +="select id_plazo,no_plazo,det_alerta ,to_char(fe_desde,'dd-mm-yyyy') as fe_desde ," + " to_char(fe_hasta,'dd-mm-yyyy') as fe_hasta,TO_CHAR(fe_hasta,'MONTH','nls_date_language=spanish') as mes," + " sysdate+CA_DIAS_TOLERANCIA as fe_tol, CA_DIAS_TOLERANCIA from rhtr_plazo where es_plazo ='1' " + " and id_requerimiento='0' and SYSDATE BETWEEN FE_DESDE AND FE_HASTA+1 "; switch (tipo) { case "1": sql += " and ti_plazo='1'"; break; case "2": sql += " and ti_plazo='2'"; break; } ResultSet rs = this.conn.query(sql); while (rs.next()) { Map<String, Object> rec = new HashMap<String, Object>(); rec.put("id", rs.getString("id_plazo")); rec.put("nom", rs.getString("no_plazo")); rec.put("det", rs.getString("DET_ALERTA")); rec.put("desde", rs.getString("FE_DESDE")); rec.put("hasta", rs.getString("FE_HASTA")); rec.put("mes", rs.getString("mes")); rec.put("dias_tol", rs.getString("CA_DIAS_TOLERANCIA")); rec.put("fe_tol", rs.getString("fe_tol")); lista.add(rec); } rs.close(); } catch (SQLException e) { throw new RuntimeException(e.getMessage()); } catch (Exception e) { throw new RuntimeException("ERROR"); } finally { try { this.conn.close(); } catch (Exception e) { } } return lista; }
5a4aa8c6-0829-4563-8110-6af8a0900d2d
7
public NoAddReason getNoAddReason(Locatable locatable) { Unit unit = (locatable instanceof Unit) ? (Unit)locatable : null; return (unit == null) ? NoAddReason.WRONG_TYPE : (units == null) ? NoAddReason.CAPACITY_EXCEEDED : (!isEmpty() && units.get(0).getOwner() != unit.getOwner()) ? NoAddReason.OCCUPIED_BY_ENEMY : (contains(unit)) ? NoAddReason.ALREADY_PRESENT : (unit.getSpaceTaken() + getSpaceTaken() > getUnitCapacity()) ? NoAddReason.CAPACITY_EXCEEDED : NoAddReason.NONE; }
c4ef59cf-8d88-4efa-ac6c-22bbc01fb97d
8
public String[][][] getLog(String mode, String sv) throws IOException { String storeAccess = null; String storeAccessUpdate = null; if (mode.equals("past")) { storeAccess = "text"; storeAccessUpdate = "past_update"; } else if (mode.equals("ranking")) { storeAccess = "rank"; storeAccessUpdate = "rank_update"; } else if (mode.equals("pair")) { storeAccess = "pair"; storeAccessUpdate = "pair_update"; } URL url1 = new URL("http://" + sv + ".appspot.com/" + mode + "?mokyu=true"); HTTPRequest request1 = new HTTPRequest(url1, HTTPMethod.GET, Builder .disallowTruncate().setDeadline(15.0)); HTTPResponse http_response1 = URLFetchServiceFactory .getURLFetchService().fetch(request1); String content1 = new String(http_response1.getContent(), "utf-8"); DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Entity past = null; try { past = datastore .get(KeyFactory.createKey("past_string", "onlyOne")); } catch (EntityNotFoundException e) { } String content2 = ((Text) past.getProperty(storeAccess)).getValue() + "<>" + (String) past.getProperty(storeAccessUpdate); String[][] log_box = new String[2][2]; log_box[0] = content1.split("<>"); log_box[1] = content2.split("<>"); if (log_box[0][0].isEmpty() || log_box[0][1].isEmpty() || log_box[1][0].isEmpty() || log_box[1][1].isEmpty()) throw new IOException(); String[][][] sp_log_box = new String[2][2][]; sp_log_box[0][0] = log_box[0][0].split(","); sp_log_box[1][0] = log_box[1][0].split(","); sp_log_box[0][1] = log_box[0][1].split(","); sp_log_box[1][1] = log_box[1][1].split(","); return sp_log_box; }
b37ebd67-929a-45c6-8540-ae8e902dcd47
2
public void onMouseEvent() { if (Mouse.hasWheel() && Mouse.isButtonDown(0)) { int angleZ = -Mouse.getDX(); double teta = Math.toRadians(angleZ); double xprime = (this.position.getPositionX() * Math.cos(teta)) + (this.position.getPositionY() * Math.sin(teta)); double yprime = (-this.position.getPositionX() * Math.sin(teta)) + (this.position.getPositionY() * Math.cos(teta)); this.position.setPositionX((float) xprime); this.position.setPositionY((float) yprime); int angleX = Mouse.getDY(); double teta2 = Math.toRadians(angleX); double ysec = (this.position.getPositionY() * Math.cos(teta2)) + (this.position.getPositionZ() * Math.sin(teta2)); double zsec = (-this.position.getPositionY() * Math.sin(teta2)) + (this.position.getPositionZ() * Math.cos(teta2)); this.position.setPositionY((float) ysec); this.position.setPositionZ((float) zsec); } }
20edcf1a-ad58-460f-8f5d-d3ef98b50543
2
@Override public void writeValue(NBTOutputStream output) throws IOException { int len = this.size(); for (int i = 0; i < len; i++) { NamedBinaryTag value = this.getTag(i); if (value != null) { output.writeNBT(value); } } output.writeEnd(); }
49385082-4333-457c-923d-2d70733485cf
4
public String getMimeType() { if (format >= 0 && format < MIME_TYPE_STRINGS.length) { if (format == FORMAT_JPEG && progressive) { return "image/pjpeg"; } return MIME_TYPE_STRINGS[format]; } else { return null; } }
597cd698-b6ec-4474-b5e6-4b251604814f
9
private boolean decode5(ByteArrayOutputStream baos) throws PDFParseException { // stream ends in ~> int[] five = new int[5]; int i; for (i = 0; i < 5; i++) { five[i] = nextChar(); if (five[i] == '~') { if (nextChar() == '>') { break; } else { throw new PDFParseException("Bad character in ASCII85Decode: not ~>"); } } else if (five[i] >= '!' && five[i] <= 'u') { five[i] -= '!'; } else if (five[i] == 'z') { if (i == 0) { five[i] = 0; i = 4; } else { throw new PDFParseException("Inappropriate 'z' in ASCII85Decode"); } } else { throw new PDFParseException("Bad character in ASCII85Decode: " + five[i] + " (" + (char) five[i] + ")"); } } if (i > 0) { i -= 1; } int value = five[0] * 85 * 85 * 85 * 85 + five[1] * 85 * 85 * 85 + five[2] * 85 * 85 + five[3] * 85 + five[4]; for (int j = 0; j < i; j++) { int shift = 8 * (3 - j); baos.write((byte) ((value >> shift) & 0xff)); } return (i == 4); }
110d63c0-99d9-44e0-9f51-7affdb54d8d9
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(DisAppFAQ.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(DisAppFAQ.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(DisAppFAQ.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(DisAppFAQ.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 DisAppFAQ().setVisible(true); } }); }
8e0711b8-dce4-474c-8083-3d466ce88cb1
3
private float limit(float eq) { if (eq==BAND_NOT_PRESENT) return eq; if (eq > 1.0f) return 1.0f; if (eq < -1.0f) return -1.0f; return eq; }
fff41e4d-f963-4530-b191-54eafa4eaa75
1
List<Position> getPositions() { final List<Position> parts = new ArrayList<Position>(); for (LightTrailPart part : lightTrail) parts.add(player.getGrid().getElementPosition(part)); return parts; }
46aad0be-2445-4330-a438-7a5a6482df59
1
private boolean isLowPriorityOperator(String o) { return o.equals(OPERATION_MINUS) || o.equals(OPERATION_PLUS); }
8ad9397b-a290-4630-a557-a40a19068049
8
private void saveCheck(final String address) { int opt = -1; if (saveReminder != null && saveReminder.isChanged()) { opt = isRemote() ? JOptionPane.NO_OPTION : saveReminder.showConfirmDialog(this, FileUtilities.getFileName(pageAddress)); } boolean readAction = true; switch (opt) { case JOptionPane.YES_OPTION: // save page first and continue to load new page SaveComponentStateReminder.setEnabled(false); savePage(false, address); readAction = false; break; case JOptionPane.CANCEL_OPTION: // cancel this action readAction = false; if (navigator != null) { if (pageAddress.equals("Untitled.cml")) { navigator.storeLocation(UNKNOWN_LOCATION); } else { navigator.storeLocation(pageAddress); } } break; } if (readAction) { readPageWithThread(address); } requestFocusInWindow(); }
4ebaa1c9-2e3f-4d54-9503-a71cebc8bc22
2
public Merchant(int reg_num) { SQLiteJDBC db = new SQLiteJDBC(); String sql = String.format("SELECT * FROM merchants WHERE reg_num ='%d'", reg_num); ResultSet resultSet = db.query(sql); try { if(resultSet.next()) { this.reg_num = resultSet.getInt("reg_num"); this.branch_num = resultSet.getInt("branch_num"); this.email = resultSet.getString("email"); this.merchant_name = resultSet.getString("merchant_name"); this.phone = resultSet.getString("phone_number"); this.address = resultSet.getString("address"); } db.close(); }catch(Exception e) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } }
8001a500-7f37-41de-b8de-4451724d5579
5
static final void method2947(boolean bool, int i, int i_4_, int i_5_, int i_6_, int i_7_) { anInt6837++; if (bool != true) method2950(121); if ((((Class348_Sub51) BitmapTable.aClass348_Sub51_3959) .aClass239_Sub26_7272.method1838(-32350) ^ 0xffffffff) != -1 && i_5_ != 0 && Message.anInt2021 < 50 && i_4_ != -1) Class258_Sub2.aClass10Array8531[Message.anInt2021++] = new Class10((byte) 1, i_4_, i_5_, i_6_, i, 0, i_7_, null); }
97f6b92e-a180-45f5-9d44-438a507f72c8
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Sales)) { return false; } Sales other = (Sales) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
6651404c-9509-4869-83ef-5b539ac5cb8e
4
private static Path getOutputModuleFile(CommandLine line) throws IOException { if (!line.hasOption(OUTPUT_MODEL)) { return null; } String outputPathName = line.getOptionValue(OUTPUT_MODEL); Path outputPath = Paths.get(outputPathName); if (!Files.exists(outputPath)) { Files.createDirectories(outputPath); } if (Files.isDirectory(outputPath) && Files.isWritable(outputPath)) { return outputPath; } else { System.err.println("Output directory option should be a writable directory"); System.exit(1); return null; } }
5d00a2e9-af14-4a3d-99a9-bfb78b0808a6
0
public boolean isManagesConnection(TVC con) { return managedConnections.contains(con); }
79947d08-18c4-435d-8c76-e99c47666a3c
0
private void updateUploadInfo(String status) { long delta = (System.currentTimeMillis() - startTime) / 1000; request.getSession().setAttribute("uploadInfo", new UploadInfo(totalFiles, totalToRead, totalBytesRead,delta,status)); }
67114bd5-d337-4df7-9369-ce52ef538ed0
1
public static void putReverseSortedInput(Comparable[] a) { for (int i = a.length; i > 0; i--) a[i] = i; }
d03b0547-78bc-454c-9c33-a8c64ef0de9e
7
public static boolean pointInside(Positioned other, double x, double y, boolean notOnTheEdge) { if (notOnTheEdge) return x > other.leftBorder() && x < other.rightBorder() && y > other.topBorder() && y < other.bottomBorder(); else return x >= other.leftBorder() && x <= other.rightBorder() && y >= other.topBorder() && y <= other.bottomBorder(); }
5143710c-cfd5-4331-af74-45cd8e1a1e91
0
public void set(int index, String datum) { RangeCheck(index); data[index] = datum; }
2fe07fa4-aa2a-474c-a7ed-e3a34dc94ac8
1
private void AddVertices(Vertex[] vertices, int[] indices, boolean calcNormals) { if(calcNormals) { CalcNormals(vertices, indices); } m_resource = new MeshResource(indices.length); glBindBuffer(GL_ARRAY_BUFFER, m_resource.GetVbo()); glBufferData(GL_ARRAY_BUFFER, Util.CreateFlippedBuffer(vertices), GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_resource.GetIbo()); glBufferData(GL_ELEMENT_ARRAY_BUFFER, Util.CreateFlippedBuffer(indices), GL_STATIC_DRAW); }
31f7bc47-639e-4876-8b41-fb85988c910a
0
public String getRemoteIP() { return remoteIP; }
37d63dd9-ca9a-4480-b364-a5e9eb03ac91
7
public void setProjectStateEnabled(boolean enabled){ //Enabled tool bar, except new and open project for(int i=2; i<mainToolBar.getComponentCount(); i++){ if(!(mainToolBar.getComponent(i) instanceof JToolBar.Separator)){ mainToolBar.getComponent(i).setEnabled(enabled); } } //Enabled file menu, except new, open project and exit for(int i=2; i<fileMenu.getMenuComponentCount()-1; i++){ if(!(fileMenu.getMenuComponent(i) instanceof JPopupMenu.Separator)){ fileMenu.getMenuComponent(i).setEnabled(enabled); } } //Enabled all the other menu in the mainMenuBar for(int i=1; i<mainMenuBar.getComponentCount(); i++){ JMenu menu = (JMenu) mainMenuBar.getComponent(i); for(Component comp : menu.getMenuComponents()){ if(!(comp instanceof JPopupMenu.Separator)){ comp.setEnabled(enabled); } } } //Show or not the middle panel (map editor, map tree, etc...) middlePanel.setVisible(enabled); }
13d4e2c5-eb2d-4dbd-8442-e5ffd77f56b1
1
@Override public ArrayList<Node> getListOfNodes() { if (isParsed) { return nodes; } else { initiateParsing(); return nodes; } }
03bed746-fcba-450c-91cf-f25bc3756afd
8
public static void main(String[] args) throws IOException { int option; Scanner input = new Scanner(System.in); System.out.println("What would you like to do?"); System.out.println(); System.out.println("<1> Add or delete a student"); System.out.println("<2> Change student grades or schedule"); System.out.println("<3> Sort students"); option = input.nextInt(); if (option == 1) { AddOrDeleteStudent.Intro(); } if (option == 2) { System.out.println("<1> Change a student's grade"); System.out.println("<2> Change a student's schedule"); option = input.nextInt(); if(option==1) { ChangeGrade.changeGrade(); } if(option==2) { SwitchClass.changeSchedule(); } } if (option == 3) { System.out.println("What would you like to sort by?"); System.out.println(); System.out.println("<1> By class"); System.out.println("<2> By GPA"); System.out.println("<3> By last name"); option = input.nextInt(); if (option ==1) { fillArray.createArraylist(); makeGPA.createGPA(); Collections.sort(Students.database,new SortByClass()); System.out.println(Students.database); } if (option ==2) { fillArray.createArraylist(); makeGPA.createGPA(); Collections.sort(Students.database,new SortByGPA()); System.out.println(Students.database); } if (option ==3) { fillArray.createArraylist(); makeGPA.createGPA(); Collections.sort(Students.database,new SortByLastName()); System.out.println(Students.database); } } }
3c2a9f1d-a97c-4202-b7cc-9a8873c86093
6
private boolean flushTable(JobConf conf) { initializeAccumuloConnector(); TableOperations ops = accumuloConnector.tableOperations(); String rowKeyRangeStart = conf.get("rowKeyRangeStart"); String rowKeyRangeEnd = conf.get("rowKeyRangeEnd"); boolean flushRangeAvailable = (rowKeyRangeStart != null && rowKeyRangeEnd != null); if (ops.exists(this.tableName)) { try { try { if (flushRangeAvailable) { ops.flush(this.tableName, new Text(rowKeyRangeStart), new Text(rowKeyRangeEnd), true); return true; } else { ops.flush(this.tableName); return true; } } catch (AccumuloSecurityException e) { LOG.error("Error in AccumuloTap.flushResource", e); e.printStackTrace(); } catch (TableNotFoundException e) { LOG.error("Error in AccumuloTap.flushResource", e); e.printStackTrace(); } } catch (AccumuloException e) { LOG.error("Error in AccumuloTap.flushResource", e); e.printStackTrace(); } } return false; }
490c0a36-f476-4aff-940a-99961891104b
2
private boolean inMergeSource(MultiType source) { while (source != null) { if (source == this) return true; source = source.mergeSource; } return false; }
c13b4c04-cf45-4164-a8cc-0a1c8ebdcac2
8
@Override public void tickTock(int howManyHours) { final TimeOfDay todCode=getTODCode(); if(howManyHours!=0) { setHourOfDay(getHourOfDay()+howManyHours); lastTicked=System.currentTimeMillis(); while(getHourOfDay()>=getHoursInDay()) { setHourOfDay(getHourOfDay()-getHoursInDay()); setDayOfMonth(getDayOfMonth()+1); if(getDayOfMonth()>getDaysInMonth()) { setDayOfMonth(1); setMonth(getMonth()+1); if(getMonth()>getMonthsInYear()) { setMonth(1); setYear(getYear()+1); } } } while(getHourOfDay()<0) { setHourOfDay(getHoursInDay()+getHourOfDay()); setDayOfMonth(getDayOfMonth()-1); if(getDayOfMonth()<1) { setDayOfMonth(getDaysInMonth()); setMonth(getMonth()-1); if(getMonth()<1) { setMonth(getMonthsInYear()); setYear(getYear()-1); } } } } if(getTODCode()!=todCode) handleTimeChange(); }
8e69a5d2-69c2-44ed-9459-200e09614f66
9
public static boolean dumpItem(int itemId) { String pageName = ItemDefinitions.getItemDefinitions(itemId).getName(); if (pageName == null || pageName.equals("null")) return false; pageName = pageName.replace("(p)", ""); pageName = pageName.replace("(p+)", ""); pageName = pageName.replace("(p++)", ""); pageName = pageName.replaceAll(" ", "_"); try { WebPage page = new WebPage("http://runescape.wikia.com/wiki/" + pageName); try { page.load(); } catch (Exception e) { System.out.println("Invalid page: " + itemId + ", " + pageName); return false; } boolean isNextLine = false; for (String line : page.getLines()) { if (!isNextLine) { if (line.equals("<th nowrap=\"nowrap\"><a href=\"/wiki/Examine\" title=\"Examine\">Examine</a>")) isNextLine = true; } else { String examine = line.replace("</th><td> ", ""); examine = examine.replace("</th><td>", ""); examine = examine.replace("<i> ", ""); examine = examine.replace("</i> ", ""); examine = examine.replace("&lt;colour&gt; ", ""); examine = examine.replace("(bright/thick/warm)", "bright"); examine = examine.replace("(Temple of Ikov) ", ""); examine = examine.replace("(Fight Arena) ", ""); try { BufferedWriter writer = new BufferedWriter( new FileWriter("itemExamines.txt", true)); writer.write(itemId + " - " + examine); writer.newLine(); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } return true; } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); return dumpItem(itemId); } return false; }
2ca5835c-c62c-4227-9350-5752700a00ad
9
public String GenerateIndividu() { int jum1 = 0; int jum2 = 0; int jum3 = 0; int i = 0; String ind; while (i < 8) { ind = getRandom(bahan); if ((ind.equals(bahan[0])) && (jum1 < 3)) { jum1++; individuRandom[i] = ind; i++; } else if ((ind.equals(bahan[1])) && (jum2 < 2)) { jum2++; individuRandom[i] = ind; i++; } else if ((ind.equals(bahan[2])) && (jum3 < 3)) { jum3++; individuRandom[i] = ind; i++; } } ind = ""; for (int j = 0; j < individuRandom.length; j++) { if (j == individuRandom.length - 1) { ind = ind + individuRandom[j] + getRandom(garis); } else { ind = ind + individuRandom[j] + getRandom(garis) + "-"; } } return ind; }
10c0c08a-a98e-4cfb-97ee-f2f58d8f0a4e
3
public List<Session> getTeamMembers(ChatColor color) { List<Session> sessions = new ArrayList<Session>(); for (Session session : HyperPVP.getGameSessions().values()) { if (session.getTeam() != null && session.getTeam().getColor() == color) { sessions.add(session); } } return sessions; }
f405b0cf-4d1f-465e-8f45-272cde2986d9
9
public static void textPack(byte packedData[], java.lang.String text) { if (text.length() > 80) text = text.substring(0, 80); text = text.toLowerCase(); int carryOverNibble = -1; int ofs = 0; for (int idx = 0; idx < text.length(); idx++) { char c = text.charAt(idx); int tableIdx = 0; for (int i = 0; i < xlateTable.length; i++) { if (c == xlateTable[i]) { tableIdx = i; break; } } if (tableIdx > 12) tableIdx += 195; if (carryOverNibble == -1) { if (tableIdx < 13) carryOverNibble = tableIdx; else packedData[ofs++] = (byte) (tableIdx); } else if (tableIdx < 13) { packedData[ofs++] = (byte) ((carryOverNibble << 4) + tableIdx); carryOverNibble = -1; } else { packedData[ofs++] = (byte) ((carryOverNibble << 4) + (tableIdx >> 4)); carryOverNibble = tableIdx & 0xf; } } if (carryOverNibble != -1) packedData[ofs++] = (byte) (carryOverNibble << 4); }
c3c94eeb-5dc0-49bd-928c-a0537acd8624
4
public int getContentLength(){ SipcHeader header = this.getHeader(SipcHeader.LENGTH); if (header != null && header.getValue() != null) { String value = header.getValue(); if (value.length() < 1) { return -1; }else if (value.indexOf(';') != -1) { return Integer.parseInt(value.substring(0,value.indexOf(';'))); }else{ return Integer.parseInt(value); } }else{ return -1; } }
8f85dd73-ac17-4fa9-aaf1-e35f3560214b
1
public void writeToUser(String user, String text){ try{ bw.write("PRIVMSG "+ user +" :"+text+"\n"); bw.flush(); }catch(IOException e){ System.out.println("IRC: Failure when trying to write to server: "+e.getMessage()); } }
8e14e2c4-2d97-4f73-b2a1-e8b7b336a8c3
5
@SuppressWarnings("unchecked") public boolean delete( Comparable key ) { ListNode<T> before = null; ListNode<T> after = front; // Traverse the list to find the ListNode before and after our deletion point. while ((after != null) && (key.compareTo(after.getData()) != 0)) { before = after; after = after.getNext(); } if (after == null) return false; else after = after.getNext(); // Delete the node by linking before to the next node of after if (size() == 1 || before == null) front = after; else before.setNext(after); numberOfNodes--; return true; }
d854e384-7888-45a5-9a04-5b858249afa0
6
public String[][] getDifferences(LLParseTable table) { if (!Arrays.equals(variables, table.variables) || !Arrays.equals(terminals, table.terminals)) throw new IllegalArgumentException( "Tables differ in variables or terminals."); ArrayList differences = new ArrayList(); for (int v = 0; v < entries.length; v++) for (int t = 0; t < entries[v].length; t++) if (!entries[v][t].equals(table.entries[v][t])) { if (t == terminals.length) differences.add(new String[] { variables[v], "$" }); else differences.add(new String[] { variables[v], terminals[t] }); } return (String[][]) differences.toArray(new String[0][0]); }
de6d1522-5f58-4447-93e0-0ce6504edf32
8
@SuppressWarnings("unchecked") void readGaussianBasis() throws Exception { /* * standard Gaussian format: * * [GTO] 1 S 3 172.2560000 2.0931324849764 25.9109000 2.93675143488078 5.5333500 1.80173711536432 * * 1 SP 2 3.6649800 -0.747384339731355 1.70917757609178 0.7705450 0.712661025209793 0.885622064435248 * */ Vector sdata = new Vector(); Vector gdata = new Vector(); int atomIndex = 0; int gaussianPtr = 0; while (readLine() != null && (line.length() == 0 || line.charAt(0) != '[')) { String[] tokens = getTokens(line); if (tokens.length == 0) continue; if (tokens.length != 1) { logger.log("Error reading GTOs: missing atom index"); new NullPointerException(); } Hashtable slater = new Hashtable(); atomIndex = parseInt(tokens[0]) - 1; tokens = getTokens(readLine()); String basisType = tokens[0]; int nGaussians = parseInt(tokens[1]); slater.put("atomIndex", new Integer(atomIndex)); slater.put("basisType", basisType); slater.put("nGaussians", new Integer(nGaussians)); slater.put("gaussianPtr", new Integer(gaussianPtr)); for (int i = 0; i < nGaussians; i++) { String[] strData = getTokens(readLine()); int nData = strData.length; float[] data = new float[nData]; for (int d = 0; d < nData; d++) data[d] = parseFloat(strData[d]); gdata.add(data); gaussianPtr++; } sdata.add(slater); } float[][] garray = new float[gaussianPtr][]; for (int i = 0; i < gaussianPtr; i++) garray[i] = (float[]) gdata.get(i); moData.put("shells", sdata); moData.put("gaussians", garray); logger.log(sdata.size() + " slater shells read"); logger.log(garray.length + " gaussian primitives read"); }
c1290e9a-f9e3-4a98-91ff-b06d1657057a
8
private static void pickSatisfyMinLeaves(BswabePolicy p, BswabePrv prv) { int i, k, l, c_i; int len; ArrayList<Integer> c = new ArrayList<Integer>(); if (p.children == null || p.children.length == 0) p.min_leaves = 1; else { len = p.children.length; for (i = 0; i < len; i++) if (p.children[i].satisfiable) pickSatisfyMinLeaves(p.children[i], prv); for (i = 0; i < len; i++) c.add(new Integer(i)); Collections.sort(c, new IntegerComparator(p)); p.satl = new ArrayList<Integer>(); p.min_leaves = 0; l = 0; for (i = 0; i < len && l < p.k; i++) { c_i = c.get(i).intValue(); /* c[i] */ if (p.children[c_i].satisfiable) { l++; p.min_leaves += p.children[c_i].min_leaves; k = c_i + 1; p.satl.add(new Integer(k)); } } } }
c6230430-08d9-4206-a45a-93a0fcb17c21
3
public ArrayList<MainMenuHeroSlot> reloadHero(){ ArrayList<MainMenuHeroSlot> temp = new ArrayList<MainMenuHeroSlot>(); while( heroTurn.peek() != null ){ BattleHeroSlots slot = heroTurn.remove(); slot.setExp(); temp.add(new MainMenuHeroSlot(slot)); } int count = temp.size(); if(count <Constants.HERO_TEAM_NUMBER){ for(int i = 0; i < Constants.HERO_TEAM_NUMBER - count ; i++){ temp.add(new MainMenuHeroSlot()); } } System.out.println("size of hero :" + temp.size()); return temp; }
47e2f003-9d31-4a4c-bd1f-b7ba5c4cbb46
6
@Override public void onAttack() { Alteration buff; MathTools math = new MathTools(); CombatLog log = CombatLog.getInstance(); int dmg; // Proc surging charge buff = engine.getPlayer().getAlterations().get("surgingCharge"); if (buff != null && (engine.getTime() - this.lastCharge) >= 0){ if (math.chance(25.0)){ log.write(engine.getTimeStr() + "Surging Charge "); dmg = engine.spellDamage(0.344,0.01,0,0,0.034,0.034,790,true); engine.dealDamage(dmg); log.writeln(" for " + dmg + " damage."); this.lastCharge = engine.getTime() + 1500; } } // Proc lightning charge buff = engine.getPlayer().getAlterations().get("lightningCharge"); if (buff != null && (engine.getTime() - this.lastCharge) >= 0){ if (math.chance(50.0)){ log.write(engine.getTimeStr() + "Lightning Charge "); dmg = engine.spellDamage(0.165, 0.01, 0, 0, 0.017, 0.017, 1610, true); engine.dealDamage(dmg); log.writeln(" for " + dmg + " damage."); this.lastCharge = engine.getTime() + 1500; } } }
e5d0d8f2-145a-4d64-bee3-79ea520387c2
0
public String getFacebookRsvpUrl() { return facebookRsvpUrl; }
e2b514f0-242d-4c71-93dd-516574b4f224
7
public static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } }
0464f2dc-b47b-4056-9e2b-f5dc8342a3e7
8
@Override protected void controlRender(RenderManager rm, ViewPort vp) { float newDistance; int level; BoundingVolume bv = spatial.getWorldBound(); Camera cam = vp.getCamera(); float atanNH = FastMath.atan(cam.getFrustumNear() * cam.getFrustumTop()); float ratio = (FastMath.PI / (8f * atanNH)); newDistance = bv.distanceTo(vp.getCamera().getLocation()) / ratio; if (Math.abs(newDistance - prevDistance) <= distanceThreshold) { level = prevLevel; // we haven't moved relative to the model, send the old measurement back. } else if (prevDistance > newDistance && prevLevel == 0) { level = prevLevel; // we're already at the lowest setting and we just got closer to the model, no need to keep trying. } else if (prevDistance < newDistance && prevLevel == numLevels - 1) { level = prevLevel; // we're already at the highest setting and we just got further from the model, no need to keep trying. } else { prevDistance = newDistance; // estimate area of polygon via bounding volume float area = AreaUtils.calcScreenArea(bv, prevDistance, cam.getWidth()); float trisToDraw = area * trianglesPerPixel; level = numLevels - 1; for (int i = numLevels; --i >= 0;) { if (trisToDraw - numTris[i] < 0) { break; } level = i; } } if(prevLevel!=level){ System.out.println("This is the Level Of Detail control, currently drawing " + cylinders[level].getTriangleCount() +" triangles on the " + name); } prevLevel = level; ((Geometry) spatial).setMesh(cylinders[level]); }
6d418fb0-6bf9-46aa-8b34-1b571ac6a278
5
public static void readMessage(String input, Core output) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; Document xmlFile = null; try { builder = factory.newDocumentBuilder(); xmlFile = builder.parse(new InputSource(new StringReader(input))); } catch (Exception e) { System.out.println(ERROR_EN_EL_XML); return; } String rootName = xmlFile.getDocumentElement().getNodeName(); XmlMessage type = null; for (XmlMessage m : XmlMessage.values()) { if (m.equals(rootName)) { //Identifies type of message type = m; break; } } if (type == null) return; else try { readMessageAux(output, xmlFile, type); } catch (Exception e) { e.printStackTrace(); System.out.println(ERROR_EN_FORMATO_DEL_XML); } }
2dba042b-910e-400a-893d-153dccc11a0f
5
private float[] kernel(float[] x, float[] w, int n, int n2, int n4, int n8){ // step 2 int xA=n4; int xB=0; int w2=n4; int A=n2; for(int i=0;i<n4;){ float x0=x[xA] - x[xB]; float x1; w[w2+i]=x[xA++]+x[xB++]; x1=x[xA]-x[xB]; A-=4; w[i++]= x0 * trig[A] + x1 * trig[A+1]; w[i]= x1 * trig[A] - x0 * trig[A+1]; w[w2+i]=x[xA++]+x[xB++]; i++; } // step 3 { for(int i=0;i<log2n-3;i++){ int k0=n>>>(i+2); int k1=1<<(i+3); int wbase=n2-2; A=0; float[] temp; for(int r=0;r<(k0>>>2);r++){ int w1=wbase; w2=w1-(k0>>1); float AEv= trig[A],wA; float AOv= trig[A+1],wB; wbase-=2; k0++; for(int s=0;s<(2<<i);s++){ dtmp1=w[w1]; dtmp2=w[w2]; wB=dtmp1-dtmp2; x[w1]=dtmp1+dtmp2; dtmp1=w[++w1]; dtmp2=w[++w2]; wA=dtmp1-dtmp2; x[w1]=dtmp1+dtmp2; x[w2] =wA*AEv - wB*AOv; x[w2-1]=wB*AEv + wA*AOv; /* wB =w[w1] -w[w2]; x[w1] =w[w1] +w[w2]; wA =w[++w1] -w[++w2]; x[w1] =w[w1] +w[w2]; x[w2] =wA*AEv - wB*AOv; x[w2-1]=wB*AEv + wA*AOv; */ w1-=k0; w2-=k0; } k0--; A+=k1; } temp=w; w=x; x=temp; } } // step 4, 5, 6, 7 { int C=n; int bit=0; int x1=0; int x2=n2-1; for(int i=0;i<n8;i++) { int t1=bitrev[bit++]; int t2=bitrev[bit++]; float wA=w[t1]-w[t2+1]; float wB=w[t1-1]+w[t2]; float wC=w[t1]+w[t2+1]; float wD=w[t1-1]-w[t2]; float wACE=wA* trig[C]; float wBCE=wB* trig[C++]; float wACO=wA* trig[C]; float wBCO=wB* trig[C++]; x[x1++]=( wC+wACO+wBCE)*16383.0f; x[x2--]=(-wD+wBCO-wACE)*16383.0f; x[x1++]=( wD+wBCO-wACE)*16383.0f; x[x2--]=( wC-wACO-wBCE)*16383.0f; } } return x; }
5022fa52-f023-4ee3-bea1-fa567ae3053e
6
protected void processClients(Map<Integer, ClientInfo> connectedClients) { // Don't process if previous map is null, i.e. not yet initialized if(map == null) return; // Loop through all of the clients in the previous mapping for(ClientInfo client : map.values()) { // Send an event notification if the client does not exist in the // map of currently connected clients if(!connectedClients.containsKey(client.clientId)) { serverQuery.getEventThread().notify( new TS3ClientDisconnectedEvent(client.clientName, client.clientId, client.clientUid)); } } // Loop through all of the clients in the current map for(ClientInfo client : connectedClients.values()) { // Get the ClientInfo object in the previous map ClientInfo previous = map.get(client.clientId); if(previous == null) { // Send an event notification if the client does not exist in // the previous map of connected clients serverQuery.getEventThread().notify(new TS3ClientConnectedEvent( client.clientName, client.clientId, client.clientUid)); } else { // Check if the client moved channels if(client.channelId != previous.channelId) { // Send notification serverQuery.getEventThread().notify(new TS3ClientMovedEvent( client.clientName, client.clientId, client.clientUid, previous.channelId, client.channelId)); } } } }
0da8b3a6-51dc-48c4-be18-884144f7cf80
1
public String getBillForCustomer(String[] orders) { for (String personOrder : orders) { item = personOrder.split(SPLIT); foodName = item[0]; foodPrice = item[1]; bill = bill + Double.valueOf(foodPrice); order = order + foodName + SPACE + Double.parseDouble(foodPrice) + BREAK; } totalBill = bill * salesTax; totalBillWithTax = totalBill + bill; order += BILL + bill + BREAK + SALES + salesTax + BREAK + GRAND + totalBillWithTax; return order; }
d3ce3b05-478f-49d1-8eca-89af65bfca38
3
@Override public void run() { while (true) { // This loop goes forever, since we don't want our game // logic to stop. // TODO: Add game mechanics here. // Update all game objects. for (RenderObject object : objectsToRender) { object.update(inputHandler, objectsToRender); } // Update the input state. inputHandler.updatedReleasedKeys(); // Delay the next action (iteration of the loop). try { Thread.sleep((long) (1000.0f/ACTIONS_PER_SECOND)); } catch (InterruptedException e) { // We were interrupted, exit the game loop. Log.error("Caught interruption exception, exiting game loop."); e.printStackTrace(); break; } } }
24eaa965-16aa-42ca-ae8d-576a7168d7b1
3
public Tree additiveExpressionDashPro(Tree firstConditionalExpression){ Tree secondConditionalExpression = null; Symbol operator = null; if((operator = accept(Symbol.Id.PUNCTUATORS,"(\\+|-)")) != null){ if((secondConditionalExpression = multiplicativeExpressionPro()) != null){ firstConditionalExpression = new BinaryExpression(firstConditionalExpression, operator, secondConditionalExpression); if((secondConditionalExpression = additiveExpressionDashPro(firstConditionalExpression)) != null){ return secondConditionalExpression; } return firstConditionalExpression; } return null; } return null; }
375797c0-7074-45d1-8d54-3be41eaa26b9
6
private static void trip(String mapFileName) { Reader mapParser = null; try { mapParser = new FileReader(mapFileName); } catch (FileNotFoundException e) { throw new RuntimeException("No file found"); } makeMap(mapParser); Scanner reqParser = new Scanner(System.in); _requests = new ArrayList<Graph<Location, Distance>.Vertex>(); while (reqParser.hasNext()) { String next = reqParser.next(); next = trim(next); if (!_locs.containsKey(next)) { reqParser.close(); throw new RuntimeException("Destination not established"); } _requests.add(_locs.get(next)); } reqParser.close(); if (_requests.size() < 2) { throw new RuntimeException("Too few locations specified"); } System.out.println("From " + _requests.get(0).getLabel().name() + ":"); System.out.println(); _count = 1; Distancer<Location> heuristic = new StraightLineHeur(); for (int i = 0; i < _requests.size() - 1; i++) { Graph<Location, Distance>.Vertex v0 = _requests.get(i); Graph<Location, Distance>.Vertex v1 = _requests.get(i + 1); List<Graph<Location, Distance>.Edge> bestPath = Graphs.shortestPath(_map, v0, v1, heuristic); if (v1.getLabel().weight() == Double.POSITIVE_INFINITY) { throw new RuntimeException("Destination unreachable"); } outputRoad(bestPath, v1); } }
3031ae2a-366e-4597-a92e-3939cecb661b
0
public static void expandAllSubheads(Node currentNode) { currentNode.ExpandAllSubheads(); currentNode.getTree().getDocument().panel.layout.redraw(); return; }
6b5ea005-d10e-4bd3-81bb-448758f42991
8
public float priorityFor(Actor actor) { final Item[] available = available(this.actor) ; if (available.length == 0) return 0 ; final float rangePenalty = ( Plan.rangePenalty(actor, origin) + Plan.rangePenalty(actor, destination) + Plan.rangePenalty(origin, destination) ) / (driven == null ? 2f : 10f) ; float offset = rangePenalty ; if (shouldPay == actor && stage <= STAGE_PICKUP) { int price = 0 ; float foodVal = 0 ; for (Item i : available) { price += purchasePrice(i, actor, origin) ; if (Visit.arrayIncludes(ALL_FOOD_TYPES, i.type)) foodVal += i.amount ; } if (price > actor.gear.credits()) return 0 ; offset += actor.mind.greedFor(price) * CASUAL ; offset -= actor.health.hungerLevel() * CASUAL * foodVal ; } else for (Item i : available) { offset -= i.amount / 5f ; } return Visit.clamp( ROUTINE + priorityMod - offset, 0, URGENT ) ; }
193664ee-43f8-4f76-9933-31cb946db27b
3
private Location rechercherLocation(int numero){ System.out.println("ModeleLocations::rechercherLocation()") ; Location location = null ; int i = 0 ; while(i < this.locations.size() && location == null){ if(this.locations.get(i).getNumero() == numero){ location = this.locations.get(i) ; } else { i += 1 ; } } return location ; }
c2ff3eeb-aefb-41e2-a2d1-d45946516052
1
static long amod(long dividend, long divisor) { long mod = mod(dividend, divisor); return (mod == 0) ? divisor : mod; }
d7314ca1-4f2b-4141-9f25-3a37d7140dec
2
public static synchronized void removeUser(int id) { for(int i = 0; i < usersOnline.size(); i++) { if(usersOnline.get(i).getId() == id) { usersOnline.remove(i); return; } } }