text:
package org.osgi.test.cases.dmt.tc3.tbc.ConfigurationPlugin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;

import org.osgi.service.cm.Configuration;
import org.osgi.service.dmt.DmtData;
import org.osgi.service.dmt.DmtException;
import org.osgi.service.dmt.spi.TransactionalDataSession;

class ConfigReadWriteSession extends ConfigReadOnlySession
        implements TransactionalDataSession {

	private Vector<Event>	changes;
	private HashSet<String>	storedConfigurationIdSet;

    private String concurrentAccessError;

    ConfigReadWriteSession(ConfigPlugin plugin) {
        super(plugin);

        init();
    }

    @Override
	public void commit() throws DmtException {
        if(concurrentAccessError != null)
            throw new DmtException((String)null, DmtException.CONCURRENT_ACCESS,
                    concurrentAccessError);

        // This is an expensive check to detect concurrent modifications on the
        // list of registered Configuration tables.
        if(storedConfigurationIdSet != null && !storedConfigurationIdSet.equals(
				new HashSet<>(Arrays.asList(super.getConfigurationIds(null)))))
            throw new DmtException((String) null,
                    DmtException.CONCURRENT_ACCESS, "Configuration table " +
                    "list was changed outside the scope of the session.");

        String[] root = ConfigPluginActivator.PLUGIN_ROOT_PATH;
        String[] pidPath = new String[root.length + 1];
        // copy plugin root path, last element left empty for configuration PIDs
        System.arraycopy(root, 0, pidPath, 0, root.length);

		Iterator<Event> i = changes.iterator();
        while (i.hasNext()) {
            Event event = i.next();
            Conf table = event.getTable();
            String name = event.getName();
            Configuration configuration;
			Dictionary<String,Object> dict;
            pidPath[pidPath.length-1] = name;
            try {
                switch(event.getType()) {
                case Event.EVENT_TYPE_DELETE:
                    plugin.deleteConfiguration(name);
                    break;
                case Event.EVENT_TYPE_UPDATE:
                    configuration = getConfiguration(name, pidPath, true);
                    dict = table.getDictionary();
                    configuration.update(dict);
                    break;
                case Event.EVENT_TYPE_RECREATE:
                    plugin.deleteConfiguration(name);
                    // continue on the EVENT_TYPE_CREATE case
                case Event.EVENT_TYPE_CREATE:
                    configuration = plugin.createConfiguration(name,
                            table.getPid(), table.getLocation(),
                            table.getFactoryPid());
                    dict = table.getDictionary();
                    configuration.update(dict);
                    break;
                default: // cannot happen
                    throw new IllegalStateException("Unknown event type: " +
                            event.getType());
                }
            } catch (ConfigPluginException e) {
                throw e.getDmtException(pidPath);
            } catch (IOException e) {
                throw new DmtException(pidPath, DmtException.DATA_STORE_FAILURE,
                        "Error updating configuration table with the given " +
                        "PID.");
            }
        }

        init();
    }

    @Override
	public void rollback() throws DmtException {
		changes = new Vector<>();
        // nothing needs to be done
    }

    @Override
	public void createInteriorNode(String[] fullPath, String type)
            throws DmtException {
        if(type != null)
            throw new DmtException(fullPath, DmtException.COMMAND_FAILED,
                    "Cannot set type property of interior configuration nodes.");

        String[] path = chopPath(fullPath);
        // path has at least one component because the root node always exists,
        // so this method is not called

        Event event = getEventForConfiguration(path[0]);

        if(path.length == 1) {
            if(configurationExists(event, path[0], fullPath))
                throw new DmtException(fullPath, DmtException.NODE_ALREADY_EXISTS,
                        "A configuration table already exists for the given PID.");

            if(event == null)
                changes.add(new Event(Event.EVENT_TYPE_CREATE, path[0]));
            else
                event.recreate();

            return;
        }

        // throw an exception if no event was found and the configuration did
        // not exist at the beginning of the session, or if a delete event was
        // found
        if(!configurationExists(event, path[0], fullPath))
            throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                    "There is no configuration data for the given PID.");

        Conf conf = getConf(event, path[0], fullPath);

        // path[1].equals(KEYS) (this node is automatically created)

        ConfigEntry entry = conf.getEntry(path[2]);

        if (path.length == 3) { // create new property
            if(entry != null)
                throw new DmtException(fullPath, DmtException.NODE_ALREADY_EXISTS,
                        "The specified key already exists in the configuration.");

            conf.createEntry(path[2]);
            return;
        }

        if(entry == null)
            throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                    "The specified key does not exist in the configuration.");

        // path.length == 4   (create VALUES node for non-scalar properties)
        try {
            entry.createValues();
        } catch(ConfigPluginException e) {
            throw e.getDmtException(fullPath);
        }
    }

    @Override
	public void createLeafNode(String[] fullPath, DmtData data,
            String mimeType) throws DmtException {
        // proper MIME type ensured by meta-data

        String[] path = chopPath(fullPath);

        // path has at least two components as the first segment is interior
        Event event = getEventForConfiguration(path[0]);

        // throw an exception if no event was found and the configuration did
        // not exist at the beginning of the session, or if a delete event was
        // found
        if(!configurationExists(event, path[0], fullPath))
            throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                    "There is no configuration data for the given PID.");

        Conf conf = getConf(event, path[0], fullPath);

        if(path.length == 2) {
            if(data == null)
                throw new DmtException(fullPath, DmtException.METADATA_MISMATCH,
                        "The specified node has no default value.");

            // the format of the data is string, as guaranteed by the meta-data
            String param = data.getString();
            if(param != null && param.length() == 0)
                throw new DmtException(fullPath, DmtException.METADATA_MISMATCH,
                        "Parameter string must be non-empty.");

            if(path[1].equals(LOCATION)) {
                if(!conf.canCreateLocation())
                    throw new DmtException(fullPath, DmtException.NODE_ALREADY_EXISTS,
                            "The '" + LOCATION + "' parameter is already set " +
                            "for the specified configuration table.");
                conf.createLocation(param);
                return;
            }

            if(param == null)
                throw new DmtException(fullPath, DmtException.METADATA_MISMATCH,
                        "PID string must not be null.");

            if(path[1].equals(PID)) {
                if(conf.getPid() != null)
                    throw new DmtException(fullPath, DmtException.NODE_ALREADY_EXISTS,
                            "The '" + PID + "' parameter is already set " +
                            "for the specified configuration table.");
                conf.createPid(param);
                return;
            }

            // path[1].equals(FACTORY_PID)

            if(!conf.canCreateFactoryPid()) {
                if(conf.getFactoryPid() == null)
                    throw new DmtException(fullPath, DmtException.COMMAND_FAILED,
                            "The specified configuration table is " +
                            "not managed by a factory.");
                throw new DmtException(fullPath, DmtException.NODE_ALREADY_EXISTS,
                        "The '" + FACTORY_PID + "' parameter is already " +
                        "set for the specified configuration table.");
            }

            conf.createFactoryPid(param);

            return;
        }

        // next leaf is at length 4

        // path[1].equals(KEYS)
        // path[2] is a key name
        ConfigEntry entry = conf.getEntry(path[2]);
        if(entry == null)
            throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                    "The specified key does not exist in the configuration.");

        if (path.length == 4) {

            if(path[3].equals(VALUE)) {
                if(data == null)
                    throw new DmtException(fullPath, DmtException.METADATA_MISMATCH,
                            "The " + VALUE + " node has no default value.");

                try {
                    entry.createValue(data);
                } catch (ConfigPluginException e) {
                    throw e.getDmtException(fullPath);
                }

                return;
            }

            if (path[3].equals(TYPE)) {
                if(data == null)
                    data = Type.ALL_TYPE_DATA[0];

                Type type = Type.getTypeByData(data);
                if(type == null) // should not happen because of meta-data
                    throw new IllegalStateException("Invalid data received " +
                            "for the type: " + data);

                try {
                    entry.createType(type);
                } catch (ConfigPluginException e) {
                    throw e.getDmtException(fullPath);
                }
                return;
            }

            // path[3].equals(CARDINALITY)
            if(data == null)
                data = Cardinality.ALL_CARDINALITY_DATA[0];

            Cardinality cardinality = Cardinality.getCardinalityByData(data);
            if(cardinality == null) // should not happen because of meta-data
                throw new IllegalStateException("Invalid data received for " +
                        "the cardinality: " + data);

            try {
                entry.createCardinality(cardinality);
            } catch (ConfigPluginException e) {
                throw e.getDmtException(fullPath);
            }
            return;
        }

        // path.length == 5, path[3].equals(VALUES)
        int index = Integer.parseInt(path[4]);
        try {
            entry.createElementAt(index, data);
        } catch(ConfigPluginException e) {
            throw e.getDmtException(fullPath);
        }
    }

    @Override
	public void setNodeValue(String[] fullPath, DmtData data)
            throws DmtException {
        // only VALUE and VALUES can be replaced, these don't have defaults
        if(data == null)
            throw new DmtException(fullPath, DmtException.METADATA_MISMATCH,
                    "The specified node has no default value.");

        String[] path = chopPath(fullPath);

        // path has at least four components because DmtAdmin only calls this
        // method for modifiable leaf nodes
        Event event = getEventForConfiguration(path[0]);

        // throw an exception if no event was found and the configuration did
        // not exist at the beginning of the session, or if a delete event was
        // found
        if(!configurationExists(event, path[0], fullPath))
            throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                    "There is no configuration data for the given PID.");

        Conf conf = getConf(event, path[0], fullPath);

        // path[1].equals(KEYS)
        // path[2] is a key name
        ConfigEntry entry = conf.getEntry(path[2]);
        if(entry == null)
            throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                    "The specified key does not exist in the configuration.");

        if (path.length == 4) {
            try {
                entry.setValue(data);
            } catch(ConfigPluginException e) {
                throw e.getDmtException(fullPath);
            }
            return;
        }

        // path.length == 5
        int index = Integer.parseInt(path[4]);
        try {
            entry.setElementAt(index, data);
        } catch(ConfigPluginException e) {
            throw e.getDmtException(fullPath);
        }
    }

    @Override
	public void deleteNode(String[] fullPath) throws DmtException {
        String[] path = chopPath(fullPath);

        // path has at least one component because the root node is permanent
        Event event = getEventForConfiguration(path[0]);

        // throw an exception if no event was found and the configuration did
        // not exist at the beginning of the session, or if a delete event was
        // found
        if(!configurationExists(event, path[0], fullPath))
            throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                    "There is no configuration data for the given PID.");

        if(path.length == 1) {
            if(event == null)
                changes.add(new Event(Event.EVENT_TYPE_DELETE, path[0]));
            else if(event.getType() == Event.EVENT_TYPE_CREATE)
                changes.remove(event);
            else // EVENT_TYPE_UPDATE or EVENT_TYPE_RECREATE
                event.delete();

            return;
        }

        Conf conf = getConf(event, path[0], fullPath);

        // path has at least three components as KEYS cannot be deleted

        // path[1].equals(KEYS)
        // path[2] is a key name

        ConfigEntry entry = conf.getEntry(path[2]);
        if(entry == null)
            throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                    "The specified key does not exist in the configuration.");

        if(path.length == 3) {
            conf.removeEntry(path[2]);
            return;
        }

        // path has five components, nothing on level 4 can be deleted

        // path[3].equals(VALUES)
        // path[4] is an index

        try {
            entry.removeElementAt(Integer.parseInt(path[4]));
        } catch(ConfigPluginException e) {
            throw e.getDmtException(fullPath);
        }
    }

    @Override
	public void setNodeType(String[] fullPath, String type)
            throws DmtException {
        if(type == null)
            return;

        if(!isLeafNode(fullPath))
            throw new DmtException(fullPath, DmtException.COMMAND_FAILED,
                "Cannot set type property of interior configuration nodes.");

        // do nothing, meta-data guarantees that type is "text/plain"
    }

    @Override
	public void setNodeTitle(String[] fullPath, String title)
            throws DmtException {
        throw new DmtException(fullPath, DmtException.FEATURE_NOT_SUPPORTED,
                "Title property not supported.");
    }

    @Override
	public void renameNode(String[] fullPath, String newName)
            throws DmtException {
        String[] path = chopPath(fullPath);

        if(path.length == 0)
            throw new DmtException(fullPath, DmtException.COMMAND_FAILED,
                    "Cannot rename root node of the configuration tree.");

        Event event = getEventForConfiguration(path[0]);

        // throw an exception if no event was found and the configuration did
        // not exist at the beginning of the session, or if a delete event was
        // found
        if(!configurationExists(event, path[0], fullPath))
            throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                    "There is no configuration data for the given PID.");

        Conf conf = getConf(event, path[0], fullPath);

        if(path.length == 1)
            throw new DmtException(fullPath, DmtException.COMMAND_FAILED,
                    "Cannot rename configuration table root node.");

        if(path.length == 2)
            throw new DmtException(fullPath, DmtException.COMMAND_FAILED,
                    "Cannot rename " + KEYS + " node.");

        // path[2] is a key name
        ConfigEntry entry = conf.getEntry(path[2]);
        if(entry == null)
            throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                    "The specified key does not exist in the configuration.");

        if(path.length == 3) {
            if(conf.getEntry(newName) != null)
                throw new DmtException(fullPath, DmtException.NODE_ALREADY_EXISTS,
                        "The specified key already exists in the configuration.");

            conf.renameEntry(path[2], newName);
            return;
        }

        if (path.length == 4)
            throw new DmtException(fullPath, DmtException.COMMAND_FAILED,
                    "Cannot rename the specified node.");

        // path.length == 5
        int index = Integer.parseInt(path[4]);
        int newIndex = Integer.parseInt(newName);
        try {
            entry.renameElementAt(index, newIndex);
        } catch(ConfigPluginException e) {
            throw e.getDmtException(fullPath);
        }
    }

    @Override
	public void copy(String[] fullPath, String[] newNodePath, boolean recursive)
            throws DmtException {
        // ENHANCE allow cloning pid, key (on the same level)
        throw new DmtException(fullPath, DmtException.FEATURE_NOT_SUPPORTED,
                "Cannot copy configuration nodes.");
    }

    // Override some read methods to provide up-to-date info in mid-session

    @Override
	public String[] getChildNodeNames(String[] fullPath) throws DmtException {
        String[] path = chopPath(fullPath);
        if(path.length == 0)
            return getConfigurationIds(fullPath);

        Event event = getEventForConfiguration(path[0]);
        if(event == null) // no event for ID, use ancestor method
            return super.getChildNodeNames(fullPath);

        Conf conf = event.getTable();
        if(conf == null) // event.getType() == Event.EVENT_TYPE_DELETE
            throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                    "Configuration data for the given PID has been deleted.");

        if (path.length == 1) {
			List<String> l = new ArrayList<>();
            if(conf.getPid() != null)
                l.add(PID);
            if(!conf.canCreateLocation())
                l.add(LOCATION);
            l.add(KEYS);
            if(conf.getFactoryPid() != null)
                l.add(FACTORY_PID);
			return l.toArray(new String[0]);
        }

        if(path.length == 2)
            return conf.getKeys();

        ConfigEntry entry = conf.getEntry(path[2]);
        if(entry == null)
            throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                    "The specified key does not exist in the configuration.");

        if(path.length == 3) {
			List<String> l = new ArrayList<>();
            if(entry.getType() != null)
                l.add(TYPE);
            if(entry.getCardinality() != null)
                l.add(CARDINALITY);
            if(entry.getValue() != null)
                l.add(VALUE);
            if(entry.getValues() != null)
                l.add(VALUES);
			return l.toArray(new String[0]);
        }

        Integer[] indices;
        try { // getElementAt checks that the entry is non-scalar
            indices = entry.getIndexArray();
        } catch (ConfigPluginException e) {
            throw e.getDmtException(fullPath);
        }

        String[] children = new String[indices.length];
        for(int i = 0; i < indices.length; i++)
            children[i] = indices[i].toString();

        return children;
    }

    @Override
	public DmtData getNodeValue(String[] fullPath) throws DmtException {
        String[] path = chopPath(fullPath);

        // path.length > 1  because only leaf nodes are given
        Event event = getEventForConfiguration(path[0]);
        if(event == null) // no event for ID, use ancestor method
            return super.getNodeValue(fullPath);

        Conf conf = event.getTable();
        if(conf == null) // event.getType() == Event.EVENT_TYPE_DELETE
            throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                    "Configuration data for the given PID has been deleted.");

        if(path.length == 2) {
            if(path[1].equals(PID)) {
                String pid = conf.getPid();
                if(pid == null)
                    throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                            "The given node has not been created yet.");
                return new DmtData(pid);
            }

            if(path[1].equals(LOCATION)) {
                String location = conf.getLocation();
                if(conf.canCreateLocation())
                    throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                            "The given node has not been created yet.");
                return new DmtData(location);
            }

            // path[1].equals(FACTORY_PID)
            String factoryPid = conf.getFactoryPid();
            if(conf.canCreateFactoryPid())
                throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                        "The given node has not been created yet.");
            if(factoryPid == null)
                throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                        "The given node does not specify a factory configuration.");
            return new DmtData(factoryPid);
        }

        // path.length > 3
        ConfigEntry entry = conf.getEntry(path[2]);
        if(entry == null)
            throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                    "The specified key does not exist in the configuration.");

        if(path.length == 4) {
            if(path[3].equals(TYPE)) {
                Type type = entry.getType();
                if(type == null)
                    throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                            "The given node has not been created yet.");
                return type.getData();
            }

            if(path[3].equals(CARDINALITY)) {
                Cardinality cardinality = entry.getCardinality();
                if(cardinality == null)
                    throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                            "The given node has not been created yet.");
                return cardinality.getData();
            }

            // path[3].equals(VALUE))
            if(entry.getValues() != null)
                throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                        "The specified key contains a non-scalar value.");

            Value value = entry.getValue();
            if(value == null)
                throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                        "The given node has not been created yet.");
            return value.getData();
        }

        // path.length == 5
        if(entry.getValue() != null)
            throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                    "The given key specifies scalar data.");

        Value element;
        try { // getElementAt checks that the entry is non-scalar
            element = entry.getElementAt(Integer.parseInt(path[4]));
        } catch(ConfigPluginException e) {
            throw e.getDmtException(fullPath);
        }

        if(element == null)
            throw new DmtException(fullPath, DmtException.NODE_NOT_FOUND,
                    "No element exists in the array/vector with the given " +
                    "index.");

        return element.getData();
    }

    @Override
	public boolean isNodeUri(String[] fullPath) {
        String[] path = chopPath(fullPath);

        if(path.length == 0) // $/Configuration
            return true;
        if(path.length > 5)
            return false;

        Event event = getEventForConfiguration(path[0]);
        if(event == null) // no event for ID, use ancestor method
            return super.isNodeUri(fullPath);

        Conf conf = event.getTable();
        if(conf == null) // event.getType() == Event.EVENT_TYPE_DELETE
            return false;

        if(path.length == 1) // $/Configuration/<pid>
            return true;

        if(path.length == 2) {
            if(path[1].equals(PID))
                return conf.getPid() != null;
            if(path[1].equals(LOCATION))
                return !conf.canCreateLocation();
            if(path[1].equals(FACTORY_PID))
                return conf.getFactoryPid() != null;

            return path[1].equals(KEYS);
        }

        if(!path[1].equals(KEYS))
            return false;

        ConfigEntry entry = conf.getEntry(path[2]);
        if(entry == null)
            return false;

        if(path.length == 3)
            return true;

        if(path.length == 4) {
            if(path[3].equals(TYPE))
                return entry.getType() != null;
            if(path[3].equals(CARDINALITY))
                return entry.getCardinality() != null;
            if(path[3].equals(VALUE))
                return entry.getValue() != null;
            if(path[3].equals(VALUES))
                return entry.getValues() != null;

            return false;
        }

        if(!path[3].equals(VALUES))
            return false;

        try { // getElementAt checks that the entry is non-scalar
            return entry.getElementAt(Integer.parseInt(path[4])) != null;
        } catch (NumberFormatException e) {
            return false;
        } catch (ConfigPluginException e) {
            return false;
        }
    }

    //----- Utility methods -----//

    @Override
	protected String[] getConfigurationIds(String[] fullPath)
            throws DmtException {
		Set<String> configurations = getStoredConfigurationIdSet(fullPath);

		Iterator<Event> i = changes.iterator();
        while (i.hasNext()) {
            Event event = i.next();
            int type = event.getType();
            if(type == Event.EVENT_TYPE_CREATE)
                configurations.add(event.getName());
            else if(type == Event.EVENT_TYPE_DELETE)
                configurations.remove(event.getName());
        }

        return configurations.toArray(new String[0]);
    }

    private void init() {
		changes = new Vector<>();
        storedConfigurationIdSet = null;
        concurrentAccessError = null;
    }

    private boolean configurationExists(Event event, String nodeName,
            String[] fullPath) throws DmtException {
        return event != null ? event.getType() != Event.EVENT_TYPE_DELETE
                : getStoredConfigurationIdSet(fullPath).contains(nodeName);
    }

	private Set<String> getStoredConfigurationIdSet(String[] fullPath)
            throws DmtException {
        if(storedConfigurationIdSet == null)
            storedConfigurationIdSet =
					new HashSet<>(
							Arrays.asList(super.getConfigurationIds(fullPath)));

		return new HashSet<>(storedConfigurationIdSet);
    }

    private Event getEventForConfiguration(String name) {
        Event event = null;
		Iterator<Event> iter = changes.iterator();
        while (iter.hasNext()) {
            event = iter.next();
            if(name.equals(event.getName())) // found event for the given name
                return event;
        }

        return null;
    }

    // precondition: configurationExists(event, nodeName, fullPath) == true
    private Conf getConf(Event event, String nodeName, String[] fullPath)
            throws DmtException {
        if(event != null)
            return event.getTable();

        Conf conf = new Conf(getConfiguration(nodeName, fullPath, false));
        changes.add(new Event(Event.EVENT_TYPE_UPDATE, nodeName, conf));
        return conf;
    }

    private Configuration getConfiguration(String nodeName, String[] fullPath,
            boolean isCommit) throws DmtException {
        try {
            return plugin.getConfiguration(nodeName);
        } catch (ConfigPluginException e) {
            if(e.getCode() != DmtException.NODE_NOT_FOUND)
                throw e.getDmtException(fullPath);
            concurrentAccessError = "Accessed configuration table was " +
                    "deleted outside the scope of the session.";
            throw new DmtException(fullPath,
                    isCommit ? DmtException.CONCURRENT_ACCESS
                            : DmtException.NODE_NOT_FOUND,
                    concurrentAccessError);
        }
    }
}

class Event {
    static final int EVENT_TYPE_CREATE   = 0;
    static final int EVENT_TYPE_UPDATE   = 1;
    static final int EVENT_TYPE_DELETE   = 2;
    static final int EVENT_TYPE_RECREATE = 3;

    int type;
    String name;
    Conf table;

    Event(int type, String name) {
        this(type, name, null);
    }

    Event(int type, String name, Conf table) {
        switch(type) {
        case EVENT_TYPE_DELETE:
            break;
        case EVENT_TYPE_CREATE:
            if(table == null)
                table = new Conf();
            break;
        case EVENT_TYPE_UPDATE:
            if(table == null)
                throw new IllegalArgumentException("Update events must have " +
                        "a configuration table parameter.");
            break;
        case EVENT_TYPE_RECREATE:
            throw new IllegalArgumentException("Cannot make 'recreate' events" +
                    "directly, these can only be changed from 'delete' events.");
        default:
            throw new IllegalStateException("Unknown event type.");
        }

        this.type = type;
        this.name = name;
        this.table = table;
    }

    void delete() {
        if(type != EVENT_TYPE_UPDATE && type != EVENT_TYPE_RECREATE)
            throw new IllegalStateException("Only 'update' or 'recreate' " +
                    "events can be changed to 'delete'.");

        type = EVENT_TYPE_DELETE;
        table = null;
    }

    void recreate() {
        if(type != EVENT_TYPE_DELETE)
            throw new IllegalStateException("Only 'delete' events can be " +
                    "changed to 'recreate'.");

        type = EVENT_TYPE_RECREATE;

        this.table = new Conf();
    }

    int getType() {
        return type;
    }

    String getName() {
        return name;
    }

    Conf getTable() {
        return table;
    }
}

class Conf {
    private String pid; // PID of the configuration object

    private String location;
    private boolean canCreateLocation;

    private String factoryPid;
    private boolean canCreateFactoryPid;

	private Map<String,Object>	properties;

    Conf() {
        pid = null;
        location = null;
        canCreateLocation = true;
        factoryPid = null;
        canCreateFactoryPid = true;
		properties = new TreeMap<>(new CaseInsensitiveStringComparator());
    }

    Conf(Configuration configuration) {
        pid = configuration.getPid();
        location = configuration.getBundleLocation();
        canCreateLocation = false;
        factoryPid = configuration.getFactoryPid();
        canCreateFactoryPid = false;
		properties = new TreeMap<>(new CaseInsensitiveStringComparator());

		Dictionary<String,Object> propertyDictionary = configuration
				.getProperties();
		Enumeration<String> e = propertyDictionary.keys();
        while (e.hasMoreElements()) {
            String key = e.nextElement();
            Object value = propertyDictionary.get(key);
			if (value instanceof Vector && ((Vector< ? >) value).size() == 0)
                continue;
            properties.put(key, new ConfigEntry(value));
        }
    }

    String getPid() {
        return pid;
    }

    /**
     * Returns the location bound to the configuration, or <code>null</code> if
     * the location has not been set yet or the configuration is not bound to
     * any location.  The method {@link #canCreateLocation} only returns
     * <code>true</code> if the location node has not been created for a
     * configuration that is just under construction.
     */
    String getLocation() {
        return location;
    }

    /**
     * Returns <code>true</code> if the location node has not been created for a
     * configuration that is just under construction.
     */
    boolean canCreateLocation() {
        return canCreateLocation;
    }

    /**
     * Returns the factory PID of the configuration, or <code>null</code> if the
     * factory PID has not been set yet or the configuration is not a factory.
     * The method {@link #canCreateFactoryPid} only returns true if the factory
     * PID node has not been created for a configuration that is just under
     * construction.
     */
    String getFactoryPid() {
        return factoryPid;
    }

    /**
     * Returns true if the factory PID node has not been created for a
     * configuration that is just under construction.
     */
    boolean canCreateFactoryPid() {
        return canCreateFactoryPid;
    }

    String[] getKeys() {
		Set<String> keySet = properties.keySet();
		return keySet.toArray(new String[0]);
    }

    void createPid(String pid) {
        if(this.pid != null)
            throw new IllegalStateException("PID already set.");
        if(pid == null || pid.length() == 0)
            throw new IllegalArgumentException("PID parameter cannot be null " +
                    "or empty.");

        this.pid = pid;
    }

    void createFactoryPid(String factoryPid) {
        if(!canCreateFactoryPid)
            throw new IllegalStateException("Cannot set factory PID, not a " +
                    "factory configuration or PID already set.");
        if(factoryPid == null || factoryPid.length() == 0)
            throw new IllegalArgumentException("Factory PID parameter cannot " +
                    "be null or empty.");

        canCreateFactoryPid = false;
        this.factoryPid = factoryPid;
    }

    void createLocation(String location) {
        if(!canCreateLocation)
            throw new IllegalStateException("Location already set.");
        if(location != null && location.length() == 0)
            throw new IllegalArgumentException("Location parameter cannot be " +
                    "empty.");

        canCreateLocation = false;
        this.location = location;
    }

    ConfigEntry createEntry(String key) {
        return (ConfigEntry) properties.put(key, new ConfigEntry());
    }

    ConfigEntry getEntry(String key) {
        return (ConfigEntry) properties.get(key);
    }

    ConfigEntry renameEntry(String oldKey, String newKey) {
        return (ConfigEntry) properties.put(newKey, properties.remove(oldKey));
    }

    ConfigEntry removeEntry(String key) {
        return (ConfigEntry) properties.remove(key);
    }

	Dictionary<String,Object> getDictionary() throws ConfigPluginException {
		Dictionary<String,Object> dict = new Hashtable<>();

		Iterator<Entry<String,Object>> i = properties.entrySet().iterator();
        while (i.hasNext()) {
			Entry<String,Object> entry = i.next();
            Object value = ((ConfigEntry) entry.getValue()).getObject();
            dict.put(entry.getKey(), value);
        }

        return dict;
    }

	class CaseInsensitiveStringComparator implements Comparator<String> {
        @Override
		public int compare(String obj1, String obj2) {
            return obj1.compareToIgnoreCase(obj2);
        }
    }
}


text:
package com.google.common.jimfs;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;

import java.io.IOException;
import java.nio.file.attribute.AclEntry;
import java.nio.file.attribute.AclFileAttributeView;
import java.nio.file.attribute.FileAttributeView;
import java.nio.file.attribute.FileOwnerAttributeView;
import java.nio.file.attribute.UserPrincipal;
import java.util.List;
import java.util.Map;

import javax.annotation.Nullable;

/**
 * Attribute provider that provides the {@link AclFileAttributeView} ("acl").
 *
 * @author Colin Decker
 */
final class AclAttributeProvider extends AttributeProvider {

  private static final ImmutableSet<String> ATTRIBUTES = ImmutableSet.of("acl");

  private static final ImmutableSet<String> INHERITED_VIEWS = ImmutableSet.of("owner");

  private static final ImmutableList<AclEntry> DEFAULT_ACL = ImmutableList.of();

  @Override
  public String name() {
    return "acl";
  }

  @Override
  public ImmutableSet<String> inherits() {
    return INHERITED_VIEWS;
  }

  @Override
  public ImmutableSet<String> fixedAttributes() {
    return ATTRIBUTES;
  }

  @Override
  public ImmutableMap<String, ?> defaultValues(Map<String, ?> userProvidedDefaults) {
    Object userProvidedAcl = userProvidedDefaults.get("acl:acl");

    ImmutableList<AclEntry> acl = DEFAULT_ACL;
    if (userProvidedAcl != null) {
      acl = toAcl(checkType("acl", "acl", userProvidedAcl, List.class));
    }

    return ImmutableMap.of("acl:acl", acl);
  }

  @Nullable
  @Override
  public Object get(File file, String attribute) {
    if (attribute.equals("acl")) {
      return file.getAttribute("acl", "acl");
    }

    return null;
  }

  @Override
  public void set(File file, String view, String attribute, Object value, boolean create) {
    if (attribute.equals("acl")) {
      checkNotCreate(view, attribute, create);
      file.setAttribute("acl", "acl", toAcl(checkType(view, attribute, value, List.class)));
    }
  }

  @SuppressWarnings("unchecked") // only cast after checking each element's type
  private static ImmutableList<AclEntry> toAcl(List<?> list) {
    ImmutableList<?> copy = ImmutableList.copyOf(list);
    for (Object obj : copy) {
      if (!(obj instanceof AclEntry)) {
        throw new IllegalArgumentException(
            "invalid element for attribute 'acl:acl': should be List<AclEntry>, "
                + "found element of type " + obj.getClass());
      }
    }

    return (ImmutableList<AclEntry>) copy;
  }

  @Override
  public Class<AclFileAttributeView> viewType() {
    return AclFileAttributeView.class;
  }

  @Override
  public AclFileAttributeView view(
      FileLookup lookup, ImmutableMap<String, FileAttributeView> inheritedViews) {
    return new View(lookup, (FileOwnerAttributeView) inheritedViews.get("owner"));
  }

  /**
   * Implementation of {@link AclFileAttributeView}.
   */
  private static final class View extends AbstractAttributeView implements AclFileAttributeView {

    private final FileOwnerAttributeView ownerView;

    public View(FileLookup lookup, FileOwnerAttributeView ownerView) {
      super(lookup);
      this.ownerView = checkNotNull(ownerView);
    }

    @Override
    public String name() {
      return "acl";
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<AclEntry> getAcl() throws IOException {
      return (List<AclEntry>) lookupFile().getAttribute("acl", "acl");
    }

    @Override
    public void setAcl(List<AclEntry> acl) throws IOException {
      checkNotNull(acl);
      lookupFile().setAttribute("acl", "acl", ImmutableList.copyOf(acl));
    }

    @Override
    public UserPrincipal getOwner() throws IOException {
      return ownerView.getOwner();
    }

    @Override
    public void setOwner(UserPrincipal owner) throws IOException {
      ownerView.setOwner(owner);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
class Product {
  String name;
  public Product (String name) {this.name = name;}
  public String toString () {return name;}
}


text:
/**
 * @author maurobuselli@gmail.com

 */
(function () {
  'use strict';

  angular.module('AngularPanelsApp.pages.maps')
      .controller('LeafletPageCtrl', LeafletPageCtrl);

  /** @ngInject */
  function LeafletPageCtrl($timeout) {
    function initialize() {
      L.Icon.Default.imagePath = 'assets/img/theme/vendor/leaflet/dist/images';
      var map = L.map(document.getElementById('leaflet-map')).setView([51.505, -0.09], 13);
      L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
      }).addTo(map);

      L.marker([51.5, -0.09]).addTo(map)
          .bindPopup('A pretty CSS3 popup.
 Easily customizable.')
          .openPopup();
    }

    $timeout(function(){
      initialize();
    }, 100);

  }

})();


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.slapvanilla.wikispeak.UsageStatisticsActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/articles_viewed" />
        <TextView
            android:id="@+id/stats_articles_viewed"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/searches_performed" />
        <TextView
            android:id="@+id/stats_searches_performed"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/random_articles_viewed" />
        <TextView
            android:id="@+id/stats_random_articles_viewed"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/sections_listened_to" />
        <TextView
            android:id="@+id/stats_sections_listened_to"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/times_hit_play" />
        <TextView
            android:id="@+id/stats_times_hit_play"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>

</LinearLayout>


text:
<?php

namespace app\modules\penatausahaan\controllers;

use yii\web\Controller;

/**
 * Default controller for the `penatausahaan` module
 */
class DefaultController extends Controller
{
    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }
}


text:
layout: post
title:  "Rage Comic Match"
date:   2017-04-05 21:11:59 +0800
categories: jekyll update
---
Rage Comic for the classic pair match game.
With funny music and animation effect. It is a very good game for relax and forget about the time.
Improve players' concentration and memory with a game everyone love and want to play over and over again.

Just open the app you will know how to play. If you successfully find a match pair, the pair will break into pieces with explode sound, which is very interesting. You just want to hear this sound. Well if you mismatch, you will get -20 points. It is time to enjoy this little game.

![](https://raw.githubusercontent.com/sunnyjoe/sunny-app.github.io/master/assets/images/success.PNG)

![](https://raw.githubusercontent.com/sunnyjoe/sunny-app.github.io/master/assets/images/full.PNG)

You can see your rank in the world. Yeah! It is globally.

![](https://raw.githubusercontent.com/sunnyjoe/sunny-app.github.io/master/assets/images/menu.PNG)


text:
package com.googlecode.aluminumproject.libraries.beans.actions;

import com.googlecode.aluminumproject.AluminumException;
import com.googlecode.aluminumproject.context.Context;
import com.googlecode.aluminumproject.context.DefaultContext;
import com.googlecode.aluminumproject.libraries.beans.BeansLibraryTest;

import java.util.Calendar;

import org.testng.annotations.Test;

@SuppressWarnings("javadoc")
@Test(groups = {"libraries", "libraries-beans", "slow"})
public class SetPropertyTest extends BeansLibraryTest {
	public void valueShouldBeSet() {
		Calendar calendar = Calendar.getInstance();

		Context context = new DefaultContext();
		context.setVariable("bean", calendar);
		context.setVariable("name", "timeInMillis");
		context.setVariable("value", 1000000000000L);

		processTemplate("set-property", context);

		assert calendar.get(Calendar.YEAR) == 2001;
	}

	@Test(dependsOnMethods = "valueShouldBeSet")
	public void valueShouldBeConverted() {
		Calendar calendar = Calendar.getInstance();

		Context context = new DefaultContext();
		context.setVariable("bean", calendar);
		context.setVariable("name", "timeInMillis");
		context.setVariable("value", "500000000000");

		processTemplate("set-property", context);

		assert calendar.get(Calendar.YEAR) == 1985;
	}

	public void bodyShouldBeUsedWhenValueParameterIsOmitted() {
		Calendar calendar = Calendar.getInstance();

		Context context = new DefaultContext();
		context.setVariable("bean", calendar);
		context.setVariable("name", "timeInMillis");
		context.setVariable("value", 250000000000L);

		processTemplate("set-property-with-body", context);

		assert calendar.get(Calendar.YEAR) == 1977;
	}

	@Test(expectedExceptions = AluminumException.class)
	public void tryingToSetPropertyOnNullBeanShouldCauseException() {
		Context context = new DefaultContext();
		context.setVariable("bean", null);
		context.setVariable("name", "type");
		context.setVariable("value", "Null");

		processTemplate("set-property", context);
	}
}


text:
COMP4711 lab 6, Fall 2017
Steven Orola, Jeffrey Nguyen

Building out our TODO list manager


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--
    Copyright 2010 The Kuali Foundation

    Licensed under the Educational Community License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.opensource.org/licenses/ecl2.php

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog/1.9"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog/1.9 http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-1.9.xsd">

	<changeSet id="KFS_40_PURAP_ADD_PREQ_ELEC_INV_REJECT_DOC"
		author="kfs">
		<addColumn tableName="ap_elctrnc_inv_rjt_doc_t">
			<column name="preq_id" type="NUMBER(9,0)" />
		</addColumn>
		<modifySql dbms="mysql">
			<replace replace="NUMBER" with="DECIMAL" />
		</modifySql>
	</changeSet>

	<changeSet author="David" id="KFS_40_PURAP_ADD_ACTIVE_ELEC_INV">
		<comment>Needs to add a new column to AP_ELCTRNC_INV_MAP_T</comment>
		<addColumn tableName="AP_ELCTRNC_INV_MAP_T">
			<column name="DOBJ_MAINT_CD_ACTV_IND" type="VARCHAR2(1)" />
		</addColumn>
		<update tableName="AP_ELCTRNC_INV_MAP_T">
			<column name="DOBJ_MAINT_CD_ACTV_IND" value="Y" />
		</update>
		<modifySql dbms="mysql">
			<replace replace="VARCHAR2" with="VARCHAR" />
			<replace replace="varchar2" with="VARCHAR" />
		</modifySql>
	</changeSet>

	<changeSet id="KFS_40_PURAP_ADD_ACTIVE_PUR_PO_QT_LST_VNDR_T" author="kfs">
		<addColumn tableName="PUR_PO_QT_LST_VNDR_T">
			<column name="ACTV_IND" type="CHAR(1)" defaultValue="Y" />
		</addColumn>
	</changeSet>

</databaseChangeLog>


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Collections.Immutable;

namespace Microsoft.CodeAnalysis.Options
{
    /// <summary>
    /// An implementation of <see cref="OptionSet"/> that fetches values it doesn't know about to the workspace's option service. It ensures a contract
    /// that values are immutable from this instance once observed.
    /// </summary>
    internal sealed class WorkspaceOptionSet : OptionSet
    {
        private readonly IOptionService _service;

        private readonly object _gate = new object();
        private ImmutableDictionary<OptionKey, object> _values;

        internal WorkspaceOptionSet(IOptionService service)
        {
            _service = service;
            _values = ImmutableDictionary.Create<OptionKey, object>();
        }

        private WorkspaceOptionSet(IOptionService service, ImmutableDictionary<OptionKey, object> values)
        {
            _service = service;
            _values = values;
        }

        public override T GetOption<T>(Option<T> option)
        {
            return (T)GetOption(new OptionKey(option, language: null));
        }

        public override T GetOption<T>(PerLanguageOption<T> option, string language)
        {
            return (T)GetOption(new OptionKey(option, language));
        }

        public override object GetOption(OptionKey optionKey)
        {
            lock (_gate)
            {
                object value;

                if (!_values.TryGetValue(optionKey, out value))
                {
                    value = _service != null ? _service.GetOption(optionKey) : optionKey.Option.DefaultValue;
                    _values = _values.Add(optionKey, value);
                }

                return value;
            }
        }

        public override OptionSet WithChangedOption<T>(Option<T> option, T value)
        {
            return WithChangedOption(new OptionKey(option, language: null), value);
        }

        public override OptionSet WithChangedOption<T>(PerLanguageOption<T> option, string language, T value)
        {
            return WithChangedOption(new OptionKey(option, language), value);
        }

        public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object value)
        {
            // make sure we first load this in current optionset
            this.GetOption(optionAndLanguage);

            return new WorkspaceOptionSet(_service, _values.SetItem(optionAndLanguage, value));
        }

        /// <summary>
        /// Gets a list of all the options that were accessed.
        /// </summary>
        internal IEnumerable<OptionKey> GetAccessedOptions()
        {
            var optionSet = _service.GetOptions();
            return GetChangedOptions(optionSet);
        }

        internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet optionSet)
        {
            foreach (var kvp in _values)
            {
                var currentValue = optionSet.GetOption(kvp.Key);
                if (!object.Equals(currentValue, kvp.Value))
                {
                    yield return kvp.Key;
                }
            }
        }
    }
}


text:
#include <time.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <pthread.h>
#include "directory.h"

static struct Directory directory[ENTRIES];
static pthread_mutex_t directoryMutex;

/* Setup the directory to an empty state.
 * Make sure that the entries are marked as unused.
 * Also sets up the mutex.
 */
void DirectoryInit()
{
  int i;
  pthread_mutex_init(&directoryMutex, NULL);
  for (i = 0; i < ENTRIES; i++) {
    directory[i].used = 0;
  }
}

/* Add a file/peer pair to the directory.
 * Will find either an empty place in the directory
 * find the oldest element to replace, or return if two
 * elemnts have the same name and peer.
 */
void DirectoryAdd(char *file, struct sockaddr_in address)
{
  int i, old;
  time_t current;
  char dest[INET_ADDRSTRLEN];
  pthread_mutex_lock(&directoryMutex);
  time(&current);

  // Find where to place the info
  for (i = 0; i < ENTRIES; i++) {
    if (directory[i].used == 0) {
      old = i;
      break;
    }
    else if (file != NULL && directory[i].file != NULL) {
      if (strcmp(file, directory[i].file) == 0) {
	if ((directory[i].peer.sin_port == address.sin_port)
	    && directory[i].peer.sin_addr.s_addr == address.sin_addr.s_addr) {
	  directory[i].timestamp = current;
	  pthread_mutex_unlock(&directoryMutex);
	  return;
	}
      }
    }
    else {
      if (directory[i].timestamp < current) {
	current = directory[i].timestamp;
	old = i;
      }
    }
  }

  // Copy information into the list.
  if (file != NULL) {
    strcpy(directory[old].file, file);
  }
  memcpy(&directory[old].peer, &address, sizeof(struct sockaddr_in));
  time(&directory[old].timestamp);
  directory[i].used = 1;
  pthread_mutex_unlock(&directoryMutex);
}

/* Return a copy of the directory.
 * This way we do not need to worry about
 * thread safety.
 */
struct Directory * DirectoryGet()
{
  return directory;
}

int DirectoryGetList(struct sockaddr_in *addresses)
{
  int i, j, count = 0;
  char unique;
  struct sockaddr_in current;
  pthread_mutex_lock(&directoryMutex);
  for (i = 0; i < ENTRIES; i++) {
    unique = 1;
    if (directory[i].used == 1) {
      current = directory[i].peer;
    }
    else
      break;
    memcpy(&addresses[count], &current,
	   sizeof(struct sockaddr_in));
    count++;
  }

  pthread_mutex_unlock(&directoryMutex);
  return count;
}

int DirectoryGetListBySearch(char *search, struct sockaddr_in *addresses)
{
  int i, j, count = 0;
  struct sockaddr_in current;

  pthread_mutex_lock(&directoryMutex);
  for (i = 0; i < ENTRIES; i++) {
    if (directory[i].used == 1
	&& strcmp(search, directory[i].file) == 0) {
      current = directory[i].peer;
    }
    else
      continue;

    memcpy(&addresses[count], &current,
	   sizeof(struct sockaddr_in));
    count++;
  }

  pthread_mutex_unlock(&directoryMutex);
  return count;
}


text:
import sys
from edu.mit.hesiod import Hesiod
from javax.naming import NameNotFoundException
h = Hesiod.getInstance()

try:
    print("-Test lookup()-");
    print(h.lookup("jmorzins","passwd"))
    print(h.lookup("sipb","filsys"))

    print("-Test lookupFilsys(zacheiss)-");
    ans = h.lookupFilsys("zacheiss")
    for rec in ans.list():
        print(rec)

    print("-Test lookupFilsys(dev-sun4sys-94)-");
    ans = h.lookupFilsys("dev-sun4sys-94")
    print(ans.list())
    print(ans.list().get(0))
    print(ans.list().get(0).get("locations"))
except NameNotFoundException:
    print sys.exc_info()[1]


text:
using System.Collections.Generic;
using BluffinMuffin.Protocol.DataTypes.Attributes;
using BluffinMuffin.Protocol.DataTypes.Enums;

namespace BluffinMuffin.Protocol.DataTypes
{
    /// <summary>
    /// Information of a Poker Game Type
    /// </summary>
    public class GameInfo
    {
        /// <summary>
        /// Type of Game
        /// </summary>
        [ExampleValue(GameTypeEnum.CommunityCardsPoker)]
        public GameTypeEnum GameType { get; set; }

        /// <summary>
        /// Available variants of this type of game
        /// </summary>
        [ExampleValues(3, GameSubTypeEnum.TexasHoldem, GameSubTypeEnum.OmahaHoldem, GameSubTypeEnum.CrazyPineapple)]
        public GameSubTypeEnum[] AvailableVariants { get; set; }

        /// <summary>
        /// Available betting limits for this type of game
        /// </summary>
        [ExampleValues(3, LimitTypeEnum.NoLimit, LimitTypeEnum.FixedLimit, LimitTypeEnum.PotLimit)]
        public LimitTypeEnum[] AvailableLimits { get; set; }

        /// <summary>
        /// Available blind types for this type of game
        /// </summary>
        [ExampleValues(1, BlindTypeEnum.Blinds)]
        public BlindTypeEnum[] AvailableBlinds { get; set; }

        /// <summary>
        /// Minimum number of player on the table to be able to play the game
        /// </summary>
        [ExampleValue(2)]
        public int MinPlayers { get; set; }

        /// <summary>
        /// Maximum number of player on the table
        /// </summary>
        [ExampleValue(10)]
        public int MaxPlayers { get; set; }
    }
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import EventBus from '../EventBus';
import StyleConstants from '../StyleConstants';
import {Router, Route, Link, hashHistory} from 'react-router';

class ViewingContactHeader extends React.Component
{
	render()
	{
		var editLink = '/edit/' + this.props.params.id;
		return (

<Link to='/'><Contacts</Link>

<Link to={editLink}>Edit</Link>

		);
	}
}

export default ViewingContactHeader


text:
package edu.indiana.lib.osid.base.repository.http;

public class IssuePartStructure implements org.osid.repository.PartStructure
{
	private org.osid.shared.Id ISSUE_PART_STRUCTURE_ID = null;
	private org.osid.shared.Type type = new Type( "sakaibrary", "partStructure",
			"issue", "Issue of resource container (i.e. Journal title, issue " +
					"213)" );
	private String displayName = "Issue";
	private String description = "Issue of resource container (i.e. Journal " +
			"title, issue 213)";
	private boolean mandatory = false;
	private boolean populatedByRepository = false;
	private boolean repeatable = false;

	private static IssuePartStructure issuePartStructure;

	private IssuePartStructure()
	{
		try
		{
			this.ISSUE_PART_STRUCTURE_ID =
				Managers.getIdManager().getId("x8349ydf67826cr4n9823520168435100");
		}
		catch (Throwable ignore) { }
	}

	/**
	 * Public method to fetch the PartStructure ID
	 */
	public static org.osid.shared.Id getPartStructureId()
	{
		org.osid.shared.Id id = null;

		try
		{
			id = getInstance().getId();
		}
		catch (org.osid.repository.RepositoryException ignore) { }

		return id;
	}

	public static synchronized IssuePartStructure getInstance()
	{
		if( issuePartStructure == null ) {
			issuePartStructure = new IssuePartStructure();
		}
		return issuePartStructure;
	}

	public String getDisplayName()
	throws org.osid.repository.RepositoryException
	{
		return this.displayName;
	}

	public String getDescription()
	throws org.osid.repository.RepositoryException
	{
		return this.description;
	}

	public boolean isMandatory()
	throws org.osid.repository.RepositoryException
	{
		return this.mandatory;
	}

	public boolean isPopulatedByRepository()
	throws org.osid.repository.RepositoryException
	{
		return this.populatedByRepository;
	}

	public boolean isRepeatable()
	throws org.osid.repository.RepositoryException
	{
		return this.repeatable;
	}

	public void updateDisplayName(String displayName)
	throws org.osid.repository.RepositoryException
	{
		throw new org.osid.repository.RepositoryException(
				org.osid.OsidException.UNIMPLEMENTED);
	}

	public org.osid.shared.Id getId()
	throws org.osid.repository.RepositoryException
	{
		return this.ISSUE_PART_STRUCTURE_ID;
	}

	public org.osid.shared.Type getType()
	throws org.osid.repository.RepositoryException
	{
		return this.type;
	}

	public org.osid.repository.RecordStructure getRecordStructure()
	throws org.osid.repository.RepositoryException
	{
		return RecordStructure.getInstance();
	}

	public boolean validatePart(org.osid.repository.Part part)
	throws org.osid.repository.RepositoryException
	{
		return true;
	}

	public org.osid.repository.PartStructureIterator getPartStructures()
	throws org.osid.repository.RepositoryException
	{
		return new PartStructureIterator(new java.util.Vector());
	}
}


text:
package ns

type Nssourceroutecachetable struct {
	Interface string `json:"Interface,omitempty"`
	Sourceip  string `json:"sourceip,omitempty"`
	Sourcemac string `json:"sourcemac,omitempty"`
	Vlan      int    `json:"vlan,omitempty"`
}


text:
from __future__ import unicode_literals

from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponseRedirect
from django.core.exceptions import PermissionDenied
from django.views.generic import (
    ListView, DetailView, CreateView, DeleteView, UpdateView)

from catalog.models import Product
from catalog.reviews.models import Review
from catalog.utils.shortcuts import get_by_slug_or_404

class ProductMixin(object):
    product = None

    def dispatch(self, request, *args, **kwargs):
        self.product = get_by_slug_or_404(Product, kwargs.get('slug', None))
        return super(ProductMixin, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        """
        Updates context to add a product object instance.
        """
        context = {'product': self.product}
        context.update(kwargs)
        return super(ProductMixin, self).get_context_data(**context)

class OwnerRequiredMixin(object):
    def dispatch(self, request, *args, **kwargs):
        """
        Raise permission error if object is not owned by user/session.
        """
        self.object = self.get_object()
        user = getattr(request, 'user', None)
        if (user and user == self.object.user or
                self.object.session_key == request.session.session_key):
            return super(OwnerRequiredMixin, self).dispatch(
                request, *args, **kwargs)
        raise PermissionDenied()

class ReviewListView(ProductMixin, ListView):
    model = Review
    template_name = 'shop/reviews/review_list.html'

    def get_queryset(self):
        qs = super(ReviewListView, self).get_queryset()
        return qs.filter(product=self.product)

class ReviewDetailView(ProductMixin, DetailView):
    model = Review
    template_name = 'shop/reviews/review_detail.html'

class ReviewCreateView(ProductMixin, CreateView):
    model = Review
    fields = ['body', 'rating']
    template_name = 'shop/reviews/review_create.html'

    def get(self, request, *args, **kwargs):
        """
        If review already written for this user/session redirect to
        update view for that review.
        """
        user = getattr(request, 'user', None)
        product = get_by_slug_or_404(Product, kwargs.get('slug', None))
        filters = {'product': product}

        if user and user.is_authenticated():
            filters['user'] = user
        else:
            filters['session_key'] = request.session.session_key

        if len(filters) > 1:
            try:
                review = Review.objects.get(**filters)
                return HttpResponseRedirect(reverse_lazy(
                    'catalog_review_update',
                    args=[product.get_slug(), review.pk]))
            except Review.DoesNotExist:
                pass

        return super(ReviewCreateView, self).get(request, *args, **kwargs)

    def form_valid(self, form):
        """
        Force product and user values into a form after it's validated
        and save review_id to session.
        """
        product = get_by_slug_or_404(Product, self.kwargs.get('slug', None))
        form.instance.product = product

        user = getattr(self.request, 'user', None)
        form.instance.user = user if user and user.is_authenticated() else None
        form.instance.session_key = self.request.session.session_key

        return super(ReviewCreateView, self).form_valid(form)

class ReviewUpdateView(OwnerRequiredMixin, ProductMixin, UpdateView):
    model = Review
    fields = ['body', 'rating']
    template_name = 'shop/reviews/review_update.html'

class ReviewDeleteView(OwnerRequiredMixin, ProductMixin, DeleteView):
    model = Review
    template_name = 'shop/reviews/review_delete.html'

    def get_success_url(self):
        return reverse_lazy(
            'catalog_review_list', args=[self.object.product.get_slug()])


text:
namespace caffe {

template <typename Dtype>
void PoseEuDistAccuracyLayer<Dtype>::LayerSetUp(
    const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top)
{
  CHECK(this->layer_param_.has_pose_eudist_accuracy_param());
  const PoseEuDistAccuracyParameter pudap =
      this->layer_param_.pose_eudist_accuracy_param();
  CHECK(pudap.has_acc_factor());
  CHECK(pudap.has_acc_factor_num());
  CHECK(pudap.has_images_num());
  CHECK(pudap.has_acc_path());
  CHECK(pudap.has_acc_name());
  CHECK(pudap.has_log_name());

  // get config variables
  this->images_itemid_   = 0;
  this->images_num_      = pudap.images_num();
  this->acc_factor_      = 1; // pudap.acc_factor();
  this->acc_factor_num_  = pudap.acc_factor_num();
  this->acc_path_        = pudap.acc_path();
  this->acc_name_        = pudap.acc_name();
  this->log_name_        = pudap.log_name();
  this->zero_iter_test_  = false;
  if(pudap.has_zero_iter_test()) {
    this->zero_iter_test_ = pudap.zero_iter_test();
  }

  // accuracy log file
  CreateDir(this->acc_path_);
  this->acc_file_ = this->acc_path_ + this->acc_name_;
  this->log_file_ = this->acc_path_ + this->log_name_;
  LOG(INFO) << "acc_path: "   << this->acc_path_;
  LOG(INFO) << "acc_name: "   << this->acc_name_;
  LOG(INFO) << "acc_file: "   << this->acc_file_;
  LOG(INFO) << "log_file: "   << this->log_file_;
  LOG(INFO) << "acc_factor: " << this->acc_factor_;

  // threshold values
  CHECK_EQ(this->acc_factor_    , 1);
  CHECK_GT(this->acc_factor_num_, this->acc_factor_);
  CHECK_LE(this->acc_factor_num_, 100);

  // get threshold values
  LOG(INFO) << "accuracy factors below: ";
  for (int idx = 1; idx <= this->acc_factor_num_; idx++) {
    const int threshold = idx;

    this->max_score_.push_back(0);
    this->max_score_iter_.push_back(0);
    this->acc_factors_.push_back(threshold);

    LOG(INFO) << "idx: "       << idx << " "
              << "factor: "    << this->acc_factor_ << " "
              << "threshold: " << threshold;
  }
  // initialize
  this->label_num_     = bottom[0]->channels();
  this->key_point_num_ = this->label_num_ / 2;
  this->initAccFactors();

  LOG(INFO) << "acc_factor: "      << this->acc_factor_;
  LOG(INFO) << "acc_factors_num: " << this->acc_factor_num_;
  LOG(INFO) << "images_num: "      << this->images_num_;
  LOG(INFO) << "images_itemid: "   << this->images_itemid_;
  LOG(INFO) << "label_num: "       << this->label_num_;
  LOG(INFO) << "key_point_num: "   << this->key_point_num_;
}

template <typename Dtype>
void PoseEuDistAccuracyLayer<Dtype>::Reshape(
    const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top)
{
  const std::string err_str =
      "The data and label should have the same number.";
  CHECK_EQ(bottom[0]->num(),      bottom[1]->num())
      << err_str;
  CHECK_EQ(bottom[0]->channels(), bottom[1]->channels())
      << err_str;
  CHECK_EQ(bottom[0]->height(),   bottom[1]->height())
      << err_str;
  CHECK_EQ(bottom[0]->width(),    bottom[1]->width())
      << err_str;
  CHECK_EQ(bottom[0]->count() /   bottom[0]->num(),
           bottom[0]->channels()) << err_str;

  // check labels' number
  this->label_num_     = bottom[0]->channels();
  this->key_point_num_ = this->label_num_ / 2;

  // check
  CHECK_GT(this->label_num_,   0);
  CHECK_EQ(this->label_num_,   this->key_point_num_ * 2);

  // diff_
  this->diff_.Reshape(bottom[0]->num(),    bottom[0]->channels(),
                      bottom[0]->height(), bottom[0]->width());

  // top blob: record the accuracy ?
  top[0]->Reshape(1, 1, 1, 1);
}

template <typename Dtype>
void PoseEuDistAccuracyLayer<Dtype>::initAccFactors() {
	// clear
  if(!this->accuracies_.empty()) {
    for (int i = 0; i < this->acc_factor_num_; i++) {
      this->accuracies_[i].clear();
    }
    this->accuracies_.clear();
  }

	CHECK_EQ(this->accuracies_.size(), 0)
      << "invalid accuracies variable, when reset them";

	for (int idx = 0; idx < this->acc_factor_num_; idx++) {
	  std::vector<float> acc_temp;
	  for(int sln = 0; sln < this->key_point_num_; sln++) {
	    acc_temp.push_back(0.);
	  }
    CHECK_EQ(acc_temp.size(), this->key_point_num_);
    this->accuracies_.push_back(acc_temp);
  }
  CHECK_EQ(this->accuracies_.size(), this->acc_factor_num_);
}

template <typename Dtype>
void PoseEuDistAccuracyLayer<Dtype>::InitQuantization() {
  // check
  CHECK_GE(this->images_itemid_, this->images_num_);
	// re-init
  this->initAccFactors();
  // reset images_itemid_ to be zero
  this->images_itemid_ = 0;
}

// index starts from zero
template<typename Dtype>
void PoseEuDistAccuracyLayer<Dtype>::CalAccPerImage(
    const Dtype* pred_coords_ptr, const Dtype* gt_coords_ptr)
{
  int index        = 0;
  const Dtype Zero = Dtype(0);
  const Dtype two  = Dtype(2.);

  Dtype pred_dist[this->key_point_num_];
  for (int idx = 0; idx < this->label_num_; idx += 2) {
    // ground true x and y
    const Dtype gt_x = gt_coords_ptr[idx + 0];
    const Dtype gt_y = gt_coords_ptr[idx + 1];

    // predicted x and y
    const Dtype pred_x  = pred_coords_ptr[idx + 0];
    const Dtype pred_y  = pred_coords_ptr[idx + 1];

    // check
    if(gt_x < Zero || gt_y < Zero || pred_x < Zero
                   || pred_y < Zero)
    {
      pred_dist[index++] = Dtype(this->acc_factor_num_ + 1);
      continue;
    }

    // distance between prediction and ground truth
    const Dtype dx      = (pred_x - gt_x) / two;
    const Dtype dy      = (pred_y - gt_y) / two;
    // const Dtype dx      = (pred_x - gt_x);
    // const Dtype dy      = (pred_y - gt_y);
    pred_dist[index++]  = std::sqrt(dx * dx + dy * dy);
  }
  CHECK_EQ(index, this->key_point_num_);

  // Count the correct ones
  for (int afn = 0; afn < this->acc_factor_num_; afn++) {
    const Dtype threshold = this->acc_factors_[afn];
    // LOG(INFO) << "afn: " << afn << ", threshold: " << threshold;
    for (int idx = 0; idx < this->key_point_num_; idx++) {
      if (pred_dist[idx] <= threshold) {
        this->accuracies_[afn][idx]++;
      }
    }
  }
}

template <typename Dtype>
void PoseEuDistAccuracyLayer<Dtype>::WriteResults(
    const float total_accuracies[])
{
  std::ofstream acc_fhd;
  acc_fhd.open(this->acc_file_.c_str(), ios::out | ios::app);
  CHECK(acc_fhd);

  const int caffe_iter = GlobalVars::caffe_iter();

  acc_fhd << GlobalVars::SpiltCodeBoundWithStellate();
  acc_fhd << GlobalVars::SpiltCodeBoundWithStellate() << std::endl;
  acc_fhd << "iter: "     << GlobalVars::caffe_iter() << std::endl;
  acc_fhd << "learn_lr: " << GlobalVars::learn_lr()   << std::endl;

  for(int afn = 0; afn < this->acc_factor_num_; afn++) {
    const float acc_factor = acc_factors_[afn];
    const Dtype accuracy   =  Dtype(total_accuracies[afn]);

    acc_fhd << "acc_factor: " << acc_factor << " " << std::endl;
    acc_fhd << "accuracy: "   << accuracy   << std::endl;

    if(accuracy > this->max_score_[afn]) {
      this->max_score_[afn]      = accuracy;
      this->max_score_iter_[afn] = Dtype(caffe_iter);
    }
    // single
    for (int lnh = 0; lnh < this->key_point_num_ - 1; lnh++) {
      acc_fhd << lnh + 1 << "th: " << accuracies_[afn][lnh] << ", ";
    }
    acc_fhd << this->key_point_num_ << "th: "
            << this->accuracies_[afn][this->key_point_num_ - 1];
    acc_fhd << std::endl;
  }

  acc_fhd << GlobalVars::SpiltCodeBoundWithStellate() << std::endl;

  for(int afn = 0; afn < this->acc_factor_num_; afn++) {
    acc_fhd << "afn: "       << afn                   << ", "
            << "pdj: "       << acc_factors_[afn]     << ", "
            << "max score: " << this->max_score_[afn] << ", "
            << "iter: "     << this->max_score_iter_[afn]
            << std::endl;

    LOG(INFO) << "afn: "       << afn                   << ", "
              << "pdj: "       << acc_factors_[afn]     << ", "
              << "max score: " << this->max_score_[afn] << ", "
              << "iter: "     << this->max_score_iter_[afn];
  }
  acc_fhd << std::endl << std::endl;
  acc_fhd.close();
}

template<typename Dtype>
void PoseEuDistAccuracyLayer<Dtype>::QuanFinalResults() {
  // statistically
  float total_accuracies[this->acc_factor_num_];

  for(int afn = 0; afn < this->acc_factor_num_; afn++) {
    total_accuracies[afn] = 0.;

    for(int lnh = 0; lnh < this->key_point_num_; lnh++) {
      this->accuracies_[afn][lnh] /= (this->images_num_ + 0.);
      total_accuracies[afn]       += accuracies_[afn][lnh];
    }

    total_accuracies[afn] /= (this->key_point_num_ + 0.);
  }

  // save
  if(GlobalVars::caffe_iter() <= 0 && !this->zero_iter_test_) {
    return;
  }

  // write results
  this->WriteResults(total_accuracies);
}

template<typename Dtype>
void PoseEuDistAccuracyLayer<Dtype>::Quantization(
    const Dtype* pred_coords, const Dtype* gt_coords,
    const int num)
{
  CHECK_EQ(this->label_num_, this->key_point_num_ * 2)
      << "invalid label_num: " << this->label_num_
      << ", and s_label_num: " << this->key_point_num_;

  for(int idx = 0; idx < num; idx++) {
    const Dtype* gt_coords_ptr   = gt_coords + this->label_num_   * idx;
    const Dtype* pred_coords_ptr = pred_coords + this->label_num_ * idx;

    if(this->images_itemid_ < this->images_num_) {
      this->CalAccPerImage(pred_coords_ptr, gt_coords_ptr);
      this->images_itemid_++;
      LOG(INFO) << "images_itemid: " << this->images_itemid_
                << " ("              << this->images_num_ << ")";
    } else {
      LOG(INFO) << "ready for writing the accuracy results...";
      break;
    }
  }

  if(this->images_itemid_ >= this->images_num_) {
    // Record final results
    this->QuanFinalResults();

    // Initialize
    this->InitQuantization();
  }
}

template <typename Dtype>
void PoseEuDistAccuracyLayer<Dtype>::Forward_cpu(
    const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top)
{
	const int count = bottom[0]->count();
	const int num   = bottom[0]->num();
  CHECK_EQ(count, num * this->label_num_);

	caffe_sub(count, bottom[0]->cpu_data(),
            bottom[1]->cpu_data(),
            this->diff_.mutable_cpu_data());

	Dtype loss = caffe_cpu_dot(count, this->diff_.cpu_data(),
                             this->diff_.cpu_data());

  loss /= Dtype(num + 0.);
  top[0]->mutable_cpu_data()[0] = loss;

  LOG(INFO) << "iter: " << GlobalVars::caffe_iter()
            << ", loss: " <<  loss;

  const Dtype* gt_coords = bottom[1]->cpu_data();
  const Dtype* pred_coords = bottom[0]->cpu_data();
  this->Quantization(pred_coords, gt_coords, num);
}

INSTANTIATE_CLASS(PoseEuDistAccuracyLayer);
REGISTER_LAYER_CLASS(PoseEuDistAccuracy);

}  // namespace caffe


text:
package org.earthtime.UPb_Redux.valueModels.definedValueModels;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.concurrent.ConcurrentMap;
import org.earthtime.UPb_Redux.valueModels.ValueModel;

/**
 *
 * @author James F. Bowring
 */
public class MolPb208s extends ValueModel implements
        Comparable<ValueModel>,
        Serializable {

    // Class variables
//    private static final long serialVersionUID =  -754922929875948476L; april 2010 does not appear to be used !!!
    private final static String NAME = "molPb208s";
    private final static String UNCT_TYPE = "ABS";
    // Instance variables
    private ValueModel r208_205m;
    private ValueModel r208_205t;
    private ValueModel molPb205t;
    private ValueModel alphaPb;
    private ValueModel molPb208b;

    /** Creates a new instance of MolPb208s */
    public MolPb208s () {
        super( NAME, UNCT_TYPE );
    }

    /**
     *
     * @param inputValueModels
     * @param parDerivTerms
     */
    @Override
    public void calculateValue (
            ValueModel[] inputValueModels,
            ConcurrentMap<String, BigDecimal> parDerivTerms ) {

        r208_205m = inputValueModels[0];
        r208_205t = inputValueModels[1];
        molPb205t = inputValueModels[2];
        alphaPb = inputValueModels[3];
        molPb208b = inputValueModels[4];

        try {
            setValue(//
                    molPb205t.getValue().
                    multiply( r208_205m.getValue().
                    multiply( alphaPb.getValue().multiply( new BigDecimal( "3.0" ) ).add( BigDecimal.ONE ) ).
                    subtract( r208_205t.getValue() ) ).
                    subtract( molPb208b.getValue() ) );
        } catch (Exception e) {
        }

    }

}


text:
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Windows;
using Caliburn.Micro;
using Xemio.ImageUploader.Client.WebServices;
using Xemio.ImageUploader.Entities;

namespace Xemio.ImageUploader.Client.UserInterface.Views.Image
{
    public class ImageViewModel : Screen
    {
        #region Fields
        private readonly UploadedImagesClient _uploadedImagesClient;
        private readonly Session _session;

        private UploadedImage _image;
        private DateTime _createdDate;
        private byte[] _imageData;
        private string _imageExtension;
        #endregion

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="ImageViewModel" /> class.
        /// </summary>
        /// <param name="_uploadedImagesClient">The _uploaded images client.</param>
        /// <param name="session">The session.</param>
        public ImageViewModel(UploadedImagesClient _uploadedImagesClient, Session session)
        {
            this._uploadedImagesClient = _uploadedImagesClient;
            this._session = session;
        }
        #endregion

        #region Properties
        /// <summary>
        /// Gets or sets the image.
        /// </summary>
        public UploadedImage Image
        {
            get { return _image; }
            set
            {
                this._image = value;
                this.ImageExtension = this.Image.ImageExtension;
                this.CreatedDate = this.Image.CreatedDate;
            }
        }
        /// <summary>
        /// Gets or sets the created date.
        /// </summary>
        public DateTime CreatedDate
        {
            get { return this._createdDate; }
            private set
            {
                this._createdDate = value;
                this.NotifyOfPropertyChange(() => this.CreatedDate);
            }
        }
        /// <summary>
        /// Gets or sets the image extension.
        /// </summary>
        public string ImageExtension
        {
            get { return this._imageExtension; }
            private set
            {
                this._imageExtension = value;
                this.NotifyOfPropertyChange(() => this.ImageExtension);
            }
        }
        /// <summary>
        /// Gets or sets the image data.
        /// </summary>
        public byte[] ImageData
        {
            get { return this._imageData; }
            private set
            {
                this._imageData = value;
                this.NotifyOfPropertyChange(() => this.ImageData);
            }
        }
        #endregion

        #region Screen Member
        /// <summary>
        /// Called when initializing.
        /// </summary>
        protected override void OnInitialize()
        {
            this.LoadImageAsync();
        }
        #endregion

        #region Methods
        /// <summary>
        /// Opens the image in the browser.
        /// </summary>
        public void OpenImageInBrowser()
        {
            string url = this._uploadedImagesClient.GetUploadedImageAddress(this._session.CurrentUser, this.Image);

            Process.Start(url);
        }
        #endregion

        #region Private Methods
        /// <summary>
        /// Loads the image async.
        /// </summary>
        private async void LoadImageAsync()
        {
            if (this.Image == null)
                return;

            HttpResponseMessage response = await this._uploadedImagesClient.GetUploadedImage(this._session.CurrentUser, this.Image);
            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                string message = await response.Content.ReadAsStringAsync();
                MessageBox.Show(message);
            }
            else
            {
                this.ImageData = await response.Content.ReadAsByteArrayAsync();
            }
        }
        #endregion
    }
}


text:
"""Module for testing the del archetype command."""

import unittest

if __name__ == "__main__":
    from broker import utils
    utils.import_depends()

from broker.brokertest import TestBrokerCommand

class TestDelArchetype(TestBrokerCommand):

    def test_100_del_utarchetype1(self):
        command = ["del_archetype", "--archetype=utarchetype1"]
        self.noouttest(command)

    def test_100_del_utarchetype2(self):
        command = ["del_archetype", "--archetype=utarchetype2"]
        self.noouttest(command)

    def test_100_del_utarchetype3(self):
        command = ["del_archetype", "--archetype=utarchetype3"]
        self.noouttest(command)

    def test_105_verif_utarchetype1(self):
        command = ["show_archetype", "--archetype=utarchetype1"]
        self.notfoundtest(command)

    def test_110_del_utappliance(self):
        command = ["del_archetype", "--archetype=utappliance"]
        self.noouttest(command)

    def test_300_verify_all(self):
        command = ["show_archetype", "--all"]
        out = self.commandtest(command)
        self.matchclean(out, "utarchetype", command)
        self.matchclean(out, "utappliance", command)

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(TestDelArchetype)
    unittest.TextTestRunner(verbosity=2).run(suite)


text:
h1, h2, h3 {
    color: #24372C !important;
}

a {
    color: #259D57 !important;
}

a:active, a:hover, a:focus {
    color: #00B84D !important;
}

blockquote {
    font-size: 14px !important;
}

cite, code {
    padding: 1px 4px !important;
    font-size: 90% !important;
    color: #000 !important;
    background-color: #F5F5F5 !important;
    white-space: nowrap !important;
    border-radius: 4px !important;
    border: 1px solid #CCC !important;
    font-style: normal !important;
    font-family: Menlo,Monaco,Consolas,"Courier New",monospace !important;
}

.label {
    display: table-cell !important;
    color: #000 !important;
    font-size: 100% !important;
    text-align: left !important;
    width: 6em !important;
}

table.citation {
    border-left: 1px solid #DDD !important;
}

table.citation td > em {
    display: none !important;
}

.table > tbody > tr > td {
    border-top: 1px solid #DDD !important;
}

#navbar {
    background: #24372C !important;
    border: none !important;
    border-bottom: 4px solid #259D57 !important;
}

#navbar a {
    color: #FFF !important;
}

.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
    background-color: #259D57 !important;
}

.navbar-default .navbar-nav > li > a:active {
    background-color: #00B84D !important;
}

#navbar .dropdown-menu > li > a {
    color: #259D57 !important;
}

#navbar .dropdown-menu > li > a:hover {
    color: #FFF !important;
    background-color: #00B84D !important;
}

.navbar-default .navbar-nav > .open > a, .navbar-default .navbar-nav > .open > a:hover, .navbar-default .navbar-nav > .open > a:focus {
    background-color: #00B84D !important;
}


text:
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.

using System.IO;
using ImageMagick;
using ImageMagick.Formats;
using Xunit;

namespace Magick.NET.Tests
{
    public partial class JpegWriteDefinesTests
    {
        public class TheSamplingFactorProperty
        {
            [Fact]
            public void ShouldSetTheDefine()
            {
                AssertSetDefine("4x2,1x1,1x1", JpegSamplingFactor.Ratio410);
                AssertSetDefine("4x1,1x1,1x1", JpegSamplingFactor.Ratio411);
                AssertSetDefine("2x2,1x1,1x1", JpegSamplingFactor.Ratio420);
                AssertSetDefine("2x1,1x1,1x1", JpegSamplingFactor.Ratio422);
                AssertSetDefine("1x2,1x1,1x1", JpegSamplingFactor.Ratio440);
                AssertSetDefine("1x1,1x1,1x1", JpegSamplingFactor.Ratio444);
            }

            [Fact]
            public void ShouldWriteJpegWithTheCorrectSamplingFactor()
            {
                var defines = new JpegWriteDefines
                {
                    SamplingFactor = JpegSamplingFactor.Ratio420,
                };

                using (var input = new MagickImage(Files.Builtin.Logo))
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        input.Write(memoryStream, defines);

                        memoryStream.Position = 0;
                        using (var output = new MagickImage(memoryStream))
                        {
                            output.Read(memoryStream);

                            Assert.Equal("2x2,1x1,1x1", output.GetAttribute("jpeg:sampling-factor"));
                        }
                    }
                }
            }

            private static void AssertSetDefine(string expected, JpegSamplingFactor samplingFactor)
            {
                var defines = new JpegWriteDefines
                {
                    SamplingFactor = samplingFactor,
                };

                using (var image = new MagickImage())
                {
                    image.Settings.SetDefines(defines);

                    Assert.Equal(expected, image.Settings.GetDefine(MagickFormat.Jpeg, "sampling-factor"));
                }
            }
        }
    }
}


text:
$Title = 'VM Hardware Version'

# Test description: How New-VesterConfig explains this value to the user
$Description = 'Specifies the hardware version configuration for a VM'

# The config entry stating the desired values
$Desired = $cfg.vm.vmhardwareversion

# The test value's data type, to help with conversion: bool/string/int
$Type = 'string'

# The command(s) to pull the actual value for comparison
# $Object will scope to the folder this test is in (Cluster, Host, etc.)
[ScriptBlock]$Actual = {
    if (!$Desired)
	{
		Write-Output "vmx-13"
    }
    else
    {
		$MinimumVersion = $Desired.Split("-")[1]
		$VMsHardwareVersion = Get-VM -Name $Object

		# If a Hardwareversion lower than the desired minimu version is found
		if (($VMsHardwareVersion.ExtensionData.Config.Version).Split("-")[1] -lt $Desired.Split("-")[1])
		{
            		[string]$Object.ExtensionData.Config.Version
		}
		# If the Hardwareversion violation is in desired state
		# output $Desired so the test will succeed
		else
		{
			$Desired
		}
    }
}

# The command(s) to match the environment to the config
# Use $Object to help filter, and $Desired to set the correct value
[ScriptBlock]$Fix = {
    $Object | Set-Vm -Version $Desired
}


text:
class ApplicationView < Dry::View
  config.paths = Rails.root.join("app/templates")
  config.default_context = ApplicationViewContext.new
end


text:
'use strict';

var util = require('../util');

/**
 *
 * @param {Object} config
 * @param {Number} config.x The cell column number that the top left of the picture will start in
 * @param {Number} config.y The cell row number that the top left of the picture will start in
 * @param {Number} config.width Width in EMU's
 * @param {Number} config.height Height in EMU's
 * @constructor
 */

var OneCellAnchor = function (config) {
  this.x = null;
  this.y = null;
  this.xOff = null;
  this.yOff = null;
  this.width = null;
  this.height = null;
  if(config) {
    this.setPos(config.x, config.y, config.xOff, config.yOff);
    this.setDimensions(config.width, config.height);
  }
};

OneCellAnchor.prototype.setPos = function (x, y, xOff, yOff) {
  this.x = x;
  this.y = y;

  if (xOff !== undefined) {
    this.xOff = xOff;
  }
  if (yOff !== undefined) {
    this.yOff = yOff;
  }
};

OneCellAnchor.prototype.setDimensions = function (width, height) {
  this.width = width;
  this.height = height;
};

OneCellAnchor.prototype.toXML = function (xmlDoc, content) {
  var root = util.createElement(xmlDoc, 'xdr:oneCellAnchor');
  var from = util.createElement(xmlDoc, 'xdr:from');
  var fromCol = util.createElement(xmlDoc, 'xdr:col');
  fromCol.appendChild(xmlDoc.createTextNode(this.x));
  var fromColOff = util.createElement(xmlDoc, 'xdr:colOff');
  fromColOff.appendChild(xmlDoc.createTextNode(this.xOff || 0));
  var fromRow = util.createElement(xmlDoc, 'xdr:row');
  fromRow.appendChild(xmlDoc.createTextNode(this.y));
  var fromRowOff = util.createElement(xmlDoc, 'xdr:rowOff');
  fromRowOff.appendChild(xmlDoc.createTextNode(this.yOff || 0));
  from.appendChild(fromCol);
  from.appendChild(fromColOff);
  from.appendChild(fromRow);
  from.appendChild(fromRowOff);

  root.appendChild(from);

  var dimensions = util.createElement(xmlDoc, 'xdr:ext');
  dimensions.setAttribute('cx', this.width);
  dimensions.setAttribute('cy', this.height);
  root.appendChild(dimensions);

  root.appendChild(content);

  root.appendChild(util.createElement(xmlDoc, 'xdr:clientData'));

  return root;
};

module.exports = OneCellAnchor;


text:
import linksTransform from '../src/lib/links-in-new-tabs';

describe('links-in-new-tabs', () => {
  let mdIt;

  beforeEach(() => {
    mdIt = new MarkdownIt({ linkify: true, breaks: true }).use(linksTransform);
  });

  it('opens links prefixed with +tab+ in a _blank target by default', () => {
    const md = mdIt.renderInline('[Test](+tab+http://www.example.com)');
    expect(md).to.equal('Test');
  });

  it('renders normal links without a new tab prefix', () => {
    const md = mdIt.renderInline('[Test](http://www.example.com)');
    expect(md).to.equal('Test');
  });

  it('accepts a customizable prefix', () => {
    mdIt = new MarkdownIt({
      linkify: true,
      breaks: true
    }).use(linksTransform, {
      prefix: '=newtab='
    });

    const md = mdIt.renderInline('[Test](=newtab=http://www.example.com)');
    expect(md).to.equal('Test');
  });
});


text:
from json import loads
from unittest import TestCase
import time

import vagrant
import paramiko

from otto.connections.ssh import parallelCmd as Cmd

paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG)

class TestCmd(TestCase):
    @classmethod
    def setUpClass(cls):
        cls.vm = vagrant.Vagrant()
        cls.vm.up()
        c = cls.vm.conf()
        cls.ip = c.get('HostName')
        cls.port = c.get('Port')
        cls.password = 'vagrant'
        cls.user = 'vagrant'
        cls.many = 100

    @classmethod
    def tearDownClass(cls):
        cls.vm = vagrant.Vagrant()
        cls.vm.destroy()

    def test_paramiko_works(self):
        cmd = Cmd(self.user, self.ip, self.password, 'uname', int(self.port))
        cmd.client.connect(cmd.hostname, cmd.port, cmd.user, cmd.password)
        self.assertEqual(cmd.client.exec_command('uname')[1].read().strip(), 'SunOS')

    def test_run(self):
        cmd = Cmd(self.user, self.ip, self.password, 'uname', int(self.port))
        cmd.run()
        while not cmd.done:
            time.sleep(1)

        self.assertEqual(cmd.result[1].strip(), 'SunOS')

    def test_fio(self):
        cmd = Cmd(self.user, self.ip, self.password, 'sudo mkdir -p /ramfs', int(self.port))
        cmd.run()
        cmd.wait()

        cmd = Cmd(self.user, self.ip, self.password, 'sudo mount -t tmpfs -o size=3G -F tmpfs /ramfs/', int(self.port))
        cmd.run()
        cmd.wait()

        for _ in range(self.many):
            cmd = Cmd(self.user,
                      self.ip,
                      self.password,
                      "sudo /opt/csw/bin/fio --output-format=json --ioengine=solarisaio "
                      "--end_fsync=1 --direct=0 --fadvise_hint=0 "
                      "--thread --norandommap --randrepeat=0 --refill_buffers "
                      "--rwmixread=70 --runtime=35 --time_based --ramp_time=5 "
                      "--group_reporting --output-format=json --size=2G "
                      "--name='run5;1;randwrite;64k;64' "
                      "--sync=1 --rw=randwrite --bs=64k --iodepth=64",
                      port=int(self.port))
            cmd.run()
            cmd.wait()
            print cmd.command
            print cmd.result

            self.assertIsInstance(loads(cmd.result[1]), dict)

    def test_Manyloops(self):
        for _ in range(self.many):
            cmd = Cmd(self.user, self.ip, self.password, 'cat /usr/dict/words', int(self.port))
            cmd.run()
            cmd.wait()
            self.assertEqual(len(cmd.result[1]), 206695)  # TODO: calculate size then check against that

    def test_ManyConnections(self):
        connections = []
        for x in range(10):
            connections.append(Cmd(self.user, self.ip, self.password, 'cat /usr/dict/words', int(self.port)))
            print x

        for cmd in connections:
            cmd.run()

        while False in [cmd.done for cmd in connections]:
            time.sleep(.01)

        for cmd in connections:
            self.assertEqual(len(cmd.result[1]), 206695)  # TODO: calculate size then check against that


text:
package org.apache.ivy.util.url;

import java.io.File;
import java.net.URL;

import org.apache.ivy.util.FileUtil;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * Test BasicURLHandler
 */
public class BasicURLHandlerTest {
    // remote.test
    private File testDir;

    private BasicURLHandler handler;

    @Before
    public void setUp() {
        testDir = new File("build/BasicURLHandlerTest");
        testDir.mkdirs();

        handler = new BasicURLHandler();
    }

    @After
    public void tearDown() {
        FileUtil.forceDelete(testDir);
    }

   @Test
    public void testIsReachable() throws Exception {
        final int connectionTimeoutInMillis = 15000; // 15 seconds
        assertTrue(handler.isReachable(new URL("http://www.google.fr/"), connectionTimeoutInMillis));
        assertFalse(handler.isReachable(new URL("http://www.google.fr/unknownpage.html"), connectionTimeoutInMillis));

        assertTrue(handler.isReachable(new File("build.xml").toURI().toURL(), connectionTimeoutInMillis));
        assertFalse(handler.isReachable(new File("unknownfile.xml").toURI().toURL(), connectionTimeoutInMillis));

        // to test ftp we should know of an anonymous ftp site... !
        // assertTrue(handler.isReachable(new URL("ftp://ftp.mozilla.org/pub/dir.sizes")));
        assertFalse(handler.isReachable(new URL("ftp://ftp.mozilla.org/unknown.file"), 5000));
    }

    @Test
    public void testContentEncoding() throws Exception {
        assertDownloadOK(new URL("http://carsten.codimi.de/gzip.yaws/daniels.html"), new File(
                testDir, "gzip.txt"));
        assertDownloadOK(new URL(
                "http://carsten.codimi.de/gzip.yaws/daniels.html?deflate=on&zlib=on"), new File(
                testDir, "deflate-zlib.txt"));
        assertDownloadOK(new URL("http://carsten.codimi.de/gzip.yaws/daniels.html?deflate=on"),
            new File(testDir, "deflate.txt"));
        assertDownloadOK(new URL("http://carsten.codimi.de/gzip.yaws/a5.ps"), new File(testDir,
                "a5-gzip.ps"));
        assertDownloadOK(new URL("http://carsten.codimi.de/gzip.yaws/a5.ps?deflate=on"), new File(
                testDir, "a5-deflate.ps"));
        assertDownloadOK(new URL("http://carsten.codimi.de/gzip.yaws/nh80.pdf"), new File(testDir,
                "nh80-gzip.pdf"));
        assertDownloadOK(new URL("http://carsten.codimi.de/gzip.yaws/nh80.pdf?deflate=on"),
            new File(testDir, "nh80-deflate.pdf"));
    }

    private void assertDownloadOK(URL url, File file) throws Exception {
        handler.download(url, file, null);
        assertTrue(file.exists());
    }
}


text:
package iso20022

type ReceiveDelivery1Code string