// Method to open a file for sequential read-only. private void openFile() { // Define local primitive(s). String contents = new String(); // If a file is open, prompt to save the file before dismissing content // and reference. if (!file.toString().equals("")) { // Close the existing file. closeFile(); } // End of if file not null or not equal to a zero String. // Open a file. fileName = FileIO.findFile(this); // If a file name is returned. if (fileName != null) { // Read file. contents = FileIO.openFile(this, fileName); // Verify that the JTextAreaPanel is empty. if (sender.isTextAreaEmpty()) { // Set JTextAreaPanel. sender.setText(contents); } // End of if JTextAreaPanel is empty. else { // Reset JTextAreaPanel by replacing the range. sender.replaceRange(contents, 0, sender.getText().length()); } // End of else JTextAreaPanel is not empty. // Set file open flag to true. fileOpen = true; } // End of if a fileName is selected. } // End of openFile method.
/** * Prints vector map * * @param iTaskID Task ID * @param iTotalTasks Total number of tasks */ private void printVectorMapPartial(String sDirection, int iTaskID, int iTotalTasks) { // fitting model sdm1.mdl1.fitModel(sdm1.arg1.sResponse, sdm1.arg1.rgsPredictors); sdm1.mdl1.loadCoefficients(); // outputting maps for (int i = 0; i < sdm1.arg1.lstTimes.size(); i++) { // loading predictions sdm1.prd1.loadPartialMap(i, iTaskID, iTotalTasks); // outputting predictions if (i == 0) { FileIO.writeFile( ((SDMPrediction_BetaDiversity) sdm1.prd1).lstMapX, sdm1.arg1.sDirOutput + "/BetaDiversity_VectorX_" + sdm1.arg1.sResponse + "_" + iTaskID + ".csv", 0, false); FileIO.writeFile( ((SDMPrediction_BetaDiversity) sdm1.prd1).lstMapY, sdm1.arg1.sDirOutput + "/BetaDiversity_VectorY_" + sdm1.arg1.sResponse + "_" + iTaskID + ".csv", 0, false); } else { FileIO.writeFile( ((SDMPrediction_BetaDiversity) sdm1.prd1).lstMapX, sdm1.arg1.sDirOutput + "/BetaDiversity_VectorX_" + sdm1.arg1.sResponse + "_" + iTaskID + ".csv", 0, true); FileIO.writeFile( ((SDMPrediction_BetaDiversity) sdm1.prd1).lstMapY, sdm1.arg1.sDirOutput + "/BetaDiversity_VectorY_" + sdm1.arg1.sResponse + "_" + iTaskID + ".csv", 0, true); } } }
// This method starts from the ButtonListener class but ends up in the Ballot class, updating the // file of each Ballot public void updateBallots() { FileIO nullFile = new FileIO(); // need to create this just to gain access to the filename of the ballots file FileIO ballotFile = new FileIO(nullFile.getBallotsFileName()); ArrayList<Ballot> ballots = ballotFile.createBallots(); for (Ballot ballot : ballots) { ballot.updateFile(); } }
@Test public void testReadFile() throws Exception { // good file ArrayList<String> result = FileIO.readFile("inputs/input1.txt"); Assert.assertEquals(3, result.size()); Assert.assertEquals(result.get(0), "A1=5"); Assert.assertEquals(result.get(1), "B45=A1+4"); Assert.assertEquals(result.get(2), "G700=4"); // file not exists Assert.assertNull(FileIO.readFile("abcabc")); }
// Initialize the buttons ArrayList because there the program messes up if the voter doesn't vote // for anything, the buttons array // will be null. public void initializeButtons() { FileIO nullFile = new FileIO(); // need to create this just to gain access to the filename of the ballots file FileIO ballotFile = new FileIO(nullFile.getBallotsFileName()); _ballots = ballotFile.createBallots(); buttons = new ArrayList<JToggleButton>(); for (Ballot ballot : _ballots) { JToggleButton[] ballotButtons = ballot.getButtons(); for (int i = 0; i < ballotButtons.length; i++) { buttons.add(ballotButtons[i]); } } }
// Grab the number of buttons from all of the ballots in the program. // This will define the votes array, which stores all of the true and false values... // as to whether the button is really selected or not (because button.isSelected() won't work for // me for some reason). public void setVotesLength() { FileIO nullFile = new FileIO(); // need to create this just to gain access to the filename of the ballots file FileIO ballotsFile = new FileIO(nullFile.getBallotsFileName()); ArrayList<Ballot> throwAwayList = ballotsFile.createBallots(); int numButtons = 0; for (Ballot ballot : throwAwayList) { numButtons += ballot.getNumButtons(); } votes = new boolean[numButtons]; }
/** * Print the student solution * * @param studs The studly students assigned to their study groups */ private void printStudentSolution(ArrayList<Student> studs) { System.out.println("Solution Format: 3"); System.out.println("Objective Function: " + Objective.getDescription()); System.out.println("Class Info: " + fileIO.getClassDesc()); System.out.println("Student Info: " + fileIO.getStudentDesc()); System.out.println("Number of students: " + studs.size()); for (Student s : studs) { System.out.println(s.getEmail()); System.out.println(s.getGroupAssignment().getTime()); System.out.println(s.getGroupAssignment().getTAEmail()); } System.out.println("Solution cost: " + solutionCost); }
/** * A method that spawns an ILDS object and calls its solve method. If other algorithms were used, * this would be a good place to call their solve methods. */ public void solve() { /* Create a depth first search instance */ ILDS dfs = new ILDS(students, fileIO.getGroupTimes()); if (timeout != 0) { Thread thread = new Thread() { public void run() { Timer timer = new Timer(); timer.schedule( new TimerTask() { @Override public void run() { dfs.end(); } }, timeout); } }; thread.start(); } /* Solve and print the solution */ dfs.solve(); solutionCost = dfs.getSolutionCost(); printStudentSolution(dfs.getSolution()); }
private static String getResourceFileContent(final String filename) { try (final InputStream inputStream = getJarResourceStream(filename)) { return inputStream != null ? FileIO.toStr(inputStream) : ""; } catch (final IOException ex) { System.err.println(filename + " : " + ex.getMessage()); return ""; } }
/** * process the sample by checking it against each existing invariant and issuing an error if any * invariant is falsified or weakened. */ public void process_sample(PptMap all_ppts, PptTopLevel ppt, ValueTuple vt, Integer nonce) { this.all_ppts = all_ppts; debug.fine("processing sample from: " + ppt.name); // Add orig and derived variables FileIO.add_orig_variables(ppt, vt.vals, vt.mods, nonce); FileIO.add_derived_variables(ppt, vt.vals, vt.mods); // Intern the sample vt = new ValueTuple(vt.vals, vt.mods); // If this is an enter point, just remember it for later if (ppt.ppt_name.isEnterPoint()) { Assert.assertTrue(nonce != null); if (dir_file != null) { // Yoav: I had to do a hack to handle the case that several dtrace files are concatenated // together, // and Sung's dtrace files have unterminated calls, and when concatenating two files you // can have the same nonce. // So I have to remove the nonce found from the call_map call_map.remove(nonce); } else Assert.assertTrue(call_map.get(nonce) == null); call_map.put(nonce, new EnterCall(ppt, vt)); debug.fine("Skipping enter sample"); return; } // If this is an exit point, process the saved enter point if (ppt.ppt_name.isExitPoint()) { Assert.assertTrue(nonce != null); EnterCall ec = call_map.get(nonce); if (ec != null) { call_map.remove(nonce); debug.fine("Processing enter sample from " + ec.ppt.name); add(ec.ppt, ec.vt); } else { // didn't find the enter if (!quiet) System.out.printf("couldn't find enter for nonce %d at ppt %s\n", nonce, ppt.name()); return; } } add(ppt, vt); }
@Test public void stubOutFileCreationWithStaticPartialMocking( @Mocked({"(String)", "(OutputStream, String)"}) FileWriter fileWriter, @Mocked("close") BufferedWriter bufferedWriter) throws Exception { fileIO.writeToFile(FILE_NAME); assertExpectedFileIO(); }
/** * This does the work of main, but it never calls System.exit, so it is appropriate to be called * progrmmatically. Termination of the program with a message to the user is indicated by throwing * Daikon.TerminationMessage. * * @see #main(String[]) * @see daikon.Daikon.TerminationMessage */ public static void mainHelper(final String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { daikon.LogHelper.setupLogs(daikon.LogHelper.INFO); LongOpt[] longopts = new LongOpt[] { new LongOpt(Daikon.suppress_redundant_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(Daikon.config_option_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(Daikon.debugAll_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(Daikon.debug_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), }; Getopt g = new Getopt("daikon.ExtractConsequent", args, "h", longopts); int c; while ((c = g.getopt()) != -1) { switch (c) { case 0: // got a long option String option_name = longopts[g.getLongind()].getName(); if (Daikon.help_SWITCH.equals(option_name)) { System.out.println(usage); throw new Daikon.TerminationMessage(); } else if (Daikon.suppress_redundant_SWITCH.equals(option_name)) { Daikon.suppress_redundant_invariants_with_simplify = true; } else if (Daikon.config_option_SWITCH.equals(option_name)) { String item = Daikon.getOptarg(g); daikon.config.Configuration.getInstance().apply(item); break; } else if (Daikon.debugAll_SWITCH.equals(option_name)) { Global.debugAll = true; } else if (Daikon.debug_SWITCH.equals(option_name)) { LogHelper.setLevel(Daikon.getOptarg(g), LogHelper.FINE); } else { throw new RuntimeException("Unknown long option received: " + option_name); } break; case 'h': System.out.println(usage); throw new Daikon.TerminationMessage(); case '?': break; // getopt() already printed an error default: System.out.println("getopt() returned " + c); break; } } // The index of the first non-option argument -- the name of the file int fileIndex = g.getOptind(); if (args.length - fileIndex != 1) { throw new Daikon.TerminationMessage("Wrong number of arguments." + Daikon.lineSep + usage); } String filename = args[fileIndex]; PptMap ppts = FileIO.read_serialized_pptmap( new File(filename), true // use saved config ); extract_consequent(ppts); }
/** * ファイルからオブジェクトを読み込む。 * * @param path - データファイルのパス * @return ファイルから読み込まれたオブジェクト * @throws MineException データの読み込みに失敗した。 */ public static Object read(String path) throws MineException { try (XMLDecoder in = new XMLDecoder(FileIO.getInputStream(path))) { Object obj = in.readObject(); if (obj != null) { return obj; } else { throw new MineException("Failed to read Beans."); } } }
// ------------------------------------------------------------------- public static void report() { String str = new String(); str += "current time: " + counter++ + "\n"; str += reportNetworkState(); str += reportDetails(); str += "###\n"; System.out.println(str); FileIO.append(str, FILENAME); }
/** * Creates a valuetuple for the receiver using the vt of the original. The method copies over * the values of variables shared by both program points and sets the rest of the variables in * the receiver's valuetuple as missing. Also, adds the orig and derived variables to the * receiver and returns the newly created valuetuple. */ private static ValueTuple copySample( PptTopLevel receiver, PptTopLevel original, ValueTuple vt, int nonce) { // Make the vt for the receiver ppt // Object values[] = new Object[receiver.num_tracevars]; // int mods[] = new int[receiver.num_tracevars]; Object values[] = new Object[receiver.var_infos.length - receiver.num_static_constant_vars]; int mods[] = new int[receiver.var_infos.length - receiver.num_static_constant_vars]; // Build the vt for the receiver ppt by looking through the current // vt and filling in the gaps. int k = 0; for (Iterator<VarInfo> i = receiver.var_info_iterator(); i.hasNext(); ) { VarInfo var = i.next(); if (var.is_static_constant) continue; boolean found = false; for (Iterator<VarInfo> j = original.var_info_iterator(); j.hasNext(); ) { VarInfo var2 = j.next(); if (var.name().equals(var2.name())) { values[k] = vt.getValueOrNull(var2); mods[k] = vt.getModified(var2); found = true; break; } } if (!found) { values[k] = null; mods[k] = 2; } k++; } ValueTuple receiver_vt = new ValueTuple(values, mods); FileIO.add_orig_variables(receiver, receiver_vt.vals, receiver_vt.mods, nonce); FileIO.add_derived_variables(receiver, receiver_vt.vals, receiver_vt.mods); return receiver_vt; }
// Update the true/false value of every button in the program, and set every value to its // respective position in the votes array public void updateButtons(String text) { FileIO nullFile = new FileIO(); // need to create this just to gain access to the filename of the ballots file FileIO ballotFile = new FileIO(nullFile.getBallotsFileName()); _ballots = ballotFile.createBallots(); buttons = new ArrayList<JToggleButton>(); for (Ballot ballot : _ballots) { JToggleButton[] ballotButtons = ballot.getButtons(); for (int i = 0; i < ballotButtons.length; i++) { buttons.add(ballotButtons[i]); } } int numButtons = 0; for (Ballot ballot : _ballots) { numButtons += ballot.getButtons().length; } for (int i = 0; i < numButtons; i++) { if (buttons.get(i).getText().equals(text)) { votes[i] = true; } } }
public Phase(String jsonString) { try { JSONObject jObj = FileIO.parseJSONString(jsonString); type = jObj.get("CycleType").toString(); start = Integer.parseInt(jObj.get("CycleStart").toString()); end = Integer.parseInt(jObj.get("CycleEnd").toString()); } catch (ClassCastException ce) { System.err.format("Malformed JSON: %s%n", ce); } catch (NullPointerException ne) { type = "error"; start = -1; end = -1; } }
// Method to saveAsFile(). private void saveAsFile() { // Set a file. fileName = FileIO.nameFile(this); // If a file name is selected. if (fileName != null) { // Try block to throw a custom exception. try { // Save file. FileIO.saveFile(this, fileName, sender.getText()); } // End of try to get message. catch (BufferEmptyException e) // Catch InvalidFileReference. { // Capture the stack trace into a String. setExceptionString(e.fillInStackTrace()); // Pass message to the JOptionPane manager. setExceptionPane( "There is nothing in the sender panel to write.\n\n" + "Do you want to see the stack trace?"); } // End of catch on BufferEmptyException. } // End of if a fileName is selected. } // End of saveAsFile() method.
@Test public void stubOutFileCreationWithMockUps() throws Exception { new MockUp<FileWriter>() { @Mock void $init(String s) {} }; new MockUp<OutputStreamWriter>() { @Mock void $init(OutputStream out, String s) {} }; new MockUp<BufferedWriter>() { @Mock void close() {} }; fileIO.writeToFile(FILE_NAME); assertExpectedFileIO(); }
public static void main(String[] args) { Outlet<Integer> outlet = null; Outlet<Integer> outlet1 = null; Outlet<Integer> outlet2 = null; Inlet<Integer> inlet = null; Inlet<Integer> inlet1 = null; Inlet<Integer> inlet2 = null; Flow<Integer, Integer, BoxedUnit> flow = Flow.of(Integer.class); Flow<Integer, Integer, BoxedUnit> flow1 = Flow.of(Integer.class); Flow<Integer, Integer, BoxedUnit> flow2 = Flow.of(Integer.class); Promise<Option<Integer>> promise = null; { Graph<SourceShape<Integer>, BoxedUnit> graphSource = null; Graph<SinkShape<Integer>, BoxedUnit> graphSink = null; Graph<FlowShape<Integer, Integer>, BoxedUnit> graphFlow = null; // #flow-wrap Source<Integer, BoxedUnit> source = Source.fromGraph(graphSource); Sink<Integer, BoxedUnit> sink = Sink.fromGraph(graphSink); Flow<Integer, Integer, BoxedUnit> aflow = Flow.fromGraph(graphFlow); Flow.fromSinkAndSource(Sink.<Integer>head(), Source.single(0)); Flow.fromSinkAndSourceMat(Sink.<Integer>head(), Source.single(0), Keep.left()); // #flow-wrap Graph<BidiShape<Integer, Integer, Integer, Integer>, BoxedUnit> bidiGraph = null; // #bidi-wrap BidiFlow<Integer, Integer, Integer, Integer, BoxedUnit> bidiFlow = BidiFlow.fromGraph(bidiGraph); BidiFlow.fromFlows(flow1, flow2); BidiFlow.fromFlowsMat(flow1, flow2, Keep.both()); // #bidi-wrap } { // #graph-create GraphDSL.create( builder -> { // ... return ClosedShape.getInstance(); }); GraphDSL.create( builder -> { // ... return new FlowShape<>(inlet, outlet); }); // #graph-create } { // #graph-create-2 GraphDSL.create( builder -> { // ... return SourceShape.of(outlet); }); GraphDSL.create( builder -> { // ... return SinkShape.of(inlet); }); GraphDSL.create( builder -> { // ... return FlowShape.of(inlet, outlet); }); GraphDSL.create( builder -> { // ... return BidiShape.of(inlet1, outlet1, inlet2, outlet2); }); // #graph-create-2 } { // #graph-builder GraphDSL.create( builder -> { builder.from(outlet).toInlet(inlet); builder.from(outlet).via(builder.add(flow)).toInlet(inlet); builder.from(builder.add(Source.single(0))).to(builder.add(Sink.head())); // ... return ClosedShape.getInstance(); }); // #graph-builder } // #source-creators Source<Integer, Promise<Option<Integer>>> src = Source.<Integer>maybe(); // Complete the promise with an empty option to emulate the old lazyEmpty promise.trySuccess(scala.Option.empty()); final Source<String, Cancellable> ticks = Source.tick( FiniteDuration.create(0, TimeUnit.MILLISECONDS), FiniteDuration.create(200, TimeUnit.MILLISECONDS), "tick"); final Source<Integer, BoxedUnit> pubSource = Source.fromPublisher(TestPublisher.<Integer>manualProbe(true, sys)); final Source<Integer, BoxedUnit> futSource = Source.fromFuture(Futures.successful(42)); final Source<Integer, Subscriber<Integer>> subSource = Source.<Integer>asSubscriber(); // #source-creators // #sink-creators final Sink<Integer, BoxedUnit> subSink = Sink.fromSubscriber(TestSubscriber.<Integer>manualProbe(sys)); // #sink-creators // #sink-as-publisher final Sink<Integer, Publisher<Integer>> pubSink = Sink.<Integer>asPublisher(false); final Sink<Integer, Publisher<Integer>> pubSinkFanout = Sink.<Integer>asPublisher(true); // #sink-as-publisher // #empty-flow Flow<Integer, Integer, BoxedUnit> emptyFlow = Flow.<Integer>create(); // or Flow<Integer, Integer, BoxedUnit> emptyFlow2 = Flow.of(Integer.class); // #empty-flow // #flatMapConcat Flow.<Source<Integer, BoxedUnit>>create() .<Integer, BoxedUnit>flatMapConcat( new Function<Source<Integer, BoxedUnit>, Source<Integer, BoxedUnit>>() { @Override public Source<Integer, BoxedUnit> apply(Source<Integer, BoxedUnit> param) throws Exception { return param; } }); // #flatMapConcat Uri uri = null; // #raw-query final akka.japi.Option<String> theRawQueryString = uri.rawQueryString(); // #raw-query // #query-param final akka.japi.Option<String> aQueryParam = uri.query().get("a"); // #query-param // #file-source-sink final Source<ByteString, Future<Long>> fileSrc = FileIO.fromFile(new File(".")); final Source<ByteString, Future<Long>> otherFileSrc = FileIO.fromFile(new File("."), 1024); final Sink<ByteString, Future<Long>> fileSink = FileIO.toFile(new File(".")); // #file-source-sink // #input-output-stream-source-sink final Source<ByteString, Future<java.lang.Long>> inputStreamSrc = StreamConverters.fromInputStream( new Creator<InputStream>() { public InputStream create() { return new SomeInputStream(); } }); final Source<ByteString, Future<java.lang.Long>> otherInputStreamSrc = StreamConverters.fromInputStream( new Creator<InputStream>() { public InputStream create() { return new SomeInputStream(); } }, 1024); final Sink<ByteString, Future<java.lang.Long>> outputStreamSink = StreamConverters.fromOutputStream( new Creator<OutputStream>() { public OutputStream create() { return new SomeOutputStream(); } }); // #input-output-stream-source-sink // #output-input-stream-source-sink final FiniteDuration timeout = FiniteDuration.Zero(); final Source<ByteString, OutputStream> outputStreamSrc = StreamConverters.asOutputStream(); final Source<ByteString, OutputStream> otherOutputStreamSrc = StreamConverters.asOutputStream(timeout); final Sink<ByteString, InputStream> someInputStreamSink = StreamConverters.asInputStream(); final Sink<ByteString, InputStream> someOtherInputStreamSink = StreamConverters.asInputStream(timeout); // #output-input-stream-source-sink }
/** Parse input and store results into FileInfo */ private void getInfo() { fileIO = new FileIO(); fileIO.getInfo(); students = fileIO.getStudents(); }
// ------------------------------------------------------------------- public static void init(int numOfStripes) { FileIO.write("", FILENAME); }
public FileFileIO(FileIO dir, String name) { this(dir.getPath(), name); }
/** * Process the sample by checking it against each existing invariant at the program point and * removing the invariant from the list of possibles if any invariant is falsified. */ public void process_sample( PptMap all_ppts, PptTopLevel ppt, ValueTuple vt, /*@Nullable*/ Integer nonce) { this.all_ppts = all_ppts; // Add samples to orig and derived variables FileIO.add_orig_variables(ppt, vt.vals, vt.mods, nonce); FileIO.add_derived_variables(ppt, vt.vals, vt.mods); // Intern the sample vt = new ValueTuple(vt.vals, vt.mods); // DaikonSimple must make the object program point manually because // the new Chicory produced dtrace files do not contain object ppts // in the dtrace part of the file (the program point is declared). // Make the object ppt PptName ppt_name = ppt.ppt_name; PptTopLevel object_ppt = null; PptTopLevel class_ppt = null; ValueTuple object_vt = null; ValueTuple class_vt = null; if ((ppt_name.isEnterPoint() && !ppt_name.isConstructor()) || ppt_name.isExitPoint()) { object_ppt = all_ppts.get(ppt_name.makeObject()); class_ppt = all_ppts.get(ppt_name.makeClassStatic()); } // C programs do not have object ppts // check whether the ppt is a static or instance method // that decides whether the sample is copied over to the object and/or // class ppt if (object_ppt != null) { // the check assumes that static fields are not stored first in the // object ppt if (ppt.find_var_by_name(object_ppt.var_infos[0].name()) != null) { // object and class ppt should be created object_vt = copySample(object_ppt, ppt, vt, nonce); if (class_ppt != null) { class_vt = copySample(class_ppt, ppt, vt, nonce); } } else { // only class ppt should be created if (class_ppt != null) { class_vt = copySample(class_ppt, ppt, vt, nonce); } object_vt = null; object_ppt = null; } } // If this is an enter point, just remember it for later if (ppt_name.isEnterPoint()) { assert nonce != null; assert call_map.get(nonce) == null; List<Call> value = new ArrayList<Call>(); value.add(new Call(ppt, vt)); if (object_ppt != null) { value.add(new Call(object_ppt, object_vt)); } if (class_ppt != null) { value.add(new Call(class_ppt, class_vt)); } call_map.put(nonce, value); last_nonce = nonce; wait = true; return; } // If this is an exit point, process the saved enter (and sometimes // object) point if (ppt_name.isExitPoint()) { assert nonce != null; List<Call> value = call_map.remove(nonce); add(ppt, vt, nonce); for (Call ec : value) { add(ec.ppt, ec.vt, nonce); } wait = false; } if (object_ppt != null) add(object_ppt, object_vt, nonce); // apply object vt if (class_ppt != null) add(class_ppt, class_vt, nonce); }
/** * This does the work of main, but it never calls System.exit, so it is appropriate to be called * progrmmatically. Termination of the program with a message to the user is indicated by throwing * Daikon.TerminationMessage. * * <p>Difference from Daikon's mainHelper: turn off optimization flags (equality, dynamic * constants, NIS suppression). * * @see #main(String[]) * @see daikon.Daikon.TerminationMessage * @see daikon.Daikon#mainHelper(String[]) */ public static void mainHelper(final String[] args) throws IOException, FileNotFoundException { // set up logging information daikon.LogHelper.setupLogs(daikon.LogHelper.INFO); // No optimizations used in the simple incremental algorithm so // optimizations are turned off. Daikon.use_equality_optimization = false; Daikon.dkconfig_use_dynamic_constant_optimization = false; Daikon.suppress_implied_controlled_invariants = false; NIS.dkconfig_enabled = false; // The flag tells FileIO and Daikon to use DaikonSimple // specific methods (e.g. FileIO.read_declaration_file). // When FileIO reads and processes // samples, it must use the SimpleProcessor rather than the // default Processor. Daikon.using_DaikonSimple = true; // Read command line options Daikon.FileOptions files = Daikon.read_options(args, usage); // DaikonSimple does not supply nor use the spinfo_files and map_files Set<File> decls_files = files.decls; Set<String> dtrace_files = files.dtrace; if ((decls_files.size() == 0) && (dtrace_files.size() == 0)) { throw new Daikon.TerminationMessage("No .decls or .dtrace files specified"); } // Create the list of all invariant types Daikon.setup_proto_invs(); // Create the program points for enter and numbered exits and // initializes the points (adding orig and derived variables) all_ppts = FileIO.read_declaration_files(decls_files); // Create the combined exits (and add orig and derived vars) // Daikon.create_combined_exits(all_ppts); // Read and process the data trace files SimpleProcessor processor = new SimpleProcessor(); FileIO.read_data_trace_files(dtrace_files, all_ppts, processor, true); // System.exit(0); // Print out the invariants for each program point (sort first) for (Iterator<PptTopLevel> t = all_ppts.pptIterator(); t.hasNext(); ) { PptTopLevel ppt = t.next(); // We do not need to print out program points that have not seen // any samples. if (ppt.num_samples() == 0) { continue; } List<Invariant> invs = PrintInvariants.sort_invariant_list(ppt.invariants_vector()); List<Invariant> filtered_invs = Daikon.filter_invs(invs); // The dkconfig_quiet printing is used for creating diffs between // DaikonSimple // and Daikon's output. The second kind of printing is used for // debugging. Since the names of the program points are the same for both // Daikon and DaikonSimple, diffing the two output will result in // only differences in the invariants, but we can not see at which program // points these differing invariants appear. Using the second kind of // printing, // Daikon's output does not have the '+' in the program point name, so in // addition // to the invariants showing up in the diff, we will also see the program // point // names. if (Daikon.dkconfig_quiet) { System.out.println("===================================================="); System.out.println(ppt.name()); } else { System.out.println("===================================================+"); System.out.println(ppt.name() + " +"); } // Sometimes the program points actually differ in number of // samples seen due to differences in how Daikon and DaikonSimple // see the variable hierarchy. System.out.println(ppt.num_samples()); for (Invariant inv : filtered_invs) { System.out.println(inv.getClass()); System.out.println(inv); } } }
/** * オブジェクトをファイルに書き出す。 * * @param path - データファイルのパス * @param Object - 書き出すオブジェクト * @throws MineException データの書き込みに失敗した。 */ public static void write(String path, Object obj) throws MineException { try (XMLEncoder out = new XMLEncoder(FileIO.getOutputStream(path))) { out.writeObject(obj); } }
// This is where all the action happens. If an action is performed (button press for example), it // goes through this method // that takes an ActionEvent, which is created at the time of the action. public void actionPerformed(ActionEvent e) { // Try to cast the ActionEvent source as JToggleButton (if successful, the button is a ballot // choice) try { JToggleButton theButton = (JToggleButton) e.getSource(); String buttonText = theButton.getText(); if (theButton.isSelected()) { theButton.setForeground(Color.RED); switchButton = true; switchButtonText = buttonText; updateButtons( buttonText); // switches this button's respective vote position to 1 (true), meaning it // is selected } else if (!theButton.isSelected()) { theButton.setForeground(Color.BLACK); unvoteButton = true; unvoteButtonText = buttonText; } // If the program can't cast the source to a JToggleButton, cast it as a JButton, which is // 100% what the source will be at this point. // This button will be one of two things: the login button or the cast vote button. } catch (Exception exception) { JButton theButton = (JButton) e.getSource(); String buttonText = theButton.getText(); // If the user hits the Login button, check if the ID is valid. // If the ID is not valid, don't let them vote. However, if it is valid, disable login and // enable everything else. if (buttonText.equals("Login")) { String voterID = JOptionPane.showInputDialog(theButton, "Enter your voter ID: ", "Login", 3); FileIO votersFile = new FileIO("voters.txt"); ArrayList<Voter> voters = votersFile.createVoters(); if (votersFile.checkValidID(voterID)) { Voter theVoter = voters.get(votersFile.getVoterIndex(voterID)); if (theVoter.getVotedStatus().equals("false")) { setVoterID(voterID); } else { JOptionPane.showMessageDialog( theButton, "You already voted " + theVoter.getVoterName() + "!"); } } else { JOptionPane.showMessageDialog(theButton, "Invalid ID!", "Error", 0); } // If the user hits the cast vote button, update the respective ballot files and disable // every button except // for the login button. } else if (buttonText.equals("Cast vote")) { int confirm = JOptionPane.showConfirmDialog(theButton, "Are you sure?"); FileIO votersFile = new FileIO("voters.txt"); ArrayList<Voter> voters = votersFile.createVoters(); Voter theVoter = voters.get(votersFile.getVoterIndex(voterID)); if (confirm == 0) { JOptionPane.showMessageDialog(theButton, "Thanks for voting!"); updateBallots(); votersFile.updateVoterFile(theVoter.getVoterID()); setVoterID("-1"); votersFile.initializeVoters(); } } } }
private static void checkInvariants() throws IOException { // Read the invariant file PptMap ppts = FileIO.read_serialized_pptmap(inv_file, true); // Yoav: make sure we have unique invariants InvariantFilters fi = InvariantFilters.defaultFilters(); // Set<String> allInvariantsStr = new HashSet<String>(); Set<Invariant> allInvariants = new HashSet<Invariant>(); for (PptTopLevel ppt : ppts.all_ppts()) for (Iterator<PptSlice> i = ppt.views_iterator(); i.hasNext(); ) { PptSlice slice = i.next(); for (Invariant inv : slice.invs) { if (doConf && inv.getConfidence() < Invariant.dkconfig_confidence_limit) { // System.out.printf ("inv ignored (conf): %s:%s\n", inv.ppt.name(), // inv.format()); continue; } if (doFilter && fi.shouldKeep(inv) == null) { // System.out.printf ("inv ignored (filter): %s:%s\n", // inv.ppt.name(), inv.format()); continue; } activeInvariants.add(inv); // String n = invariant2str(ppt, inv); // if (!allInvariants.contains(inv) && allInvariantsStr.contains(n)) throw new // Daikon.TerminationMessage("Two invariants have the same ppt.name+inv.rep:"+n); allInvariants.add(inv); // allInvariantsStr.add(n); } } // Read and process the data trace files FileIO.Processor processor = new InvariantCheckProcessor(); Daikon.FileIOProgress progress = new Daikon.FileIOProgress(); progress.start(); progress.clear(); FileIO.read_data_trace_files(dtrace_files, ppts, processor, false); progress.shouldStop = true; System.out.println(); System.out.printf( "%s: %,d errors found in %,d samples (%s)\n", inv_file, error_cnt, sample_cnt, toPercentage(error_cnt, sample_cnt)); int failedCount = failedInvariants.size(); int testedCount = testedInvariants.size(); String percent = toPercentage(failedCount, testedCount); System.out.println( inv_file + ": " + failedCount + " false positives, out of " + testedCount + ", which is " + percent + "."); if (false) { for (Invariant inv : failedInvariants) { System.out.printf("+%s:%s\n", inv.ppt.name(), inv.format()); } } }
private static void take_photo_new( CameraDevice cameraDevice, ImageView imageviewer_new_picture, String file_name) { Context context_holder = ApplicationContextProvider.getContext(); CameraManager manager = (CameraManager) context_holder.getSystemService(Context.CAMERA_SERVICE); HandlerThread mBackgroundThread; mBackgroundThread = new HandlerThread("Camera Background"); mBackgroundThread.start(); final Handler mBackgroundHandler = new Handler(mBackgroundThread.getLooper()); try { CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId()); Size[] jpegSizes = null; if (characteristics != null) { jpegSizes = characteristics .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) .getOutputSizes(ImageFormat.JPEG); } int width = 640; int height = 480; if (jpegSizes != null && 0 < jpegSizes.length) { width = jpegSizes[0].getWidth(); height = jpegSizes[0].getHeight(); } ImageReader reader = ImageReader.newInstance((width + 1), (height + 1), ImageFormat.JPEG, 1); final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE); captureBuilder.addTarget(reader.getSurface()); captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO); captureBuilder.set( CaptureRequest.COLOR_CORRECTION_MODE, CameraMetadata.COLOR_CORRECTION_MODE_FAST); captureBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_OFF); captureBuilder.set(CaptureRequest.JPEG_THUMBNAIL_QUALITY, null); List<Surface> outputSurfaces = new ArrayList<Surface>(2); outputSurfaces.add(reader.getSurface()); captureBuilder.build(); cameraDevice.createCaptureSession( outputSurfaces, new CameraCaptureSession.StateCallback() { @Override public void onConfigured(CameraCaptureSession session) { try { session.capture(captureBuilder.build(), null, null); } catch (CameraAccessException e) { e.printStackTrace(); } } @Override public void onConfigureFailed(CameraCaptureSession session) {} }, mBackgroundHandler); Log.e("camera", "take picture... sleep"); try { Thread.sleep(2000); } catch (InterruptedException e) { } byte[] bytes; Image image = null; try { // Log.e("camera", " reader"+reader.getHeight()); image = reader.acquireLatestImage(); image.getFormat(); ByteBuffer buffer = image.getPlanes()[0].getBuffer(); bytes = new byte[buffer.capacity()]; buffer.get(bytes); } finally { if (image != null) { image.close(); } } // String file_name = "curent_photo"; FileOutputStream out_put_stream = null; try { out_put_stream = ApplicationContextProvider.getContext() .openFileOutput( file_name + ".jpg", ApplicationContextProvider.getContext().MODE_PRIVATE); } catch (IOException exception) { exception.printStackTrace(); } try { out_put_stream.write(bytes); Log.e("camera", "saved picture! " + file_name); if (imageviewer_new_picture != null) { ImageView cap_picture = (ImageView) imageviewer_new_picture; Bitmap bitmap_found = FileIO.loadBMPPrivate(file_name, Bitmap.CompressFormat.JPEG); cap_picture.setImageBitmap(bitmap_found); } } catch (IOException e) { e.printStackTrace(); } finally { if (null != out_put_stream) { try { out_put_stream.close(); } catch (IOException e) { e.printStackTrace(); } } closeCamera(cameraDevice); } } catch (CameraAccessException e) { e.printStackTrace(); } }