text:
package com.itracker.android.data.message;

import android.database.Cursor;
import android.os.Environment;

import com.itracker.android.Application;
import com.itracker.android.R;
import com.itracker.android.data.NetworkException;
import com.itracker.android.data.OnLoadListener;
import com.itracker.android.data.SettingsManager;
import com.itracker.android.data.SettingsManager.ChatsShowStatusChange;
import com.itracker.android.data.account.AccountItem;
import com.itracker.android.data.account.AccountManager;
import com.itracker.android.data.account.ArchiveMode;
import com.itracker.android.data.account.OnAccountArchiveModeChangedListener;
import com.itracker.android.data.account.OnAccountDisabledListener;
import com.itracker.android.data.account.OnAccountRemovedListener;
import com.itracker.android.data.account.StatusMode;
import com.itracker.android.data.connection.ConnectionItem;
import com.itracker.android.data.connection.OnDisconnectListener;
import com.itracker.android.data.connection.OnPacketListener;
import com.itracker.android.data.entity.BaseEntity;
import com.itracker.android.data.entity.NestedMap;
import com.itracker.android.data.extension.archive.MessageArchiveManager;
import com.itracker.android.data.extension.blocking.BlockingManager;
import com.itracker.android.data.extension.blocking.PrivateMucChatBlockingManager;
import com.itracker.android.data.extension.file.FileManager;
import com.itracker.android.data.extension.muc.MUCManager;
import com.itracker.android.data.extension.muc.RoomChat;
import com.itracker.android.data.message.chat.MucPrivateChatNotification;
import com.itracker.android.data.notification.EntityNotificationProvider;
import com.itracker.android.data.notification.NotificationManager;
import com.itracker.android.data.roster.OnRosterReceivedListener;
import com.itracker.android.data.roster.OnStatusChangeListener;
import com.itracker.android.data.roster.RosterManager;
import com.itracker.android.utils.StringUtils;
import com.itracker.android.xmpp.address.Jid;
import com.itracker.android.xmpp.carbon.CarbonManager.Direction;
import com.itracker.android.xmpp.delay.Delay;

import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smackx.muc.packet.MUCUser;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Manage chats and its messages.
 *

 * Warning: message processing using chat instances should be changed.
 *
 * @author alexander.ivanov
 */
public class MessageManager implements OnLoadListener, OnPacketListener, OnDisconnectListener,
        OnAccountRemovedListener, OnAccountDisabledListener, OnRosterReceivedListener,
        OnAccountArchiveModeChangedListener, OnStatusChangeListener {

    private final static MessageManager instance;

    private final EntityNotificationProvider<MucPrivateChatNotification> mucPrivateChatRequestProvider;

    static {
        instance = new MessageManager();
        Application.getInstance().addManager(instance);
    }

    /**
     * Registered chats for bareAddresses in accounts.
     */
    private final NestedMap<AbstractChat> chats;
    /**
     * Visible chat.
     *

     * Will be null if there is no one.
     */
    private AbstractChat visibleChat;

    private MessageManager() {
        chats = new NestedMap<>();

        mucPrivateChatRequestProvider = new EntityNotificationProvider<>
                (R.drawable.ic_stat_muc_private_chat_request_white_24dp);
        mucPrivateChatRequestProvider.setCanClearNotifications(false);
    }

    public static MessageManager getInstance() {
        return instance;
    }

    /**
     * @param messageItems
     * @param clearId      Whether message id must be set to the null.
     * @return Collection with ids for specified messages.
     */
    static Collection<Long> getMessageIds(Collection<MessageItem> messageItems, boolean clearId) {
        ArrayList<Long> ids = new ArrayList<>();
        for (MessageItem messageItem : messageItems) {
            Long id = messageItem.getId();
            if (id == null) {
                continue;
            }
            ids.add(id);
            if (clearId) {
                messageItem.setId(null);
            }
        }
        return ids;
    }

    @Override
    public void onLoad() {
        final Set<BaseEntity> loadChats = new HashSet<BaseEntity>();
        Cursor cursor;
        cursor = MessageTable.getInstance().messagesToSend();
        try {
            if (cursor.moveToFirst()) {
                do {
                    loadChats.add(new BaseEntity(MessageTable.getAccount(cursor), MessageTable.getUser(cursor)));
                } while (cursor.moveToNext());
            }
        } finally {
            cursor.close();
        }
        Application.getInstance().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                onLoaded(loadChats);
            }
        });
    }

    private void onLoaded(Set<BaseEntity> loadChats) {
        NotificationManager.getInstance().registerNotificationProvider(mucPrivateChatRequestProvider);

        for (BaseEntity baseEntity : loadChats) {
            if (getChat(baseEntity.getAccount(), Jid.getBareAddress(baseEntity.getUser())) == null) {
                createChat(baseEntity.getAccount(), baseEntity.getUser());
            }
        }
    }

    /**
     * @param account
     * @param user
     * @return null if there is no such chat.
     */
    public AbstractChat getChat(String account, String user) {
        return chats.get(account, user);
    }

    public Collection<AbstractChat> getChats() {
        final Map<String, List<String>> blockedContacts = BlockingManager.getInstance().getBlockedContacts();
        final Map<String, Collection<String>> blockedMucContacts = new HashMap<>();//PrivateMucChatBlockingManager.getInstance().getBlockedContacts();
        List<AbstractChat> unblockedChats = new ArrayList<>();
        for (AbstractChat chat : chats.values()) {
            final List<String> blockedContactsForAccount = blockedContacts.get(chat.getAccount());
            if (blockedContactsForAccount != null) {
                if (blockedContactsForAccount.contains(chat.getUser())) {
                    continue;
                }
            }

            final Collection<String> blockedMucContactsForAccount = blockedMucContacts.get(chat.getAccount());
            if (blockedMucContactsForAccount != null) {
                if (blockedMucContactsForAccount.contains(chat.getUser())) {
                    continue;
                }
            }

            unblockedChats.add(chat);
        }

        return Collections.unmodifiableCollection(unblockedChats);
    }

    /**
     * Creates and adds new regular chat to be managed.
     *
     * @param account
     * @param user
     * @return
     */
    private RegularChat createChat(String account, String user) {
        RegularChat chat = new RegularChat(account, user, false);
        addChat(chat);
        return chat;
    }

    private RegularChat createPrivateMucChat(String account, String user) {
        RegularChat chat = new RegularChat(account, user, true);
        addChat(chat);
        return chat;
    }

    /**
     * Adds chat to be managed.
     *
     * @param chat
     */
    public void addChat(AbstractChat chat) {
        if (getChat(chat.getAccount(), chat.getUser()) != null) {
            throw new IllegalStateException();
        }
        chats.put(chat.getAccount(), chat.getUser(), chat);
    }

    /**
     * Removes chat from managed.
     *
     * @param chat
     */
    public void removeChat(AbstractChat chat) {
        chats.remove(chat.getAccount(), chat.getUser());
    }

    /**
     * Sends message. Creates and registers new chat if necessary.
     *
     * @param account
     * @param user
     * @param text
     */
    public void sendMessage(String account, String user, String text) {
        AbstractChat chat = getChat(account, user);
        if (chat == null) {
            chat = createChat(account, user);
        }
        sendMessage(text, chat);
    }

    private void sendMessage(String text, AbstractChat chat) {
        MessageItem messageItem = chat.newMessage(text);
        chat.sendQueue(messageItem);
    }

    public MessageItem createFileMessage(String account, String user, File file) {
        AbstractChat chat = getChat(account, user);
        if (chat == null) {
            chat = createChat(account, user);
        }

        chat.openChat();
        return chat.newFileMessage(FileManager.getFileName(file.getPath()), file, false);
    }

    public void replaceMessage(String account, String user, MessageItem srcFileMessage, String text) {
        AbstractChat chat = getChat(account, user);
        if (chat == null) {
            return;
        }

        chat.removeMessage(srcFileMessage);
        MessageItem messageItem = chat.newMessage(text);
        messageItem.setFile(srcFileMessage.getFile());
        chat.sendQueue(messageItem);
    }

    public void updateMessageWithError(String account, String user, MessageItem srcFileMessage, String text) {
        AbstractChat chat = getChat(account, user);
        if (chat == null) {
            return;
        }

        chat.removeMessage(srcFileMessage);
        chat.newFileMessage(String.format(Application.getInstance().getString(R.string.error_sending_file), text), srcFileMessage.getFile(), true);
    }

    /**
     * @param account
     * @param user
     * @return Where there is active chat.
     */
    public boolean hasActiveChat(String account, String user) {
        AbstractChat chat = getChat(account, user);
        return chat != null && chat.isActive();
    }

    /**
     * @return Collection with active chats.
     */
    public Collection<AbstractChat> getActiveChats() {
        Collection<AbstractChat> collection = new ArrayList<>();
        for (AbstractChat chat : chats.values()) {
            if (chat.isActive()) {
                collection.add(chat);
            }
        }
        return Collections.unmodifiableCollection(collection);
    }

    /**
     * Returns existed chat or create new one.
     *
     * @param account
     * @param user
     * @return
     */
    public AbstractChat getOrCreateChat(String account, String user) {
        String bareAddress = Jid.getBareAddress(user);

        if (MUCManager.getInstance().isMucPrivateChat(account, user)) {
            return getOrCreatePrivateMucChat(account, user);
        }

        AbstractChat chat = getChat(account, bareAddress);
        if (chat == null) {
            chat = createChat(account, bareAddress);
        }
        return chat;
    }

    public AbstractChat getOrCreatePrivateMucChat(String account, String user) {
        AbstractChat chat = getChat(account, user);
        if (chat == null) {
            chat = createPrivateMucChat(account, user);
        }
        return chat;
    }

    /**
     * Force open chat (make it active).
     *
     * @param account
     * @param user
     */
    public void openChat(String account, String user) {
        getOrCreateChat(account, user).openChat();
    }

    public void openPrivateMucChat(String account, String user) {
        getOrCreatePrivateMucChat(account, user).openChat();
    }

    /**
     * Closes specified chat (make it inactive).
     *
     * @param account
     * @param user
     */
    public void closeChat(String account, String user) {
        AbstractChat chat = getChat(account, user);
        if (chat == null) {
            return;
        }
        chat.closeChat();
    }

    public void requestToLoadLocalHistory(String account, String user) {
        AbstractChat chat = getChat(account, user);
        if (chat == null) {
            chat = createChat(account, user);
        }
        chat.requestToLoadLocalHistory();
    }

    /**
     * @param account
     * @param user
     * @return Last incoming message's text. Empty string if last message is
     * outgoing.
     */
    public String getLastText(String account, String user) {
        AbstractChat chat = getChat(account, user);
        if (chat == null) {
            return "";
        }
        return chat.getLastText();
    }

    /**
     * @param account
     * @param user
     * @return Time of last message in chat. Can be null.
     */
    public Date getLastTime(String account, String user) {
        AbstractChat chat = getChat(account, user);
        if (chat == null) {
            return null;
        }
        return chat.getLastTime();
    }

    /**
     * Sets currently visible chat.
     */
    public void setVisibleChat(BaseEntity visibleChat) {
        final boolean remove = !AccountManager.getInstance().getArchiveMode(visibleChat.getAccount()).saveLocally();
        AbstractChat chat = getChat(visibleChat.getAccount(), visibleChat.getUser());
        if (chat == null) {
            chat = createChat(visibleChat.getAccount(), visibleChat.getUser());
        } else {
            // Mark messages as read and them delete from db if necessary.
            final ArrayList<MessageItem> messageItems = new ArrayList<MessageItem>();
            for (MessageItem messageItem : chat.getMessages()) {
                if (!messageItem.isRead()) {
                    messageItem.markAsRead();
                    messageItems.add(messageItem);
                }
            }
            Application.getInstance().runInBackground(new Runnable() {
                @Override
                public void run() {
                    Collection<Long> ids = getMessageIds(messageItems, remove);
                    if (remove) {
                        MessageTable.getInstance().removeMessages(ids);
                    } else {
                        MessageTable.getInstance().markAsRead(ids);
                    }
                }
            });
        }
        this.visibleChat = chat;
    }

    /**
     * All chats become invisible.
     */
    public void removeVisibleChat() {
        visibleChat = null;
    }

    /**
     * @param chat
     * @return Whether specified chat is currently visible.
     */
    boolean isVisibleChat(AbstractChat chat) {
        return visibleChat == chat;
    }

    /**
     * Removes all messages from chat.
     *
     * @param account
     * @param user
     */
    public void clearHistory(String account, String user) {
        AbstractChat chat = getChat(account, user);
        if (chat == null) {
            return;
        }
        chat.removeAllMessages();
        onChatChanged(chat.getAccount(), chat.getUser(), false);
    }

    /**
     * Removes message from history.
     *
     * @param messageItem
     */
    public void removeMessage(MessageItem messageItem) {
        AbstractChat chat = messageItem.getChat();
        chat.removeMessage(messageItem);
        onChatChanged(chat.getAccount(), chat.getUser(), false);
    }

    /**
     * @param account
     * @param user
     * @return List of messages or empty list.
     */
    public Collection<MessageItem> getMessages(String account, String user) {
        AbstractChat chat = getChat(account, user);
        if (chat == null) {
            return Collections.emptyList();
        }
        return chat.getMessages();
    }

    /**
     * Called on action settings change.
     */
    public void onSettingsChanged() {
        ChatsShowStatusChange showStatusChange = SettingsManager.chatsShowStatusChange();
        Collection<BaseEntity> changedEntities = new ArrayList<>();
        for (AbstractChat chat : chats.values()) {
            if ((chat instanceof RegularChat && showStatusChange != ChatsShowStatusChange.always)
                    || (chat instanceof RoomChat && showStatusChange == ChatsShowStatusChange.never)) {
                // Remove actions with status change.
                ArrayList<MessageItem> remove = new ArrayList<>();
                for (MessageItem messageItem : chat.getMessages()) {
                    if (messageItem.getAction() != null && messageItem.getAction().isStatusChage()) {
                        remove.add(messageItem);
                    }
                }
                if (remove.isEmpty()) {
                    continue;
                }
                for (MessageItem messageItem : remove) {
                    chat.removeMessage(messageItem);
                }
                changedEntities.add(chat);
            }
        }
        RosterManager.getInstance().onContactsChanged(changedEntities);
    }

    @Override
    public void onAccountArchiveModeChanged(AccountItem accountItem) {
        final ArchiveMode archiveMode = AccountManager.getInstance().getArchiveMode(accountItem.getAccount());
        if (archiveMode.saveLocally()) {
            return;
        }
        final String account = accountItem.getAccount();
        final ArrayList<MessageItem> removeMessageItems = new ArrayList<MessageItem>();
        for (AbstractChat chat : chats.getNested(account).values()) {
            for (MessageItem messageItem : chat.getMessages()) {
                if (archiveMode == ArchiveMode.dontStore || ((messageItem.isRead()
                        || archiveMode != ArchiveMode.unreadOnly) && messageItem.isSent())) {
                    removeMessageItems.add(messageItem);
                }
            }
        }
        Application.getInstance().runInBackground(new Runnable() {
            @Override
            public void run() {
                // If message was read or received after removeMessageItems
                // was created then it's ID will be not null. DB actions with
                // such message will have no effect as if it was removed.
                // History ids becomes invalid and will be cleared on next
                // history load.
                MessageTable.getInstance().removeMessages(getMessageIds(removeMessageItems, true));
                if (archiveMode == ArchiveMode.dontStore) {
                    MessageTable.getInstance().removeAccount(account);
                } else if (archiveMode == ArchiveMode.unreadOnly) {
                    MessageTable.getInstance().removeReadAndSent(account);
                } else {
                    MessageTable.getInstance().removeSent(account);
                }
            }
        });
        AccountManager.getInstance().onAccountChanged(accountItem.getAccount());
    }

    @Override
    public void onPacket(ConnectionItem connection, String bareAddress, Stanza packet) {
        if (!(connection instanceof AccountItem)) {
            return;
        }
        String account = ((AccountItem) connection).getAccount();
        if (bareAddress == null) {
            return;
        }
        if (packet instanceof Message
                && MessageArchiveManager.getInstance().isModificationsSucceed(account)
                && Delay.isOfflineMessage(Jid.getServer(account), packet)) {
            // Ignore offline message if modification from server side message
            // archive have been received.
            return;
        }

        String contact = bareAddress;

        if (packet instanceof Message) {
            Message message = (Message) packet;
            if (MUCManager.getInstance().hasRoom(account, bareAddress)
                    && message.getType() != Message.Type.groupchat ) {
                contact = packet.getFrom();
            }
        }

        final String user = packet.getFrom();
        boolean processed = false;
        for (AbstractChat chat : chats.getNested(account).values()) {
            if (chat.onPacket(contact, packet)) {
                processed = true;
                break;
            }
        }

        final AbstractChat chat = getChat(account, user);

        if (chat != null && packet instanceof Message) {
            if (chat.isPrivateMucChat() && !chat.isPrivateMucChatAccepted()) {
                if (mucPrivateChatRequestProvider.get(chat.getAccount(), chat.getUser()) == null) {
                    if (!PrivateMucChatBlockingManager.getInstance().getBlockedContacts(account).contains(chat.getUser())) {
                        mucPrivateChatRequestProvider.add(new MucPrivateChatNotification(account, user), true);
                    }
                }
            }

            return;
        }
        if (!processed && packet instanceof Message) {
            final Message message = (Message) packet;
            final String body = message.getBody();
            if (body == null) {
                return;
            }

            if (message.getType() == Message.Type.chat && MUCManager.getInstance().hasRoom(account, Jid.getBareAddress(user))) {
                createPrivateMucChat(account, user).onPacket(contact, packet);
                if (!PrivateMucChatBlockingManager.getInstance().getBlockedContacts(account).contains(user)) {
                    mucPrivateChatRequestProvider.add(new MucPrivateChatNotification(account, user), true);
                }
                return;
            }

            for (ExtensionElement packetExtension : message.getExtensions()) {
                if (packetExtension instanceof MUCUser) {
                    return;
                }
            }

            createChat(account, user).onPacket(contact, packet);
        }
    }

    public void displayForwardedMessage(ConnectionItem connection, Message message, Direction direction) {

        if (!(connection instanceof AccountItem))
            return;
        String account = ((AccountItem) connection).getAccount();
        if (MessageArchiveManager.getInstance().isModificationsSucceed(account)
                && Delay.isOfflineMessage(Jid.getServer(account), message)) {
            // Ignore offline message if modification from server side message
            // archive have been received.
            return;
        }

        if (direction == Direction.sent) {
            String companion = Jid.getBareAddress(message.getTo());
            if (companion == null) {
                return;
            }
            AbstractChat chat = getChat(account, companion);
            if (chat == null) {
                chat = createChat(account, companion);
            }
            String body = message.getBody();
            if (body == null) {
                return;
            }
            chat.newMessage(body);
            return;
        }

        String companion = Jid.getBareAddress(message.getFrom());
        boolean processed = false;
        for (AbstractChat chat : chats.getNested(account).values()) {
            if (chat.onPacket(companion, message)) {
                processed = true;
                break;
            }
        }
        if (getChat(account, companion) != null) {
            return;
        }
        if (processed) {
            return;
        }
        final String body = message.getBody();
        if (body == null) {
            return;
        }
        createChat(account, companion).onPacket(companion, message);

    }
    @Override
    public void onRosterReceived(AccountItem accountItem) {
        String account = accountItem.getAccount();
        for (AbstractChat chat : chats.getNested(account).values()) {
            chat.onComplete();
        }
    }

    @Override
    public void onDisconnect(ConnectionItem connection) {
        if (!(connection instanceof AccountItem)) {
            return;
        }
        String account = ((AccountItem) connection).getAccount();
        for (AbstractChat chat : chats.getNested(account).values()) {
            chat.onDisconnect();
        }
    }

    @Override
    public void onAccountRemoved(AccountItem accountItem) {
        chats.clear(accountItem.getAccount());
    }

    @Override
    public void onAccountDisabled(AccountItem accountItem) {
        chats.clear(accountItem.getAccount());
    }

    /**
     * Export chat to file with specified name.
     *
     * @param account
     * @param user
     * @param fileName
     * @throws NetworkException
     */
    public File exportChat(String account, String user, String fileName) throws NetworkException {
        final File file = new File(Environment.getExternalStorageDirectory(), fileName);
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter(file));
            final String titleName = RosterManager.getInstance().getName(account, user) + " (" + user + ")";
            out.write("<title>");
            out.write(StringUtils.escapeHtml(titleName));
            out.write("</title>");
            final AbstractChat abstractChat = getChat(account, user);
            if (abstractChat != null) {
                final boolean isMUC = abstractChat instanceof RoomChat;
                final String accountName = AccountManager.getInstance().getNickName(account);
                final String userName = RosterManager.getInstance().getName(account, user);
                for (MessageItem messageItem : abstractChat.getMessages()) {
                    if (messageItem.getAction() != null) {
                        continue;
                    }
                    final String name;
                    if (isMUC) {
                        name = messageItem.getResource();
                    } else {
                        if (messageItem.isIncoming()) {
                            name = userName;
                        } else {
                            name = accountName;
                        }
                    }
                    out.write("");
                    out.write(StringUtils.escapeHtml(name));
                    out.write(" (");
                    out.write(StringUtils.getDateTimeText(messageItem.getTimestamp()));
                    out.write(")
\n
");
                    out.write(StringUtils.escapeHtml(messageItem.getText()));
                    out.write("

\n");
                }
            }
            out.write("");
            out.close();
        } catch (IOException e) {
            throw new NetworkException(R.string.FILE_NOT_FOUND);
        }
        return file;
    }

    /**
     * Notifies registered {@link OnChatChangedListener}.
     *
     * @param account
     * @param user
     * @param incoming
     */
    public void onChatChanged(final String account, final String user,
                              final boolean incoming) {
        Application.getInstance().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                for (OnChatChangedListener onChatChangedListener
                        : Application.getInstance().getUIListeners(OnChatChangedListener.class)) {
                    onChatChangedListener.onChatChanged(account, user, incoming);
                }
            }
        });
    }

    private boolean isStatusTrackingEnabled(String account, String bareAddress) {
        if (SettingsManager.chatsShowStatusChange() != ChatsShowStatusChange.always) {
            return false;
        }
        AbstractChat abstractChat = getChat(account, bareAddress);
        return abstractChat != null && abstractChat instanceof RegularChat && abstractChat.isStatusTrackingEnabled();
    }

    @Override
    public void onStatusChanged(String account, String bareAddress, String resource, String statusText) {
        if (isStatusTrackingEnabled(account, bareAddress)) {
            getChat(account, bareAddress).newAction(resource, statusText, ChatAction.status);
        }
    }

    @Override
    public void onStatusChanged(String account, String bareAddress, String resource,
                                StatusMode statusMode, String statusText) {
        if (isStatusTrackingEnabled(account, bareAddress)) {
            getChat(account, bareAddress).newAction(resource, statusText, ChatAction.getChatAction(statusMode));
        }
    }

    public void acceptMucPrivateChat(String account, String user) {
        mucPrivateChatRequestProvider.remove(account, user);
        getOrCreatePrivateMucChat(account, user).setIsPrivateMucChatAccepted(true);
    }

    public void discardMucPrivateChat(String account, String user) {
        mucPrivateChatRequestProvider.remove(account, user);
    }
}


text:
namespace AutoTest.ArgNullEx.Xunit
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using AutoTest.ArgNullEx.Filter;
    using global::Xunit;

    public class ExcludeAllAttributeShould
    {
        [Theory, AutoMock]
        public void BeACustomization(ExcludeAllAttribute sut)
        {
            // Assert
            Assert.IsAssignableFrom<IArgNullExCustomization>(sut);
            Assert.IsAssignableFrom<CustomizeAttribute>(sut);
        }

        [Fact]
        public void HaveDefaultExclusionTypeOfTypes()
        {
            // Act
            var sut = new ExcludeAllAttribute();

            // Assert
            Assert.Equal(ExclusionType.Types, sut.ExclusionType);
        }

        [Theory, AutoMock]
        public void ReturnSelfCustomization(ExcludeAllAttribute sut, MethodInfo method)
        {
            // Act
            IArgNullExCustomization customization = sut.GetCustomization(method);

            // Assert
            Assert.Same(sut, customization);
        }

        private static void AssertSingleExcludeAllTypesRule(IRegexFilter regexFilter)
        {
            RegexRule regexRule = regexFilter.TypeRules.Single();
            Assert.False(regexRule.Include);
            Assert.Matches(regexRule.Type, Guid.NewGuid().ToString());
        }

        private static void AssertSingleExcludeAllMethodsRule(IRegexFilter regexFilter)
        {
            RegexRule regexRule = regexFilter.MethodRules.Single();
            Assert.False(regexRule.Include);
            Assert.Null(regexRule.Type);
            Assert.Matches(regexRule.Method, Guid.NewGuid().ToString());
        }

        private static void AssertSingleExcludeAllParametersRule(IRegexFilter regexFilter)
        {
            RegexRule regexRule = regexFilter.ParameterRules.Single();
            Assert.False(regexRule.Include);
            Assert.Null(regexRule.Type);
            Assert.Null(regexRule.Method);
            Assert.Matches(regexRule.Parameter, Guid.NewGuid().ToString());
        }

        [Theory, AutoMock]
        public void ExcludeAllTypes(
            ExcludeAllAttribute sut,
            MethodInfo method)
        {
            // Arrange
            sut.ExclusionType = ExclusionType.Types;
            var fixture = new ArgumentNullExceptionFixture(GetType().GetTypeInfo().Assembly);
            IArgNullExCustomization customization = sut.GetCustomization(method);

            // Act
            customization.Customize(fixture);
            IEnumerable<MethodData> data = fixture.GetData();

            // Assert
            Assert.Empty(data);
            IRegexFilter regexFilter = fixture.Filters.OfType<IRegexFilter>().Single();
            Assert.Single(regexFilter.Rules);
            AssertSingleExcludeAllTypesRule(regexFilter);
        }

        [Theory, AutoMock]
        public void ExcludeAllMethods(
            ExcludeAllAttribute sut,
            MethodInfo method)
        {
            // Arrange
            sut.ExclusionType = ExclusionType.Methods;
            var fixture = new ArgumentNullExceptionFixture(GetType().GetTypeInfo().Assembly);
            IArgNullExCustomization customization = sut.GetCustomization(method);

            // Act
            customization.Customize(fixture);
            IEnumerable<MethodData> data = fixture.GetData();

            // Assert
            Assert.Empty(data);
            IRegexFilter regexFilter = fixture.Filters.OfType<IRegexFilter>().Single();
            Assert.Single(regexFilter.Rules);
            AssertSingleExcludeAllMethodsRule(regexFilter);
        }

        [Theory, AutoMock]
        public void ExcludeAllParameters(
            ExcludeAllAttribute sut,
            MethodInfo method)
        {
            // Arrange
            sut.ExclusionType = ExclusionType.Parameters;
            var fixture = new ArgumentNullExceptionFixture(GetType().GetTypeInfo().Assembly);
            IArgNullExCustomization customization = sut.GetCustomization(method);

            // Act
            customization.Customize(fixture);
            IEnumerable<MethodData> data = fixture.GetData();

            // Assert
            Assert.Empty(data);
            IRegexFilter regexFilter = fixture.Filters.OfType<IRegexFilter>().Single();
            Assert.Single(regexFilter.Rules);
            AssertSingleExcludeAllParametersRule(regexFilter);
        }

        [Theory, AutoMock]
        public void ExcludesAll(
            ExcludeAllAttribute sut,
            MethodInfo method)
        {
            // Arrange
            sut.ExclusionType = ExclusionType.All;
            var fixture = new ArgumentNullExceptionFixture(GetType().GetTypeInfo().Assembly);
            IArgNullExCustomization customization = sut.GetCustomization(method);

            // Act
            customization.Customize(fixture);
            IEnumerable<MethodData> data = fixture.GetData();

            // Assert
            Assert.Empty(data);
            IRegexFilter regexFilter = fixture.Filters.OfType<IRegexFilter>().Single();
            Assert.Equal(3, regexFilter.Rules.Count);
            AssertSingleExcludeAllTypesRule(regexFilter);
            AssertSingleExcludeAllMethodsRule(regexFilter);
            AssertSingleExcludeAllParametersRule(regexFilter);
        }

        [Theory, AutoMock]
        public void ExcludeNone(
            ExcludeAllAttribute sut,
            MethodInfo method)
        {
            // Arrange
            sut.ExclusionType = ExclusionType.None;
            var fixture = new ArgumentNullExceptionFixture(GetType().GetTypeInfo().Assembly);
            IArgNullExCustomization customization = sut.GetCustomization(method);

            // Act
            customization.Customize(fixture);

            // Assert
            IRegexFilter regexFilter = fixture.Filters.OfType<IRegexFilter>().Single();
            Assert.Empty(regexFilter.Rules);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package godl

import (
	"fmt"
	"os"
	"path/filepath"
)

// VCS represents package vcs root.
type VCS struct {
	Root       string
	ImportPath string
	Type       string
}

// Download downloads package by its import path. It can be a subpackage,
// whole repo will be downloaded anyway.
// if repoPath is not empty string, it will be uses for vcs.
// target is top directory for download. i.e. if target is vendor/ and
// importPath is github.com/LK4D4/vndr, package will be downloaded to
// vendor/github.com/LK4D4/vndr.
// rev is desired revision of package.
func Download(importPath, repoPath, target, rev string) (*VCS, error) {
	security := secure
	// Analyze the import path to determine the version control system,
	// repository, and the import path for the root of the repository.
	rr, err := repoRootForImportPath(importPath, security)
	if err != nil {
		return nil, err
	}
	root := filepath.Join(target, rr.root)
	if repoPath != "" {
		rr.repo = repoPath
	}

	if err := os.RemoveAll(root); err != nil {
		return nil, fmt.Errorf("remove package root: %v", err)
	}
	// Some version control tools require the parent of the target to exist.
	parent, _ := filepath.Split(root)
	if err = os.MkdirAll(parent, 0777); err != nil {
		return nil, err
	}
	if rev == "" {
		if err = rr.vcs.create(root, rr.repo); err != nil {
			return nil, err
		}
	} else {
		if err = rr.vcs.createRev(root, rr.repo, rev); err != nil {
			return nil, err
		}
	}
	return &VCS{Root: root, ImportPath: rr.root, Type: rr.vcs.cmd}, nil
}


text:
<?php

namespace gordian\reefknot\autoload\classmap;

/**
 * Class YamlFileClassMap
 *
 * This class implements the file class map to use a YAML file.
 *
 * @package gordian\reefknot\autoload\classmap
 */
class YamlFileClassMap extends abstr\FileClassMap {

	public function load ()
	{
		// TODO: Implement load() method.
	}

	public function save ()
	{
		// TODO: Implement save() method.
	}

	public function __construct () {
		if (!extension_loaded ('yaml')) {
			throw new \RuntimeException ("This class requires the YAML extension");
		}
	}
}


text:
namespace
{
using namespace iox;
using namespace iox::popo;
using namespace ::testing;

class NotificationInfo_test : public Test
{
  public:
    class NotificationOriginTest
    {
      public:
        static void callback(NotificationOriginTest* const origin)
        {
            origin->m_callbackOrigin = origin;
        }

        NotificationOriginTest* m_callbackOrigin = nullptr;
    };

    NotificationInfo_test()
    {
    }

    ~NotificationInfo_test()
    {
    }

    NotificationOriginTest m_origin;
    NotificationOriginTest m_falseOrigin;
    NotificationInfo m_sut{&m_origin, 1478U, createNotificationCallback(NotificationOriginTest::callback)};
};

TEST_F(NotificationInfo_test, defaultCTorConstructsEmptyNotificationInfo)
{
    ::testing::Test::RecordProperty("TEST_ID", "5677ccf1-4072-4600-a67c-b34c7a258444");
    int bla;
    NotificationInfo sut;

    EXPECT_EQ(sut.getNotificationId(), NotificationInfo::INVALID_ID);
    EXPECT_EQ(sut.doesOriginateFrom(&bla), false);
    EXPECT_EQ(sut(), false);
}

TEST_F(NotificationInfo_test, getNotificationIdReturnsValidNotificationId)
{
    ::testing::Test::RecordProperty("TEST_ID", "68a5240f-e9ab-4bf7-93a3-2d36f4ddc176");
    EXPECT_EQ(m_sut.getNotificationId(), 1478U);
}

TEST_F(NotificationInfo_test, doesOriginateFromStatesOriginCorrectly)
{
    ::testing::Test::RecordProperty("TEST_ID", "c9d362dc-cd25-42e6-907d-82da6d079061");
    EXPECT_EQ(m_sut.doesOriginateFrom(&m_origin), true);
    EXPECT_EQ(m_sut.doesOriginateFrom(&m_falseOrigin), false);
}

TEST_F(NotificationInfo_test, getOriginReturnsCorrectOriginWhenHavingCorrectType)
{
    ::testing::Test::RecordProperty("TEST_ID", "a1ad935f-9658-460a-863b-57dedac07ff8");
    EXPECT_EQ(m_sut.getOrigin<NotificationOriginTest>(), &m_origin);
}

TEST_F(NotificationInfo_test, constGetOriginReturnsCorrectOriginWhenHavingCorrectType)
{
    ::testing::Test::RecordProperty("TEST_ID", "97a222ab-0ddf-4ab6-be27-056739844e20");
    EXPECT_EQ(const_cast<const NotificationInfo&>(m_sut).getOrigin<NotificationOriginTest>(), &m_origin);
}

TEST_F(NotificationInfo_test, getOriginReturnsNullptrWithWrongType)
{
    ::testing::Test::RecordProperty("TEST_ID", "badb467b-bf64-4e43-af30-77c163e90c99");
    auto errorHandlerCalled{false};
    iox::PoshError error{PoshError::NO_ERROR};
    auto errorHandlerGuard =
        iox::ErrorHandlerMock::setTemporaryErrorHandler<iox::PoshError>([&](const auto e, const iox::ErrorLevel) {
            error = e;
            errorHandlerCalled = true;
        });

    m_sut.getOrigin<int>();

    ASSERT_TRUE(errorHandlerCalled);
    EXPECT_EQ(error, iox::PoshError::POPO__NOTIFICATION_INFO_TYPE_INCONSISTENCY_IN_GET_ORIGIN);
}

TEST_F(NotificationInfo_test, constGetOriginReturnsNullptrWithWrongType)
{
    ::testing::Test::RecordProperty("TEST_ID", "4fdb2bed-9928-4181-b195-e411d1b16572");
    auto errorHandlerCalled{false};
    iox::PoshError error{PoshError::NO_ERROR};
    auto errorHandlerGuard =
        iox::ErrorHandlerMock::setTemporaryErrorHandler<iox::PoshError>([&](const auto e, const iox::ErrorLevel) {
            error = e;
            errorHandlerCalled = true;
        });

    const_cast<const NotificationInfo&>(m_sut).getOrigin<int>();

    ASSERT_TRUE(errorHandlerCalled);
    EXPECT_EQ(error, iox::PoshError::POPO__NOTIFICATION_INFO_TYPE_INCONSISTENCY_IN_GET_ORIGIN);
}

TEST_F(NotificationInfo_test, triggerCallbackReturnsTrueAndCallsCallbackWithSettedCallback)
{
    ::testing::Test::RecordProperty("TEST_ID", "b2ed19d1-cf45-4cc0-ad92-fa652d215a17");
    EXPECT_TRUE(m_sut());
    EXPECT_EQ(m_origin.m_callbackOrigin, &m_origin);
}

TEST_F(NotificationInfo_test, triggerCallbackReturnsFalseWithUnsetCallback)
{
    ::testing::Test::RecordProperty("TEST_ID", "d015f42f-cc01-467a-b568-e957a45a97e6");
    m_sut = NotificationInfo{&m_origin, 9U, NotificationCallback<NotificationOriginTest, int>{}};
    EXPECT_FALSE(m_sut());
}

} // namespace


text:
gRPC Cronet Transport
========================

**EXPERIMENTAL:**  *gRPC's Cronet transport is an experimental API. Its stability
depends on upstream Cronet's implementation, which involves some experimental features.*

This code enables using the [Chromium networking stack
(Cronet)](https://chromium.googlesource.com/chromium/src/+/master/components/cronet)
as the transport layer for gRPC on Android. This lets your Android app make
RPCs using the same networking stack as used in the Chrome browser.

Some advantages of using Cronet with gRPC:

* Bundles an OpenSSL implementation, enabling TLS connections even on older
  versions of Android without additional configuration
* Robust to Android network connectivity changes
* Support for [QUIC](https://www.chromium.org/quic)

Since gRPC's 1.24 release, the `grpc-cronet` package provides access to the
`CronetChannelBuilder` class. Cronet jars are available on Google's Maven repository.
See the example app at https://github.com/GoogleChrome/cronet-sample/blob/master/README.md.

## Example usage:

In your app module's `build.gradle` file, include a dependency on both `grpc-cronet` and the
Google Play Services Client Library for Cronet

```
implementation 'io.grpc:grpc-cronet:1.51.0'
implementation 'com.google.android.gms:play-services-cronet:16.0.0'
```

In cases where Cronet cannot be loaded from Google Play services, there is a less performant
implementation of Cronet's API that can be used. Depend on `org.chromium.net:cronet-fallback`
to use this fall-back implementation.

You will also need permission to access the device's network state in your
`AndroidManifest.xml`:

```
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
```

Once the above steps are completed, you can create a gRPC Cronet channel as
follows:

```
import io.grpc.cronet.CronetChannelBuilder;
import org.chromium.net.ExperimentalCronetEngine;

...

ExperimentalCronetEngine engine =
    new ExperimentalCronetEngine.Builder(context /* Android Context */).build();
ManagedChannel channel = CronetChannelBuilder.forAddress("localhost", 8080, engine).build();
```


text:
package org.apache.camel.component.cassandra;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.querybuilder.Update;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.cassandraunit.CassandraCQLUnit;
import org.junit.Rule;
import org.junit.Test;

import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
import static com.datastax.driver.core.querybuilder.QueryBuilder.set;
import static com.datastax.driver.core.querybuilder.QueryBuilder.update;

public class CassandraComponentProducerTest extends BaseCassandraTest {

    private static final String CQL = "insert into camel_user(login, first_name, last_name) values (?, ?, ?)";
    private static final String NO_PARAMETER_CQL = "select login, first_name, last_name from camel_user";
    private static final String NOT_CONSISTENT_URI = "cql://localhost/camel_ks?cql=" + CQL + "&consistencyLevel=ANY";

    @Rule
    public CassandraCQLUnit cassandra = CassandraUnitUtils.cassandraCQLUnit();

    @Produce(uri = "direct:input")
    ProducerTemplate producerTemplate;

    @Produce(uri = "direct:inputNoParameter")
    ProducerTemplate noParameterProducerTemplate;

    @Produce(uri = "direct:inputNotConsistent")
    ProducerTemplate notConsistentProducerTemplate;

    @Produce(uri = "direct:loadBalancingPolicy")
    ProducerTemplate loadBalancingPolicyTemplate;

    @Produce(uri = "direct:inputNoEndpointCql")
    ProducerTemplate producerTemplateNoEndpointCql;

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() {

                from("direct:input")
                        .to("cql://localhost/camel_ks?cql=" + CQL);
                from("direct:inputNoParameter")
                        .to("cql://localhost/camel_ks?cql=" + NO_PARAMETER_CQL);
                from("direct:loadBalancingPolicy")
                        .to("cql://localhost/camel_ks?cql=" + NO_PARAMETER_CQL + "&loadBalancingPolicy=RoundRobinPolicy");
                from("direct:inputNotConsistent")
                        .to(NOT_CONSISTENT_URI);
                from("direct:inputNoEndpointCql")
                        .to("cql://localhost/camel_ks");
            }
        };
    }

    @Test
    public void testRequestUriCql() throws Exception {
        if (!canTest()) {
            return;
        }

        producerTemplate.requestBody(Arrays.asList("w_jiang", "Willem", "Jiang"));

        Cluster cluster = CassandraUnitUtils.cassandraCluster();
        Session session = cluster.connect(CassandraUnitUtils.KEYSPACE);
        ResultSet resultSet = session.execute("select login, first_name, last_name from camel_user where login = ?", "w_jiang");
        Row row = resultSet.one();
        assertNotNull(row);
        assertEquals("Willem", row.getString("first_name"));
        assertEquals("Jiang", row.getString("last_name"));
        session.close();
        cluster.close();
    }

    @Test
    public void testRequestNoParameterNull() throws Exception {
        if (!canTest()) {
            return;
        }

        Object response = noParameterProducerTemplate.requestBody(null);

        assertNotNull(response);
        assertIsInstanceOf(List.class, response);
        List<Row> rows = (List<Row>) response;
    }

    @Test
    public void testRequestNoParameterEmpty() throws Exception {
        if (!canTest()) {
            return;
        }

        Object response = noParameterProducerTemplate.requestBody(Collections.emptyList());

        assertNotNull(response);
        assertIsInstanceOf(List.class, response);
        List<Row> rows = (List<Row>) response;
    }

    @Test
    public void testRequestMessageCql() throws Exception {
        if (!canTest()) {
            return;
        }

        producerTemplate.requestBodyAndHeader(new Object[] {"Claus 2", "Ibsen 2", "c_ibsen"}, CassandraConstants.CQL_QUERY,
                                              "update camel_user set first_name=?, last_name=? where login=?");

        Cluster cluster = CassandraUnitUtils.cassandraCluster();
        Session session = cluster.connect(CassandraUnitUtils.KEYSPACE);
        ResultSet resultSet = session.execute("select login, first_name, last_name from camel_user where login = ?", "c_ibsen");
        Row row = resultSet.one();
        assertNotNull(row);
        assertEquals("Claus 2", row.getString("first_name"));
        assertEquals("Ibsen 2", row.getString("last_name"));
        session.close();
        cluster.close();
    }

    @Test
    public void testLoadBalancing() throws Exception {
        if (!canTest()) {
            return;
        }

        loadBalancingPolicyTemplate.requestBodyAndHeader(new Object[] {"Claus 2", "Ibsen 2", "c_ibsen"}, CassandraConstants.CQL_QUERY,
                                                         "update camel_user set first_name=?, last_name=? where login=?");

        Cluster cluster = CassandraUnitUtils.cassandraCluster();
        Session session = cluster.connect(CassandraUnitUtils.KEYSPACE);
        ResultSet resultSet = session.execute("select login, first_name, last_name from camel_user where login = ?", "c_ibsen");
        Row row = resultSet.one();
        assertNotNull(row);
        assertEquals("Claus 2", row.getString("first_name"));
        assertEquals("Ibsen 2", row.getString("last_name"));
        session.close();
        cluster.close();
    }

    /**
     * Test with incoming message containing a header with RegularStatement.
     */
    @Test
    public void testRequestMessageStatement() throws Exception {
        if (!canTest()) {
            return;
        }

        Update.Where update = update("camel_user")
                .with(set("first_name", bindMarker()))
                .and(set("last_name", bindMarker()))
                .where(eq("login", bindMarker()));
        producerTemplate.requestBodyAndHeader(new Object[] {"Claus 2", "Ibsen 2", "c_ibsen"}, CassandraConstants.CQL_QUERY, update);

        Cluster cluster = CassandraUnitUtils.cassandraCluster();
        Session session = cluster.connect(CassandraUnitUtils.KEYSPACE);
        ResultSet resultSet = session.execute("select login, first_name, last_name from camel_user where login = ?", "c_ibsen");
        Row row = resultSet.one();
        assertNotNull(row);
        assertEquals("Claus 2", row.getString("first_name"));
        assertEquals("Ibsen 2", row.getString("last_name"));
        session.close();
        cluster.close();
    }

    /**
     * Simulate different CQL statements in the incoming message containing a header with RegularStatement, justifying the cassandracql endpoint not containing a "cql" Uri parameter
     */
    @Test
    public void testEndpointNoCqlParameter() throws Exception {
        if (!canTest()) {
            return;
        }

        Update.Where updateFirstName = update("camel_user")
                .with(set("first_name", bindMarker()))
                .where(eq("login", bindMarker()));
        @SuppressWarnings("unused")
        Object response1 = producerTemplateNoEndpointCql.requestBodyAndHeader(new Object[]{"Claus 2", "c_ibsen"},
                CassandraConstants.CQL_QUERY, updateFirstName);

        Cluster cluster = CassandraUnitUtils.cassandraCluster();
        Session session = cluster.connect(CassandraUnitUtils.KEYSPACE);
        ResultSet resultSet1 = session.execute("select login, first_name, last_name from camel_user where login = ?", "c_ibsen");
        Row row1 = resultSet1.one();
        assertNotNull(row1);
        assertEquals("Claus 2", row1.getString("first_name"));
        assertEquals("Ibsen", row1.getString("last_name"));

        Update.Where updateLastName = update("camel_user")
                .with(set("last_name", bindMarker()))
                .where(eq("login", bindMarker()));
        @SuppressWarnings("unused")
        Object response2 = producerTemplateNoEndpointCql.requestBodyAndHeader(new Object[]{"Ibsen 2", "c_ibsen"},
                CassandraConstants.CQL_QUERY, updateLastName);

        ResultSet resultSet2 = session.execute("select login, first_name, last_name from camel_user where login = ?", "c_ibsen");
        Row row2 = resultSet2.one();
        assertNotNull(row2);
        assertEquals("Claus 2", row2.getString("first_name"));
        assertEquals("Ibsen 2", row2.getString("last_name"));

        session.close();
        cluster.close();
    }

    @Test
    public void testRequestNotConsistent() throws Exception {
        if (!canTest()) {
            return;
        }

        CassandraEndpoint endpoint = getMandatoryEndpoint(NOT_CONSISTENT_URI, CassandraEndpoint.class);
        assertEquals(ConsistencyLevel.ANY, endpoint.getConsistencyLevel());

        notConsistentProducerTemplate.requestBody(Arrays.asList("j_anstey", "Jonathan", "Anstey"));
    }
}


text:
a convenient abstraction for the [reddit.com](http://reddit.com) API in Go

Checkout the [godoc page](http://godoc.org/github.com/jzelinskie/geddit)

## warning

this is a **work in progress**!

## example

```Go
package main

import (
	"fmt"

	"github.com/jzelinskie/geddit"
)

// Please don't handle errors this way.
func main() {
	// Login to reddit
	session, _ := geddit.NewLoginSession(
		"novelty_account",
		"password",
		"gedditAgent v1",
	)

	// Set listing options
	subOpts := geddit.ListingOptions{
		Limit: 10,
	}

	// Get reddit's default frontpage
	submissions, _ := session.DefaultFrontpage(geddit.DefaultPopularity, subOpts)

	// Get our own personal frontpage
	submissions, _ = session.Frontpage(geddit.DefaultPopularity, subOpts)

	// Get specific subreddit submissions, sorted by new
	submissions, _ = session.SubredditSubmissions("hockey", geddit.NewSubmissions, subOpts)

	// Print title and author of each submission
	for _, s := range submissions {
		fmt.Printf("Title: %s\nAuthor: %s\n\n", s.Title, s.Author)
	}

	// Upvote the first post
	session.Vote(submissions[0], geddit.UpVote)
}
```


text:
package org.loofer.framework.widget.autolayout;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.ViewGroup;

import com.zhy.autolayout.AutoLayoutInfo;
import com.zhy.autolayout.utils.AutoLayoutHelper;

/**
 * Created by jess on 16/4/14.
 */
public class AutoToolbar extends Toolbar {
    private AutoLayoutHelper mHelper = new AutoLayoutHelper(this);

    public AutoToolbar(Context context) {
        super(context);
    }

    public AutoToolbar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public AutoToolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        if (!isInEditMode())
            mHelper.adjustChildren();
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
        super.onLayout(changed, l, t, r, b);
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new AutoToolbar.LayoutParams(getContext(), attrs);
    }

    public static class LayoutParams extends Toolbar.LayoutParams
            implements AutoLayoutHelper.AutoLayoutParams
    {
        private AutoLayoutInfo mAutoLayoutInfo;

        public LayoutParams(Context c, AttributeSet attrs)
        {
            super(c, attrs);
            mAutoLayoutInfo = AutoLayoutHelper.getAutoLayoutInfo(c, attrs);
        }

        @Override
        public AutoLayoutInfo getAutoLayoutInfo()
        {
            return mAutoLayoutInfo;
        }

        public LayoutParams(int width, int height)
        {
            super(width, height);
        }

        public LayoutParams(ViewGroup.LayoutParams source)
        {
            super(source);
        }

        public LayoutParams(MarginLayoutParams source)
        {
            super(source);
        }

    }
}


text:
package org.wso2.carbon.apimgt.usage.client.bean;

import java.util.List;

/**
 * This class is used as a bean for represent API Destination based Statistics result from the DAS REST API
 */
public class APIUsageByDestinationValue {
    private int totalRequestCount;
    private List<String> api_version_context_dest_facet;

    public APIUsageByDestinationValue(int lastAccessTime, List<String> api_version_userId_facet) {
        this.totalRequestCount = lastAccessTime;
        this.api_version_context_dest_facet = api_version_userId_facet;
    }

    public int getTotalRequesCount() {
        return totalRequestCount;
    }

    public void setTotalRequesCount(int lastAccessTime) {
        this.totalRequestCount = lastAccessTime;
    }

    public List<String> getColumnNames() {
        return api_version_context_dest_facet;
    }

    public void setColumnNames(List<String> api_version_userId_facet) {
        this.api_version_context_dest_facet = api_version_userId_facet;
    }

}


text:
Protocol Buffers Descriptor Library
===================================

    Copyright © 2014 Patryk Zadarnowski «pat@jantar.org».
    All rights reserved.

This is a Haskell library for parsing and manipulation of Google's standard
protocol buffer descriptor specifications (.proto files) The parser is written
in a combination of Happy and Alex.

This is work in progress and the interface is going to change dramatically
moving forward.


text:
	<title>David's Tech Blog</title>
	<link rel="stylesheet" type="text/css" href="../stylesheets/default.css">
	<link rel="stylesheet" type="text/css" href="../stylesheets/blog.css">

David's Blog

A journey into tech

BLOG

ABOUT

PROJECTS

CONTACT

RESUME

        Take a look at my blog posts!

Week 1

Week 2

Week 3

Week 4

Week 9

Link up with me on social media!

WEEK 9: Personal Website

				Building a personal website has been like a rollercoaster ride - It's been challenging at some points, but very rewarding at others.

				One challenging aspect that frustrated me was having to constantly update every document whenever I update my website. I've been trying to find a solution to this issue, but it seems as though it requires learning PHP and having an actual server to host different parts of the website.

				In terms of becoming a web developer, it's taught me to really appreciate just how much work goes into making a proper functioning website. It's like trying to build a house on a flowing river - so many pieces all constantly changing.


text:
package org.apache.poi.ss.formula.eval;

import java.util.regex.Pattern;

/**
 * Provides functionality for evaluating arguments to functions and operators.
 *
 * @author Josh Micich
 * @author Brendan Nolan
 */
public final class OperandResolver {

    // Based on regular expression defined in JavaDoc at {@link java.lang.Double#valueOf}
    // modified to remove support for NaN, Infinity, Hexadecimal support and floating type suffixes
    private static final String Digits    = "(\\p{Digit}+)";
    private static final String Exp    = "[eE][+-]?"+Digits;
    private static final String fpRegex    =
                ("[\\x00-\\x20]*" +
                 "[+-]?(" +
                   "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+
                 "(\\.("+Digits+")("+Exp+")?))))"+
                 "[\\x00-\\x20]*");

    private OperandResolver() {
        // no instances of this class
    }

    /**
     * Retrieves a single value from a variety of different argument types according to standard
     * Excel rules.  Does not perform any type conversion.
     * @param arg the evaluated argument as passed to the function or operator.
     * @param srcCellRow used when arg is a single column AreaRef
     * @param srcCellCol used when arg is a single row AreaRef
     * @return a <tt>NumberEval</tt>, <tt>StringEval</tt>, <tt>BoolEval</tt> or <tt>BlankEval</tt>.
     * Never null or <tt>ErrorEval</tt>.
     * @throws EvaluationException(#VALUE!) if srcCellRow or srcCellCol do not properly index into
     *  an AreaEval.  If the actual value retrieved is an ErrorEval, a corresponding
     *  EvaluationException is thrown.
     */
    public static ValueEval getSingleValue(ValueEval arg, int srcCellRow, int srcCellCol)
            throws EvaluationException {
        final ValueEval result;
        if (arg instanceof RefEval) {
            result = chooseSingleElementFromRef((RefEval) arg);
        } else if (arg instanceof AreaEval) {
            result = chooseSingleElementFromArea((AreaEval) arg, srcCellRow, srcCellCol);
        } else {
            result = arg;
        }
        if (result instanceof ErrorEval) {
            throw new EvaluationException((ErrorEval) result);
        }
        return result;
    }

    /**
     * Implements (some perhaps not well known) Excel functionality to select a single cell from an
     * area depending on the coordinates of the calling cell.  Here is an example demonstrating
     * both selection from a single row area and a single column area in the same formula.
     *
     *

     *
 	 A 	 B 	 C 	 D

     *
1	15	20	25

     *
2	 	 	 	200

     *
3	 	 	 	300

     *
3	 	 	 	400

     *

     *
     * If the formula "=1000+A1:B1+D2:D3" is put into the 9 cells from A2 to C4, the spreadsheet
     * will look like this:
     *
     *

     *
 	 A 	 B 	 C 	 D

     *
1	15	20	25

     *
2	1215	1220	#VALUE!	200

     *
3	1315	1320	#VALUE!	300

     *
4	#VALUE!	#VALUE!	#VALUE!	400

     *

     *
     * Note that the row area (A1:B1) does not include column C and the column area (D2:D3) does
     * not include row 4, so the values in C1(=25) and D4(=400) are not accessible to the formula
     * as written, but in the 4 cells A2:B3, the row and column selection works ok.

     *
     * The same concept is extended to references across sheets, such that even multi-row,
     * multi-column areas can be useful.

     *
     * Of course with carefully (or carelessly) chosen parameters, cyclic references can occur and
     * hence this method can throw a 'circular reference' EvaluationException.  Note that
     * this method does not attempt to detect cycles.  Every cell in the specified Area <tt>ae</tt>
     * has already been evaluated prior to this method call.  Any cell (or cells) part of
     * <tt>ae</tt> that would incur a cyclic reference error if selected by this method, will
     * already have the value <t>ErrorEval.CIRCULAR_REF_ERROR</tt> upon entry to this method.  It
     * is assumed logic exists elsewhere to produce this behaviour.
     *
     * @return whatever the selected cell's evaluated value is.  Never null. Never
     *  <tt>ErrorEval</tt>.
     * @throws EvaluationException if there is a problem with indexing into the area, or if the
     *  evaluated cell has an error.
     */
    public static ValueEval chooseSingleElementFromArea(AreaEval ae,
            int srcCellRow, int srcCellCol) throws EvaluationException {
        ValueEval result = chooseSingleElementFromAreaInternal(ae, srcCellRow, srcCellCol);
        if (result instanceof ErrorEval) {
            throw new EvaluationException((ErrorEval) result);
        }
        return result;
    }

    /**
     * @return possibly <tt>ErrorEval</tt>, and null
     */
    private static ValueEval chooseSingleElementFromAreaInternal(AreaEval ae,
            int srcCellRow, int srcCellCol) throws EvaluationException {

//        if(false) {
//            // this is too simplistic
//            if(ae.containsRow(srcCellRow) && ae.containsColumn(srcCellCol)) {
//                throw new EvaluationException(ErrorEval.CIRCULAR_REF_ERROR);
//            }
//        /*
//        Circular references are not dealt with directly here, but it is worth noting some issues.
//
//        ANY one of the return statements in this method could return a cell that is identical
//        to the one immediately being evaluated.  The evaluating cell is identified by srcCellRow,
//        srcCellRow AND sheet.  The sheet is not available in any nearby calling method, so that's
//        one reason why circular references are not easy to detect here. (The sheet of the returned
//        cell can be obtained from ae if it is an Area3DEval.)
//
//        Another reason there's little value in attempting to detect circular references here is
//        that only direct circular references could be detected.  If the cycle involved two or more
//        cells this method could not detect it.
//
//        Logic to detect evaluation cycles of all kinds has been coded in EvaluationCycleDetector
//        (and FormulaEvaluator).
//         */
//        }

        if (ae.isColumn()) {
            if(ae.isRow()) {
                return ae.getRelativeValue(0, 0);
            }
            if(!ae.containsRow(srcCellRow)) {
                throw EvaluationException.invalidValue();
            }
            return ae.getAbsoluteValue(srcCellRow, ae.getFirstColumn());
        }
        if(!ae.isRow()) {
            // multi-column, multi-row area
            if(ae.containsRow(srcCellRow) && ae.containsColumn(srcCellCol)) {
                return ae.getAbsoluteValue(ae.getFirstRow(), ae.getFirstColumn());
            }
            throw EvaluationException.invalidValue();
        }
        if(!ae.containsColumn(srcCellCol)) {
            throw EvaluationException.invalidValue();
        }
        return ae.getAbsoluteValue(ae.getFirstRow(), srcCellCol);
    }

    private static ValueEval chooseSingleElementFromRef(RefEval ref) {
        return ref.getInnerValueEval( ref.getFirstSheetIndex() );
    }

    /**
     * Applies some conversion rules if the supplied value is not already an integer.

     * Value is first coerced to a <tt>double</tt> ( See <tt>coerceValueToDouble()</tt> ).
     * Note - <tt>BlankEval</tt> is converted to 0.

     *
     * Excel typically converts doubles to integers by truncating toward negative infinity.

     * The equivalent java code is:

     *   return (int)Math.floor(d);

     * not:

     *   return (int)d; // wrong - rounds toward zero
     *
     */
    public static int coerceValueToInt(ValueEval ev) throws EvaluationException {
        if (ev == BlankEval.instance) {
            return 0;
        }
        double d = coerceValueToDouble(ev);
        // Note - the standard java type conversion from double to int truncates toward zero.
        // but Math.floor() truncates toward negative infinity
        return (int)Math.floor(d);
    }

    /**
     * Applies some conversion rules if the supplied value is not already a number.
     * Note - <tt>BlankEval</tt> is converted to {@link NumberEval#ZERO}.
     * @param ev must be a {@link NumberEval}, {@link StringEval}, {@link BoolEval} or
     * {@link BlankEval}
     * @return actual, parsed or interpreted double value (respectively).
     * @throws EvaluationException(#VALUE!) only if a StringEval is supplied and cannot be parsed
     * as a double (See <tt>parseDouble()</tt> for allowable formats).
     * @throws RuntimeException if the supplied parameter is not {@link NumberEval},
     * {@link StringEval}, {@link BoolEval} or {@link BlankEval}
     */
    public static double coerceValueToDouble(ValueEval ev) throws EvaluationException {

        if (ev == BlankEval.instance) {
            return 0.0;
        }
        if (ev instanceof NumericValueEval) {
            // this also handles booleans
            return ((NumericValueEval)ev).getNumberValue();
        }
        if (ev instanceof StringEval) {
            Double dd = parseDouble(((StringEval) ev).getStringValue());
            if (dd == null) {
                throw EvaluationException.invalidValue();
            }
            return dd.doubleValue();
        }
        throw new RuntimeException("Unexpected arg eval type (" + ev.getClass().getName() + ")");
    }

    /**
     * Converts a string to a double using standard rules that Excel would use.

     * Tolerates leading and trailing spaces,

     *
     * Doesn't support currency prefixes, commas, percentage signs or arithmetic operations strings.
     *
     *  Some examples:

     *  " 123 " -> 123.0

     *  ".123" -> 0.123

     *  "1E4" -> 1000

     *  "-123" -> -123.0

     *  These not supported yet:

     *  " $ 1,000.00 " -> 1000.0

     *  "$1.25E4" -> 12500.0

     *  "5**2" -> 500

     *  "250%" -> 2.5

     *
     * @return null if the specified text cannot be parsed as a number
     */
    public static Double parseDouble(String pText) {

        if (Pattern.matches(fpRegex, pText))
            try {
                return Double.parseDouble(pText);
            } catch (NumberFormatException e) {
                return null;
            }
        else {
            return null;
        }

    }

    /**
     * @param ve must be a <tt>NumberEval</tt>, <tt>StringEval</tt>, <tt>BoolEval</tt>, or <tt>BlankEval</tt>
     * @return the converted string value. never null
     */
    public static String coerceValueToString(ValueEval ve) {
        if (ve instanceof StringValueEval) {
            StringValueEval sve = (StringValueEval) ve;
            return sve.getStringValue();
        }
        if (ve == BlankEval.instance) {
            return "";
        }
        throw new IllegalArgumentException("Unexpected eval class (" + ve.getClass().getName() + ")");
    }

    /**
     * @return null to represent blank values
     * @throws EvaluationException if ve is an ErrorEval, or if a string value cannot be converted
     */
    public static Boolean coerceValueToBoolean(ValueEval ve, boolean stringsAreBlanks) throws EvaluationException {

        if (ve == null || ve == BlankEval.instance) {
            // TODO - remove 've == null' condition once AreaEval is fixed
            return null;
        }
        if (ve instanceof BoolEval) {
            return Boolean.valueOf(((BoolEval) ve).getBooleanValue());
        }

        if (ve == BlankEval.instance) {
            return null;
        }

        if (ve instanceof StringEval) {
            if (stringsAreBlanks) {
                return null;
            }
            String str = ((StringEval) ve).getStringValue();
            if (str.equalsIgnoreCase("true")) {
                return Boolean.TRUE;
            }
            if (str.equalsIgnoreCase("false")) {
                return Boolean.FALSE;
            }
            // else - string cannot be converted to boolean
            throw new EvaluationException(ErrorEval.VALUE_INVALID);
        }

        if (ve instanceof NumericValueEval) {
            NumericValueEval ne = (NumericValueEval) ve;
            double d = ne.getNumberValue();
            if (Double.isNaN(d)) {
                throw new EvaluationException(ErrorEval.VALUE_INVALID);
            }
            return Boolean.valueOf(d != 0);
        }
        if (ve instanceof ErrorEval) {
            throw new EvaluationException((ErrorEval) ve);
        }
        throw new RuntimeException("Unexpected eval (" + ve.getClass().getName() + ")");
    }
}


text:
#include <common/configure.h>
#include <ledger/ledger_manager.h>
#include "account.h"
#include "issue_asset_ope_frm.h"

namespace bubi {
	IssueOpeFrm::IssueOpeFrm(const protocol::Operation &operation, TransactionFrm &tran, AccountFrm::pointer &account_ptr) :
		OperationFrm(operation, tran, account_ptr), operation_issue_asset_(operation.issue_asset()) {}

	IssueOpeFrm::~IssueOpeFrm() {}

	int32_t IssueOpeFrm::CheckValid(const protocol::Operation &ope, const std::string &source_address) {
		auto operation_issue_asset = ope.issue_asset();
		auto assetprop = operation_issue_asset.asset().property();

		protocol::Asset asset = operation_issue_asset.asset();
		if (!AssetFrm::IsValid(asset)) {
			LOG_ERROR("Asset is not legal");
			return (protocol::ERRCODE_ASSET_INVALID);
		}

		if (assetprop.issuer() != source_address) {
			LOG_ERROR("Asset's issuer is not equal to transaction owner");
			return (protocol::ERRCODE_ASSET_INVALID);
		}

		return protocol::ERRCODE_SUCCESS;
	}

	bool IssueOpeFrm::Apply(AccountEntry &entry) {
		std::string strAddress = sourceaccount_ptr_->GetAccountAddress();
		if (!entry.GetEntry(strAddress, sourceaccount_ptr_)) {
			LOG_ERROR("Source account does not exist");
			result_.set_code(protocol::ERRCODE_ACCOUNT_NOT_EXIST);
			return false;
		}

		protocol::AssetProperty_Type pay_type = operation_issue_asset_.asset().property().type();

		protocol::Asset tmp = operation_issue_asset_.asset();
		if (tmp.details_size() == 0) {
			protocol::Detail *dtl = tmp.add_details();
			dtl->set_amount(tmp.amount());
			dtl->set_start(0);
			dtl->set_length(-1); //0 for permanent, -1 for uninitialized
			dtl->set_ext("");
		}

		if (!sourceaccount_ptr_->RecvAsset(tmp, transaction_.GetHeader()->ledger_version())) {
			result_.set_desc("Dest account asset amount too large");
			result_.set_code(protocol::ERRCODE_ACCOUNT_ASSET_AMOUNT_TOO_LARGE);
			LOG_ERROR("Dest account(%s) asset amount too large", sourceaccount_ptr_->GetAccountAddress().c_str());
			return false;
		}

		return true;
	}
	int32_t IssueOpeFrm::GetThreshold() {
		return sourceaccount_ptr_->GetProtoMedThreshold();
	}
}


text:
var ng = require('@angular/core');

module.exports = ng.Component({
  selector: 'fountain-tech',
  template: require('./tech.html'),
  inputs: ['tech']
})
.Class({
  constructor: function () {}
});


text:
@implementation DTVersionTest

- (void)testCreate
{
	DTVersion *version = [DTVersion versionWithString:@"foobar"];
	STAssertNil(version, @"DTVersion object should not be create of an unsupported string");

	version = [DTVersion versionWithString:@"1.-1"];
	STAssertNil(version, @"DTVersion object should not be create of an unsupported string");

	//version = [DTVersion versionWithString:@"1.2.1.1"];
	//STAssertNil(version, @"DTVersion object should not be create of an unsupported string");

	version = [DTVersion versionWithString:@"1.2.3"];
	STAssertNotNil(version, @"DTVersion object should be create");
	STAssertEquals(1, (int)version.major, @"version.major is not the correct value %d", version.major);
	STAssertEquals(2, (int)version.minor, @"version.minor is not the correct value %d", version.minor);
	STAssertEquals(3, (int)version.maintenance, @"version.maintenance is not the correct value %d", version.maintenance);

	version = [DTVersion versionWithString:@"2.9999"];
	STAssertNotNil(version, @"DTVersion object should be create");
	STAssertEquals(2, (int)version.major, @"version.major is not the correct value %d", version.major);
	STAssertEquals(9999, (int)version.minor, @"version.minor is not the correct value %d", version.minor);
	STAssertEquals(0, (int)version.maintenance, @"version.maintenance is not the correct value %d", version.maintenance);

	version = [DTVersion versionWithString:@"1"];
	STAssertNotNil(version, @"DTVersion object should be create");
	STAssertEquals(1, (int)version.major, @"version.major is not the correct value %d", version.major);
	STAssertEquals(0, (int)version.minor, @"version.minor is not the correct value %d", version.minor);
	STAssertEquals(0, (int)version.maintenance, @"version.maintenance is not the correct value %d", version.maintenance);

	version = [DTVersion versionWithString:@"1.2.3.4"];
	STAssertNotNil(version, @"DTVersion object should be create");
	STAssertEquals(1, (int)version.major, @"version.major is not the correct value %d", version.major);
	STAssertEquals(2, (int)version.minor, @"version.minor is not the correct value %d", version.minor);
	STAssertEquals(3, (int)version.maintenance, @"version.maintenance is not the correct value %d", version.maintenance);
	STAssertEquals(4, (int)version.build, @"version.build is not the correct value %d", version.build);
}

- (void)testEquals
{
	DTVersion *first = [DTVersion versionWithString:@"1.2.3"];
	DTVersion *second = [DTVersion versionWithString:@"1.2.4"];

	STAssertFalse([first isEqualToVersion:second], @"first version is not equal to second, but should");
	STAssertFalse([first isEqual:second], @"first version is not equal to second, but should");

	second = [DTVersion versionWithString:@"1.2"];
	STAssertFalse([first isEqualToVersion:second], @"first version is equal to second, but should not");
	STAssertFalse([first isEqual:second], @"first version is equal to second, but should not");

	first = [DTVersion versionWithString:@"1.0.0"];
	second = [DTVersion versionWithString:@"1"];
	STAssertTrue([first isEqualToVersion:second], @"first version is not equal to second, but should");
	STAssertTrue([first isEqual:second], @"first version is not equal to second, but should");

	second = [DTVersion versionWithString:@"1.0"];
	STAssertTrue([first isEqualToVersion:second], @"first version is not equal to second, but should");
	STAssertTrue([first isEqual:second], @"first version is not equal to second, but should");

	STAssertTrue([first isEqualToString:@"1.0.0"], @"first version is not equal to second, but should");
	STAssertTrue([first isEqual:@"1.0.0"], @"first version is not equal to second, but should");
	STAssertTrue([first isEqualToString:@"1.0"], @"first version is not equal to second, but should");
	STAssertTrue([first isEqualToString:@"1"], @"first version is not equal to second, but should");
	STAssertTrue([first isEqual:@"1.0.0.0"], @"first version is not equal to second, but should");

	STAssertFalse([first isEqualToString:@"1.2"], @"first version is equal to second, but should not");
	STAssertFalse([first isEqualToString:@"1.1.1"], @"first version is equal to second, but should not");
	STAssertFalse([first isEqualToString:@"foobar"], @"first version is equal to second, but should not");
	STAssertFalse([first isEqualToString:@"0.0.0"], @"first version is equal to second, but should not");

	first = [DTVersion versionWithString:@"1.2.3.4"];
	second = [DTVersion versionWithString:@"1.2.3.4"];
	STAssertTrue([first isEqualToVersion:second], @"first version is not equal to second, but should");
}

- (void)testCompare
{
	DTVersion *first = [DTVersion versionWithString:@"1.2.3"];
	DTVersion *second = [DTVersion versionWithString:@"1.2.3"];

	STAssertEquals(NSOrderedSame, [first compare:second], @"should be the same");

	second = [DTVersion versionWithString:@"1.2.0"];
	STAssertEquals(NSOrderedDescending, [first compare:second], @"%@ should be larger then %@", first, second);

	second = [DTVersion versionWithString:@"1.2.4"];
	STAssertEquals(NSOrderedAscending, [first compare:second], @"%@ should be smaller then %@", first, second);

	second = [DTVersion versionWithString:@"0.9.9"];
	STAssertEquals(NSOrderedDescending, [first compare:second], @"%@ should be smaller then %@", first, second);

	second = [DTVersion versionWithString:@"0.9.9"];
	STAssertEquals(NSOrderedDescending, [first compare:nil], @"%@ should be smaller then %@", first, second);

	second = [DTVersion versionWithString:@"0.9.9.0"];
	STAssertEquals(NSOrderedDescending, [first compare:nil], @"%@ should be smaller then %@", first, second);
}

- (void)testLessThan
{
	DTVersion *first = [DTVersion versionWithString:@"1.0"];
	DTVersion *second = [DTVersion versionWithString:@"2.0"];

	STAssertTrue([first isLessThenVersion:second], @"first version is not less the second");
	STAssertFalse([second isLessThenVersion:first], @"second should not be less then first");

	STAssertTrue([second isGreaterThenVersion:first], @"second version is not greater then first");

	STAssertFalse([second isLessThenVersionString:@"2.0.0"], @"second should not be less then 2.0.0");
	STAssertFalse([second isLessThenVersionString:@"1.9.9"], @"second should not be less then 1.9.9");
	STAssertTrue([second isLessThenVersionString:@"2.0.1"], @"second should be less then 2.0.0");
}

- (void)testVersion
{
	DTVersion *first = [DTVersion versionWithString:@"8.00.047 build 010"];
	DTVersion *second = [DTVersion versionWithString:@"8.00.047"];

	STAssertEquals(NSOrderedSame, [first compare:second], @"should be the same");

	STAssertFalse([first isLessThenVersionString:@"8.00.047"], @"first version is not less than 8.00.047");

	second = [DTVersion versionWithString:@"8.00.047 build 010"];
	STAssertEquals(NSOrderedSame, [first compare:second], @"should be the same");
}

@end


text:
'use strict';

import { Button } from './buttons';
import { Login, Register } from './login';
import { GridOverlayElement } from './grid';
import { UseNavigo } from './navigo';

class App {
  constructor () {
    console.log('Constructor of the class');

    document.registerElement('grid-overlay', GridOverlayElement);

    this._gridOverlayElement = document.createElement('grid-overlay');
    document.body.appendChild(this._gridOverlayElement);

    // buttons DOM
    this._btnMMP = document.querySelector('.buttonMMP');
    this._btnGMB = document.querySelector('.buttonGMB');
    this._btnCMO = document.querySelector('.buttonCMO');

    // check if a "users" key exists, if not -> create an admin user.
    if (localStorage.getItem('users') === null) {
      let _adminUser = [{'user': 'Ururu', 'pass': '--fixplease'}];
      localStorage.setItem('users', JSON.stringify(_adminUser));
    }

    // init funx
    this.resizeWindow();
    this.initMap();

    // this.loadDataBlogPosts();
    window.addEventListener('resize', () => this.resizeWindow());

    // check if a "users" key exists, if not -> create an admin user.
    if (localStorage.getItem('users') === null) {
      let _adminUser = [{'user': 'Ururu', 'pass': '--fixplease'}];
      localStorage.setItem('users', JSON.stringify(_adminUser));
    }
  }

  resizeWindow () {
    this._gridOverlayElement.updateRendering(window.innerWidth, Math.max(
      window.innerHeight,
      document.body.offsetHeight,
      document.documentElement.clientHeight
    ), 24);
  }

  // voor google maps
  initMap () {
    if (document.title === 'Contact | Ururu | New Media Development | Artevelde University College Ghent') {
      let uluru = {lat: 51.0673017, lng: 3.7004048};
      let map = new google.maps.Map(document.querySelector('.map'), {
        zoom: 16,
        center: uluru
      });
      let marker = new google.maps.Marker({
        position: uluru,
        map: map
      });
    }
  }

  init () {
    console.log('Initialization of the class App');

    let useNavigo = new UseNavigo();
    // instances of our classes
    let toggleButton = new Button();
    // make sure the nav stays none if the screen is < 768 unless the pullnav is pressed.
    toggleButton.resizeNav();
    let userRegister = new Register();
    userRegister.loggedIn();
  }
};

//
window.addEventListener('load', (ev) => {
  const app = new App();
  app.init();
});


text:
/* Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0
 *
 * 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.
 */
package org.camunda.bpm.engine.test.api.authorization.util;

import java.util.ArrayList;
import java.util.List;

import org.camunda.bpm.engine.authorization.Authorization;
import org.camunda.bpm.engine.authorization.Permission;
import org.camunda.bpm.engine.authorization.Resource;
import org.camunda.bpm.engine.identity.Group;
import org.camunda.bpm.engine.identity.User;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.junit.Assert;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

/**
 * @author Thorben Lindhauer
 *
 */
public class AuthorizationTestBaseRule extends TestWatcher {

  protected ProcessEngineRule engineRule;

  protected List<User> users = new ArrayList<User>();
  protected List<Group> groups = new ArrayList<Group>();
  protected List<Authorization> authorizations = new ArrayList<Authorization>();

  public AuthorizationTestBaseRule(ProcessEngineRule engineRule) {
    this.engineRule = engineRule;
  }

  public void enableAuthorization(String userId) {
    engineRule.getProcessEngine().getProcessEngineConfiguration().setAuthorizationEnabled(true);
    if (userId != null) {
      engineRule.getIdentityService().setAuthenticatedUserId(userId);
    }
  }

  public void disableAuthorization() {
    engineRule.getProcessEngine().getProcessEngineConfiguration().setAuthorizationEnabled(false);
    engineRule.getIdentityService().clearAuthentication();
  }

  protected void finished(Description description) {
    engineRule.getIdentityService().clearAuthentication();

    deleteManagedAuthorizations();

    super.finished(description);

    Assert.assertTrue("Users have been created but not deleted", users.isEmpty());
    Assert.assertTrue("Groups have been created but not deleted", groups.isEmpty());
  }

  public void manageAuthorization(Authorization authorization) {
    this.authorizations.add(authorization);
  }

  protected Authorization createAuthorization(int type, Resource resource, String resourceId) {
    Authorization authorization = engineRule.getAuthorizationService().createNewAuthorization(type);

    authorization.setResource(resource);
    if (resourceId != null) {
      authorization.setResourceId(resourceId);
    }

    return authorization;
  }

  public void createGrantAuthorization(Resource resource, String resourceId, String userId, Permission... permissions) {
    Authorization authorization = createAuthorization(Authorization.AUTH_TYPE_GRANT, resource, resourceId);
    authorization.setUserId(userId);
    for (Permission permission : permissions) {
      authorization.addPermission(permission);
    }

    engineRule.getAuthorizationService().saveAuthorization(authorization);
    manageAuthorization(authorization);
  }

  protected void deleteManagedAuthorizations() {
    for (Authorization authorization : authorizations) {
      engineRule.getAuthorizationService().deleteAuthorization(authorization.getId());
    }
  }

  public void createUserAndGroup(String userId, String groupId) {

    User user = engineRule.getIdentityService().newUser(userId);
    engineRule.getIdentityService().saveUser(user);
    users.add(user);

    Group group = engineRule.getIdentityService().newGroup(groupId);
    engineRule.getIdentityService().saveGroup(group);
    groups.add(group);
  }

  public void deleteUsersAndGroups() {
    for (User user : users) {
      engineRule.getIdentityService().deleteUser(user.getId());
    }
    users.clear();

    for (Group group : groups) {
      engineRule.getIdentityService().deleteGroup(group.getId());
    }
    groups.clear();
  }
}


text:
#include "u_dataViewQos.h"
#include "os_stdlib.h"

u_dataViewQos
u_dataViewQosNew(
    const u_dataViewQos _template)
{
    u_dataViewQos _this;

    assert(!_template || ((v_qos)_template)->kind == V_DATAVIEW_QOS);

    _this = os_malloc(sizeof(C_STRUCT(v_dataViewQos)));
    if (_template != NULL) {
        *_this = *_template;

        _this->userKey.v.expression = NULL;
        if (_template->userKey.v.enable) {
            if (_template->userKey.v.expression != NULL) {
                _this->userKey.v.expression = os_strdup (_template->userKey.v.expression);
            }
        }
    } else {
        ((v_qos)_this)->kind      = V_DATAVIEW_QOS;
        _this->userKey.v.enable     = FALSE;
        _this->userKey.v.expression = NULL;
    }
    return _this;
}

void
u_dataViewQosFree(
    u_dataViewQos _this)
{
    assert(_this && ((v_qos)_this)->kind == V_DATAVIEW_QOS);
    os_free(_this->userKey.v.expression);
    os_free(_this);
}


text:
package org.smart4j.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by lan_cyl on 2016/11/2.
 */
public final class ReflectionUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class);

    public static Object newInstance(Class<?> cls) {
        try {
            return cls.newInstance();
        } catch (Exception e) {
            LOGGER.error("new instance failure", e);
            throw new RuntimeException(e);
        }
    }

    public static Object invokeMethod(Object obj, Method method, Object... args) {
        try {
            method.setAccessible(true);
            return method.invoke(obj, args);
        } catch (Exception e) {
            LOGGER.error("invoke method failure", e);
            throw new RuntimeException(e);
        }
    }

    public static void setField(Object obj, Field field, Object value) {
        try {
            field.setAccessible(true);
            field.set(obj, value);
        } catch (IllegalAccessException e) {
            LOGGER.error("set field failure", e);
            throw new RuntimeException(e);
        }
    }
}


text:
<?php

/**
 * Copy this file to your APPPATH/config directory and modify it there.
 */
return array(

	/**
	 * General configuration
	 */

	/**
	 * Your GTM ID from Google
	 */
	'ID'	=> '[ENTER YOUR GTM ID]',

	/**
	 * Enhanced Ecommerce
	 */

	/**
	 * For all those currency code fields :)
	 */
	'currency_code'	=> 'USD',

	/**
	 *  Set the page URI to a human readable page name. This key is used for EVERYTHING that uses the "list"
	 *  property. This property is always the name of the page. If a page is not specified here, the script
	 *  will use the URL path for this field.
	 *
	 *  @link https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#impression-data
	 */
	'list'	=> array(

		'/'	=> 'Home Page'

	),

	/**
	 * If the page isn't listed with the 'list' key above, the script will use the URL path for the 'list' option.
	 * Should we remove a portion of the URL when doing so? If so, set the portion to remove. If the URL result is
	 * empty, we will use "/".
	 */
	'remove_from_url'	=> '',

	/**
	 * Should we include the query string in the output for URLs not listed with 'list'?
	 */
	'include_query_string'	=> false,

	/**
	 * The script manages what items are in the cart based on cart additions and removals. In order to keep
	 * a running list, it must use either the "name" of the product, or its "id" field. Set this to "id" or
	 * "name" to tell the script what to use to track your cart's contents. The contents of this key must be
	 * unique to each product and it must be present.
	 *
	 * @link https://developers.google.com/tag-manager/enhanced-ecommerce#checkout
	 */
	'cart_products_identifier'	=> 'id',

	/**
	 * Default values for every type of analytical data
	 *
	 * @link https://developers.google.com/tag-manager/enhanced-ecommerce
	 * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#ecommerce-data
	 */
	'defaults'	=> array(

		/**
		 * Only items common to every impression. These are merged with each "impressions" section.
		 *
		 * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#impression-data
		 */
		'impressions'	=> array(

			// 'category'	=> 'Core Products',

		),

		/**
		 * Only items common to every product view. These are merged with each "products" section.
		 *
		 * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#product-data
		 */
		'product_view'	=> array(

			// 'category'	=> 'Core Products',

		),

		/**
		 * Only items common to every cart change. These are merged with each "products" section.
		 *
		 * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#product-data
		 */
		'cart'	=> array(

			// 'category'	=> 'Core Products',

		),

		/**
		 * All possible values for productFieldObject (List of your products) You may set the $config property of the
		 * \GTM\Analytics class to change this value in realtime.
		 * Ex. $analytics->config['defaults']['product_click'] = array()
		 *
		 * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#product-data
		 */
		'product_click'	=> array(

			/*
			'product-free'	=> array(

				'name'		=> 'Free for Life',
				'category'	=> 'Core Products',
				'price'		=> 0.00

			),
			'product-tier1'	=> array(

				'name'		=> 'Tier 1',
				'category'	=> 'Core Products',
				'price'		=> 0.00

			),
			'product-tier2'	=> array(

				'name'		=> 'Tier 2',
				'category'	=> 'Core Products',
				'price'		=> 0.00

			)
			*/

		),

		/**
		 * All possible values for promoFieldObject (List of your promos) You may set the $config property of the
		 * \GTM\Analytics class to change this value in realtime.
		 * Ex. $analytics->config['defaults']['product_click'] = array()
		 *
		 * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#promotion-data
		 */
		'promo_click'	=> array(

			/*
			'promo-test'	=> array(

				'id'		=> 'TEST_TOP',
				'name'		=> 'Test Top',
				'creative'	=> 'test_banner',
				'position'	=> 'header'

			),

			'promo-test2'	=> array(

				'id'		=> 'TEST_TOP2',
				'name'		=> 'Test Top2',
				'creative'	=> 'test_banner2',
				'position'	=> 'footer'

			),

			'promo-test3'	=> array(

				'id'		=> 'TEST_TOP3',
				'name'		=> 'Test Top3',
				'creative'	=> 'test_banner3',
				'position'	=> 'sidebar'

			),
			*/
		),

		/**
		 * Any variables you'd like to set for your page before the GTM code loads. Don't add events here. The non-js
		 * version uses this key and cannot use events. Use the non_events key or set_non_event() method for non_events
		 * or use the events key or the set_event() method for custom events.
		 *
		 * @link https://developers.google.com/tag-manager/devguide#multipush
		 */
		'variables'	=> array(

			// 'testvar'	=> 'testval'

		),

		/**
		 * All calls that do not have a specified event (or are specified with 'event': 'gtm.js') must be added to
		 * this key or they will never be used by GTM. You may of course omit any non-event code handled by this
		 * package.
		 *
		 * @link https://productforums.google.com/d/msg/tag-manager/albJCkoKhFk/gVx23nIqatYJ
		 * @link https://productforums.google.com/d/msg/tag-manager/Y4-0cizIosw/knE7u86VwHcJ
		 */
		'non_events'	=> array(

			/*
			'test'	=> array(

				'test1'	=> 'test2'

			),

			'ecommerce'	=> array(

				'my_ecommerce'	=> 'my_val'

			)
			*/

		),

		'events'	=> array(

			/*
			'my_event_name'	=> array(

				'ecommerce'	=> array(

					'testevent'	=> 'testval'

				)

			)
			*/

		)

	)

);


text:
set -e

export CLASSPATH=<%= @classpath %>
export PIG_OPTS="<% @pig_opts.each do |k,v| %>-J-D<%= k %>=<%= v %> <% end %>"
export DEFAULT_PIG_OPTS_FILES="<%= @default_pig_opts_files %>"
export LOG4J_CONF=<%= @log4j_conf %>

# UDF paths are relative to this direectory
cd <%= @project_home %>/pigscripts

# Setup python environment
source <%= @local_install_dir %>/pythonenv/bin/activate

# To debug add the following line to the Run Jython statement
#  -J-Xdebug -J-Xrunjdwp:transport=dt_socket,server=y,address=8000 \

# Run Jython
<%= @local_install_dir %>/jython/bin/jython \
  $PIG_OPTS \
  -Dpython.verbose=error \
  -Dpython.security.respectJavaAccessibility=false \
  <%= @pig_jig_directory %>/pigjig.py


text:
'use strict';

const empty = (obj) => !Object.keys(obj).length;

module.exports = (selector, divider, value) => {
    if (!value) {
        value = divider;
        divider = '.';
    }

    check(selector, value);

    if (!selector)
        return value;

    if (empty(value))
        return undefined;

    const selects = selector.split(divider);

    selects
        .some((name, i) => {
            const nestedName = selects.slice(i).join(divider);

            if (typeof value[nestedName] !== 'undefined') {
                value = value[nestedName];
                return true;
            }

            if (!value[name]) {
                value = undefined;
                return true;
            }

            value = value[name];

            return !value;
        });

    return value;
};

function check(selector, obj) {
    if (typeof selector !== 'string')
        throw Error('selector should be string!');

    if (typeof obj !== 'object')
        throw Error('obj should be object!');
}


text:
package com.zimbra.qa.selenium.projects.ajax.ui.addressbook;

import com.zimbra.qa.selenium.framework.items.ContactGroupItem;
import com.zimbra.qa.selenium.framework.items.IItem;
import com.zimbra.qa.selenium.framework.ui.AbsApplication;
import com.zimbra.qa.selenium.framework.ui.AbsForm;
import com.zimbra.qa.selenium.framework.util.HarnessException;
import com.zimbra.qa.selenium.projects.ajax.ui.addressbook.FormContactGroupNew.Locators;

public class SimpleFormContactGroupNew extends AbsForm {

	public static final String WINDOW_DIALOGNAME = "css=div#CreateContactGroupDialog";
	public static final String INPUT_GROUPNAME = "css=input#CreateContactGroupDialog_name";
	public static final String BUTTON_SAVE     = "css=div#CreateContactGroupDialog_button2";
	public static final String BUTTON_CANCEL   = "css=div#CreateContactGroupDialog_button1";

	public SimpleFormContactGroupNew(AbsApplication application) {
		super(application);
		logger.info("new " + SimpleFormContactGroupNew.class.getCanonicalName());
	}

	@Override
	public String myPageName() {
		return (this.getClass().getName());
	}

	@Override
	public void zSubmit() throws HarnessException {
		logger.info("SimpleFormContactNew.zSubmit()");
		// Click on it
		zClick(BUTTON_SAVE);
		zWaitForBusyOverlay();
	}

	public void zCancel() throws HarnessException {
		logger.info("SimpleFormContactNew.zCancel()");
		// Click on it
		zClick(BUTTON_CANCEL);
		zWaitForBusyOverlay();
	}

	@Override
	public boolean zIsActive() throws HarnessException {
		logger.info(myPageName() + " zIsActive()");

		if ( !this.sIsElementPresent(WINDOW_DIALOGNAME) ) {
			return (false); // Not even present
		}

		if ( !this.zIsVisiblePerPosition(WINDOW_DIALOGNAME, 0, 0) ) {
			return (false);	// Not visible per position
		}

		// Yes, visible
		logger.info(myPageName() + " zIsVisible() = true");
		return (true);
	}

	@Override
	public void zFill(IItem item) throws HarnessException {
		logger.info("SimpleFormContactGroupNew.fill(IItem)");
		logger.info(item.prettyPrint());

		// Make sure the item is a ContactGroupItem
		if ( !(item instanceof ContactGroupItem) ) {
			throw new HarnessException("Invalid item type - must be ContactGroupItem");
		}

		// Convert object to ContactGroupItem
		ContactGroupItem group = (ContactGroupItem) item;

		// Fill out the form
		if (( group.groupName != null )  && (group.groupName.trim().length() >0)){
			sType(INPUT_GROUPNAME,group.groupName);

		}
		else {
			throw new HarnessException("Empty group name - group name is required");
		}

	}
}


text:
import * as d3 from "d3-request";
import {
    default as paramsToQuery
} from '../util/paramsToQuery.js';
import {
    default as createRequestFactory
} from './RequestFactory.js';

function performRequest(method, type, url, params, headers, callback) {
    var request;
    request = d3[type](url);
    Object.keys(headers).forEach(function(key) {
        request.header(key, headers[key]);
    });
    request.on("error", function(error) {
        var errorTarget = error.target;
        try {
            errorTarget = JSON.parse(errorTarget.responseText);
        } catch (e) {
            // parse failed -> call with unparsed errorTarget
        }
        callback(errorTarget);
    }).on("load", function(data) {
        callback(false, data);
    });
    request.send(method, paramsToQuery(params));
}

export default createRequestFactory(performRequest);