text:
package java.io;

/**
 * This abstract class is the superclass of all classes representing
 * an output stream of bytes. An output stream accepts output bytes
 * and sends them to some sink.
 *

 * Applications that need to define a subclass of
 * OutputStream must always provide at least a method
 * that writes one byte of output.
 *
 * @author  Arthur van Hoff
 * @see     java.io.BufferedOutputStream
 * @see     java.io.ByteArrayOutputStream
 * @see     java.io.DataOutputStream
 * @see     java.io.FilterOutputStream
 * @see     java.io.InputStream
 * @see     java.io.OutputStream#write(int)
 * @since   JDK1.0
 */
public abstract class OutputStream implements Closeable, Flushable {
    /**
     * Writes the specified byte to this output stream. The general
     * contract for write is that one byte is written
     * to the output stream. The byte to be written is the eight
     * low-order bits of the argument b. The 24
     * high-order bits of b are ignored.
     *

     * Subclasses of OutputStream must provide an
     * implementation for this method.
     *
     * @param      b   the byte.
     * @exception  IOException  if an I/O error occurs. In particular,
     *             an IOException may be thrown if the
     *             output stream has been closed.
     */
    public abstract void write(int b) throws IOException;

    /**
     * Writes b.length bytes from the specified byte array
     * to this output stream. The general contract for write(b)
     * is that it should have exactly the same effect as the call
     * write(b, 0, b.length).
     *
     * @param      b   the data.
     * @exception  IOException  if an I/O error occurs.
     * @see        java.io.OutputStream#write(byte[], int, int)
     */
    public void write(byte b[]) throws IOException {
        write(b, 0, b.length);
    }

    /**
     * Writes len bytes from the specified byte array
     * starting at offset off to this output stream.
     * The general contract for write(b, off, len) is that
     * some of the bytes in the array b are written to the
     * output stream in order; element b[off] is the first
     * byte written and b[off+len-1] is the last byte written
     * by this operation.
     *

     * The write method of OutputStream calls
     * the write method of one argument on each of the bytes to be
     * written out. Subclasses are encouraged to override this method and
     * provide a more efficient implementation.
     *

     * If b is null, a
     * NullPointerException is thrown.
     *

     * If off is negative, or len is negative, or
     * off+len is greater than the length of the array
     * b, then an <tt>IndexOutOfBoundsException</tt> is thrown.
     *
     * @param      b     the data.
     * @param      off   the start offset in the data.
     * @param      len   the number of bytes to write.
     * @exception  IOException  if an I/O error occurs. In particular,
     *             an IOException is thrown if the output
     *             stream is closed.
     */
    public void write(byte b[], int off, int len) throws IOException {
        if (b == null) {
            throw new NullPointerException();
        } else if ((off < 0) || (off > b.length) || (len < 0) ||
                   ((off + len) > b.length) || ((off + len) < 0)) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return;
        }
        for (int i = 0 ; i < len ; i++) {
            write(b[off + i]);
        }
    }

    /**
     * Flushes this output stream and forces any buffered output bytes
     * to be written out. The general contract of flush is
     * that calling it is an indication that, if any bytes previously
     * written have been buffered by the implementation of the output
     * stream, such bytes should immediately be written to their
     * intended destination.
     *

     * If the intended destination of this stream is an abstraction provided by
     * the underlying operating system, for example a file, then flushing the
     * stream guarantees only that bytes previously written to the stream are
     * passed to the operating system for writing; it does not guarantee that
     * they are actually written to a physical device such as a disk drive.
     *

     * The flush method of OutputStream does nothing.
     *
     * @exception  IOException  if an I/O error occurs.
     */
    public void flush() throws IOException {
    }

    /**
     * Closes this output stream and releases any system resources
     * associated with this stream. The general contract of close
     * is that it closes the output stream. A closed stream cannot perform
     * output operations and cannot be reopened.
     *

     * The close method of OutputStream does nothing.
     *
     * @exception  IOException  if an I/O error occurs.
     */
    public void close() throws IOException {
    }

}


text:
title: Update naskah rubrik Kasatmata
date: 2012-11-12
categories:
- laporan
- LenteraTimur.com – Menyigi Identitas Indonesia
layout: laporancmb
---

**Tujuan** : Update naskah rubrik Kasatmata "Surakarta - Republik Terus Menguji Kesabaran Kami" (Kontributor - Wahyu Indro Sasongko)

**Lokasi** : Sekretariat Lentera Timur

**Alamat** : Jalan Sawo Manila No. 10 Pasar Minggu, Jakarta Selatan

**Jam** :

**Hadir** :

**Ringkasan** :
* Naskah dapat dibaca [di sini](http://www.lenteratimur.com/2012/11/surakarta-republik-terus-menguji-kesabaran-kami/)

redpajama_set_name: RedPajamaGithub


text:
#ifndef MSGFMT_H
#define MSGFMT_H

#include "unicode/utypes.h"

/**
 * \file
 * \brief C++ API: Formats messages in a language-neutral way.
 */

#if !UCONFIG_NO_FORMATTING

#include "unicode/format.h"
#include "unicode/locid.h"
#include "unicode/messagepattern.h"
#include "unicode/parseerr.h"
#include "unicode/plurfmt.h"
#include "unicode/plurrule.h"

U_CDECL_BEGIN
// Forward declaration.
struct UHashtable;
typedef struct UHashtable UHashtable; /**< @internal */
U_CDECL_END

U_NAMESPACE_BEGIN

class AppendableWrapper;
class DateFormat;
class NumberFormat;

/**
 *
MessageFormat prepares strings for display to users,
 * with optional arguments (variables/placeholders).
 * The arguments can occur in any order, which is necessary for translation
 * into languages with different grammars.
 *
 *
A MessageFormat is constructed from a pattern string
 * with arguments in {curly braces} which will be replaced by formatted values.
 *
 *
MessageFormat differs from the other Format
 * classes in that you create a MessageFormat object with one
 * of its constructors (not with a createInstance style factory
 * method). Factory methods aren't necessary because MessageFormat
 * itself doesn't implement locale-specific behavior. Any locale-specific
 * behavior is defined by the pattern that you provide and the
 * subformats used for inserted arguments.
 *
 *
Arguments can be named (using identifiers) or numbered (using small ASCII-digit integers).
 * Some of the API methods work only with argument numbers and throw an exception
 * if the pattern has named arguments (see {@link #usesNamedArguments()}).
 *
 *
An argument might not specify any format type. In this case,
 * a Number value is formatted with a default (for the locale) NumberFormat,
 * a Date value is formatted with a default (for the locale) DateFormat,
 * and for any other value its toString() value is used.
 *
 *
An argument might specify a "simple" type for which the specified
 * Format object is created, cached and used.
 *
 *
An argument might have a "complex" type with nested MessageFormat sub-patterns.
 * During formatting, one of these sub-messages is selected according to the argument value
 * and recursively formatted.
 *
 *
After construction, a custom Format object can be set for
 * a top-level argument, overriding the default formatting and parsing behavior
 * for that argument.
 * However, custom formatting can be achieved more simply by writing
 * a typeless argument in the pattern string
 * and supplying it with a preformatted string value.
 *
 *
When formatting, MessageFormat takes a collection of argument values
 * and writes an output string.
 * The argument values may be passed as an array
 * (when the pattern contains only numbered arguments)
 * or as an array of names and and an array of arguments (which works for both named
 * and numbered arguments).
 *
 *
Each argument is matched with one of the input values by array index or argument name
 * and formatted according to its pattern specification
 * (or using a custom Format object if one was set).
 * A numbered pattern argument is matched with an argument name that contains that number
 * as an ASCII-decimal-digit string (without leading zero).
 *
 *
Patterns and Their Interpretation

 *
 * MessageFormat uses patterns of the following form:
 *

 * message = messageText (argument messageText)*
 * argument = noneArg | simpleArg | complexArg
 * complexArg = choiceArg | pluralArg | selectArg | selectordinalArg
 *
 * noneArg = '{' argNameOrNumber '}'
 * simpleArg = '{' argNameOrNumber ',' argType [',' argStyle] '}'
 * choiceArg = '{' argNameOrNumber ',' "choice" ',' choiceStyle '}'
 * pluralArg = '{' argNameOrNumber ',' "plural" ',' pluralStyle '}'
 * selectArg = '{' argNameOrNumber ',' "select" ',' selectStyle '}'
 * selectordinalArg = '{' argNameOrNumber ',' "selectordinal" ',' pluralStyle '}'
 *
 * choiceStyle: see {@link ChoiceFormat}
 * pluralStyle: see {@link PluralFormat}
 * selectStyle: see {@link SelectFormat}
 *
 * argNameOrNumber = argName | argNumber
 * argName = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+
 * argNumber = '0' | ('1'..'9' ('0'..'9')*)
 *
 * argType = "number" | "date" | "time" | "spellout" | "ordinal" | "duration"
 * argStyle = "short" | "medium" | "long" | "full" | "integer" | "currency" | "percent" | argStyleText
 *

 *
 *

 *
messageText can contain quoted literal strings including syntax characters.
 *       A quoted literal string begins with an ASCII apostrophe and a syntax character
 *       (usually a {curly brace}) and continues until the next single apostrophe.
 *       A double ASCII apostrohpe inside or outside of a quoted string represents
 *       one literal apostrophe.
 *
Quotable syntax characters are the {curly braces} in all messageText parts,
 *       plus the '#' sign in a messageText immediately inside a pluralStyle,
 *       and the '|' symbol in a messageText immediately inside a choiceStyle.
 *
See also {@link #UMessagePatternApostropheMode}
 *
In argStyleText, every single ASCII apostrophe begins and ends quoted literal text,
 *       and unquoted {curly braces} must occur in matched pairs.
 *

 *
 *
Recommendation: Use the real apostrophe (single quote) character
 * \htmlonly’\endhtmlonly (U+2019) for
 * human-readable text, and use the ASCII apostrophe ' (U+0027)
 * only in program syntax, like quoting in MessageFormat.
 * See the annotations for U+0027 Apostrophe in The Unicode Standard.
 *
 *
The choice argument type is deprecated.
 * Use plural arguments for proper plural selection,
 * and select arguments for simple selection among a fixed set of choices.
 *
 *
The argType and argStyle values are used to create
 * a Format instance for the format element. The following
 * table shows how the values map to Format instances. Combinations not
 * shown in the table are illegal. Any argStyleText must
 * be a valid pattern string for the Format subclass used.
 *
 *

 *

 *       argType
 *       argStyle
 *       resulting Format object
 *

 *       (none)
 *       null
 *

 *       number
 *       (none)
 *       NumberFormat.createInstance(getLocale(), status)
 *

 *       integer
 *       NumberFormat.createInstance(getLocale(), kNumberStyle, status)
 *

 *       currency
 *       NumberFormat.createCurrencyInstance(getLocale(), status)
 *

 *       percent
 *       NumberFormat.createPercentInstance(getLocale(), status)
 *

 *       argStyleText
 *       new DecimalFormat(argStyleText, new DecimalFormatSymbols(getLocale(), status), status)
 *

 *       date
 *       (none)
 *       DateFormat.createDateInstance(kDefault, getLocale(), status)
 *

 *       short
 *       DateFormat.createDateInstance(kShort, getLocale(), status)
 *

 *       medium
 *       DateFormat.createDateInstance(kDefault, getLocale(), status)
 *

 *       long
 *       DateFormat.createDateInstance(kLong, getLocale(), status)
 *

 *       full
 *       DateFormat.createDateInstance(kFull, getLocale(), status)
 *

 *       argStyleText
 *       new SimpleDateFormat(argStyleText, getLocale(), status)
 *

 *       time
 *       (none)
 *       DateFormat.createTimeInstance(kDefault, getLocale(), status)
 *

 *       short
 *       DateFormat.createTimeInstance(kShort, getLocale(), status)
 *

 *       medium
 *       DateFormat.createTimeInstance(kDefault, getLocale(), status)
 *

 *       long
 *       DateFormat.createTimeInstance(kLong, getLocale(), status)
 *

 *       full
 *       DateFormat.createTimeInstance(kFull, getLocale(), status)
 *

 *       argStyleText
 *       new SimpleDateFormat(argStyleText, getLocale(), status)
 *

 *       spellout
 *       argStyleText (optional)
 *       new RuleBasedNumberFormat(URBNF_SPELLOUT, getLocale(), status)
 *
    .setDefaultRuleset(argStyleText, status);
 *

 *       ordinal
 *       argStyleText (optional)
 *       new RuleBasedNumberFormat(URBNF_ORDINAL, getLocale(), status)
 *
    .setDefaultRuleset(argStyleText, status);
 *

 *       duration
 *       argStyleText (optional)
 *       new RuleBasedNumberFormat(URBNF_DURATION, getLocale(), status)
 *
    .setDefaultRuleset(argStyleText, status);
 *

 *

 *
 *
Usage Information

 *
 *
Here are some examples of usage:
 * Example 1:
 *
 *

 * \code
 *     UErrorCode success = U_ZERO_ERROR;
 *     GregorianCalendar cal(success);
 *     Formattable arguments[] = {
 *         7L,
 *         Formattable( (Date) cal.getTime(success), Formattable::kIsDate),
 *         "a disturbance in the Force"
 *     };
 *
 *     UnicodeString result;
 *     MessageFormat::format(
 *          "At {1,time} on {1,date}, there was {2} on planet {0,number}.",
 *          arguments, 3, result, success );
 *
 *     cout << "result: " << result << endl;
 *     //<output>: At 4:34:20 PM on 23-Mar-98, there was a disturbance
 *     //             in the Force on planet 7.
 * \endcode
 *

 *
 * Typically, the message format will come from resources, and the
 * arguments will be dynamically set at runtime.
 *
 *
Example 2:
 *
 *

 *  \code
 *     success = U_ZERO_ERROR;
 *     Formattable testArgs[] = {3L, "MyDisk"};
 *
 *     MessageFormat form(
 *         "The disk \"{1}\" contains {0} file(s).", success );
 *
 *     UnicodeString string;
 *     FieldPosition fpos = 0;
 *     cout << "format: " << form.format(testArgs, 2, string, fpos, success ) << endl;
 *
 *     // output, with different testArgs:
 *     // output: The disk "MyDisk" contains 0 file(s).
 *     // output: The disk "MyDisk" contains 1 file(s).
 *     // output: The disk "MyDisk" contains 1,273 file(s).
 *  \endcode
 *

 *
 *
 *
For messages that include plural forms, you can use a plural argument:
 *

 * \code
 *  success = U_ZERO_ERROR;
 *  MessageFormat msgFmt(
 *       "{num_files, plural, "
 *       "=0{There are no files on disk \"{disk_name}\".}"
 *       "=1{There is one file on disk \"{disk_name}\".}"
 *       "other{There are # files on disk \"{disk_name}\".}}",
 *      Locale("en"),
 *      success);
 *  FieldPosition fpos = 0;
 *  Formattable testArgs[] = {0L, "MyDisk"};
 *  UnicodeString testArgsNames[] = {"num_files", "disk_name"};
 *  UnicodeString result;
 *  cout << msgFmt.format(testArgs, testArgsNames, 2, result, fpos, 0, success);
 *  testArgs[0] = 3L;
 *  cout << msgFmt.format(testArgs, testArgsNames, 2, result, fpos, 0, success);
 * \endcode
 * output:
 * There are no files on disk "MyDisk".
 * There are 3 files on "MyDisk".
 *

 * See {@link PluralFormat} and {@link PluralRules} for details.
 *
 *
Synchronization

 *
 *
MessageFormats are not synchronized.
 * It is recommended to create separate format instances for each thread.
 * If multiple threads access a format concurrently, it must be synchronized
 * externally.
 *
 * @stable ICU 2.0
 */
class U_I18N_API MessageFormat : public Format {
public:
#ifndef U_HIDE_OBSOLETE_API
    /**
     * Enum type for kMaxFormat.
     * @obsolete ICU 3.0.  The 10-argument limit was removed as of ICU 2.6,
     * rendering this enum type obsolete.
     */
    enum EFormatNumber {
        /**
         * The maximum number of arguments.
         * @obsolete ICU 3.0.  The 10-argument limit was removed as of ICU 2.6,
         * rendering this constant obsolete.
         */
        kMaxFormat = 10
    };
#endif /* U_HIDE_OBSOLETE_API */

    /**
     * Constructs a new MessageFormat using the given pattern and the
     * default locale.
     *
     * @param pattern   Pattern used to construct object.
     * @param status    Input/output error code.  If the
     *                  pattern cannot be parsed, set to failure code.
     * @stable ICU 2.0
     */
    MessageFormat(const UnicodeString& pattern, UErrorCode& status);

    /**
     * Constructs a new MessageFormat using the given pattern and locale.
     * @param pattern   Pattern used to construct object.
     * @param newLocale The locale to use for formatting dates and numbers.
     * @param status    Input/output error code.  If the
     *                  pattern cannot be parsed, set to failure code.
     * @stable ICU 2.0
     */
    MessageFormat(const UnicodeString& pattern, const Locale& newLocale, UErrorCode& status);
    /**
     * Constructs a new MessageFormat using the given pattern and locale.
     * @param pattern   Pattern used to construct object.
     * @param newLocale The locale to use for formatting dates and numbers.
     * @param parseError Struct to receive information on the position
     *                   of an error within the pattern.
     * @param status    Input/output error code.  If the
     *                  pattern cannot be parsed, set to failure code.
     * @stable ICU 2.0
     */
    MessageFormat(const UnicodeString& pattern, const Locale& newLocale, UParseError& parseError, UErrorCode& status);
    /**
     * Constructs a new MessageFormat from an existing one.
     * @stable ICU 2.0
     */
    MessageFormat(const MessageFormat&);

    /**
     * Assignment operator.
     * @stable ICU 2.0
     */
    const MessageFormat& operator=(const MessageFormat&);

    /**
     * Destructor.
     * @stable ICU 2.0
     */
    virtual ~MessageFormat();

    /**
     * Clones this Format object polymorphically.  The caller owns the
     * result and should delete it when done.
     * @stable ICU 2.0
     */
    virtual Format* clone(void) const;

    /**
     * Returns true if the given Format objects are semantically equal.
     * Objects of different subclasses are considered unequal.
     * @param other  the object to be compared with.
     * @return       true if the given Format objects are semantically equal.
     * @stable ICU 2.0
     */
    virtual UBool operator==(const Format& other) const;

    /**
     * Sets the locale to be used for creating argument Format objects.
     * @param theLocale    the new locale value to be set.
     * @stable ICU 2.0
     */
    virtual void setLocale(const Locale& theLocale);

    /**
     * Gets the locale used for creating argument Format objects.
     * format information.
     * @return    the locale of the object.
     * @stable ICU 2.0
     */
    virtual const Locale& getLocale(void) const;

    /**
     * Applies the given pattern string to this message format.
     *
     * @param pattern   The pattern to be applied.
     * @param status    Input/output error code.  If the
     *                  pattern cannot be parsed, set to failure code.
     * @stable ICU 2.0
     */
    virtual void applyPattern(const UnicodeString& pattern, UErrorCode& status);
    /**
     * Applies the given pattern string to this message format.
     *
     * @param pattern    The pattern to be applied.
     * @param parseError Struct to receive information on the position
     *                   of an error within the pattern.
     * @param status    Input/output error code.  If the
     *                  pattern cannot be parsed, set to failure code.
     * @stable ICU 2.0
     */
    virtual void applyPattern(const UnicodeString& pattern, UParseError& parseError, UErrorCode& status);

    /**
     * Sets the UMessagePatternApostropheMode and the pattern used by this message format.
     * Parses the pattern and caches Format objects for simple argument types.
     * Patterns and their interpretation are specified in the
     * class description.
     *

     * This method is best used only once on a given object to avoid confusion about the mode,
     * and after constructing the object with an empty pattern string to minimize overhead.
     *
     * @param pattern    The pattern to be applied.
     * @param aposMode   The new apostrophe mode.
     * @param parseError Struct to receive information on the position
     *                   of an error within the pattern.
     *                   Can be NULL.
     * @param status    Input/output error code.  If the
     *                  pattern cannot be parsed, set to failure code.
     * @stable ICU 4.8
     */
    virtual void applyPattern(const UnicodeString& pattern,
                              UMessagePatternApostropheMode aposMode,
                              UParseError* parseError,
                              UErrorCode& status);

    /**
     * @return this instance's UMessagePatternApostropheMode.
     * @stable ICU 4.8
     */
    UMessagePatternApostropheMode getApostropheMode() const {
        return msgPattern.getApostropheMode();
    }

    /**
     * Returns a pattern that can be used to recreate this object.
     *
     * @param appendTo  Output parameter to receive the pattern.
     *                  Result is appended to existing contents.
     * @return          Reference to 'appendTo' parameter.
     * @stable ICU 2.0
     */
    virtual UnicodeString& toPattern(UnicodeString& appendTo) const;

    /**
     * Sets subformats.
     * See the class description about format numbering.
     * The caller should not delete the Format objects after this call.
     * The array formatsToAdopt is not itself adopted. Its
     * ownership is retained by the caller. If the call fails because
     * memory cannot be allocated, then the formats will be deleted
     * by this method, and this object will remain unchanged.
     *
     *
If this format uses named arguments, the new formats are discarded
     * and this format remains unchanged.
     *
     * @stable ICU 2.0
     * @param formatsToAdopt    the format to be adopted.
     * @param count             the size of the array.
     */
    virtual void adoptFormats(Format** formatsToAdopt, int32_t count);

    /**
     * Sets subformats.
     * See the class description about format numbering.
     * Each item in the array is cloned into the internal array.
     * If the call fails because memory cannot be allocated, then this
     * object will remain unchanged.
     *
     *
If this format uses named arguments, the new formats are discarded
     * and this format remains unchanged.
     *
     * @stable ICU 2.0
     * @param newFormats the new format to be set.
     * @param cnt        the size of the array.
     */
    virtual void setFormats(const Format** newFormats, int32_t cnt);

    /**
     * Sets one subformat.
     * See the class description about format numbering.
     * The caller should not delete the Format object after this call.
     * If the number is over the number of formats already set,
     * the item will be deleted and ignored.
     *
     *
If this format uses named arguments, the new format is discarded
     * and this format remains unchanged.
     *
     * @stable ICU 2.0
     * @param formatNumber     index of the subformat.
     * @param formatToAdopt    the format to be adopted.
     */
    virtual void adoptFormat(int32_t formatNumber, Format* formatToAdopt);

    /**
     * Sets one subformat.
     * See the class description about format numbering.
     * If the number is over the number of formats already set,
     * the item will be ignored.
     * @param formatNumber     index of the subformat.
     * @param format    the format to be set.
     * @stable ICU 2.0
     */
    virtual void setFormat(int32_t formatNumber, const Format& format);

    /**
     * Gets format names. This function returns formatNames in StringEnumerations
     * which can be used with getFormat() and setFormat() to export formattable
     * array from current MessageFormat to another.  It is the caller's responsibility
     * to delete the returned formatNames.
     * @param status  output param set to success/failure code.
     * @stable ICU 4.0
     */
    virtual StringEnumeration* getFormatNames(UErrorCode& status);

    /**
     * Gets subformat pointer for given format name.
     * This function supports both named and numbered
     * arguments. If numbered, the formatName is the
     * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
     * The returned Format object should not be deleted by the caller,
     * nor should the ponter of other object .  The pointer and its
     * contents remain valid only until the next call to any method
     * of this class is made with this object.
     * @param formatName the name or number specifying a format
     * @param status  output param set to success/failure code.
     * @stable ICU 4.0
     */
    virtual Format* getFormat(const UnicodeString& formatName, UErrorCode& status);

    /**
     * Sets one subformat for given format name.
     * See the class description about format name.
     * This function supports both named and numbered
     * arguments-- if numbered, the formatName is the
     * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
     * If there is no matched formatName or wrong type,
     * the item will be ignored.
     * @param formatName  Name of the subformat.
     * @param format      the format to be set.
     * @param status  output param set to success/failure code.
     * @stable ICU 4.0
     */
    virtual void setFormat(const UnicodeString& formatName, const Format& format, UErrorCode& status);

    /**
     * Sets one subformat for given format name.
     * See the class description about format name.
     * This function supports both named and numbered
     * arguments-- if numbered, the formatName is the
     * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
     * If there is no matched formatName or wrong type,
     * the item will be ignored.
     * The caller should not delete the Format object after this call.
     * @param formatName  Name of the subformat.
     * @param formatToAdopt  Format to be adopted.
     * @param status      output param set to success/failure code.
     * @stable ICU 4.0
     */
    virtual void adoptFormat(const UnicodeString& formatName, Format* formatToAdopt, UErrorCode& status);

    /**
     * Gets an array of subformats of this object.  The returned array
     * should not be deleted by the caller, nor should the pointers
     * within the array.  The array and its contents remain valid only
     * until the next call to this format. See the class description
     * about format numbering.
     *
     * @param count output parameter to receive the size of the array
     * @return an array of count Format* objects, or NULL if out of
     * memory.  Any or all of the array elements may be NULL.
     * @stable ICU 2.0
     */
    virtual const Format** getFormats(int32_t& count) const;

    using Format::format;

    /**
     * Formats the given array of arguments into a user-readable string.
     * Does not take ownership of the Formattable* array or its contents.
     *
     *
If this format uses named arguments, appendTo is unchanged and
     * status is set to U_ILLEGAL_ARGUMENT_ERROR.
     *
     * @param source    An array of objects to be formatted.
     * @param count     The number of elements of 'source'.
     * @param appendTo  Output parameter to receive result.
     *                  Result is appended to existing contents.
     * @param ignore    Not used; inherited from base class API.
     * @param status    Input/output error code.  If the
     *                  pattern cannot be parsed, set to failure code.
     * @return          Reference to 'appendTo' parameter.
     * @stable ICU 2.0
     */
    UnicodeString& format(
        const Formattable* source, int32_t count, UnicodeString& appendTo, FieldPosition& ignore, UErrorCode& status) const;

    /**
     * Formats the given array of arguments into a user-readable string
     * using the given pattern.
     *
     *
If this format uses named arguments, appendTo is unchanged and
     * status is set to U_ILLEGAL_ARGUMENT_ERROR.
     *
     * @param pattern   The pattern.
     * @param arguments An array of objects to be formatted.
     * @param count     The number of elements of 'source'.
     * @param appendTo  Output parameter to receive result.
     *                  Result is appended to existing contents.
     * @param status    Input/output error code.  If the
     *                  pattern cannot be parsed, set to failure code.
     * @return          Reference to 'appendTo' parameter.
     * @stable ICU 2.0
     */
    static UnicodeString& format(
        const UnicodeString& pattern, const Formattable* arguments, int32_t count, UnicodeString& appendTo, UErrorCode& status);

    /**
     * Formats the given array of arguments into a user-readable
     * string.  The array must be stored within a single Formattable
     * object of type kArray. If the Formattable object type is not of
     * type kArray, then returns a failing UErrorCode.
     *
     *
If this format uses named arguments, appendTo is unchanged and
     * status is set to U_ILLEGAL_ARGUMENT_ERROR.
     *
     * @param obj       A Formattable of type kArray containing
     *                  arguments to be formatted.
     * @param appendTo  Output parameter to receive result.
     *                  Result is appended to existing contents.
     * @param pos       On input: an alignment field, if desired.
     *                  On output: the offsets of the alignment field.
     * @param status    Input/output error code.  If the
     *                  pattern cannot be parsed, set to failure code.
     * @return          Reference to 'appendTo' parameter.
     * @stable ICU 2.0
     */
    virtual UnicodeString& format(const Formattable& obj, UnicodeString& appendTo, FieldPosition& pos, UErrorCode& status) const;

    /**
     * Formats the given array of arguments into a user-defined argument name
     * array. This function supports both named and numbered
     * arguments-- if numbered, the formatName is the
     * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
     *
     * @param argumentNames argument name array
     * @param arguments An array of objects to be formatted.
     * @param count     The number of elements of 'argumentNames' and
     *                  arguments.  The number of argumentNames and arguments
     *                  must be the same.
     * @param appendTo  Output parameter to receive result.
     *                  Result is appended to existing contents.
     * @param status    Input/output error code.  If the
     *                  pattern cannot be parsed, set to failure code.
     * @return          Reference to 'appendTo' parameter.
     * @stable ICU 4.0
     */
    UnicodeString& format(
        const UnicodeString* argumentNames, const Formattable* arguments, int32_t count, UnicodeString& appendTo, UErrorCode& status) const;
    /**
     * Parses the given string into an array of output arguments.
     *
     * @param source    String to be parsed.
     * @param pos       On input, starting position for parse. On output,
     *                  final position after parse.  Unchanged if parse
     *                  fails.
     * @param count     Output parameter to receive the number of arguments
     *                  parsed.
     * @return an array of parsed arguments.  The caller owns both
     * the array and its contents.
     * @stable ICU 2.0
     */
    virtual Formattable* parse(const UnicodeString& source, ParsePosition& pos, int32_t& count) const;

    /**
     * Parses the given string into an array of output arguments.
     *
     *
If this format uses named arguments, status is set to
     * U_ARGUMENT_TYPE_MISMATCH.
     *
     * @param source    String to be parsed.
     * @param count     Output param to receive size of returned array.
     * @param status    Input/output error code.  If the
     *                  pattern cannot be parsed, set to failure code.
     * @return an array of parsed arguments.  The caller owns both
     * the array and its contents. Returns NULL if status is not U_ZERO_ERROR.
     *
     * @stable ICU 2.0
     */
    virtual Formattable* parse(const UnicodeString& source, int32_t& count, UErrorCode& status) const;

    /**
     * Parses the given string into an array of output arguments
     * stored within a single Formattable of type kArray.
     *
     * @param source    The string to be parsed into an object.
     * @param result    Formattable to be set to the parse result.
     *                  If parse fails, return contents are undefined.
     * @param pos       On input, starting position for parse. On output,
     *                  final position after parse.  Unchanged if parse
     *                  fails.
     * @stable ICU 2.0
     */
    virtual void parseObject(const UnicodeString& source, Formattable& result, ParsePosition& pos) const;

    /**
     * Convert an 'apostrophe-friendly' pattern into a standard
     * pattern.  Standard patterns treat all apostrophes as
     * quotes, which is problematic in some languages, e.g.
     * French, where apostrophe is commonly used.  This utility
     * assumes that only an unpaired apostrophe immediately before
     * a brace is a true quote.  Other unpaired apostrophes are paired,
     * and the resulting standard pattern string is returned.
     *
     *
Note it is not guaranteed that the returned pattern
     * is indeed a valid pattern.  The only effect is to convert
     * between patterns having different quoting semantics.
     *
     * @param pattern the 'apostrophe-friendly' patttern to convert
     * @param status    Input/output error code.  If the pattern
     *                  cannot be parsed, the failure code is set.
     * @return the standard equivalent of the original pattern
     * @stable ICU 3.4
     */
    static UnicodeString autoQuoteApostrophe(const UnicodeString& pattern, UErrorCode& status);

    /**
     * Returns true if this MessageFormat uses named arguments,
     * and false otherwise.  See class description.
     *
     * @return true if named arguments are used.
     * @stable ICU 4.0
     */
    UBool usesNamedArguments() const;

#ifndef U_HIDE_INTERNAL_API
    /**
     * This API is for ICU internal use only.
     * Please do not use it.
     *
     * Returns argument types count in the parsed pattern.
     * Used to distinguish pattern "{0} d" and "d".
     *
     * @return           The number of formattable types in the pattern
     * @internal
     */
    int32_t getArgTypeCount() const;
#endif /* U_HIDE_INTERNAL_API */

    /**
     * Returns a unique class ID POLYMORPHICALLY.  Pure virtual override.
     * This method is to implement a simple version of RTTI, since not all
     * C++ compilers support genuine RTTI.  Polymorphic operator==() and
     * clone() methods call this method.
     *
     * @return          The class ID for this object. All objects of a
     *                  given class have the same class ID.  Objects of
     *                  other classes have different class IDs.
     * @stable ICU 2.0
     */
    virtual UClassID getDynamicClassID(void) const;

    /**
     * Return the class ID for this class.  This is useful only for
     * comparing to a return value from getDynamicClassID().  For example:
     *

     * .   Base* polymorphic_pointer = createPolymorphicObject();
     * .   if (polymorphic_pointer->getDynamicClassID() ==
     * .      Derived::getStaticClassID()) ...
     *

     * @return          The class ID for all objects of this class.
     * @stable ICU 2.0
     */
    static UClassID U_EXPORT2 getStaticClassID(void);

#ifndef U_HIDE_INTERNAL_API
    /**
     * Compares two Format objects. This is used for constructing the hash
     * tables.
     *
     * @param left pointer to a Format object. Must not be NULL.
     * @param right pointer to a Format object. Must not be NULL.
     *
     * @return whether the two objects are the same
     * @internal
     */
    static UBool equalFormats(const void* left, const void* right);
#endif /* U_HIDE_INTERNAL_API */

private:
    Locale fLocale;
    MessagePattern msgPattern;
    Format** formatAliases; // see getFormats
    int32_t formatAliasesCapacity;

    MessageFormat(); // default constructor not implemented

    /**
     * This provider helps defer instantiation of a PluralRules object
     * until we actually need to select a keyword.
     * For example, if the number matches an explicit-value selector like "=1"
     * we do not need any PluralRules.
     */
    class U_I18N_API PluralSelectorProvider : public PluralFormat::PluralSelector {
    public:
        PluralSelectorProvider(const MessageFormat& mf, UPluralType type);
        virtual ~PluralSelectorProvider();
        virtual UnicodeString select(void* ctx, double number, UErrorCode& ec) const;

        void reset();

    private:
        const MessageFormat& msgFormat;
        PluralRules* rules;
        UPluralType type;
    };

    /**
     * A MessageFormat formats an array of arguments.  Each argument
     * has an expected type, based on the pattern.  For example, if
     * the pattern contains the subformat "{3,number,integer}", then
     * we expect argument 3 to have type Formattable::kLong.  This
     * array needs to grow dynamically if the MessageFormat is
     * modified.
     */
    Formattable::Type* argTypes;
    int32_t argTypeCount;
    int32_t argTypeCapacity;

    /**
     * TRUE if there are different argTypes for the same argument.
     * This only matters when the MessageFormat is used in the plain C (umsg_xxx) API
     * where the pattern argTypes determine how the va_arg list is read.
     */
    UBool hasArgTypeConflicts;

    // Variable-size array management
    UBool allocateArgTypes(int32_t capacity, UErrorCode& status);

    /**
     * Default Format objects used when no format is specified and a
     * numeric or date argument is formatted.  These are volatile
     * cache objects maintained only for performance.  They do not
     * participate in operator=(), copy constructor(), nor
     * operator==().
     */
    NumberFormat* defaultNumberFormat;
    DateFormat* defaultDateFormat;

    UHashtable* cachedFormatters;
    UHashtable* customFormatArgStarts;

    PluralSelectorProvider pluralProvider;
    PluralSelectorProvider ordinalProvider;

    /**
     * Method to retrieve default formats (or NULL on failure).
     * These are semantically const, but may modify *this.
     */
    const NumberFormat* getDefaultNumberFormat(UErrorCode&) const;
    const DateFormat* getDefaultDateFormat(UErrorCode&) const;

    /**
     * Finds the word s, in the keyword list and returns the located index.
     * @param s the keyword to be searched for.
     * @param list the list of keywords to be searched with.
     * @return the index of the list which matches the keyword s.
     */
    static int32_t findKeyword(const UnicodeString& s, const UChar* const* list);

    /**
     * Thin wrapper around the format(... AppendableWrapper ...) variant.
     * Wraps the destination UnicodeString into an AppendableWrapper and
     * supplies default values for some other parameters.
     */
    UnicodeString& format(const Formattable* arguments,
                          const UnicodeString* argumentNames,
                          int32_t cnt,
                          UnicodeString& appendTo,
                          FieldPosition* pos,
                          UErrorCode& status) const;

    /**
     * Formats the arguments and writes the result into the
     * AppendableWrapper, updates the field position.
     *
     * @param msgStart      Index to msgPattern part to start formatting from.
     * @param plNumber      NULL except when formatting a plural argument sub-message
     *                      where a '#' is replaced by the format string for this number.
     * @param arguments     The formattable objects array. (Must not be NULL.)
     * @param argumentNames NULL if numbered values are used. Otherwise the same
     *                      length as "arguments", and each entry is the name of the
     *                      corresponding argument in "arguments".
     * @param cnt           The length of arguments (and of argumentNames if that is not NULL).
     * @param appendTo      Output parameter to receive the result.
     *                      The result string is appended to existing contents.
     * @param pos           Field position status.
     * @param success       The error code status.
     */
    void format(int32_t msgStart,
                const void* plNumber,
                const Formattable* arguments,
                const UnicodeString* argumentNames,
                int32_t cnt,
                AppendableWrapper& appendTo,
                FieldPosition* pos,
                UErrorCode& success) const;

    UnicodeString getArgName(int32_t partIndex);

    void setArgStartFormat(int32_t argStart, Format* formatter, UErrorCode& status);

    void setCustomArgStartFormat(int32_t argStart, Format* formatter, UErrorCode& status);

    int32_t nextTopLevelArgStart(int32_t partIndex) const;

    UBool argNameMatches(int32_t partIndex, const UnicodeString& argName, int32_t argNumber);

    void cacheExplicitFormats(UErrorCode& status);

    Format* createAppropriateFormat(
        UnicodeString& type, UnicodeString& style, Formattable::Type& formattableType, UParseError& parseError, UErrorCode& ec);

    const Formattable* getArgFromListByName(const Formattable* arguments,
                                            const UnicodeString* argumentNames,
                                            int32_t cnt,
                                            UnicodeString& name) const;

    Formattable* parse(int32_t msgStart, const UnicodeString& source, ParsePosition& pos, int32_t& count, UErrorCode& ec) const;

    FieldPosition* updateMetaData(AppendableWrapper& dest, int32_t prevLength, FieldPosition* fp, const Formattable* argId) const;

    /**
     * Finds the "other" sub-message.
     * @param partIndex the index of the first PluralFormat argument style part.
     * @return the "other" sub-message start part index.
     */
    int32_t findOtherSubMessage(int32_t partIndex) const;

    /**
     * Returns the ARG_START index of the first occurrence of the plural number in a sub-message.
     * Returns -1 if it is a REPLACE_NUMBER.
     * Returns 0 if there is neither.
     */
    int32_t findFirstPluralNumberArg(int32_t msgStart, const UnicodeString& argName) const;

    Format* getCachedFormatter(int32_t argumentNumber) const;

    UnicodeString getLiteralStringUntilNextArgument(int32_t from) const;

    void copyObjects(const MessageFormat& that, UErrorCode& ec);

    void formatComplexSubMessage(int32_t msgStart,
                                 const void* plNumber,
                                 const Formattable* arguments,
                                 const UnicodeString* argumentNames,
                                 int32_t cnt,
                                 AppendableWrapper& appendTo,
                                 UErrorCode& success) const;

    /**
     * Convenience method that ought to be in NumberFormat
     */
    NumberFormat* createIntegerFormat(const Locale& locale, UErrorCode& status) const;

    /**
     * Returns array of argument types in the parsed pattern
     * for use in C API.  Only for the use of umsg_vformat().  Not
     * for public consumption.
     * @param listCount  Output parameter to receive the size of array
     * @return           The array of formattable types in the pattern
     */
    const Formattable::Type* getArgTypeList(int32_t& listCount) const {
        listCount = argTypeCount;
        return argTypes;
    }

    /**
     * Resets the internal MessagePattern, and other associated caches.
     */
    void resetPattern();

    /**
     * A DummyFormatter that we use solely to store a NULL value. UHash does
     * not support storing NULL values.
     */
    class U_I18N_API DummyFormat : public Format {
    public:
        virtual UBool operator==(const Format&) const;
        virtual Format* clone() const;
        virtual UnicodeString& format(const Formattable& obj, UnicodeString& appendTo, UErrorCode& status) const;
        virtual UnicodeString& format(const Formattable&, UnicodeString& appendTo, FieldPosition&, UErrorCode& status) const;
        virtual UnicodeString& format(const Formattable& obj,
                                      UnicodeString& appendTo,
                                      FieldPositionIterator* posIter,
                                      UErrorCode& status) const;
        virtual void parseObject(const UnicodeString&, Formattable&, ParsePosition&) const;
    };

    friend class MessageFormatAdapter; // getFormatTypeList() access
};

U_NAMESPACE_END

#endif /* #if !UCONFIG_NO_FORMATTING */

#endif // _MSGFMT
// eof


text:
static UIImage *checkImageNormal()
{
    static UIImage *image = nil;
    if (image == nil)
        image = [UIImage imageNamed:@"ImagePickerThumbnalSelect.png"];
    return image;
}

static UIImage *checkImageChecked()
{
    static UIImage *image = nil;
    if (image == nil)
        image = [UIImage imageNamed:@"ImagePickerThumbnalSelect_Checked.png"];
    return image;
}

@interface TGImagePickerCellCheckButton ()
{
    bool _checked;
}

@end

@implementation TGImagePickerCellCheckButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self != nil)
    {
        [self commonInit];
    }
    return self;
}

- (id)init
{
    self = [super init];
    if (self != nil)
    {
        [self commonInit];
    }
    return self;
}

- (void)commonInit
{
    _checkView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 33, 33)];
    [self addSubview:_checkView];
}

- (void)setHighlighted:(BOOL)highlighted
{
    [super setHighlighted:highlighted];

    if (highlighted)
        _checkView.transform = CGAffineTransformMakeScale(0.8f, 0.8f);
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    _checkView.transform = CGAffineTransformIdentity;

    [super touchesCancelled:touches withEvent:event];
}

- (bool)checked
{
    return _checked;
}

- (void)setChecked:(bool)checked animated:(bool)animated
{
    _checked = checked;

    _checkView.image = checked ? checkImageChecked() : checkImageNormal();

    if (animated)
    {
        _checkView.transform = CGAffineTransformMakeScale(0.8f, 0.8f);
        if (checked)
        {
            [UIView animateWithDuration:0.12 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^
             {
                 _checkView.transform = CGAffineTransformMakeScale(1.16f, 1.16f);
             } completion:^(BOOL finished)
             {
                 if (finished)
                 {
                     [UIView animateWithDuration:0.08 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^
                      {
                          _checkView.transform = CGAffineTransformIdentity;
                      } completion:nil];
                 }
             }];
        }
        else
        {
            [UIView animateWithDuration:0.16 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^
            {
                _checkView.transform = CGAffineTransformIdentity;
            } completion:nil];
        }
    }
    else
    {
        _checkView.transform = CGAffineTransformIdentity;
    }
}

@end


text:
import Ember from 'ember';

export default Ember.Route.extend({
    model() {
        return new Ember.RSVP.Promise(function(resolve, reject){
            setTimeout(function(){
                resolve([{name:'hello I am fetched from google'}]);
            }, 5000);
        });
    },
    actions: {
        loading(transition, originRoute) {
            console.log('I am status.google loading event');
            // Bubble the event
            return true;
        },
        error(transition, originRoute) {
            console.log('I am google error event');
            // Bubble the event
            return true;
        },
    }
});


text:
**Version 0.9.1, (c) Song LIU**
## Overview
HK Dataminer is a python library for constructing statistical models for bimolecular dynamics data. The package includes complementary data mining algorithms such as clustering and Markov state models (MSMs).

# Installation guide
## I. Package requirement
* [Python v3.7](https://www.python.org)
* [NumPy v1.1.8](https://numpy.org)
* [SciPy v1.17.0](https://www.scipy.org)
* [MDTraj 1.9.3](mdtraj.org)
* [Scikit-Learn v0.21.3](https://scikit-learn.org)
* [Matplotlib](https://matplotlib.org)
* [Xmipp](http://xmipp.i2pc.es/)
## II.Installing
We highly recommend that you download the Python 3.7 version of Anaconda, which is a completely free enterprise-ready Python distribution for large-scale data processing, predictive analytics, and scientific computing.

# A step-by-step guide of running HKDataminer
## 1.Introduction and Alanine Dipeptide

## 2.Move to tutorial directory Assuming you've in the MD Data Miner folder, move to the Tutorial directory.
`cd Tutorial`

## 3.Cluster your data The following command clusters your data using the RMSD metric by k-centers clustering method.
`python ../scripts/test_kcenters.py  -n 500`

After Clustering, the assignments of each conformation are stored as assignments.txt, the cluster centers are sotred as generators.txt.

## 4.Lump microstates into macrostates
Once we have determined the number of macrostates in the system, we will use Perron Cluster CLuster Analysis (PCCA) algorithm to lump microstates into macrostates. We use the doLumping.py script to lump the microstates into macrostates. We could define the number of macrostates using -n option.The command below will build 4 macrostates.

`python ../scripts/doLumping.py -c assignments_kcenters_n_500.txt -m 6`

Examining the macrostate decomposition It is known that the relevant degrees of freedom for alanine dipeptide are the phi and psi backbone angles. Let's compute the dihedrals and plot the conformations of each macrostate.

## 5.Template matching to obtain popuplations in multiplr conformtions of cryo-EM dataset
Template matching project: aimed to use the templates to match the multiple structures (conformations) so that obtain the equilibrium distributions
in different conformations.
There are three steps: 1. select the best viewing angle which can distinguish the multiple conformations well. 2. project the 3D volumes into 2D
images for both templates and experimental volumes. 3. two-stage matching to obtain the populations of multiple conformations.

requirements: python, linux system and xmipp

Dataset: Each dataset is consisted of template structures and experimental structures. We use two expmples to test our algorithm, one is
simulation dataset, the other is real dataset. We provide simualtion dataset: open.vol, close.vol, intermediate.vol(same as test data and templates)
and real dataset:6P1K.vol(test data), H_EV2_red.vol, H_EV2_grey.vol, H_EV2_blue.vol(templates)

Preprocess: you can use command:
`xmipp_xmipp_volume_from_pdb -i open.pdb -o open.vol`     transfer pdb file to vol file

`xmipp_image_convert -i open.vol -o open.mrc`            transfer vol file to mrc file

run our algorithm: `python TSTM.py --datatype='sim' --vol_size=128`, the output is '2nd_stage_brute_force_classification_result.dat'

and `python ./two_stage_matching/analyze_population.py` to obatin population

# Deployment
HKUST method is developed by [Prof. Xuhui Huang's group](http://compbio.ust.hk)

# Authors
* **Prof. Xuhui Huang** - *Project leader* - [xuhuihuang](http://compbio.ust.hk/public_html/pmwiki-2.2.8/pmwiki.php?n=People.XuhuiHuang)
* **Mr. Song Liu** - *Developer* -[liusong299](https://github.com/liusong299/)

See also the list of [contributors](https://github.com/liusong299/gromacs-2019-CWBSol/graphs/contributors) who participated in this project.

# License
This project is licensed under the GPL License - see the [LICENSE](LICENSE) file for details

# Acknowledgments

# References:


text:
brew tap homebrew/cask-versions
brew tap homebrew/cask-drivers
brew tap homebrew/cask-fonts

# Install packages

apps=(
  alfred
  android-platform-tools
  android-studio
  dropbox
  clamxav
  jumpcut
  macdown
  microsoft-office
  microsoft-teams
  skype
  slack
  spotify
  vlc
  imageoptim
  firefox
  chromium
  opera
  brave-browser
  iterm2
  visual-studio-code
  github
  transmit
  virtualbox
  postman
  sublime-text
  sketch
  tableplus
  docker
  kitematic
  # Quick Look Plugins (https://github.com/sindresorhus/quick-look-plugins)
  qlstephen
  qlmarkdown
  quicklook-json
  qlprettypatch
  quicklook-csv
  suspicious-package
)

brew install "${apps[@]}"

# Link Hammerspoon config
[ -d ~/.hammerspoon ] || ln -sfv "$DOTFILES_DIR/etc/hammerspoon/" ~/.hammerspoon

apps=(
    font-fira-code
    font-montserrat
    font-muli
    font-playfair-display
    font-playfair-display-sc
    font-quicksand
    font-source-sans-pro
    font-ubuntu
    font-dejavu-sans
    font-fira-code
    font-josefin-sans
    font-museo
    font-open-sans
    font-roboto
)

brew install "${apps[@]}"


text:
package org.drools.core.util;

import org.drools.core.common.InternalFactHandle;

public interface FactEntry {
    public InternalFactHandle getFactHandle();
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Journal of the Asiatic Society of Bengal 58(2): 250 (1889)

#### Original name
Puccinia caricis-filicinae Barclay

### Remarks
null


text:
from ABACGuard import *
from ArgumentCheck import *
import tools.MA_constants as MA
from tools.chapi_log import *
from tools.policy_file_checker import PolicyFileChecker

# Specific guard for GPO MA
# Provide a set of invocation checks and row checks per method
class MAv1Guard(ABACGuardBase):

# Methods
#   def get_version(self):
#    def lookup_public_member_info(self, credentials, options):
#    def lookup_private_member_info(self, credentials, options):
#    def lookup_identifying_member_info(self, credentials, options):
#    def update_member_info(self, member_urn, credentials, options):
#    def create_key(self, member_urn, credentials, options):
#    def delete_key(self, member_urn, key_id, credentials, options):
#    def update_key(self, member_urn, key_id, credentials, options):
#    def lookup_keys(self, credentials, options):
#    def create_certificate(self, member_urn, credentials, options):

    # Set of argument checks indexed by method name
    ARGUMENT_CHECK_FOR_METHOD = \
        {
        'lookup_public_member_info' : \
            LookupArgumentCheck(select_fields(MA.standard_fields, \
                                              MA.public_fields), \
                                select_fields(MA.optional_fields, \
                                              MA.public_fields), \
                                select_fields(MA.standard_plus_optional, \
                                              MA.match_fields)),
        'lookup_private_member_info' : \
            LookupArgumentCheck(select_fields(MA.standard_fields, \
                                              MA.private_fields), \
                                select_fields(MA.optional_fields, \
                                              MA.private_fields), \
                                select_fields(MA.standard_plus_optional, \
                                              MA.match_fields)),
        'lookup_identifying_member_info' : \
            LookupArgumentCheck(select_fields(MA.standard_fields, \
                                              MA.identifying_fields), \
                                select_fields(MA.optional_fields, \
                                              MA.identifying_fields), \
                                select_fields(MA.standard_plus_optional, \
                                              MA.match_fields)),
        'lookup_public_identifying_member_info' : \
            LookupArgumentCheck(select_fields(MA.standard_fields, \
                                              MA.public_fields+MA.identifying_fields), \
                                select_fields(MA.optional_fields, \
                                              MA.public_fields+MA.identifying_fields), \
                                select_fields(MA.standard_plus_optional, \
                                              MA.match_fields)),
        'lookup_login_info' : \
            LookupArgumentCheck(select_fields(MA.standard_fields, \
                                                  MA.public_fields+MA.identifying_fields+MA.private_fields),
                                select_fields(MA.optional_fields,
                                                  MA.public_fields+MA.identifying_fields+MA.private_fields),
                                ['_GENI_MEMBER_EPPN']),
        'get_credentials' : SimpleArgumentCheck({'member_urn' : 'URN'}),
        'update_member_info' :  \
            UpdateArgumentCheck({}, {}, {'member_urn' : "URN"}),

        'create_key' : \
            CreateArgumentCheck(select_fields(MA.standard_key_fields, \
                                           MA.allowed_create_key_fields), \
                                    select_fields(MA.optional_key_fields, \
                                           MA.allowed_create_key_fields)),
        'delete_key' : \
            None,
        'update_key' : \
            UpdateArgumentCheck(select_fields(MA.standard_key_fields, \
                                                  MA.updatable_key_fields), \
                                    select_fields(MA.optional_key_fields, \
                                                      MA.updatable_key_fields),
                                {'key_id' : 'STRING'}),
        'lookup_keys' : \
            LookupArgumentCheck(MA.standard_key_fields, \
                                    MA.optional_key_fields),
        'create_certificate' : \
            None,
        'create_member' : \
            None, # Check is done in create_member itself

        'list_clients' : None,
        'list_authorized_clients' : None,
        'authorize_client' : None,
        'enable_user': None,
        'add_member_privilege': None,
        'revoke_member_privilege': None,
        'add_member_attribute': SimpleArgumentCheck({'member_urn' : 'URN',
                                                     'name' : 'STRING',
                                                     'value' : 'STRING',
                                                     'self_asserted' : 'STRING'}),
        'remove_member_attribute': SimpleArgumentCheck({'member_urn' : 'URN',
                                                        'name' : 'STRING',
                                                        'value' : 'STRING'
                                                        }),
        }

    # Set of invocation checks indexed by method name
    INVOCATION_CHECK_FOR_METHOD = None

    # Name of policies file
    policies_filename = "/etc/geni-chapi/member_authority_policy.json"

    # Thread to check whether the policies file has changed
    policies_file_checker = None

    # Lookup argument check per method (or None if none registered)
    def get_argument_check(self, method):
        if self.ARGUMENT_CHECK_FOR_METHOD.has_key(method):
            return self.ARGUMENT_CHECK_FOR_METHOD[method]
        return None

    # Lookup invocation check per method (or None if none registered)
    def get_invocation_check(self, method):
        # Initiate file check thread
        if self.policies_file_checker == None:
            self.policies_file_checker = \
                PolicyFileChecker(self.policies_filename, 5, \
                                      self, MA_LOG_PREFIX)
            self.policies_file_checker.start()

        if self.INVOCATION_CHECK_FOR_METHOD == None:
            policies = \
                parse_method_policies(self.policies_filename)
            self.INVOCATION_CHECK_FOR_METHOD = \
                create_subject_invocation_checks(self, policies)
        if self.INVOCATION_CHECK_FOR_METHOD.has_key(method):
            return self.INVOCATION_CHECK_FOR_METHOD[method]
        return None


text:
SMS-Mailing-List
================

A mailing list application using the Twilio API


text:
<?php

namespace Cert\IncidentBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * IncidentRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class IncidentRepository extends EntityRepository
{
}


text:
'''
An API to assist with the creation and enforcement of cortex data models.
'''
import fnmatch
import functools
import collections
import logging

import regex

import synapse.common as s_common

import synapse.lib.tags as s_tags
import synapse.lib.types as s_types

logger = logging.getLogger(__name__)

hexre = regex.compile('^[0-9a-z]+$')
propre = regex.compile('^[0-9a-z:_]+$')

tlib = s_types.TypeLib()

def rebuildTlib():
    '''
    Rebuild the datamodel's global TypeLib instance.

    The datamodel.py module maintains a instance of the TypeLib object.  If there are new models dynamically loaded
    into Synapse, this can be used to rebuild the TypeLib object with those additions.

    Returns:
        (None): Returns None.
    '''
    global tlib
    tlib = s_types.TypeLib()

def getTypeRepr(name, valu):
    '''
    Return the humon readable form of the given type value.
    '''
    return tlib.reqDataType(name).repr(valu)

def getTypeNorm(name, valu):
    '''
    Normalize a type specific value in system mode.
    '''
    return tlib.reqDataType(name).norm(valu)

def getTypeParse(name, text):
    '''
    Parse input text for the given type into it's system form.
    '''
    return tlib.reqDataType(name).parse(text)

def parsetypes(*atypes, **kwtypes):
    '''
    Decorator to parse input args from humon to system values.

    Example:

        class Woot:

            @parsetypes('int','hash:md5')
            def getFooBar(self, size, md5):
                # size will be an int and md5 will be lower
                dostuff()

        woot = Woot()

        # call with user input strings...
        woot.getFooBar('20','0a0a0a0a0B0B0B0B0c0c0c0c0D0D0D0D')

    '''
    #typeargs = [ basetypes.get(a) for a in atypes ]
    #typekwargs = { k:basetypes.get(v) for (k,v) in kwtypes.items() }

    def wrapfunc(f):

        def runfunc(self, *args, **kwargs):

            try:
                args = [getTypeParse(atypes[i], args[i])[0] for i in range(len(args))]
                kwargs = {k: getTypeParse(kwtypes[k], v)[0] for (k, v) in kwargs.items()}

            except IndexError as e:
                raise Exception('parsetypes() too many args in: %s' % (f.__name__,))

            except KeyError as e:
                raise Exception('parsetypes() no such kwtype in: %s' % (f.__name__,))

            return f(self, *args, **kwargs)

        functools.update_wrapper(runfunc, f)
        return runfunc

    return wrapfunc

class DataModel(s_types.TypeLib):

    def __init__(self, load=True):
        self.props = {}
        self.forms = set()

        self.reqprops = collections.defaultdict(list)
        self.defvals = collections.defaultdict(list)
        self.subprops = collections.defaultdict(list)
        self.propsbytype = collections.defaultdict(list)
        self.propsdtyp = {}
        self.uniprops = set()
        self.unipropsreq = set()

        self._type_hooks = collections.defaultdict(list)

        self.globs = []
        self.cache = {} # for globs
        self.model = {
            'ver': (0, 0, 0),
            'enums': {},
            'props': {},
            'globs': {},
            'forms': [],
        }

        s_types.TypeLib.__init__(self, load=load)
        self._initUniversalProps()

    def _initUniversalProps(self):
        '''
        Initialize universal properties in the DataModel.
        These properties are not bound to a specific form and may be present on a node.
        '''
        self.addPropDef('tufo:form',
                        ptype='str',
                        doc='The form of the node',
                        ro=1,
                        req=1,
                        univ=1,
                        )
        self.addPropDef('node:created',
                        ptype='time',
                        doc='The time the node was created',
                        ro=1,
                        req=1,
                        univ=1,
                        )
        self.addPropDef('node:ndef',
                        ptype='ndef',
                        doc='The unique guid representing the combination of the node form and primary property.',
                        ro=1,
                        req=1,
                        univ=1)

    def getModelDict(self):
        '''
        Returns a dictionary which represents the data model.
        '''
        return dict(self.model)

    def _addDataModels(self, modtups):
        '''
        Load a list of (name,modl) tuples into the DataModel.
        '''
        # first load all the types...
        s_types.TypeLib._addDataModels(self, modtups)

        for name, modl in modtups:

            for form, info, props in modl.get('forms', ()):
                self.addTufoForm(form, **info)

                for prop, pnfo in props:
                    self.addTufoProp(form, prop, **pnfo)

    def addTufoForm(self, form, **info):
        '''
        Add a tufo form to the data model

        Example:

            # must add tufo before adding tufo props
            model.addTufoForm('woot')

        Raises:
            BadPropName: If the property name is poorly formed.
        '''
        if not propre.match(form):
            raise s_common.BadPropName(name=form)

        if info.get('ptype') is None:
            if self.isDataType(form):
                info['ptype'] = form
            else:
                info['ptype'] = 'str'

        self.forms.add(form)

        info['form'] = form
        self.model['forms'].append(form)
        return self.addPropDef(form, **info)

    def isTufoForm(self, name):
        '''
        Check if a form is a valid form.

        Args:
            name (str): Form to check

        Returns:
            bool: True if the form is a valid form. False otherwise.
        '''
        return name in self.forms

    def isTufoProp(self, name):
        '''
        Check if a prop is a valid prop.

        Args:
            name (str): Prop to check

        Returns:
            bool: True if the prop is a valid form. False otherwise.
        '''
        return name in self.props

    def reqTufoForm(self, name):
        '''
        Check if a form is a valid form, raise an exception otherwise.

        Args:
            name (str): Form to check

        Raises:
            NoSuchForm: If the form does not exist in the datamodel.
        '''
        ret = self.isTufoForm(name)
        if not ret:
            raise s_common.NoSuchForm(name=name)

    def getTufoForms(self):
        '''
        Get a list of the currently loaded tufo forms.

        Returns:
            list: List of forms.
        '''
        return list(self.forms)

    def getUnivProps(self):
        '''
        Get a list of the universal tufo props.

        Returns:
            list: List of universal tufo props
        '''
        return list(self.uniprops)

    def addTufoProp(self, form, prop, **info):
        '''
        Add a property to the data model.

        Example:

            # all foo tufos must have a foo:bar property
            model.addTufoProp('foo', 'bar', ptype='int', defval=0)

        '''
        pdef = self.getPropDef(form)
        if pdef is None:
            raise s_common.NoSuchForm(name=form)

        if info.get('glob'):
            self._addPropGlob(form, prop, **info)
            return

        info['form'] = form
        fullprop = '%s:%s' % (form, prop)

        if not propre.match(fullprop):
            raise s_common.BadPropName(name=fullprop)

        self.addPropDef(fullprop, **info)

    def getPropFormBase(self, prop):
        '''
        Return a form,base tuple for the name parts of a given property.

        Example:

        Args:
            prop (str): The fully qualified property name

        Returns:
            ((str,str)):  The (form,base) name tuple for the prop.

        '''
        pdef = self.getPropDef(prop)
        if pdef is None:
            raise s_common.NoSuchProp(name=prop)

        return pdef[1].get('form'), pdef[1].get('base')

    def addPropDef(self, prop, **info):
        '''
        Add a property definition to the DataModel.

        Example:

            model.addPropDef('foo:bar', ptype='int', defval=30)

        Returns:
            ((str, dict)): Retuns the prop, property definition tuple.

        Raises:
            DupPropName: If the property name is already present in the data model.
            BadPropConf: If the propety has an invalid configuration.
        '''
        if self.props.get(prop) is not None:
            raise s_common.DupPropName(name=prop)

        info.setdefault('ptype', None)
        info.setdefault('doc', self.getTypeInfo(info.get('ptype'), 'doc', ''))
        info.setdefault('req', False)
        info.setdefault('title', self.getTypeInfo(info.get('ptype'), 'title', ''))
        info.setdefault('defval', None)
        info.setdefault('univ', False)

        univ = info.get('univ')
        form = info.get('form')
        if form and univ:
            raise s_common.BadPropConf(mesg='Universal props cannot be set on forms.',
                                       prop=prop, form=form,)
        relname = None
        if form:
            relname = prop[len(form) + 1:]
            if relname:
                info['relname'] = relname

        if ':' in prop:
            _, base = prop.rsplit(':', 1)
            info.setdefault('base', base)

        defval = info.get('defval')

        if defval is not None:
            self.defvals[form].append((prop, defval))

        req = info.get('req')
        if req:
            self.reqprops[form].append(prop)

        pdef = (prop, info)

        ptype = info.get('ptype')
        if ptype is not None:
            dtyp = self.reqDataType(ptype)
            pdtyp = dtyp.extend(dtyp.name, prop=prop)
            self.propsbytype[ptype].append(pdef)
            self.propsdtyp[prop] = pdtyp

        self.props[prop] = pdef
        if relname:
            self.props[(form, relname)] = pdef

        self.model['props'][prop] = pdef

        if univ:
            self.uniprops.add(prop)
            if info.get('req'):
                self.unipropsreq.add(prop)

        self._addSubRefs(pdef)

        if ptype is not None:
            for func in self._type_hooks.get(ptype, ()):
                func(pdef)

        return pdef

    def addPropTypeHook(self, name, func):
        '''
        Add a callback function for props declared from a given type.

        Args:
            name (str): The name of a type to hook props
            func (function): A function callback

        Example:
            def func(pdef):
                dostuff(pdef)

            modl.addPropTypeHook('foo:bar', func)

        NOTE: This will be called immediately for existing props and
              incrementally as future props are declared using the type.
        '''
        for pdef in self.propsbytype.get(name, ()):
            func(pdef)

        self._type_hooks[name].append(func)

    def getFormDefs(self, form):
        '''
        Return a list of (prop,valu) tuples for the default values of a form.
        '''
        return self.defvals.get(form, ())

    def getFormReqs(self, form):
        '''
        Return a list of prop values which are required form a form.

        Args:
            form (str): Form to request values for.

        Returns:
            list: List of required properties needed for making the given form.
        '''
        return self.reqprops.get(form, ())

    def _addSubRefs(self, pdef):
        name = pdef[0]
        for prop in s_tags.iterTagUp(pdef[0], div=':'):
            if prop == pdef[0]:
                continue
            self.subprops[prop].append(pdef)

    def getPropsByType(self, name):
        '''
        Return a list of prop def tuples (name,info) for all props of the given type.

        Example:

            for prop,info in modl.getPropsByType('guid'):
                dostuff()

        '''
        return self.propsbytype.get(name, ())

    def _addPropGlob(self, form, prop, **info):
        prop = '%s:%s' % (form, prop)
        info['form'] = form
        self.globs.append((prop, info))

    def getSubProps(self, prop):
        '''
        Return a list of (name,info) prop defs for all sub props.

        Example:

            for pdef in model.getSubProps('foo:bar'):
                dostuff(pdef)

        '''
        return self.subprops.get(prop, ())

    def getSubPropDefs(self, prop):
        '''
        Return a dict of defvals for props under prop.
        '''
        ret = {}
        for pdef in self.getSubProps(prop):
            valu = pdef[1].get('defval')
            if valu is None:
                continue

            ret[pdef[0]] = valu

        return ret

    def getPropRepr(self, prop, valu):
        '''
        Return the humon readable representation for a property.

        Example:
            valu = tufo[1].get(prop)
            x = model.getPropRepr(prop, valu)

        '''
        dtype = self.getPropType(prop)
        if dtype is None:
            return str(valu)

        return dtype.repr(valu)

    def getPropTypeName(self, prop):
        '''
        Retrieve the name of the type for the given property.

        Args:
            prop (str): The property

        Returns:
            (str):  The type name (or None)
        '''
        pdef = self.getPropDef(prop)
        if pdef is None:
            return None

        return pdef[1].get('ptype')

    def getTypeOfs(self, name):
        '''
        Return a list of type inheritence (including specified name).

        Args:
            name (str): The name of a type

        Returns:
            ([str, ...]):   The list of type names it inherits from
        '''
        retn = []
        while name is not None:
            retn.append(name)
            name = self.getTypeInfo(name, 'subof')
        return retn

    def getPropNorm(self, prop, valu, oldval=None):
        '''
        Return a normalized system mode value for the given property.

        Args:
            prop (str): Property to normalize.
            valu: Input value to normalize.
            oldval: Optional previous version of the value.

        Examples:
            Normalize an IPV4 address::

                valu, subs = model.getPropNorm('inet:ipv4', '1.2.3.4')
                # valu = 16909060

            Normalize a DNS A record::

                valu, subs = model.getPropNorm('inet:dns:a', 'woot.com/1.2.3.4')
                # valu = 'woot.com/1.2.3.4'
                # subs['fqdn'] = 'woot.com'
                # subs['fqdn:domain'] = 'com'
                # subs['fqdn:host'] = 'woot'
                # subs['ipv4'] = 16909060

        Notes:
            If the requested property is not part of the data model, this returns the input valu. If this is not
            desired behavior, the reqPropNorm() function can be used to throw a NoSuchProp exception.

        Returns:
            tuple: A tuple of two items. The first item is the system normalized valu, as an integer or string. The
                   second item is a dictionary of subproperties for the input.
        '''
        dtype = self.getPropType(prop)
        if dtype is None:
            return valu, {}

        return dtype.norm(valu, oldval=oldval)

    def getPropParse(self, prop, valu):
        '''
        Parse a humon input string into a system mode property value.

        Example:

            valu,subs = model.getPropParse(prop, text)

        '''
        dtype = self.getPropType(prop)
        if dtype is None:
            return valu

        return dtype.parse(valu)

    def getPropDef(self, prop, glob=True):
        '''
        Return a property definition tufo by property name.

        Example:

            pdef = model.getPropDef('foo:bar')

        '''
        pdef = self.props.get(prop)
        if pdef is not None:
            return pdef

        if not glob:
            return None

        # check the cache
        pdef = self.cache.get(prop)
        if pdef is not None:
            return pdef

        # no match, lets check the globs...
        for glob, pinfo in self.globs:
            if fnmatch.fnmatch(prop, glob):
                pdef = (prop, dict(pinfo))
                self.cache[prop] = pdef
                return pdef

    def getPropType(self, prop):
        '''
        Return the data model type instance for the given property, or
        None if the data model doesn't have an entry for the property.

        Args:
            prop (str): Property to get the DataType instance for.

        Returns:
            s_types.DataType: A DataType for a given property.
        '''

        # Default to pulling dtype from the propsdtyp dict
        dtyp = self.propsdtyp.get(prop)
        if dtyp:
            return dtyp

        # Otherwise, fall back on getPropDef/getDataType methods.
        pdef = self.getPropDef(prop)
        if pdef is None:
            return None

        return self.getDataType(pdef[1].get('ptype'))

    def getPropInfo(self, prop, name):
        '''
        A helper function to resolve a prop info from either the
        property itself or the first type it inherits from which
        contains the info.

        Example:

            ex = modl.getPropInfo('inet:dns:a:fqdn','ex')

        '''
        pdef = self.getPropDef(prop)
        if pdef is None:
            return None

        valu = pdef[1].get(name)
        if valu is not None:
            return valu

        ptype = pdef[1].get('ptype')
        if ptype is None:
            return None

        return self.getTypeInfo(ptype, name)

    def reqPropNorm(self, prop, valu, oldval=None):
        '''
        Return a normalized system mode value for the given property. This throws an exception if the property does
        not exist.

        Args:
            prop (str): Property to normalize.
            valu: Input value to normalize.
            oldval: Optional previous version of the value.

        Examples:
            Normalize an IPV4 address::

                valu, subs = model.reqPropNorm('inet:ipv4', '1.2.3.4')
                # valu = 16909060

            Normalize a DNS A record::

                valu, subs = model.reqPropNorm('inet:dns:a', 'woot.com/1.2.3.4')
                # valu = 'woot.com/1.2.3.4'
                # subs['fqdn'] = 'woot.com'
                # subs['fqdn:domain'] = 'com'
                # subs['fqdn:host'] = 'woot'
                # subs['ipv4'] = 16909060

        Notes:
            This is similar to the getPropNorm() function, however it throws an exception on a missing property
            instead of returning the valu to the caller.

        Returns:
            tuple: A tuple of two items. The first item is the system normalized valu, as an integer or string. The
                   second item is a dictionary of subproperties for the input.

        Raises:
            NoSuchProp: If the requested property is not part of the data model.
        '''
        dtype = self.getPropType(prop)
        if dtype is None:
            raise s_common.NoSuchProp(mesg='Prop does not exist.',
                                      prop=prop, valu=valu)

        return dtype.norm(valu, oldval=oldval)


text:
package org.microemu.applet;

import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Locale;
import java.util.Vector;

import javax.microedition.lcdui.Image;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.swing.Timer;

import org.microemu.DisplayComponent;
import org.microemu.EmulatorContext;
import org.microemu.MIDletBridge;
import org.microemu.MIDletContext;
import org.microemu.MicroEmulator;
import org.microemu.RecordStoreManager;
import org.microemu.app.launcher.Launcher;
import org.microemu.app.ui.swing.SwingDeviceComponent;
import org.microemu.app.util.MIDletResourceLoader;
import org.microemu.app.util.MIDletSystemProperties;
import org.microemu.device.DeviceDisplay;
import org.microemu.device.DeviceFactory;
import org.microemu.device.FontManager;
import org.microemu.device.InputMethod;
import org.microemu.device.impl.DeviceImpl;
import org.microemu.device.j2se.J2SEDevice;
import org.microemu.device.j2se.J2SEDeviceDisplay;
import org.microemu.device.j2se.J2SEFontManager;
import org.microemu.device.j2se.J2SEInputMethod;
import org.microemu.log.Logger;
import org.microemu.util.JadMidletEntry;
import org.microemu.util.JadProperties;
import org.microemu.util.MemoryRecordStoreManager;

public class Main extends Applet implements MicroEmulator {

	private static final long serialVersionUID = 1L;

	private MIDlet midlet = null;

	private RecordStoreManager recordStoreManager;

	private JadProperties manifest = new JadProperties();

	private SwingDeviceComponent devicePanel;

	/**
	 * Host name accessible by MIDlet
	 */
	private String accessibleHost;

	private EmulatorContext emulatorContext = new EmulatorContext() {
		private InputMethod inputMethod = new J2SEInputMethod();

		private DeviceDisplay deviceDisplay = new J2SEDeviceDisplay(this);

		private FontManager fontManager = new J2SEFontManager();

		public DisplayComponent getDisplayComponent() {
			return devicePanel.getDisplayComponent();
		}

		public InputMethod getDeviceInputMethod() {
			return inputMethod;
		}

		public DeviceDisplay getDeviceDisplay() {
			return deviceDisplay;
		}

		public FontManager getDeviceFontManager() {
			return fontManager;
		}

		public InputStream getResourceAsStream(String name) {
			return getClass().getResourceAsStream(name);
		}
	};

	public Main() {
		devicePanel = new SwingDeviceComponent();
		devicePanel.addKeyListener(devicePanel);
	}

	public void init() {
		if (midlet != null) {
			return;
		}

		MIDletSystemProperties.applyToJavaSystemProperties = false;
		MIDletBridge.setMicroEmulator(this);

		URL baseURL = getCodeBase();
		if (baseURL != null) {
			accessibleHost = baseURL.getHost();
		}

		recordStoreManager = new MemoryRecordStoreManager();

		setLayout(new BorderLayout());
		add(devicePanel, "Center");

		DeviceImpl device;
		String deviceParameter = getParameter("device");
		if (deviceParameter == null) {
			device = new J2SEDevice();
			DeviceFactory.setDevice(device);
			device.init(emulatorContext);
		} else {
			try {
				Class cl = Class.forName(deviceParameter);
				device = (DeviceImpl) cl.newInstance();
				DeviceFactory.setDevice(device);
				device.init(emulatorContext);
			} catch (ClassNotFoundException ex) {
				try {
					device = DeviceImpl.create(emulatorContext, Main.class.getClassLoader(), deviceParameter,
							J2SEDevice.class);
					DeviceFactory.setDevice(device);
				} catch (IOException ex1) {
					Logger.error(ex);
					return;
				}
			} catch (IllegalAccessException ex) {
				Logger.error(ex);
				return;
			} catch (InstantiationException ex) {
				Logger.error(ex);
				return;
			}
		}

		devicePanel.init();

		manifest.clear();
		try {
			URL url = getClass().getClassLoader().getResource("META-INF/MANIFEST.MF");
			manifest.load(url.openStream());
			if (manifest.getProperty("MIDlet-Name") == null) {
				manifest.clear();
			}
		} catch (IOException e) {
			Logger.error(e);
		}

		// load jad
		String midletClassName = null;
		String jadFile = getParameter("jad");
		if (jadFile != null) {
			InputStream jadInputStream = null;
			try {
				URL jad = new URL(getCodeBase(), jadFile);
				jadInputStream = jad.openStream();
				manifest.load(jadInputStream);
				Vector entries = manifest.getMidletEntries();
				// only load the first (no midlet suite support anyway)
				if (entries.size() > 0) {
					JadMidletEntry entry = (JadMidletEntry) entries.elementAt(0);
					midletClassName = entry.getClassName();
				}
			} catch (IOException e) {
			} finally {
				if (jadInputStream != null) {
					try {
						jadInputStream.close();
					} catch (IOException e1) {
					}
				}
			}
		}

		if (midletClassName == null) {
			midletClassName = getParameter("midlet");
			if (midletClassName == null) {
				Logger.debug("There is no midlet parameter");
				return;
			}
		}

		// Applet is using only one classLoader
		MIDletResourceLoader.classLoader = this.getClass().getClassLoader();
		Class midletClass;
		try {
			midletClass = Class.forName(midletClassName);
		} catch (ClassNotFoundException ex) {
			Logger.error("Cannot find " + midletClassName + " MIDlet class");
			return;
		}

		try {
			midlet = (MIDlet) midletClass.newInstance();
		} catch (Exception ex) {
			Logger.error("Cannot initialize " + midletClass + " MIDlet class", ex);
			return;
		}

		Image tmpImg = DeviceFactory.getDevice().getNormalImage();
		resize(tmpImg.getWidth(), tmpImg.getHeight());

		return;
	}

	public void start() {
		devicePanel.requestFocus();

		new Thread("midlet_starter") {
			public void run() {
				try {
					MIDletBridge.getMIDletAccess(midlet).startApp();
				} catch (MIDletStateChangeException ex) {
					System.err.println(ex);
				}
			}
		}.start();

		Timer timer = new Timer(1000, new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				devicePanel.requestFocus();
			}
		});
		timer.setRepeats(false);
		timer.start();
	}

	public void stop() {
		MIDletBridge.getMIDletAccess(midlet).pauseApp();
	}

	public void destroy() {
		try {
			MIDletBridge.getMIDletAccess(midlet).destroyApp(true);
		} catch (MIDletStateChangeException ex) {
			System.err.println(ex);
		}
	}

	public RecordStoreManager getRecordStoreManager() {
		return recordStoreManager;
	}

	public String getAppProperty(String key) {
		if (key.equals("applet")) {
			return "yes";
		}

		String value = null;
		if (key.equals("microedition.platform")) {
			value = "MicroEmulator";
		} else if (key.equals("microedition.profiles")) {
			value = "MIDP-2.0";
		} else if (key.equals("microedition.configuration")) {
			value = "CLDC-1.0";
		} else if (key.equals("microedition.locale")) {
			value = Locale.getDefault().getLanguage();
		} else if (key.equals("microedition.encoding")) {
			value = System.getProperty("file.encoding");
		} else if (key.equals("microemu.applet")) {
			value = "true";
		} else if (key.equals("microemu.accessible.host")) {
			value = accessibleHost;
		} else if (getParameter(key) != null) {
			value = getParameter(key);
		} else {
			value = manifest.getProperty(key);
		}

		return value;
	}

	public InputStream getResourceAsStream(String name) {
		return emulatorContext.getResourceAsStream(name);
	}

	public boolean platformRequest(String url) {
		try {
			getAppletContext().showDocument(new URL(url), "mini");
		} catch (Exception e) {
		}
		return false;
	}

	public void notifyDestroyed(MIDletContext midletContext) {
	}

	public void destroyMIDletContext(MIDletContext midletContext) {

	}

	public Launcher getLauncher() {
		return null;
	}

	public String getAppletInfo() {
		return "Title: MicroEmulator \nAuthor: Bartek Teodorczyk, 2001";
	}

	public String[][] getParameterInfo() {
		String[][] info = { { "midlet", "MIDlet class name", "The MIDlet class name. This field is mandatory." }, };

		return info;
	}

}