Java Code Examples for java.util.Hashtable.put()

The following are Jave code examples for showing how to use put() of the java.util.Hashtable class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: CommonFramework   File: ImageUtils.java   View Source Code Vote up 6 votes
/**
 * 解析二维码图片工具类
 *
 * @param bitmap
 */
public static String analyzeBitmap(Bitmap bitmap) {
    MultiFormatReader multiFormatReader = new MultiFormatReader();

    // 解码的参数
    Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>(2);
    // 可以解析的编码类型
    Vector<BarcodeFormat> decodeFormats = new Vector<BarcodeFormat>();
    if (decodeFormats == null || decodeFormats.isEmpty()) {
        decodeFormats = new Vector<BarcodeFormat>();

        // 这里设置可扫描的类型,我这里选择了都支持
        decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS);
        decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);
        decodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS);
    }
    hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
    // 设置继续的字符编码格式为UTF8
    hints.put(DecodeHintType.CHARACTER_SET, "UTF8");
    // 设置解析配置参数
    multiFormatReader.setHints(hints);

    // 开始对图像资源解码
    Result rawResult = null;
    try {
        rawResult = multiFormatReader.decodeWithState(new BinaryBitmap(new HybridBinarizer(new BitmapLuminanceSource(bitmap))));
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (rawResult != null) {
        return rawResult.getText();
    } else {
        return "Failed";
    }
}
 
Example 2
Project: tvConnect_android   File: EncodingHandler.java   View Source Code Vote up 6 votes
public static Bitmap createQRCode(String str, int size) throws WriterException {
	Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
	hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
	BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, size, size);
	int width = matrix.getWidth();
	int height = matrix.getHeight();
	int[] pixels = new int[width * height];
	for(int x = 0; x < width; x ++){
		for(int y = 0; y < height; y ++){
			if(matrix.get(x, y)){
				pixels[y * width + x] = BLACK;
			}
		}
	}
	Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
	bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
	return bitmap;
}
 
Example 3
Project: EvoServ   File: SGHSystem.java   View Source Code Vote up 6 votes
public int[] distFeaturesOnServers() {
    Hashtable<SGHFeature, Integer> count = new Hashtable<SGHFeature, Integer>();
    for (SGHServer s : servers) {
        for (SGHFeature f : s.featureSet) {
            if (!count.containsKey(f)) {
                count.put(f, 1);
            }
            else {
                count.put(f, count.get(f) + 1);
            }
        }
    }
    ArrayList<Integer> counts = new ArrayList<Integer>(count.values());
    Collections.sort(counts);
    int[] result = new int[counts.size()];
    for (int i=0; i<counts.size(); i++) result[counts.size()-i-1] = counts.get(i);
    return result;
}
 
Example 4
Project: openjdk-jdk10   File: TestAttributedStringCtor.java   View Source Code Vote up 6 votes
public static void main(String[] args) {

        // Create a new AttributedString with one attribute.
        Hashtable attributes = new Hashtable();
        attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);
        AttributedString origString = new AttributedString("Hello world.", attributes);

        // Create an iterator over part of the AttributedString.
        AttributedCharacterIterator iter = origString.getIterator(null, 4, 6);

        // Attempt to create a new AttributedString from the iterator.
        // This will throw IllegalArgumentException.
        AttributedString newString = new AttributedString(iter);

        // Without the exception this would get executed.
        System.out.println("DONE");
    }
 
Example 5
Project: routerapp   File: MenuManagementWindow.java   View Source Code Vote up 5 votes
/**
 * Builds a list from the components array.
 * @param components the components array
 * @return a list to be placed on the GUI
 */
JList buildListFromComponents (Component [] components) {
	JList list = new JList();
	
	if (components != null) {
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		list.setSize(100,200);
		
		listData = new Vector();
		menuItems = new Hashtable();
		
		// build a hash look-up table and fill list with components's text
		for (int i=0 ; i<components.length ; i++) {
			if (components[i] instanceof JMenuItem) {
				listData.addElement(((JMenuItem)components[i]).getText());
				menuItems.put(((JMenuItem)components[i]).getText(),components[i]);
			}
			else {
				listData.addElement(SEPARATOR_STRING);
				menuItems.put(SEPARATOR_STRING,components[i]);
			}
		}
		
		list.setListData(listData);
	}
		
	return list;
}
 
Example 6
Project: unitimes   File: MakeAssignmentsForClassEvents.java   View Source Code Vote up 5 votes
public MakeAssignmentsForClassEvents(Session session, org.hibernate.Session hibSession) {
    iHibSession = hibSession;
    iSession = session;
    Calendar date = Calendar.getInstance(Locale.US);
    date.setLenient(true);
    date.setTime(iSession.getSessionBeginDateTime());
    iWeekDate = new Vector(); 
    while (date.getTime().compareTo(iSession.getSessionEndDateTime())<=0) {
        iWeekDate.add(date.getTime());
        int idx = 0;
        while (idx<7) {
            date.add(Calendar.DAY_OF_YEAR, 1);
            if (iSession.getHoliday(date.get(Calendar.DAY_OF_MONTH),date.get(Calendar.MONTH))!=Session.sHolidayTypeBreak) idx++;
        }
    }
    iWeekDate.add(date.getTime());
    iDatePatterns = new Hashtable();
    for (Iterator i=DatePattern.findAll(iSession, true, null, null).iterator();i.hasNext();) {
        DatePattern dp = (DatePattern)i.next();
        iDatePatterns.put(dp.getName(), dp);
    }
    iExactTimePattern = TimePattern.findExactTime(iSession.getUniqueId());
    iLocations = new Hashtable();
    for (Iterator i=Location.findAll(iSession.getUniqueId()).iterator();i.hasNext();) {
        Location location = (Location)i.next();
        if (location.getPermanentId()!=null)
            iLocations.put(location.getPermanentId(), location);
    }
}
 
Example 7
Project: openjdk-jdk10   File: CheckboxOperator.java   View Source Code Vote up 5 votes
/**
 * Returns information about component.
 */
@Override
public Hashtable<String, Object> getDump() {
    Hashtable<String, Object> result = super.getDump();
    result.put(TEXT_DPROP, ((Checkbox) getSource()).getLabel());
    return result;
}
 
Example 8
Project: JenkinsHue   File: LDAPManager.java   View Source Code Vote up 5 votes
private InitialDirContext createContext() throws NamingException {
	Hashtable<String, String> env = new Hashtable<>();
	env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
	env.put(Context.PROVIDER_URL, ldapValue.getLdapUrl());
	env.put(Context.SECURITY_AUTHENTICATION, "simple");
	env.put(Context.SECURITY_PRINCIPAL, ldapValue.getUserName() + "@" + ldapValue.getLdapDomain());
	env.put(Context.SECURITY_CREDENTIALS, ldapValue.getPassword());
	return new InitialDirContext(env);
}
 
Example 9
Project: Rxjava2.0Demo   File: QrCodeActivity.java   View Source Code Vote up 5 votes
private void createImage(String text,int QR_WIDTH,int QR_HEIGHT) {
    try {
        // 需要引入core包
        QRCodeWriter writer = new QRCodeWriter();

        // 把输入的文本转为二维码
        BitMatrix martix = writer.encode(text, BarcodeFormat.QR_CODE,
                QR_WIDTH, QR_HEIGHT);

        System.out.println("w:" + martix.getWidth() + "h:"
                + martix.getHeight());

        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        BitMatrix bitMatrix = new QRCodeWriter().encode(text,
                BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
        int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
        for (int y = 0; y < QR_HEIGHT; y++) {
            for (int x = 0; x < QR_WIDTH; x++) {
                if (bitMatrix.get(x, y)) {
                    pixels[y * QR_WIDTH + x] = 0xff000000;
                } else {
                    pixels[y * QR_WIDTH + x] = 0xffffffff;
                }

            }
        }

        Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
                Bitmap.Config.ARGB_8888);

        bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
        ivCode.setImageBitmap(bitmap);

    } catch (WriterException e) {
        e.printStackTrace();
    }
}
 
Example 10
Project: creoson   File: JLJsonCreoHandler.java   View Source Code Vote up 5 votes
private Hashtable<String, Object> actionPwd(String sessionId, Hashtable<String, Object> input) throws JLIException {
       
	String outdir = proeHandler.pwd(sessionId);
	
	if (outdir!=null) {
		Hashtable<String, Object> out = new Hashtable<String, Object>();
		out.put(OUTPUT_DIRNAME, outdir);
		return out;
	}
	return null;
}
 
Example 11
Project: creoson   File: JLJsonDimensionHandler.java   View Source Code Vote up 5 votes
private Hashtable<String, Object> actionList(String sessionId, Hashtable<String, Object> input) throws JLIException {
       String modelname = checkStringParameter(input, PARAM_MODEL, false);
       String namePattern = checkStringParameter(input, PARAM_NAME, false);
       List<String> dimNames = null;
       Object namesObj = checkParameter(input, PARAM_NAMES, false);
       if (namesObj!=null) {
       	dimNames = getStringListValue(namesObj);
       }
       boolean encoded = checkFlagParameter(input, PARAM_ENCODED, false, false);

       List<DimData> dims = dimHandler.list(modelname, namePattern, dimNames, encoded, sessionId);
       
       if (dims!=null && dims.size()>0) {
		Hashtable<String, Object> out = new Hashtable<String, Object>();
		Vector<Map<String, Object>> outDims = new Vector<Map<String, Object>>();
		out.put(OUTPUT_DIMLIST, outDims);
		Map<String, Object> outDim = null;
		for (DimData dim : dims) {
			outDim = new Hashtable<String, Object>();
			if (dim.getName()!=null)
				outDim.put(PARAM_NAME, dim.getName());
			if (dim.getValue()!=null)
				outDim.put(PARAM_VALUE, dim.getValue());
			outDim.put(PARAM_ENCODED, Boolean.valueOf(dim.isEncoded()));
			
			outDims.add(outDim);
		}
		
		return out;
       }
       return null;
}
 
Example 12
Project: openjdk-jdk10   File: JSplitPaneOperator.java   View Source Code Vote up 5 votes
@Override
public Hashtable<String, Object> getDump() {
    Hashtable<String, Object> result = super.getDump();
    result.put(MINIMUM_DPROP, Integer.toString(((JSplitPane) getSource()).getMinimumDividerLocation()));
    result.put(MAXIMUM_DPROP, Integer.toString(((JSplitPane) getSource()).getMaximumDividerLocation()));
    result.put(ORIENTATION_DPROP, (((JSplitPane) getSource()).getOrientation() == JSplitPane.HORIZONTAL_SPLIT)
            ? HORIZONTAL_ORIENTATION_DPROP_VALUE
            : VERTICAL_ORIENTATION_DPROP_VALUE);
    result.put(VALUE_DPROP, Integer.toString(((JSplitPane) getSource()).getDividerLocation()));
    result.put(IS_ONE_TOUCH_EXPANDABLE_DPROP, ((JSplitPane) getSource()).isOneTouchExpandable() ? "true" : "false");
    return result;
}
 
Example 13
Project: ChronoBike   File: LdapThread.java   View Source Code Vote up 5 votes
public void run()
  {
Log.logNormal("LDap request " + m_nRequestId + ": trying to get ldap info from server " + m_csServer);
int nNbTries = 0;
while(nNbTries < 2)
{
          Hashtable<String, String> env = new Hashtable<String, String>();
          env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
          env.put(Context.PROVIDER_URL, "ldap://"+m_csServer+"/");
          env.put(Context.SECURITY_AUTHENTICATION, "simple");
          env.put(Context.SECURITY_PRINCIPAL, m_csUserId);
          env.put(Context.SECURITY_CREDENTIALS, m_csPassword);  
          if(m_ldapUtil != null)
          {
          	DirContext dirContext = m_ldapUtil.getDirContext(env);
          	if(dirContext != null)
          	{
          		m_ldapUtil.setOnceDirContext(dirContext);
          		Log.logNormal("LDap request " + m_nRequestId + ": dir context correctly set");
          		return;
          	}
          }   
          nNbTries++;
}
if(m_NbThreadCreated.dec() <= 0)
{
	m_ldapUtil.setOnceDirContext(null);
}
Log.logCritical("LDap request " + m_nRequestId + ": dir context NOT correctly set");
  }
 
Example 14
Project: OpenJSharp   File: InitialLdapContext.java   View Source Code Vote up 4 votes
/**
 * Constructs an initial context
 * using environment properties and connection request controls.
 * See <tt>javax.naming.InitialContext</tt> for a discussion of
 * environment properties.
 *
 * <p> This constructor will not modify its parameters or
 * save references to them, but may save a clone or copy.
 * Caller should not modify mutable keys and values in
 * <tt>environment</tt> after it has been passed to the constructor.
 *
 * <p> <tt>connCtls</tt> is used as the underlying context instance's
 * connection request controls.  See the class description
 * for details.
 *
 * @param environment
 *          environment used to create the initial DirContext.
 *          Null indicates an empty environment.
 * @param connCtls
 *          connection request controls for the initial context.
 *          If null, no connection request controls are used.
 *
 * @throws  NamingException if a naming exception is encountered
 *
 * @see #reconnect
 * @see LdapContext#reconnect
 */
@SuppressWarnings("unchecked")
public InitialLdapContext(Hashtable<?,?> environment,
                          Control[] connCtls)
        throws NamingException {
    super(true); // don't initialize yet

    // Clone environment since caller owns it.
    Hashtable<Object,Object> env = (environment == null)
        ? new Hashtable<>(11)
        : (Hashtable<Object,Object>)environment.clone();

    // Put connect controls into environment.  Copy them first since
    // caller owns the array.
    if (connCtls != null) {
        Control[] copy = new Control[connCtls.length];
        System.arraycopy(connCtls, 0, copy, 0, connCtls.length);
        env.put(BIND_CONTROLS_PROPERTY, copy);
    }
    // set version to LDAPv3
    env.put("java.naming.ldap.version", "3");

    // Initialize with updated environment
    init(env);
}
 
Example 15
Project: parabuild-ci   File: JDBCTypes.java   View Source Code Vote up 4 votes
JDBCTypes() {

        hStringJDBCtypes = new Hashtable();
        hIntJDBCtypes    = new Hashtable();

        hStringJDBCtypes.put(new Integer(ARRAY), "ARRAY");
        hStringJDBCtypes.put(new Integer(BLOB), "BLOB");
        hStringJDBCtypes.put(new Integer(CLOB), "CLOB");
        hStringJDBCtypes.put(new Integer(DISTINCT), "DISTINCT");
        hStringJDBCtypes.put(new Integer(JAVA_OBJECT), "JAVA_OBJECT");
        hStringJDBCtypes.put(new Integer(REF), "REF");
        hStringJDBCtypes.put(new Integer(STRUCT), "STRUCT");

        //
        hStringJDBCtypes.put(new Integer(java.sql.Types.BIGINT), "BIGINT");
        hStringJDBCtypes.put(new Integer(java.sql.Types.BINARY), "BINARY");
        hStringJDBCtypes.put(new Integer(java.sql.Types.BIT), "BIT");
        hStringJDBCtypes.put(new Integer(java.sql.Types.CHAR), "CHAR");
        hStringJDBCtypes.put(new Integer(java.sql.Types.DATE), "DATE");
        hStringJDBCtypes.put(new Integer(java.sql.Types.DECIMAL), "DECIMAL");
        hStringJDBCtypes.put(new Integer(java.sql.Types.DOUBLE), "DOUBLE");
        hStringJDBCtypes.put(new Integer(java.sql.Types.FLOAT), "FLOAT");
        hStringJDBCtypes.put(new Integer(java.sql.Types.INTEGER), "INTEGER");
        hStringJDBCtypes.put(new Integer(java.sql.Types.LONGVARBINARY),
                             "LONGVARBINARY");
        hStringJDBCtypes.put(new Integer(java.sql.Types.LONGVARCHAR),
                             "LONGVARCHAR");
        hStringJDBCtypes.put(new Integer(java.sql.Types.NULL), "NULL");
        hStringJDBCtypes.put(new Integer(java.sql.Types.NUMERIC), "NUMERIC");
        hStringJDBCtypes.put(new Integer(java.sql.Types.OTHER), "OTHER");
        hStringJDBCtypes.put(new Integer(java.sql.Types.REAL), "REAL");
        hStringJDBCtypes.put(new Integer(java.sql.Types.SMALLINT),
                             "SMALLINT");
        hStringJDBCtypes.put(new Integer(java.sql.Types.TIME), "TIME");
        hStringJDBCtypes.put(new Integer(java.sql.Types.TIMESTAMP),
                             "TIMESTAMP");
        hStringJDBCtypes.put(new Integer(java.sql.Types.TINYINT), "TINYINT");
        hStringJDBCtypes.put(new Integer(java.sql.Types.VARBINARY),
                             "VARBINARY");
        hStringJDBCtypes.put(new Integer(java.sql.Types.VARCHAR), "VARCHAR");

        hStringJDBCtypes.put(new Integer(java.sql.Types.BOOLEAN), "BOOLEAN");
        //
        hIntJDBCtypes.put("ARRAY", new Integer(ARRAY));
        hIntJDBCtypes.put("BLOB", new Integer(BLOB));
        hIntJDBCtypes.put("CLOB", new Integer(CLOB));
        hIntJDBCtypes.put("DISTINCT", new Integer(DISTINCT));
        hIntJDBCtypes.put("JAVA_OBJECT", new Integer(JAVA_OBJECT));
        hIntJDBCtypes.put("REF", new Integer(REF));
        hIntJDBCtypes.put("STRUCT", new Integer(STRUCT));

        //
        hIntJDBCtypes.put("BIGINT", new Integer(java.sql.Types.BIGINT));
        hIntJDBCtypes.put("BINARY", new Integer(java.sql.Types.BINARY));
        hIntJDBCtypes.put("BIT", new Integer(java.sql.Types.BIT));
        hIntJDBCtypes.put("CHAR", new Integer(java.sql.Types.CHAR));
        hIntJDBCtypes.put("DATE", new Integer(java.sql.Types.DATE));
        hIntJDBCtypes.put("DECIMAL", new Integer(java.sql.Types.DECIMAL));
        hIntJDBCtypes.put("DOUBLE", new Integer(java.sql.Types.DOUBLE));
        hIntJDBCtypes.put("FLOAT", new Integer(java.sql.Types.FLOAT));
        hIntJDBCtypes.put("INTEGER", new Integer(java.sql.Types.INTEGER));
        hIntJDBCtypes.put("LONGVARBINARY",
                          new Integer(java.sql.Types.LONGVARBINARY));
        hIntJDBCtypes.put("LONGVARCHAR",
                          new Integer(java.sql.Types.LONGVARCHAR));
        hIntJDBCtypes.put("NULL", new Integer(java.sql.Types.NULL));
        hIntJDBCtypes.put("NUMERIC", new Integer(java.sql.Types.NUMERIC));
        hIntJDBCtypes.put("OTHER", new Integer(java.sql.Types.OTHER));
        hIntJDBCtypes.put("REAL", new Integer(java.sql.Types.REAL));
        hIntJDBCtypes.put("SMALLINT", new Integer(java.sql.Types.SMALLINT));
        hIntJDBCtypes.put("TIME", new Integer(java.sql.Types.TIME));
        hIntJDBCtypes.put("TIMESTAMP", new Integer(java.sql.Types.TIMESTAMP));
        hIntJDBCtypes.put("TINYINT", new Integer(java.sql.Types.TINYINT));
        hIntJDBCtypes.put("VARBINARY", new Integer(java.sql.Types.VARBINARY));
        hIntJDBCtypes.put("VARCHAR", new Integer(java.sql.Types.VARCHAR));
        hIntJDBCtypes.put("BOOLEAN", new Integer(java.sql.Types.BOOLEAN));
    }
 
Example 16
Project: unitimes   File: CurriculaServlet.java   View Source Code Vote up 4 votes
private Hashtable<Long, Hashtable<CourseInterface, Set<Long>>> loadClasfCourse2enrl(org.hibernate.Session hibSession, Long acadAreaId, Collection<Long> majors, boolean multipleMajors) {
	List<Object[]> lines = null;
	String select = "a.academicClassification.uniqueId, e.courseOffering.uniqueId, e.courseOffering.subjectArea.subjectAreaAbbreviation || ' ' || e.courseOffering.courseNbr, s.uniqueId";
	String from = "StudentClassEnrollment e inner join e.student s inner join s.areaClasfMajors a inner join a.major m";
	String where = "s.session.uniqueId = :sessionId and a.academicArea.uniqueId = :areaId";
	if (majors.isEmpty()) {
		// students with no major
		if (!multipleMajors)
			lines = hibSession.createQuery("select " + select + " from " + from + " where " + where)
				.setLong("sessionId", getAcademicSessionId()).setLong("areaId", acadAreaId)
				.setCacheable(true).list();
	} else if (!multipleMajors || majors.size() == 1) {
		// students with one major
		lines = hibSession.createQuery("select " + select + " from " + from + " where " + where + " and m.uniqueId in :majorIds")
				.setLong("sessionId", getAcademicSessionId()).setLong("areaId", acadAreaId)
				.setParameterList("majorIds", majors)
				.setCacheable(true).list();
	} else {
		// students with multiple majors
		Map<String, Long> params = new HashMap<String, Long>();
		int idx = 0;
		for (Long major: majors) {
			if (idx == 0) {
				where += " and m.uniqueId = :m" + idx;
			} else {
				from += " inner join s.areaClasfMajors a" + idx;
				where += " and a" + idx + ".academicArea.uniqueId = :areaId and a" + idx + ".major.uniqueId = :m" + idx;
			}
			params.put("m" + idx, major);
			idx ++;
		}
		org.hibernate.Query q = hibSession.createQuery("select " + select + " from " + from + " where " + where)
				.setLong("sessionId", getAcademicSessionId()).setLong("areaId", acadAreaId);
		for (Map.Entry<String, Long> e: params.entrySet())
			q.setLong(e.getKey(), e.getValue());
		lines = q.setCacheable(true).list();
	}
	Hashtable<Long, Hashtable<CourseInterface, Set<Long>>> clasf2course2enrl = new Hashtable<Long, Hashtable<CourseInterface,Set<Long>>>();
	if (lines != null)
		for (Object[] o : lines) {
			Long clasfId = (Long)o[0];
			Long courseId = (Long)o[1];
			String courseName = (String)o[2];
			Long studentId = (Long)o[3];
			CourseInterface course = new CourseInterface();
			course.setId(courseId);
			course.setCourseName(courseName);
			Hashtable<CourseInterface, Set<Long>> course2enrl = clasf2course2enrl.get(clasfId);
			if (course2enrl == null) {
				course2enrl = new Hashtable<CourseInterface, Set<Long>>();
				clasf2course2enrl.put(clasfId, course2enrl);
			}
			Set<Long> students = course2enrl.get(course);
			if (students == null) {
				students = new HashSet<Long>();
				course2enrl.put(course, students);
			}
			students.add(studentId);
		}
	
	return clasf2course2enrl;
}
 
Example 17
Project: smile_1.5.0_java7   File: LogisticDistributionDemo.java   View Source Code Vote up 4 votes
public LogisticDistributionDemo() {
    super(new BorderLayout());

    Hashtable<Integer, JLabel> labelTable = new Hashtable<>();
    for (int i = 0; i <= 50; i+=10) {
        labelTable.put(new Integer(i), new JLabel(String.valueOf(i/10)));
    }

    sigmaSlider = new JSlider(0, 50, (int) Math.round(sigma * 10));
    sigmaSlider.addChangeListener(this);
    sigmaSlider.setLabelTable(labelTable);
    sigmaSlider.setMajorTickSpacing(10);
    sigmaSlider.setMinorTickSpacing(2);
    sigmaSlider.setPaintTicks(true);
    sigmaSlider.setPaintLabels(true);

    optionPane = new JPanel(new FlowLayout(FlowLayout.LEFT));
    optionPane.setBorder(BorderFactory.createRaisedBevelBorder());
    optionPane.add(new JLabel("Scale:"));
    optionPane.add(sigmaSlider);

    add(optionPane, BorderLayout.NORTH);

    canvas = new JPanel(new GridLayout(2, 2));
    add(canvas, BorderLayout.CENTER);

    LogisticDistribution dist = new LogisticDistribution(0, sigma);

    double[][] p = new double[200][2];
    double[][] q = new double[200][2];
    for (int i = 0; i < p.length; i++) {
        p[i][0] = (i - 100) / 10.0;
        p[i][1] = dist.p(p[i][0]);
        q[i][0] = (i - 100) / 10.0;
        q[i][1] = dist.cdf(p[i][0]);
    }

    pdf = LinePlot.plot(p, Line.Style.SOLID, Color.BLUE);
    pdf.setTitle("PDF");
    canvas.add(pdf);

    cdf = LinePlot.plot(q, Line.Style.SOLID, Color.BLUE);
    cdf.setTitle("CDF");
    canvas.add(cdf);

    double[] data = new double[500];
    for (int i = 0; i < data.length; i++) {
        data[i] = dist.rand();
    }

    histogram = Histogram.plot(data, 20);
    histogram.setTitle("Histogram");
    canvas.add(histogram);

    qqplot = QQPlot.plot(data, dist);
    qqplot.setTitle("Q-Q Plot");
    canvas.add(qqplot);
}
 
Example 18
Project: lazycat   File: StandardContext.java   View Source Code Vote up 4 votes
/**
 * Allocate resources, including proxy. Return <code>true</code> if
 * initialization was successfull, or <code>false</code> otherwise.
 */
public boolean resourcesStart() {

	boolean ok = true;

	Hashtable<String, String> env = new Hashtable<String, String>();
	if (getParent() != null)
		env.put(ProxyDirContext.HOST, getParent().getName());
	env.put(ProxyDirContext.CONTEXT, getName());

	try {
		ProxyDirContext proxyDirContext = new ProxyDirContext(env, webappResources);
		if (webappResources instanceof FileDirContext) {
			filesystemBased = true;
			((FileDirContext) webappResources).setAllowLinking(isAllowLinking());
		}
		if (webappResources instanceof BaseDirContext) {
			((BaseDirContext) webappResources).setDocBase(getBasePath());
			((BaseDirContext) webappResources).setCached(isCachingAllowed());
			((BaseDirContext) webappResources).setCacheTTL(getCacheTTL());
			((BaseDirContext) webappResources).setCacheMaxSize(getCacheMaxSize());
			((BaseDirContext) webappResources).allocate();
			// Alias support
			((BaseDirContext) webappResources).setAliases(getAliases());

			if (effectiveMajorVersion >= 3 && addWebinfClassesResources) {
				try {
					DirContext webInfCtx = (DirContext) webappResources.lookup("/WEB-INF/classes");
					// Do the lookup to make sure it exists
					webInfCtx.lookup("META-INF/resources");
					((BaseDirContext) webappResources).addAltDirContext(webInfCtx);
				} catch (NamingException e) {
					// Doesn't exist - ignore and carry on
				}
			}
		}
		// Register the cache in JMX
		if (isCachingAllowed() && proxyDirContext.getCache() != null) {
			String contextName = getName();
			if (!contextName.startsWith("/")) {
				contextName = "/" + contextName;
			}
			ObjectName resourcesName = new ObjectName(
					this.getDomain() + ":type=Cache,host=" + getHostname() + ",context=" + contextName);
			Registry.getRegistry(null, null).registerComponent(proxyDirContext.getCache(), resourcesName, null);
		}
		this.resources = proxyDirContext;
	} catch (Throwable t) {
		ExceptionUtils.handleThrowable(t);
		log.error(sm.getString("standardContext.resourcesStart"), t);
		ok = false;
	}

	return (ok);

}
 
Example 19
Project: jdk8u-jdk   File: ReachableObjects.java   View Source Code Vote up 4 votes
public ReachableObjects(JavaHeapObject root,
                        final ReachableExcludes excludes) {
    this.root = root;

    final Hashtable<JavaHeapObject, JavaHeapObject> bag = new Hashtable<JavaHeapObject, JavaHeapObject>();
    final Hashtable<String, String> fieldsExcluded = new Hashtable<String, String>();  //Bag<String>
    final Hashtable<String, String> fieldsUsed = new Hashtable<String, String>();   // Bag<String>
    JavaHeapObjectVisitor visitor = new AbstractJavaHeapObjectVisitor() {
        public void visit(JavaHeapObject t) {
            // Size is zero for things like integer fields
            if (t != null && t.getSize() > 0 && bag.get(t) == null) {
                bag.put(t, t);
                t.visitReferencedObjects(this);
            }
        }

        public boolean mightExclude() {
            return excludes != null;
        }

        public boolean exclude(JavaClass clazz, JavaField f) {
            if (excludes == null) {
                return false;
            }
            String nm = clazz.getName() + "." + f.getName();
            if (excludes.isExcluded(nm)) {
                fieldsExcluded.put(nm, nm);
                return true;
            } else {
                fieldsUsed.put(nm, nm);
                return false;
            }
        }
    };
    // Put the closure of root and all objects reachable from root into
    // bag (depth first), but don't include root:
    visitor.visit(root);
    bag.remove(root);

    // Now grab the elements into a vector, and sort it in decreasing size
    JavaThing[] things = new JavaThing[bag.size()];
    int i = 0;
    for (Enumeration e = bag.elements(); e.hasMoreElements(); ) {
        things[i++] = (JavaThing) e.nextElement();
    }
    ArraySorter.sort(things, new Comparer() {
        public int compare(Object lhs, Object rhs) {
            JavaThing left = (JavaThing) lhs;
            JavaThing right = (JavaThing) rhs;
            int diff = right.getSize() - left.getSize();
            if (diff != 0) {
                return diff;
            }
            return left.compareTo(right);
        }
    });
    this.reachables = things;

    this.totalSize = root.getSize();
    for (i = 0; i < things.length; i++) {
        this.totalSize += things[i].getSize();
    }

    excludedFields = getElements(fieldsExcluded);
    usedFields = getElements(fieldsUsed);
}
 
Example 20
Project: incubator-netbeans   File: ModuleListParserTest.java   View Source Code Vote up 4 votes
public void testScanSourcesInNetBeansOrg() throws Exception {
    Hashtable<String,Object> properties = new Hashtable<>();
    properties.put("nb_all", nball.getAbsolutePath());
    File build = file(nball, "nbbuild/netbeans");
    properties.put("netbeans.dest.dir", build.getAbsolutePath());
    properties.put("nb.cluster.foo", "beans,clazz");
    properties.put("nb.cluster.foo.dir", "foodir");
    properties.put("nb.cluster.bar", "core.startup");
    properties.put("nb.cluster.bar.dir", "bardir");
    properties.put("basedir", new File(nball, "nbbuild").getAbsolutePath());
    long start = System.currentTimeMillis();
    ModuleListParser p = new ModuleListParser(properties, ModuleType.NB_ORG, null);
    System.err.println("Scanned " + nball + " sources in " + (System.currentTimeMillis() - start) + "msec");
    ModuleListParser.Entry e = p.findByCodeNameBase("org.netbeans.modules.beans");
    assertNotNull(e);
    assertEquals("org.netbeans.modules.beans", e.getCnb());
    assertEquals(file(build, "foodir/modules/org-netbeans-modules-beans.jar"), e.getJar());
    assertEquals(Collections.EMPTY_LIST, Arrays.asList(e.getClassPathExtensions()));
    e = p.findByCodeNameBase("org.netbeans.libs.xerces");
    assertNotNull("found module in a subdir", e);
    assertEquals("org.netbeans.libs.xerces", e.getCnb());
    assertEquals("unknown module put in extra cluster by default", file(build, "extra/modules/org-netbeans-libs-xerces.jar"), e.getJar());
    assertEquals("correct CP extensions (using <binary-origin> and relative paths)",
        Collections.singletonList(file(nball, "libs.xerces/external/xercesImpl-2.8.0.jar")),
        Arrays.asList(e.getClassPathExtensions()));
    e = p.findByCodeNameBase("org.netbeans.swing.tabcontrol");
    assertNotNull("found module in a subsubdir", e);
    e = p.findByCodeNameBase("org.netbeans.core.startup");
    assertNotNull(e);
    assertEquals("org.netbeans.core.startup", e.getCnb());
    assertEquals("handling special JAR names correctly", file(build, "bardir/core/core.jar"), e.getJar());
    assertEquals(Collections.EMPTY_LIST, Arrays.asList(e.getClassPathExtensions()));
    e = p.findByCodeNameBase("org.netbeans.modules.xml.tax");
    assertNotNull("found xml/tax", e);
    assertEquals("org.netbeans.modules.xml.tax", e.getCnb());
    assertEquals(file(build, "extra/modules/org-netbeans-modules-xml-tax.jar"), e.getJar());
    assertEquals("correct CP extensions (using runtime-relative-path)", Arrays.asList(new File[] {
        file(build, "extra/modules/ext/org-netbeans-tax.jar"),
    }), Arrays.asList(e.getClassPathExtensions()));
    e = p.findByCodeNameBase("org.netbeans.modules.masterfs");
    /* too fragile:
    assertNotNull(e);
    String testDeps[] = e.getTestDependencies().get("unit");
    assertNotNull(testDeps);
    assertEquals("depends on one test entry",1,testDeps.length);
    assertEquals("org.openide.filesystems",testDeps[0]);
     */
}