text:
package info.guardianproject.otr.app.im.service;

import info.guardianproject.otr.app.im.IContactList;
import info.guardianproject.otr.app.im.IContactListListener;
import info.guardianproject.otr.app.im.ISubscriptionListener;
import info.guardianproject.otr.app.im.R;
import info.guardianproject.otr.app.im.engine.Address;
import info.guardianproject.otr.app.im.engine.Contact;
import info.guardianproject.otr.app.im.engine.ContactList;
import info.guardianproject.otr.app.im.engine.ContactListListener;
import info.guardianproject.otr.app.im.engine.ContactListManager;
import info.guardianproject.otr.app.im.engine.ImErrorInfo;
import info.guardianproject.otr.app.im.engine.ImException;
import info.guardianproject.otr.app.im.engine.Presence;
import info.guardianproject.otr.app.im.provider.Imps;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.net.Uri.Builder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.widget.Toast;

public class ContactListManagerAdapter extends
        info.guardianproject.otr.app.im.IContactListManager.Stub implements Runnable {

    ImConnectionAdapter mConn;
    ContentResolver mResolver;

    private ContactListManager mAdaptee;
    private ContactListListenerAdapter mContactListListenerAdapter;
    private SubscriptionRequestListenerAdapter mSubscriptionListenerAdapter;

    final RemoteCallbackList<IContactListListener> mRemoteContactListeners = new RemoteCallbackList<IContactListListener>();
    final RemoteCallbackList<ISubscriptionListener> mRemoteSubscriptionListeners = new RemoteCallbackList<ISubscriptionListener>();

    HashMap<Address, ContactListAdapter> mContactLists;
    // Temporary contacts are created when a peer is encountered, and that peer
    // is not yet on any contact list.
    HashMap<String, Contact> mTemporaryContacts;
    // Offline contacts are created from the local DB before the server contact lists
    // are loaded.
    HashMap<String, Contact> mOfflineContacts;

    HashSet<String> mValidatedContactLists;
    HashSet<String> mValidatedContacts;
    HashSet<String> mValidatedBlockedContacts;

    private long mAccountId;
    private long mProviderId;

    private Uri mAvatarUrl;
    private Uri mContactUrl;

    static final long FAKE_TEMPORARY_LIST_ID = -1;
    static final String[] CONTACT_LIST_ID_PROJECTION = { Imps.ContactList._ID };

    RemoteImService mContext;

    public ContactListManagerAdapter(ImConnectionAdapter conn) {
        mAdaptee = conn.getAdaptee().getContactListManager();
        mConn = conn;
        mContext = conn.getContext();
        mResolver = mContext.getContentResolver();

        new Thread(this).start();
    }

    public void run ()
    {
        mContactListListenerAdapter = new ContactListListenerAdapter();
        mSubscriptionListenerAdapter = new SubscriptionRequestListenerAdapter();
        mContactLists = new HashMap<Address, ContactListAdapter>();
        mTemporaryContacts = new HashMap<String, Contact>();
        mOfflineContacts = new HashMap<String, Contact>();
        mValidatedContacts = new HashSet<String>();
        mValidatedContactLists = new HashSet<String>();
        mValidatedBlockedContacts = new HashSet<String>();

        mAdaptee.addContactListListener(mContactListListenerAdapter);
        mAdaptee.setSubscriptionRequestListener(mSubscriptionListenerAdapter);

        mAccountId = mConn.getAccountId();
        mProviderId = mConn.getProviderId();

        Uri.Builder builder = Imps.Avatars.CONTENT_URI_AVATARS_BY.buildUpon();
        ContentUris.appendId(builder, mProviderId);
        ContentUris.appendId(builder, mAccountId);

        mAvatarUrl = builder.build();

        builder = Imps.Contacts.CONTENT_URI_CONTACTS_BY.buildUpon();
        ContentUris.appendId(builder, mProviderId);
        ContentUris.appendId(builder, mAccountId);

        mContactUrl = builder.build();

        seedInitialPresences();
        loadOfflineContacts();
    }

    private void loadOfflineContacts() {
        Cursor contactCursor = mResolver.query(mContactUrl, new String[] { Imps.Contacts.USERNAME },
                null, null, null);

        String[] addresses = new String[contactCursor.getCount()];
        int i = 0;
        while (contactCursor.moveToNext())
        {
            addresses[i++] = contactCursor.getString(0);

        }

        Contact[] contacts = mAdaptee.createTemporaryContacts(addresses);
        for (Contact contact : contacts)
                mOfflineContacts.put(contact.getAddress().getBareAddress(), contact);

        contactCursor.close();
    }

    public int createContactList(String name, List<Contact> contacts) {
        try {
            mAdaptee.createContactListAsync(name, contacts);
        } catch (ImException e) {
            return e.getImError().getCode();
        }

        return ImErrorInfo.NO_ERROR;
    }

    public int deleteContactList(String name) {
        try {
            mAdaptee.deleteContactListAsync(name);
        } catch (ImException e) {
            return e.getImError().getCode();
        }

        return ImErrorInfo.NO_ERROR;
    }

    public List<ContactListAdapter> getContactLists() {
        synchronized (mContactLists) {
            return new ArrayList<ContactListAdapter>(mContactLists.values());
        }
    }

    public int removeContact(String address) {

        closeChatSession(address);

        if (isTemporary(address)) {
            synchronized (mTemporaryContacts) {
                mTemporaryContacts.remove(address);
            }
        } else {
            synchronized (mContactLists) {
                for (ContactListAdapter list : mContactLists.values()) {
                    int resCode = list.removeContact(address);
                    if (ImErrorInfo.ILLEGAL_CONTACT_ADDRESS == resCode) {
                        // Did not find in this list, continue to remove from
                        // other list.
                        continue;
                    }
                    if (ImErrorInfo.NO_ERROR != resCode) {
                        return resCode;
                    }
                }

            }
        }

        String selection = Imps.Contacts.USERNAME + "=?";
        String[] selectionArgs = { address };
        mResolver.delete(mContactUrl, selection, selectionArgs);

        return ImErrorInfo.NO_ERROR;
    }

    public int setContactName(String address, String name) {
        // update the server
        try {
            mAdaptee.setContactName(address,name);
        } catch (ImException e) {
            return e.getImError().getCode();
        }
        // update locally
        String selection = Imps.Contacts.USERNAME + "=?";
        String[] selectionArgs = { address };
        ContentValues values = new ContentValues(1);
        values.put( Imps.Contacts.NICKNAME, name);
        int updated = mResolver.update(mContactUrl, values, selection, selectionArgs);
        if( updated != 1 ) {
            return ImErrorInfo.ILLEGAL_CONTACT_ADDRESS;
        }

        return ImErrorInfo.NO_ERROR;
    }

    public void approveSubscription(Contact address) {
        mAdaptee.approveSubscriptionRequest(address);
    }

    public void declineSubscription(Contact address) {
        mAdaptee.declineSubscriptionRequest(address);
    }

    public int blockContact(String address) {
        try {
            mAdaptee.blockContactAsync(address);
        } catch (ImException e) {
            return e.getImError().getCode();
        }

        return ImErrorInfo.NO_ERROR;
    }

    public int unBlockContact(String address) {
        try {
            mAdaptee.unblockContactAsync(address);
        } catch (ImException e) {
            RemoteImService.debug(e.getMessage());
            return e.getImError().getCode();
        }

        return ImErrorInfo.NO_ERROR;
    }

    public boolean isBlocked(String address) {
        try {
            return mAdaptee.isBlocked(address);
        } catch (ImException e) {
            RemoteImService.debug(e.getMessage());
            return false;
        }
    }

    public void registerContactListListener(IContactListListener listener) {
        if (listener != null) {
            mRemoteContactListeners.register(listener);
        }
    }

    public void unregisterContactListListener(IContactListListener listener) {
        if (listener != null) {
            mRemoteContactListeners.unregister(listener);
        }
    }

    public void registerSubscriptionListener(ISubscriptionListener listener) {
        if (listener != null) {
            mRemoteSubscriptionListeners.register(listener);
        }
    }

    public void unregisterSubscriptionListener(ISubscriptionListener listener) {
        if (listener != null) {
            mRemoteSubscriptionListeners.unregister(listener);
        }
    }

    public IContactList getContactList(String name) {
        return getContactListAdapter(name);
    }

    public void loadContactLists() {
        if (mAdaptee.getState() == ContactListManager.LISTS_NOT_LOADED) {
            clearValidatedContactsAndLists();
            mAdaptee.loadContactListsAsync();
        }
    }

    public int getState() {
        return mAdaptee.getState();
    }

    public Contact getContactByAddress(String address) {
        if (mAdaptee.getState() == ContactListManager.LISTS_NOT_LOADED) {
            return mOfflineContacts.get(address);
        }

        Contact c = mAdaptee.getContact(address);
        if (c == null) {
            synchronized (mTemporaryContacts) {
                return mTemporaryContacts.get(address);
            }
        } else {
            return c;
        }
    }

    public Contact[] createTemporaryContacts(String[] addresses) {
        Contact[] contacts = mAdaptee.createTemporaryContacts(addresses);

        for (Contact c : contacts)
            insertTemporary(c);
        return contacts;
    }

    public long queryOrInsertContact(Contact c) {
        long result;

        String username = mAdaptee.normalizeAddress(c.getAddress().getAddress());
        String selection = Imps.Contacts.USERNAME + "=?";
        String[] selectionArgs = { username };
        String[] projection = { Imps.Contacts._ID };

        Cursor cursor = mResolver.query(mContactUrl, projection, selection, selectionArgs, null);

        if (cursor != null && cursor.moveToFirst()) {
            result = cursor.getLong(0);
        } else {
            result = insertTemporary(c);
        }

        if (cursor != null) {
            cursor.close();
        }
        return result;
    }

    private long insertTemporary(Contact c) {
        synchronized (mTemporaryContacts) {
            mTemporaryContacts.put(mAdaptee.normalizeAddress(c.getAddress().getBareAddress()), c);
        }
        Uri uri = insertContactContent(c, FAKE_TEMPORARY_LIST_ID);
        return ContentUris.parseId(uri);
    }

    /**
     * Tells if a contact is a temporary one which is not in the list of
     * contacts that we subscribe presence for. Usually created because of the
     * user is having a chat session with this contact.
     *
     * @param address the address of the contact.
     * @return true if it's a temporary contact; false
     *         otherwise.
     */
    public boolean isTemporary(String address) {
        synchronized (mTemporaryContacts) {
            return mTemporaryContacts.containsKey(address);
        }
    }

    ContactListAdapter getContactListAdapter(String name) {
        synchronized (mContactLists) {
            for (ContactListAdapter list : mContactLists.values()) {
                if (name.equals(list.getName())) {
                    return list;
                }
            }

            return null;
        }
    }

    ContactListAdapter getContactListAdapter(Address address) {
        synchronized (mContactLists) {
            return mContactLists.get(address);
        }
    }

    private class Exclusion {
        private StringBuilder mSelection;
        private List<String> mSelectionArgs;
        private String mExclusionColumn;

        Exclusion(String exclusionColumn, Collection<String> items) {
            mSelection = new StringBuilder();
            mSelectionArgs = new ArrayList<String>();
            mExclusionColumn = exclusionColumn;
            for (String s : items) {
                add(s);
            }
        }

        public void add(String exclusionItem) {
            if (mSelection.length() == 0) {
                mSelection.append(mExclusionColumn + "!=?");
            } else {
                mSelection.append(" AND " + mExclusionColumn + "!=?");
            }
            mSelectionArgs.add(exclusionItem);
        }

        public String getSelection() {
            return mSelection.toString();
        }

        public String[] getSelectionArgs() {
            return (String[]) mSelectionArgs.toArray(new String[0]);
        }
    }

    private void removeObsoleteContactsAndLists() {
        // remove all contacts for this provider & account which have not been
        // added since login, yet still exist in db from a prior login
        Exclusion exclusion = new Exclusion(Imps.Contacts.USERNAME, mValidatedContacts);
        mResolver.delete(mContactUrl, exclusion.getSelection(), exclusion.getSelectionArgs());

        // remove all blocked contacts for this provider & account which have not been
        // added since login, yet still exist in db from a prior login
        exclusion = new Exclusion(Imps.BlockedList.USERNAME, mValidatedBlockedContacts);
        Uri.Builder builder = Imps.BlockedList.CONTENT_URI.buildUpon();
        ContentUris.appendId(builder, mProviderId);
        ContentUris.appendId(builder, mAccountId);
        Uri uri = builder.build();
        mResolver.delete(uri, exclusion.getSelection(), exclusion.getSelectionArgs());

        // remove all contact lists for this provider & account which have not been
        // added since login, yet still exist in db from a prior login
        exclusion = new Exclusion(Imps.ContactList.NAME, mValidatedContactLists);
        builder = Imps.ContactList.CONTENT_URI.buildUpon();
        ContentUris.appendId(builder, mProviderId);
        ContentUris.appendId(builder, mAccountId);
        uri = builder.build();
        mResolver.delete(uri, exclusion.getSelection(), exclusion.getSelectionArgs());

    }

    interface ContactListBroadcaster {
        void broadcast(IContactListListener listener) throws RemoteException;
    }

    interface SubscriptionBroadcaster {
        void broadcast(ISubscriptionListener listener) throws RemoteException;
    }

    final class ContactListListenerAdapter implements ContactListListener {
        private boolean mAllContactsLoaded;

        // class to hold contact changes made before mAllContactsLoaded
        private class StoredContactChange {
            int mType;
            ContactList mList;
            Contact mContact;

            StoredContactChange(int type, ContactList list, Contact contact) {
                mType = type;
                mList = list;
                mContact = contact;
            }
        }

        private Vector<StoredContactChange> mDelayedContactChanges = new Vector<StoredContactChange>();

        private void broadcast(ContactListBroadcaster callback) {
            synchronized (mRemoteContactListeners) {
                final int N = mRemoteContactListeners.beginBroadcast();
                for (int i = 0; i < N; i++) {
                    IContactListListener listener = mRemoteContactListeners.getBroadcastItem(i);
                    try {
                        callback.broadcast(listener);
                    } catch (RemoteException e) {
                        // The RemoteCallbackList will take care of removing the
                        // dead listeners.
                    }
                }
                mRemoteContactListeners.finishBroadcast();
            }
        }

        public void onContactsPresenceUpdate(final Contact[] contacts) {
            // The client listens only to presence updates for now. Update
            // the avatars first to ensure it can get the new avatar when
            // presence updated.
            // TODO: Don't update avatar now since none of the server supports it
            // updateAvatarsContent(contacts);
            updatePresenceContent(contacts);

            broadcast(new ContactListBroadcaster() {
                public void broadcast(IContactListListener listener) throws RemoteException {
                    listener.onContactsPresenceUpdate(contacts);
                }
            });
        }

        public void onContactChange(final int type, final ContactList list, final Contact contact) {
            ContactListAdapter removed = null;
            String notificationText = null;

            switch (type) {
            case LIST_LOADED:
            case LIST_CREATED:
                addContactListContent(list);
                break;

            case LIST_DELETED:
                removed = removeContactListFromDataBase(list.getName());
                // handle case where a list is deleted before mAllContactsLoaded
                if (!mAllContactsLoaded) {
                    // if a cached contact list is deleted before the actual contact list is
                    // downloaded from the server, we will have to remove the list again once
                    // once mAllContactsLoaded is true
                    if (!mValidatedContactLists.contains(list.getName())) {
                        mDelayedContactChanges.add(new StoredContactChange(type, list, contact));
                    }
                }
                break;

            case LIST_CONTACT_ADDED:
                long listId = getContactListAdapter(list.getAddress()).getDataBaseId();
                if (isTemporary(mAdaptee.normalizeAddress(contact.getAddress().getAddress()))) {
                    moveTemporaryContactToList(mAdaptee.normalizeAddress(contact.getAddress().getAddress()), listId);
                } else {

                    boolean exists = updateContact(contact, listId);

                    if (!exists)
                           insertContactContent(contact, listId);
                }
                notificationText = mContext.getResources().getString(R.string.add_contact_success,
                        contact.getName());
                // handle case where a contact is added before mAllContactsLoaded
                if (!mAllContactsLoaded) {
                    // if a contact is added to a cached contact list before the actual contact
                    // list is downloaded from the server, we will have to add the contact to
                    // the contact list once mAllContactsLoaded is true
                    if (!mValidatedContactLists.contains(list.getName())) {
                        mDelayedContactChanges.add(new StoredContactChange(type, list, contact));
                    }
                }
                break;

            case LIST_CONTACT_REMOVED:
                deleteContactFromDataBase(contact, list);
                // handle case where a contact is removed before mAllContactsLoaded
                if (!mAllContactsLoaded) {
                    // if a contact is added to a cached contact list before the actual contact
                    // list is downloaded from the server, we will have to add the contact to
                    // the contact list once mAllContactsLoaded is true
                    if (!mValidatedContactLists.contains(list.getName())) {
                        mDelayedContactChanges.add(new StoredContactChange(type, list, contact));
                    }
                }

                // Clear ChatSession if any.
                String address = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
                closeChatSession(address);

                notificationText = mContext.getResources().getString(
                        R.string.delete_contact_success, contact.getName());
                break;

            case LIST_RENAMED:
                updateListNameInDataBase(list);
                // handle case where a list is renamed before mAllContactsLoaded
                if (!mAllContactsLoaded) {
                    // if a contact list name is updated before the actual contact list is
                    // downloaded from the server, we will have to update the list name again
                    // once mAllContactsLoaded is true
                    if (!mValidatedContactLists.contains(list.getName())) {
                        mDelayedContactChanges.add(new StoredContactChange(type, list, contact));
                    }
                }
                break;

            case CONTACT_BLOCKED:
                insertBlockedContactToDataBase(contact);
                address = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
                updateContactType(address, Imps.Contacts.TYPE_BLOCKED);
                closeChatSession(address);
                notificationText = mContext.getResources().getString(
                        R.string.block_contact_success, contact.getName());
                break;

            case CONTACT_UNBLOCKED:
                removeBlockedContactFromDataBase(contact);
                notificationText = mContext.getResources().getString(
                        R.string.unblock_contact_success, contact.getName());
                // handle case where a contact is unblocked before mAllContactsLoaded
                if (!mAllContactsLoaded) {
                    // if a contact list name is updated before the actual contact list is
                    // downloaded from the server, we will have to update the list name again
                    // once mAllContactsLoaded is true
                    if (!mValidatedBlockedContacts.contains(contact.getName())) {
                        mDelayedContactChanges.add(new StoredContactChange(type, list, contact));
                    }
                }
                break;

            default:
                RemoteImService.debug("Unknown list update event!");
                break;
            }

            final ContactListAdapter listAdapter;
            if (type == LIST_DELETED) {
                listAdapter = removed;
            } else {
                listAdapter = (list == null) ? null : getContactListAdapter(list.getAddress());
            }

            broadcast(new ContactListBroadcaster() {
                public void broadcast(IContactListListener listener) throws RemoteException {
                    listener.onContactChange(type, listAdapter, contact);
                }
            });

            if (mAllContactsLoaded && notificationText != null) {
           //     mContext.showToast(notificationText, Toast.LENGTH_SHORT);
            }
        }

        public void onContactError(final int errorType, final ImErrorInfo error,
                final String listName, final Contact contact) {
            broadcast(new ContactListBroadcaster() {
                public void broadcast(IContactListListener listener) throws RemoteException {
                    listener.onContactError(errorType, error, listName, contact);
                }
            });
        }

        public void handleDelayedContactChanges() {
            for (StoredContactChange change : mDelayedContactChanges) {
                onContactChange(change.mType, change.mList, change.mContact);
            }
        }

        public void onAllContactListsLoaded() {
            mAllContactsLoaded = true;

            handleDelayedContactChanges();
            removeObsoleteContactsAndLists();

            broadcast(new ContactListBroadcaster() {
                public void broadcast(IContactListListener listener) throws RemoteException {
                    listener.onAllContactListsLoaded();
                }
            });
        }
    }

    final class SubscriptionRequestListenerAdapter extends ISubscriptionListener.Stub {

        public void onSubScriptionRequest(final Contact from, long providerId, long accountId) {
            String username = mAdaptee.normalizeAddress(from.getAddress().getAddress());
            String nickname = from.getName();
            queryOrInsertContact(from); // FIXME Miron
            Uri uri = insertOrUpdateSubscription(username, nickname,
                    Imps.Contacts.SUBSCRIPTION_TYPE_FROM,
                    Imps.Contacts.SUBSCRIPTION_STATUS_SUBSCRIBE_PENDING);

            boolean hadListener = broadcast(new SubscriptionBroadcaster() {
                public void broadcast(ISubscriptionListener listener) throws RemoteException {
                    listener.onSubScriptionRequest(from, mProviderId, mAccountId);
                }
            });

            if (!hadListener)
            {
                mContext.getStatusBarNotifier().notifySubscriptionRequest(mProviderId, mAccountId,
                        ContentUris.parseId(uri), username, nickname);
            }
        }

        public void onUnSubScriptionRequest(final Contact from, long providerId, long accountId) {
            String username = mAdaptee.normalizeAddress(from.getAddress().getAddress());
            String nickname = from.getName();

            //to be implemented - should prompt user to approve unsubscribe?
        }

        private boolean broadcast(SubscriptionBroadcaster callback) {
            boolean hadListener = false;

            synchronized (mRemoteSubscriptionListeners) {
                final int N = mRemoteSubscriptionListeners.beginBroadcast();
                for (int i = 0; i < N; i++) {
                    ISubscriptionListener listener = mRemoteSubscriptionListeners.getBroadcastItem(i);
                    try {
                        callback.broadcast(listener);
                        hadListener = true;
                    } catch (RemoteException e) {
                        // The RemoteCallbackList will take care of removing the
                        // dead listeners.
                    }
                }
                mRemoteSubscriptionListeners.finishBroadcast();
            }

            return hadListener;
        }

        public void onSubscriptionApproved(final Contact contact, long providerId, long accountId) {
            insertOrUpdateSubscription(contact.getAddress().getBareAddress(), null, Imps.Contacts.SUBSCRIPTION_TYPE_NONE,
                    Imps.Contacts.SUBSCRIPTION_STATUS_NONE);

            broadcast(new SubscriptionBroadcaster() {
                public void broadcast(ISubscriptionListener listener) throws RemoteException {
                    listener.onSubscriptionApproved(contact, mProviderId, mAccountId);
                }
            });
        }

        public void onSubscriptionDeclined(final Contact contact, long providerId, long accountId) {
            insertOrUpdateSubscription(contact.getAddress().getBareAddress(), null, Imps.Contacts.SUBSCRIPTION_TYPE_NONE,
                    Imps.Contacts.SUBSCRIPTION_STATUS_NONE);

            broadcast(new SubscriptionBroadcaster() {
                public void broadcast(ISubscriptionListener listener) throws RemoteException {
                    listener.onSubscriptionDeclined(contact, mProviderId, mAccountId);
                }
            });
        }

        public void onApproveSubScriptionError(final String contact, final ImErrorInfo error) {
            String displayableAddress = getDisplayableAddress(contact);
            String msg = mContext
                    .getString(R.string.approve_subscription_error, displayableAddress);
            mContext.showToast(msg, Toast.LENGTH_SHORT);
        }

        public void onDeclineSubScriptionError(final String contact, final ImErrorInfo error) {
            String displayableAddress = getDisplayableAddress(contact);
            String msg = mContext
                    .getString(R.string.decline_subscription_error, displayableAddress);
            mContext.showToast(msg, Toast.LENGTH_SHORT);
        }
    }

    String getDisplayableAddress(String impsAddress) {
        if (impsAddress.startsWith("wv:")) {
            return impsAddress.substring(3);
        }
        return impsAddress;
    }

    void insertBlockedContactToDataBase(Contact contact) {
        // Remove the blocked contact if it already exists, to avoid duplicates and
        // handle the odd case where a blocked contact's nickname has changed
        removeBlockedContactFromDataBase(contact);

        Uri.Builder builder = Imps.BlockedList.CONTENT_URI.buildUpon();
        ContentUris.appendId(builder, mProviderId);
        ContentUris.appendId(builder, mAccountId);
        Uri uri = builder.build();

        String username = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
        ContentValues values = new ContentValues(2);
        values.put(Imps.BlockedList.USERNAME, username);
        values.put(Imps.BlockedList.NICKNAME, contact.getName());

        mResolver.insert(uri, values);

        mValidatedBlockedContacts.add(username);
    }

    void removeBlockedContactFromDataBase(Contact contact) {
        String address = mAdaptee.normalizeAddress(contact.getAddress().getAddress());

        Uri.Builder builder = Imps.BlockedList.CONTENT_URI.buildUpon();
        ContentUris.appendId(builder, mProviderId);
        ContentUris.appendId(builder, mAccountId);

        Uri uri = builder.build();
        mResolver.delete(uri, Imps.BlockedList.USERNAME + "=?", new String[] { address });

        int type = isTemporary(address) ? Imps.Contacts.TYPE_TEMPORARY : Imps.Contacts.TYPE_NORMAL;
        updateContactType(address, type);
    }

    void moveTemporaryContactToList(String address, long listId) {
        synchronized (mTemporaryContacts) {
            mTemporaryContacts.remove(address);
        }
        ContentValues values = new ContentValues(2);
        values.put(Imps.Contacts.TYPE, Imps.Contacts.TYPE_NORMAL);
        values.put(Imps.Contacts.CONTACTLIST, listId);

        String selection = Imps.Contacts.USERNAME + "=? AND " + Imps.Contacts.TYPE + "="
                           + Imps.Contacts.TYPE_TEMPORARY;
        String[] selectionArgs = { address };

        mResolver.update(mContactUrl, values, selection, selectionArgs);
    }

    void updateContactType(String address, int type) {
        ContentValues values = new ContentValues(1);
        values.put(Imps.Contacts.TYPE, type);
        updateContact(address, values);
    }

    /**
     * Insert or update subscription request from user into the database.
     *
     * @param username
     * @param nickname
     * @param subscriptionType
     * @param subscriptionStatus
     */
    Uri insertOrUpdateSubscription(String username, String nickname, int subscriptionType,
            int subscriptionStatus) {
        Cursor cursor = mResolver.query(mContactUrl, new String[] { Imps.Contacts._ID },
                Imps.Contacts.USERNAME + "=?", new String[] { username }, null);
        if (cursor == null) {
            RemoteImService.debug("query contact " + username + " failed");
            return null;
        }

        Uri uri;
        if (cursor.moveToFirst()) {
            ContentValues values = new ContentValues(2);
            values.put(Imps.Contacts.SUBSCRIPTION_TYPE, subscriptionType);
            values.put(Imps.Contacts.SUBSCRIPTION_STATUS, subscriptionStatus);

            long contactId = cursor.getLong(0);
            uri = ContentUris.withAppendedId(Imps.Contacts.CONTENT_URI, contactId);
            mResolver.update(uri, values, null, null);
        } else {
            ContentValues values = new ContentValues(6);
            values.put(Imps.Contacts.USERNAME, username);
            values.put(Imps.Contacts.NICKNAME, nickname);
            values.put(Imps.Contacts.TYPE, Imps.Contacts.TYPE_NORMAL);
            values.put(Imps.Contacts.CONTACTLIST, FAKE_TEMPORARY_LIST_ID);
            values.put(Imps.Contacts.SUBSCRIPTION_TYPE, subscriptionType);
            values.put(Imps.Contacts.SUBSCRIPTION_STATUS, subscriptionStatus);

            uri = mResolver.insert(mContactUrl, values);
        }
        cursor.close();
        return uri;
    }

    boolean updateContact(Contact contact, long listId)
    {
        ContentValues values = getContactContentValues(contact, listId);
        return updateContact(mAdaptee.normalizeAddress(contact.getAddress().getAddress()),values);

    }
    boolean updateContact(String username, ContentValues values) {
        String selection = Imps.Contacts.USERNAME + "=?";
        String[] selectionArgs = { username };
        return (mResolver.update(mContactUrl, values, selection, selectionArgs)) > 0;
    }

    void updatePresenceContent(Contact[] contacts) {
        ArrayList<String> usernames = new ArrayList<String>();
        ArrayList<String> statusArray = new ArrayList<String>();
        ArrayList<String> customStatusArray = new ArrayList<String>();
        ArrayList<String> clientTypeArray = new ArrayList<String>();

        for (Contact c : contacts) {
            String username = mAdaptee.normalizeAddress(c.getAddress().getAddress());
            Presence p = c.getPresence();
            int status = convertPresenceStatus(p);
            String customStatus = p.getStatusText();
            int clientType = translateClientType(p);

            usernames.add(username);
            statusArray.add(String.valueOf(status));
            customStatusArray.add(customStatus);
            clientTypeArray.add(String.valueOf(clientType));
        }

        ContentValues values = new ContentValues();
        values.put(Imps.Contacts.ACCOUNT, mAccountId);
        putStringArrayList(values, Imps.Contacts.USERNAME, usernames);
        putStringArrayList(values, Imps.Presence.PRESENCE_STATUS, statusArray);
        putStringArrayList(values, Imps.Presence.PRESENCE_CUSTOM_STATUS, customStatusArray);
        putStringArrayList(values, Imps.Presence.CONTENT_TYPE, clientTypeArray);

        mResolver.update(Imps.Presence.BULK_CONTENT_URI, values, null, null);
    }

    void updateAvatarsContent(Contact[] contacts) {
        ArrayList<ContentValues> avatars = new ArrayList<ContentValues>();
        ArrayList<String> usernames = new ArrayList<String>();

        for (Contact contact : contacts) {
            byte[] avatarData = contact.getPresence().getAvatarData();
            if (avatarData == null) {
                continue;
            }

            String username = mAdaptee.normalizeAddress(contact.getAddress().getAddress());

            ContentValues values = new ContentValues(2);
            values.put(Imps.Avatars.CONTACT, username);
            values.put(Imps.Avatars.DATA, avatarData);
            avatars.add(values);
            usernames.add(username);
        }
        if (avatars.size() > 0) {
            // ImProvider will replace the avatar content if it already exist.
            mResolver.bulkInsert(mAvatarUrl, avatars.toArray(new ContentValues[avatars.size()]));

            // notify avatar changed
            Intent i = new Intent(ImServiceConstants.ACTION_AVATAR_CHANGED);
            i.putExtra(ImServiceConstants.EXTRA_INTENT_FROM_ADDRESS, usernames);
            i.putExtra(ImServiceConstants.EXTRA_INTENT_PROVIDER_ID, mProviderId);
            i.putExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, mAccountId);
            mContext.sendBroadcast(i);
        }
    }

    ContactListAdapter removeContactListFromDataBase(String name) {
        ContactListAdapter listAdapter = getContactListAdapter(name);
        if (listAdapter == null) {
            return null;
        }
        long id = listAdapter.getDataBaseId();

        // delete contacts of this list first
        mResolver.delete(mContactUrl, Imps.Contacts.CONTACTLIST + "=?",
                new String[] { Long.toString(id) });

        mResolver.delete(ContentUris.withAppendedId(Imps.ContactList.CONTENT_URI, id), null, null);
        synchronized (mContactLists) {
            return mContactLists.remove(listAdapter.getAddress());
        }
    }

    void addContactListContent(ContactList list) {
        String selection = Imps.ContactList.NAME + "=? AND " + Imps.ContactList.PROVIDER
                           + "=? AND " + Imps.ContactList.ACCOUNT + "=?";
        String[] selectionArgs = { list.getName(), Long.toString(mProviderId),
                                  Long.toString(mAccountId) };
        Cursor cursor = mResolver.query(Imps.ContactList.CONTENT_URI, CONTACT_LIST_ID_PROJECTION,
                selection, selectionArgs, null); // no sort order
        long listId = 0;
        Uri uri = null;
        try {
            if (cursor.moveToFirst()) {
                listId = cursor.getLong(0);
                uri = ContentUris.withAppendedId(Imps.ContactList.CONTENT_URI, listId);
            }
        } finally {
            cursor.close();
        }
        if (uri == null) {
            ContentValues contactListValues = new ContentValues(3);
            contactListValues.put(Imps.ContactList.NAME, list.getName());
            contactListValues.put(Imps.ContactList.PROVIDER, mProviderId);
            contactListValues.put(Imps.ContactList.ACCOUNT, mAccountId);

            uri = mResolver.insert(Imps.ContactList.CONTENT_URI, contactListValues);
            listId = ContentUris.parseId(uri);
        }

        mValidatedContactLists.add(list.getName());

        synchronized (mContactLists) {
            mContactLists.put(list.getAddress(), new ContactListAdapter(list, listId));
        }

        Cursor contactCursor = mResolver.query(mContactUrl, new String[] { Imps.Contacts.USERNAME },
                Imps.Contacts.CONTACTLIST + "=?", new String[] { "" + listId }, null);
        Set<String> existingUsernames = new HashSet<String>();

        while (contactCursor.moveToNext())
                existingUsernames.add(contactCursor.getString(0));

        contactCursor.close();

        Collection<Contact> contacts = list.getContacts();
        if (contacts == null || contacts.size() == 0) {
            return;
        }

        Iterator<Contact> iter = contacts.iterator();
        while (iter.hasNext()) {
            Contact c = iter.next();
            String address = mAdaptee.normalizeAddress(c.getAddress().getAddress());
            if (isTemporary(address)) {
                if (!existingUsernames.contains(address)) {
                    moveTemporaryContactToList(address, listId);
                }
                iter.remove();
            }
            mValidatedContacts.add(address);
        }

        ArrayList<String> usernames = new ArrayList<String>();
        ArrayList<String> nicknames = new ArrayList<String>();
        ArrayList<String> contactTypeArray = new ArrayList<String>();
        for (Contact c : contacts) {

            if (updateContact(c,listId))
                continue; //contact existed and was updated to this list

            String username = mAdaptee.normalizeAddress(c.getAddress().getAddress());
            String nickname = c.getName();

            int type = Imps.Contacts.TYPE_NORMAL;
            if (isTemporary(username)) {
                type = Imps.Contacts.TYPE_TEMPORARY;
            }
            if (isBlocked(username)) {
                type = Imps.Contacts.TYPE_BLOCKED;
            }

            usernames.add(username);
            nicknames.add(nickname);
            contactTypeArray.add(String.valueOf(type));
        }
        ContentValues values = new ContentValues(6);

        values.put(Imps.Contacts.PROVIDER, mProviderId);
        values.put(Imps.Contacts.ACCOUNT, mAccountId);
        values.put(Imps.Contacts.CONTACTLIST, listId);
        putStringArrayList(values, Imps.Contacts.USERNAME, usernames);
        putStringArrayList(values, Imps.Contacts.NICKNAME, nicknames);
        putStringArrayList(values, Imps.Contacts.TYPE, contactTypeArray);

        mResolver.insert(Imps.Contacts.BULK_CONTENT_URI, values);
    }

    private void putStringArrayList(ContentValues values, String key, ArrayList<String> nicknames) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream os = new ObjectOutputStream(bos);
            os.writeObject(nicknames);
            os.close();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        values.put(key, bos.toByteArray());

    }

    void updateListNameInDataBase(ContactList list) {
        ContactListAdapter listAdapter = getContactListAdapter(list.getAddress());

        Uri uri = ContentUris.withAppendedId(Imps.ContactList.CONTENT_URI,
                listAdapter.getDataBaseId());
        ContentValues values = new ContentValues(1);
        values.put(Imps.ContactList.NAME, list.getName());

        mResolver.update(uri, values, null, null);
    }

    void deleteContactFromDataBase(Contact contact, ContactList list) {

        String username = mAdaptee.normalizeAddress(contact.getAddress().getAddress());

        //if list is provided, then delete from one list
        if (list != null)
        {
            String selection = Imps.Contacts.USERNAME + "=? AND " + Imps.Contacts.CONTACTLIST + "=?";
            long listId = getContactListAdapter(list.getAddress()).getDataBaseId();
            String[] selectionArgs = { username, Long.toString(listId) };
            mResolver.delete(mContactUrl, selection, selectionArgs);

        }
        else //if it is null, delete from all
        {
            String selection = Imps.Contacts.USERNAME + "=?";
            String[] selectionArgs = { username };
            mResolver.delete(mContactUrl, selection, selectionArgs);

        }

        // clear the history message if the contact doesn't exist in any list
        // anymore.
        if (mAdaptee.getContact(contact.getAddress()) == null) {
            clearHistoryMessages(username);
        }
    }

    Uri insertContactContent(Contact contact, long listId) {
        ContentValues values = getContactContentValues(contact, listId);

        Uri uri = mResolver.insert(mContactUrl, values);

        ContentValues presenceValues = getPresenceValues(ContentUris.parseId(uri),
                contact.getPresence());

        mResolver.insert(Imps.Presence.CONTENT_URI, presenceValues);

        return uri;
    }

    private ContentValues getContactContentValues(Contact contact, long listId) {
        final String username = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
        final String nickname = contact.getName();
        int type = Imps.Contacts.TYPE_NORMAL;
        if (isTemporary(username)) {
            type = Imps.Contacts.TYPE_TEMPORARY;
        }
        if (isBlocked(username)) {
            type = Imps.Contacts.TYPE_BLOCKED;
        }

        ContentValues values = new ContentValues(4);
        values.put(Imps.Contacts.USERNAME, username);
        values.put(Imps.Contacts.NICKNAME, nickname);
        values.put(Imps.Contacts.CONTACTLIST, listId);
        values.put(Imps.Contacts.TYPE, type);
        return values;
    }

    void clearHistoryMessages(String contact) {
        Uri uri = Imps.Messages.getContentUriByContact(mAccountId, contact);
        mResolver.delete(uri, null, null);
    }

    private ContentValues getPresenceValues(long contactId, Presence p) {
        ContentValues values = new ContentValues(3);
        values.put(Imps.Presence.CONTACT_ID, contactId);
        values.put(Imps.Contacts.PRESENCE_STATUS, convertPresenceStatus(p));
        values.put(Imps.Contacts.PRESENCE_CUSTOM_STATUS, p.getStatusText());
        values.put(Imps.Presence.CLIENT_TYPE, translateClientType(p));
        return values;
    }

    private int translateClientType(Presence presence) {
        int clientType = presence.getClientType();
        switch (clientType) {
        case Presence.CLIENT_TYPE_MOBILE:
            return Imps.Presence.CLIENT_TYPE_MOBILE;
        default:
            return Imps.Presence.CLIENT_TYPE_DEFAULT;
        }
    }

    /**
     * Converts the presence status to the value defined for ImProvider.
     *
     * @param presence The presence from the IM engine.
     * @return The status value defined in for ImProvider.
     */
    public static int convertPresenceStatus(Presence presence) {
        switch (presence.getStatus()) {
        case Presence.AVAILABLE:
            return Imps.Presence.AVAILABLE;

        case Presence.IDLE:
            return Imps.Presence.IDLE;

        case Presence.AWAY:
            return Imps.Presence.AWAY;

        case Presence.DO_NOT_DISTURB:
            return Imps.Presence.DO_NOT_DISTURB;

        case Presence.OFFLINE:
            return Imps.Presence.OFFLINE;
        }

        // impossible...
        RemoteImService.debug("Illegal presence status value " + presence.getStatus());
        return Imps.Presence.AVAILABLE;
    }

    public void clearOnLogout() {
        clearValidatedContactsAndLists();
        clearTemporaryContacts();
        clearPresence();
    }

    /**
     * Clears the list of validated contacts and contact lists. As contacts and
     * contacts lists are added after login, contacts and contact lists are
     * stored as "validated contacts". After initial download of contacts is
     * complete, any contacts and contact lists that remain in the database, but
     * are not in the validated list, are obsolete and should be removed. This
     * function resets that list for use upon login.
     */
    private void clearValidatedContactsAndLists() {
        // clear the list of validated contacts, contact lists, and blocked contacts
        mValidatedContacts.clear();
        mValidatedContactLists.clear();
        mValidatedBlockedContacts.clear();
    }

    /**
     * Clear the temporary contacts in the database. As contacts are persist
     * between IM sessions, the temporary contacts need to be cleared after
     * logout.
     */
    private void clearTemporaryContacts() {
        String selection = Imps.Contacts.CONTACTLIST + "=" + FAKE_TEMPORARY_LIST_ID;
        mResolver.delete(mContactUrl, selection, null);
    }

    /**
     * Clears the presence of the all contacts. As contacts are persist between
     * IM sessions, the presence need to be cleared after logout.
     */
    void clearPresence() {
        StringBuilder where = new StringBuilder();
        where.append(Imps.Presence.CONTACT_ID);
        where.append(" in (select _id from contacts where ");
        where.append(Imps.Contacts.ACCOUNT);
        where.append("=");
        where.append(mAccountId);
        where.append(")");
        mResolver.delete(Imps.Presence.CONTENT_URI, where.toString(), null);
    }

    void closeChatSession(String address) {
        ChatSessionManagerAdapter chatSessionManager = (ChatSessionManagerAdapter) mConn
                .getChatSessionManager();
        ChatSessionAdapter session = (ChatSessionAdapter) chatSessionManager
                .getChatSession(address);
        if (session != null) {
            session.leave();
        }
    }

    void updateChatPresence(String address, String nickname, Presence p) {
        ChatSessionManagerAdapter sessionManager = (ChatSessionManagerAdapter) mConn
                .getChatSessionManager();
        // TODO: This only find single chat sessions, we need to go through all
        // active chat sessions and find if the contact is a participant of the
        // session.
        ChatSessionAdapter session = (ChatSessionAdapter) sessionManager.getChatSession(address);
        if (session != null) {
            session.insertPresenceUpdatesMsg(nickname, p);
        }
    }

    private void seedInitialPresences() {
        Builder builder = Imps.Presence.SEED_PRESENCE_BY_ACCOUNT_CONTENT_URI.buildUpon();
        ContentUris.appendId(builder, mAccountId);
        mResolver.insert(builder.build(), new ContentValues(0));
    }
}


text:
'use strict';

var Tuio = require('./lib/tuio');
require('./lib/tuio-time')(Tuio);
require('./lib/tuio-point')(Tuio);
require('./lib/tuio-container')(Tuio);
require('./lib/tuio-cursor')(Tuio);
require('./lib/tuio-object')(Tuio);
require('./lib/tuio-client')(Tuio);

module.exports = Tuio;

redpajama_set_name: RedPajamaGithub


text:
#include "api/media_stream_interface.h"
#include "api/media_types.h"

namespace webrtc {

const char* const MediaStreamTrackInterface::kVideoKind =
    cricket::kMediaTypeVideo;
const char* const MediaStreamTrackInterface::kAudioKind =
    cricket::kMediaTypeAudio;

VideoTrackInterface::ContentHint VideoTrackInterface::content_hint() const {
  return ContentHint::kNone;
}

bool AudioTrackInterface::GetSignalLevel(int* level) {
  return false;
}

rtc::scoped_refptr<AudioProcessorInterface>
AudioTrackInterface::GetAudioProcessor() {
  return nullptr;
}

const cricket::AudioOptions AudioSourceInterface::options() const {
  return {};
}

}  // namespace webrtc


text:
status :published
satisfies_need "101006"

country_name_query = SmartAnswer::Calculators::CountryNameFormatter.new
reg_data_query = SmartAnswer::Calculators::RegistrationsDataQuery.new
translator_query = SmartAnswer::Calculators::TranslatorLinks.new
country_has_no_embassy = SmartAnswer::Predicate::RespondedWith.new(%w(iran syria yemen))
exclude_countries = %w(holy-see british-antarctic-territory)
modified_card_only_countries = %w(czech-republic slovakia hungary poland switzerland)

# Q1
multiple_choice :where_did_the_death_happen? do
  save_input_as :where_death_happened
  option england_wales: :did_the_person_die_at_home_hospital?
  option scotland: :did_the_person_die_at_home_hospital?
  option northern_ireland: :did_the_person_die_at_home_hospital?
  option overseas: :which_country?
end

# Q2
multiple_choice :did_the_person_die_at_home_hospital? do
  option :at_home_hospital
  option :elsewhere
  calculate :died_at_home_hospital do
    responses.last == 'at_home_hospital'
  end
  next_node :was_death_expected?
end

# Q3
multiple_choice :was_death_expected? do
  option :yes
  option :no

  calculate :death_expected do
    responses.last == 'yes'
  end

  next_node :uk_result
end

# Q4
country_select :which_country?, exclude_countries: exclude_countries do
  save_input_as :country_of_death

  calculate :current_location do
    reg_data_query.registration_country_slug(responses.last) || responses.last
  end

  calculate :current_location_name_lowercase_prefix do
    country_name_query.definitive_article(country_of_death)
  end

  calculate :death_country_name_lowercase_prefix do
    current_location_name_lowercase_prefix
  end

  next_node_if(:commonwealth_result, reg_data_query.responded_with_commonwealth_country?)
  next_node_if(:no_embassy_result, country_has_no_embassy)
  next_node(:where_are_you_now?)
end

# Q5
multiple_choice :where_are_you_now? do
  option :same_country
  option another_country: :which_country_are_you_in_now?
  option :in_the_uk

  calculate :another_country do
    responses.last == 'another_country'
  end

  calculate :in_the_uk do
    responses.last == 'in_the_uk'
  end

  on_condition(->(_) { reg_data_query.class::ORU_TRANSITION_EXCEPTIONS.include?(country_of_death) }) do
    next_node_if(:embassy_result, responded_with('same_country'))
  end

  next_node_if(:oru_result, reg_data_query.died_in_oru_transitioned_country? | responded_with('in_the_uk'))
  next_node_if(:embassy_result, responded_with('same_country'))
  next_node(:which_country_are_you_in_now?)
end

# Q6
country_select :which_country_are_you_in_now?, exclude_countries: exclude_countries do
  calculate :current_location do
    reg_data_query.registration_country_slug(responses.last) || responses.last
  end

  calculate :current_location_name_lowercase_prefix do
    country_name_query.definitive_article(current_location)
  end

  next_node_if(:oru_result, reg_data_query.died_in_oru_transitioned_country?)
  next_node :embassy_result
end

outcome :commonwealth_result
outcome :no_embassy_result

outcome :uk_result do
  precalculate :content_sections do
    sections = PhraseList.new
    if where_death_happened == 'england_wales'
      sections << :intro_ew << :who_can_register
      sections << (died_at_home_hospital ? :who_can_register_home_hospital : :who_can_register_elsewhere)
      sections << :"what_you_need_to_do_#{death_expected ? :expected : :unexpected}"
      sections << :need_to_tell_registrar
      sections << :"documents_youll_get_ew_#{death_expected ? :expected : :unexpected}"
    else
      sections << :"intro_#{where_death_happened}"
    end
    sections
  end
end

outcome :oru_result do
  precalculate :button_data do
    {text: "Pay now", url: "https://pay-register-death-abroad.service.gov.uk/start"}
  end

  precalculate :translator_link_url do
    translator_query.links[country_of_death]
  end

  precalculate :translator_link do
    if translator_link_url
      PhraseList.new(:approved_translator_link)
    else
      PhraseList.new(:no_translator_link)
    end
  end

  precalculate :waiting_time do
    phrases = PhraseList.new
    if reg_data_query.class::ORU_TRANSITIONED_COUNTRIES.exclude?(country_of_death) && in_the_uk
      phrases << :registration_can_take_3_months
    else
      phrases << :registration_takes_3_days
    end
    phrases
  end

  precalculate :oru_documents_variant_death do
    if reg_data_query.class::ORU_DOCUMENTS_VARIANT_COUNTRIES_DEATH.include?(country_of_death)
      PhraseList.new(:"oru_documents_variant_#{country_of_death}")
    else
      PhraseList.new(:oru_documents_death)
    end
  end

  precalculate :oru_address do
    if in_the_uk
      PhraseList.new(:oru_address_uk)
    else
      PhraseList.new(:oru_address_abroad)
    end
  end

  precalculate :oru_courier_text do
    phrases = PhraseList.new
    if reg_data_query.class::ORU_COURIER_VARIANTS.include?(current_location)
      if current_location == 'cameroon'
        phrases << :oru_courier_text_cameroon
      else
        phrases << :"oru_courier_text_#{current_location}" << :oru_courier_text_common
      end
    else
      phrases << :oru_courier_text_default
    end
    phrases
  end
end

outcome :embassy_result do
  precalculate :documents_required_embassy_result do
    phrases = PhraseList.new
    if country_of_death == 'libya'
      phrases << :documents_list_embassy_libya
    elsif country_of_death == 'north-korea'
      phrases << :"documents_list_embassy_north-korea"
    else
      phrases << :documents_list_embassy
    end
    phrases
  end

  precalculate :embassy_high_commission_or_consulate do
    if reg_data_query.has_high_commission?(current_location)
      "British high commission"
    elsif reg_data_query.has_consulate?(current_location)
      "British embassy or consulate"
    elsif reg_data_query.has_trade_and_cultural_office?(current_location)
      "British Trade & Cultural Office"
    elsif reg_data_query.has_consulate_general?(current_location)
      "British consulate general"
    else
      "British embassy"
    end
  end

  precalculate :go_to_the_embassy_heading do
    unless reg_data_query.post_only_countries?(current_location)
      PhraseList.new(:go_to_the_embassy_heading_text)
    end
  end
  precalculate :booking_text_embassy_result do
    unless reg_data_query.post_only_countries?(current_location)
      phrases = PhraseList.new
      if current_location == 'hong-kong'
        phrases << :booking_text_embassy_hong_kong
      else
        phrases << :booking_text_embassy
      end
      phrases
    end
  end

  precalculate :post_only do
    if reg_data_query.post_only_countries?(current_location)
      PhraseList.new(:"post_only_#{current_location}")
    else
      ''
    end
  end
  precalculate :postal_form_url do
    reg_data_query.postal_form(current_location)
  end
  precalculate :postal_return_form_url do
    reg_data_query.postal_return_form(current_location)
  end

  precalculate :postal do
    phrases = PhraseList.new
    if modified_card_only_countries.include?(current_location)
      phrases << :"post_only_pay_by_card_countries"
    elsif reg_data_query.post_only_countries?(current_location)
      phrases << :"post_only_#{current_location}"
    elsif reg_data_query.register_death_by_post?(current_location)
      phrases = PhraseList.new(:postal_intro)
      if postal_form_url
        phrases << :postal_registration_by_form
      else
        phrases << :"postal_registration_#{current_location}"
      end
      phrases << :postal_delivery_form if postal_return_form_url
      phrases
    else
      ''
    end
  end

  precalculate :fees_for_consular_services do
    phrases = PhraseList.new
    if current_location == 'libya'
      phrases << :consular_service_fees_libya
    else
      phrases << :consular_service_fees
    end
    phrases
  end

  precalculate :cash_only do
    if reg_data_query.cheque_only?(current_location)
      PhraseList.new(:cheque_only)
    elsif reg_data_query.cash_only?(current_location)
      PhraseList.new(:cash_only)
    elsif reg_data_query.cash_and_card_only?(current_location)
      PhraseList.new(:cash_and_card)
    else
      ''
    end
  end

  precalculate :location do
    loc = WorldLocation.find(current_location)
    raise InvalidResponse unless loc
    loc
  end
  precalculate :organisation do
    location.fco_organisation
  end
  precalculate :overseas_passports_embassies do
    if organisation
      organisation.offices_with_service 'Births and Deaths registration service'
    else
      []
    end
  end

  precalculate :footnote do
    if reg_data_query.class::FOOTNOTE_EXCLUSIONS.include?(country_of_death)
      phrases = PhraseList.new(:footnote_exceptions)
      phrases << :"footnote_oru_variants_#{current_location}" if reg_data_query.class::ORU_TRANSITION_EXCEPTIONS.include?(current_location)
      phrases
    elsif country_of_death != current_location and reg_data_query.eastern_caribbean_countries?(country_of_death) and reg_data_query.eastern_caribbean_countries?(current_location)
      PhraseList.new(:footnote_caribbean)
    elsif reg_data_query.class::ORU_COURIER_VARIANTS.include?(current_location) and ! reg_data_query.class::ORU_COURIER_VARIANTS.include?(country_of_death)
      PhraseList.new(:footnote_oru_variants_intro,
                      :"footnote_oru_variants_#{current_location}",
                      :footnote_oru_variants_out)
    elsif another_country
      PhraseList.new(:footnote_another_country)
    else
      PhraseList.new(:footnote)
    end
  end
end


text:
package gate.alignment;

import java.io.Serializable;

/**
 * Exception that could occur while aligning annotations with one other
 *
 * @author niraj
 *
 */
public class AlignmentException extends Exception implements Serializable {

  private static final long serialVersionUID = 1147261517821203797L;

  public AlignmentException(String message, Throwable t) {
    super(message, t);
  }

  public AlignmentException(String message) {
    super(message);
  }

  public AlignmentException() {
    super();
  }

  public AlignmentException(Exception e) {
    super(e);
  }
}


text:
using namespace Oryol;
using namespace _priv;

//------------------------------------------------------------------------------
TEST(glTypesTest) {

    // glTexImage format
    // FIXME: incomplete
    CHECK(glTypes::asGLTexImageFormat(PixelFormat::RGBA8) == GL_RGBA);
    CHECK(glTypes::asGLTexImageFormat(PixelFormat::RGB8) == GL_RGB);
    CHECK(glTypes::asGLTexImageFormat(PixelFormat::R5G6B5) == GL_RGB);
    CHECK(glTypes::asGLTexImageFormat(PixelFormat::R5G5B5A1) == GL_RGBA);
    CHECK(glTypes::asGLTexImageFormat(PixelFormat::RGBA4) == GL_RGBA);
    CHECK(glTypes::asGLTexImageFormat(PixelFormat::RGBA32F) == GL_RGBA);
    CHECK(glTypes::asGLTexImageFormat(PixelFormat::RGBA16F) == GL_RGBA);
    CHECK(glTypes::asGLTexImageFormat(PixelFormat::DEPTH) == GL_DEPTH_COMPONENT);
    CHECK(glTypes::asGLTexImageFormat(PixelFormat::DEPTHSTENCIL) == GL_DEPTH_STENCIL);

    // glTexImage type
    // FIXME: incomplete
    CHECK(glTypes::asGLTexImageType(PixelFormat::RGBA8) == GL_UNSIGNED_BYTE);
    CHECK(glTypes::asGLTexImageType(PixelFormat::RGB8) == GL_UNSIGNED_BYTE);
    CHECK(glTypes::asGLTexImageType(PixelFormat::R5G6B5) == GL_UNSIGNED_SHORT_5_6_5);
    CHECK(glTypes::asGLTexImageType(PixelFormat::R5G5B5A1) == GL_UNSIGNED_SHORT_5_5_5_1);
    CHECK(glTypes::asGLTexImageType(PixelFormat::RGBA4) == GL_UNSIGNED_SHORT_4_4_4_4);
    CHECK(glTypes::asGLTexImageType(PixelFormat::DEPTH) == GL_UNSIGNED_SHORT);
    CHECK(glTypes::asGLTexImageType(PixelFormat::RGBA32F) == GL_FLOAT);
    CHECK(glTypes::asGLTexImageType(PixelFormat::RGBA16F) == GL_HALF_FLOAT);
    CHECK(glTypes::asGLTexImageType(PixelFormat::DEPTHSTENCIL) == GL_UNSIGNED_INT_24_8);
}


text:
"""
Resource Resolver
=================

This service provides global access to resources on disk, set up in
the configuration.
"""
__author__ = u"Andr\xe9 Malo"
__docformat__ = "restructuredtext en"

import datetime as _datetime
import errno as _errno
import os as _os
import sys as _sys

from wtf.config import ConfigurationError
from wtf import services as _services
from wtf import stream as _stream
from wtf import util as _util

class BuiltinModuleError(ConfigurationError):
    """ A builtin module was specified for relative reference """

class GlobalResources(object):
    """
    Globally visible resource service object

    :IVariables:
     - `__resources`: Resource mapping (``{'name': Resource}``)

    :Types:
     - `__resources`: ``dict``
    """

    def __init__(self, locator, resources):
        """
        Initialization

        :Parameters:
         - `resources`: Resource mapping (``{'name': Resource}``)

        :Types:
         - `resources`: ``dict``
        """
        self.__locate = locator
        self.__resources = resources

    def __call__(self, *args, **kwargs):
        return self.__locate(*args, **kwargs)

    def __getitem__(self, name):
        """
        Dict like resource getter

        :Parameters:
         - `name`: Name to look up

        :Types:
         - `name`: ``str``

        :Exceptions:
         - `KeyError`: Resource not found
        """
        return self.__resources[name]

    def __getattr__(self, name):
        """
        Attribute like resource getter

        :Parameters:
         - `name`: Name to look up

        :Types:
         - `name`: ``str``

        :Exceptions:
         - `AttributeError`: Resource not found
        """
        try:
            return self[name]
        except KeyError:
            raise AttributeError(name)

    def __contains__(self, name):
        """
        Check for availability of resource `name`

        :Parameters:
         - `name`: The resource name to look up

        :Types:
         - `name`: ``str``

        :return: Is the resource available (aka configured)?
        :rtype: ``bool``
        """
        return name in self.__resources

class ResourceService(object):
    """
    Resource Resolver

    This service provides global access to resources on disk.
    """
    __implements__ = [_services.ServiceInterface]

    def __init__(self, config, opts, args):
        """
        Initialization

        :See: `wtf.services.ServiceInterface.__init__`
        """
        self._locate = Locator(config)
        self._rsc = dict((key, [self._locate(item) for item in value])
            for key, value in config.resources)

    def shutdown(self):
        """ :See: `wtf.services.ServiceInterface.shutdown` """
        pass

    def global_service(self):
        """ :See: `wtf.services.ServiceInterface.global_service` """
        return 'wtf.resource', GlobalResources(self._locate, self._rsc)

    def middleware(self, func):
        """ :See: `wtf.services.ServiceInterface.middleware` """
        return func

class Locator(object):
    """
    Resource locator

    :IVariables:
     - `_config`: Configuration

    :Types:
     - `_config`: `wtf.config.Config`
    """

    def __init__(self, config):
        """
        Initialization

        :Parameters:
         - `config`: Configuration

        :Types:
         - `config`: `wtf.config.Config`
        """
        self._config = config

    def __call__(self, spec, isfile=False):
        """
        Locate a particular resource

        :Parameters:
         - `spec`: The specification
         - `isfile`: Does spec refer to a file?

        :Types:
         - `spec`: ``str``
         - `isfile`: ``bool``

        :return: A resource Container
        :rtype: `Resource`
        """
        if spec.startswith('pkg:') or spec.startswith('mod:'):
            rsc = Resource.frommodule(spec[4:], isfile)
        elif spec.startswith('dir:'):
            rsc = Resource(spec[4:], self._config.ROOT, isfile)
        else:
            try:
                rsc = Resource.frommodule(spec, isfile)
            except (IOError, ImportError):
                rsc = Resource(spec, self._config.ROOT, isfile)
        return rsc

class Resource(object):
    """
    Base resource container

    :IVariables:
     - `_base`: Base directory which is represented by this object

    :Types:
     - `_base`: ``unicode``
    """
    _encoding = _sys.getfilesystemencoding() or 'latin-1'

    def __new__(cls, base, root=None, isfile=False):
        """
        Construction

        :Parameters:
         - `base`: Base directory to represent
         - `root`: Root directory in case that `base` is relative. If it's
           ``None``, the current working directory is taken.
         - `isfile`: Does it refer to a file?

        :Types:
         - `base`: ``unicode``
         - `root`: ``str``
         - `isfile`: ``bool``

        :Exceptions:
         - `IOError`: path not found
        """
        if root is None:
            root = _os.getcwd().decode(cls._encoding)
        base = base.encode('utf-8')
        base = _os.path.normpath(
            _os.path.join(root.encode('utf-8'), base.encode('utf-8'))
        ).decode('utf-8')
        if isfile:
            basename = _os.path.basename(base)
            base = _os.path.normpath(_os.path.dirname(base))
        if not _os.path.isdir(base):
            raise IOError(_errno.ENOENT, base)

        self = super(Resource, cls).__new__(cls)
        self._base = base

        if isfile:
            return self.resolve(basename)
        return self

    @classmethod
    def frommodule(cls, base, isfile=False):
        """
        Determine a resource relative to a module

        :Parameters:
         - `base`: The combined module and path. Like:
           ``wtf.app.sample:static``. This resolves to the static subdirectory
           of the wtf.app.sample package. If the last part is a module, the
           directory is treated as parallel to the module, Like:
           ``wtf.app.sample.index:static`` resolves to the static subdir of
           wtf.app.sample, too; parallel to index.py.
         - `isfile`: Does it refer to a file?

        :Types:
         - `base`: ``unicode``
         - `isfile`: Does it refer to a file?

        :return: New resource instance
        :rtype: `Resource`

        :Exceptions:
         - `ImportError`: Module could not be imported
         - `BuiltinModuleError`: Module doesn't have a __file__ attribute
         - `UnicodeError`: Recoding according to the locale failed.
        """
        base = unicode(base)
        tup = base.split(u':', 1)
        if len(tup) == 1:
            modname, reldir = base, None
        else:
            modname, reldir = tup

        modname = modname.encode('ascii')
        mod = _util.load_dotted(modname)
        try:
            modfile = mod.__file__
        except AttributeError:
            raise BuiltinModuleError(
                "Cannot take builtin module %r as relative path reference" %
                (modname,)
            )

        tup = [_os.path.normpath(_os.path.dirname(
            modfile.decode(cls._encoding).encode('utf-8')))]
        if reldir is not None:
            reldir = _os.path.normpath(reldir.encode('utf-8'))
            root = _os.path.normpath('/')
            while reldir.startswith(root):
                reldir = reldir[1:]
            tup.append(reldir)
        return cls(_os.path.join(*tup).decode('utf-8'), isfile=isfile)

    def list(self):
        """
        List the directory

        :return: List of strings (as returned by ``os.listdir``)
        :rtype: ``list``
        """
        # pylint: disable = E1101

        return _os.listdir(self._base.encode(self._encoding))

    def resolve(self, name):
        """
        Resolve a filename relative to this directory

        :Parameters:
         - `name`: filename to resolve

        :Types:
         - `name`: ``unicode``

        :return: resolved filename in system encoding
        :rtype: ``str``

        :Exceptions:
         - `UnicodeError`: Recoding failed
        """
        # pylint: disable = E1101

        root = _os.path.normpath('/')
        resolved = _os.path.splitdrive(_os.path.normpath(
            _os.path.join(root, unicode(name).encode('utf-8'))
        ))[1]
        while resolved.startswith(root):
            resolved = resolved[1:]
        resolved = _os.path.normpath(
            _os.path.join(self._base, resolved)
        ).decode('utf-8')
        return FileResource(self, name, resolved.encode(self._encoding))

    def open(self, name, mode='rb', buffering=-1, blockiter=1):
        """
        Open a file relative to this directory

        :Parameters:
         - `name`: relative filename
         - `mode`: File open mode
         - `buffering`: buffer spec (``-1`` == default, ``0`` == unbuffered)
         - `blockiter`: Iterator mode
           (``<= 0: Default block size, 1: line, > 1: This block size``)

        :Types:
         - `name`: ``unicode``
         - `mode`: ``str``
         - `buffering`: ``int``
         - `blockiter`: ``int``

        :return: open stream
        :rtype: `ResourceStream`

        :Exceptions:
         - `IOError`: Error opening file
        """
        return self.resolve(name).open(mode, buffering, blockiter)

class FileResource(object):
    """
    Resource representing a file

    :IVariables:
     - `directory`: The directory resource
     - `resource`: The file resource name
     - `filename`: The full file name

    :Types:
     - `directory`: `Resource`
     - `resource`: ``unicode``
     - `filename`: ``str``
    """
    def __init__(self, directory, resource, filename):
        """
        Initialization

        :Parameters:
         - `directory`: The directory resource
         - `resource`: The file resource name
         - `filename`: The full file name

        :Types:
         - `directory`: `Resource`
         - `resource`: ``unicode``
         - `filename`: ``str``
        """
        self.directory = directory
        self.resource = resource
        self.filename = filename

    def open(self, mode='rb', buffering=-1, blockiter=1):
        """
        Open the file

        :Parameters:
         - `mode`: The opening mode
         - `buffering`: Buffering spec
         - `blockiter`: Iterator mode
           (``1: Line, <= 0: Default chunk size, > 1: This chunk size``)

        :Types:
         - `mode`: ``str``
         - `buffering`: ``int``
         - `blockiter`: ``int``

        :return: The open stream
        :rtype: `ResourceStream`
        """
        return ResourceStream(
            self.resource, self.filename, mode, buffering, blockiter
        )

class ResourceStream(_stream.GenericStream):
    """
    Extended generic stream, which provides more info about the resource

    :IVariables:
     - `_length`: Resource size in bytes. Retrieve it via len``(r)``
     - `resource`: The name, which the resource was resolved from
     - `last_modified`: Last modification time

    :Types:
     - `_length`: ``int``
     - `resource`: ``str``
     - `last_modified`: ``datetime.datetime``
    """

    def __new__(cls, resource, fullname, mode, buffering, blockiter):
        """
        Initialization

        :Parameters:
         - `resource`: Resource name (just for making it available)
         - `fullname`: Full name of the file to open
         - `mode`: File opening mode
         - `buffering`: Buffering spec
         - `blockiter`: Iterator mode

        :Types:
         - `resource`: ``str``
         - `fullname`: ``str``
         - `mode`: ``str``
         - `buffering`: ``int``
         - `blockiter`: ``int``
        """
        # pylint: disable = W0221

        stream = file(fullname, mode)
        self = super(ResourceStream, cls).__new__(
            cls, stream, buffering, blockiter, read_exact=True
        )
        self.resource = resource
        stres = _os.fstat(stream.fileno())
        self.last_modified = _datetime.datetime.utcfromtimestamp(
            stres.st_mtime
        )
        self._length = stres.st_size
        return self

    def __len__(self):
        """
        Determine the size of the resource in bytes

        :return: The resource size
        :rtype: ``int``
        """
        return self._length # pylint: disable = E1101


text:
class BaseTest {
  protected static java.util.List ourList;
}

class MyTest extends BaseTest {
  {
    <selection>ourList</selection>
  }
}


text:
module Azure::CognitiveServices::Autosuggest::V1_0
  module Models
    #
    # Defines the error that occurred.
    #
    class Error

      include MsRestAzure

      @@discriminatorMap = Hash.new

      def initialize
        @_type = "Error"
      end

      attr_accessor :_type

      # @return [ErrorCode] The error code that identifies the category of
      # error. Possible values include: 'None', 'ServerError',
      # 'InvalidRequest', 'RateLimitExceeded', 'InvalidAuthorization',
      # 'InsufficientAuthorization'. Default value: 'None' .
      attr_accessor :code

      # @return [String] A description of the error.
      attr_accessor :message

      # @return [String] A description that provides additional information
      # about the error.
      attr_accessor :more_details

      # @return [String] The parameter in the request that caused the error.
      attr_accessor :parameter

      # @return [String] The parameter's value in the request that was not
      # valid.
      attr_accessor :value

      #
      # Mapper for Error class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'Error',
          type: {
            name: 'Composite',
            polymorphic_discriminator: '_type',
            uber_parent: 'Error',
            class_name: 'Error',
            model_properties: {
              code: {
                client_side_validation: true,
                required: true,
                serialized_name: 'code',
                default_value: 'None',
                type: {
                  name: 'String'
                }
              },
              message: {
                client_side_validation: true,
                required: true,
                serialized_name: 'message',
                type: {
                  name: 'String'
                }
              },
              more_details: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'moreDetails',
                type: {
                  name: 'String'
                }
              },
              parameter: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'parameter',
                type: {
                  name: 'String'
                }
              },
              value: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'value',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\Equipo */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'idEquipo')->textInput() ?>

    <?= $form->field($model, 'Disciplina_idDisciplina')->textInput() ?>

    <?= $form->field($model, 'Nombre')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'Descripcion')->textInput(['maxlength' => true]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
#region Copyright notice

#endregion
using Newtonsoft.Json;
using System.Collections.Generic;

namespace DexterCS
{
    [JsonObject(MemberSerialization.OptIn)]
    public class ResultJsonParsing
    {
        [JsonProperty("snapshotId")]
        public long SnapshotId { get; set; }
        [JsonProperty("modulePath")]
        public string ModulePath { get; set; }
        [JsonProperty("fileName")]
        public string FileName { get; set; }
        [JsonProperty("fullFilePath")]
        public string FullFilePath { get; set; }
        [JsonProperty("groupId")]
        public string GroupId { get; set; }
        [JsonProperty("projectName")]
        public string ProjectName { get; set; }
        [JsonProperty("defectCount")]
        public int defectCount { get; set; }
        [JsonProperty("defectList")]
        public IList<DefectJsonParsing> DefectList { get; set; }
    }

    [JsonObject(MemberSerialization.OptIn)]
    public class DefectJsonParsing
    {
        [JsonProperty("message")]
        public string Message { get; set; }
        [JsonProperty("severityCode")]
        public string SeverityCode { get; set; }
        [JsonProperty("categoryName")]
        public string CategoryName { get; set; }
        [JsonProperty("analysisType")]
        public string AnalysisType { get; set; }
        [JsonProperty("occurences")]
        public IList<OccurenceJsonParsing> Occurences { get; set; }
        [JsonProperty("checkerCode")]
        public string CheckerCode { get; set; }
        [JsonProperty("className")]
        public string ClassName { get; set; }
        [JsonProperty("methodName")]
        public string MethodName { get; set; }
        [JsonProperty("toolName")]
        public string ToolName { get; set; }
        [JsonProperty("language")]
        public string Language { get; set; }
        [JsonProperty("fileStatus")]
        public string FileStatus { get; set; }
        [JsonProperty("modulePath")]
        public string ModulePath { get; set; }
        [JsonProperty("fileName")]
        public string FileName { get; set; }
    }

    [JsonObject(MemberSerialization.OptIn)]
    public class OccurenceJsonParsing
    {
        [JsonProperty("code")]
        public string Code { get; set; }
        [JsonProperty("startLine")]
        public int StartLine { get; set; }
        [JsonProperty("endLine")]
        public int EndLine { get; set; }
        [JsonProperty("charStart")]
        public int CharStart { get; set; }
        [JsonProperty("charEnd")]
        public int CharEnd { get; set; }
        [JsonProperty("variableName")]
        public string VariableName { get; set; }
        [JsonProperty("stringValue")]
        public string StringValue { get; set; }
        [JsonProperty("fieldName")]
        public string FieldName { get; set; }
        [JsonProperty("message")]
        public string Message { get; set; }
    }
}


text:
define('profit_calc', ['converter'], function (converter) {
	var template = `

 <input type="checkbox" name="enabler-{{value}}" checked enabler>
Investment {{value}}

 Cost Price<input type="number" name="costprice-{{value}}" value="0" min="0"> Volume<input type="number" name="volume-{{value}}" value="0" min="0"> Fee %<input type="number" name="fee-{{value}}" step="0.0001" value="0.0025" min="0" max="100">

`;
	function init(profitForm) {
		profitForm.addEventListener('input', calculateProfit)
		var enablers = profitForm.querySelectorAll('[enabler]')
		for(var i =0; i < enablers.length; i++){
			enablers[i].addEventListener('change', toggleGroupInputs)
		}
		profitForm.querySelector('[adder]').addEventListener('click', addInvestmentOptions)
		markDisabled(profitForm)
	}

	function bindEvents(div) {
		div.querySelector('[enabler]').addEventListener('change', toggleGroupInputs)
	}

	var trackIndex = 0;

	function calculateProfit(event) {
		var inputContainer = this.querySelector('[data-inputs-container]')
		var inputCounts = inputContainer.querySelectorAll('[data-index]').length
		var investedAmount = 0, coinData = [];
		var sellingInput = this.querySelector('[name="sellingprice"]')
		var sellValue = Number(sellingInput.value)
		for(var i=0; i < inputCounts; i++){
			coinData.push(getInputContainerData(inputContainer.querySelector('[data-index="'+i+'"]')))
		}
		this.querySelector('[name="profit"]').value = converter.profit(coinData, sellValue)
	}

	function toggleGroupInputs(event) {
		var container = this.closest('[data-index]')
		if(this.checked){
			container.removeAttribute('disable-body')
		} else {
			container.setAttribute('disable-body', '')
		}

		markDisabled(this.closest('form'))

	}

	function getInputContainerData(inputContainer) {
		var index = inputContainer.getAttribute('data-index');
		return {
			price : Number(inputContainer.querySelector('[name="costprice-'+index+'"]').value),
			count : Number(inputContainer.querySelector('[name="volume-'+index+'"]').value),
			fee   : Number(inputContainer.querySelector('[name="fee-'+index+'"]').value)
		}
	}

	function addInvestmentOptions(e){
		e.preventDefault()
		var node = generateInvestmentGroup()
		bindEvents(node)
		this.closest('#profit-calculator').querySelector('[data-inputs-container]').appendChild(node)
		markDisabled(this.closest('form'))
	}

	function generateInvestmentGroup(index) {
		var newIndex = index || getIndex()
		var div =  document.createElement('div')
		div.innerHTML = template.replace(/\{\{value\}\}/g, newIndex)
		return div.firstElementChild
	}

	function getIndex() {
		return ++trackIndex;
	}

	function markDisabled(formEl) {
		var checkedInputs = [];
		formEl.querySelectorAll('input[enabler]').forEach(function(input) {
			if(input.checked){
				checkedInputs.push(input)
			}
		})

		var disabledInput = formEl.querySelector('input[enabler][disabled]')
		if(checkedInputs.length > 1 && disabledInput){
			disabledInput.removeAttribute('disabled')
		} else if (checkedInputs.length === 1){
			checkedInputs[0].setAttribute('disabled', true)
		}
	}

	return {
		init : init,
		generate : generateInvestmentGroup
	}
})


text:
from django.conf.urls import patterns, include, url

urlpatterns = patterns(
    'calculation.views',
    url(r'^$', 'index'),
)


text:
import System.Environment
import System.Random
import System.Time
import Data.List
import CsvViewer.Types

main = do
   args <- getArgs
   now <- getClockTime
   clt <- toCalendarTime now

   let gen = mkStdGen $ fromInteger $ ctPicosec clt
       (cols, rows) = parseParams args

   putStrLn $ csvsifyTable $ createRandomTable gen rows cols

createRandomWord :: StdGen -> Int -> (String, StdGen)
createRandomWord gen range = (take n (randomRs ('A', 'z') g), g)
   where (n, g) = randomR (0,range) gen :: (Int, StdGen)

createRandomRow :: StdGen -> Int -> (Row, StdGen)
createRandomRow gen maxLength = randomList g n
   where (n, g) = randomR (0, maxLength) gen :: (Int, StdGen)
         randomList gl 0 = ([], gl)
         randomList gl n = (word : (fst $ randomList gw $ n-1), gw)
            where (word, gw) = createRandomWord gl mx
                  (mx, gx) = randomR(0, maxLength) gen :: (Int, StdGen)

createRandomTable :: StdGen -> Int -> Int -> [Row]
createRandomTable _ 0 _ = []
createRandomTable gen rows cols = r : rs
   where (r, g) = createRandomRow gen cols
         rs = createRandomTable g (rows-1) cols

csvsifyTable :: [Row] -> String
csvsifyTable rs = unlines (map (intercalate ";") rs)

dummy ::  Int -> Int -> String
dummy c r = (show c) ++ (show r)

-- createTable :: Int ->) Int -> String
-- createTable c r = show $ createRow cDjkh--
-- createRow :: Int -> [Int])
-- createRow c = take c $ randoms $ mkStdGen c :: Int
--
parseParams :: [String] -> (Int, Int)
parseParams [] = error "Expects first cols then rows as arguments"
parseParams (c:[]) =  ((read c),  (read c))
parseParams (c:r:[]) = ((read c), (read r))
parseParams (_:_:args) = error "Too many arguments"