List of usage examples for java.util Vector Vector
public Vector()
From source file:EmbedJTableSWTNoFlicker.java
public static void main(String[] args) { final Display display = new Display(); final Shell shell = new Shell(display); shell.setLayout(new FillLayout()); Composite composite = new Composite(shell, SWT.NO_BACKGROUND | SWT.EMBEDDED); /*/* ww w .ja v a 2s . co m*/ * Set a Windows specific AWT property that prevents heavyweight components * from erasing their background. Note that this is a global property and * cannot be scoped. It might not be suitable for your application. */ try { System.setProperty("sun.awt.noerasebackground", "true"); } catch (NoSuchMethodError error) { } /* Create and setting up frame */ Frame frame = SWT_AWT.new_Frame(composite); Panel panel = new Panel(new BorderLayout()) { public void update(java.awt.Graphics g) { /* Do not erase the background */ paint(g); } }; frame.add(panel); JRootPane root = new JRootPane(); panel.add(root); java.awt.Container contentPane = root.getContentPane(); /* Creating components */ int nrows = 1000, ncolumns = 10; Vector rows = new Vector(); for (int i = 0; i < nrows; i++) { Vector row = new Vector(); for (int j = 0; j < ncolumns; j++) { row.addElement("Item " + i + "-" + j); } rows.addElement(row); } Vector columns = new Vector(); for (int i = 0; i < ncolumns; i++) { columns.addElement("Column " + i); } JTable table = new JTable(rows, columns); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.createDefaultColumnsFromModel(); JScrollPane scrollPane = new JScrollPane(table); contentPane.setLayout(new BorderLayout()); contentPane.add(scrollPane); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }
From source file:net.java.sen.tools.MkSenDic.java
/** * Build sen dictionary.//w w w . j a v a 2s .c om * * @param args * custom dictionary files. see dic/build.xml. */ public static void main(String args[]) { ResourceBundle rb = ResourceBundle.getBundle("dictionary"); DictionaryMaker dm1 = new DictionaryMaker(); DictionaryMaker dm2 = new DictionaryMaker(); DictionaryMaker dm3 = new DictionaryMaker(); // 1st field information of connect file. Vector rule1 = new Vector(); // 2nd field information of connect file. Vector rule2 = new Vector(); // 3rd field information of connect file. Vector rule3 = new Vector(); // 4th field information of connect file. // this field shows cost of morpheme connection // [size3*(x3*size2+x2)+x1] // [size3*(Attr1*size2+Attr2)+Attl] short score[] = new short[20131]; long start = System.currentTimeMillis(); // ///////////////////////////////////////// // // Step1. Loading connetion file. // log.info("(1/7): reading connection matrix ... "); try { log.info("connection file = " + rb.getString("text_connection_file")); log.info("charset = " + rb.getString("dic.charset")); CSVParser csvparser = new CSVParser(new FileInputStream(rb.getString("text_connection_file")), rb.getString("dic.charset")); String t[]; int line = 0; while ((t = csvparser.nextTokens()) != null) { if (t.length < 4) { log.warn("invalid line in " + rb.getString("text_connection_file") + ":" + line); log.warn(rb.getString("text_connection_file") + "may be broken."); break; } dm1.add(t[0]); rule1.add(t[0]); dm2.add(t[1]); rule2.add(t[1]); dm3.add(t[2]); rule3.add(t[2]); if (line == score.length) { score = resize(score); } score[line++] = (short) Integer.parseInt(t[3]); } // ///////////////////////////////////////// // // Step2. Building internal dictionary // log.info("(2/7): building type dictionary ... "); dm1.build(); dm2.build(); dm3.build(); // if you want check specified morpheme, you uncomment and modify // following line: /* * System.out.print("22="); dm3.getById(22); * System.out.print("368="); dm3.getById(368); * * System.out.println(dm3.getDicId("?????*,*,*,*,?")); * DictionaryMaker.debug = true; * System.out.println(dm3.getDicId("?????*,*,*,*,?")); * System.out.println(dm3.getDicIdNoCache("?????*,*,*,*,?")); */ } catch (IOException e) { e.printStackTrace(); System.exit(0); } // ------------------------------------------------- int size1 = dm1.size(); int size2 = dm2.size(); int size3 = dm3.size(); int ruleSize = rule1.size(); short matrix[] = new short[size1 * size2 * size3]; short default_cost = (short) Integer.parseInt(rb.getString("default_connection_cost")); // ///////////////////////////////////////// // // Step3. Writing Connection Matrix // log.info("(3/7): writing conection matrix (" + size1 + " x " + size2 + " x " + size3 + " = " + size1 * size2 * size3 + ") ..."); for (int i = 0; i < (int) (size1 * size2 * size3); i++) matrix[i] = default_cost; for (int i = 0; i < ruleSize; i++) { Vector r1 = dm1.getRuleIdList((String) rule1.get(i)); Vector r2 = dm2.getRuleIdList((String) rule2.get(i)); Vector r3 = dm3.getRuleIdList((String) rule3.get(i)); for (Iterator i1 = r1.iterator(); i1.hasNext();) { int ii1 = ((Integer) i1.next()).intValue(); for (Iterator i2 = r2.iterator(); i2.hasNext();) { int ii2 = ((Integer) i2.next()).intValue(); for (Iterator i3 = r3.iterator(); i3.hasNext();) { int ii3 = ((Integer) i3.next()).intValue(); int pos = size3 * (size2 * ii1 + ii2) + ii3; matrix[pos] = score[i]; } } } } try { DataOutputStream out = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(rb.getString("matrix_file")))); out.writeShort(size1); out.writeShort(size2); out.writeShort(size3); for (int i1 = 0; i1 < size1; i1++) for (int i2 = 0; i2 < size2; i2++) for (int i3 = 0; i3 < size3; i3++) { out.writeShort(matrix[size3 * (size2 * i1 + i2) + i3]); // if (matrix[size3 * (size2 * i1 + i2) + i3] != // default_cost) { // } } out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(0); } matrix = null; score = null; // ------------------------------------------------- int pos_start = Integer.parseInt(rb.getString("pos_start")); int pos_size = Integer.parseInt(rb.getString("pos_size")); int di = 0; int offset = 0; ArrayList dicList = new ArrayList(); // ///////////////////////////////////////// // // Step4. Reading Morpheme Information // log.info("(4/7): reading morpheme information ... "); String t = null; String[] csv = null; try { // writer for feature file. BufferedWriter bw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(rb.getString("pos_file")), rb.getString("sen.charset"))); log.info("load dic: " + rb.getString("text_dic_file")); BufferedReader dicStream = null; int custom_dic = -1; if (args.length == 0) { dicStream = new BufferedReader(new InputStreamReader( new FileInputStream(rb.getString("text_dic_file")), rb.getString("dic.charset"))); } else { custom_dic = 0; dicStream = new BufferedReader( new InputStreamReader(new FileInputStream(args[custom_dic]), rb.getString("dic.charset"))); } int line = 0; CSVData key_b = new CSVData(); CSVData pos_b = new CSVData(); while (true) { t = dicStream.readLine(); if (t == null) { dicStream.close(); custom_dic++; if (args.length == custom_dic) { break; } else { // read custum dictionary log.info("load dic: " + "args[custum_dic]"); dicStream = new BufferedReader(new InputStreamReader(new FileInputStream(args[custom_dic]), rb.getString("dic.charset"))); } continue; } CSVParser parser = new CSVParser(t); csv = parser.nextTokens(); if (csv.length < (pos_size + pos_start)) { throw new RuntimeException("format error:" + t); } key_b.clear(); pos_b.clear(); for (int i = pos_start; i < (pos_start + pos_size - 1); i++) { key_b.append(csv[i]); pos_b.append(csv[i]); } key_b.append(csv[pos_start + pos_size - 1]); pos_b.append(csv[pos_start + pos_size - 1]); for (int i = pos_start + pos_size; i < (csv.length - 1); i++) { pos_b.append(csv[i]); } pos_b.append(csv[csv.length - 1]); CToken token = new CToken(); token.rcAttr2 = (short) dm1.getDicId(key_b.toString()); token.rcAttr1 = (short) dm2.getDicId(key_b.toString()); token.lcAttr = (short) dm3.getDicId(key_b.toString()); token.posid = 0; token.posID = offset; token.length = (short) csv[0].length(); token.cost = (short) Integer.parseInt(csv[1]); dicList.add(new PairObject(csv[0], token)); byte b[] = pos_b.toString().getBytes(rb.getString("sen.charset")); offset += (b.length + 1); String pos_b_str = pos_b.toString(); bw.write(pos_b_str, 0, pos_b_str.length()); // bw.write(b, 0, b.length); bw.write(0); if (++di % 50000 == 0) log.info("" + di + "... "); } bw.close(); // ----end of writing feature.cha ---- } catch (Exception e) { log.error("Error: " + t); e.printStackTrace(); System.exit(1); } rule1 = null; rule2 = null; rule3 = null; // ///////////////////////////////////////// // // Step5. Sort lexs and write to file // log.info("(5/7): sorting lex... "); int value[] = new int[dicList.size()]; char key[][] = new char[dicList.size()][]; int spos = 0; int dsize = 0; int bsize = 0; String prev = ""; Collections.sort(dicList); // ///////////////////////////////////////// // // Step6. Writing Token Information // log.info("(6/7): writing token... "); try { // writer for token file. DataOutputStream out = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(rb.getString("token_file")))); // writing 'bos' and 'eos' and 'unknown' token. CToken token = new CToken(); token.rcAttr2 = (short) dm1.getDicId(rb.getString("bos_pos")); token.rcAttr1 = (short) dm2.getDicId(rb.getString("bos_pos")); token.lcAttr = (short) dm3.getDicId(rb.getString("bos_pos")); token.write(out); token.rcAttr2 = (short) dm1.getDicId(rb.getString("eos_pos")); token.rcAttr1 = (short) dm2.getDicId(rb.getString("eos_pos")); token.lcAttr = (short) dm3.getDicId(rb.getString("eos_pos")); token.write(out); token.rcAttr2 = (short) dm1.getDicId(rb.getString("unknown_pos")); token.rcAttr1 = (short) dm2.getDicId(rb.getString("unknown_pos")); token.lcAttr = (short) dm3.getDicId(rb.getString("unknown_pos")); token.posID = -1; token.write(out); log.info("key size = " + key.length); for (int i = 0; i < key.length; i++) { String k = (String) ((PairObject) dicList.get(i)).key; if (!prev.equals(k) && i != 0) { key[dsize] = ((String) ((PairObject) dicList.get(spos)).key).toCharArray(); value[dsize] = bsize + (spos << 8); dsize++; bsize = 1; spos = i; } else { bsize++; } prev = (String) ((PairObject) dicList.get(i)).key; ((CToken) (((PairObject) dicList.get(i)).value)).write(out); } out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } key[dsize] = ((String) ((PairObject) dicList.get(spos)).key).toCharArray(); value[dsize] = bsize + (spos << 8); dsize++; dm1 = null; dm2 = null; dm3 = null; dicList = null; // ///////////////////////////////////////// // // Step7. Build Double Array // log.info("(7/7): building Double-Array (size = " + dsize + ") ..."); DoubleArrayTrie da = new DoubleArrayTrie(); da.build(key, null, value, dsize); try { da.save(rb.getString("double_array_file")); } catch (Exception e) { e.printStackTrace(); } log.info("total time = " + (System.currentTimeMillis() - start) / 1000 + "[ms]"); }
From source file:gentracklets.Propagate.java
public static void main(String[] args) throws OrekitException { // load the data files File data = new File("/home/zittersteijn/Documents/java/libraries/orekit-data.zip"); DataProvidersManager DM = DataProvidersManager.getInstance(); ZipJarCrawler crawler = new ZipJarCrawler(data); DM.clearProviders();/*ww w . j a v a 2 s . c om*/ DM.addProvider(crawler); // Read in TLE elements File tleFile = new File("/home/zittersteijn/Documents/TLEs/ASTRA20151207.tle"); FileReader TLEfr; Vector<TLE> tles = new Vector<>(); tles.setSize(30); try { // read and save TLEs to a vector TLEfr = new FileReader("/home/zittersteijn/Documents/TLEs/ASTRA20151207.tle"); BufferedReader readTLE = new BufferedReader(TLEfr); Scanner s = new Scanner(tleFile); String line1, line2; TLE2 tle = new TLE2(); int nrOfObj = 4; for (int ii = 1; ii < nrOfObj + 1; ii++) { System.out.println(ii); line1 = s.nextLine(); line2 = s.nextLine(); if (TLE.isFormatOK(line1, line2)) { tles.setElementAt(new TLE(line1, line2), ii); System.out.println(tles.get(ii).toString()); } else { System.out.println("format problem"); } } readTLE.close(); // define a groundstation Frame inertialFrame = FramesFactory.getEME2000(); TimeScale utc = TimeScalesFactory.getUTC(); double longitude = FastMath.toRadians(7.465); double latitude = FastMath.toRadians(46.87); double altitude = 950.; GeodeticPoint station = new GeodeticPoint(latitude, longitude, altitude); Frame earthFrame = FramesFactory.getITRF(IERSConventions.IERS_2010, true); BodyShape earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS, Constants.WGS84_EARTH_FLATTENING, earthFrame); TopocentricFrame staF = new TopocentricFrame(earth, station, "station"); Vector<Orbit> eles = new Vector<>(); eles.setSize(tles.size()); for (int ii = 1; ii < nrOfObj + 1; ii++) { double a = FastMath.pow(Constants.WGS84_EARTH_MU / FastMath.pow(tles.get(ii).getMeanMotion(), 2), (1.0 / 3)); // convert them to orbits Orbit kep = new KeplerianOrbit(a, tles.get(ii).getE(), tles.get(ii).getI(), tles.get(ii).getPerigeeArgument(), tles.get(ii).getRaan(), tles.get(ii).getMeanAnomaly(), PositionAngle.MEAN, inertialFrame, tles.get(ii).getDate(), Constants.WGS84_EARTH_MU); eles.setElementAt(kep, ii); // set up propagators KeplerianPropagator kepler = new KeplerianPropagator(eles.get(ii)); System.out.println("a: " + a); // Initial state definition double mass = 1000.0; SpacecraftState initialState = new SpacecraftState(kep, mass); // Adaptive step integrator // with a minimum step of 0.001 and a maximum step of 1000 double minStep = 0.001; double maxstep = 1000.0; double positionTolerance = 10.0; OrbitType propagationType = OrbitType.KEPLERIAN; double[][] tolerances = NumericalPropagator.tolerances(positionTolerance, kep, propagationType); AdaptiveStepsizeIntegrator integrator = new DormandPrince853Integrator(minStep, maxstep, tolerances[0], tolerances[1]); NumericalPropagator propagator = new NumericalPropagator(integrator); propagator.setOrbitType(propagationType); // set up and add force models double AMR = 4.0; double crossSection = mass * AMR; double Cd = 0.01; double Cr = 0.5; double Co = 0.8; NormalizedSphericalHarmonicsProvider provider = GravityFieldFactory.getNormalizedProvider(4, 4); ForceModel holmesFeatherstone = new HolmesFeatherstoneAttractionModel( FramesFactory.getITRF(IERSConventions.IERS_2010, true), provider); SphericalSpacecraft ssc = new SphericalSpacecraft(crossSection, Cd, Cr, Co); PVCoordinatesProvider sun = CelestialBodyFactory.getSun(); SolarRadiationPressure srp = new SolarRadiationPressure(sun, Constants.WGS84_EARTH_EQUATORIAL_RADIUS, ssc); // propagator.addForceModel(srp); // propagator.addForceModel(holmesFeatherstone); propagator.setInitialState(initialState); // propagate the orbits with steps size and tracklet lenght at several epochs (tracklets) Vector<AbsoluteDate> startDates = new Vector<>(); startDates.setSize(1); startDates.setElementAt(new AbsoluteDate(2016, 1, 26, 20, 00, 00, utc), 0); // set the step size [s] and total length double tstep = 100; double ld = 3; double ls = FastMath.floor(ld * (24 * 60 * 60) / tstep); System.out.println(ls); SpacecraftState currentStateKep = kepler.propagate(startDates.get(0)); SpacecraftState currentStatePer = propagator.propagate(startDates.get(0)); for (int tt = 0; tt < startDates.size(); tt++) { // set up output file String app = tles.get(ii).getSatelliteNumber() + "_" + startDates.get(tt) + ".txt"; // with formatted output File file1 = new File("/home/zittersteijn/Documents/propagate/keplerian/MEO/" + app); File file2 = new File("/home/zittersteijn/Documents/propagate/perturbed/MEO/" + app); file1.createNewFile(); file2.createNewFile(); Formatter fmt1 = new Formatter(file1); Formatter fmt2 = new Formatter(file2); for (int kk = 0; kk < (int) ls; kk++) { AbsoluteDate propDate = startDates.get(tt).shiftedBy(tstep * kk); currentStateKep = kepler.propagate(propDate); currentStatePer = propagator.propagate(propDate); System.out.println(currentStateKep.getPVCoordinates().getPosition() + "\t" + currentStateKep.getDate()); // convert to RADEC coordinates double[] radecKep = conversions.geo2radec(currentStateKep.getPVCoordinates(), staF, inertialFrame, propDate); double[] radecPer = conversions.geo2radec(currentStatePer.getPVCoordinates(), staF, inertialFrame, propDate); // write the orbit to seperate files with the RA, DEC, epoch and fence given AbsoluteDate year = new AbsoluteDate(YEAR, utc); fmt1.format("%.12f %.12f %.12f %d%n", radecKep[0], radecKep[2], (currentStateKep.getDate().durationFrom(year) / (24 * 3600)), (tt + 1)); fmt2.format("%.12f %.12f %.12f %d%n", radecPer[0], radecPer[2], (currentStateKep.getDate().durationFrom(year) / (24 * 3600)), (tt + 1)); } fmt1.flush(); fmt1.close(); fmt2.flush(); fmt2.close(); } double[] radecKep = conversions.geo2radec(currentStateKep.getPVCoordinates(), staF, inertialFrame, new AbsoluteDate(startDates.get(0), ls * tstep)); double[] radecPer = conversions.geo2radec(currentStatePer.getPVCoordinates(), staF, inertialFrame, new AbsoluteDate(startDates.get(0), ls * tstep)); double sig0 = 1.0 / 3600.0 / 180.0 * FastMath.PI; double dRA = radecKep[0] - radecPer[0] / (sig0 * sig0); double dDEC = radecKep[2] - radecPer[2] / (sig0 * sig0); System.out.println(dRA + "\t" + dDEC); } } catch (FileNotFoundException ex) { Logger.getLogger(GenTracklets.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException iox) { Logger.getLogger(GenTracklets.class.getName()).log(Level.SEVERE, null, iox); } }
From source file:gentracklets.GenTracklets.java
public static void main(String[] args) throws OrekitException { // load the data files File data = new File("/home/zittersteijn/Documents/java/libraries/orekit-data.zip"); DataProvidersManager DM = DataProvidersManager.getInstance(); ZipJarCrawler crawler = new ZipJarCrawler(data); DM.clearProviders();//from w w w. ja v a 2 s . c o m DM.addProvider(crawler); // Read in TLE elements File tleFile = new File("/home/zittersteijn/Documents/TLEs/ASTRA20151207.tle"); FileReader TLEfr; Vector<TLE> tles = new Vector<>(); tles.setSize(30); try { // read and save TLEs to a vector TLEfr = new FileReader("/home/zittersteijn/Documents/TLEs/ASTRA20151207.tle"); BufferedReader readTLE = new BufferedReader(TLEfr); Scanner s = new Scanner(tleFile); String line1, line2; TLE2 tle = new TLE2(); int nrOfObj = 4; for (int ii = 1; ii < nrOfObj + 1; ii++) { System.out.println(ii); line1 = s.nextLine(); line2 = s.nextLine(); if (TLE.isFormatOK(line1, line2)) { tles.setElementAt(new TLE(line1, line2), ii); System.out.println(tles.get(ii).toString()); } else { System.out.println("format problem"); } } readTLE.close(); // define a groundstation Frame inertialFrame = FramesFactory.getEME2000(); TimeScale utc = TimeScalesFactory.getUTC(); double longitude = FastMath.toRadians(7.465); double latitude = FastMath.toRadians(46.87); double altitude = 950.; GeodeticPoint station = new GeodeticPoint(latitude, longitude, altitude); Frame earthFrame = FramesFactory.getITRF(IERSConventions.IERS_2010, true); BodyShape earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS, Constants.WGS84_EARTH_FLATTENING, earthFrame); TopocentricFrame staF = new TopocentricFrame(earth, station, "station"); Vector<Orbit> eles = new Vector<>(); eles.setSize(tles.size()); for (int ii = 1; ii < nrOfObj + 1; ii++) { double a = FastMath.pow(Constants.WGS84_EARTH_MU / FastMath.pow(tles.get(ii).getMeanMotion(), 2), (1.0 / 3)); // convert them to orbits Orbit kep = new KeplerianOrbit(a, tles.get(ii).getE(), tles.get(ii).getI(), tles.get(ii).getPerigeeArgument(), tles.get(ii).getRaan(), tles.get(ii).getMeanAnomaly(), PositionAngle.MEAN, inertialFrame, tles.get(ii).getDate(), Constants.WGS84_EARTH_MU); eles.setElementAt(kep, ii); // set up propagators KeplerianPropagator kepler = new KeplerianPropagator(eles.get(ii)); System.out.println("a: " + a); // Initial state definition double mass = 1000.0; SpacecraftState initialState = new SpacecraftState(kep, mass); // Adaptive step integrator // with a minimum step of 0.001 and a maximum step of 1000 double minStep = 0.001; double maxstep = 1000.0; double positionTolerance = 10.0; OrbitType propagationType = OrbitType.KEPLERIAN; double[][] tolerances = NumericalPropagator.tolerances(positionTolerance, kep, propagationType); AdaptiveStepsizeIntegrator integrator = new DormandPrince853Integrator(minStep, maxstep, tolerances[0], tolerances[1]); NumericalPropagator propagator = new NumericalPropagator(integrator); propagator.setOrbitType(propagationType); // set up and add force models double AMR = 0.4; double crossSection = mass * AMR; double Cd = 0.01; double Cr = 0.5; double Co = 0.8; NormalizedSphericalHarmonicsProvider provider = GravityFieldFactory.getNormalizedProvider(4, 4); ForceModel holmesFeatherstone = new HolmesFeatherstoneAttractionModel( FramesFactory.getITRF(IERSConventions.IERS_2010, true), provider); SphericalSpacecraft ssc = new SphericalSpacecraft(crossSection, Cd, Cr, Co); PVCoordinatesProvider sun = CelestialBodyFactory.getSun(); SolarRadiationPressure srp = new SolarRadiationPressure(sun, Constants.WGS84_EARTH_EQUATORIAL_RADIUS, ssc); propagator.addForceModel(srp); propagator.addForceModel(holmesFeatherstone); propagator.setInitialState(initialState); // propagate the orbits with steps size and tracklet lenght at several epochs (tracklets) Vector<AbsoluteDate> startDates = new Vector<>(); startDates.setSize(3); startDates.setElementAt(new AbsoluteDate(2015, 12, 8, 20, 00, 00, utc), 0); startDates.setElementAt(new AbsoluteDate(2015, 12, 9, 21, 00, 00, utc), 1); startDates.setElementAt(new AbsoluteDate(2015, 12, 10, 22, 00, 00, utc), 2); double tstep = 30; int l = 7; for (int tt = 0; tt < startDates.size(); tt++) { // set up output file String app = "S_" + tles.get(ii).getSatelliteNumber() + "_" + startDates.get(tt) + ".txt"; // FileWriter trackletsOutKep = new FileWriter("/home/zittersteijn/Documents/tracklets/simulated/keplerian/ASTRA/dt1h/AMR040/" + app); // FileWriter trackletsOutPer = new FileWriter("/home/zittersteijn/Documents/tracklets/simulated/perturbed/ASTRA/dt1h/AMR040/" + app); // BufferedWriter trackletsKepBW = new BufferedWriter(trackletsOutKep); // BufferedWriter trackletsPerBW = new BufferedWriter(trackletsOutPer); // with formatted output File file1 = new File( "/home/zittersteijn/Documents/tracklets/simulated/keplerian/ASTRA/dt1d/AMR040/" + app); File file2 = new File( "/home/zittersteijn/Documents/tracklets/simulated/perturbed/ASTRA/dt1d/AMR040/" + app); file1.createNewFile(); file2.createNewFile(); Formatter fmt1 = new Formatter(file1); Formatter fmt2 = new Formatter(file2); for (int kk = 0; kk < l; kk++) { AbsoluteDate propDate = startDates.get(tt).shiftedBy(tstep * kk); SpacecraftState currentStateKep = kepler.propagate(propDate); SpacecraftState currentStatePer = propagator.propagate(propDate); System.out.println(currentStateKep.getPVCoordinates().getPosition() + "\t" + currentStateKep.getDate()); // convert to RADEC coordinates double[] radecKep = conversions.geo2radec(currentStateKep.getPVCoordinates(), staF, inertialFrame, propDate); double[] radecPer = conversions.geo2radec(currentStatePer.getPVCoordinates(), staF, inertialFrame, propDate); // write the tracklets to seperate files with the RA, DEC, epoch and fence given // System.out.println(tles.get(kk).getSatelliteNumber() + "\t" + radec[0] / (2 * FastMath.PI) * 180 + "\t" + currentState.getDate()); AbsoluteDate year = new AbsoluteDate(YEAR, utc); fmt1.format("%.12f %.12f %.12f %d%n", radecKep[0], radecKep[2], (currentStateKep.getDate().durationFrom(year) / (24 * 3600)), (tt + 1)); fmt2.format("%.12f %.12f %.12f %d%n", radecPer[0], radecPer[2], (currentStateKep.getDate().durationFrom(year) / (24 * 3600)), (tt + 1)); } fmt1.flush(); fmt1.close(); fmt2.flush(); fmt2.close(); } } } catch (FileNotFoundException ex) { Logger.getLogger(GenTracklets.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException iox) { Logger.getLogger(GenTracklets.class.getName()).log(Level.SEVERE, null, iox); } }
From source file:it.acubelab.smaph.learn.GenerateModel.java
public static void main(String[] args) throws Exception { Locale.setDefault(Locale.US); String freebKey = ""; SmaphConfig.setConfigFile("smaph-config.xml"); String bingKey = SmaphConfig.getDefaultBingKey(); WikipediaApiInterface wikiApi = new WikipediaApiInterface("wid.cache", "redirect.cache"); FreebaseApi freebApi = new FreebaseApi(freebKey, "freeb.cache"); double[][] paramsToTest = new double[][] { /*/*from w ww .ja va2 s .co m*/ * {0.035, 0.5 }, {0.035, 1 }, {0.035, 4 }, {0.035, 8 }, {0.035, 10 }, * {0.035, 16 }, {0.714, .5 }, {0.714, 1 }, {0.714, 4 }, {0.714, 8 }, * {0.714, 10 }, {0.714, 16 }, {0.9, .5 }, {0.9, 1 }, {0.9, 4 }, {0.9, 8 * }, {0.9, 10 }, {0.9, 16 }, * * { 1.0/15.0, 1 }, { 1.0/27.0, 1 }, */ /* * {0.01, 1}, {0.01, 5}, {0.01, 10}, {0.03, 1}, {0.03, 5}, {0.03, 10}, * {0.044, 1}, {0.044, 5}, {0.044, 10}, {0.06, 1}, {0.06, 5}, {0.06, * 10}, */ { 0.03, 5 }, }; double[][] weightsToTest = new double[][] { /* * { 3, 4 } */ { 3.8, 3 }, { 3.8, 4 }, { 3.8, 5 }, { 3.8, 6 }, { 3.8, 7 }, { 3.8, 8 }, { 3.8, 9 }, { 3.8, 10 }, }; Integer[][] featuresSetsToTest = new Integer[][] { //{ 1, 2, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 }, { 1, 2, 3, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 }, /* * { 1, 2, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}, */ }; // < -------------------------------------- MIND THIS int wikiSearckTopK = 10; // <--------------------------- String filePrefix = "_ANW";// <--------------------------- WikipediaToFreebase wikiToFreebase = new WikipediaToFreebase("mapdb"); List<ModelConfigurationResult> mcrs = new Vector<>(); for (double editDistanceThr = 0.7; editDistanceThr <= 0.7; editDistanceThr += 0.7) { SmaphAnnotator bingAnnotator = GenerateTrainingAndTest.getDefaultBingAnnotator(wikiApi, wikiToFreebase, editDistanceThr, wikiSearckTopK, bingKey); WATAnnotator.setCache("wikisense.cache"); SmaphAnnotator.setCache(SmaphConfig.getDefaultBingCache()); BinaryExampleGatherer trainEntityFilterGatherer = new BinaryExampleGatherer(); BinaryExampleGatherer testEntityFilterGatherer = new BinaryExampleGatherer(); GenerateTrainingAndTest.gatherExamplesTrainingAndDevel(bingAnnotator, trainEntityFilterGatherer, testEntityFilterGatherer, wikiApi, wikiToFreebase, freebApi); SmaphAnnotator.unSetCache(); BinaryExampleGatherer trainGatherer = trainEntityFilterGatherer; // ////////////// // <---------------------- BinaryExampleGatherer testGatherer = testEntityFilterGatherer; // ////////////// // <---------------------- int count = 0; for (Integer[] ftrToTestArray : featuresSetsToTest) { // double gamma = 1.0 / ftrToTestArray.length; // // <--------------------- MIND THIS // double C = 1;// < -------------------------------------- MIND // THIS for (double[] paramsToTestArray : paramsToTest) { double gamma = paramsToTestArray[0]; double C = paramsToTestArray[1]; for (double[] weightsPosNeg : weightsToTest) { double wPos = weightsPosNeg[0], wNeg = weightsPosNeg[1]; Vector<Integer> features = new Vector<>(Arrays.asList(ftrToTestArray)); Triple<svm_problem, double[], double[]> ftrsMinsMaxs = TuneModel .getScaledTrainProblem(features, trainGatherer); svm_problem trainProblem = ftrsMinsMaxs.getLeft(); String fileBase = getModelFileNameBaseEF(features.toArray(new Integer[0]), wPos, wNeg, editDistanceThr, gamma, C) + filePrefix; /* * String fileBase = getModelFileNameBaseEQF( * features.toArray(new Integer[0]), wPos, wNeg); */// < ------------------------- LibSvmUtils.dumpRanges(ftrsMinsMaxs.getMiddle(), ftrsMinsMaxs.getRight(), fileBase + ".range"); svm_model model = TuneModel.trainModel(wPos, wNeg, features, trainProblem, gamma, C); svm.svm_save_model(fileBase + ".model", model); MetricsResultSet metrics = TuneModel.ParameterTester.computeMetrics(model, TuneModel.getScaledTestProblems(features, testGatherer, ftrsMinsMaxs.getMiddle(), ftrsMinsMaxs.getRight())); int tp = metrics.getGlobalTp(); int fp = metrics.getGlobalFp(); int fn = metrics.getGlobalFn(); float microF1 = metrics.getMicroF1(); float macroF1 = metrics.getMacroF1(); float macroRec = metrics.getMacroRecall(); float macroPrec = metrics.getMacroPrecision(); int totVects = testGatherer.getExamplesCount(); mcrs.add(new ModelConfigurationResult(features, wPos, wNeg, editDistanceThr, tp, fp, fn, totVects - tp - fp - fn, microF1, macroF1, macroRec, macroPrec)); System.err.printf("Trained %d/%d models.%n", ++count, weightsToTest.length * featuresSetsToTest.length * paramsToTest.length); } } } } for (ModelConfigurationResult mcr : mcrs) System.out.printf("%.5f%%\t%.5f%%\t%.5f%%%n", mcr.getMacroPrecision() * 100, mcr.getMacroRecall() * 100, mcr.getMacroF1() * 100); for (double[] weightPosNeg : weightsToTest) System.out.printf("%.5f\t%.5f%n", weightPosNeg[0], weightPosNeg[1]); for (ModelConfigurationResult mcr : mcrs) System.out.println(mcr.getReadable()); for (double[] paramGammaC : paramsToTest) System.out.printf("%.5f\t%.5f%n", paramGammaC[0], paramGammaC[1]); WATAnnotator.flush(); }
From source file:com.pervasive07.MsgReader.java
public static void main(String[] args) throws Exception { String source = null;//ww w. j a va 2 s .co m Vector v = new Vector(); if (args.length > 0) { for (int i = 0; i < args.length; i++) { if (args[i].equals("-comm")) { source = args[++i]; } else { String className = args[i]; try { Class c = Class.forName(className); Object packet = c.newInstance(); Message msg = (Message) packet; if (msg.amType() < 0) { System.err.println(className + " does not have an AM type - ignored"); } else { v.addElement(msg); } } catch (Exception e) { System.err.println(e); } } } } else if (args.length != 0) { usage(); System.exit(1); } MsgReader mr = new MsgReader(source); Enumeration msgs = v.elements(); while (msgs.hasMoreElements()) { Message m = (Message) msgs.nextElement(); mr.addMsgType(m); } mr.start(); }
From source file:createSod.java
/** * @param args//from w w w .j a va2 s . com * @throws CMSException */ public static void main(String[] args) throws Exception { try { CommandLine options = verifyArgs(args); String privateKeyLocation = options.getOptionValue("privatekey"); String keyPassword = options.getOptionValue("keypass"); String certificate = options.getOptionValue("certificate"); String sodContent = options.getOptionValue("content"); String sod = ""; if (options.hasOption("out")) { sod = options.getOptionValue("out"); } // CHARGEMENT DU FICHIER PKCS#12 KeyStore ks = null; char[] password = null; Security.addProvider(new BouncyCastleProvider()); try { ks = KeyStore.getInstance("PKCS12"); // Password pour le fichier personnal_nyal.p12 password = keyPassword.toCharArray(); ks.load(new FileInputStream(privateKeyLocation), password); } catch (Exception e) { System.out.println("Erreur: fichier " + privateKeyLocation + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect"); return; } // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE X509Certificate cert = null; PrivateKey privatekey = null; PublicKey publickey = null; try { Enumeration en = ks.aliases(); String ALIAS = ""; Vector vectaliases = new Vector(); while (en.hasMoreElements()) vectaliases.add(en.nextElement()); String[] aliases = (String[]) (vectaliases.toArray(new String[0])); for (int i = 0; i < aliases.length; i++) if (ks.isKeyEntry(aliases[i])) { ALIAS = aliases[i]; break; } privatekey = (PrivateKey) ks.getKey(ALIAS, password); cert = (X509Certificate) ks.getCertificate(ALIAS); publickey = ks.getCertificate(ALIAS).getPublicKey(); } catch (Exception e) { e.printStackTrace(); return; } // Chargement du certificat partir du fichier InputStream inStream = new FileInputStream(certificate); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(inStream); inStream.close(); // Chargement du fichier qui va tre sign File file_to_sign = new File(sodContent); byte[] buffer = new byte[(int) file_to_sign.length()]; DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign)); in.readFully(buffer); in.close(); // Chargement des certificats qui seront stocks dans le fichier .p7 // Ici, seulement le certificat personnal_nyal.cer sera associ. // Par contre, la chane des certificats non. ArrayList certList = new ArrayList(); certList.add(cert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator signGen = new CMSSignedDataGenerator(); // privatekey correspond notre cl prive rcupre du fichier PKCS#12 // cert correspond au certificat publique personnal_nyal.cer // Le dernier argument est l'algorithme de hachage qui sera utilis signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1); signGen.addCertificatesAndCRLs(certs); CMSProcessable content = new CMSProcessableByteArray(buffer); // Generation du fichier CMS/PKCS#7 // L'argument deux permet de signifier si le document doit tre attach avec la signature // Valeur true: le fichier est attach (c'est le cas ici) // Valeur false: le fichier est dtach CMSSignedData signedData = signGen.generate(content, true, "BC"); byte[] signeddata = signedData.getEncoded(); // Ecriture du buffer dans un fichier. if (sod.equals("")) { System.out.print(signeddata.toString()); } else { FileOutputStream envfos = new FileOutputStream(sod); envfos.write(signeddata); envfos.close(); } } catch (OptionException oe) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(NAME, getOptions()); System.exit(-1); } catch (Exception e) { e.printStackTrace(); return; } }
From source file:com.seanmadden.fast.ldap.main.Main.java
/** * The Main Event.//from w ww .j a v a2s. com * * @param args */ @SuppressWarnings("static-access") public static void main(String[] args) { BasicConfigurator.configure(); log.debug("System initializing"); try { Logger.getRootLogger().addAppender( new FileAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN), "log.log")); } catch (IOException e1) { log.error("Unable to open the log file..?"); } /* * Initialize the configuration engine. */ XMLConfiguration config = new XMLConfiguration(); config.setListDelimiter('|'); /* * Initialize the Command-Line parsing engine. */ CommandLineParser parser = new PosixParser(); Options opts = new Options(); opts.addOption(OptionBuilder.withLongOpt("config-file").hasArg() .withDescription("The configuration file to load").withArgName("config.xml").create("c")); opts.addOption(OptionBuilder.withLongOpt("profile").hasArg().withDescription("The profile to use") .withArgName("Default").create("p")); opts.addOption(OptionBuilder.withLongOpt("password").hasArg().withDescription("Password to connect with") .withArgName("password").create("P")); opts.addOption(OptionBuilder.withLongOpt("debug").hasArg(false).create('d')); opts.addOption(OptionBuilder.withLongOpt("verbose").hasArg(false).create('v')); File configurationFile = new File("config.xml"); try { // Parse the command-line options CommandLine cmds = parser.parse(opts, args); if (!cmds.hasOption('p')) { Logger.getRootLogger().addAppender(new GuiErrorAlerter(Level.ERROR)); } Logger.getRootLogger().setLevel(Level.ERROR); if (cmds.hasOption('v')) { Logger.getRootLogger().setLevel(Level.INFO); } if (cmds.hasOption('d')) { Logger.getRootLogger().setLevel(Level.DEBUG); } log.debug("Enabling configuration file parsing"); // The user has given us a file to parse. if (cmds.hasOption("c")) { configurationFile = new File(cmds.getOptionValue("c")); } log.debug("Config file: " + configurationFile); // Load the configuration file if (configurationFile.exists()) { config.load(configurationFile); } else { log.error("Cannot find config file"); } /* * Convert the profiles into memory */ Vector<ConnectionProfile> profs = new Vector<ConnectionProfile>(); List<?> profList = config.configurationAt("Profiles").configurationsAt("Profile"); for (Object p : profList) { SubnodeConfiguration profile = (SubnodeConfiguration) p; String name = profile.getString("[@name]"); String auth = profile.getString("LdapAuthString"); String server = profile.getString("LdapServerString"); String group = profile.getString("LdapGroupsLocation"); ConnectionProfile prof = new ConnectionProfile(name, server, auth, group); profs.add(prof); } ConnectionProfile prof = null; if (!cmds.hasOption('p')) { /* * Deploy the profile selector, to select a profile */ ProfileSelector profSel = new ProfileSelector(profs); prof = profSel.getSelection(); if (prof == null) { return; } /* * Empty the profiles and load a clean copy - then save it back * to the file */ config.clearTree("Profiles"); for (ConnectionProfile p : profSel.getProfiles()) { config.addProperty("Profiles.Profile(-1)[@name]", p.getName()); config.addProperty("Profiles.Profile.LdapAuthString", p.getLdapAuthString()); config.addProperty("Profiles.Profile.LdapServerString", p.getLdapServerString()); config.addProperty("Profiles.Profile.LdapGroupsLocation", p.getLdapGroupsString()); } config.save(configurationFile); } else { for (ConnectionProfile p : profs) { if (p.getName().equals(cmds.getOptionValue('p'))) { prof = p; break; } } } log.info("User selected " + prof); String password = ""; if (cmds.hasOption('P')) { password = cmds.getOptionValue('P'); } else { password = PasswordPrompter.promptForPassword("Password?"); } if (password.equals("")) { return; } LdapInterface ldap = new LdapInterface(prof.getLdapServerString(), prof.getLdapAuthString(), prof.getLdapGroupsString(), password); /* * Gather options information from the configuration engine for the * specified report. */ Hashtable<String, Hashtable<String, ReportOption>> reportDataStructure = new Hashtable<String, Hashtable<String, ReportOption>>(); List<?> repConfig = config.configurationAt("Reports").configurationsAt("Report"); for (Object p : repConfig) { SubnodeConfiguration repNode = (SubnodeConfiguration) p; // TODO Do something with the report profile. // Allowing the user to deploy "profiles" is a nice feature // String profile = repNode.getString("[@profile]"); String reportName = repNode.getString("[@report]"); Hashtable<String, ReportOption> reportOptions = new Hashtable<String, ReportOption>(); reportDataStructure.put(reportName, reportOptions); // Loop through the options and add each to the table. for (Object o : repNode.configurationsAt("option")) { SubnodeConfiguration option = (SubnodeConfiguration) o; String name = option.getString("[@name]"); String type = option.getString("[@type]"); String value = option.getString("[@value]"); ReportOption ro = new ReportOption(); ro.setName(name); if (type.toLowerCase().equals("boolean")) { ro.setBoolValue(Boolean.parseBoolean(value)); } else if (type.toLowerCase().equals("integer")) { ro.setIntValue(Integer.valueOf(value)); } else { // Assume a string type here then. ro.setStrValue(value); } reportOptions.put(name, ro); log.debug(ro); } } System.out.println(reportDataStructure); /* * At this point, we now need to deploy the reports window to have * the user pick a report and select some happy options to allow * that report to work. Let's go. */ /* * Deploy the Reports selector, to select a report */ Reports.getInstance().setLdapConnection(ldap); ReportsWindow reports = new ReportsWindow(Reports.getInstance().getAllReports(), reportDataStructure); Report report = reports.getSelection(); if (report == null) { return; } /* * Empty the profiles and load a clean copy - then save it back to * the file */ config.clearTree("Reports"); for (Report r : Reports.getInstance().getAllReports()) { config.addProperty("Reports.Report(-1)[@report]", r.getClass().getCanonicalName()); config.addProperty("Reports.Report[@name]", "Standard"); for (ReportOption ro : r.getOptions().values()) { config.addProperty("Reports.Report.option(-1)[@name]", ro.getName()); config.addProperty("Reports.Report.option[@type]", ro.getType()); config.addProperty("Reports.Report.option[@value]", ro.getStrValue()); } } config.save(configurationFile); ProgressBar bar = new ProgressBar(); bar.start(); report.execute(); ASCIIFormatter format = new ASCIIFormatter(); ReportResult res = report.getResult(); format.format(res, new File(res.getForName() + "_" + res.getReportName() + ".txt")); bar.stop(); JOptionPane.showMessageDialog(null, "The report is at " + res.getForName() + "_" + res.getReportName() + ".txt", "Success", JOptionPane.INFORMATION_MESSAGE); } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("FAST Ldap Searcher", opts); } catch (ConfigurationException e) { e.printStackTrace(); log.fatal("OH EM GEES! Configuration errors."); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.hp.avmon.snmp.discover.SLPClient.java
/** * Test method.//from ww w. ja v a 2s . c o m * * @param args * Ignored */ public static void main(String[] args) { SLPClient client = new SLPClient(); List<String> wbemservices = client.findWbemServices(); Iterator<String> serviceIterator = wbemservices.iterator(); while (serviceIterator.hasNext()) { String url = serviceIterator.next().toString(); System.out.println(url); logger.debug(url); List<String> attributes = client.findAttributes(url, SCOPE, new Vector<String>()); Iterator<String> attributeIterator = attributes.iterator(); while (attributeIterator.hasNext()) { System.out.println(attributeIterator.next()); logger.debug(attributeIterator.next()); } } }
From source file:net.lightbody.bmp.proxy.jetty.jetty.win32.Service.java
public static void main(String[] arg) { String opt;//from ww w .ja v a2 s. com opt = System.getProperty("SERVICE_OUT"); if (opt != null) { try { PrintStream stdout = new PrintStream(new FileOutputStream(opt)); System.setOut(stdout); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } } opt = System.getProperty("SERVICE_ERR"); if (opt != null) { try { PrintStream stderr = new PrintStream(new FileOutputStream(opt)); System.setErr(stderr); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } } if (arg.length == 0) arg = new String[] { "etc/jetty.xml" }; try { _configs = new Vector(); for (int i = 0; i < arg.length; i++) _configs.add(arg[i]); createAll(); startAll(); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } }