method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
cbf4e197-b3ca-4442-8fe3-091f367b30a8
3
protected synchronized void execute(boolean synchronous) { // see if we're already running if (thread != null) { // we're already running. Make sure we wake up on any change. synchronized (statusLock) { statusLock.notifyAll(); } return; } else if (isFinished()) { // we're all finished return; } // we'return not running. Start up if (synchronous) { thread = Thread.currentThread(); run(); } else { thread = new Thread(this); thread.setName(getClass().getName()); thread.start(); } }
6a4c5305-2438-4071-9b42-5d1dc5ffb3b9
9
private void adjustMinPrefForSpanningComps(DimConstraint[] specs, Float[] defGrow, FlowSizeSpec fss, ArrayList<LinkedDimGroup>[] groupsLists) { for (int r = 0; r < groupsLists.length; r++) { ArrayList<LinkedDimGroup> groups = groupsLists[r]; for (int i = 0; i < groups.size(); i++) { LinkedDimGroup group = groups.get(i); if (group.span == 1) { continue; } int cSize = group.getMinPrefMax()[LayoutUtil.PREF]; if (cSize == LayoutUtil.NOT_SET) { continue; } int rowSize = 0; int sIx = (r << 1) + 1; int len = Math.min(group.span << 1, fss.sizes.length - sIx) - 1; for (int j = sIx; j < sIx + len; j++) { int sz = fss.sizes[j][LayoutUtil.PREF]; if (sz != LayoutUtil.NOT_SET) { rowSize += sz; } } if (rowSize < cSize) { for (int eag = 0, newRowSize = 0; eag < 4 && newRowSize < cSize; eag++) { newRowSize = fss.expandSizes(specs, defGrow, cSize, sIx, len, LayoutUtil.PREF, eag); } } } } }
57fe976e-1082-4b3e-b997-17c024d5264c
3
public void SendText(){ String x = Tinput.getText (); //Checks to see if it is a server command if(x.length() > 5 && x.substring(0,5).equals("serv.")){ send(x); } else if (!x.equals("")) { x = Username + ": " + Tinput.getText (); send(x); Tinput.setText(""); } }
c52a1ea1-3e09-4636-9870-b1781ac84ee2
7
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { int completion=16; final Item fire=getRequiredFire(mob,0); if(fire==null) return false; final PairVector<EnhancedExpertise,Integer> enhancedTypes=enhancedTypes(mob,commands); buildingI=null; messedUp=false; int woodRequired=50; final int[] pm={RawMaterial.MATERIAL_METAL,RawMaterial.MATERIAL_MITHRIL}; final int[][] data=fetchFoundResourceData(mob, woodRequired,"metal",pm, 0,null,null, false, auto?RawMaterial.RESOURCE_MITHRIL:0, enhancedTypes); if(data==null) return false; woodRequired=data[0][FOUND_AMT]; if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; if(!auto) CMLib.materials().destroyResourcesValue(mob.location(),woodRequired,data[0][FOUND_CODE],0,null); buildingI=CMClass.getWeapon("GenWeapon"); completion=50-CMLib.ableMapper().qualifyingClassLevel(mob,this); final String itemName="the Holy Avenger"; buildingI.setName(itemName); final String startStr=L("<S-NAME> start(s) crafting @x1.",buildingI.name()); displayText=L("You are crafting @x1",buildingI.name()); verb=L("crafting @x1",buildingI.name()); buildingI.setDisplayText(L("@x1 lies here",itemName)); buildingI.setDescription(itemName+". "); buildingI.basePhyStats().setWeight(woodRequired); buildingI.setBaseValue(0); buildingI.setMaterial(data[0][FOUND_CODE]); buildingI.basePhyStats().setLevel(mob.phyStats().level()); buildingI.basePhyStats().setAbility(5); final Weapon w=(Weapon)buildingI; w.setWeaponClassification(Weapon.CLASS_SWORD); w.setWeaponDamageType(Weapon.TYPE_SLASHING); w.setRanges(w.minRange(),1); buildingI.setRawLogicalAnd(true); Ability A=CMClass.getAbility("Prop_HaveZapper"); A.setMiscText("-CLASS +Paladin -ALIGNMENT +Good"); buildingI.addNonUninvokableEffect(A); A=CMClass.getAbility("Prop_Doppleganger"); A.setMiscText("120%"); buildingI.addNonUninvokableEffect(A); buildingI.recoverPhyStats(); buildingI.text(); buildingI.recoverPhyStats(); messedUp=!proficiencyCheck(mob,0,auto); if(completion<6) completion=6; final CMMsg msg=CMClass.getMsg(mob,null,CMMsg.MSG_NOISYMOVEMENT,startStr); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,mob,asLevel,completion); enhanceItem(mob,buildingI,enhancedTypes); } return true; }
fa91e3f8-ed7c-4aa7-bf10-57d560e1c56a
4
public static User readFrom(HttpServletRequest request) throws Exception { Cookie[] cookies = request.getCookies(); if (cookies == null || cookies.length == 0) { return null; } for (Cookie cookie: cookies) { if ("FB_ID".equals(cookie.getName())) { System.out.println("User: readFrom FB_ID cookie found."); return getUser(URLDecoder.decode(cookie.getValue(), "UTF-8")); } } // no cookie found return null; }
a3fbe555-6aed-4bc6-a7ea-15004b271ee0
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(Frm_CadOrigem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Frm_CadOrigem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Frm_CadOrigem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Frm_CadOrigem.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 Frm_CadOrigem().setVisible(true); } }); }
36c20584-bb07-438f-9ed9-3346e97e98ae
1
public SampleComperator(boolean decreasing_order) { order = decreasing_order ? -1 : 1; }
d8100547-cc0c-438a-b4ed-cabaa8342d0d
0
public int getUpcomingEventsCount() { return upcomingEventsCount; }
e4d4c45e-940a-43ac-82aa-ddb6d47c1752
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(Frm_RelClienteBySegmento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Frm_RelClienteBySegmento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Frm_RelClienteBySegmento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Frm_RelClienteBySegmento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { // new Frm_RelClienteBySegmento().setVisible(true); } }); }
29dcb135-0915-49d7-a0c5-1eccc8e67c8d
3
public boolean isElementPresent(By by) { try { List allElements = driver.findElements(by); if ((allElements == null) || (allElements.size() == 0)) return false; else return true; } catch(java.util.NoSuchElementException e) { return false; } }
a0f279d4-6ae0-45bd-9b2e-96a45815503d
9
private boolean checkClass(HashMap<String, ClassInfo> db, ClassInfo info) { if(info == null) { return false; } /* check extends */ for(String cls : classes) { if(cls.equals(info.superName)) { return true; } } /* check implements */ String[] clsImpl = info.getInterfaceNames(); for(String ref : interfaces) { for(String impl : clsImpl) { if(impl.equals(ref)) { return true; } } } /* check parent data */ if(checkClass(db, db.get(info.superName))) { return true; } /* check interface data */ for(String impl : clsImpl) { if(checkClass(db, db.get(impl))) { return true; } } return false; }
e17bad66-6607-4a5e-8f5c-0577cab2e09e
8
@EventHandler(priority = EventPriority.LOWEST) public void PlayerCommand(PlayerCommandPreprocessEvent event) { DwDPlayer pCheck = DwDPlayers.getPlayer(event.getPlayer().getUniqueId()); DwDBridgePlugin plugin = DwDBridgePlugin.getPlugin(); if (event.getMessage().toLowerCase().startsWith("/confirm") || event.getMessage().equalsIgnoreCase("/confirm")) { if (!pCheck.isMcConfirmed()) { if (pCheck.getXenID() > 0) { // Confirm pCheck.rankSync(); pCheck.setMcConfirmed(true); event.setCancelled(true); event.setMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("messages.confirmed") .replaceAll("%N", pCheck.getXenUsername()))); event.getPlayer().sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("messages.confirmed") .replaceAll("%N", pCheck.getXenUsername()) )); } } } else if (event.getMessage().toLowerCase().startsWith("/deny") || event.getMessage().equalsIgnoreCase("/deny")) { if (!pCheck.isMcConfirmed()) { if (pCheck.getXenID() > 0) { // Confirm pCheck.setMcConfirmed(false); pCheck.removeEntry(); event.setCancelled(true); event.setMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("messages.denied") .replaceAll("%N", pCheck.getXenUsername()))); event.getPlayer().sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("messages.denied") .replaceAll("%N", pCheck.getXenUsername()) )); } } } }
86ba8d53-134a-4521-9e64-11915d06468d
0
public ZoomPane(SelectionDrawer drawer) { super(drawer); drawer.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { transform = null; } }); }
e2e6585a-0f5e-4952-bc92-b492a475e4cb
0
public int run() { qSortMedianThree(aInt, 0, aInt.length-1); return 0; }
77b84657-7473-4939-9f2f-e64b1e56bdce
6
public void dispose(boolean cache) { // dispose the nameTree if (nameTree != null) { nameTree.dispose(); namesTreeInited = false; if (!cache) nameTree = null; } if (pageTree != null) { pageTree.dispose(cache); if (!cache) pageTree = null; } if (outlines != null) { if (!cache) { outlines.dispose(); outlines = null; } } }
9baaf3bc-9276-4c7e-bc94-7d90c110b2c7
2
@Test public void testCmd() throws Exception { for (CommandBase command : container.getCommands()) { try { assertTrue(command.execute(new CommandInvocation(null, command.getDescriptor().getDescription(), scm.getProviderManager()))); } catch (Exception e) { System.out.println(command.getDescriptor().getName()); throw e; } } }
aaf88564-9eec-498b-888b-fa57582a912d
1
private String formatNoteElementLabel(NoteElement element) { String noteText = ensureTextIsValid(element.getText().toString()); // does the note provides its own wrap if(noteText.contains("\\n")) return noteText; return wrap(noteText, noteWrapLength, "\\n", false); }
03fbd677-cbd2-442f-a2b2-c6c6e520c329
2
public void PrintMe(String _title) { System.out.println(_title); for(int i=0;i<Block.N;i++) { System.out.println(); for (int j = 0; j < Block.N; j++) { System.out.print(this.block[i][j] + " "); } } }
b8958f9d-4935-4ca8-b379-584d73864852
5
@Override public int compareTo(final Version other) { if (this == ALL || other == ALL) { return 0; } int c = modifier.compareTo(other.modifier); if (c != 0) { return c; } c = major - other.major; if (c != 0) { return c; } c = minor - other.minor; if (c != 0) { return c; } return revision - other.revision; }
60d1e436-115a-4647-94fe-f40387256190
4
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityDeath(EntityDeathEvent event){ //check if the entity is tagged Entity dead = event.getEntity(); int id = dead.getEntityId(); if(plugin.getMobsTagged().containsKey(id)){ Player killer = plugin.getServer().getPlayer(plugin.getMobsTagged().get(id)); if(dead instanceof Creature) playerKilledCreature(killer, (Creature) dead); // Checkes if it is a player or if not a player a livingentity(slime, magmacube, and enderdragon) *Croyd* if(dead instanceof Player) { playerKilledPlayer(killer, (Player) dead); } else if (dead instanceof LivingEntity){ playerKilledLivingEntity(killer, (LivingEntity) dead); } //death counted, remove from tagged list plugin.getMobsTagged().remove(id); } }
dfa90311-8e4a-4e19-a6c9-804ee66a67e9
0
public static void main(String[] args) { // TODO Auto-generated method stub }
efdd2f23-7d59-4aec-8605-0c8a17449290
3
public double interpolate(double xx){ double h=0.0D,b=0.0D,a=0.0D, yy=0.0D; int k=0; int klo=0; int khi=this.nPoints-1; while (khi-klo > 1){ k=(khi+klo) >> 1; if(this.x[k] > xx){ khi=k; } else{ klo=k; } } h=this.x[khi]-this.x[klo]; if (h == 0.0){ throw new IllegalArgumentException("Two values of x are identical: point "+klo+ " ("+this.x[klo]+") and point "+khi+ " ("+this.x[khi]+")" ); } else{ a=(this.x[khi]-xx)/h; b=(xx-this.x[klo])/h; yy=a*this.y[klo]+b*this.y[khi]+((a*a*a-a)*this.d2ydx2[klo]+(b*b*b-b)*this.d2ydx2[khi])*(h*h)/6.0; } return yy; }
621a15a8-da4c-4c49-8f7f-1beec257bf29
0
@XmlElementDecl(namespace = "http://www.w3.org/2000/09/xmldsig#", name = "Reference") public JAXBElement<ReferenceType> createReference(ReferenceType value) { return new JAXBElement<ReferenceType>(_Reference_QNAME, ReferenceType.class, null, value); }
8af57ca6-62de-4f76-8742-e825faa8d7ea
7
public static Cons matchPatternElement(Symbol patternElement, Stella_Object datumElement) { if (Stella_Object.isaP(datumElement, Stella.SGT_STELLA_CONS)) { { Stella_Object datumType = ((((Cons)(datumElement)).value == Stella.SYM_STELLA_SPECIAL) ? ((Cons)(datumElement)).rest.value : ((Cons)(datumElement)).value); if (datumType == patternElement) { return (((Cons)(datumElement))); } else { return (Stella.NIL); } } } else if (((Cons)(Stella.$SPECIAL_SYMBOLS$.get())).memberP(patternElement)) { return (Stella.NIL); } else { { java.lang.reflect.Method function = Symbol.lookupFunction(patternElement).functionCode; Stella_Object match = ((Stella_Object)(edu.isi.stella.javalib.Native.funcall(function, null, new java.lang.Object [] {datumElement}))); if (Surrogate.subtypeOfBooleanP(Stella_Object.safePrimaryType(match))) { { BooleanWrapper match000 = ((BooleanWrapper)(match)); if (BooleanWrapper.coerceWrappedBooleanToBoolean(match000)) { return (Cons.consList(Cons.cons(patternElement, Cons.cons(datumElement, Stella.NIL)))); } else { return (Stella.NIL); } } } else { if (match != null) { return (Cons.consList(Cons.cons(patternElement, Cons.cons(match, Stella.NIL)))); } else { return (Stella.NIL); } } } } }
d0df60e0-539f-408e-81b9-2e91035acbac
9
private T getHermanoABBUtil(NodoArbol <T> nodo, T dato) { int i; if(nodo == null || nodo.dato == null) return null; if(containsABBRecursivo(dato) == false) return null; if(dato == this.raiz.dato) return null; if(nodo.der.dato.compareTo(dato) == 0){ if(nodo.izq == null) return null; return nodo.izq.dato; } if(nodo.izq.dato.compareTo(dato) == 0 ){ if(nodo.der == null) return null; return nodo.der.dato; } else{ i = nodo.dato.compareTo(dato); if(i > 0) return getHermanoABBUtil(nodo.izq, dato); else return getHermanoABBUtil(nodo.der, dato); } }
f2fbea2e-135b-4a7e-b836-ccd1f695d2ca
9
public static Rate parse(final String name, byte[] rateBytes) throws ParseException { Rate rate; int rateUnit = rateBytes[4] + rateBytes[5] * 16; if (rateUnit == 0) { int frequency = 0; for (int i = 0; i < 4; i++) { frequency += (rateBytes[i] * Math.pow(16, i)); } rate = new FrequencyRate(name, frequency == 0x8000 ? null : frequency / 100.0); } else if (rateUnit == 1) { int cycles = rateBytes[0] + rateBytes[1] * 16; int beats = rateBytes[2] + rateBytes[3] * 16; if (beats == 0x80 && cycles == 0x00) { rate = new BeatRate(name, null, null); } else { rate = new BeatRate(name, cycles, beats); } } else if (rateUnit == 4) { int ms = 0; for (int i = 0; i < 4; i++) { ms += (rateBytes[i] * Math.pow(16, i)); } rate = new TapMsRate(name, ms == 0x8000 ? null : ms); } else { throw new ParseException("Unexpected rate unit: " + rateUnit); } return rate; }
e81a38e7-8a0b-416e-8fb6-a346f19232b9
4
private Entity getEntityAt(Position pos, Environment enviro) { ArrayList<Entity> entities = enviro.getEntities(); Entity closest = entities.get(0); for(int i = 1; i < enviro.getEntityAmount(); i++){ Entity x = entities.get(i); if(x.getPosition().x()-pos.x() < closest.getPosition().x()- pos.x()){ if(x.getPosition().y() - pos.y() < closest.getPosition().y() -pos.y()){ if(x.getPosition().z() - pos.z() < closest.getPosition().y() -pos.y()){ closest = x; } } } } return closest; }
849b2e20-7a16-4ec5-aeb0-cb3ae9e916bb
4
public void atNewArrayExpr(NewExpr expr) throws CompileError { int type = expr.getArrayType(); ASTList size = expr.getArraySize(); ASTList classname = expr.getClassName(); ASTree init = expr.getInitializer(); if (init != null) init.accept(this); if (size.length() > 1) atMultiNewArray(type, classname, size); else { ASTree sizeExpr = size.head(); if (sizeExpr != null) sizeExpr.accept(this); exprType = type; arrayDim = 1; if (type == CLASS) className = resolveClassName(classname); else className = null; } }
3374b015-8337-46bc-a4a0-003555c2607f
9
String getCurrentOrientation() { axisangleT.set(matrixRotate); float degrees = axisangleT.angle * degreesPerRadian; StringBuffer sb = new StringBuffer(); if (degrees < 0.01f) { if (matrixRotate.m00 == -1.0f || matrixRotate.m11 == -1.0f || matrixRotate.m22 == -1.0f) { sb.append(" 1000 0 0 -180"); // rear view } else { sb.append(" 0 0 0 0"); // front view } } else { vectorT.set(axisangleT.x, axisangleT.y, axisangleT.z); vectorT.normalize(); vectorT.scale(1000); truncate0(sb, vectorT.x); truncate0(sb, vectorT.y); truncate0(sb, vectorT.z); truncate1(sb, degrees); } int zoom = getZoomPercent(); int tX = (int) getTranslationXPercent(); int tY = (int) getTranslationYPercent(); if (zoom != 100 || tX != 0 || tY != 0) { sb.append(" "); sb.append(zoom); if (tX != 0 || tY != 0) { sb.append(" "); sb.append(tX); sb.append(" "); sb.append(tY); } } return sb.toString().trim(); }
5c7e3ed7-3ca9-4645-8d19-7f0c3dba211b
1
static final void indent(Writer writer, int indent) throws IOException { for (int i = 0; i < indent; i += 1) { writer.write(' '); } }
a6ae6ad3-34e0-4df7-b357-511d364a38df
1
public void clear (int color){ for(int i = 0; i < pixels.length; i++){ pixels[i] = color; } }
a0c48bb8-b64a-4546-a854-b8d00fb3e848
8
public boolean processRead(SocketChannel sc) throws IOException, RemoteSocketClosedException { final String socketAddresss = ServerLogger.parseSocketAddress(sc); if (disconnectionRequested) { // Block the reads if a disconnect was requested, let the outbound // buffer clear itself. LOGGER.log(new ClientConnectionLogRecord( Level.WARNING, socketAddresss, SystemEvent.CLIENT_CONNECTION, "Client " + socketAddresss + " attempted to perform additional operations after " + "requesting a disconnect.")); return true; } switch (readingStatus) { case READING_HEADER: int r = sc.read(headerBuffer); if (r < 0) { LOGGER.log(new ClientConnectionLogRecord(Level.SEVERE, socketAddresss, SystemEvent.BUFFER_IO, "Socket was closed unexpectedly by " + socketAddresss)); throw new RemoteSocketClosedException(); } if (!headerBuffer.hasRemaining()) { headerBuffer.flip(); try { int bodyLength = processHeader(); readingStatus = ReadStatus.READING_BODY; bodyBuffer = ByteBuffer.allocate(bodyLength); LOGGER.log(new ClientConnectionLogRecord( socketAddresss, SystemEvent.BUFFER_IO, String.format( "Finished reading header for new request" + " from %s expecting now %d bytes for the body", socketAddresss, bodyLength))); } catch (InvalidHeaderException e) { LOGGER.log(new ClientConnectionLogRecord(socketAddresss, SystemEvent.BUFFER_IO, "Received an invalid header from " + socketAddresss + " , ignoring it and awaiting a new one.", e)); headerBuffer.clear(); } } return false; case READING_BODY: int k = sc.read(bodyBuffer); if (k < 0) { LOGGER.log(new ClientConnectionLogRecord(Level.SEVERE, socketAddresss, SystemEvent.BUFFER_IO, "Socket was closed unexpectedly by " + socketAddresss)); throw new RemoteSocketClosedException(); } if (!bodyBuffer.hasRemaining()) { bodyBuffer.flip(); boolean needWrite = processBody(ServerLogger .parseSocketAddress(sc)); headerBuffer.clear(); bodyBuffer = null; readingStatus = ReadStatus.READING_HEADER; return needWrite; } return false; } return false; }
d89091bd-f4c8-402b-8ad8-fbe3651d83b3
5
public void setLocationFromPriority(){ switch(priority){ case 1:{ setxCoord(1600); setyCoord(40); break; } case 2:{ setxCoord(1640); setyCoord(90); break; } case 3:{ setxCoord(1680); setyCoord(140); break; } case 4:{ setxCoord(1680); int y = rnd.nextInt(660) + 20; setyCoord(y); break; } case 5:{ setxCoord(580); setyCoord(600); break; } } }
d789889b-f0b9-432e-98ba-d98269f46ac6
0
public void setSignDatetime(Date signDatetime) { this.signDatetime = signDatetime; }
5b4f895c-4bef-4183-9f36-fd64a146123d
1
public boolean isSymmetric(treeNode root) { if(root == null) return true; return treesSymmetric(root.leftLeaf,root.rightLeaf); }
960bc9cd-1596-48f6-ac0a-437c5f610f55
9
private void jTextFieldSearchEmpruntKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldSearchEmpruntKeyTyped // TODO add your handling code here: if (evt.getKeyChar() == KeyEvent.VK_ENTER) { String toSearch = jTextFieldSearchEmprunt.getText(); if (jRadioButtonIdEmprunt.isSelected()) { try { this.searchByIdEmprunt(toSearch); } catch (Exception ex) { Logger.getLogger(TableauDeBord.class.getName()).log(Level.SEVERE, null, ex); jLabelNbFoundEmprunt.setText("<html><body><font color='red'>" + ex.getMessage() + "</font></body></html>"); } } else if (jRadioButtonEmpruntByAdherent.isSelected()) { try { this.searchByAdherentEmprunt(toSearch); } catch (Exception ex) { Logger.getLogger(TableauDeBord.class.getName()).log(Level.SEVERE, null, ex); jLabelNbFoundEmprunt.setText("<html><body><font color='red'>" + ex.getMessage() + "</font></body></html>"); } } else if (jRadioButtonEmpruntByLivre.isSelected()) { try { this.searchByLivreEmprunt(toSearch); } catch (Exception ex) { Logger.getLogger(TableauDeBord.class.getName()).log(Level.SEVERE, null, ex); jLabelNbFoundEmprunt.setText("<html><body><font color='red'>" + ex.getMessage() + "</font></body></html>"); } } else if (jRadioButtonEmpruntByDate.isSelected()) { try { this.searchByDateEmprunt(toSearch); } catch (Exception ex) { Logger.getLogger(TableauDeBord.class.getName()).log(Level.SEVERE, null, ex); jLabelNbFoundEmprunt.setText("<html><body><font color='red'>" + ex.getMessage() + "</font></body></html>"); } } } }
cc28652f-2db7-4725-bb9b-6a7a1b06a2eb
8
static int f(int x,int y,int z){ LinkedList<int[]> cola=new LinkedList<int[]>(); cola.add(new int[]{x,y,z,0});vis[x][y][z]=true; for(int[] u;!cola.isEmpty();){ u=cola.pollFirst(); if(mat[u[0]][u[1]][u[2]]=='E')return u[3]; for(int i=0;i<3;i++) for(int h=-1;h<2;h+=2) if(u[i]+h>=0&&u[i]+h<t[i]){ u[i]+=h; if(!vis[u[0]][u[1]][u[2]]&&mat[u[0]][u[1]][u[2]]!='#'){ cola.add(new int[]{u[0],u[1],u[2],u[3]+1}); vis[u[0]][u[1]][u[2]]=true; } u[i]-=h; } } return MIN_VALUE; }
47eabfcf-55c3-4a62-b20a-99da54259650
4
protected static boolean isAListChar(char character) { switch (character) { case ':': case ';': case '#': case '*': return true; } return false; }
30992f62-ce22-4360-98fe-b8410ad3e94f
4
public void fireSubLWorkerDataAvailableEvent(SubLWorkerEvent event) { if (event.getEventType() != SubLWorkerEvent.DATA_AVAILABLE_EVENT_TYPE) { throw new RuntimeException("Got bad event type; " + event.getEventType().getName()); } synchronized(listeners) { Object[] curListeners = listeners.getListenerList(); for (int i = curListeners.length-2; i >= 0; i -= 2) { if (curListeners[i] == listenerClass) { try { //System.out.println("GOT DATA FOR SUBL CALL: " + event); ((SubLWorkerListener)curListeners[i+1]).notifySubLWorkerDataAvailable(event); } catch (Exception e) { Logger.getLogger(this.getClass().toString()).log(Level.WARNING, e.getMessage(), e); } } } } }
4352ffe8-8d8b-48ce-a564-6b2ddf01cf78
9
public void update() { super.update(); if(fireRate>0) fireRate--; int xa = 0, ya = 0; if(anim < 7500) anim++; else anim = 0; if(input.up.down) ya--; if(input.down.down) ya++; if(input.left.down) xa--; if(input.right.down) xa++; if(xa != 0 || ya != 0) { move(xa, ya); walking = true; } else { walking = false; } clear(); updateShooting(); if(health <= 0){ dead = true; } }
70901f75-762d-4559-935f-55ddc1043d84
6
public static void loadBinary(LC3Bridge bridge, String filename) throws IOException { FileInputStream stream = null; byte[] buffer = null; try { File handle = new File(filename); stream = new FileInputStream(handle); buffer = new byte[(int)handle.length()]; stream.read(buffer); } catch (IOException e) { throw new LC3Exception("An error occurred while opening object file '" + filename + "'"); } catch (Exception e) { throw new LC3Exception("Failed to parse object file '" + filename + "'"); } finally { if (stream != null) stream.close(); } if (buffer.length % 2 == 1) throw new LC3Exception("Length of the object file '" + filename + "'parsed is wrong"); if (buffer.length < 2) throw new LC3Exception("The object file '" + filename + "' is empty or corrupted"); // get start location int counter = bytes2int(buffer[0], buffer[1]); bridge.setPC(counter); for (int i = 2; i < buffer.length; i+= 2) { int bytes = bytes2int(buffer[i], buffer[i + 1]); //System.out.println("writing " + Tools.int2bin(bytes) + " to x" + Integer.toHexString(counter)); bridge.writeMemory(counter, bytes); counter++; } }
3874847a-bd99-495d-b825-c57d241b5efb
4
protected int read_(long pos, byte[] b, int offset, int len) throws IOException { file.seek(pos); int n = file.read(b, offset, len); if (debugAccess) { if (showRead) System.out.println(" **read_ " + location + " = " + len + " bytes at " + pos + "; block = " + (pos / buffer.length)); debug_nseeks.incrementAndGet(); debug_nbytes.addAndGet(len); } if (extendMode && (n < len)) { //System.out.println(" read_ = "+len+" at "+pos+"; got = "+n); n = len; } return n; }
dd106559-d769-472d-ae16-c453cf800ab0
2
public void multiply() { System.out.println("Enter the range "); int n=in.nextInt(); int[][] multTable=new int[n+1][n+1]; for (int i=1;i<=n;i++) { System.out.println("Multiplication table of " + i); for (int j=1;j<=n;j++)//j<=10 { multTable[i][j] = i*j; System.out.println(i + "*" + j + " = " + (i * j)); } } }
e9e4bde1-fd44-46cb-b637-3ba6abd19c58
4
private void saveParagraph(org.w3c.dom.Document xmlDoc, Paragraph para, Element paraElt) { for (Sentence sent : para.getSentences()) { Element sentElt = xmlDoc.createElement("sentence"); sentElt.setAttribute("id", Integer.toString(sent.getId())); // prepare plain text Element plainTextElt = xmlDoc.createElement("plainText"); plainTextElt.setTextContent(sent.getPlainText()); sentElt.appendChild(plainTextElt); // prepare constituency parse Element parseElt = xmlDoc.createElement("constituencyParse"); parseElt.setTextContent(sent.getConstituencyParse()); sentElt.appendChild(parseElt); // prepare tokens if (sent.isTokenized()) { Element tokensElt = xmlDoc.createElement("tokens"); for (Token token : sent.getTokens()) { Element tokenElt = xmlDoc.createElement("token"); tokenElt.setAttribute("id", sent.getId() + "." + token.getId()); tokenElt.setTextContent(token.getStr()); for (String key : token.getKeys()) { tokenElt.setAttribute(key, token.getKeyVal(key)); } tokensElt.appendChild(tokenElt); } sentElt.appendChild(tokensElt); } paraElt.appendChild(sentElt); } }
ed44096b-b162-45f5-a4d8-40f9a244474f
9
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ if (args.length == 0){ sender.sendMessage("This server is running " + Bukkit.getName() + " version " + Bukkit.getVersion() + " (Implementing API version " + Bukkit.getBukkitVersion() + ")"); } else { StringBuilder name = new StringBuilder(); for (String arg : args) { if (name.length() > 0) { name.append(' '); } name.append(arg); } Plugin plugin = Bukkit.getPluginManager().getPlugin(name.toString()); if (plugin == null || vanillaPlugin.getConfigHandler().getHiddenPlugins().contains(plugin.getDescription().getName().toLowerCase())){ sender.sendMessage("This server is not running any plugin by that name."); sender.sendMessage("Use /plugins to get a list of plugins."); }else { PluginDescriptionFile desc = plugin.getDescription(); sender.sendMessage(ChatColor.GREEN + desc.getName() + ChatColor.WHITE + " version " + ChatColor.GREEN + desc.getVersion()); if (desc.getDescription() != null) { sender.sendMessage(desc.getDescription()); } if (desc.getWebsite() != null) { sender.sendMessage("Website: " + ChatColor.GREEN + desc.getWebsite()); } if (!desc.getAuthors().isEmpty()) { if (desc.getAuthors().size() == 1) { sender.sendMessage("Author: " + getAuthors(desc)); } else { sender.sendMessage("Authors: " + getAuthors(desc)); } } } } return true; }
6d50708f-4ee1-4bf2-a92c-3aa2b474b0bf
4
public boolean SetTime(int responseTime){ boolean test = false; if (test || m_test) { System.out.println("OthelloAI :: SetTime() BEGIN"); } m_time = responseTime; if (test || m_test) { System.out.println("ConnectFourAI :: SetTime() END"); } return true; }
38b69e7a-976f-4f71-95b2-7bebe9a8990e
0
public void setAge(int age) { Age = age; }
69d85089-e0b9-4b8a-9b67-85c86eb03f6c
0
private PublicStaticFieldSingleton () {};
f8121456-6c10-456c-8ec5-70a71b239dfa
4
public String toFirstUpperCase(String title) { char[] c = title.toCharArray(); for(int i = 0; i < c.length; i++) { if(c[i] != ' ' && (i == 0 || c[i - 1] == ' ')) c[i] = (char)(c[i] - 32); } return new String(c); }
36370c1b-f4e0-437e-ba15-a1a44ddd3ba0
3
private CtClass searchImports(String orgName) throws CompileError { if (orgName.indexOf('.') < 0) { Iterator it = classPool.getImportedPackages(); while (it.hasNext()) { String pac = (String)it.next(); String fqName = pac + '.' + orgName; try { CtClass cc = classPool.get(fqName); // if the class is found, classPool.recordInvalidClassName(orgName); return cc; } catch (NotFoundException e) { classPool.recordInvalidClassName(fqName); } } } throw new CompileError("no such class: " + orgName); }
bdf36945-6ace-481f-b9f2-e4f3047363dd
4
protected void stableRun() { // Timing varibles long startTime = System.nanoTime(), waitTime, urdTime = 0; int targetTime = 1000 / targetFramerate; long tTime = 0; int fCount = 0; while (running) { // Increment the amount of frames that have passed by one fCount++; // Add the time it took to complete the last frame tTime += System.nanoTime() - startTime; // Turn the totaled time between frame and convert it into seconds. // If a second has passed, make the framerate the amount of frames // passed and reset all varibles. if ((double) tTime / (double) 1e9 >= 1) { framerate = fCount; tTime = 0; fCount = 0; } // Calculate the delta (time to complete last frame) double delta = (double) (System.nanoTime() - startTime) / (double) 1e9; // Get the start time to compare against startTime = System.nanoTime(); // Update THEN render the game listener.threadTick(this, delta); // Get the difference in time from the start time to now // Also convert it into milliseconds so that sleep can use it urdTime = (System.nanoTime() - startTime) / (long) 1e6; // Calculate the difference in the time and target time so we can // sleep just the right amount waitTime = targetTime - urdTime; try { // Sleep the thread as long as waitTime isn't a negative value if (waitTime >= 0) Thread.sleep(waitTime); } catch (Exception e) { // Print any errors e.printStackTrace(); } } }
c9a24562-243e-4e5b-a7dd-7a50a6dd0c20
0
Caller(Incrementable cbh) { callbackReference = cbh; }
53d3a86e-b1d7-4e29-89b4-b6ca40c572f5
3
private double[] calculateNetworkConsumption(Message message, SoftwareSystem system) { double consumption[] = { 0, -1 }; for (Connector connector : project.getConnectors()) if (connector.getComponent().equals(message.getSender()) && connector.getToInterface().equals(message.getSignature())) { consumption[0] = connector.getEnergyPoints(); consumption[1] = Utils.consumptionNetwork(connector.getSize(), getNetworkDevices((Component) message.getSender(), system), getNetworkDevices((Component) message.getReceiver(), system))[1]; } return consumption; }
9f3c0585-a76c-430c-9115-992d665c418e
7
private boolean playerAttackCollision(){ if(!weapon){ CollisionResults [] results = new CollisionResults [4]; for(int i = 0; i < results.length; i++){ results[i] = new CollisionResults(); } BoundingVolume bv = ((Node)getStageNode().getChild("Player1")).getChild("Collider").getWorldBound(); ((Node)spatial).getChild("Hand_R").collideWith(bv, results[0]); if(results[0].size() > 0){ return true; } ((Node)spatial).getChild("Hand_L").collideWith(bv, results[1]); if(results[1].size() > 0){ return true; } ((Node)spatial).getChild("Foot_R").collideWith(bv, results[2]); if(results[2].size() > 0){ return true; } ((Node)spatial).getChild("Foot_L").collideWith(bv, results[3]); if(results[3].size() > 0){ return true; } }else{ CollisionResults results = new CollisionResults(); BoundingVolume bv = ((Node)getStageNode().getChild("Player1")).getChild("Collider").getWorldBound(); ((Node)spatial).getChild("Weapon_R").collideWith(bv, results); if(results.size() > 0){ return true; } } return false; }
01a8cc92-1c25-4a26-8789-237b128c24c7
5
@EventHandler(priority = EventPriority.HIGHEST) public void onPlayerBetInteract(PlayerInteractEvent event) { ItemStack itemInHand = event.getItem(); if(event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { Block clickedBlock = event.getClickedBlock(); if(! FancyRoulette.instance.tableManager.isBlockTile(clickedBlock)) return; if(itemInHand == null) { event.getPlayer().sendMessage(ChatColor.GOLD + "You need to have roulette tokens to play the roulette!"); return; } else if(! isToken(itemInHand)) { event.getPlayer().sendMessage(ChatColor.RED + "You can only place roulette tokens on roulette tiles!"); return; } event.setCancelled(false); // Bypass shit like worldguard. int tableId = FancyRoulette.instance.tableManager.getTableId(clickedBlock); int maxNumberOfBets = FancyRoulette.instance.getConfig().getInt("maximum bets per player"); if(bets.getNumberOfBets(event.getPlayer()) >= maxNumberOfBets) { event.getPlayer().sendMessage(ChatColor.RED + "You cannot have more bets than " + maxNumberOfBets + "!"); } event.getPlayer().sendMessage(ChatColor.GOLD + "You placed a bet for " + ChatColor.BOLD + getWoolNameIfWool(clickedBlock) + ChatColor.RESET + " " + ChatColor.GOLD + " on table " + ChatColor.AQUA + tableId + ChatColor.WHITE + "!"); bets.addBet(event.getPlayer(), clickedBlock.getRelative(BlockFace.UP)); } }
03536735-c536-4e48-b18d-f8a091b9dea6
3
public void dostepnyFilm(Osoba osoba, Film film) { osoba = em.find(Osoba.class, osoba.getId()); film = em.find(Film.class, film.getId()); Film usun = null; // lazy loading here (person.getCars) for (Film filmy : osoba.getFilm()) if (filmy.getId().compareTo(film.getId()) == 0) { usun = filmy; break; } if (usun != null) osoba.getFilm().remove(usun); film.setWypoz(false); }
2a1e6e99-38fc-4ce7-86ba-5cd350cde827
9
public AlphabetDialog() { this.setTitle("Customize Alphabet"); this.getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); this.setModal(true); this.setBounds(200, 200, 400, 600); this.changed = false; //Initialize the alphabet combobox final JTextArea taSymbols = new JTextArea(); taSymbols.setLineWrap(true); taSymbols.setRows(10); final JComboBox<DefaultAlphabet> cbPresetAlphas = new JComboBox<DefaultAlphabet>(); for (DefaultAlphabet alpha : DefaultAlphabet.values()) { if (!DefaultAlphabet.CUSTOM.equals(alpha)) { cbPresetAlphas.addItem(alpha); } } cbPresetAlphas.setSelectedItem(DefaultAlphabet.BINARY.toString()); cbPresetAlphas.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Set the textArea's content according to the selected Alphabet char[] selected = ((DefaultAlphabet) cbPresetAlphas.getSelectedItem()).getAlphabet(); if (!DefaultAlphabet.CUSTOM.equals(cbPresetAlphas.getSelectedItem())) { taSymbols.setText(""); for (char symbol : selected) { taSymbols.setText(taSymbols.getText() + " " + symbol); } } } }); this.getContentPane().add(cbPresetAlphas); Component rigidArea = Box.createRigidArea(new Dimension(40, 40)); this.getContentPane().add(rigidArea); JLabel lblCustomizeAlphabetSymbols = new JLabel("Customize Alphabet Symbols:"); this.getContentPane().add(lblCustomizeAlphabetSymbols); Component rigidArea_1 = Box.createRigidArea(new Dimension(20, 20)); this.getContentPane().add(rigidArea_1); taSymbols.setText("0 1"); taSymbols.addKeyListener(new KeyListener() { @Override public void keyReleased(KeyEvent e) { if (!changed) { cbPresetAlphas.addItem(DefaultAlphabet.CUSTOM); cbPresetAlphas.setSelectedItem(DefaultAlphabet.CUSTOM); changed = true; } } @Override public void keyTyped(KeyEvent e) {} @Override public void keyPressed(KeyEvent e) {} }); this.getContentPane().add(taSymbols); JLabel lblHint = new JLabel("Each Character must be seperated by a space"); getContentPane().add(lblHint); JPanel pnlButtons = new JPanel(); this.getContentPane().add(pnlButtons); JButton btnCancel = new JButton("Cancel"); btnCancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cancelled = true; setVisible(false); } }); pnlButtons.add(btnCancel); JButton btnConfirm = new JButton("Confirm"); btnConfirm.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cancelled = false; //Set the alphabet to the custom one, if custom option has been chosen if (DefaultAlphabet.CUSTOM.equals(cbPresetAlphas.getSelectedItem())) { StringTokenizer tokenizer = new StringTokenizer(taSymbols.getText(), " "); String customAlpha = ""; String token = ""; while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken().trim(); if (token.length() == 1 && !customAlpha.contains(token)) { customAlpha += token; } } alphabet = customAlpha.toCharArray(); } else { alphabet = ((DefaultAlphabet)cbPresetAlphas.getSelectedItem()).getAlphabet(); } setVisible(false); } }); pnlButtons.add(btnConfirm); }
d02775dc-874d-47f3-bece-515addb886d0
1
public int[] generate(int nplayers, int bowlsize) { int nfruits = nplayers * bowlsize; int[] dist = new int[12]; int unit = nfruits / 12; dist[0] = nfruits - unit * 11; for (int i = 1; i < 12; i++) dist[i] = unit; return dist; }
f6b34ffd-dc61-4671-87b1-7e462dad3fc8
1
public static double calGain(double rootEntropy, ArrayList<Double> subEntropies, ArrayList<Integer> setSizes, int data) { double gain = rootEntropy; for(int i = 0; i < subEntropies.size(); i++) { gain += -((setSizes.get(i) / (double)data) * subEntropies.get(i)); } return gain; }
cbb178b4-a575-434f-bea2-3547e14098ca
3
public static JSONObject toJSONObject(String string) throws JSONException { String name; JSONObject jo = new JSONObject(); Object value; JSONTokener x = new JSONTokener(string); jo.put("name", x.nextTo('=')); x.next('='); jo.put("value", x.nextTo(';')); x.next(); while (x.more()) { name = unescape(x.nextTo("=;")); if (x.next() != '=') { if (name.equals("secure")) { value = Boolean.TRUE; } else { throw x.syntaxError("Missing '=' in cookie parameter."); } } else { value = unescape(x.nextTo(';')); x.next(); } jo.put(name, value); } return jo; }
eabf6d0e-dd87-4be9-900f-e7382be4aad5
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_tasa.getText().equals("")){ posicionarAyuda(field_tasa.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); } } } }
2872fa7c-0e16-49cc-89a2-4a88b079b43c
7
public void increaseRope(int x , int y) { if (ropelength < 125){ ropelength ++; } x += 1; y += 2; switch (ropelength) { case 1: getWorld().addObject(rope, x, y); getWorld().addObject(ropeman, x, y+3); break; case 25: y+= 2; getWorld().addObject(rope2, x, y); ropeman.setLocation(x, y+3); break; case 50: y+= 4; getWorld().addObject(rope3, x, y); ropeman.setLocation(x, y+3); break; case 75: y+= 6; getWorld().addObject(rope4, x, y); ropeman.setLocation(x, y+3); break; case 100: y+= 8; getWorld().addObject(rope5, x, y); ropeman.setLocation(x, y+3); break; case 125: y+= 10; getWorld().addObject(rope6, x, y); ropeman.setLocation(x, y+3); break; } }
d9b0c734-b09f-4e2a-9a17-ce44d8bb3732
6
public static int minCut4(String s) { int length = s.length(); int[] dp = new int[length + 1]; boolean[][] parlin = new boolean[length][length]; for (int i = length; i >= 0; i--) { dp[i] = length - i; } for (int i = length - 1; i >= 0; i--) { for (int j = i; j < length; j++) { if (s.charAt(i) == s.charAt(j) && (j - i < 2 || parlin[i + 1][j - 1])) { parlin[i][j] = true; dp[i] = Math.min(dp[i], dp[j + 1] + 1); } } } return dp[0] - 1; }
b616d768-8969-4850-bd11-1b0531f7d241
5
public void convertInfixArrayToPostFixArray(List<BaseOperClass> infixEquationArray) { Stack<BaseOperClass> tempStack = new Stack<BaseOperClass>(); for(BaseOperClass token : infixEquationArray) { if(token instanceof Operator) { while(tempStack.size() != 0 && tempStack.peek().getPrecedence() >= token.getPrecedence()) { this.postfixEquationArray.add(tempStack.pop()); } tempStack.push(token); } else { this.postfixEquationArray.add(token); } } while(tempStack.size() !=0) { this.postfixEquationArray.add(tempStack.pop()); } }
07b92b6a-948b-4275-b874-0580342e6456
9
private double runBestAlgorithm(String feature) { // TODO Auto-generated method stub //String language, double np, CoNLLHandler ch, String trainingCorpus, String rootHandling File f=new File(feature); if (f.exists()) { CoNLLHandler ch=new CoNLLHandler(trainingCorpus); AlgorithmTester at=new AlgorithmTester("lang",this.percentage,ch,trainingCorpus,optionMenosR); double result=0.0; try { if (bestAlgorithm.equals("nivreeager")) { result=at.executeNivreEager(feature); } if (bestAlgorithm.equals("nivrestandard")) { //A PARTIR DE LA PROXIMA VERSION PONER EL FEATURE CORRESPONDIENTE!!! //result=at.executeNivreEager(feature); result=at.executeNivreStandard(feature); } if (bestAlgorithm.equals("covnonproj")) { //result=at.executeNivreEager(feature); result=at.executeCovingtonNonProjective(feature); } if (bestAlgorithm.equals("covproj")) { //result=at.executeNivreEager(feature); result=at.executeCovingtonProjective(feature); } if (bestAlgorithm.equals("stackproj")) { //result=at.executeNivreEager(feature); result=at.executeStackProjective(feature); } if (bestAlgorithm.equals("stackeager")) { //result=at.feature); result=at.executestackEager(feature); } if (bestAlgorithm.equals("stacklazy")) { //result=at.executeNivreEager(feature); result=at.executeStackLazy(feature); } }catch(Exception e) { System.out.println("Feature not valid."); } //System.out.println(result); return result; } return 0.0; }
02c10883-3d9e-4d7a-b2ca-5f337d0cef88
7
private long set_clock_time(String config_value) { String value = "0"; String identifier = ""; long time = 0; /* loop to split string into value and identifier */ for (int i = 0; i < config_value.length(); i++) { if( (config_value.charAt(i) >= '0') && (config_value.charAt(i) <= '9') ) { value += config_value.charAt(i); continue; } identifier = config_value.substring(i, config_value.length()); time = Long.parseLong(value); break; } if(identifier.equals("ms") || (identifier.length() == 0)) { log.log(3, log_key, "calculated clock time: ", new Long(time).toString(), "ms\n"); } else if(identifier.equals("Hz") || identifier.equals("hz") ) { time = (long)((1000 / time) + 0.5); log.log(3, log_key, "calculated clock time: ", new Long(time).toString(), "ms\n"); } else { log.log(0, log_key, "\n\n" + "ERROR: value from config file is not valid.\n" + "DETAILED ERROR:\n" + " value 'takt_frequenzy' is not valid!\n" + " 'takt_frequenzy' is set to: '" + config_value + "'\n" + " should be be set to something like:\n" + " -100ms for 100 milliseconds\n" + " -50hz or 50Hz for 50 Hertz\n" + " -0 if interpreter should evaluate without frequenzy.\n" + " as expected the size can vary.\n" + "note: if no identifier (ms/hz/Hz) is specified, value is read as ms.\n\n" ); Main.exit(); } return time; }
131fb6b3-f1f4-4744-9636-5bb33f4912ac
8
private static void BinaryTreeMenu(BinaryTree<Integer> BinaryTree){ System.out.println("\nWhat do you want to do ?"); System.out.println(" 1) Insert"); System.out.println(" 2) Search"); System.out.println(" 3) Delete"); System.out.println(" 4) Print"); System.out.println("Enter your option and hit enter: (from 1 to 4)"); try{ choose = in.nextInt(); switch (choose){ case 1: try{ System.out.println("Insert the number to add: "); size = in.nextInt(); start = System.nanoTime(); BinaryTree.insert(size); end = System.nanoTime(); System.out.println("Adding lasted: " + (end - start)); break; }catch(Exception e){ break; } case 2: try{ System.out.println("Insert the number to search: "); size = in.nextInt(); start = System.nanoTime(); System.out.println("Does that number exist? " + BinaryTree.exists(size)); end = System.nanoTime(); System.out.println("Adding lasted: " + (end - start)); break; }catch(Exception e){ break; } case 3: try{ System.out.println("Insert the number to delete: "); size = in.nextInt(); start = System.nanoTime(); BinaryTree.delete(size); end = System.nanoTime(); System.out.println("Delete lasted: " + (end - start)); break; }catch(Exception e){ break; } case 4 : BinaryTree.describe(); System.out.println("\n"); } System.out.println("Do you want to exit the Binary Tree ? (Yes / No)"); exitBinaryTree(BinaryTree); }catch(Exception e){ System.out.println("Do you want to exit the Binary Tree ? (Yes / No)"); exitBinaryTree(BinaryTree); } }
341ff00c-c6c2-459d-ac4e-4c2ba2ad0533
1
public static void spawnSkeletonWarriorGold (Location loc, int amount) { int i = 0; while (i < amount) { Skeleton SkeletonWarriorIron = (Skeleton) loc.getWorld() .spawnEntity(loc, EntityType.SKELETON); SkeletonWarriorIron.getEquipment().setChestplate( new ItemStack(Material.GOLD_CHESTPLATE, 1)); SkeletonWarriorIron.getEquipment().setHelmet( new ItemStack(Material.GOLD_HELMET, 1)); SkeletonWarriorIron.getEquipment().setLeggings( new ItemStack(Material.GOLD_LEGGINGS, 1)); SkeletonWarriorIron.getEquipment().setBoots( new ItemStack(Material.GOLD_BOOTS, 1)); SkeletonWarriorIron.getEquipment().setItemInHand( new ItemStack(Material.BOW, 1)); SkeletonWarriorIron.getEquipment().setHelmetDropChance(0.50F); SkeletonWarriorIron.getEquipment().setChestplateDropChance(0.50F); SkeletonWarriorIron.getEquipment().setItemInHandDropChance(0.50F); SkeletonWarriorIron.addPotionEffect(new PotionEffect( PotionEffectType.SPEED, 2147483647, 1)); SkeletonWarriorIron.setCanPickupItems(false); i++; } }
5f0b5e65-cb07-421e-8f82-8aeeaa04d4c4
7
public boolean equals (Particulier part) { boolean exists = false; if ((this.getNom().equals(part.getNom())) && (this.getPrenom().equals(part.getPrenom())) && (this.getCivilite().equals(part.getCivilite())) && (this.getAdresse().equals(part.getAdresse())) && (this.getTelD().equals(part.getTelD())) && (this.getTelP().equals(part.getTelP())) && (this.getEmail().equals(part.getEmail()))) { exists = true; } return exists; }
38798f23-f1e5-4cd0-965e-cd76a7bb1438
4
public void move(String dir) { if (dir.equalsIgnoreCase("up")) { ypos--; } else if (dir.equalsIgnoreCase("down")) { ypos++; } else if (dir.equalsIgnoreCase("left")) { xpos--; } else if (dir.equalsIgnoreCase("right")) { xpos++; } }
21d3ea3b-fc99-4bef-85df-0a166dd52e69
8
public void lookForConstructorCall() { type01Count = cons.length; for (int i = 0; i < type01Count;) { MethodAnalyzer current = cons[i]; FlowBlock header = cons[i].getMethodHeader(); /* Check that code block is fully analyzed */ if (header == null || !header.hasNoJumps()) return; StructuredBlock body = cons[i].getMethodHeader().block; int type = isStatic ? 0 : getConstructorType(body); if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_CONSTRS) != 0) GlobalOptions.err.println("constr " + i + ": type" + type + " " + body); switch (type) { case 0: // type0 are moved to the beginning. cons[i] = cons[type0Count]; cons[type0Count++] = current; /* fall through */ case 1: // type1 are not moved at all. i++; break; case 2: // type2 are moved to the end. cons[i] = cons[--type01Count]; cons[type01Count] = current; break; } } }
40044155-d874-4e4e-804e-1e8451308fcf
6
public static void main(String[] args) { Locale.setDefault(Locale.US); Scanner s = new Scanner(System.in); double a = s.nextDouble(); double b = s.nextDouble(); double c = s.nextDouble(); if(Math.abs(b-c) < a && a < b+c && Math.abs(a-c) < b && b < a+c && Math.abs(a-b) < c && c < a+b){ System.out.printf("Perimetro = %.1f\n", a+b+c); }else{ System.out.printf("Area = %.1f\n", (a+b)*c/2); } }
97e36f13-aeef-4124-ba4a-3bc7593538c8
6
private void avaliarCaso(boolean avaliacao) { try { admin.avaliarCaso(avaliacao); removerPainelCaso(); } catch (SQLException ex) { JOptionPane.showMessageDialog(this, "Erro ao atualizar a base de dados... Por favor contacte um administrador.\nA sair do programa..."); System.exit(0); } catch (RemoteException ex) { JOptionPane.showMessageDialog(this, "Erro ao contactar o servidor... Tente novamento.\nSe o erro persistir contacte um administrador"); } try { apresentarCaso(admin.receberNovoCaso()); }catch (OfertaEmpregoNotFoundException | OfertaRecursosNotFoundException | UserNotLoggedInException | NoPrivilegesException ex) { } catch (RemoteException ex) { Logger.getLogger(AdminAPP.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { JOptionPane.showMessageDialog(this, "Erro ao contactar a base de dados... Tente novamente. Se o erro persistir contacte um administrador."); } catch (IOException ex) { JOptionPane.showMessageDialog(this, "Erro no sistema de ficheiros do servidor. Por favor, contacte um administrador."); } }
b927c93a-443d-478a-9b5c-3bd912923d11
9
public ParseException generateParseException() { jj_expentries.clear(); boolean[] la1tokens = new boolean[41]; if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 15; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1<<j)) != 0) { la1tokens[j] = true; } if ((jj_la1_1[i] & (1<<j)) != 0) { la1tokens[32+j] = true; } } } } for (int i = 0; i < 41; i++) { if (la1tokens[i]) { jj_expentry = new int[1]; jj_expentry[0] = i; jj_expentries.add(jj_expentry); } } jj_endpos = 0; jj_rescan_token(); jj_add_error_token(0, 0); int[][] exptokseq = new int[jj_expentries.size()][]; for (int i = 0; i < jj_expentries.size(); i++) { exptokseq[i] = jj_expentries.get(i); } return new ParseException(token, exptokseq, tokenImage); }
668853ca-e79f-4cca-83e2-1538be754ef1
5
private void loadTowerPref() { Scanner scanner = null; try { scanner = new Scanner(new FileInputStream("res" + File.separator + "towerPref.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } String currentLine; String[] lineTowerLevelArray; String[] lineTowerPrefArray; ArrayList<ArrayList<int[]>> prefList = new ArrayList<ArrayList<int[]>>(); ArrayList<int[]> levelsList = new ArrayList<int[]>(); int[] towerPref = new int[6]; while (scanner.hasNext()) { currentLine = scanner.nextLine(); //if the line starts with a # it's a comment so ignore it. if (!(currentLine.substring(0, 1)).equals("#")) { lineTowerLevelArray = currentLine.split(";"); //now we have an array of all the upgrades //loop through each and split the line by the commas and add it to the array list for (int i = 0; i < lineTowerLevelArray.length; i++) { lineTowerPrefArray = lineTowerLevelArray[i].split(","); for (int j = 0; j < lineTowerPrefArray.length; j++) { towerPref[j] = Integer.parseInt(lineTowerPrefArray[j]); } levelsList.add(Arrays.copyOf(towerPref, towerPref.length)); } prefList.add((ArrayList<int[]>) levelsList.clone()); levelsList.clear(); } } Tower.setDefaults(prefList); }
5eb50d18-06b8-4d36-bf04-a02c879f7b78
8
private StringBuilder add(CharSequence num1, CharSequence num2) { StringBuilder builder = new StringBuilder(); int maxLen = Math.max(num1.length(), num2.length()); boolean carryOne = false; for (int i = 0; i < maxLen; i ++) { char c1 = '0'; char c2 = '0'; if (i < num1.length()) { c1 = num1.charAt(num1.length() - i - 1); } if (i < num2.length()) { c2 = num2.charAt(num2.length() - i - 1); } int sum = c1 - '0' + c2 - '0'; if (carryOne) { sum ++; } if (sum > 9) { carryOne = true; sum -= 10; } else { carryOne = false; } builder.insert(0, sum); } if (carryOne) { builder.insert(0, 1); } for (int i = 0; i < builder.length() - 1; i ++) { if (builder.charAt(i) == '0') { builder.deleteCharAt(i); i --; } else { break; } } return builder; }
0846b2ad-5a6f-426c-bfa7-52f5d649a59f
5
public void mouseMoved(MouseEvent e) { if (shiftPressed) { int oldMouseX = mouseX; int oldMouseY = mouseY; mouseX = e.getX(); mouseY = e.getY(); if (mouseX > oldMouseX) { // Mouse moved right // scene.adjustCameraX(.01f); } else if (mouseX < oldMouseX) { // Mouse moved left // scene.adjustCameraX(-.01f); } if (mouseY > oldMouseY) { // Mouse moved Up // scene.adjustCameraY(-.01f); } else if (mouseY < oldMouseY) { // Mouse moved Down // scene.adjustCameraY(.01f); } } }
407c59a2-a127-4160-bf2e-388fb4feb5a1
5
@Override public void actionPerformed(ActionEvent arg0) { // Making a lot of assumptions about what could possibly result in an event String command = ((JMenuItem) arg0.getSource()).getText(); if(command.equals(HIDE_MENU_ITEM_TEXT)) { toggleVisible(); } else if(command.equals(SAVE_MENU_ITEM_TEXT)) { JFileChooser chooser = new JFileChooser(); int returnVal = chooser.showSaveDialog(frame); if(returnVal == JFileChooser.APPROVE_OPTION) { File logFile = chooser.getSelectedFile(); PrintWriter printWriter = null; try { printWriter = new PrintWriter(new FileWriter(logFile)); printWriter.write(area.getText()); // lazy, I know printWriter.flush(); printWriter.close(); } catch(IOException ex) { log.throwing(getClass().getSimpleName(), "actionPerformed(ActionEvent)", ex); ex.printStackTrace(); } finally { if(printWriter != null) { printWriter.close(); } } log.logp(Level.INFO, getClass().getSimpleName(), "actionPerformed(ActionEvent)", "Wrote log to \"" + logFile.getName() + "\"."); } else { log.logp(Level.WARNING, getClass().getSimpleName(), "actionPerformed(ActionEvent)", "User canceled file selection."); } } }
8e9a98c5-ce87-4c08-b397-05666d8c9468
6
public ListFiles(String wd){ thisFolder=new File(wd); listOfFiles= thisFolder.listFiles(); int jj=0,ii=0; System.out.println("Directories"); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isDirectory()) { jj++; System.out.println("["+jj+"] "+ listOfFiles[i].getName()); } } ii=jj; if(jj==0) System.out.println("."); System.out.println("Files"); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { jj++; System.out.println("["+jj+"] "+ listOfFiles[i].getName()); } if(ii==jj) System.out.println("."); } }
c15fe874-266d-4155-a5e1-23038b4c50b3
4
public static boolean Connect(String connection, String user, String password){ boolean result = false; try { //String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; // String url = "jdbc:odbc:northwind"; //String username = ""; //String password = ""; //Class.forName(driver); Class.forName("com.mysql.jdbc.Driver").newInstance(); Logger.getLogger(DatabaseConnectie.class.getName()).log(Level.INFO, "Driver instantiated"); con = DriverManager.getConnection("jdbc:mysql:" + connection, user, password); //con = DriverManager.getConnection("jdbc:odbc:" + connection, "", ""); Logger.getLogger(DatabaseConnectie.class.getName()).log(Level.INFO, " Database connection made"); result = true; } catch (ClassNotFoundException ex) { Logger.getLogger(DatabaseConnectie.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(DatabaseConnectie.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(DatabaseConnectie.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(DatabaseConnectie.class.getName()).log(Level.SEVERE, null, ex); } return result; }
fa2cdf0c-7df9-4197-97cc-c1bab823eb3e
7
@Override public List<Integer> getTopRankedRoles(Function func) { final List<ClanPosition> allRoles=new LinkedList<ClanPosition>(); for(final ClanPosition pos : govt().getPositions()) { if((func==null)||(pos.getFunctionChart()[func.ordinal()]!=Authority.CAN_NOT_DO)) allRoles.add(pos); } final List<Integer> roleIDs=new LinkedList<Integer>(); int topRank=Integer.MAX_VALUE; for(final ClanPosition pos : allRoles) { if(pos.getRank() < topRank) topRank=pos.getRank(); } for(final ClanPosition pos : allRoles) { if(pos.getRank() == topRank) roleIDs.add(Integer.valueOf(pos.getRoleID())); } return roleIDs; }
e05a8791-f13c-40fc-a25b-937ae70da18c
0
private void timetablePage(){ timetablePane = new JPanel(); timetablePane.setBackground(SystemColor.activeCaption); timetablePane.setLayout(null); JLabel lblTimetable = new JLabel("Timetable"); lblTimetable.setHorizontalAlignment(SwingConstants.CENTER); lblTimetable.setFont(new Font("Arial", Font.BOLD, 30)); lblTimetable.setBounds(349, 20, 286, 47); timetablePane.add(lblTimetable); db.showBookingDoc(TiT_model, doctorID); TiB_menu.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { cardLayout.show(contentPane, "Menu"); }}); }
0398cec1-3b86-4f1c-99ac-27750b85d644
5
public Object getProperty(Class<?> clazz, Object key) { Object value = this.systemProperties.get(key); if (value != null) { return value; } if (customConfigurator != null) { value = customConfigurator.apply(key); if (value != null) { return value; } } Properties clazzProperties = this.getProperties(clazz); if (clazzProperties != null) { value = clazzProperties.get(key); } return value; }
a1c6a641-d695-43e2-a7ee-51c20c56c224
6
public String nextCDATA() throws JSONException { char c; int i; StringBuffer sb = new StringBuffer(); for (;;) { c = next(); if (end()) { throw syntaxError("Unclosed CDATA"); } sb.append(c); i = sb.length() - 3; if (i >= 0 && sb.charAt(i) == ']' && sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { sb.setLength(i); return sb.toString(); } } }
f7f1f891-8256-453e-b2e5-5582fd10ecc8
8
public int pointsPulled(){ int sum = 0; for(int n : toPar){ if(n > 2) sum += -1; if(n == 2) sum = sum; if(n == 1) sum += 1; if(n == 0) sum += 2; if(n == -1) sum += 4; if(n == -2) sum += 8; if(n == -3) sum += 10; } return sum; }
f4489c7c-b9ee-4ab0-96a2-35109830bf29
8
public static void main(String ar[]) { try{ int k=1; int numD; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); numD=Integer.parseInt(br.readLine()); int y=0; while(k-1 < (numD + y)) { y++;k<<=1; } System.out.println("Y Out" + y); k>>>=1; int[] c = new int[y+numD+1]; int tot = y+numD; System.out.println("Bits : " + y + " k: " + k); for(int i=1;i<=tot;i++) { if(((i)&(i-1)) != 0){ System.out.println("Enter the Databit here : " + i); c[i] = Integer.parseInt(br.readLine()); } else c[i]=0; } int l=1,temp=0; for(int i=1;i<=tot;i++) { l=1; for(int j=0;j<y;j++) { if(((l&i)&((l&i)-1)) == 0) c[l]^= c[i]; l<<=1; } } l=1; for(int j=0;j<y;j++) { System.out.println("C"+l+" : "+c[l]); l<<=1; } } catch(Exception e) { System.out.println(e); } }
5e21856b-0bbc-4de3-a10c-fc9f646afb02
9
public static Map<String, String> simpleCommandLineParser(String[] args) { Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i <= args.length; i++) { String key = (i > 0 ? args[i - 1] : null); String value = (i < args.length ? args[i] : null); if (key == null || key.startsWith("-")) { if (value != null && value.startsWith("-")) value = null; if (key != null || value != null) map.put(key, value); } } return map; }
52c6df8a-ff10-48dc-958d-ad65635d770e
0
public void mouseExited(MouseEvent e) { }
cdcc8ddd-a733-4033-93f4-53f1193d4035
4
private static boolean canDecrease(int[] A, int index, int leng){ int cnt = 0; int secondMax = Integer.MIN_VALUE; for(int k=0;k<leng-1;k++){ if(A[index-k-1]>=A[index]) cnt++; if(k==1) secondMax = A[index-k-1]; } return cnt<2 && secondMax<A[index]-1; }
c2179901-8d13-4d21-9c03-c06436050c42
7
public Window() throws IOException { //Window creation start super(WordUtils.capitalizeFully(properties.propertiesInit("resources/universe.txt", "universe", 0))); Main.setUniverse(WordUtils.capitalizeFully(properties.propertiesInit("resources/universe.txt", "universe", 0))); setSize(800, 600); setResizable(true); setDefaultCloseOperation(EXIT_ON_CLOSE); //Window creation end //Font properties fetch start String outputBackground = properties.propertiesInit("resources/theme properties.txt", "output.background", 0); outputBackground = outputBackground.toUpperCase(); String[] oBA = outputBackground.split(","); String outputForeground = properties.propertiesInit("resources/theme properties.txt", "output.foreground", 0); outputForeground = outputForeground.toUpperCase(); String[] oFA = outputForeground.split(","); String inputBackground = properties.propertiesInit("resources/theme properties.txt", "input.background", 0); inputBackground = inputBackground.toUpperCase(); String[] iBA = inputBackground.split(","); String inputForeground = properties.propertiesInit("resources/theme properties.txt", "input.foreground", 0); inputForeground = inputForeground.toUpperCase(); String[] iFA = inputForeground.split(","); String caretColor = properties.propertiesInit("resources/theme properties.txt", "caret.color", 0); caretColor = caretColor.toUpperCase(); String[] cCA = caretColor.split(","); String fontName = properties.propertiesInit("resources/theme properties.txt", "font", 0); //Font properties fetch end //Font customization start InputStream is = this.getClass().getResourceAsStream( "resources/fonts/" + fontName); Font f = null; try { f = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(12f); } catch (FontFormatException FontCreationFFE) { // TODO Auto-generated catch block FontCreationFFE.printStackTrace(); } catch (IOException FontFileIOE) { // TODO Auto-generated catch block FontFileIOE.printStackTrace(); } //Font customization end //Output text area construction start output = new JTextArea(); output.setEditable(false); output.setLineWrap(true); output.setWrapStyleWord(true); //Output background set start try { Color oBColor = new Color(Integer.parseInt(oBA[0]),Integer.parseInt(oBA[1]),Integer.parseInt(oBA[2])); output.setBackground(oBColor); } catch (NumberFormatException oBColorNFE) { // TODO Auto-generated catch block oBColorNFE.printStackTrace(); } //Output background set end //Output foreground set start try { Color oFColor = new Color(Integer.parseInt(oFA[0]),Integer.parseInt(oFA[1]),Integer.parseInt(oFA[2])); output.setForeground(oFColor); } catch (NumberFormatException oFColorNFE) { // TODO Auto-generated catch block oFColorNFE.printStackTrace(); } //Output foreground set end output.setFont(f); output.setAutoscrolls(true); PrintStream ps = new PrintStream(new TextAreaOutputStream(output)); System.setOut(ps); System.setErr(ps); outputScrollPane = new JScrollPane(output); outputScrollPane.setAutoscrolls(true); caret = (DefaultCaret) output.getCaret(); caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); //Output text area construction end //Input text area construction start input = new JTextField(); input.setEditable(true); //input background set start try { Color iBColor = new Color(Integer.parseInt(iBA[0]),Integer.parseInt(iBA[1]),Integer.parseInt(iBA[2])); input.setBackground(iBColor); } catch (NumberFormatException iBColorNFE) { // TODO Auto-generated catch block iBColorNFE.printStackTrace(); } //input background set end //input foreground set start try { Color iFColor = new Color(Integer.parseInt(iFA[0]),Integer.parseInt(iFA[1]),Integer.parseInt(iFA[2])); input.setForeground(iFColor); } catch (NumberFormatException iFColorNFE) { // TODO Auto-generated catch block iFColorNFE.printStackTrace(); } //input foreground set end //caret color set start try { Color cCColor = new Color(Integer.parseInt(cCA[0]),Integer.parseInt(cCA[1]),Integer.parseInt(cCA[2])); input.setCaretColor(cCColor); } catch (NumberFormatException cCColorNFE) { // TODO Auto-generated catch block cCColorNFE.printStackTrace(); } //caret color set end input.setFont(f); tFS = new TextFieldStreamer(input); input.addKeyListener(tFS); System.setIn(tFS); add(outputScrollPane, BorderLayout.CENTER); add(input, BorderLayout.SOUTH); //Input text area construction end }
60b18e4a-e562-4a3c-8333-de4ab5bdc070
2
@Override public void finishTurn(IPresenter presenter) { MoveResponse response = presenter.getProxy().finishTurn(presenter.getPlayerInfo().getIndex(), presenter.getCookie()); if(response != null && response.isSuccessful()) { presenter.updateServerModel(response.getGameModel()); presenter.setVersion(presenter.getVersion()-1); } else { System.err.println("Error with ending turn in playing state"); } }
3c7d440e-37a3-4e20-af30-31fba53af655
8
private void performOperation(List<String> values){ for(int i = 0;i<values.size();i++) { char[] c = values.get(i).toCharArray(); char previousChar = ' ',currentChar=' '; switch(c[0]){ case 'A': System.out.println("A found"); break; case 'B': System.out.println("B found"); break; case 'C': System.out.println("C found"); break; case 'D': System.out.println("D found"); break; case 'E': System.out.println("E found"); break; case '-': System.out.println("subtraction found"); break; case '+': System.out.println("Addition found"); } } }
4cc31e85-2e84-4b7e-88da-8adfd33db726
9
public static void registerExceptionHandler() { Logger.getLogger(ExceptionHandler.class.getName()).entering(ExceptionHandler.class.getName(), "registerExceptionHandler"); Enumeration<String> loggers = LogManager.getLogManager().getLoggerNames(); while (loggers.hasMoreElements()) { Logger.getLogger(loggers.nextElement()).setLevel(Level.SEVERE); } Handler[] handlers = Logger.getLogger("").getHandlers(); String logLevel = PropertiesManager.getInstance().getKey("logLevel"); if (logLevel != null && Level.parse(logLevel).intValue() < Level.INFO.intValue()) { Logger.getLogger("").setLevel(Level.parse(logLevel)); } else { Logger.getLogger("").setLevel(Level.INFO); // Min level to accept log message } boolean registerHandlers = true; for (Handler handler : handlers) { if (handler instanceof ConsoleHandler) { if (logLevel != null) { handler.setLevel(Level.parse(logLevel)); Logger.getLogger(ExceptionHandler.class.getName()).log(Level.INFO, "Log level set to {0}", logLevel); } else { handler.setLevel(Level.SEVERE); } } if (handler instanceof ExceptionHandler) { registerHandlers = false; } } if (registerHandlers) { try { Logger.getLogger("").addHandler(new FileHandler(new File(OSBasics.getAppDataDir(), "log.txt").toString())); } catch (IOException | SecurityException ex) { Logger.getLogger(ExceptionHandler.class.getName()).log(Level.SEVERE, "Can't log messages to the log file", ex); } Logger.getLogger("").addHandler(new ExceptionHandler()); } Logger.getLogger(ExceptionHandler.class.getName()).exiting(ExceptionHandler.class.getName(), "registerExceptionHandler"); }
527fdc9d-7d71-446f-97a6-87f0aa30d8dd
2
private void checkportfolio() { String response = "Your current balance is $" + user.getBalance(); System.out.println("Your current balance is $" + user.getBalance()); ArrayList<UserStocks> portfolio = user.getUserStock(); if (portfolio != null) { System.out.println("Your portfolio is as follows :"); System.out .println("TickerName \t\t\t Full Name \t\t\t Current Price \t\t\t Quantity"); response += "\nYour portfolio is as follows :" + "\nTickerName \t\t\t Full Name \t\t\t Current Price \t\t\t Quantity"; for (UserStocks e : portfolio) { System.out.println(e.getTickername() + " \t\t\t " + PriceUpdater.name(e.getTickername()) + " \t\t\t " + PriceUpdater.price(e.getTickername()) + " \t\t\t " + e.getNo()); response += "\n" + e.getTickername() + " \t\t\t " + PriceUpdater.name(e.getTickername()) + " \t\t\t " + PriceUpdater.price(e.getTickername()) + " \t\t\t " + e.getNo(); } } else { System.out.println("You do not have any stocks yet"); response += "\nYou do not have any stocks yet"; } currentCommand = ""; sendToUser(response); }
5d89ebb2-150d-4232-97ca-e65d4536b566
8
public static String getMessage(int status) { // method from Response. // Does HTTP requires/allow international messages or // are pre-defined? The user doesn't see them most of the time switch (status) { case 200: if (st_200 == null) st_200 = sm.getString("sc.200"); return st_200; case 302: if (st_302 == null) st_302 = sm.getString("sc.302"); return st_302; case 400: if (st_400 == null) st_400 = sm.getString("sc.400"); return st_400; case 404: if (st_404 == null) st_404 = sm.getString("sc.404"); return st_404; } return sm.getString("sc." + status); }
0058a1c0-8676-41ba-99ce-d30cef0405bc
7
public synchronized Connection getConnection() { Connection connection = null; // Check if there is a connection available. There could be times when all the // connections in the pool may be used up if (connectionPool.size() > 0) { connection = connectionPool.get(0); connectionPool.remove(0); dbPoolIdleSize--; if (!testConnection(connection)) { try { if (!connection.isClosed()) connection.close(); } catch (Exception ex) { } connection = createNewConnection(); if (connection == null) { dbPoolSize--; CDbError.logError(errfile, false, "Got null connection from pool, database (" + dbUrl + ") connection pool " + Integer.toString(dbPoolSize), null); } } } // add a new connection if below the limit else if (dbPoolSize < dbPoolMax) { connection = createNewConnection(); if (connection == null) CDbError.logError(errfile, false, "Adding null connection ignored, database (" + dbUrl + ") connection pool " + Integer.toString(dbPoolSize), null); else { dbPoolSize++; CDbError.logError(errfile, false, "Added connection to database (" + dbUrl + ") connection pool " + Integer.toString(dbPoolSize), null); } } else { CDbError.logError(errfile, false, "Database (" + dbUrl + ") connection pool cannot be extended " + Integer.toString(dbPoolSize), null); } return(connection); }
3a38e2c8-b6ff-4924-a337-409d98888e7b
2
private void initFond(Graphics2D g) { if (!initiated) { InputStream is = this.getClass().getClassLoader() .getResourceAsStream("fonts/TechnoHideo.ttf"); try { font = Font.createFont(Font.TRUETYPE_FONT, is); } catch (Exception e) { e.printStackTrace(); font = new Font(Font.SANS_SERIF, 4, 4); } font = font.deriveFont(40.0f); initiated = true; } }
26ff439a-9eb0-45b4-a97a-6795255eca85
9
public static void main(String[] args) { Deck deck = new Deck(); deck.shuffle(); PokerHand hand = deck.deal(5); hand.shuffle(); hand.print(); if (hand.isStraight()) System.out.println("straight"); if (hand.hasStraightFlush()) System.out.println("straight flush"); if (hand.hasFullHouse()) System.out.println("full house"); if (hand.hasThreeOfKind()) System.out.println("3 of a kind"); if (hand.hasFourOfKind()) System.out.println("4 of a kind"); if (hand.hasFlush()) System.out.println("flush"); int nreps = 1000000; double nflushes = 0; double nthrees = 0; for (int i = 0; i < nreps; i++) { deck.shuffle(); PokerHand hand1 = new PokerHand(deck.deal(5)); if (hand1.hasFlush()) { nflushes++; } if (hand1.hasThreeOfKind()) { nthrees++; } } System.out.println("%flushes: "+nflushes/nreps*100); System.out.println("%threes: "+nthrees/nreps*100); }
474fb142-12d7-468b-8dec-e3f2287b6f59
0
public void setY2Coordinate(double y) { this.y2Coordinate=y; }
1ac70d7c-5bc1-4d0d-b3ad-946008a9e4d2
3
@Override public void run() { while(true){ // If we us the HMI at all process inputs if(hmi.useHMI){ // First process commands from remote control, which is more important than sending data for visualization. processInputs(); } try{ Thread.sleep(100); } catch(InterruptedException ie){ System.out.println("Interruption of HmiReaderThread in sleep()"); } } }