text
stringlengths
14
410k
label
int32
0
9
public int getViewerCount() { return viewerCount; }
0
public static void m92_screenrefresh(osd_bitmap bitmap,rectangle clip) { if (pf3_shape != 0) /* Updating all tilemaps causes palette overflow */ tilemap_update(pf3_wide_layer); else tilemap_update(pf3_layer); tilemap_update(pf2_layer); if (pf1_shape != 0) tilemap_update(pf1_wide_layer); else tilemap_update(pf1_layer); if (RYPELEO_SPEEDUP() != 0) tilemap_update(pf1_hlayer); /* This should be done once a frame only... but we can almost get away with it */ palette_init_used_colors(); mark_sprite_colours(); if (palette_recalc()!=null) tilemap_mark_all_pixels_dirty(ALL_TILEMAPS); tilemap_render(ALL_TILEMAPS); if (pf3_enable != 0) { tilemap_draw(bitmap,pf3_wide_layer,TILEMAP_BACK); tilemap_draw(bitmap,pf3_layer,TILEMAP_BACK); } else fillbitmap(bitmap,palette_transparent_pen,clip); tilemap_draw(bitmap,pf2_layer,TILEMAP_BACK); tilemap_draw(bitmap,pf1_wide_layer,TILEMAP_BACK); if (RYPELEO_SPEEDUP()!=0 && pf1_vram_ptr==0xc000) tilemap_draw(bitmap,pf1_hlayer,TILEMAP_BACK); else tilemap_draw(bitmap,pf1_layer,TILEMAP_BACK); m92_drawsprites(bitmap,clip,0); tilemap_draw(bitmap,pf3_wide_layer,TILEMAP_FRONT); tilemap_draw(bitmap,pf3_layer,TILEMAP_FRONT); tilemap_draw(bitmap,pf2_layer,TILEMAP_FRONT); tilemap_draw(bitmap,pf1_wide_layer,TILEMAP_FRONT); if (RYPELEO_SPEEDUP()!=0 && pf1_vram_ptr==0xc000) tilemap_draw(bitmap,pf1_hlayer,TILEMAP_FRONT); else tilemap_draw(bitmap,pf1_layer,TILEMAP_FRONT); m92_drawsprites(bitmap,clip,1); /* These sprites are over all playfields */ }
9
public static TorrentInfo getTorrentInfo(File torrentFile) { FileInputStream fis = null; TorrentInfo ti = null; try { fis = new FileInputStream(torrentFile); } catch (FileNotFoundException e) { System.err.println("File not found"); System.exit(1); } byte [] bytes = new byte[(int) torrentFile.length()]; try { fis.read(bytes, 0, bytes.length); } catch (IOException e) { e.printStackTrace(); } try { ti = new TorrentInfo(bytes); } catch (BencodingException e) { e.printStackTrace(); } try { fis.close(); } catch (IOException e) { e.printStackTrace(); } return ti; }
4
@Override public void earlyStartup() { Display.getDefault().asyncExec(new Runnable() { public void run() { IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); // get preference store of this plugin IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); // check auto word wrap on startup if (preferenceStore.getBoolean("de.cdhq.eclipse.wordwrap.autoenable.onstartup")) { WordWrapUtils.setWordWrapInWindow(workbenchWindow, true); } // auto word wrap: listen to opening of editors events if (workbenchWindow != null) { workbenchWindow.getPartService().addPartListener(new IPartListener2() { @Override public void partVisible(IWorkbenchPartReference partRef) { } @Override public void partOpened(IWorkbenchPartReference partRef) { // a new part was opened: hand over part reference to word wrap handler ActivateOnFileOpenHandler.handleFileOpenEvent(partRef); } @Override public void partInputChanged(IWorkbenchPartReference partRef) { } @Override public void partHidden(IWorkbenchPartReference partRef) { } @Override public void partDeactivated(IWorkbenchPartReference partRef) { } @Override public void partClosed(IWorkbenchPartReference partRef) { } @Override public void partBroughtToTop(IWorkbenchPartReference partRef) { } @Override public void partActivated(IWorkbenchPartReference partRef) { } }); } } }); }
2
synchronized public static org.omg.CORBA.TypeCode type () { if (__typeCode == null) { synchronized (org.omg.CORBA.TypeCode.class) { if (__typeCode == null) { if (__active) { return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); } __active = true; org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [4]; org.omg.CORBA.TypeCode _tcOf_members0 = null; _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); _members0[0] = new org.omg.CORBA.StructMember ( "levelPrefix", _tcOf_members0, null); _tcOf_members0 = pgrid.service.corba.PeerReferenceHelper.type (); _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (pgrid.service.corba.PeerArrayHelper.id (), "PeerArray", _tcOf_members0); _members0[1] = new org.omg.CORBA.StructMember ( "failedHosts", _tcOf_members0, null); _tcOf_members0 = pgrid.service.corba.PeerReferenceHelper.type (); _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (pgrid.service.corba.PeerArrayHelper.id (), "PeerArray", _tcOf_members0); _members0[2] = new org.omg.CORBA.StructMember ( "updatedHosts", _tcOf_members0, null); _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); _members0[3] = new org.omg.CORBA.StructMember ( "failedPath", _tcOf_members0, null); __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (pgrid.service.corba.repair.RepairSolutionHelper.id (), "RepairSolution", _members0); __active = false; } } } return __typeCode; }
3
public SimpleNode interpret(Environment env) { env.print(); if (((SimpleNode)jjtGetChild(0)).type.equals("ident")) return ((SimpleNode) ((SimpleNode)jjtGetChild(0)).interpret(env).jjtGetChild(0)).interpret(env); else if (((SimpleNode)jjtGetChild(0).jjtGetChild(0)).type.equals("ident") || ((SimpleNode)jjtGetChild(0).jjtGetChild(0)).type.equals("int") || ((SimpleNode)jjtGetChild(0).jjtGetChild(0)).type.equals("float")) {return ((SimpleNode)jjtGetChild(0).jjtGetChild(0)).interpret(env);} else if (((SimpleNode)jjtGetChild(0).jjtGetChild(0)).type.equals("cons") || ((SimpleNode)jjtGetChild(0).jjtGetChild(0)).type.equals("cdr")) { //Added Cons and Cdr checks System.out.println(((SimpleNode)jjtGetChild(0).jjtGetChild(1)).interpret(env).name); return ((SimpleNode)((SimpleNode)jjtGetChild(0).jjtGetChild(1)).interpret(env).jjtGetChild(0)).interpret(env); } else return ((SimpleNode)((SimpleNode)jjtGetChild(0).jjtGetChild(1)).interpret(env).jjtGetChild(0)).interpret(env); }
6
void clearIndicator() { hboxIndicator.getChildren().remove(indicator); errorMessage.setVisible(false); }
0
public int getMenuSize() { if(prayings.size() <= 9) return 9; if(prayings.size() <= 18) return 18; if(prayings.size() <= 27) return 27; if(prayings.size() <= 36) return 36; if(prayings.size() <= 45) return 45; if(prayings.size() <= 54) return 54; return 0; }
6
static void P(){ int S = 0; int O = 0; int SMax=19; int OMax=19; int STemp = 0; int OTemp = 0; int OCounter = 0; while(O <= OMax){ S = 0; while(S <= SMax){ //code start OTemp = 0; STemp = S; while(STemp >= 5){ STemp = STemp - 5; OTemp = OTemp + 1; } //code end if(O == OTemp){ OCounter = OCounter + 1; break; } if(S < SMax) S = S + 1; else break; } if(O < OMax) O = O + 1; else break; } System.out.println(OCounter); if(OCounter == 4){ System.out.println(OCounter); } }
7
private void siirryLuvunLoppuun() { while (true) { if (!merkkiOsaLukua()) { break; } paikka++; } }
2
public void processData(String link, String urlText, WriteToCsvPostsFile writeToCSV, int howTimes){ Document doc; try { doc = Jsoup.connect(link).userAgent("Mozilla").get(); Element body = doc.body(); if(body!=null) { findAllPosts(body); } } catch (SocketTimeoutException a){ //try three times the same URL if timeoutexecption if (howTimes+1==3){ OutputParams.appendToFailedUrlsFile(link); Logger.getLogger(InitParser.class).debug("Can't process this URL :" + link +" Content, cause time out exception"); } else { processData(link, urlText, writeToCSV, howTimes+1); } return; } catch (IOException e) { Logger.getLogger(InitParser.class).debug("Exception :"+e.getMessage() + " Description :"+ e.toString()); return; } writeToCSV.writePostToCSVFile(ids, authors, dates, messages, link, urlText); OutputParams.appendToSuccedUrlsFile(link); }
4
public PreferenceBoolean getApplyFontStyleForEditability() { if (useDocumentSettings()) { return this.applyFontStyleForEditability; } else { return Preferences.getPreferenceBoolean(Preferences.APPLY_FONT_STYLE_FOR_EDITABILITY); } }
1
public static void main(String[] args) { //ExtractionService extractor = new ExtractionService(); CoreNlpParser parser = new CoreNlpParser(); String sentence = "A rare black squirrel has become a regular visitor to a suburban garden"; Tree root = parser.parseAndRemovePeriods(sentence)[0]; List<Triplet> output = parser.parseText(sentence); if(output.size() == 0) System.err.println("ERROR: Could not find triplet"); else { for(Triplet out : output) { System.out.println( out.toString() ); } } String testString = "Now is the time for all good men to come to the aid of their country. Sam has a fork. A rare black squirrel has become a regular visitor to a suburban garden."; List<SemanticGraph> dependencies = parser.getTextDependencyTree(testString); if(dependencies.size() == 0) System.err.println("ERROR: Could not find dependencies"); else { for(SemanticGraph graph : dependencies) { System.out.println("Graph:"); System.out.println(graph.toString()); Collection<IndexedWord> roots = graph.getRoots(); for(IndexedWord r : roots) { System.out.println("Root:"); System.out.println(r.toString() ); System.out.println("Child Pairs:"); System.out.println(graph.childPairs(r).toString() ); } System.out.println(); System.out.println(graph.toString() ); System.out.println(graph.toDotFormat() ); System.out.println(graph.getRoots().toString()); System.out.println(graph.childRelns(graph.getFirstRoot()).toString() ); System.out.println(graph.childPairs(graph.getFirstRoot()).toString() ); System.out.println(graph.getEdgeSet().toString()); System.out.println(graph.vertexSet().toString()); } } }
5
@Override public void deserialize(Buffer buf) { barType = buf.readByte(); if (barType < 0) throw new RuntimeException("Forbidden value on barType = " + barType + ", it doesn't respect the following condition : barType < 0"); firstSlot = buf.readInt(); if (firstSlot < 0 || firstSlot > 99) throw new RuntimeException("Forbidden value on firstSlot = " + firstSlot + ", it doesn't respect the following condition : firstSlot < 0 || firstSlot > 99"); secondSlot = buf.readInt(); if (secondSlot < 0 || secondSlot > 99) throw new RuntimeException("Forbidden value on secondSlot = " + secondSlot + ", it doesn't respect the following condition : secondSlot < 0 || secondSlot > 99"); }
5
public void schrijfQuizzenNaarBestand(QuizCatalogus quizCatalogus) { File file = new File("bestanden/quizzen"); try { PrintWriter writer = new PrintWriter(file); for (int i = 0; i < quizCatalogus.getQuizzen().size(); i++) { Quiz quiz = quizCatalogus.getQuizzen().get(i); String lijn = quiz.getId() + "," + quiz.getAantalDeelnames() + "," + quiz.getLeerjaar() + "," + quiz.getLeraar().getVoorNaam()+"," +quiz.getLeraar().getFamilieNaam()+ "," + quiz.getOnderwerp() + "," + quiz.getQuizStatus(); for (Opdracht opdr :quiz.getOpdrachten()){ lijn+=","+opdr.getId(); } writer.println(lijn); } if (writer != null) writer.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); } }
4
public static void main(String[] args) throws Exception { // TODO Auto-generated method stub File file = new File("C:/1.txt"); in = new BufferedReader(new FileReader(file)); String line; while ((line = in.readLine()) != null) { char[] array = line.toCharArray(); int sum = 0; for (char c : array) { sum += Character.digit(c, 10); } System.out.println(sum); } }
2
private void loadDatabase() { //Declare a few local variables for later use ClassLoader currentClassLoader = null; Field cacheField = null; boolean cacheValue = true; try { //Store the current ClassLoader, so it can be reverted later currentClassLoader = Thread.currentThread().getContextClassLoader(); //Set the ClassLoader to Plugin ClassLoader Thread.currentThread().setContextClassLoader(classLoader); //Get a reference to the private static "defaultUseCaches"-field in URLConnection cacheField = URLConnection.class.getDeclaredField("defaultUseCaches"); //Make it accessible, store the default value and set it to false cacheField.setAccessible(true); cacheValue = cacheField.getBoolean(null); cacheField.setBoolean(null, false); //Setup Ebean based on the configuration ebeanServer = EbeanServerFactory.create(serverConfig); } catch(Exception ex) { throw new RuntimeException("Failed to create a new instance of the EbeanServer", ex); } finally { //Revert the ClassLoader back to its original value if(currentClassLoader != null) { Thread.currentThread().setContextClassLoader(currentClassLoader); } //Revert the "defaultUseCaches"-field in URLConnection back to its original value try { if(cacheField != null) { cacheField.setBoolean(null, cacheValue); } } catch (Exception e) { System.out.println("Failed to revert the \"defaultUseCaches\"-field back to its original value, URLConnection-caching remains disabled."); } } }
4
public static void printAll() { try { PreparedStatement stmt = Main.EMART_CONNECTION.prepareStatement("select * from sale"); ResultSet rs = stmt.executeQuery(); System.out.println("Orders:"); while (rs.next()) { System.out.println("Order:"); System.out.println(rs.getString("order_id") + " | " + rs.getString("cid") + " | " + rs.getDouble("total") + " | " + rs.getTimestamp("tstmp")); System.out.println("ordered items:"); PreparedStatement desstmt = Main.EMART_CONNECTION.prepareStatement("select * from ordereditem where order_id = ?"); desstmt.setString(1, rs.getString("order_id")); ResultSet desrs = desstmt.executeQuery(); while (desrs.next()) { System.out.println(desrs.getString("stock_number") + ": " + desrs.getInt("amount") + " $" + desrs.getDouble("item_total")); } } } catch (SQLException e) { e.printStackTrace(); } }
3
public static void main(String[] args) { if(args.length != 1){ System.out.println("Invalid number of parameters. Application will exit."); System.exit(0); } try{ WSDLDomParser wsdlParser = new WSDLDomParser(args[0]); System.out.println("Service name: " + wsdlParser.getServiceName()); System.out.println("The root element is " + wsdlParser.getRootElement()); showPorts(wsdlParser.getPorts()); Element methodElement; System.out.println(); System.out.println("====== WEBMETHODS ======"); for (Entry<Node, Map<String, Map<String, NodeList>>> entry : wsdlParser.getOperationsMap().entrySet()) { methodElement = (Element)entry.getKey(); System.out.println("Webmethod: " + methodElement.getAttribute("name")); System.out.println("Parameters:"); showParameters(entry, "input"); System.out.println("Returns:"); showParameters(entry, "output"); } System.out.println("======= TYPES ======="); for(Entry<String, NodeList> typeEntry : wsdlParser.getComplexTypeMap().entrySet()){ String typeName = typeEntry.getKey(); System.out.println("Typename: " + typeName); System.out.println("Fields: "); showFields(typeEntry); } } catch (SAXParseException err) { System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ()); System.out.println(" " + err.getMessage ()); }catch (SAXException e) { Exception x = e.getException (); ((x == null) ? e : x).printStackTrace (); }catch (Throwable t) { t.printStackTrace (); } }
7
private boolean startExpr(Symbol token) { return lexer.token == Symbol.FALSE || lexer.token == Symbol.TRUE || lexer.token == Symbol.NOT || lexer.token == Symbol.THIS || lexer.token == Symbol.NUMBER || lexer.token == Symbol.SUPER || lexer.token == Symbol.LEFTPAR || lexer.token == Symbol.NULL || lexer.token == Symbol.IDENT || lexer.token == Symbol.LITERALSTRING; }
9
public void avanzar() { switch (direccion) { case ARRIBA: ArribaM(); break; case ABAJO: AbajoM(); break; case IZQUIERDA: IzquierdaM(); break; case DERECHA: DerechaM(); break; } }
4
public ISocketServerConnection getClientConnection() { return clientConnection; }
0
public static boolean isPositiveInteger(String s){ try { Integer.parseInt(s); } catch(NumberFormatException e) { return false; } int var = Integer.parseInt(s); if (var > 0 && var <= 1000) { return true; } else { return false; } }
3
public boolean isValid(String urlString) { URL url = null; try { url = new URL(urlString); } catch (MalformedURLException e) { return false; } URLConnection conn; try { conn = url.openConnection(); conn.connect(); } catch (IOException e) { return false; } return true; }
2
public static Cons walkSysCallTree(Cons tree, Object [] MV_returnarray) { { Slot slot = Cons.slotFromExpressionTree(tree); StandardObject slottype = Stella.SGT_STELLA_UNKNOWN; if (slot != null) { slottype = ((CompoundTypeSpecifier)(KeyValueList.dynamicSlotValue(slot.dynamicSlots, Stella.SYM_STELLA_SLOT_TYPE_SPECIFIER, null))); { boolean testValue000 = false; testValue000 = slottype != null; if (testValue000) { if (Stella_Object.anchoredTypeSpecifierP(slottype)) { testValue000 = true; } else { { boolean foundP000 = false; { StandardObject ts = null; Cons iter000 = ((ParametricTypeSpecifier)(slottype)).specifierParameterTypes.theConsList; loop000 : for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { ts = ((StandardObject)(iter000.value)); if (Stella_Object.anchoredTypeSpecifierP(ts)) { foundP000 = true; break loop000; } } } testValue000 = foundP000; } } } if (testValue000) { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("walk-sys-call-tree: OOPS, can't handle anchored slot types: `" + tree + "'"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } } if (!(slottype != null)) { slottype = slot.type(); } } { Cons _return_temp = tree; MV_returnarray[0] = slottype; return (_return_temp); } } }
7
private void MoreSellMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_MoreSellMouseClicked // TODO add your handling code here: List<String> s = new Conectar().GetFecha(); String f = null; int x,y; Map<Integer,Integer> in = new TreeMap<Integer,Integer>(); for(String sq:s){ StringTokenizer tokens=new StringTokenizer(sq, "/"); int ndatos=tokens.countTokens(); int[] datos=new int[ndatos]; int i=0; while(tokens.hasMoreTokens()){ String str=tokens.nextToken(); datos[i] = parseInt(str); if(i == 2){ x = datos[i-1]; y = datos[i]; in.put(x, y); } i++; } } Iterator i = in.keySet().iterator(); List<String> f1 = new ArrayList<>(); while(i.hasNext()){ int k = (int)i.next(); String f2 = "00/"+k+"/"+in.get(k); f1.add(f2); } new Fecha().Call(f1,"Mas"); }//GEN-LAST:event_MoreSellMouseClicked
4
public void setEmail(String email) { this.email = email; }
0
@Override public void moveInto(GameEntity target) { if (target instanceof Monster) { int damage = attack((Actor) target); if (((Actor) target).applyDamage(damage, this)) { char fl = getName().charAt(0); GamePanel.get().logMessage( "You killed " + (fl == 'a' || fl == 'e' || fl == 'i' || fl == 'o' || fl == 'u' ? "an " : "a ") + target.getName() + ".", Color.magenta); } } }
7
public static String replaceAll(String str, Pattern regex, Replacer replacer){ if(regex==null){ throw new ESTypeException("A regex must be provided"); } if(replacer==null){ throw new ESTypeException("A replacer must be provided"); } Matcher matcher=regex.matcher(str); StringBuffer sb = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(sb, replacer.next(matcher,matcher.start(),str)); } matcher.appendTail(sb); return sb.toString(); }
3
protected SnmpValue decodeValueContext() throws BerException { try { byte tag = (byte)decodeTag(-1); int length = decodeLength(); if (debug) dump("Context " + tag + " length " + length + " " + SNMP_ENDOFMIBVIEW); if ((tag == SNMP_NOSUCHOBJECT) || (tag == SNMP_NOSUCHINSTANCE) || (tag == SNMP_ENDOFMIBVIEW)) { if (debug) dump("Known context " + tag + " length " + length); while (length > 0) { read(); } return new SnmpNull(ASN_TYPE & tag); } if (debug) dump("Unknown context " + tag + " length " + length + "(just skipping)"); byte[] buffer = new byte[length]; for (int i = 0 ; i < length ; i++) { buffer[i]= (byte)read(); } return new SnmpOctetStr(buffer); } catch (SnmpValueException e) { } throw new BerException("A context encoding error"); }
9
@Override public void deleteMax() throws EmptyCollectionException, KeyNotFoundException { if (treeIsEmpty()) throw new EmptyCollectionException(); Node x = root; while (x.right != null) x = x.right; delete(x.key); }
2
private long calc(int pos, int n) { if (pos < numbers.length && (pos + n - 1) < numbers.length) { long v = 1; for (int i = pos - 1; i < pos + n - 1; i++) { v *= numbers[i]; } return v; } return 0; }
3
@Override public void update() { if (!entityRemoveBuffer.isEmpty()) { removeEntities(); entityRemoveBuffer.clear(); } if (!entityChangeBuffer.isEmpty()) { checkEntities(); entityChangeBuffer.clear(); } for (Entity entity : entities) { process(entity); } }
3
public static Integer getNumeros(String numeroString) { StringTokenizer st = new StringTokenizer(numeroString); List lstLetras = Arrays.asList(Letras); Integer numero = 0; Integer mil = 0; Integer millon = 0; while (st.hasMoreTokens()) { String t = st.nextToken(); t = t.toUpperCase(); if (t.equals("MILLON")) { millon = 1000000; } if (t.equals("MILLONES")) { if (mil == 0) { millon = numero * 1000000; } else { millon = 1 * 1000000; } mil = 0; numero = 0; } if (t.equals("MIL")) { if (numero == 0) { mil = 1 * 1000; } else { mil = numero * 1000; } numero = 0; } if (lstLetras.indexOf(t) > -1) { numero += Valores[lstLetras.indexOf(t)]; } } numero = numero + mil + millon; return numero; }
7
boolean dejaLugarAOtro() { if(criterioInscripcion instanceof ModoSolidario){ return true; } else { return false; } }
1
public static Record getRecordByXMLElem(XMLElement root) { if (!root.attributeMap.containsKey("type")) { System.out.println("Record should contain attribute 'type'"); return null; } String type = root.attributeMap.get("type"); if (type.equals("quiz-taken")) { return QuizTakenRecord.getQuizTakenRecordByXMLElem(root); } else if (type.equals("quiz-created")) { return QuizCreatedRecord.getQuizCreatedRecordByXMLElem(root); } else if (type.equals("achievement")) { return AchievementRecord.getAchievementRecordByXMLElem(root); } else { System.out.println("Unrecognized record type " + type); return null; } }
4
private boolean jj_2_17(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_17(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(16, xla); } }
1
public Instance nextInstance() { double attrib1 = 0, attrib2 = 0, attrib3 = 0; int group = 0; boolean desiredClassFound = false; while (!desiredClassFound) { // generate attributes attrib1 = 10 * this.instanceRandom.nextDouble(); attrib2 = 10 * this.instanceRandom.nextDouble(); attrib3 = 10 * this.instanceRandom.nextDouble(); // determine class group = classificationFunctions[this.functionOption.getValue() - 1] .determineClass(attrib1, attrib2, attrib3); if (!this.balanceClassesOption.isSet()) { desiredClassFound = true; } else { // balance the classes if ((this.nextClassShouldBeZero && (group == 0)) || (!this.nextClassShouldBeZero && (group == 1))) { desiredClassFound = true; this.nextClassShouldBeZero = !this.nextClassShouldBeZero; } // else keep searching } } //Add Noise if ((1 + (this.instanceRandom.nextInt(100))) <= this.noisePercentageOption .getValue()) { group = (group == 0 ? 1 : 0); } // construct instance InstancesHeader header = getHeader(); Instance inst = new DenseInstance(header.numAttributes()); inst.setValue(0, attrib1); inst.setValue(1, attrib2); inst.setValue(2, attrib3); inst.setDataset(header); inst.setClassValue(group); return inst; }
8
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Round " + round + ":\n"); sb.append("Payload: (" + PAYLOAD_SIZE + " bytes)\n"); sb.append(Arrays.toString(payload)); return sb.toString(); }
0
public ToolAdapter(AutomatonPane pane) { this.pane = pane; }
0
private void refreshLabels() { setTitle(settings.getLanguage().getLabel("title_settings")); languageLabel.setText(settings.getLanguage().getLabel("label_language")); nameLabel.setText(settings.getLanguage().getLabel("label_name")); portLabel.setText(settings.getLanguage().getLabel("label_port")); minimizeToTrayLabel.setText(settings.getLanguage().getLabel("label_minimizetotray")); resetButton.setText(settings.getLanguage().getLabel("button_reset")); saveButton.setText(settings.getLanguage().getLabel("button_save")); pack(); }
0
private void updateSelection(int x, int y) { //check which button is at the point x,y and select it and update cursor if (onNewPlayer(x, y)) { setCursor(new Cursor(Cursor.HAND_CURSOR)); selected = ButtonSelected.NEW; } else if (onLoadPlayer(x, y)) { setCursor(new Cursor(Cursor.HAND_CURSOR)); selected = ButtonSelected.LOAD; } else if (onStartServer(x, y)) { setCursor(new Cursor(Cursor.HAND_CURSOR)); selected = ButtonSelected.SERVER; } else if (onControls(x, y)) { setCursor(new Cursor(Cursor.HAND_CURSOR)); selected = ButtonSelected.CONTROLS; } else { setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); selected = null; } repaint(); }
4
private void privFlushPages(PageId pageid, int all_pages) throws HashOperationException, PageUnpinnedException, PagePinnedException, PageNotFoundException, BufMgrException, IOException { // The current page Page curPage; // The current frame descriptor FrameDesc frame; // Iterate through the Buffer Pool for (int i=0; i < numBuffers; i++) { // If flushAllPages() or pageId specified in flushPage() if ( (all_pages == 1) || (frmeTable[i].pageNo.pid == pageid.pid)) { // If the pin_count isn't 0, the page is still in use and can't be flushed if ( frmeTable[i].pin_count() != 0 ) throw new PagePinnedException (null, "BUFMGR: Page is still pinned."); // If page is dirty if (frmeTable[i].dirty) { // You cannot write an INVALID_PAGE if (frmeTable[i].pageNo.pid == INVALID_PAGE) throw new PageNotFoundException( null, "BUFMGR: Page not found"); // Set the current frame and current page frame = frmeTable[i]; curPage = new Page(bufPool[i]); pageid.pid = frame.pageNo.pid; // Write the dirty page write_page(pageid, curPage); // Remove the page from the Page Table hashTable.remove(pageid); // Reset the Buffer Table // NOTE: this should be a FrameDesc method frmeTable[i].pageNo.pid = INVALID_PAGE; // frame is empty frmeTable[i].dirty = false ; } // end if } // end if } // end for } // end privFlushPages()
6
public int getAlertid() { return alertid; }
0
public static ArrayList<Planet> forShips(SimulatedPlanetWars simpw){ ArrayList<Planet> asw = new ArrayList<Planet>(2); // Find the biggest fleet to attack with and our weakest planet to know what is our goal of fleet to be destroyed in the enemey int maxShips = 0; int minShips = 1000; for (Planet p : simpw.MyPlanets()){ int ships = p.NumShips(); if (ships > maxShips){ maxShips = ships; asw.add(0,p); } if (ships< minShips) minShips = ships; } // Find the destination with a dangerous fleet int maxDist = 0; maxShips = 0; for (Planet p : simpw.NotMyPlanets()){ int ships = p.NumShips(); if ((ships/2)>minShips && ships>maxShips) { // We choose the biggest Enemy to attack to defend more our planets maxShips = ships; } } return asw; }
6
public void testThreeArgsConstructorException() { // first case : the nominator is null. constructor should fail. try { Quantity testo = new Quantity(100 , null, Arrays.asList("this homework is too hard")); fail(); } // test is passed. no need to catch anything. catch(IllegalArgumentException e) {} // second case : denumerator is null. constructor should fail. try { Quantity testo = new Quantity(100 , Arrays.asList("Idon'twanttogotoKoreanarmy"), null); fail(); } // test is passed. no need to catch anything. catch(IllegalArgumentException e) {} }
2
public Chunk(int biome, int initResources, Point loc) { this.loc = loc; this.setBiome(biome); this.setResources(initResources); }
0
public void playerKeyPress(int down, int up, int right, int left, int bomb) { if (Keyboard.isKeyDown(down)) { update(Direction.DOWN); xOffset = 0.0f; } if (Keyboard.isKeyDown(up)) { update(Direction.UP); xOffset = 0.25f; } if (Keyboard.isKeyDown(right)) { update(Direction.RIGHT); xOffset = 0.50f; } if (Keyboard.isKeyDown(left)) { update(Direction.LEFT); xOffset = 0.75f; } if (Keyboard.isKeyDown(bomb)) { placeBomb(); } }
5
public void update(){ player.update(); player.checkAttack(enemies); player.checkCoins(coins); finish.update(); finish.checkGrab(player); // System.out.println(player.gety()); // System.out.println(player.getx()); bg.setPosition(tileMap.getx(), tileMap.gety()); tileMap.setPosition( GamePanel.WIDTH / 2 - player.getx(), GamePanel.HEIGHT / 2 - player.gety()); if(player.isDead()){ player.setPosition(100, 400); player.revive(); player.reset(); restart(); } for(int i = 0; i < enemies.size(); i++){ Enemy e = enemies.get(i); e.update(); if(player.isDrunk()){ e.kill(); } if(e.isDead()){ enemies.remove(i); e.addScore(Level2State.score); i--; } } for(int i = 0; i < coins.size(); i++){ Coin c = coins.get(i); c.update(); if(c.shouldRemove()){ c.addScore(); coins.remove(i); i--; } } bg.setPosition(tileMap.getx(), tileMap.gety()); }
6
public boolean existBlackForest(){ for(int i=0;i<getDim();i++) for(int j=0;j<getDim();j++) if(!damiera[i][j].isFree() && damiera[i][j].getPezzo().getColore()==Color.BLACK) if(!damiera[i][j].getPezzo().getAlberoMosse().isSAMNull()) return true; return false; }
5
public final void mapCommand(String command, Action a) { if(commandMap.containsKey(command)) System.err.println("[CLC] Command " + command + " has already been registered."); else if(a == null) { System.err.println("[CLC] Command " + command + " can not be linked to a null Action."); } else if(contextMap.containsKey(command)) { contextMap.get(command).setRootAction(a); } else { commandMap.put(command, a); } }
3
@Override public Temporal adjustInto(Temporal input) { LocalDate date = LocalDate.from(input); if (date.getDayOfWeek() == DayOfWeek.FRIDAY || date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY){ return input.with(date.with(TemporalAdjusters.next(DayOfWeek.MONDAY))); } else{ return input.with(date.plusDays(1)); } }
3
public int findRankBinary(int[][] matrix) { int n = matrix.length; int m = matrix[0].length; // number of linearly independent row vector so far int row = 0; for (int i = 0; i < m; i++) { // for every column, scan the entire column int max = 0; int maxRow = 0; for (int j = row; j < n; j++) { if (max < matrix[j][i]) { max = matrix[j][i]; maxRow = j; break; // because it's binary } } if (max == 0) continue; // swap such that matrix[row] is another linearly independent vector with // the ith entry non-zero int[] temp = matrix[maxRow]; matrix[maxRow] = matrix[row]; matrix[row] = temp; // subtract multiple of ith row so that all other rows have the ith entry 0 // since its binary, the non-zero element is always 1 for (int j = row + 1; j < n; j++) { if (matrix[j][i] != 0) { for (int k = i; k < m; k++) { matrix[j][k] = matrix[j][k] - matrix[row][k]; // mod 2 if (matrix[j][k] == -1) matrix[j][k] = 1; } } } row++; if (row == n) break; } // row = rank now return row; }
9
public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here }
0
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Controller other = (Controller) obj; if (jsRoutes == null) { if (other.jsRoutes != null) return false; } else if (!jsRoutes.equals(other.jsRoutes)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
9
public Path shortestPath(Vertex start, Vertex end) { checkVertexExists(start); checkVertexExists(end); DHeap<Vertex> pq = new DHeap<Vertex>(2); Map<Vertex, Vertex> prevMap = new HashMap<Vertex, Vertex>(); /* v_k -> v_k+1 if v_k+1 is the previous vertex on the shortest path to v_k */ for (Vertex v : graph.keySet()) { if (v.equals(start)) v.setCost(0); else v.setCost(Integer.MAX_VALUE); pq.insert(v); } Vertex current = pq.deleteMin(); // current.equals(start) here while(!pq.isEmpty() && !current.equals(end)) { for(Edge e : graph.get(current)) { if (pq.contains(e.getDestination())) { /* if pq does not contain the destination vertex, the shortest path to that vertex is known. */ Vertex destination = pq.get(e.getDestination()); /* must do get() to get corresponding Vertex within pq */ if (current.getCost() + e.getWeight() < destination.getCost()) { destination.setCost(current.getCost() + e.getWeight()); prevMap.put(destination, e.getSource()); pq.decreaseKey(destination, e.getWeight() + current.getCost()); } } } /* the minimum value in pq is the vertex with the cheapest cost from start of the unknown vertices */ Vertex next = pq.deleteMin(); current = next; } return getBackpointPath(prevMap, start, current); }
7
public void repaintData() { if ( currentEntry != null ) { TProjectData current = TGlobal.projects.getCurrentData() ; int len = langFields.length ; for ( int t = 0 ; t < len ; t++ ) { String str = current.getTranslation( currentEntry, t ) ; TLangTextField field = langFields[t] ; if ( str == null ) { str = "" ; field.setStatus( TLangTextField.REQUIRE_STATE ) ; } else if ( str.length() < 1 ) { field.setStatus( TLangTextField.REQUIRE_STATE ) ; } else // something available { field.setStatus( TLangTextField.NOTHING_STATE ) ; } // with/without unicode if ( showSource ) { field.setText( str ) ; } else { field.setText( Utils.get_WYSIWYG_String( str ) ) ; } } } else // no entry data available - clear all fields { int len = langFields.length ; for ( int t = 0 ; t < len ; t++ ) { TLangTextField field = langFields[t] ; field.setText( "" ) ; field.setStatus( TLangTextField.REQUIRE_STATE ) ; } } GUIGlobals.oPanel.updateEntryComment( "" ) ; }
6
@Override public void disconnect() throws Exception { try { if ((keepAliveThread != null) && (keepAliveThread.isAlive())) { keepAliveThread.setStopped(true); } } finally { super.disconnect(); } }
2
public Queue<Grid> getStack() { return stack; }
0
public boolean keyup(KeyEvent ev) { if (focusctl) { if (focused != null) { if (focused.keyup(ev)) return (true); return (false); } else { return (false); } } else { for (Widget wdg = child; wdg != null; wdg = wdg.next) { if (wdg.keyup(ev)) return (true); } } return (false); }
5
private void viewResultsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewResultsButtonActionPerformed if(getProposal().getAuthor() == FOTE.getUser().getId() || ProposalLogic.isExpired(getProposal())){ new ViewResults((Frame) this.getParent(), true, getProposal()).setVisible(true); } else{ JOptionPane.showMessageDialog(this, "You are not the author of this proposal, you cannot view the results!\n" + "Please wait until the proposal is expired.", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_viewResultsButtonActionPerformed
2
public void loadFromImage(){ try { BufferedImage img = ImageIO.read(new File("res/Map.png")); createWorld(img); loading = false; } catch (IOException e) { e.printStackTrace(); } }
1
public void initialize() throws Exception { // EXC for (int e=0; e<5; e++) { client.callProcedure(new BenchmarkCallback("EXC.insert"),"EXC.insert",e); } System.out.println(" loaded 5 records into EXC"); // SEC for (int s=0; s<numSecs; s++) { client.callProcedure(new BenchmarkCallback("SEC.insert"),"SEC.insert",s,rand.nextInt(5)); prices[s] = (double)rand.nextInt(100); } System.out.println(" loaded "+numSecs+" records into SEC"); // CNT for (int t=0; t<config.traders; t++) { client.callProcedure(new BenchmarkCallback("CNT.insert"),"CNT.insert",t); } System.out.println(" loaded "+config.traders+" records into CNT"); // positions (client side only) for (int t=0; t<config.traders; t++) { // make a list of random securities with no duplicates List<Integer> secs = new ArrayList<Integer>(); while(secs.size() < config.secpercnt) { int sec = rand.nextInt(numSecs); if(!secs.contains(sec)) secs.add(sec); } // put securities into an two-dimension array: positions[trader][index] = sec_id for (int i=0; i<config.secpercnt; i++) { positions[t][i] = (int)secs.get(i); } } System.out.println(" initialized client with array of "+ config.traders * config.secpercnt +" possible positions"); }
7
public void reLoadDomains(CyNetwork network) { hitMap = new HashMap<CyIdentifiable, List<CDDHit>>(); featureMap = new HashMap<CyIdentifiable, List<CDDFeature>>(); pdbChainMap = new HashMap<CyIdentifiable, List<PDBStructure>>(); // System.out.println("Reloading domains"); boolean havePDB = PDBStructure.havePDB(network); for (CyNode node: network.getNodeList()) { CyIdentifiable id = (CyIdentifiable)node; List<CDDHit> hitList = CDDHit.reloadHits(network, id); if (hitList == null || hitList.size() == 0) continue; // System.out.println("Found "+hitList.size()+" domains for "+id); hitMap.put(id, hitList); List<CDDFeature> featureList = CDDFeature.reloadFeatures(network, id); if (featureList == null || featureList.size() == 0) continue; // System.out.println("Found "+featureList.size()+" features for "+id); featureMap.put(id, featureList); // Reload chains... List<PDBStructure> chains = PDBStructure.reloadStructures(network, id, hitList); if (chains != null && chains.size() > 0) pdbChainMap.put(id, chains); } if (hitMap.size() > 0 || featureMap.size() > 0) { // Update the charts PieChart.updatePieChartColumn(network, hitMap, featureMap); } }
9
public void update() { checkTileMapCollision(); setPosition(xtemp, ytemp); if (dx == 0 && !hit) { setHit(); } animation.update(); if (hit && animation.hasPlayedOnce()) { remove = true; } }
4
public mxICellOverlay removeCellOverlay(Object cell, mxICellOverlay overlay) { if (overlay == null) { removeCellOverlays(cell); } else { mxICellOverlay[] arr = getCellOverlays(cell); if (arr != null) { // TODO: Use arraycopy from/to same array to speed this up List<mxICellOverlay> list = new ArrayList<mxICellOverlay>( Arrays.asList(arr)); if (list.remove(overlay)) { removeCellOverlayComponent(overlay, cell); } arr = list.toArray(new mxICellOverlay[list.size()]); overlays.put(cell, arr); } } return overlay; }
3
public static String determineBondType(Formula formula) { List<String> elements = formula.getElements(); List<String> elementTypes = new ArrayList<String>(); for (String element : elements) { elementTypes.add(typeList.get(element)); } String bondType = null; if (elementTypes.contains("Hydrogen") && elements.size() <= 2) { bondType = "hydrogen"; return bondType; } if (elementTypes.contains("Metal") && elementTypes.contains("Nonmetal")) { bondType = "ionic"; } else if(elementTypes.contains("Metal") && !elementTypes.contains("Nonmetal")) { bondType = "metallic"; } else if(elementTypes.contains("Nonmetal")&& !elementTypes.contains("Metal")) { bondType = "covalent"; } return bondType; }
9
@Override public void deconneced(OVNode n) { if (n.equals(inNode_)) { if (isFree() ||( inNode_.getConnections().size()==1 && outNode_.isFree())) { outNode_.setType(ValueType.VOID); inNode_.setType(ValueType.VOID); } else if (inNode_.isFree() && !outNode_.isFree()) { inNode_.setType(outNode_.getType()); } } else { if (isFree()) { outNode_.setType(ValueType.VOID); inNode_.setType(ValueType.VOID); } else if (!inNode_.isFree() && outNode_.isFree()) { outNode_.setType(inNode_.getType()); } } }
9
public void setVisible(boolean visible) { // // Centering About windows // if (visible && fWhichAbout != kMessageReceived) ComponentUtil.centerComponent(this, fParentFrame.getLocation(), fParentFrame.getSize()); // // Restore / Save the location of Message Received Dialog. // if (fWhichAbout == kMessageReceived) { if (visible) ComponentUtil.fitComponentIntoScreen(this, fPropertiesDB.getRcvDialogLocation()); else { fPropertiesDB.setRcvDialogLocation(getLocation()); fPropertiesDB.saveProperties(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "")); } } // // Update memory usage if necesary // if (visible && fWhichAbout == kSystemProperties) updateMemoryInformation(); super.setVisible(visible); }
6
public Block clone(){ try{ return (Block) super.clone(); }catch(Exception e){ e.printStackTrace(); return null; } }
1
public JSONWriter object() throws JSONException { if (this.mode == 'i') { this.mode = 'o'; } if (this.mode == 'o' || this.mode == 'a') { this.append("{"); this.push(new JSONObject()); this.comma = false; return this; } throw new JSONException("Misplaced object."); }
3
public Model getRotatedModel() { Model model = aSpotAnim_1568.getModel(); if(model == null) return null; int j = aSpotAnim_1568.aAnimation_407.anIntArray353[anInt1569]; Model model_1 = new Model(true, Class36.method532(j), false, model); if(!aBoolean1567) { model_1.method469(); model_1.method470(j); model_1.anIntArrayArray1658 = null; model_1.anIntArrayArray1657 = null; } if(aSpotAnim_1568.anInt410 != 128 || aSpotAnim_1568.anInt411 != 128) model_1.method478(aSpotAnim_1568.anInt410, aSpotAnim_1568.anInt410, aSpotAnim_1568.anInt411); if(aSpotAnim_1568.anInt412 != 0) { if(aSpotAnim_1568.anInt412 == 90) model_1.method473(); if(aSpotAnim_1568.anInt412 == 180) { model_1.method473(); model_1.method473(); } if(aSpotAnim_1568.anInt412 == 270) { model_1.method473(); model_1.method473(); model_1.method473(); } } model_1.method479(64 + aSpotAnim_1568.anInt413, 850 + aSpotAnim_1568.anInt414, -30, -50, -30, true); return model_1; }
8
private String display() { String displayString = ""; if (this.contents == null) { return displayString; //Will update display with blank string if contents is empty } displayString += this.contents; return displayString; }
1
public boolean equalsIgnoreCase(CharSequence other) { return other != null ? toString().equalsIgnoreCase(other.toString()) : false; }
1
public Pair<ParseDirective,Item> beginCB(Node aInData, Item aInParentItem) { // TRY TO FIND EXISTING META NODE MNode lMNode = (MNode) (null != aInParentItem ? aInParentItem.getChildItem(MNode.MY_CAT, aInData.getQual()) : MNode.MY_CAT.getItem(aInData.getQual())); // CHECK IF FOUND if (null == lMNode) { // NOT FOUND: CREATE META NODE THAT CORRESPONDS TO THIS NODE PARSING RULE lMNode = new MNode(aInParentItem, aInData.getQual()); } if (NodeType.NODE == type) { // CHECK IF IT HAS INDIRECTION ALREADY SPECIFIED if (!lMNode.usesOtherNode()) { // CHECK IF WE HAVE TO USE OTHER NODE'S PARSER String lUse = aInData.getNamedValue("use", null, false); if (!Strings.isEmpty(lUse)) { lMNode.addUses(lUse); } } // CHECK IF NEITHER INDIRECTION OR EXPLICIT CLASS ARE SPECIFIED if (!(lMNode.usesOtherNode() || lMNode.hasExplicitParseClassName())) { // NEITHER INDIRECTION OR EXPLICIT CLASS ARE SPECIFIED // GET THE PARSE NODE'S EXPLICIT PARSING CLASS DIRECTIVE String lExplicit = aInData.getNamedValue("explicit", null, false); // CHECK IF DIRECT PARSING CLASS DIRECTIVE IS SET String lParserImplClassName = null; if (!Strings.isEmpty(lExplicit)) { lParserImplClassName = lExplicit; } // CHECK IF THIS THIS IS A GENERIC/PLACEHOLDER NODE else if (aInData.checkFlag("generic")) { lParserImplClassName = "org.opendaylight.opflex.genie.engine.parse.model.ParseNode"; } // THIS IS AN AUTO-PICKED PARSING NODE... LET'S FABRICATE THE NAME else { // DETERMINE DEFAULT PARSER NAME FOR THIS NODE String lQual = aInData.getQual(); String lNs = aInData.getNamedValue("namespace", lQual, false); StringWriter lParserImplClassNameBuff = new StringWriter(); lParserImplClassNameBuff.append("org.opendaylight.opflex.genie.content.parse.p"); lParserImplClassNameBuff.append(lNs.toLowerCase()); lParserImplClassNameBuff.append(".P"); lParserImplClassNameBuff.append(Strings.upFirstLetter(lQual)); lParserImplClassNameBuff.append("Node"); lParserImplClassName = lParserImplClassNameBuff.toString(); } // Set the parser node class name lMNode.addExplicitParserClassName(lParserImplClassName); } lMNode.setInheritProps(aInData.getNamedOption("inherit-props",true)); } return new Pair<ParseDirective, Item>( ParseDirective.CONTINUE, lMNode); }
9
private Distance(String value) { _value = value; }
0
@Override public boolean colides(SchlangenKopf head) { if (!super.colides(head)) { head.die(); return true; } return false; }
1
public ResetGraphState(Graph g) { this.graph = g; for (int i = 0; i < g.getEdges().getSize(); i++) { g.getEdges().get(i).setVisited(false); } for (int i = 0; i < g.getVertices().getSize(); i++) { g.getVertices().get(i).setColor(null); g.getVertices().get(i).setDistance(0); g.getVertices().get(i).setPath(null); } }
2
@Override public final void focusLost(FocusEvent focusevent) { awtFocus = false; for (int i = 0; i < 128; i++) { heldKeys[i] = 0; } }
1
protected URL getAudioURL() { String urlString = getAudioFileName(); URL url = null; if (urlString!=null) { try { url = new URL(getDocumentBase(), urlString); } catch (Exception ex) { System.err.println(ex); } } return url; }
2
public SentiWordNetFeature createFeaturesObject(String s) { int wordCount = 0; double sumPositiveScore = 0.0; double sumNegativeScore = 0.0; double sumObjectiveScore = 0.0; int nonZeroPositiveCount = 0; int nonZeroNegativeCount = 0; int nonZeroObjectiveCount = 0; double sumPositiveAdjectiveScore = 0.0; double sumNegativeAdjectiveScore = 0.0; double sumObjectiveAdjectiveScore = 0.0; int nonZeroPositiveAdjectiveCount = 0; int nonZeroNegativeAdjectiveCount = 0; int nonZeroObjectiveAdjectiveCount = 0; List<TaggedToken> tagged = tagger.tokenizeAndTag(s); for (TaggedToken taggedToken : tagged) { String token = taggedToken.token.toLowerCase().replace("#", ""); List<SentiWordNetEntry> entries = sentiWordNet.getSentiWordNetEntries( arkTweetNLPTagToSentiWordNetTag.get(taggedToken.tag), token); for (SentiWordNetEntry entry : entries) { wordCount++; sumPositiveScore += entry.getPositiveScore(); sumNegativeScore += entry.getNegativeScore(); sumObjectiveScore += entry.getObjectiveScore(); if (entry.getPositiveScore() > 0.0) nonZeroPositiveCount++; if (entry.getNegativeScore() > 0.0) nonZeroNegativeCount++; if (entry.getObjectiveScore() > 0.0) nonZeroObjectiveCount++; if (taggedToken.tag.equals("A")) { sumPositiveAdjectiveScore += entry.getPositiveScore(); sumNegativeAdjectiveScore += entry.getNegativeScore(); sumObjectiveAdjectiveScore += entry.getObjectiveScore(); if (entry.getPositiveScore() > 0.0) nonZeroPositiveAdjectiveCount++; if (entry.getNegativeScore() > 0.0) nonZeroNegativeAdjectiveCount++; if (entry.getObjectiveScore() > 0.0) nonZeroObjectiveAdjectiveCount++; } } } return new SentiWordNetFeature(wordCount, sumPositiveScore, sumNegativeScore, sumObjectiveScore, nonZeroPositiveCount, nonZeroNegativeCount, nonZeroObjectiveCount, sumPositiveAdjectiveScore, sumNegativeAdjectiveScore, sumObjectiveAdjectiveScore, nonZeroPositiveAdjectiveCount, nonZeroNegativeAdjectiveCount, nonZeroObjectiveAdjectiveCount); }
9
@Override public void addEdge(int v, int w) throws InvalidEdgeException, SelfLoopExistsException, ParallelEdgeExistsException { // check for invalid edge if (v < 0 || v >= V() || w < 0 || w >= V()) throw new InvalidEdgeException("Invalid edge : " + v + "-" + w); if (v == w) throw new SelfLoopExistsException("Self loops not allowed : " + v + "-" + w); for (int a : adj[v]) if (a == w) throw new ParallelEdgeExistsException( "Parallel edges not allowed : " + v + "-" + w); adj[v].add(w); E++; }
7
protected void reconnect() { if (this.isReconnectionAllowed()) { // Since there is no thread running, creates a new one to attempt // the reconnection. Thread reconnectionThread = new Thread() { /** * Holds the current number of reconnection attempts */ private int attempts = 0; /** * Returns the number of seconds until the next reconnection attempt. * * @return the number of seconds until the next reconnection attempt. */ private int timeDelay() { if (attempts > 13) { return 60 * 5; // 5 minutes } if (attempts > 7) { return 60; // 1 minute } return 10; // 10 seconds } /** * The process will try the reconnection until the connection succeed or the user * cancell it */ public void run() { // The process will try to reconnect until the connection is established or // the user cancel the reconnection process {@link XMPPConnection#disconnect()} while (ReconnectionManager.this.isReconnectionAllowed()) { // Find how much time we should wait until the next reconnection int remainingSeconds = timeDelay(); // Sleep until we're ready for the next reconnection attempt. Notify // listeners once per second about how much time remains before the next // reconnection attempt. while (ReconnectionManager.this.isReconnectionAllowed() && remainingSeconds > 0) { try { Thread.sleep(1000); remainingSeconds--; ReconnectionManager.this .notifyAttemptToReconnectIn(remainingSeconds); } catch (InterruptedException e1) { e1.printStackTrace(); // Notify the reconnection has failed ReconnectionManager.this.notifyReconnectionFailed(e1); } } // Makes a reconnection attempt try { if (ReconnectionManager.this.isReconnectionAllowed()) { connection.connect(); } } catch (XMPPException e) { // Fires the failed reconnection notification ReconnectionManager.this.notifyReconnectionFailed(e); } } } }; reconnectionThread.setName("Smack Reconnection Manager"); reconnectionThread.setDaemon(true); reconnectionThread.start(); } }
9
private void parsePlayerUpdateFlags(Stream stream) { for (int j = 0; j < entityUpdateCount; j++) { int k = playerUpdateIndices[j]; Player player = localPlayers[k]; int l = stream.getUnsignedByte(); if ((l & 0x40) != 0) { l += stream.getUnsignedByte() << 8; } parsePlayerUpdateFlag(l, k, stream, player); } }
2
private static List<Server> parseServers(DeployConfig config, String targetServer) { List<Server> result = new ArrayList<Server>(); boolean flag = true; String[] serverList = targetServer.split(C.separator); Server server = null; for (String target : serverList) { server = config.getServers().getServerById(target); flag = flag && server != null; if (!flag) { logger.error("Not found server with id:" + target); result.clear(); break; } result.add(server); } return result; }
3
public void applyNews(News news){ double effect = news.getEffect(); if (effect < 0) stockStrength += effect; else stockStrength += effect; if (effect < -.4) price -= .2; if (effect > .4) price += .2; }
3
public void actionPerformed(ActionEvent evt) { if (evt.getSource() == browseButton) { if (browseFile() && recording) startRecording(); } else if (evt.getSource() == recordButton) { if (!recording) { startRecording(); } else { stopRecording(); fnameField.setText(nextNewFilename(fnameField.getText())); } } else if (evt.getSource() == nextButton) { fnameField.setText(nextNewFilename(fnameField.getText())); if (recording) startRecording(); } else if (evt.getSource() == closeButton) { setVisible(false); } }
8
private void parseArguements(String[] args, Job job) throws IOException { for (int i = 0; i < args.length; ++i) { if ("-input".equals(args[i])) { FileInputFormat.addInputPaths(job, args[++i]); } else if ("-output".equals(args[i])) { FileOutputFormat.setOutputPath(job, new Path(args[++i])); } else if ("-jobName".equals(args[i])) { job.getConfiguration().set("mapred.job.name", args[++i]); } else if ("-columnToClean".equals(args[i])) { job.getConfiguration().set("columnToClean", args[++i]); } else if ("-delimiter".equals(args[i])) { job.getConfiguration().set("delimiter", args[++i]); } } }
6
public FormulaTools(String name, String prefix, String[] formula, boolean numChangeable, List<Parameter> params, List<Parameter> sysParams) { setLayout(new BorderLayout()); setBorder(new TitledBorder(name)); this.params = params; this.sysParams = sysParams; if (formula == null) { formula = new String[] { "0" }; } if (numChangeable) { numSpinner = new IntSpinner(this, formula.length, 1, 10, 1); } else { numField = new JTextField("" + formula.length); numField.setEditable(false); } area.setEditable(false); area.addMouseListener(ml); editBtn.addActionListener(this); JPanel cp = new JPanel(); cp.add(new JLabel("Number of " + name + ": ")); if (numChangeable) cp.add(numSpinner); else cp.add(numField); cp.add(editBtn); add(new JScrollPane(area)); add(cp, BorderLayout.NORTH); this.formula = formula; this.prefix = prefix; this.name = name; display(); }
3
public void mouseClicked(MouseEvent e){ chosenColumn = e.getX()/100 - 1; chosenRow = e.getY()/100 - 1; //this method connects the UI with the logic int size = logic.getGameBoard().length; if ((chosenColumn >= 0) && (chosenColumn < size) && (chosenRow >= 0) && (chosenRow < size)) { //this is the main method that connects the UI with the Logic. logic.insertQueen(chosenColumn, chosenRow); repaint(); } }
4
public double getTotalRevenue() { return totalRevenue; }
0
public static ColaLigada<String> convertirPostfija(String infija) throws Exception { ColaLigada<String> colaPostfija = new ColaLigada<>(); PilaLigada<String> pila = new PilaLigada<>(); ArrayList<String> separada= Utilidades.convertir(infija); for(int i=0; i<separada.size();i++) { String letra = separada.get(i); if (letra.equals("(")) { pila.push(letra); } else { if (letra.equals(")")) { while (!pila.peek().equals("(")) { colaPostfija.push(pila.pop()); } pila.pop(); } else { if (!Utilidades.isOperador(letra)) { colaPostfija.push(letra); } else { while (!pila.vacia() && Utilidades.isLessPriority(letra, pila.peek()) && !pila.peek().equals("(")) { colaPostfija.push(pila.pop()); } pila.push(letra); } } } } while (!pila.vacia()) { colaPostfija.push(pila.pop()); } return colaPostfija; }
9
@Override public void mouseReleased(MouseEvent e) { if (e.getSource() == addPersonToParticipantsListLabel && searchList.getSelectedValue() != null) { addParticipants(); } else if (e.getSource() == removePersonFromParticipantsListLabel && invitedList.getSelectedValue() != null) { removeParticipants(); } else if (e.getSource() == searchField) { searchField.selectAll(); } else if (e.getSource() == searchList && e.getClickCount() == 2) { addParticipants(); } else if (e.getSource() == invitedList && e.getClickCount() == 2) { removeParticipants(); } }
9
static void plotUnclipped(int x, int y, int z, int argb, int argbBackground, Graphics3D g3d, int textWidth, int textHeight, int[] bitmap) { int offset = 0; int shiftregister = 0; int i = 0, j = 0; int[] zbuf = g3d.zbuf; int[] pbuf = g3d.pbuf; int screenWidth = g3d.width; int pbufOffset = y * screenWidth + x; boolean addBackground = (argbBackground != 0); while (i < textHeight) { while (j < textWidth) { if ((offset & 31) == 0) shiftregister = bitmap[offset >> 5]; if (shiftregister == 0 && !addBackground) { int skip = 32 - (offset & 31); j += skip; offset += skip; pbufOffset += skip; } else { if (z < zbuf[pbufOffset]) { if (shiftregister < 0) { zbuf[pbufOffset] = z; pbuf[pbufOffset] = argb; } else if (addBackground) { zbuf[pbufOffset] = z; pbuf[pbufOffset] = argbBackground; } } shiftregister <<= 1; ++offset; ++j; ++pbufOffset; } } while (j >= textWidth) { ++i; j -= textWidth; pbufOffset += (screenWidth - textWidth); } } }
9
public boolean remove(int index){ if(index <1 || index > size()){ return false; } Node current = head; for(int i = 0; i < index; i++){ if(current.getNext() == null){ return false; } current = current.getNext(); } current.setNext(current.getNext().getNext()); count--; return true; }
4
public static BufferedImage cropImage(BufferedImage source, double tolerance) { // Get our top-left pixel color as our "baseline" for cropping int baseColor = source.getRGB(0, 0); int width = source.getWidth(); int height = source.getHeight(); int topY = Integer.MAX_VALUE, topX = Integer.MAX_VALUE; int bottomY = -1, bottomX = -1; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (colorWithinTolerance(baseColor, source.getRGB(x, y), tolerance)) { if (x < topX) { topX = x; } if (y < topY) { topY = y; } if (x > bottomX) { bottomX = x; } if (y > bottomY) { bottomY = y; } } } } BufferedImage destination = new BufferedImage((bottomX - topX + 1), (bottomY - topY + 1), BufferedImage.TYPE_INT_ARGB); destination.getGraphics().drawImage(source, 0, 0, destination.getWidth(), destination.getHeight(), topX, topY, bottomX, bottomY, null); return destination; }
7
public Move getBestMoveNegascout(GameBoard board, int d) { ArrayList<NegascoutThread> threads = new ArrayList<NegascoutThread>(); for (Move child : board.getAllPossibleMoves(board.currentColor)) { NegascoutThread t = new NegascoutThread(child, board, d); t.start(); threads.add(t); } System.out.println(threads.size() + " threads started!"); long start = System.currentTimeMillis(); long lastPrint = start; while (true) { boolean finished = true; for (NegascoutThread t : threads) { if (!t.finished) { finished = false; break; } } if (!finished) { try { if (System.currentTimeMillis() - lastPrint >= SEARCH_PRINT_DELAY) { System.out.println("Elapsed: " + (System.currentTimeMillis() - start) / 1000. + "s. Searched " + benchMark + " nodes."); lastPrint = System.currentTimeMillis(); } Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } else { break; } } Move best = null; int alpha = MIN; for (NegascoutThread t : threads) { if (t.alpha >= alpha) { alpha = t.alpha; best = t.best; } } System.out.println("Best score: " + alpha); cache.clear(); return best; }
9
void showpage(String url,BufferedReader b,PrintStream p) { File f; try { f = new File( "website/" + url); System.out.println(f.getAbsolutePath()); String m = hf.defPageOrder(url); if (m.compareTo("NO") != 0) { url = m; h.setUrl(url); } if (h.getExt().compareTo("jsx")==0) { f = new File("website"+ url); printHeader(p, "text/html" , HTTP_OK, "OK"); pjx.parser(p, f); } else if (url.charAt(url.length()-1) == '/') { printHeader(p, "text/html" , HTTP_OK, "OK"); d.Viewlist(p,url); } else if (f.exists()) { try { String type=hf.newfiletype(url); String[] help; if (type.compareTo("NO")!=0) { help = type.split(":"); printHeader(p, help[1], HTTP_OK, "OK"); printimage(f,p); } else { printHeader(p, "text/html", HTTP_OK, "OK"); p.println("Sorry the file type is not supported yet"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { p.print("HTTP/1.0 " + HTTP_NOTFOUND + " File Not Found "); p.flush(); p.write(EOL); p.flush(); p.write(EOL); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
7
public Persistent Next() throws InstantiationException, IllegalAccessException { if (ids == null) initSearch(); if (currentPosition >= ids.size()) return null; Persistent obj = (Persistent) (searchClass.newInstance()); obj.Id = ids.get(currentPosition); obj.LoadData(); currentPosition++; return obj; }
2
public TextoCompactadoHuffman comprimirHuffman(){ if(texto==null){ return null; } NodoHuffman[] nodos=new NodoHuffman[MAXIMO_CARACTERES]; for(int i=0;i<MAXIMO_CARACTERES;i++){ nodos[i]=new NodoHuffman((char)i); } for(int i=0;i<texto.length();i++){ nodos[texto.charAt(i)].registrarNuevo(); } ListaHuffman lista=new ListaHuffman(); int caracteresDiferentes=0; for(int i=0;i<MAXIMO_CARACTERES;i++){ if(nodos[i].darFrecuencia()>0){ lista.insertarOrdenado(nodos[i]); caracteresDiferentes++; } } lista.generarArbolHuffman(); TextoCompactadoHuffman th=new TextoCompactadoHuffman(caracteresDiferentes); for(int i=0;i<MAXIMO_CARACTERES;i++){ if(nodos[i].darFrecuencia()>0){ th.agregarCaracterTabla(nodos[i].darInfo()); } } for(int i=0;i<texto.length();i++){ th.agregarCaracterTexto(nodos[texto.charAt(i)].darInfo()); } return th; }
8