text
stringlengths
14
410k
label
int32
0
9
private int centerAndValueOn() { CABot3Net factNet = (CABot3Net)getNet("FactNet"); CABot3Net valueNet = (CABot3Net)getNet("ValueNet"); boolean valueOn=false; boolean centerOn=false; int result = 0; for (int i = 0; i < valueNet.getSize(); i ++) { if (valueNet.neurons[i].getFired()) valueOn = true; } //check the center fact for (int i = 520; i < 560; i ++) { if (factNet.neurons[i].getFired()) centerOn = true; } if (valueOn && centerOn) return 1; else if (valueOn || centerOn) return 2; else return 0; }
8
public void setPrpIdElemento(int prpIdElemento) { this.prpIdElemento = prpIdElemento; }
0
public Tracker(java.lang.String name, long delay, long period, java.lang.String filename) { super(name); boolean __b = getAgentType() == tracker.Tracker.class; if (__b) { __init1(); __init2(); } java.lang.System.out.println(name + "\tstarted "); java.util.StringTokenizer tokens; java.lang.String record; java.lang.String t1; java.lang.String t2; java.lang.String t3; java.lang.String t4; java.lang.String t5; java.lang.String t6; java.lang.String t7; java.io.BufferedReader datafile = null; try { datafile = new java.io.BufferedReader(new java.io.FileReader(filename)); } catch (java.io.FileNotFoundException e) { java.lang.System.err.println("unable to open file " + e.toString()); java.lang.System.exit(1); } try { while ((record = datafile.readLine()) != null) { tokens = new java.util.StringTokenizer(record); t1 = tokens.nextToken(); t2 = tokens.nextToken(); t3 = tokens.nextToken(); t4 = tokens.nextToken(); t5 = tokens.nextToken(); t6 = tokens.nextToken(); t7 = tokens.nextToken(); //System.out.println("id: " + t1 + " warning count: "+ t2 + " upload: " + t3 + " download: "+ t4 + " isonline: " + t5); TrackerBS.add(java.lang.Integer.parseInt(t1),java.lang.Integer.parseInt(t2),java.lang.Integer.parseInt(t3),java.lang.Integer.parseInt(t4),java.lang.Integer.parseInt(t5),java.lang.Integer.parseInt(t6),java.lang.Integer.parseInt(t7)); } } catch (java.lang.Exception e) { java.lang.System.err.println("error reading data into beliefset"); java.lang.System.exit(1); } java.util.Timer timer = new java.util.Timer(); timer.scheduleAtFixedRate(new java.util.TimerTask(){ public void run() { analysePeerInfo(); } },delay,period); if (__b) startAgent(); }
5
private static void consume_Tf(GraphicsState graphicState, Stack stack, Resources resources) { // collectTokenFrequency(PdfOps.Tf_TOKEN); //graphicState.translate(-shift,0); //shift=0; float size = ((Number) stack.pop()).floatValue(); Name name2 = (Name) stack.pop(); // build the new font and initialize it. graphicState.getTextState().font = resources.getFont(name2.getName()); // in the rare case that the font can't be found then we try and build // one so the document can be rendered in some shape or form. if (graphicState.getTextState().font == null || graphicState.getTextState().font.getFont() == null){ // turn on the old awt font engine, as we have a null font FontFactory fontFactory = FontFactory.getInstance(); boolean awtState = fontFactory.isAwtFontSubstitution(); fontFactory.setAwtFontSubstitution(true); // get the first pages resources, no need to lock the page, already locked. Resources res = resources.getLibrary().getCatalog().getPageTree().getPage(0,null).getResources(); // try and get a font off the first page. Object pageFonts = res.getEntries().get("Font"); if (pageFonts instanceof Hashtable){ // get first font graphicState.getTextState().font = (org.icepdf.core.pobjects.fonts.Font)resources.getLibrary() .getObject(((Hashtable)pageFonts).elements().nextElement()); // might get a null pointer but we'll get on on deriveFont too graphicState.getTextState().font.init(); } // return factory to original state. fontFactory.setAwtFontSubstitution(awtState); // if no fonts found then we just bail and accept the null pointer } graphicState.getTextState().currentfont = graphicState.getTextState().font.getFont().deriveFont(size); }
3
private void create(FileFilter filter, boolean directoryOnly) { this.chooser.setDialogType(JFileChooser.OPEN_DIALOG); this.chooser.setFileHidingEnabled(true); this.chooser.setAcceptAllFileFilterUsed(false); this.basePanel.add(this.chooser, BorderLayout.CENTER); if (filter != null) { this.chooser.setFileFilter(filter); } if (directoryOnly) { this.chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } this.chooser.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JFileChooser jFileChooser = (JFileChooser) event.getSource(); String command = event.getActionCommand(); if (command.equals(JFileChooser.APPROVE_SELECTION)) { File selectedFile = jFileChooser.getSelectedFile(); Settings.setFilechooserBasepath(selectedFile.toPath()); onApprove(selectedFile); dispose(); } else if (command.equals(JFileChooser.CANCEL_SELECTION)) { onCancel(); dispose(); } } }); if (Settings.getFilechooserBasePath() != null) { this.chooser.setCurrentDirectory(Settings.getFilechooserBasePath().toFile()); } }
5
private static String toWords(int n) { final String s = String.valueOf(n); final int l = s.length(); if (l == 1) { return numbersToWords.get(n); } else if (l == 2) { if (numbersToWords.containsKey(n)) { return numbersToWords.get(n); } final int tens = n / 10 * 10; final int ones = n - tens; return numbersToWords.get(tens) + " " + numbersToWords.get(ones); } else if (l == 3) { final int hundreds = n / 100 * 100; final int remainder = (n - hundreds); if (numbersToWords.containsKey(remainder)) { return numbersToWords.get((hundreds / 100)) + " hundred and " + numbersToWords.get(remainder); } else { final int tens = (n - hundreds) / 10 * 10; final int ones = n - hundreds - tens; if (ones > 0 && tens > 0) { return numbersToWords.get((hundreds / 100)) + " hundred and " + numbersToWords.get(tens) + " " + numbersToWords.get(ones); } else if (tens > 0) { return numbersToWords.get((hundreds / 100)) + " hundred and " + numbersToWords.get(tens); } else { return numbersToWords.get((hundreds / 100)) + " hundred"; } } } else if (l == 4) { final int thousands = n / 1000 * 1000; return numbersToWords.get((thousands / 1000)) + " thousand"; } return null; }
9
public boolean scoped(String scope) { if (this.scope != null) { for (String s : this.scope.split(" ")) if (scope.equals(s)) return true; } return false; }
3
public void duplicateTrack() { int theId = lookForBlankId(); int newMatchesSize = Math.max(theId + 1, highestId() + 1); int[] matches = new int[newMatchesSize]; for (int i = 0; i < matches.length; i++) { if (i == matches.length - 1) matches[i] = 0; else matches[i] = currentTrack().getMatches()[i]; } Track newTrack = new Track(theId, currentTrack().getAuthor(), currentTrack().getTitle(), currentTrack().getPart() + 1, currentTrack() .getBpm(), currentTrack().getKeyFr(), currentTrack().getFrPerBpm(), currentTrack().getTempoForRef(), currentTrack().getRefFr(), currentTrack().getKeyNotes(), matches); for (int i = 0; i < parent.tracks.size(); i++) { int[] newMatches = new int[newMatchesSize]; for (int j = 0; j < newMatches.length; j++) newMatches[j] = 0; for (int j = 0; j < parent.tracks.get(i).getMatches().length; j++) newMatches[j] = parent.tracks.get(i).getMatches()[j]; newMatches[theId] = matches[i]; parent.tracks.get(i).setMatches(newMatches); } parent.tracks.add(newTrack); currentTrack = theId; makeTheList(null); parent.cellsManager.updateEditTrack(); parent.cellsManager.updateList(); }
5
public void stop() { continueLoop = false; if(thread != null) { thread.interrupt(); } }
1
@Override public Object getSupportedAttributeValues(Class<? extends Attribute> category, DocFlavor flavor, AttributeSet attributes) { if (category == Media.class) { return new Media[] { MediaSizeName.NA_LETTER, MediaSizeName.NA_LEGAL, MediaSizeName.ISO_A4 }; } if (category == OrientationRequested.class) { return new OrientationRequested[] { OrientationRequested.PORTRAIT, OrientationRequested.LANDSCAPE }; } return null; }
3
protected static String readInputCommadForServer(BufferedReader commandReader) { String commandLine = null; do { try { commandLine = commandReader.readLine(); log.info("receive command: " + commandLine); } catch (IOException e) { // TODO Auto-generated catch block //e.printStackTrace(); commandLine = null; log.info("receive command: FAIL"); } } while (commandLine == null); return commandLine; }
2
@Override public void startSetup(Attributes atts) { super.startSetup(atts); addActionListener(this); }
0
public String toString() { StringBuilder sb = new StringBuilder("["); Node node = _head.next; String sep = ""; while (node != null) { sb.append(sep).append("(").append(node.waketime).append(",") .append(node.agent).append(")"); node = node.next; sep = ";"; } sb.append("]"); return (sb.toString()); }
1
private static void permutate(char[] s, int n){ for(int i=n;i<s.length;i++){ for(int j=i+1;j<s.length;j++){ swap(i, j, s); permutations.add(new String(s)); permutate(s, n+1); swap(i, j, s); permutate(s, n+1); } } }
2
public static String camelCaseToUnderline(String name) { final int length = name.length(); boolean inupper = false; StringBuilder stb = new StringBuilder(length); int i = 0; while (i < length) { char c = name.charAt(i); i = i + 1; if(inupper) { if(Character.isLowerCase(c)){ stb.append(c); inupper = false; }else if(i < length && Character.isUpperCase(c) && Character.isLowerCase(name.charAt(i))){ stb.append('_'); stb.append(Character.toLowerCase(c)); inupper = false; }else{ stb.append(Character.toLowerCase(c)); } }else{ if(Character.isUpperCase(c)) { stb.append('_'); stb.append(Character.toLowerCase(c)); inupper = true; }else{ stb.append(c); } } } return stb.toString(); }
7
protected void generateCSVFile(File dir, String typeFilter) throws IOException { try { File skillListFile = new File(dir, "skillsList_" + typeFilter + ".csv"); HashSet<String> writtenKeys = new HashSet(skillSets.size()); if (skillListFile.exists()) { skillListFile.delete(); } System.out.println("There are " + skillSets.size() + " entries."); if (!skillSets.isEmpty()) { PrintWriter pwSkillSet = new PrintWriter(skillListFile); pwSkillSet.println("Skill,Type"); for (Skillset skillSet : skillSets) { if (typeFilter.equalsIgnoreCase(skillSet.getSkillsetType())) { if ((skillSet.getSkillsetKey() != null) && (!skillSet.getSkillsetKey().isEmpty())) { if (!writtenKeys.contains(skillSet.getSkillsetKey())) { pwSkillSet.println(skillSet.getSkillsetKey() + "," + skillSet.getSkillsetType()); writtenKeys.add(skillSet.getSkillsetKey()); } } else { if (!writtenKeys.contains(skillSet.getName())) { pwSkillSet.println(skillSet.getName() + "," + skillSet.getSkillsetType()); writtenKeys.add(skillSet.getName()); } } } } pwSkillSet.flush(); pwSkillSet.close(); } } catch (IOException e1) {} }
9
public static Node insert(Node head, Node insert) { if (head == null && insert != null) { head = insert; return head; } if (head == null) { return head; } Node traverse = head; while (traverse.info < insert.info && traverse.next != null) { traverse = traverse.next; } insert.next = traverse.next; traverse.next = insert; return head; }
5
public static void createNgramsFromFolder(File input_folder, File output_folder, int ngram_value) { Stack<File> stack = new Stack<File>(); stack.push(input_folder); while(!stack.isEmpty()) { File child = stack.pop(); if (child.isDirectory()) { for(File f : child.listFiles()) stack.push(f); } else if (child.isFile()) { try{ System.out.println("Processing: "+child.getAbsolutePath()); FileReader fr=new FileReader(child.getAbsolutePath()); FileWriter outputFile = new FileWriter(output_folder+"/file"+file_no); BufferedReader br=new BufferedReader(fr); String readline = ""; while((readline = br.readLine())!=null){ String[] words = readline.split("\\s+"); for(int i=0;i<words.length-ngram_value+1;i++){ String ngram=""; for(int j=0; j<ngram_value; j++) ngram = ngram+" "+words[i+j]; outputFile.write(ngram+"\n"); } } file_no++; outputFile.close(); br.close(); fr.close(); } catch(Exception e){ System.out.println("File not found:"+e); } } } }
8
/* */ public boolean isActive() /* */ { /* 35 */ if (this.context == 0) { /* 36 */ this.context = -1; /* */ try { /* 38 */ if (getAppletContext() != null) this.context = 1; /* */ } /* */ catch (Exception localException) /* */ { /* */ } /* */ } /* 43 */ if (this.context == -1) return this.active; /* 44 */ return super.isActive(); /* */ }
4
public void runOptimisticUnchoke(){ RUBTConstants.main_log.info("*** RUNNING OPTIMISTIC UNCHOKE ***"); if (this.activePeers.size() >= RUBTConstants.MAX_UNCHOKED_PEERS) { RUBTConstants.main_log.info("too little active peers: " + this.activePeers.size()); return; } //Lookup selected peer in active list to unchoke ArrayList<Peer> chokedPeers = new ArrayList<Peer>(); if(RUBTToolKit.isSeed(this.client_info.getClient_bitfield())){ // when only uploading our end needs unchocked for(Peer peer: this.connectedPeers){ if(peer.getLocalStatus() == RUBTConstants.PeerStatus.CHOKED){ chokedPeers.add(peer); } } //Otherwise, repeat same process with upload rates }else{ // when still downloading their end needs unchocked for(Peer peer: this.connectedPeers){ if(peer.getRemoteStatus() == RUBTConstants.PeerStatus.CHOKED){ chokedPeers.add(peer); } } } //Generate a random peer to unchoke within choked list //seed your random Random rand = new Random(System.currentTimeMillis()); final Peer luckyPeer = chokedPeers.get(rand.nextInt(chokedPeers.size())); RUBTConstants.main_log.info("Peer choosed by optimistic unchocke is " + luckyPeer.toString()); this.workers.execute(new Runnable() { @Override public void run() { try { if(RUBTToolKit.isSeed(Manager.this.client_info.getClient_bitfield())) { //open our end luckyPeer.setLocalStatus(RUBTConstants.PeerStatus.UNCHOKED); luckyPeer.sendMessageToPeer(new UnchokeMessage()); luckyPeer.peer_log.info("Peer is unchoked in optimistic unchoke!"); } else { //try to open their end, send interested luckyPeer.setRemoteStatus(RUBTConstants.PeerStatus.INTERESTED); luckyPeer.peer_log.info("sending interested to peer"); luckyPeer.sendMessageToPeer(RUBTConstants.INTERESTED_MESSAGE); } if (!Manager.this.activePeers.contains(luckyPeer)) { Manager.this.activePeers.add(luckyPeer); } } catch (IOException e) { //peer socket is bad disconnect Manager.this.connectedPeers.remove(luckyPeer); Manager.this.activePeers.remove(luckyPeer); luckyPeer.removeMessageListener(Manager.this); luckyPeer.disconnect(); } } }); }
9
public ArrayList<String> getAllIdentifier() { ArrayList<String> result = new ArrayList<>(); NodeList nl = doc.getDocumentElement().getElementsByTagName("stock"); for (int i = 0; i < nl.getLength(); i++) { Element e = (Element) nl.item(i); result.add(e.getAttribute("identifier")); } return result; }
1
public Double getDistance(int distanceType, Entries other, int VERBOSE) { int logFlag = 0b10; // if one of the entries contains nothing, then we cannot // compute the distance if (other.size()==0) return null; if (this.size() ==0) return null; // say, we have two timeSeries 1 and 2 // our assumption timeEnd(i) = timeStart(i+1) long initStart1 = this.get(0).timeStart; long initStart2 = other.get(0).timeStart; long len1 = this.get(this.size()-1).timeEnd - initStart1; long len2 = other.get(other.size()-1).timeEnd - initStart2; if (len1 != len2 ) { System.err.print("[Dataset.getDistance] Error: Both entries should have the same length."); System.exit(1); } Util.logPrintln(VERBOSE, logFlag, "compute distance, length: "+len1); // current entry under consideration int cur1 = 0; int cur2 = 0; long min1 = this.get(cur1).timeStart - initStart1; long min2 = other.get(cur2).timeStart - initStart2; if (min1 != min2 ) { System.err.print("[Dataset.getDistance] Error: Problem in initial time start."); System.exit(1); } long nextMin1 = this.get(cur1).timeEnd - initStart1; long nextMin2 = other.get(cur2).timeEnd - initStart2; double sym1Double = this.get(cur1).value; double sym2Double = other.get(cur2).value; // choose either min1 or min2 (both should have the same value at this point, i.e., 0) long post = min1; double dist = 0.0; while (true) { if ( nextMin1 < nextMin2 ) { // compute symbol differences long length = nextMin1 - post; dist = dist + computeDistance(distanceType, sym1Double, sym2Double, length); // update the post post = nextMin1; Util.logPrintln(VERBOSE, logFlag, "post on ts1: "+ (post+initStart1)); // increase our lookup cursor on timeSeries1 cur1 ++; // update info on timeSeries 1 min1 = this.get(cur1).timeStart - initStart1; nextMin1 = this.get(cur1).timeEnd - initStart1; sym1Double = (int) (this.get(cur1).value); } else { long length = nextMin2 - post; dist = dist + computeDistance(distanceType, sym1Double, sym2Double, length); post = nextMin2; Util.logPrintln(VERBOSE, logFlag, "post on ts2: "+ (post+initStart2) + ", "+(nextMin2 + initStart2)); // increase our lookup cursor on timeSeries2 cur2 ++; if ( cur2 >= other.size() ) break; min2 = other.get(cur2).timeStart - initStart2; nextMin2 = other.get(cur2).timeEnd - initStart2; sym2Double = (int) (other.get(cur2).value); } } return dist; }
7
public float mean() { float sum = 0; for (float x : data) { sum += x; } return sum / data.size(); }
1
public void resolveAddresses() { for(int i = 0; i < byteCodeFile.size(); i++) { String byteCode = byteCodeFile.get(i).get(0); if(byteCode.equals("FALSEBRANCH") || byteCode.equals("GOTO") || byteCode.equals("RETURN") || byteCode.equals("CALL")) { int address = 0; String byteCodeArg = byteCodeFile.get(i).get(0); // was get(1) for(int j = 0; j < byteCodeFile.size(); j++) { String label = byteCodeFile.get(j).get(0); if(label.equals("LABEL")) { String labelArg = byteCodeFile.get(j).get(1); if(labelArg.equals(byteCodeArg)) { address = j; break; } } } // if address doesn't change then it wasn't available // remove arg // add 'address' if(address != 0) { byteCodeFile.get(i).remove(1); byteCodeFile.get(i).add(Integer.toString(address)); } } } }
9
static public boolean mapEquals(IPersistentMap m1, Object obj){ if(m1 == obj) return true; if(!(obj instanceof Map)) return false; Map m = (Map) obj; if(m.size() != m1.count() || m.hashCode() != m1.hashCode()) return false; for(ISeq s = m1.seq(); s != null; s = s.next()) { Map.Entry e = (Map.Entry) s.first(); boolean found = m.containsKey(e.getKey()); if(!found || !Util.equals(e.getValue(), m.get(e.getKey()))) return false; } return true; }
7
public float palDifUni(int[] a, int[] b) { boolean aTransp = a[3] == 0; boolean bTransp = b[3] == 0; if (aTransp != bTransp) return Float.POSITIVE_INFINITY; float dif = 0; int len = aTransp ? 3 : 4; boolean[] sel = new boolean[len]; for (int i = 0; i < len; i++) { int c = a[i]; float diff = Float.POSITIVE_INFINITY; int i2 = -1; for (int j = 0; j < len; j++) { if (sel[j]) continue; float diff2 = Util.colorDiff(c, b[j]); if (diff2 < diff || i2 == -1) { i2 = j; diff = diff2; } } sel[i2] = true; dif += diff; } return dif; }
7
void animateBall() { switch(animCoun) { case 0: img=imgAnim01; break; case 20: img=imgAnim02; break; case 40: img=imgAnim03; break; case 60: img=imgAnim04; break; case 80: MetalBreaker.nBalls--; ballAlive=false; } animCoun++; }
5
protected int indexToInsert(GameComponent<?> component) { int lowerIndex = 0; int higherIndex = this.getComponentCount() - 1; int searchedZ = component.getZ(); if(this.getComponents().isEmpty() || searchedZ < this.getZFromComponentAt(lowerIndex)) { return 0; } if(searchedZ >= this.getZFromComponentAt(higherIndex)) { return this.getComponentCount(); } while(lowerIndex <= higherIndex) { int middleIndex = lowerIndex + higherIndex >>> 1; int middleZ = this.getZFromComponentAt(middleIndex); if(middleZ <= searchedZ) { lowerIndex = middleIndex + 1; } else if(middleZ > searchedZ) { higherIndex = middleIndex - 1; } } return lowerIndex; }
7
public static boolean uniqueASCII(String s) { int[] counts = new int[256]; char[] chars = s.toCharArray(); for(char c : chars) { counts[c]++; if(counts[c] > 1) { return false; } } return true; }
2
public static void metroStyleTitlebar(JInternalFrame internalFrame) { JComponent title = ((BasicInternalFrameUI)internalFrame.getUI()).getNorthPane(); for (int i = 0; i < title.getComponentCount(); i++) { JComponent component = (JComponent)title.getComponent(i); if(component instanceof JButton) { JButton button = ((JButton)component); if(button.getName() == null) continue; if(button.getName().endsWith("closeButton")) { button.setIcon(close); button.setSelectedIcon(closeHighlighted); button.setPressedIcon(closePressed); } else if(button.getName().endsWith("maximizeButton")) { button.setIcon(max); button.setSelectedIcon(maxHighlighted); button.setPressedIcon(maxPressed); } } } }
5
@Override public void run() { DNSPacket dnsMessage = new DNSPacket(true); dnsMessage.setAuthoritativeAnswer(true); List<ServiceInfo> removalList = new LinkedList<ServiceInfo>(); boolean bannouncedLocalInfo = false; if(_LocalInfo.getState().isAnnouncing()) { synchronized(_LocalInfo) { addLocalInfoRecord(dnsMessage); } bannouncedLocalInfo = true; } if(_AnnounceList != null && _AnnounceList.size() > 0) { for (ServiceInfo info : _AnnounceList) { synchronized(info) { dnsMessage.addAnswer(new DNSRecord.Pointer(info.getType(), DNSEntry.EntryType.PTR, DNSEntry.EntryClass.IN, DNSEntry.TTL, info.getQualifiedName())); // dnsMessage.addAnswer(new DNSRecord.Pointer("_services._dns-sd._udp.local.", DNSEntry.EntryType.PTR, // DNSEntry.EntryClass.IN, false, DNSConstants.DNS_TTL, info.getType())); dnsMessage.addAnswer(new DNSRecord.Service(info.getQualifiedName(), DNSEntry.EntryClass.IN, true, DNSEntry.TTL, info.getPriority(), info.getWeight(), info.getPort(),_LocalInfo.getName())); if(info.getTextBytes() != null) { dnsMessage.addAnswer(new DNSRecord.Text(info.getQualifiedName(), DNSEntry.EntryClass.IN, true, DNSEntry.TTL, info.getTextBytes())); } info.advanceState(); if(info.getState().isAnnounced()) removalList.add(info); } } // If we haven't announced local information, announce it now, since some service depends on it. if(!bannouncedLocalInfo) addLocalInfoRecord(dnsMessage); } for(ServiceInfo info : removalList) _AnnounceList.remove(info); if(dnsMessage.getAnswers().size() > 0) _Socket.send(dnsMessage); else cancel(); }
9
public boolean legalMove(Move m) { return ( // the player must exist (m.player.equals("red") || m.player.equals("blue")) && // it must be his turn (m.player.equals(turn)) && // the player must own the piece he wants to move (owner(m.begin) != null) && (owner(m.begin).equals(m.player)) && // the goal position must be empty (owner(m.end) == null) && // the goal position can be reached with a step or a jump (m.begin.neighbour(m.end) || m.begin.jumpNeighbour(m.end))); }
7
public void successAndUpdate(NullParamFn<? extends Boolean> fn) { this.val(this.suc ? fn.fn() : false); }
2
public void removeActivity(Activity a) { if (user.getActivities().contains(a.getId())) { //user will actually be changed user.removeActivity(a.getId()); //we got rid of it, so don't keep it around activities.remove(activityIdNameMap.get(a.getId())); activityIdNameMap.remove(a.getId()); activityNames = activities.keySet().toArray(new String[0]); //cleanup //remove from schedule if (schedule != null) { schedule.removeActivity(a.getId()); MongoHelper.save(schedule, MongoHelper.SCHEDULE_COLLECTION); } //get the group and clean if (groups != null && groupIdNameMap != null) { Group f = groups.get(groupIdNameMap.get(a.getGroup())); if (f != null) { f.removeActivity(a.getId()); MongoHelper.save(f, MongoHelper.GROUP_COLLECTION); } } //make changes to db MongoHelper.save(user, MongoHelper.USER_COLLECTION); MongoHelper.delete(a, MongoHelper.ACTIVITY_COLLECTION); } }
5
public static void main(String[] args) { final Count2 count = new Count2(); for (int i = 0; i < 5; i++) { new Thread() { public void run() { count.get(); } }.start(); } for (int i = 0; i < 5; i++) { new Thread() { public void run() { count.put(); } }.start(); } }
2
public static void main(String[] args) { boolean[] primes = new boolean[2000000]; for (int i = 2; i < primes.length; i++) primes[i] = true; for (int i = 2; i < primes.length; i++) if (primes[i]) for (int j = 2; i*j < primes.length; j++) primes[i*j] = false; ArrayList<Integer> primeList = new ArrayList<Integer>(); for (int i = 5; i <= 1000000; i++) if (primes[i]) primeList.add(i); int a = 1000000; while (true) { a++; if (primes[a]) { primeList.add(a); break; } } long sum = 0L; for (int i = 0; i < primeList.size()-1; i++) sum += lowestMultiple(primeList.get(i),primeList.get(i+1)); System.out.println(sum); }
9
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { boolean handled = false; if (is(label, "ol")) { if ((args.length == 1) && (is(args[0], "reload"))) { handled = true; if (!isPlayer(sender)) { OKConfig.loadkeys(); OKLogger.info("Configuration reloaded!"); } else if (OKmain.checkPermission(getPlayer(sender), "oklogger.reload")) { OKConfig.loadkeys(); sendMessage(sender, ChatColor.GOLD + "Configuration reloaded!"); } else { sendMessage(sender, ChatColor.LIGHT_PURPLE + "You do not have permission to do this."); } } else { handled = true; sendMessage(sender, "Incorrect command usage: /" + label + " " + join(args, 0)); } } return handled; }
5
public boolean lookupEmail(String email) { Connection connection = null; String query = null; PreparedStatement statement = null; try { connection = dataSource.getConnection(); query = "SELECT * FROM users WHERE email = ?;"; statement = (PreparedStatement)connection.prepareStatement(query); statement.setString(1, email); ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { return true; } } catch (SQLException sqle) { sqle.printStackTrace(); } finally { try { statement.close(); connection.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } } return false; }
3
public Object get() { return queueList.removeFirst(); }
0
public String getNick() { return _nick; }
0
public static int calculateNumberOfWaysToGetChange(int num, int type){ int next_type = 0; if(type == QUARTER) next_type = DIME; else if(type == DIME) next_type = NICKEL; else if(type == NICKEL) next_type = PENNY; else if(type == PENNY) return PENNY; int ways = 0; for(int i = 0; i * type <= num; i++){ ways += calculateNumberOfWaysToGetChange(num - i * type, next_type); } return ways; }
5
public boolean isItemReceived() { if (itemReceivedInt == "1") { return true; } else { return false; } }
1
public static void raggiunto (int num_uno, double grow_uno, int num_due, double grow_due) { int final_uno = 0; int final_due = 0; int years = 1; boolean flag = false; if ( (num_uno > num_due && grow_uno > grow_due) && (num_due > num_uno && grow_due > grow_uno) ) { System.out.println ("Le Popolazioni Non Si Raggiungeranno Mai !!!"); return; } do { final_uno = number_after_year (years,num_uno,grow_uno); final_due = number_after_year (years,num_due,grow_due); if (final_uno == final_due) { flag = true; System.out.println ("Le Popolazioni Si Raggiungono Dopo " + num_uno + " anni (" + final_uno + " Individui )"); } years++; } while (!flag); }
6
public void setFesUsuario(String fesUsuario) { this.fesUsuario = fesUsuario; }
0
public void Start(boolean changefilename) throws FileNotFoundException { if (changefilename) { try { ChangeFilePath(filepath); } catch (IOException e) { e.printStackTrace(); } } Running = true; runner = new Log(); runner.start(); }
2
private int checkPasswordField() { int res = 0; lblError.setVisible(false); if (cbAdministrator.isSelected() && roleStateAdministrator == 0) { if (!Validate.tfEmpty(tfPassword) && Validate.notOverSize(tfPassword)) { res = 1; } else { lblError.setText("Fyll i ett lösenord"); lblError.setVisible(true); } } return res; }
4
public void addParameter(String parameterType) throws SQLException { switch (parameterType) { case "string": try { StringParameter newParameter = new StringParameter(); newParameter.setElementId(element.getId()); newParameter.setName("New parameter"); newParameter.setDescription(""); newParameter.setData(""); newParameter.setMandatory(false); newParameter.setEditable(true); newParameter.setLocked(false); newParameter.setTable(Database.StringParametersTable); int newParameterId = Database.getNextFreeIndex(Database.StringParametersTable); newParameter.save(); StringParameterWindow stringParameterWindow = new StringParameterWindow(); stringParameterWindow.alert(this, "load", newParameterId); } catch (AccessFlagException e) { Log.log(e); } break; case "integer": try { IntegerParameter newParameter = new IntegerParameter(); newParameter.setElementId(element.getId()); newParameter.setName("New parameter"); newParameter.setDescription(""); newParameter.setData(0); newParameter.setMandatory(false); newParameter.setEditable(true); newParameter.setLocked(false); newParameter.setTable(Database.IntegerParametersTable); int newParameterId = Database.getNextFreeIndex(Database.StringParametersTable); newParameter.save(); IntegerParameterWindow integerParameterWindow = new IntegerParameterWindow(); integerParameterWindow.alert(this, "load", newParameterId); } catch (AccessFlagException e) { Log.log(e); } break; case "float": try { FloatParameter newParameter = new FloatParameter(); newParameter.setElementId(element.getId()); newParameter.setName("New parameter"); newParameter.setDescription(""); newParameter.setData(0.0f); newParameter.setMandatory(false); newParameter.setEditable(true); newParameter.setLocked(false); newParameter.setTable(Database.FloatParametersTable); int newParameterId = Database.getNextFreeIndex(Database.StringParametersTable); newParameter.save(); FloatParameterWindow floatParameterWindow = new FloatParameterWindow(); floatParameterWindow.alert(this, "load", newParameterId); } catch (AccessFlagException e) { Log.log(e); } break; } }
6
public void mainMenu() throws IOException { Account aA = new Account(activeAccount); Scanner in = new Scanner(System.in); System.out.println("Logged in as "+aA.getName()); System.out.println("-----------------------"); System.out.println("What do you want to manage?"); System.out.println("1.Accounts"); System.out.println("2.Apps"); System.out.println("Type a number to select an option"); System.out.println("-----------------------"); String choice = in.nextLine(); switch (choice) { case "1": accMng(); break; case "2": appMng(); break; default: System.out.println("Not a valid option."); System.out.println("-----------------------"); mainMenu(); break; } }
2
public void setUser(IrcUser user){ this.User = user; }
0
public Class<?> getColumnClass(int column) { switch(column) { case NATION_COLUMN: return Nation.class; case AVAILABILITY_COLUMN: return NationOptions.NationState.class; case ADVANTAGE_COLUMN: return NationType.class; case COLOR_COLUMN: return Color.class; case PLAYER_COLUMN: return Player.class; } return String.class; }
6
public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int row = Integer.parseInt(br.readLine()); int col = Integer.parseInt(br.readLine()); int[][] input = new int[row][col]; int[][] minPath = new int[row][col]; for (int i = 0; i < row; i++) { String[] in = br.readLine().split(" "); for (int j = 0; j < col; j++) { input[i][j] = Integer.parseInt(in[j]); if (i == 0 && j == 0) { minPath[i][j] = input[i][j]; } else { int v1 = Integer.MAX_VALUE; int v2 = Integer.MAX_VALUE; int v3 = Integer.MAX_VALUE; try { v1 = minPath[i - 1][j - 1]; } catch (Exception e) { } try { v2 = minPath[i - 1][j]; } catch (Exception e) { } try { v3 = minPath[i][j - 1]; } catch (Exception e) { } minPath[i][j] = input[i][j] + min_value(v1, v2, v3); } } } int r = Integer.parseInt(br.readLine()); int c = Integer.parseInt(br.readLine()); System.out.println(minPath[r][c]); }
7
public void killUser(String userid) { Card card = _view.cards.get(userid); _view.cards.remove(userid); _view.gamePanel.remove(card); }
0
public static Collection<String> getResourceCollection(Class clazz, String path) throws IOException { Collection<String> resourceCollection = new HashSet<>(); URL dirUrl = clazz.getResource(path); if (dirUrl == null) { try ( InputStream in = ResourceUtil.class.getResourceAsStream(path); BufferedReader br = new BufferedReader(new InputStreamReader(in))) { String line; while ((line = br.readLine()) != null) { resourceCollection.add(line); } } } else { switch (dirUrl.getProtocol()) { case "file": try { resourceCollection.addAll(Arrays.asList(new File(dirUrl.toURI()).list())); } catch (URISyntaxException e) { throw new IOException(e); } break; case "jar": String jarPath = dirUrl.getPath().substring(5, dirUrl.getPath().indexOf("!")); JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { String name = "/" + entries.nextElement().getName(); if (name.startsWith(path)) { resourceCollection.add(name.substring(path.length() + 1)); } } } } return resourceCollection; }
7
private void tulosta() { for (Henkilo h : henkilot) { System.out.println(h); } }
1
private static String round(String num, int length) { // used by realToString if (num.indexOf('.') < 0) return num; if (num.length() <= length) return num; if (num.charAt(length) >= '5' && num.charAt(length) != '.') { char[] temp = new char[length+1]; int ct = length; boolean rounding = true; for (int i = length-1; i >= 0; i--) { temp[ct] = num.charAt(i); if (rounding && temp[ct] != '.') { if (temp[ct] < '9') { temp[ct]++; rounding = false; } else temp[ct] = '0'; } ct--; } if (rounding) { temp[ct] = '1'; ct--; } // ct is -1 or 0 return new String(temp,ct+1,length-ct); } else return num.substring(0,length); }
9
private static void Take(){ if (currentLocale.getId() == 0){ mapFound = true; bag[0].setFound(true); newBag.add(bag[0].getName()); System.out.println("You found " + bag[0].getName() + ", it is in your bag."); } else if (currentLocale.getId() == 1){ bag[1].setFound(true); newBag.add(bag[1].getName()); System.out.println("You found " + bag[1].getName() + ", it is in your bag."); } else if (currentLocale.getId() == 4){ bag[2].setFound(true); newBag.add(bag[2].getName()); System.out.println("You found " + bag[2].getName() + ", it is in your bag."); } else if (currentLocale.getId() == 10){ bag[3].setFound(true); newBag.add(bag[3].getName()); System.out.println("You found " + bag[3].getName() + ", it is in your bag."); } else if (currentLocale.getId() == 9 && unlock == true){ bag[4].setFound(true); newBag.add(bag[4].getName()); System.out.println("You found " + bag[4].getName() + ", it is in your bag."); }else System.out.println("There is nothing to take here."); }
6
private Instances subset(Instances insts, HotTestDetails test) { Instances sub = new Instances(insts, insts.numInstances()); for (int i = 0; i < insts.numInstances(); i++) { Instance temp = insts.instance(i); if (!temp.isMissing(test.m_splitAttIndex)) { if (insts.attribute(test.m_splitAttIndex).isNominal()) { if (temp.value(test.m_splitAttIndex) == test.m_splitValue) { sub.add(temp); } } else { if (test.m_lessThan) { if (temp.value(test.m_splitAttIndex) <= test.m_splitValue) { sub.add(temp); } } else { if (temp.value(test.m_splitAttIndex) > test.m_splitValue) { sub.add(temp); } } } } } sub.compactify(); return sub; }
7
public void setKeywordExtractMode(String keywordExtractMode) { if( !keywordExtractMode.equals(AlchemyAPI_KeywordParams.EXTRACT_MODE_STRICT)) { throw new RuntimeException("Invalid setting " + keywordExtractMode + " for parameter keywordExtractMode"); } this.keywordExtractMode = keywordExtractMode; }
1
public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new FileReader("empty.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("empty.out"))); StringTokenizer st = new StringTokenizer(br.readLine()); n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); while(k-->0){ st = new StringTokenizer(br.readLine()); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); long A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); for(int i=1; i<=y; i++){ int preferred = (int)(A*i+B)%n; if(map.isEmpty()){ map.put(preferred, end(preferred, x)); continue; } Map.Entry<Integer,Integer> prev = prev(preferred); int start, begin, end=0; ArrayList<Integer> deleted = new ArrayList<Integer>(); if(isInside(preferred,prev)){ start = nextAdj(prev); begin = prev.getKey(); deleted.add(prev.getKey()); } else{ start = preferred; begin = preferred; } while(x>0){ Map.Entry<Integer, Integer> next = next(start); int available = length(start, prevAdj(next)); if(x>available){ x = x-available; start=nextAdj(next); deleted.add(next.getKey()); } else{ end = end(start,x); if(end == prevAdj(next)){ end = next.getValue(); deleted.add(next.getKey()); } x = 0; } } for(int key : deleted) map.remove(key); map.put(begin, end); } } int result = Math.min(prevAdj(map.firstEntry()), nextAdj(map.lastEntry())); result = Math.min(result, nextAdj(map.firstEntry())); // when first starts at 0; out.println(result); out.close(); }
8
public static void main(String[] args) { EvolvingGlobalProblemSetInitialisation starter = new EvolvingGlobalProblemSetInitialisation(); starter.initLanguage(new char[] { '0', '1' }, 10, "(1(01*0)*1|0)*"); int solutionFoundCounter = 0; int noSolutionFound = 0; List<Long> cycleCount = new LinkedList<Long>(); long tmpCycle; long timeStamp; int[] problemCount = new int[25]; int[] candidatesCount = new int[1]; int[] noCycles = new int[2]; problemCount[0] = 3; problemCount[1] = 6; problemCount[2] = 9; problemCount[3] = 12; problemCount[4] = 15; problemCount[5] = 18; problemCount[6] = 21; problemCount[7] = 24; problemCount[8] = 27; problemCount[9] = 30; problemCount[10] = 33; problemCount[11] = 36; problemCount[12] = 39; problemCount[13] = 42; problemCount[14] = 45; problemCount[15] = 48; problemCount[16] = 51; problemCount[17] = 54; problemCount[18] = 57; problemCount[19] = 60; problemCount[20] = 63; problemCount[21] = 66; problemCount[22] = 69; problemCount[23] = 72; problemCount[24] = 75; candidatesCount[0] = 50; problemCount[0] = 100; noCycles[0] = 250; noCycles[1] = 500; int pc = 0; int cc = 0; int nc = 0; for (int x = 0; x < 1; x++) { System.out.println("x:" + x); for (int n = 0; n < 25; n++) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss"); Logger l = new Logger("E_G_PS_" + df.format(new Date()) + ".log", true); pc = problemCount[n]; cc = candidatesCount[0]; nc = noCycles[1]; l.log("Problem Count: " + pc); l.log("CandidatesCount: " + cc); l.log("Max Cycles: " + nc); solutionFoundCounter = 0; noSolutionFound = 0; cycleCount = new LinkedList<Long>(); for (int i = 0; i < 100; i++) { timeStamp = System.currentTimeMillis(); starter.initProblems(pc); starter.initCandidates(cc); tmpCycle = starter.startEvolution(nc); l.log(i + ": finished (" + (System.currentTimeMillis() - timeStamp) + "ms, " + tmpCycle + "cycles)"); if (starter.getWinner() != null) { solutionFoundCounter++; cycleCount.add(tmpCycle); l.log(i + ": Solution found."); // GraphvizRenderer.renderGraph(starter.getWinner().getObj(), // "winner.svg"); } else { noSolutionFound++; l.log(i + ": No solution found."); } } long max = 0; long min = 10000; long sum = 0; for (long no : cycleCount) { sum += no; max = (no > max ? no : max); min = (no < min ? no : min); } l.log("Solution Found: " + solutionFoundCounter); l.log("Avg cycles: " + (cycleCount.size() > 0 ? sum / cycleCount.size() : '0')); l.log("Max cycles: " + max); l.log("Min cycles: " + min); l.log("No solution found: " + noSolutionFound); l.finish(); } } }
8
@Override public final void testFinished(Description description) throws Exception { super.testFinished(description); selectListener(description).testFinished(description); }
0
@Override public String toString() { return String.format("%s='%s'", getType(), getId()); }
0
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(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new MainWindow().setVisible(true); } }); }
6
public Map<String, String> writeToFile() throws FileNotFoundException, IOException { File file = new File("property.prop"); if (!file.exists()) { FileOutputStream fosTemp = new FileOutputStream("property.prop"); } FileInputStream inputFis = new FileInputStream("property.prop"); Properties inputDump = new Properties(); inputDump.load(inputFis); //System.out.println("Now DB contains " + inputDump.size() + " entries."); //Copying all the DB from file "properties.prop" into a Map<S, S> allTemp Map<String, String> allTemp = new HashMap<>(); Set<Object> allKeySet = inputDump.keySet(); for (Object o : allKeySet) { allTemp.put((String) o, (String) inputDump.get(o)); } Properties properties = new Properties(); FileOutputStream fos = new FileOutputStream("property.prop"); Map<String, String> newUpdates = new HashMap<>(); Set<String> currentMapSet = currentMap.keySet(); for (String s : currentMapSet) { if (!allTemp.containsKey(s)) { newUpdates.put(s, currentMap.get(s)); //Now allTemp contains both old and new entries allTemp.put(s, currentMap.get(s)); //properties.put(s, currentMap.get(s)); } } //System.out.println("You have " + newUpdates.size() + " new entries"); properties.putAll(allTemp); properties.store(fos, "property.prop"); return newUpdates; }
4
private void method60(int id) { Interface interfaceInstance = Interface.cachedInterfaces[id]; for (int childId : interfaceInstance.children) { if (childId == -1) { break; } Interface children = Interface.cachedInterfaces[childId]; if (children.interfaceType == 1) { method60(children.id); } children.anInt246 = 0; children.anInt208 = 0; } }
3
private static boolean binarySearch1(Long number, int lo, int hi) { if (lo > hi) return false; int location = (lo + hi) / 2; if (sorted[location]==number) return true; if (sorted[location] < number) return binarySearch1(number, location+1, hi); return binarySearch1(number, lo, location-1); }
3
void setSelectionBackground () { if (!instance.startup) { tabFolder1.setSelectionBackground(selectionBackgroundColor); } // Set the selection background item's image to match the background color of the selection. Color color = selectionBackgroundColor; if (color == null) color = tabFolder1.getSelectionBackground (); TableItem item = colorAndFontTable.getItem(SELECTION_BACKGROUND_COLOR); Image oldImage = item.getImage(); if (oldImage != null) oldImage.dispose(); item.setImage (colorImage(color)); }
3
public static Image createDegrade(boolean isColor, int height, int width, int color1, int color2) { Image degradee = null; if (isColor) { degradee = new RgbImage(width, height); } else { degradee = new RgbImage(width, height); } Color c1 = new Color(color1); Color c2 = new Color(color2); Color currentColor = new Color(color1); float redFactor = (float) (c2.getRed() - c1.getRed()) / height; float greenFactor = (float) (c2.getGreen() - c1.getGreen()) / height; float blueFactor = (float) (c2.getBlue() - c1.getBlue()) / height; float red = 0; float green = 0; float blue = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { degradee.setPixel(x, y, currentColor.getRGB()); } red = red + redFactor; green = green + greenFactor; blue = blue + blueFactor; currentColor = new Color(c1.getRGB() + (int) ((int) red * 0x010000) + (int) ((int) green * 0x000100) + (int) ((int) blue * 0x000001)); } return degradee; }
3
@Override public Formula generateOffer (Formula offer, int snum) { Formula responseOffer = getPreferedOffer(offer, snum); if (responseOffer != null) { addHistoryFormula(responseOffer); } if (offer != null && offer.equals(responseOffer) && offer.getPrice() >= responseOffer.getThreshold()) responseOffer.setAccepted(true); return responseOffer; }
4
private void handleDisplay() { //prompt user System.out.println("\n--Display Course Sections--"); if (dataModel.isEmpty()) { System.out.println("No courses stored. Nothing to display."); return; } System.out.println("Stored courses:"); for (String str : dataModel.getCourseSet()) { System.out.println(str); } System.out.println(); System.out.println("Specify which course to display, or enter \"ALL\""); String input = getUserInput(); //TODO: Sanitize if (input.equalsIgnoreCase("ALL")) { for (String str : dataModel.getCourseSet()) printSections(dataModel.getSections(str)); } else { printSections(dataModel.getSections(input)); } }
4
public static int maxValue(Node root) { if(root == null) return -1; else if(root.left == null && root.right == null) return root.data; else if(root.left == null) return Math.max(root.data, maxValue(root.right)); else if(root.right == null) return Math.max(root.data, maxValue(root.left)); else return Math.max(root.data, Math.max(maxValue(root.left), maxValue(root.right))); }
5
@Override public void inputData(Map<String, Map<String, String>> input) { //name : index[] : answer Iterator<String> nameIterator = input.keySet().iterator(); Map<String, String> indexToAnswers = input.get(nameIterator.next()); String[] data = indexToAnswers.get("0").split(COLON_SEPARATOR); if (data[0].equals("0")) { //mouse move event int xMove = Integer.parseInt(data[1]); int yMove = Integer.parseInt(data[2]); Point p = MouseInfo.getPointerInfo().getLocation(); int x = p.x; int y = p.y; r.mouseMove(x + xMove, y + yMove); } else if (data[0].equals("1")){ //mouse button event if (data[2].equals("0")){ //left mouse click r.mousePress(InputEvent.BUTTON1_MASK); r.waitForIdle(); r.mouseRelease(InputEvent.BUTTON1_MASK); } else if(data[2].equals("1")){//right mouse click r.mousePress(InputEvent.BUTTON3_MASK); r.waitForIdle(); r.mouseRelease(InputEvent.BUTTON3_MASK); } else if(data[2].equals("2")){//left mouse down r.mousePress(InputEvent.BUTTON1_MASK); } else if(data[2].equals("3")){//left mouse up r.mouseRelease(InputEvent.BUTTON1_MASK); } else if(data[2].equals("4")){//right mouse down r.mousePress(InputEvent.BUTTON3_MASK); } else if(data[2].equals("5")){//right mouse up r.mouseRelease(InputEvent.BUTTON3_MASK); } } // else if (data[0].equals("2")){//keyboard event // //System.out.println("received keyboard event: "+(char)(data[2])); //// typeCharacter(r, Character.toString((char)data[2]) ); // // } }
8
private void loadPrefab(int spawnX, int spawnY){ String pathTag = "HousePrefab"; String path = ""; path = "data/" + pathTag + String.valueOf(spawnRotation) + ".pfb"; File f = new File(path); if (f.isFile()){ try { prefab.buildPrefab(spawnX, spawnY, path); } catch (IOException e) { e.printStackTrace(); } spawnRotation++; } else { spawnRotation = 0; } }
2
@Override public void open(String name) throws ChannelException { try { if (port == null) { port = (SerialPort) commPortIdentifier.open(name, 2000); } port.setSerialPortParams( 19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); port.addEventListener(new Receiver()); port.notifyOnDataAvailable(true); inputStream = port.getInputStream(); outputStream = port.getOutputStream(); } catch (PortInUseException | UnsupportedCommOperationException | TooManyListenersException | IOException ex) { throw new ChannelException(ex); } }
2
public List<ElementInfo> getElementsOnPosition(Position pos) { final List<ElementInfo> elements = new ArrayList<ElementInfo>(); for (Element elem : grid.getElementsOnPosition(pos)) elements.add((ElementInfo) elem); return elements; }
1
public static ImageIcon importState() { if(isImChose) { if(isImPress) return imPre; if(isImHover) return imChoHov; return imCho; } if(isImPress) return imPre; if(isImHover) return imHov; return imDef; }
5
public boolean addCouponToDatabase(Coupon coupon) throws SQLException { if (couponExists(coupon)) return false; Connection con = sql.getConnection(); PreparedStatement p = null; if (coupon instanceof ItemCoupon) { ItemCoupon c = (ItemCoupon) coupon; p = con.prepareStatement("INSERT INTO couponcodes (name, ctype, usetimes, usedplayers, ids, timeuse) "+ "VALUES (?, ?, ?, ?, ?, ?)"); p.setString(1, c.getName()); p.setString(2, c.getType()); p.setInt(3, c.getUseTimes()); p.setString(4, plugin.convertHashToString2(c.getUsedPlayers())); p.setString(5, plugin.convertHashToString(c.getIDs())); p.setInt(6, c.getTime()); } else if (coupon instanceof EconomyCoupon) { EconomyCoupon c = (EconomyCoupon) coupon; p = con.prepareStatement("INSERT INTO couponcodes (name, ctype, usetimes, usedplayers, money, timeuse) "+ "VALUES (?, ?, ?, ?, ?, ?)"); p.setString(1, c.getName()); p.setString(2, c.getType()); p.setInt(3, c.getUseTimes()); p.setString(4, plugin.convertHashToString2(c.getUsedPlayers())); p.setInt(5, c.getMoney()); p.setInt(6, c.getTime()); } else if (coupon instanceof RankCoupon) { RankCoupon c = (RankCoupon) coupon; p = con.prepareStatement("INSERT INTO couponcodes (name, ctype, usetimes, usedplayers, groupname, timeuse) "+ "VALUES (?, ?, ?, ?, ?, ?)"); p.setString(1, c.getName()); p.setString(2, c.getType()); p.setInt(3, c.getUseTimes()); p.setString(4, plugin.convertHashToString2(c.getUsedPlayers())); p.setString(5, c.getGroup()); p.setInt(6, c.getTime()); } else if (coupon instanceof XpCoupon) { XpCoupon c = (XpCoupon) coupon; p = con.prepareStatement("INSERT INTO couponcodes (name, ctype, usetimes, usedplayers, timeuse, xp) "+ "VALUES (?, ?, ?, ?, ?, ?)"); p.setString(1, c.getName()); p.setString(2, c.getType()); p.setInt(3, c.getUseTimes()); p.setString(4, plugin.convertHashToString2(c.getUsedPlayers())); p.setInt(5, c.getTime()); p.setInt(6, c.getXp()); } p.addBatch(); con.setAutoCommit(false); p.executeBatch(); con.setAutoCommit(true); EventHandle.callCouponAddToDatabaseEvent(coupon); return true; }
5
public boolean hasCycle(ListNode head) { if (head ==null){ return false; } if(head.next == null) return false; if(head.next.next == null) return false; ListNode p_fast = head.next.next; ListNode p_slow = head.next; while (p_slow != p_fast){ if(p_fast.next == null){ return false; } if(p_fast.next.next == null){ return false; } p_slow = p_slow.next; p_fast = p_fast.next.next; } return true; }
6
@BeforeClass public static void setUpBeforeClass() { try { new MySQLConnection(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
5
public ProductDao getProductDao() { if (productDao == null) { productDao = new ProductDaoImp(); } return productDao; }
1
public static void main(String argv[]) { try { String filepath = "c:\\file.xml"; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(filepath); NodeList list = doc.getElementsByTagName("staff"); System.out.println("Total of elements : " + list.getLength()); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (SAXException sae) { sae.printStackTrace(); } }
3
public void uploadArray(String vname,float defaultValue) throws UnknownHostException, IOException, WrongArgumentException, InterruptedException { creater = new ArrayCreater(conf, zone, this.shapes.get(this.shapes.size() - 1),vname,this.thread_num,defaultValue); int i ; int []srcShape = new int [chunk.getChunkStep().length]; long tmpSize = 1; for( i = 0 ; i < chunk.getChunkStep().length ; ++i) { srcShape[i] = chunk.getChunkStep()[i]; tmpSize *= this.vsize[i]; } this.dataSize += tmpSize; srcShape[i-1] = 1; creater.create(); long btime = System.currentTimeMillis(); do{ //float []data = new float [chunk.getSize()]; //TODO how to parralel reading from source creater.createPartition(scanner,chunk,vname); }while(this.chunk.nextChunk()); try { while(!creater.close(30, TimeUnit.SECONDS)) { //System.out.println("Waiting for the creating of the array"); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } long etime = System.currentTimeMillis(); this.timeUsed += etime - btime; }
4
public void actionPerformed(ActionEvent ae) { // // Process the action command // // "ok" - Data entry is complete // "cancel" - Cancel the request // "help" - Display help for investment accounts // try { switch (ae.getActionCommand()) { case "ok": if (processFields()) { setVisible(false); dispose(); } break; case "cancel": setVisible(false); dispose(); break; case "help": Main.mainWindow.displayHelp(HelpWindow.INVESTMENT_ACCOUNT); break; } } catch (Exception exc) { Main.logException("Exception while processing action event", exc); } }
5
private void printParts(String query, PartFactory partFactory, PrintStream psHtml, int maxRows) { TreeSet<Part> parts = new TreeSet<Part>(); for (Part part : partFactory) { if (partMatchesQuery(part, query)) { parts.add(part); if (parts.size() >= maxRows) { break; } } } psHtml.println("<table cellpadding=0 cellspacing=0 class='firebom_table'>"); psHtml.println("<tr>"); psHtml.println("<th class='firebom_th'>#</th>"); psHtml.println("<th class='firebom_th'>OBJECT</th>"); psHtml.println("<th class='firebom_th'>ID</th>"); psHtml.println("<th class='firebom_th firebom_longtext'>TITLE</th>"); psHtml.println("<th class='firebom_th'>AGE@REFRESH</th>"); psHtml.println("</tr>"); int row = 1; for (Part part : parts) { psHtml.print("<tr>"); psHtml.print("<td class='firebom_td'>"); psHtml.print(row++); psHtml.print("</td>"); psHtml.print("<td class='firebom_td firebom_longtext'>"); psHtml.print(part.hashCode()); psHtml.print("</td>"); psHtml.print("<td class='firebom_td' title='"); psHtml.print(part.getUrl()); psHtml.print("'>"); psHtml.print(part.getId()); psHtml.print("</td>"); psHtml.print("<td class='firebom_td firebom_longtext' title='"); psHtml.print(part.getSourceUrl()); psHtml.print("'>"); psHtml.print(part.getTitle()); psHtml.print("</td>"); if (part.getRefreshException() != null) { psHtml.print("<td class='firebom_td firebom_error' title='"); psHtml.print(part.getRefreshException().getMessage()); psHtml.print("'>"); } else if (!part.isResolved()) { psHtml.print("<td class='firebom_td firebom_unresolved'>"); } else if (!part.isFresh()) { psHtml.print("<td class='firebom_td firebom_stale'>"); } else { psHtml.print("<td class='firebom_td firebom_fresh'>"); } psHtml.print((part.getAge() + 500) / 1000); psHtml.print("@"); psHtml.print((part.getRefreshInterval() + 500) / 1000); psHtml.print("</td>"); psHtml.print("</tr>"); } psHtml.print("</table>"); psHtml.print("Refresh queue: "); psHtml.println("<ol>"); for (Part part : partFactory.getRefreshQueue()) { psHtml.println("<li>"); psHtml.println(part.getUrl()); psHtml.println("</li>"); } psHtml.println("</ol>"); psHtml.println("<script>setTimeout(function() {location.reload();}, 5000)</script>"); }
8
private boolean getIsIdRightOrientedInEdge(int id, Edge edge){ if(id == edge.getIdA()){ //id is A if(edge.getType() == EdgeType.NORMAL || edge.getType() == EdgeType.INNIE){ return true; }else{ return false; } }else{ //id is B if(edge.getType() == EdgeType.NORMAL || edge.getType() == EdgeType.OUTIE){ return true; }else{ return false; } } }
5
private void readRLE(BufferedImage im, LittleEndianInputStream in) throws IOException { in.readInt(); // length int palSize = in.readInt(); if (palSize < 1 || palSize > 256) throw new FileFormatException("Invalid palette size"); int[] pal = new int[palSize]; for (int i = 0; i < palSize; i++) pal[i] = readPix(in); int x = 0; int y = 0; while (y < height) { int c = in.readByte(); int num = (c >> 1) + 1; if ((c & 1) == 0) { for (int i = 0; i < num; i++) { im.setRGB(x, y, pal[in.readByte()]); if (++x >= width) { x = 0; y++; } } } else { int pix = pal[in.readByte()]; for (int i = 0; i < num; i++) { im.setRGB(x, y, pix); if (++x >= width) { x = 0; y++; } } } } }
9
private void executeBattleCommand(String[] commandString, Player player) throws CommandException { if (AttackCommand.isAttackCommand(commandString[0])) { BattleFeedbackEnum feedback = null; AttackCommand firstCommand = AttackCommand.toCommand(commandString[0]); switch (firstCommand) { case TARGET: feedback = target(commandString, player); break; case REPAIR: feedback = repair(commandString, player); break; case ESCAPE: feedback = escape(player); break; } if (feedback != null) { handleBattleFeedback(feedback, player, battlePlayer, false); if (state == GameState.BATTLE) { if (battlePlayer instanceof AIPlayer) { handleBattleFeedback(PlayerManagerAI.attackPlayer((AIPlayer) battlePlayer, player, battleCounter), battlePlayer, player, true); } else { // future code for hotseat human battles } } } } else { throw new CommandException("Invalid battle command: " + commandString[0]); } }
7
public void setMinecraftArguments(String minecraftArguments) { if (minecraftArguments == null) throw new IllegalArgumentException("Process arguments cannot be null or empty"); this.minecraftArguments = minecraftArguments; }
1
private void writeCurrentClassificationResultsForOneInterval( String classificationResultsFilename, int interval) throws IOException { // find maxHop byte maxHop = 0; for (byte hop : this.results.get(interval).getCorrelatedSpikesStats() .keySet()) { if (maxHop < hop) { maxHop = hop; } } // create folders if needed if (classificationResultsFilename.lastIndexOf("/") != -1) { File file = new File(classificationResultsFilename.substring(0, classificationResultsFilename.lastIndexOf("/"))); file.mkdirs(); } // prepare file File file = new File(classificationResultsFilename); FileWriter fwr = new FileWriter(file, true); BufferedWriter bwr = new BufferedWriter(fwr); if (!file.exists()) { // write header bwr.write("Spike_size\tSingle_0.33\tSingleUpdates_0.33\tSingle_0.66\tSingleUpdates_0.66\tSingle_1\tSingleUpdates_1"); for (byte hop = 1; hop <= maxHop; hop++) { bwr.write("\tDuplicated_" + hop + "_hop\tDuplicatedUpdates_" + hop + "_hop"); } } // start a new line bwr.write("\n"); // write spike sizes bwr.write("" + (interval * 100 - 100) + ".." + (interval * 100 - 1)); // write stats for single spikes with visibility <= 0.33 bwr.write("\t" + this.results.get(interval).getSingleSpikesMax033Visible() .getTotalNumberOfSpikes() + "\t" + this.results.get(interval).getSingleSpikesMax033Visible() .getTotalNumberOfPrefixes()); // write stats for single spikes with (0.33 < visibility <= 0.66) bwr.write("\t" + this.results.get(interval).getSingleSpikesMax066Visible() .getTotalNumberOfSpikes() + "\t" + this.results.get(interval).getSingleSpikesMax066Visible() .getTotalNumberOfPrefixes()); // write stats for single spikes with (0.66 < visibility <= 1) bwr.write("\t" + this.results.get(interval).getSingleSpikes100Visible() .getTotalNumberOfSpikes() + "\t" + this.results.get(interval).getSingleSpikes100Visible() .getTotalNumberOfPrefixes()); // write statistics for correlated spikes for every hop for (byte hop = 1; hop <= maxHop; hop++) { SpikeClassStats stats = this.results.get(interval) .getCorrelatedSpikesStats().get(hop); if (stats != null) { bwr.write("\t" + stats.getTotalNumberOfSpikes() + "\t" + stats.getTotalNumberOfPrefixes()); } else { bwr.write("\t" + 0 + "\t" + 0); } } bwr.close(); fwr.close(); }
7
public void attack() { if(monsterLP <= 0 || lifepoints <= 0) { System.out.print("The winner has been chosen"); } else { if(damage>monsterD) { int gap= monsterD-damage; monsterLP = monsterLP+gap; } if(monsterD>damage) { int gap= damage-monsterD; lifepoints = lifepoints+gap; } System.out.println("Your Hero:"); System.out.println("Lifepoints: "+lifepoints); System.out.println("Damage: "+damage); System.out.println("The Monster:"); System.out.println("Lifepoints: "+monsterLP); System.out.print("Damage: "+monsterD); } }
4
public List<Ability> returnOffensiveAffects(Physical fromMe) { final Vector<Ability> offenders=new Vector<Ability>(); for(final Enumeration<Ability> a=fromMe.effects();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A!=null)&&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_POISON)) offenders.addElement(A); } if(fromMe instanceof MOB) { final MOB mob=(MOB)fromMe; for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A!=null)&&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_POISON)) offenders.addElement(A); } } return offenders; }
7
public Set<PointGame> getAdjacentPoints() { Set<PointGame> adjacent = new HashSet<PointGame>(); // Search in 4 directions: We are done each branch if // we run out of boundary or have found a valid point. // ---------------------------------------- // x+ direction: PointGame rightNeighbor = getRightNeighbor(); if(rightNeighbor!=null) adjacent.add(rightNeighbor); // x- direction: PointGame leftNeighbor = getLeftNeighbor(); if(leftNeighbor!=null) adjacent.add(leftNeighbor); // y+ direction: down PointGame downNeighbor = getDownNeighbor(); if(downNeighbor!=null) adjacent.add(downNeighbor); // y- direction: up PointGame upNeighbor = getUpNeighbor(); if(upNeighbor!=null) adjacent.add(upNeighbor); return adjacent; }
4
public ArrayList<Account> getAccountNoMatchProject(Project project) { ArrayList<Account> result = new ArrayList<>(); for(Account account : accounts.getBusinessObjects()) { if (!project.getBusinessObjects().contains(account)){ result.add(account); } } return result; }
2
public void run(){ try{ if(lport==-1){ Class c=Class.forName(target); daemon=(ForwardedTCPIPDaemon)c.newInstance(); PipedOutputStream out=new PipedOutputStream(); io.setInputStream(new PassiveInputStream(out , 32*1024 ), false); daemon.setChannel(this, getInputStream(), out); Object[] foo=getPort(getSession(), rport); daemon.setArg((Object[])foo[3]); new Thread(daemon).start(); } else{ socket=(factory==null) ? Util.createSocket(target, lport, TIMEOUT) : factory.createSocket(target, lport); socket.setTcpNoDelay(true); io.setInputStream(socket.getInputStream()); io.setOutputStream(socket.getOutputStream()); } sendOpenConfirmation(); } catch(Exception e){ sendOpenFailure(SSH_OPEN_ADMINISTRATIVELY_PROHIBITED); close=true; disconnect(); return; } thread=Thread.currentThread(); Buffer buf=new Buffer(rmpsize); Packet packet=new Packet(buf); int i=0; try{ Session _session = getSession(); while(thread!=null && io!=null && io.in!=null){ i=io.in.read(buf.buffer, 14, buf.buffer.length-14 -Session.buffer_margin ); if(i<=0){ eof(); break; } packet.reset(); buf.putByte((byte)Session.SSH_MSG_CHANNEL_DATA); buf.putInt(recipient); buf.putInt(i); buf.skip(i); synchronized(this){ if(close) break; _session.write(packet, this, i); } } } catch(Exception e){ //System.err.println(e); } //thread=null; //eof(); disconnect(); }
9
public void fireSelectionEvent(final SelectionEvent EVENT) { fireEvent(EVENT); final EventType TYPE = EVENT.getEventType(); final EventHandler<SelectionEvent> HANDLER; if (SelectionEvent.SELECT == TYPE) { HANDLER = getOnSelect(); } else if (SelectionEvent.DESELECT == TYPE) { HANDLER = getOnDeselect(); } else { HANDLER = null; } if (null == HANDLER) return; HANDLER.handle(EVENT); }
3
public static String read_block(char[][] block, boolean row) { StringBuilder sb=new StringBuilder(); int r=block.length; int c=block[0].length; if(row) { for(int i=0;i<r;i++) { for(int j=0;j<c;j++) { if(block[i][j]!='\0') { sb.append(block[i][j]); } } } } else { for(int j=0;j<c;j++) { for(int i=0;i<r;i++) { if(block[i][j]!='\0') { sb.append(block[i][j]); } } } } return sb.toString(); }
7
public boolean isWithinDistance(Location other) { if (z != other.z) { return false; } int deltaX = other.x - x, deltaY = other.y - y; return deltaX <= 14 && deltaX >= -15 && deltaY <= 14 && deltaY >= -15; }
4
public static IdParser createParser(String id) { if (SolexaFastqParser.matchID(id)) return new SolexaFastqParser(id); if (CasavaFastqParser.matchID(id)) return new CasavaFastqParser(id); if(NCBIFastqIdParser.matchID(id)) return new NCBIFastqIdParser(id); return null; }
3
public static void clean(ResultSet result) throws SQLException { if (!activeResults.containsKey(result)) return; WeakReference<PreparedStatement> ref = activeResults.get(result); boolean removeStatement = true; for (Entry<ResultSet, WeakReference<PreparedStatement>> ent : activeResults .entrySet()) { if (!ent.getKey().equals(result) && ent.getValue().equals(ref)) removeStatement = false; } result.close(); if (removeStatement) { ref.get().close(); activeStatements.remove(ref.get()); } activeResults.remove(result); System.gc(); }
5
public void setText(String text) { if (text.equals("Main Menu")) { int i = 9; } if (!this.isSolidified() && !this.isSolidifying()) { this.initialText = text; return; } this.text = text; if (text.length() > maxChars) { for (int i = 0; i < maxChars - 3; i++) { ((CharComponent)this.getSubComponent(i)).setCharacter(text.charAt(i)); } ((CharComponent)this.getSubComponent(this.getNumSubComponents() - 3)).setCharacter('.'); ((CharComponent)this.getSubComponent(this.getNumSubComponents() - 2)).setCharacter('.'); ((CharComponent)this.getSubComponent(this.getNumSubComponents() - 1)).setCharacter('.'); } else { int i; for (i = 0; i < text.length(); i++) { ((CharComponent)this.getSubComponent(i)).setCharacter(text.charAt(i)); } while (i < maxChars) { this.getSubComponent(i).setVisible(false); i++; } } numCurrentCharacters = Math.min(text.length(), maxChars); needsAligned = true; }
7