text:
package io.xlate.edi.internal.schema;

import static io.xlate.edi.internal.schema.StaEDISchemaFactory.schemaException;
import static io.xlate.edi.internal.schema.StaEDISchemaFactory.unexpectedElement;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.logging.Logger;
import java.util.stream.StreamSupport;

import javax.xml.namespace.QName;
import javax.xml.stream.Location;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;

import io.xlate.edi.internal.schema.implementation.BaseComplexImpl;
import io.xlate.edi.internal.schema.implementation.BaseImpl;
import io.xlate.edi.internal.schema.implementation.CompositeImpl;
import io.xlate.edi.internal.schema.implementation.DiscriminatorImpl;
import io.xlate.edi.internal.schema.implementation.ElementImpl;
import io.xlate.edi.internal.schema.implementation.LoopImpl;
import io.xlate.edi.internal.schema.implementation.Positioned;
import io.xlate.edi.internal.schema.implementation.SegmentImpl;
import io.xlate.edi.internal.schema.implementation.TransactionImpl;
import io.xlate.edi.schema.EDIComplexType;
import io.xlate.edi.schema.EDIElementPosition;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.EDISchemaException;
import io.xlate.edi.schema.EDIType;
import io.xlate.edi.schema.EDIType.Type;
import io.xlate.edi.schema.implementation.Discriminator;
import io.xlate.edi.schema.implementation.EDITypeImplementation;
import io.xlate.edi.schema.implementation.LoopImplementation;

class SchemaReaderV3 extends SchemaReaderBase implements SchemaReader {

    private static final Logger LOGGER = Logger.getLogger(SchemaReaderV3.class.getName());

    private static final String ATTR_POSITION = "position";
    private static final String ATTR_DISCRIMINATOR = "discriminator";

    final Deque<EDITypeImplementation> implementedTypes = new LinkedList<>();

    static class ValueSet {
        Map<String, String> value;

        void set(Map<String, String> value) {
            this.value = value;
        }

        Map<String, String> get() {
            return requireNonNullElseGet(value, Collections::emptyMap);
        }

        void clear() {
            this.value = null;
        }
    }

    final ValueSet valueSet = new ValueSet();

    protected SchemaReaderV3(String xmlns, XMLStreamReader reader, Map<String, Object> properties) {
        super(xmlns, reader, properties);
    }

    public SchemaReaderV3(XMLStreamReader reader, Map<String, Object> properties) {
        this(StaEDISchemaFactory.XMLNS_V3, reader, properties);
    }

    @Override
    protected String readReferencedId(XMLStreamReader reader) {
        String id = reader.getAttributeValue(null, "type");
        if (id == null) {
            id = reader.getAttributeValue(null, "ref");

            if (id != null) {
                Location parseLocation = reader.getLocation();
                LOGGER.warning("Attribute 'ref' is deprecated at line "
                        + parseLocation.getLineNumber()
                        + ", column " + parseLocation.getColumnNumber());
            }
        }
        return id;
    }

    @Override
    protected void readInclude(XMLStreamReader reader, Map<String, EDIType> types) throws EDISchemaException {
        // Included schema not supported in V3 Schema
        throw unexpectedElement(reader.getName(), reader);
    }

    @Override
    protected void readImplementation(XMLStreamReader reader, Map<String, EDIType> types) {
        QName element = reader.getName();

        if (qnImplementation.equals(element)) {
            LoopImplementation impl = readImplementation(reader, element, types);

            if (impl != null) {
                types.put(StaEDISchema.IMPLEMENTATION_ID, impl);
            }

            nextTag(reader, "seeking next element after implementation end");
        }
    }

    @Override
    void setReferences(Map<String, EDIType> types) {
        super.setReferences(types);

        StreamSupport.stream(Spliterators.spliteratorUnknownSize(implementedTypes.descendingIterator(),
            Spliterator.ORDERED),
            false)
                     .filter(type -> type.getType() != Type.ELEMENT)
                     .map(BaseComplexImpl.class::cast)
                     .forEach(type -> setReferences(type, types));
    }

    void setReferences(BaseComplexImpl type, Map<String, EDIType> types) {
        String typeId = type.getTypeId();
        EDIComplexType standard = (EDIComplexType) types.get(typeId);
        if (standard == null) {
            throw schemaException("Type " + typeId + " does not correspond to a standard type");
        }
        List<EDIReference> standardRefs = standard.getReferences();
        List<EDITypeImplementation> implSequence = type.getSequence();

        if (implSequence.isEmpty()) {
            implSequence.addAll(getDefaultSequence(standardRefs));
            return;
        }

        AtomicBoolean verifyOrder = new AtomicBoolean(false);

        implSequence.stream()
            .filter(BaseImpl.class::isInstance)
            .map(BaseImpl.class::cast)
            .forEach(typeImpl -> {
                if (typeImpl instanceof Positioned) {
                    typeImpl.setStandardReference(getReference((Positioned) typeImpl, standard));
                } else {
                    typeImpl.setStandardReference(getReference(typeImpl, standard));
                    verifyOrder.set(true);
                }
            });

        if (verifyOrder.get()) {
            verifyOrder(standard, implSequence);
        }
    }

    EDIReference getReference(Positioned positionedTypeImpl, EDIComplexType standard) {
        final int position = positionedTypeImpl.getPosition();
        final List<EDIReference> standardRefs = standard.getReferences();
        final int offset = position - 1;

        if (offset < standardRefs.size()) {
            return standardRefs.get(offset);
        } else {
            throw schemaException("Position " + position + " does not correspond to an entry in type " + standard.getId());
        }
    }

    EDIReference getReference(BaseImpl<?> typeImpl, EDIComplexType standard) {
        final String refTypeId = typeImpl.getTypeId();

        for (EDIReference stdRef : standard.getReferences()) {
            if (stdRef.getReferencedType().getId().equals(refTypeId)) {
                return stdRef;
            }
        }

        throw schemaException("Reference " + refTypeId + " does not correspond to an entry in type " + standard.getId());
    }

    void verifyOrder(EDIComplexType standard, List<EDITypeImplementation> implSequence) {
        Iterator<String> standardTypes = standard.getReferences()
                .stream()
                .map(EDIReference::getReferencedType)
                .map(EDIType::getId)
                .iterator();

        String stdId = standardTypes.next();

        for (EDITypeImplementation implRef : implSequence) {
            String implId = implRef.getReferencedType().getId();

            while (!implId.equals(stdId)) {
                if (standardTypes.hasNext()) {
                    stdId = standardTypes.next();
                } else {
                    String template = "%s reference %s is not in the correct order for the sequence of standard type %s";
                    throw schemaException(String.format(template, implRef.getType(), implRef.getCode(), standard.getId()));
                }
            }
        }
    }

    List<EDITypeImplementation> getDefaultSequence(List<EDIReference> standardRefs) {
        List<EDITypeImplementation> sequence = new ArrayList<>(standardRefs.size());
        int position = 0;

        for (EDIReference ref : standardRefs) {
            sequence.add(getDefaultImplementation(ref, ++position));
        }

        return sequence;
    }

    EDITypeImplementation getDefaultImplementation(EDIReference standardReference, int position) {
        EDIType std = standardReference.getReferencedType();

        switch (std.getType()) {
        case ELEMENT:
            return new ElementImpl(standardReference, position);
        case COMPOSITE:
            return new CompositeImpl(standardReference, position, getDefaultSequence(((EDIComplexType) std).getReferences()));
        case SEGMENT:
            return new SegmentImpl(standardReference, getDefaultSequence(((EDIComplexType) std).getReferences()));
        case LOOP:
            return new LoopImpl(standardReference, getDefaultSequence(((EDIComplexType) std).getReferences()));
        default:
            throw schemaException("Implementation of " + std.getId() + " must not be empty");
        }
    }

    LoopImplementation readImplementation(XMLStreamReader reader,
                                          QName complexType,
                                          Map<String, EDIType> types) {

        LoopImplementation loop = readLoopImplementation(reader, complexType, true);
        String typeId = StaEDISchema.TRANSACTION_ID;
        EDIComplexType standard = (EDIComplexType) types.get(typeId);
        LoopImpl impl = new TransactionImpl(StaEDISchema.IMPLEMENTATION_ID, typeId, loop.getSequence());
        impl.setStandardReference(new Reference(standard, 1, 1));
        implementedTypes.add(impl);
        return impl;
    }

    LoopImplementation readLoopImplementation(XMLStreamReader reader, QName complexType, boolean transactionLoop) {
        List<EDITypeImplementation> sequence = new ArrayList<>();
        String id;
        String typeId;
        int minOccurs;
        int maxOccurs;
        EDIElementPosition discriminatorPos;
        String title;

        if (transactionLoop) {
            id = StaEDISchema.IMPLEMENTATION_ID;
            typeId = null;
            minOccurs = 0;
            maxOccurs = 0;
            discriminatorPos = null;
            title = null;
        } else {
            id = parseAttribute(reader, "code", String::valueOf);
            typeId = parseAttribute(reader, "type", String::valueOf);
            minOccurs = parseAttribute(reader, ATTR_MIN_OCCURS, Integer::parseInt, -1);
            maxOccurs = parseAttribute(reader, ATTR_MAX_OCCURS, Integer::parseInt, -1);
            discriminatorPos = parseElementPosition(reader, ATTR_DISCRIMINATOR);
            title = parseAttribute(reader, ATTR_TITLE, String::valueOf, null);
        }

        return readTypeImplementation(reader,
            () -> readSequence(reader, e -> readLoopSequenceEntry(e, sequence)),
            descr -> whenExpected(reader, complexType, () -> {
                Discriminator disc = null;
                if (discriminatorPos != null) {
                    SegmentImpl segImpl = (SegmentImpl) sequence.get(0);
                    disc = buildDiscriminator(discriminatorPos, segImpl.getSequence());
                }
                return new LoopImpl(minOccurs, maxOccurs, id, typeId, disc, sequence, title, descr);
            }));
    }

    void readLoopSequenceEntry(QName entryName, List<EDITypeImplementation> sequence) {
        if (entryName.equals(qnLoop)) {
            if (sequence.isEmpty()) {
                throw schemaException("segment element must be first child of loop sequence", reader);
            }
            LoopImplementation loop = readLoopImplementation(reader, entryName, false);
            implementedTypes.add(loop);
            sequence.add(loop);
        } else if (entryName.equals(qnSegment)) {
            sequence.add(readSegmentImplementation());
        } else {
            throw unexpectedElement(entryName, reader);
        }
    }

    SegmentImpl readSegmentImplementation() {
        List<EDITypeImplementation> sequence = new ArrayList<>();
        String typeId = parseAttribute(reader, "type", String::valueOf);
        String code = parseAttribute(reader, "code", String::valueOf, typeId);
        int minOccurs = parseAttribute(reader, ATTR_MIN_OCCURS, Integer::parseInt, -1);
        int maxOccurs = parseAttribute(reader, ATTR_MAX_OCCURS, Integer::parseInt, -1);
        EDIElementPosition discriminatorPos = parseElementPosition(reader, ATTR_DISCRIMINATOR);
        String title = parseAttribute(reader, ATTR_TITLE, String::valueOf, null);

        return readTypeImplementation(reader,
            () -> readSequence(reader, e -> readPositionedSequenceEntry(e, sequence, true)),
            descr -> whenExpected(reader, qnSegment, () -> {
                Discriminator disc = buildDiscriminator(discriminatorPos, sequence);
                SegmentImpl segment = new SegmentImpl(minOccurs,
                    maxOccurs,
                    typeId,
                    code,
                    disc,
                    sequence,
                    title,
                    descr);
                implementedTypes.add(segment);
                return segment;
            }));
    }

    void readPositionedSequenceEntry(QName entryName, List<EDITypeImplementation> sequence, boolean composites) {
        EDITypeImplementation type;

        if (entryName.equals(qnElement)) {
            type = readElementImplementation(reader);
        } else if (composites && entryName.equals(qnComposite)) {
            type = readCompositeImplementation(reader);
        } else {
            throw unexpectedElement(entryName, reader);
        }

        implementedTypes.add(type);

        int position = ((Positioned) type).getPosition();

        while (position > sequence.size()) {
            sequence.add(null);
        }

        EDITypeImplementation previous = sequence.set(position - 1, type);

        if (previous != null) {
            throw schemaException("Duplicate value for position " + position, reader);
        }
    }

    Discriminator buildDiscriminator(EDIElementPosition discriminatorPos,
                                     List<EDITypeImplementation> sequence) {
        Discriminator disc = null;

        if (discriminatorPos != null) {
            final int elementPosition = discriminatorPos.getElementPosition();
            final int componentPosition = discriminatorPos.getComponentPosition();

            EDITypeImplementation eleImpl = getDiscriminatorElement(discriminatorPos, elementPosition, sequence, "element");

            if (eleImpl instanceof CompositeImpl) {
                sequence = ((CompositeImpl) eleImpl).getSequence();
                eleImpl = getDiscriminatorElement(discriminatorPos, componentPosition, sequence, "component");
            }

            Set<String> discValues;

            if (eleImpl != null) {
                discValues = ((ElementImpl) eleImpl).getValueSet();
            } else {
                throw schemaException("Discriminator position is unused (not specified): " + discriminatorPos, reader);
            }

            if (!discValues.isEmpty()) {
                disc = new DiscriminatorImpl(discriminatorPos, discValues);
            } else {
                throw schemaException("Discriminator element does not specify value enumeration: " + discriminatorPos, reader);
            }
        }

        return disc;
    }

    EDITypeImplementation getDiscriminatorElement(EDIElementPosition discriminatorPos,
                                                  int position,
                                                  List<EDITypeImplementation> sequence,
                                                  String type) {

        validatePosition(position, 1, sequence.size(), () -> "Discriminator " + type + " position invalid: " + discriminatorPos);
        return sequence.get(position - 1);
    }

    CompositeImpl readCompositeImplementation(XMLStreamReader reader) {
        List<EDITypeImplementation> sequence = new ArrayList<>(5);
        int position = parseAttribute(reader, ATTR_POSITION, Integer::parseInt, -1);
        int minOccurs = parseAttribute(reader, ATTR_MIN_OCCURS, Integer::parseInt, -1);
        int maxOccurs = parseAttribute(reader, ATTR_MAX_OCCURS, Integer::parseInt, -1);
        String title = parseAttribute(reader, ATTR_TITLE, String::valueOf, null);

        validatePosition(position, 1, Integer.MAX_VALUE, () -> "Invalid position");

        return readTypeImplementation(reader,
            () -> readSequence(reader, e -> readPositionedSequenceEntry(e, sequence, false)),
            descr -> whenExpected(reader,
                qnComposite,
                () -> new CompositeImpl(minOccurs,
                    maxOccurs,
                    null,
                    position,
                    sequence,
                    title,
                    descr)));
    }

    void readSequence(XMLStreamReader reader, Consumer<QName> startHandler) {
        requireElementStart(qnSequence, reader);

        do {
            if (nextTag(reader, "reading sequence") == XMLStreamConstants.START_ELEMENT) {
                startHandler.accept(reader.getName());
            }
        } while (!reader.getName().equals(qnSequence));
    }

    ElementImpl readElementImplementation(XMLStreamReader reader) {
        this.valueSet.clear();
        int position = parseAttribute(reader, ATTR_POSITION, Integer::parseInt, -1);
        int minOccurs = parseAttribute(reader, ATTR_MIN_OCCURS, Integer::parseInt, -1);
        int maxOccurs = parseAttribute(reader, ATTR_MAX_OCCURS, Integer::parseInt, -1);
        String title = parseAttribute(reader, ATTR_TITLE, String::valueOf, null);

        validatePosition(position, 1, Integer.MAX_VALUE, () -> "Invalid position");

        return readTypeImplementation(reader,
            () -> valueSet.set(super.readEnumerationValues(reader)),
            descr -> whenExpected(reader,
                qnElement,
                () -> new ElementImpl(minOccurs,
                    maxOccurs,
                    (String) null,
                    position,
                    valueSet.get(),
                    title,
                    descr)));
    }

    void validatePosition(int position, int min, int max, Supplier<String> message) {
        if (position < min || position > max) {
            throw schemaException(message.get(), reader);
        }
    }

    <T> T whenExpected(XMLStreamReader reader, QName expected, Supplier<T> supplier) {
        requireElement(expected, reader);
        return supplier.get();
    }

    <T> T readTypeImplementation(XMLStreamReader reader, Runnable contentHandler, Function<String, T> endHandler) {

        String descr = readDescription(reader);

        if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
            contentHandler.run();
        } else {
            return endHandler.apply(descr);
        }

        nextTag(reader, "reading type implementation end element");
        requireEvent(XMLStreamConstants.END_ELEMENT, reader);
        return endHandler.apply(descr);
    }
}


text:
#region License

#endregion

#region Imports

using System;
using System.Reflection;

using Spring.Aop;

#endregion

namespace Spring.AopQuickStart.Aspects
{
    /// <summary>
    /// Simple implementation of the <see cref="Spring.Aop.IMethodBeforeAdvice"/> interface
    /// for a logging aspect using <see cref="System.Console"/>.
    /// </summary>
    /// <author>Rick Evans</author>
    /// <version>$Id: ConsoleLoggingBeforeAdvice.cs,v 1.1 2006/11/26 18:57:59 bbaia Exp $</version>
	public class ConsoleLoggingBeforeAdvice : IMethodBeforeAdvice
	{
		public void Before(MethodInfo method, object[] args, object target)
		{
			Console.Out.WriteLine("Intercepted call to this method : " + method.Name);
			Console.Out.WriteLine("    The target is       : " + target);
			Console.Out.WriteLine("    The arguments are   : ");
			if(args != null)
			{
				foreach (object arg in args)
				{
					Console.Out.WriteLine("\t: " + arg);
				}
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#include "../javaexport_api.h"
#include "../exporter/ExportError.h"
#include "Visitor.h"

namespace Export {
	class SourceDir;
	class SourceFile;
	class SourceFragment;
}

namespace JavaExport {

class JAVAEXPORT_API DeclarationVisitor : public Visitor {
	public:
		using Visitor::Visitor;

		Export::SourceDir* visitProject(OOModel::Project* project, Export::SourceDir* parent = nullptr);
		Export::SourceDir* visitModule(OOModel::Module* module, Export::SourceDir* parent);
		Export::SourceFile* visitTopLevelClass(OOModel::Class* classs, Export::SourceDir* parent);

		Export::SourceFragment* visit(OOModel::Declaration* declaration);

		Export::SourceFragment* visit(OOModel::Class* classs);
		Export::SourceFragment* visit(OOModel::Method* method);
		//Export::SourceFragment* visit(OOModel::Field* field); Omitted on purpose, VariableDeclaration suffices
		Export::SourceFragment* visit(OOModel::NameImport* nameImport);
		Export::SourceFragment* visit(OOModel::VariableDeclaration* vd);

		Export::SourceFragment* visit(OOModel::ExplicitTemplateInstantiation* eti);
		Export::SourceFragment* visit(OOModel::TypeAlias* ta);

		Export::SourceFragment* printAnnotationsAndModifiers(OOModel::Declaration* declaration);
};

} /* namespace JavaExport */


text:
title: Features
aliases:
    - /enterprise/v1.0/features/
menu:
  enterprise_influxdb_1_0:
    weight: 40
---

## [InfluxEnterprise Users](/enterprise_influxdb/v1.0/features/users/)
## [Cluster Commands](/enterprise_influxdb/v1.0/features/cluster-commands/)
## [Clustering Features](/enterprise_influxdb/v1.0/features/clustering-features/)
## [Web Console Features](/enterprise_influxdb/v1.0/features/web-console-features/)


text:
"""Tests for the creator dashboard and the notifications dashboard."""

import datetime

from constants import constants
from core.controllers import creator_dashboard
from core.domain import collection_services
from core.domain import event_services
from core.domain import exp_fetchers
from core.domain import exp_services
from core.domain import feedback_domain
from core.domain import feedback_services
from core.domain import rating_services
from core.domain import rights_manager
from core.domain import subscription_services
from core.domain import suggestion_services
from core.domain import user_jobs_continuous
from core.domain import user_jobs_one_off
from core.domain import user_services
from core.platform import models
from core.tests import test_utils
import feconf

(user_models, stats_models, suggestion_models) = models.Registry.import_models(
    [models.NAMES.user, models.NAMES.statistics, models.NAMES.suggestion])
taskqueue_services = models.Registry.import_taskqueue_services()

class MockUserStatsAggregator(
        user_jobs_continuous.UserStatsAggregator):
    """A modified UserStatsAggregator that does not start a new
     batch job when the previous one has finished.
    """
    @classmethod
    def _get_batch_job_manager_class(cls):
        return MockUserStatsMRJobManager

    @classmethod
    def _kickoff_batch_job_after_previous_one_ends(cls):
        pass

class MockUserStatsMRJobManager(
        user_jobs_continuous.UserStatsMRJobManager):

    @classmethod
    def _get_continuous_computation_class(cls):
        return MockUserStatsAggregator

class HomePageTests(test_utils.GenericTestBase):

    def test_logged_out_homepage(self):
        """Test the logged-out version of the home page."""
        response = self.get_html_response('/', expected_status_int=302)

        self.assertIn('splash', response.headers['location'])

    def test_notifications_dashboard_redirects_for_logged_out_users(self):
        """Test the logged-out view of the notifications dashboard."""
        response = self.get_html_response(
            '/notifications_dashboard', expected_status_int=302)
        # This should redirect to the login page.
        self.assertIn('signup', response.headers['location'])
        self.assertIn('notifications_dashboard', response.headers['location'])

        self.login('reader@example.com')
        self.get_html_response(
            '/notifications_dashboard', expected_status_int=302)
        # This should redirect the user to complete signup.
        self.logout()

    def test_logged_in_notifications_dashboard(self):
        """Test the logged-in view of the notifications dashboard."""
        self.signup(self.EDITOR_EMAIL, self.EDITOR_USERNAME)

        self.login(self.EDITOR_EMAIL)
        self.get_html_response('/notifications_dashboard')
        self.logout()

class CreatorDashboardStatisticsTests(test_utils.GenericTestBase):
    OWNER_EMAIL_1 = 'owner1@example.com'
    OWNER_USERNAME_1 = 'owner1'
    OWNER_EMAIL_2 = 'owner2@example.com'
    OWNER_USERNAME_2 = 'owner2'

    EXP_ID_1 = 'exp_id_1'
    EXP_TITLE_1 = 'Exploration title 1'
    EXP_ID_2 = 'exp_id_2'
    EXP_TITLE_2 = 'Exploration title 2'

    EXP_DEFAULT_VERSION = 1

    USER_SESSION_ID = 'session1'
    USER_IMPACT_SCORE_DEFAULT = 0.0

    def setUp(self):
        super(CreatorDashboardStatisticsTests, self).setUp()
        self.signup(self.OWNER_EMAIL_1, self.OWNER_USERNAME_1)
        self.signup(self.OWNER_EMAIL_2, self.OWNER_USERNAME_2)

        self.owner_id_1 = self.get_user_id_from_email(self.OWNER_EMAIL_1)
        self.owner_id_2 = self.get_user_id_from_email(self.OWNER_EMAIL_2)
        self.owner_1 = user_services.UserActionsInfo(self.owner_id_1)

    def _record_start(self, exp_id, exp_version, state):
        """Record start event to an exploration.
        Completing the exploration is not necessary here since the total_plays
        are currently being counted taking into account only the # of starts.
        """
        event_services.StartExplorationEventHandler.record(
            exp_id, exp_version, state, self.USER_SESSION_ID, {},
            feconf.PLAY_TYPE_NORMAL)
        event_services.StatsEventsHandler.record(
            exp_id, exp_version, {
                'num_starts': 1,
                'num_actual_starts': 0,
                'num_completions': 0,
                'state_stats_mapping': {}
            })

    def _rate_exploration(self, exp_id, ratings):
        """Create num_ratings ratings for exploration with exp_id,
        of values from ratings.
        """
        # Generate unique user ids to rate an exploration. Each user id needs
        # to be unique since each user can only give an exploration one rating.
        user_ids = ['user%d' % i for i in range(len(ratings))]
        self.process_and_flush_pending_tasks()
        for ind, user_id in enumerate(user_ids):
            rating_services.assign_rating_to_exploration(
                user_id, exp_id, ratings[ind])
        self.process_and_flush_pending_tasks()

    def _run_user_stats_aggregator_job(self):
        """Runs the User Stats Aggregator job."""
        MockUserStatsAggregator.start_computation()
        self.assertEqual(
            self.count_jobs_in_taskqueue(
                taskqueue_services.QUEUE_NAME_CONTINUOUS_JOBS), 1)
        self.process_and_flush_pending_tasks()
        self.assertEqual(
            self.count_jobs_in_taskqueue(
                taskqueue_services.QUEUE_NAME_CONTINUOUS_JOBS), 0)
        self.process_and_flush_pending_tasks()

    def _run_one_off_job(self):
        """Runs the one-off MapReduce job."""
        self.assertEqual(
            self.count_jobs_in_taskqueue(
                taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0)
        job_id = user_jobs_one_off.DashboardStatsOneOffJob.create_new()
        user_jobs_one_off.DashboardStatsOneOffJob.enqueue(job_id)
        self.assertEqual(
            self.count_jobs_in_taskqueue(
                taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 1)
        self.process_and_flush_pending_tasks()

    def test_stats_no_explorations(self):
        self.login(self.OWNER_EMAIL_1)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(response['explorations_list'], [])
        self._run_user_stats_aggregator_job()
        self.assertIsNone(user_models.UserStatsModel.get(
            self.owner_id_1, strict=False))
        self.logout()

    def test_one_play_for_single_exploration(self):
        exploration = self.save_new_default_exploration(
            self.EXP_ID_1, self.owner_id_1, title=self.EXP_TITLE_1)

        self.login(self.OWNER_EMAIL_1)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 1)

        exp_version = self.EXP_DEFAULT_VERSION
        exp_id = self.EXP_ID_1
        state = exploration.init_state_name

        self._record_start(exp_id, exp_version, state)

        self._run_user_stats_aggregator_job()
        user_model = user_models.UserStatsModel.get(self.owner_id_1)
        self.assertEqual(user_model.total_plays, 1)
        self.assertEqual(
            user_model.impact_score, self.USER_IMPACT_SCORE_DEFAULT)
        self.assertEqual(user_model.num_ratings, 0)
        self.assertIsNone(user_model.average_ratings)
        self.logout()

    def test_one_rating_for_single_exploration(self):
        self.save_new_default_exploration(
            self.EXP_ID_1, self.owner_id_1, title=self.EXP_TITLE_1)

        self.login(self.OWNER_EMAIL_1)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 1)

        exp_id = self.EXP_ID_1
        self._rate_exploration(exp_id, [4])

        self._run_user_stats_aggregator_job()
        user_model = user_models.UserStatsModel.get(self.owner_id_1)
        self.assertEqual(user_model.total_plays, 0)
        self.assertEqual(
            user_model.impact_score, self.USER_IMPACT_SCORE_DEFAULT)
        self.assertEqual(user_model.num_ratings, 1)
        self.assertEqual(user_model.average_ratings, 4)
        self.logout()

    def test_one_play_and_rating_for_single_exploration(self):
        exploration = self.save_new_default_exploration(
            self.EXP_ID_1, self.owner_id_1, title=self.EXP_TITLE_1)

        self.login(self.OWNER_EMAIL_1)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 1)

        exp_id = self.EXP_ID_1

        exp_version = self.EXP_DEFAULT_VERSION
        state = exploration.init_state_name

        self._record_start(exp_id, exp_version, state)

        self._rate_exploration(exp_id, [3])

        self._run_user_stats_aggregator_job()

        def _mock_get_date_after_one_week():
            """Returns the date of the next week."""
            return (
                (datetime.datetime.utcnow() + datetime.timedelta(7)).strftime(
                    feconf.DASHBOARD_STATS_DATETIME_STRING_FORMAT))

        # Test to see if last week stats get updated by setting the date to the
        # next week.
        with self.swap(
            user_services, 'get_current_date_as_string',
            _mock_get_date_after_one_week):
            self._run_one_off_job()
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(
            response['last_week_stats']
            [_mock_get_date_after_one_week()]['average_ratings'], 3)

        user_model = user_models.UserStatsModel.get(self.owner_id_1)
        self.assertEqual(user_model.total_plays, 1)
        self.assertEqual(
            user_model.impact_score, self.USER_IMPACT_SCORE_DEFAULT)
        self.assertEqual(user_model.num_ratings, 1)
        self.assertEqual(user_model.average_ratings, 3)

        def _mock_get_last_week_dashboard_stats(user_id):
            """Mocks 'get_last_week_dashboard_stats()' to return more than one
            key-value pair.
            """
            return {
                'date1': {user_id: 'stats1'}, 'date2': {user_id: 'stats2'}
            }

        # 'last_week_stats' is None if 'get_last_week_dashboard_stats()' returns
        # more than one key-value pair.
        with self.swap(
            user_services, 'get_last_week_dashboard_stats',
            _mock_get_last_week_dashboard_stats):
            response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
            self.assertIsNone(response['last_week_stats'])
        self.logout()

    def test_multiple_plays_and_ratings_for_single_exploration(self):
        exploration = self.save_new_default_exploration(
            self.EXP_ID_1, self.owner_id_1, title=self.EXP_TITLE_1)

        self.login(self.OWNER_EMAIL_1)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 1)

        exp_version = self.EXP_DEFAULT_VERSION
        exp_id = self.EXP_ID_1
        state = exploration.init_state_name

        self._record_start(exp_id, exp_version, state)
        self._record_start(exp_id, exp_version, state)
        self._record_start(exp_id, exp_version, state)
        self._record_start(exp_id, exp_version, state)

        self._rate_exploration(exp_id, [3, 4, 5])

        self._run_user_stats_aggregator_job()
        user_model = user_models.UserStatsModel.get(self.owner_id_1)
        self.assertEqual(user_model.total_plays, 4)
        self.assertEqual(
            user_model.impact_score, self.USER_IMPACT_SCORE_DEFAULT)
        self.assertEqual(user_model.num_ratings, 3)
        self.assertEqual(user_model.average_ratings, 4)
        self.logout()

    def test_one_play_and_rating_for_multiple_explorations(self):
        exploration_1 = self.save_new_default_exploration(
            self.EXP_ID_1, self.owner_id_1, title=self.EXP_TITLE_1)

        self.save_new_default_exploration(
            self.EXP_ID_2, self.owner_id_1, title=self.EXP_TITLE_2)

        self.login(self.OWNER_EMAIL_1)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 2)

        exp_version = self.EXP_DEFAULT_VERSION
        exp_id_1 = self.EXP_ID_1
        state_1 = exploration_1.init_state_name

        self._record_start(exp_id_1, exp_version, state_1)

        self._rate_exploration(exp_id_1, [4])

        self._run_user_stats_aggregator_job()
        user_model = user_models.UserStatsModel.get(self.owner_id_1)
        self.assertEqual(user_model.total_plays, 1)
        self.assertEqual(
            user_model.impact_score, self.USER_IMPACT_SCORE_DEFAULT)
        self.assertEqual(user_model.num_ratings, 1)
        self.assertEqual(user_model.average_ratings, 4)
        self.logout()

    def test_multiple_plays_and_ratings_for_multiple_explorations(self):
        exploration_1 = self.save_new_default_exploration(
            self.EXP_ID_1, self.owner_id_1, title=self.EXP_TITLE_1)
        exploration_2 = self.save_new_default_exploration(
            self.EXP_ID_2, self.owner_id_1, title=self.EXP_TITLE_2)

        self.login(self.OWNER_EMAIL_1)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 2)

        exp_version = self.EXP_DEFAULT_VERSION

        exp_id_1 = self.EXP_ID_1
        state_1 = exploration_1.init_state_name
        exp_id_2 = self.EXP_ID_2
        state_2 = exploration_2.init_state_name

        self._record_start(exp_id_1, exp_version, state_1)
        self._record_start(exp_id_2, exp_version, state_2)
        self._record_start(exp_id_2, exp_version, state_2)

        self._rate_exploration(exp_id_1, [4])
        self._rate_exploration(exp_id_2, [3, 3])

        self._run_user_stats_aggregator_job()

        user_model = user_models.UserStatsModel.get(self.owner_id_1)
        self.assertEqual(user_model.total_plays, 3)
        self.assertEqual(
            user_model.impact_score, self.USER_IMPACT_SCORE_DEFAULT)
        self.assertEqual(user_model.num_ratings, 3)
        self.assertEqual(user_model.average_ratings, 10 / 3.0)
        self.logout()

    def test_stats_for_single_exploration_with_multiple_owners(self):
        exploration = self.save_new_default_exploration(
            self.EXP_ID_1, self.owner_id_1, title=self.EXP_TITLE_1)

        rights_manager.assign_role_for_exploration(
            self.owner_1, self.EXP_ID_1, self.owner_id_2,
            rights_manager.ROLE_OWNER)

        self.login(self.OWNER_EMAIL_1)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 1)

        exp_version = self.EXP_DEFAULT_VERSION
        exp_id = self.EXP_ID_1
        state = exploration.init_state_name

        self._record_start(exp_id, exp_version, state)
        self._record_start(exp_id, exp_version, state)

        self._rate_exploration(exp_id, [3, 4, 5])
        self.logout()

        self.login(self.OWNER_EMAIL_2)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 1)

        self._rate_exploration(exp_id, [3, 4, 5])

        self._run_user_stats_aggregator_job()

        user_model_1 = user_models.UserStatsModel.get(
            self.owner_id_1)
        self.assertEqual(user_model_1.total_plays, 2)
        self.assertEqual(
            user_model_1.impact_score, self.USER_IMPACT_SCORE_DEFAULT)
        self.assertEqual(user_model_1.num_ratings, 3)
        self.assertEqual(user_model_1.average_ratings, 4)

        user_model_2 = user_models.UserStatsModel.get(
            self.owner_id_2)
        self.assertEqual(user_model_2.total_plays, 2)
        self.assertEqual(
            user_model_2.impact_score, self.USER_IMPACT_SCORE_DEFAULT)
        self.assertEqual(user_model_2.num_ratings, 3)
        self.assertEqual(user_model_2.average_ratings, 4)
        self.logout()

    def test_stats_for_multiple_explorations_with_multiple_owners(self):
        exploration_1 = self.save_new_default_exploration(
            self.EXP_ID_1, self.owner_id_1, title=self.EXP_TITLE_1)
        exploration_2 = self.save_new_default_exploration(
            self.EXP_ID_2, self.owner_id_1, title=self.EXP_TITLE_2)

        rights_manager.assign_role_for_exploration(
            self.owner_1, self.EXP_ID_1, self.owner_id_2,
            rights_manager.ROLE_OWNER)
        rights_manager.assign_role_for_exploration(
            self.owner_1, self.EXP_ID_2, self.owner_id_2,
            rights_manager.ROLE_OWNER)

        self.login(self.OWNER_EMAIL_2)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 2)

        exp_version = self.EXP_DEFAULT_VERSION

        exp_id_1 = self.EXP_ID_1
        state_1 = exploration_1.init_state_name
        exp_id_2 = self.EXP_ID_2
        state_2 = exploration_2.init_state_name

        self._record_start(exp_id_1, exp_version, state_1)
        self._record_start(exp_id_1, exp_version, state_1)
        self._record_start(exp_id_2, exp_version, state_2)
        self._record_start(exp_id_2, exp_version, state_2)
        self._record_start(exp_id_2, exp_version, state_2)

        self._rate_exploration(exp_id_1, [5, 3])
        self._rate_exploration(exp_id_2, [5, 5])

        self._run_user_stats_aggregator_job()

        expected_results = {
            'total_plays': 5,
            'num_ratings': 4,
            'average_ratings': 18 / 4.0
        }

        user_model_2 = user_models.UserStatsModel.get(self.owner_id_2)
        self.assertEqual(
            user_model_2.total_plays, expected_results['total_plays'])
        self.assertEqual(
            user_model_2.impact_score, self.USER_IMPACT_SCORE_DEFAULT)
        self.assertEqual(
            user_model_2.num_ratings, expected_results['num_ratings'])
        self.assertEqual(
            user_model_2.average_ratings, expected_results['average_ratings'])
        self.logout()

        self.login(self.OWNER_EMAIL_1)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 2)

        user_model_1 = user_models.UserStatsModel.get(self.owner_id_1)
        self.assertEqual(
            user_model_1.total_plays, expected_results['total_plays'])
        self.assertEqual(
            user_model_1.impact_score, self.USER_IMPACT_SCORE_DEFAULT)
        self.assertEqual(
            user_model_1.num_ratings, expected_results['num_ratings'])
        self.assertEqual(
            user_model_1.average_ratings, expected_results['average_ratings'])
        self.logout()

class CreatorDashboardHandlerTests(test_utils.GenericTestBase):

    COLLABORATOR_EMAIL = 'collaborator@example.com'
    COLLABORATOR_USERNAME = 'collaborator'

    OWNER_EMAIL_1 = 'owner1@example.com'
    OWNER_USERNAME_1 = 'owner1'
    OWNER_EMAIL_2 = 'owner2@example.com'
    OWNER_USERNAME_2 = 'owner2'

    EXP_ID = 'exp_id'
    EXP_TITLE = 'Exploration title'
    EXP_ID_1 = 'exp_id_1'
    EXP_TITLE_1 = 'Exploration title 1'
    EXP_ID_2 = 'exp_id_2'
    EXP_TITLE_2 = 'Exploration title 2'
    EXP_ID_3 = 'exp_id_3'
    EXP_TITLE_3 = 'Exploration title 3'

    def setUp(self):
        super(CreatorDashboardHandlerTests, self).setUp()
        self.signup(self.OWNER_EMAIL, self.OWNER_USERNAME)
        self.signup(self.OWNER_EMAIL_1, self.OWNER_USERNAME_1)
        self.signup(self.OWNER_EMAIL_2, self.OWNER_USERNAME_2)
        self.signup(self.COLLABORATOR_EMAIL, self.COLLABORATOR_USERNAME)
        self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME)

        self.owner_id = self.get_user_id_from_email(self.OWNER_EMAIL)
        self.owner_id_1 = self.get_user_id_from_email(self.OWNER_EMAIL_1)
        self.owner_id_2 = self.get_user_id_from_email(self.OWNER_EMAIL_2)
        self.owner = user_services.UserActionsInfo(self.owner_id)
        self.owner_1 = user_services.UserActionsInfo(self.owner_id_1)
        self.collaborator_id = self.get_user_id_from_email(
            self.COLLABORATOR_EMAIL)
        self.viewer_id = self.get_user_id_from_email(self.VIEWER_EMAIL)

    def test_no_explorations(self):
        self.login(self.OWNER_EMAIL)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(response['explorations_list'], [])
        self.logout()

    def test_no_explorations_and_visit_dashboard(self):
        self.login(self.OWNER_EMAIL)
        # Testing that creator only visit dashboard without any exploration
        # created.
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 0)
        self.logout()

    def test_create_single_exploration_and_visit_dashboard(self):
        self.login(self.OWNER_EMAIL)
        self.save_new_default_exploration(
            self.EXP_ID, self.owner_id, title=self.EXP_TITLE)
        # Testing the quantity of exploration created and it should be 1.
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 1)
        self.logout()

    def test_create_two_explorations_delete_one_and_visit_dashboard(self):
        self.login(self.OWNER_EMAIL_1)
        self.save_new_default_exploration(
            self.EXP_ID_1, self.owner_id_1, title=self.EXP_TITLE_1)
        self.save_new_default_exploration(
            self.EXP_ID_2, self.owner_id_1, title=self.EXP_TITLE_2)
        # Testing the quantity of exploration and it should be 2.
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 2)
        exp_services.delete_exploration(self.owner_id_1, self.EXP_ID_1)
        # Testing whether 1 exploration left after deletion of previous one.
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 1)
        self.logout()

    def test_create_multiple_explorations_delete_all_and_visit_dashboard(self):
        self.login(self.OWNER_EMAIL_2)
        self.save_new_default_exploration(
            self.EXP_ID_1, self.owner_id_2, title=self.EXP_TITLE_1)
        self.save_new_default_exploration(
            self.EXP_ID_2, self.owner_id_2, title=self.EXP_TITLE_2)
        self.save_new_default_exploration(
            self.EXP_ID_3, self.owner_id_2, title=self.EXP_TITLE_3)
        # Testing for quantity of explorations to be 3.
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 3)
        # Testing for deletion of all created previously.
        exp_services.delete_exploration(self.owner_id_2, self.EXP_ID_1)
        exp_services.delete_exploration(self.owner_id_2, self.EXP_ID_2)
        exp_services.delete_exploration(self.owner_id_2, self.EXP_ID_3)
        # All explorations have been deleted, so the dashboard query should not
        # load any explorations.
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 0)
        self.logout()

    def test_managers_can_see_explorations(self):
        self.save_new_default_exploration(
            self.EXP_ID, self.owner_id, title=self.EXP_TITLE)
        self.set_admins([self.OWNER_USERNAME])

        self.login(self.OWNER_EMAIL)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 1)
        self.assertEqual(
            response['explorations_list'][0]['status'],
            rights_manager.ACTIVITY_STATUS_PRIVATE)

        rights_manager.publish_exploration(self.owner, self.EXP_ID)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 1)
        self.assertEqual(
            response['explorations_list'][0]['status'],
            rights_manager.ACTIVITY_STATUS_PUBLIC)

        self.logout()

    def test_collaborators_can_see_explorations(self):
        self.save_new_default_exploration(
            self.EXP_ID, self.owner_id, title=self.EXP_TITLE)
        rights_manager.assign_role_for_exploration(
            self.owner, self.EXP_ID, self.collaborator_id,
            rights_manager.ROLE_EDITOR)
        self.set_admins([self.OWNER_USERNAME])

        self.login(self.COLLABORATOR_EMAIL)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 1)
        self.assertEqual(
            response['explorations_list'][0]['status'],
            rights_manager.ACTIVITY_STATUS_PRIVATE)

        rights_manager.publish_exploration(self.owner, self.EXP_ID)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 1)
        self.assertEqual(
            response['explorations_list'][0]['status'],
            rights_manager.ACTIVITY_STATUS_PUBLIC)

        self.logout()

    def test_viewer_cannot_see_explorations(self):
        self.save_new_default_exploration(
            self.EXP_ID, self.owner_id, title=self.EXP_TITLE)
        rights_manager.assign_role_for_exploration(
            self.owner, self.EXP_ID, self.viewer_id,
            rights_manager.ROLE_VIEWER)
        self.set_admins([self.OWNER_USERNAME])

        self.login(self.VIEWER_EMAIL)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(response['explorations_list'], [])

        rights_manager.publish_exploration(self.owner, self.EXP_ID)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(response['explorations_list'], [])

        self.logout()

    def test_can_see_feedback_thread_counts(self):
        self.save_new_default_exploration(
            self.EXP_ID, self.owner_id, title=self.EXP_TITLE)

        self.login(self.OWNER_EMAIL)

        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['explorations_list']), 1)
        self.assertEqual(
            response['explorations_list'][0]['num_open_threads'], 0)
        self.assertEqual(
            response['explorations_list'][0]['num_total_threads'], 0)

        def mock_get_thread_analytics_multi(unused_exploration_ids):
            return [feedback_domain.FeedbackAnalytics(
                feconf.ENTITY_TYPE_EXPLORATION, self.EXP_ID, 2, 3)]

        with self.swap(
            feedback_services, 'get_thread_analytics_multi',
            mock_get_thread_analytics_multi):

            response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
            self.assertEqual(len(response['explorations_list']), 1)
            self.assertEqual(
                response['explorations_list'][0]['num_open_threads'], 2)
            self.assertEqual(
                response['explorations_list'][0]['num_total_threads'], 3)

        self.logout()

    def test_can_see_subscribers(self):
        self.login(self.OWNER_EMAIL)

        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['subscribers_list']), 0)

        # Subscribe to creator.
        subscription_services.subscribe_to_creator(
            self.viewer_id, self.owner_id)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['subscribers_list']), 1)
        self.assertEqual(
            response['subscribers_list'][0]['subscriber_username'],
            self.VIEWER_USERNAME)

        # Unsubscribe from creator.
        subscription_services.unsubscribe_from_creator(
            self.viewer_id, self.owner_id)
        response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
        self.assertEqual(len(response['subscribers_list']), 0)

    def test_get_topic_summary_dicts_with_new_structure_players_enabled(self):
        self.login(self.OWNER_EMAIL)
        with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True):
            response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
            self.assertEqual(len(response['topic_summary_dicts']), 0)
            self.save_new_topic(
                'topic_id', self.owner_id, 'Name', 'Description',
                ['story_id_1', 'story_id_2'], ['story_id_3'],
                ['skill_id_1', 'skill_id_2'], [], 1)
            response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
            self.assertEqual(len(response['topic_summary_dicts']), 1)
            self.assertTrue(isinstance(response['topic_summary_dicts'], list))
            self.assertEqual(response['topic_summary_dicts'][0]['name'], 'Name')
            self.assertEqual(
                response['topic_summary_dicts'][0]['id'], 'topic_id')
        self.logout()

    def test_get_no_topic_summary_dicts_with_new_structure_players_disabled(
            self):
        self.login(self.OWNER_EMAIL)
        with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', False):
            response = self.get_json(feconf.CREATOR_DASHBOARD_DATA_URL)
            self.assertIsNone(response.get('topic_summary_dicts'))
        self.logout()

    def test_can_update_display_preference(self):
        self.login(self.OWNER_EMAIL)
        display_preference = self.get_json(
            feconf.CREATOR_DASHBOARD_DATA_URL)['display_preference']
        self.assertEqual(display_preference, 'card')
        csrf_token = self.get_new_csrf_token()
        self.post_json(
            feconf.CREATOR_DASHBOARD_DATA_URL,
            {'display_preference': 'list'},
            csrf_token=csrf_token)
        display_preference = self.get_json(
            feconf.CREATOR_DASHBOARD_DATA_URL)['display_preference']
        self.assertEqual(display_preference, 'list')
        self.logout()

    def test_can_create_collections(self):
        self.set_admins([self.OWNER_USERNAME])
        self.login(self.OWNER_EMAIL)
        csrf_token = self.get_new_csrf_token()
        collection_id = self.post_json(
            feconf.NEW_COLLECTION_URL, {}, csrf_token=csrf_token)[
                creator_dashboard.COLLECTION_ID_KEY]
        collection = collection_services.get_collection_by_id(collection_id)
        self.assertEqual(collection.id, collection_id)
        self.assertEqual(collection.title, feconf.DEFAULT_COLLECTION_TITLE)
        self.assertEqual(
            collection.objective, feconf.DEFAULT_COLLECTION_CATEGORY)
        self.assertEqual(
            collection.category, feconf.DEFAULT_COLLECTION_OBJECTIVE)
        self.assertEqual(
            collection.language_code, constants.DEFAULT_LANGUAGE_CODE)
        self.logout()

    def test_get_collections_list(self):
        self.set_admins([self.OWNER_USERNAME])
        self.login(self.OWNER_EMAIL)
        collection_list = self.get_json(
            feconf.CREATOR_DASHBOARD_DATA_URL)['collections_list']
        self.assertEqual(collection_list, [])
        self.save_new_default_collection(
            'collection_id', self.owner_id, title='A title',
            objective='An objective', category='A category')
        collection_list = self.get_json(
            feconf.CREATOR_DASHBOARD_DATA_URL)['collections_list']
        self.assertEqual(len(collection_list), 1)
        self.assertEqual(collection_list[0]['id'], 'collection_id')
        self.assertEqual(collection_list[0]['title'], 'A title')
        self.assertEqual(collection_list[0]['objective'], 'An objective')
        self.assertEqual(collection_list[0]['category'], 'A category')
        self.logout()

    def test_get_suggestions_list(self):
        self.login(self.OWNER_EMAIL)
        suggestions = self.get_json(
            feconf.CREATOR_DASHBOARD_DATA_URL)['created_suggestions_list']
        self.assertEqual(suggestions, [])
        change_dict = {
            'cmd': 'edit_state_property',
            'property_name': 'content',
            'state_name': 'Introduction',
            'new_value': ''
        }
        self.save_new_default_exploration('exploration_id', self.owner_id)
        suggestion_services.create_suggestion(
            'edit_exploration_state_content', 'exploration',
            'exploration_id', 1, self.owner_id, change_dict, '', None)
        suggestions = self.get_json(
            feconf.CREATOR_DASHBOARD_DATA_URL)['created_suggestions_list'][0]
        change_dict['old_value'] = {
            'content_id': 'content',
            'html': ''
        }
        self.assertEqual(suggestions['change'], change_dict)
        # Test to check if suggestions populate old value of the change.
        self.assertEqual(
            suggestions['change']['old_value']['content_id'], 'content')
        self.logout()

class NotificationsDashboardHandlerTests(test_utils.GenericTestBase):

    DASHBOARD_DATA_URL = '/notificationsdashboardhandler/data'

    def setUp(self):
        super(NotificationsDashboardHandlerTests, self).setUp()
        self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME)
        self.viewer_id = self.get_user_id_from_email(self.VIEWER_EMAIL)

    def _get_recent_notifications_mock_by_viewer(self, unused_user_id):
        """Returns a single feedback thread by VIEWER_ID."""
        return (
            100000, [{
                'activity_id': 'exp_id',
                'activity_title': 'exp_title',
                'author_id': self.viewer_id,
                'last_updated_ms': 100000,
                'subject': 'Feedback Message Subject',
                'type': feconf.UPDATE_TYPE_FEEDBACK_MESSAGE,
            }])

    def _get_recent_notifications_mock_by_anonymous_user(self, unused_user_id):
        """Returns a single feedback thread by an anonymous user."""
        return (
            200000, [{
                'activity_id': 'exp_id',
                'activity_title': 'exp_title',
                'author_id': None,
                'last_updated_ms': 100000,
                'subject': 'Feedback Message Subject',
                'type': feconf.UPDATE_TYPE_FEEDBACK_MESSAGE,
            }])

    def test_author_ids_are_handled_correctly(self):
        """Test that author ids are converted into author usernames
        and that anonymous authors are handled correctly.
        """
        with self.swap(
            user_jobs_continuous.DashboardRecentUpdatesAggregator,
            'get_recent_notifications',
            self._get_recent_notifications_mock_by_viewer):

            self.login(self.VIEWER_EMAIL)
            response = self.get_json(self.DASHBOARD_DATA_URL)
            self.assertEqual(len(response['recent_notifications']), 1)
            self.assertEqual(
                response['recent_notifications'][0]['author_username'],
                self.VIEWER_USERNAME)
            self.assertNotIn('author_id', response['recent_notifications'][0])

        with self.swap(
            user_jobs_continuous.DashboardRecentUpdatesAggregator,
            'get_recent_notifications',
            self._get_recent_notifications_mock_by_anonymous_user):

            self.login(self.VIEWER_EMAIL)
            response = self.get_json(self.DASHBOARD_DATA_URL)
            self.assertEqual(len(response['recent_notifications']), 1)
            self.assertEqual(
                response['recent_notifications'][0]['author_username'], '')
            self.assertNotIn('author_id', response['recent_notifications'][0])

    def test_get_unseen_notifications_data(self):
        with self.swap(
            user_jobs_continuous.DashboardRecentUpdatesAggregator,
            'get_recent_notifications',
            self._get_recent_notifications_mock_by_anonymous_user):
            self.login(self.VIEWER_EMAIL)
            response = self.get_json('/notificationshandler')
            self.assertEqual(response['num_unseen_notifications'], 1)
            self.logout()

class CreationButtonsTests(test_utils.GenericTestBase):

    def setUp(self):
        super(CreationButtonsTests, self).setUp()
        self.signup(self.EDITOR_EMAIL, self.EDITOR_USERNAME)
        self.signup(self.ADMIN_EMAIL, self.ADMIN_USERNAME)

    def test_new_exploration_ids(self):
        """Test generation of exploration ids."""
        self.login(self.EDITOR_EMAIL)

        csrf_token = self.get_new_csrf_token()
        exp_a_id = self.post_json(
            feconf.NEW_EXPLORATION_URL, {}, csrf_token=csrf_token
        )[creator_dashboard.EXPLORATION_ID_KEY]
        self.assertEqual(len(exp_a_id), 12)

        self.logout()

    def test_can_non_admins_can_not_upload_exploration(self):
        self.login(self.ADMIN_EMAIL)
        csrf_token = self.get_new_csrf_token()

        response = self.post_json(
            feconf.UPLOAD_EXPLORATION_URL, {}, csrf_token=csrf_token,
            expected_status_int=401)
        self.assertEqual(
            response['error'],
            'You do not have credentials to upload exploration.')

        self.logout()

    def test_can_upload_exploration(self):
        with self.swap(constants, 'ALLOW_YAML_FILE_UPLOAD', True):
            self.set_admins([self.ADMIN_USERNAME])
            self.login(self.ADMIN_EMAIL, is_super_admin=True)

            csrf_token = self.get_new_csrf_token()
            explorations_list = self.get_json(
                feconf.CREATOR_DASHBOARD_DATA_URL)['explorations_list']
            self.assertEqual(explorations_list, [])
            exp_a_id = self.post_json(
                '%s?yaml_file=%s' % (
                    feconf.UPLOAD_EXPLORATION_URL,
                    self.SAMPLE_YAML_CONTENT), {},
                csrf_token=csrf_token)[creator_dashboard.EXPLORATION_ID_KEY]
            explorations_list = self.get_json(
                feconf.CREATOR_DASHBOARD_DATA_URL)['explorations_list']
            exploration = exp_fetchers.get_exploration_by_id(exp_a_id)
            self.assertEqual(explorations_list[0]['id'], exp_a_id)
            self.assertEqual(exploration.to_yaml(), self.SAMPLE_YAML_CONTENT)
            self.logout()

    def test_can_not_upload_exploration_when_server_does_not_allow_file_upload(
            self):
        self.set_admins([self.ADMIN_USERNAME])
        self.login(self.ADMIN_EMAIL, is_super_admin=True)
        csrf_token = self.get_new_csrf_token()
        self.post_json(
            '%s?yaml_file=%s' % (
                feconf.UPLOAD_EXPLORATION_URL,
                self.SAMPLE_YAML_CONTENT), {}, csrf_token=csrf_token,
            expected_status_int=400)

        self.logout()


text:
#ifndef WIN32
#include <strings.h>
#endif
#include "parse_primitives.h"
#include <iostream>

using namespace std;

void tokenize(char delim, substring s, v_array<substring>& ret, bool allow_empty)
{
  ret.erase();
  char *last = s.begin;
  for (; s.begin != s.end; s.begin++) {
    if (*s.begin == delim) {
      if (allow_empty || (s.begin != last))
	{
	  substring temp = {last, s.begin};
	  ret.push_back(temp);
	}
      last = s.begin+1;
    }
  }
  if (allow_empty || (s.begin != last))
    {
      substring final = {last, s.begin};
      ret.push_back(final);
    }
}


text:
@implementation Configuration

static NSMutableDictionary *config;

+ (void)initialize
{
    config = [NSMutableDictionary dictionary];
    [self addConfig:@"MBALibFramework.bundle/mbalib-default.cfg"];
}

+ (void)addConfig:(NSString *)file
{
    NSURL *url = [[NSBundle mainBundle] URLForResource:file withExtension:nil];

    NSString *content = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
    NSArray *lines = [content componentsSeparatedByString:@"\n"];

    for (NSString *line in lines)
    {
        NSString *temp = [line stringByReplacingOccurrencesOfString:[StringUtils blank] withString:[StringUtils EMPTY]];
        if([StringUtils isEmpty:temp] || [temp hasPrefix:@"#"] || [temp hasPrefix:@"//"]) continue;
        if([temp containsString:@"="])
        {
            NSRange range = [temp rangeOfString:@"="];
            NSString *key = [temp substringToIndex:range.location];
            NSString *value = [temp substringFromIndex:range.location + 1];
            [config setObject:value forKey:key];
        }

    }

}

+ (NSString *)getString:(NSString *)key
{
    return [self getString:key def:[StringUtils EMPTY]];
}

+ (NSString *)getString:(NSString *)key def:(NSString *)def
{
    NSString *value = [config objectForKey:key];
    return [StringUtils isEmpty:value] ? def : value;
}

@end


text:
layout: post
title: "Speaking slowly 3/7"
date: 2015-07-07 21:35:26 +1000
summary:
categories: [slow-speaking,daygame]
---
Strange day today. I spoke only to 3 girls. I'm having really good time with making girls feel sexy BUT my ego is badass motherfucker. It just controlls me way too much. I'm approaching only 2 types of girls now 100% my type and really approachable (smiling, walking slowly, looking friendly).

There is a whole world of oportunity that I'm missing by doing this and I was in that world before. I guess that being so long without tangible success makes my confidence little bit more fragile than I would wish.

I read a nice view on this from Liam McRae in his book Rapid Escalation:

> Part of my success is that I'm open to the negative reactions as much as the positive ones. I accept it all as part of the process of putting myself out there.

I need to adopt this mindset and the hell gates will open. So far I'm happy with liking approaching girls again thanks to I'm going to make her feel sexy and make me feel lik a man approach.

Need a medic
------------
I got a number on a stunning medicine student. Toll blonde. I didn't speak as slowly as I would wish still but it's much slower than few last weeks. I was keeping strong eye contact the whole time but I forgot to hold her hand for longer time. That clearly shows that I didn't have clear "fucking" intent. I fix that next time.


text:
from __future__ import absolute_import, division, print_function

from twisted.application.internet import StreamServerEndpointService
from twisted.application.service import MultiService
from twisted.internet.endpoints import serverFromString
from twisted.python import usage
from twisted.internet.protocol import Factory, Protocol, connectionDone
from twisted.python.filepath import FilePath
from twisted.web.resource import ForbiddenResource, Resource
from twisted.web.server import Site
from twisted.web.static import File

from txsockjs.factory import SockJSResource

from .protocol import DaneDoctorProtocol

class Options(usage.Options):
    pass

class NoListDirFile(File):
    """
    Behaves like Twisted's File but refuses to list directories.
    """
    def directoryListing(self):
        return ForbiddenResource(message=b'Nope.')

class DaneDoctorService(MultiService, object):
    def __init__(self, reactor, config):
        MultiService.__init__(self)
        self._config = config
        self._reactor = reactor

    def startService(self):
        MultiService.startService(self)

        staticPath = FilePath(__file__).sibling("static")
        root = NoListDirFile(staticPath.path)
        root.putChild('api', SockJSResource(
            Factory.forProtocol(DaneDoctorProtocol))
        )

        webService = StreamServerEndpointService(
            serverFromString(self._reactor, "tcp:8080"),
            Site(root)
        )
        webService.setServiceParent(self)

def makeService(options):
    from twisted.internet import reactor

    # with open(options[b'config']) as f:
    #     config = yaml.safe_load(f)
    config = {}

    return DaneDoctorService(reactor, config)


text:
package edu.isi.wings.portal.controllers;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Properties;

import org.apache.commons.io.FileUtils;
import edu.isi.wings.catalog.provenance.ProvenanceFactory;
import edu.isi.wings.catalog.provenance.api.ProvenanceAPI;
import edu.isi.wings.portal.classes.config.Config;
import edu.isi.wings.portal.classes.JsonHandler;
import edu.isi.wings.portal.classes.users.User;
import edu.isi.wings.portal.classes.users.UsersDB;

import com.google.gson.Gson;

@SuppressWarnings("unused")
public class UserController {
  public Config config;
  public Properties props;
  public Gson json;
  public UsersDB api;

  public UserController(Config config) {
    this.config = config;
    json = JsonHandler.createDataGson();
    this.props = config.getProperties();
    this.api = new UsersDB();
  }

  public String getUserJSON(String userid) {
    try {
      User user = api.getUser(userid);
      if(user == null)
        return null;

      if(user.getPassword() != null)
        user.setPassword(user.getPassword().replaceAll(".", "*"));
      return json.toJson(user);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  public boolean saveUserJSON(String userid, String uservals_json) {
    if (this.api == null)
      return false;

    try {
      User user = json.fromJson(uservals_json, User.class);
      // Can only save your own information, or if the viewer is admin
      if(!this.config.getViewerId().equals(user.getId())
          && !this.config.isAdminViewer())
        return false;

      // If the password is all "*" (i.e. shadowed), then set to null
      if(user.getPassword().matches("\\**"))
        user.setPassword(null);

      // A non-admin user cannot set itself to be admin
      if(!config.isAdminViewer())
        user.setAdmin(false);

      return this.api.saveUser(user)
          && this.api.save();

    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  public boolean addUser(String userid) {
    try {
      User user = api.getUser(userid);
      if(user != null)
        return false;
      return this.api.addUser(userid, null, null)
          && this.api.save();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }

  public boolean removeUser(String userid) {
    try {
      if(config.getViewerId().equals(userid))
        return false;
      User user = api.getUser(userid);
      if(user == null)
        return false;

      if(this.api.removeUser(userid)) {
        // Remove user domains
        config.setUserId(userid);
        config.setViewerId(userid);
        DomainController dc = new DomainController(this.config);
        for(String domain : dc.getDomainsList()) {
          dc.deleteDomain(domain);
        }
        // Remove user directory
        FileUtils.deleteDirectory(new File(config.getUserDir()));

        ProvenanceAPI prov = ProvenanceFactory.getAPI(config.getProperties());
        prov.removeUser(userid);
        prov.save();

        return this.api.save();
      }
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="edu.umn.paull011.evolveworkoutlogger.activities.ComponentTesting">

    <include
        layout="@layout/component_set_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/header"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true" />

    <include
        layout="@layout/component_set"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_below="@id/header"/>

</RelativeLayout>


text:
require 'optparse'
require 'rails/test_help'
require 'rails/performance_test_help'

ENV["BENCHMARK_TESTS"] = '1'
require 'active_support/testing/performance'

def options
  options = {}
  defaults = ActiveSupport::Testing::Performance::DEFAULTS

  OptionParser.new do |opt|
    opt.banner = "Usage: rails benchmarker 'Ruby.code' 'Ruby.more_code' ... [OPTS]"
    opt.on('-r', '--runs N', Numeric, 'Number of runs.', "Default: #{defaults[:runs]}") { |r| options[:runs] = r }
    opt.on('-o', '--output PATH', String, 'Directory to use when writing the results.', "Default: #{defaults[:output]}") { |o| options[:output] = o }
    opt.on('-m', '--metrics a,b,c', Array, 'Metrics to use.', "Default: #{defaults[:metrics].join(",")}") { |m| options[:metrics] = m.map(&:to_sym) }
    opt.parse!(ARGV)
  end

  options
end

class BenchmarkerTest < ActionDispatch::PerformanceTest #:nodoc:
  self.profile_options = options

  ARGV.each do |expression|
    eval <<-RUBY
      def test_#{expression.parameterize('_')}
        #{expression}
      end
    RUBY
  end
  ARGV.clear
end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.compute.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Key Vault Key Url to be used for server side encryption of Managed Disks and Snapshots. */
@Fluent
public final class KeyForDiskEncryptionSet {
    /*
     * Resource id of the KeyVault containing the key or secret. This property is optional and cannot be used if the
     * KeyVault subscription is not the same as the Disk Encryption Set subscription.
     */
    @JsonProperty(value = "sourceVault")
    private SourceVault sourceVault;

    /*
     * Fully versioned Key Url pointing to a key in KeyVault. Version segment of the Url is required regardless of
     * rotationToLatestKeyVersionEnabled value.
     */
    @JsonProperty(value = "keyUrl", required = true)
    private String keyUrl;

    /** Creates an instance of KeyForDiskEncryptionSet class. */
    public KeyForDiskEncryptionSet() {
    }

    /**
     * Get the sourceVault property: Resource id of the KeyVault containing the key or secret. This property is optional
     * and cannot be used if the KeyVault subscription is not the same as the Disk Encryption Set subscription.
     *
     * @return the sourceVault value.
     */
    public SourceVault sourceVault() {
        return this.sourceVault;
    }

    /**
     * Set the sourceVault property: Resource id of the KeyVault containing the key or secret. This property is optional
     * and cannot be used if the KeyVault subscription is not the same as the Disk Encryption Set subscription.
     *
     * @param sourceVault the sourceVault value to set.
     * @return the KeyForDiskEncryptionSet object itself.
     */
    public KeyForDiskEncryptionSet withSourceVault(SourceVault sourceVault) {
        this.sourceVault = sourceVault;
        return this;
    }

    /**
     * Get the keyUrl property: Fully versioned Key Url pointing to a key in KeyVault. Version segment of the Url is
     * required regardless of rotationToLatestKeyVersionEnabled value.
     *
     * @return the keyUrl value.
     */
    public String keyUrl() {
        return this.keyUrl;
    }

    /**
     * Set the keyUrl property: Fully versioned Key Url pointing to a key in KeyVault. Version segment of the Url is
     * required regardless of rotationToLatestKeyVersionEnabled value.
     *
     * @param keyUrl the keyUrl value to set.
     * @return the KeyForDiskEncryptionSet object itself.
     */
    public KeyForDiskEncryptionSet withKeyUrl(String keyUrl) {
        this.keyUrl = keyUrl;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (sourceVault() != null) {
            sourceVault().validate();
        }
        if (keyUrl() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException("Missing required property keyUrl in model KeyForDiskEncryptionSet"));
        }
    }

    private static final ClientLogger LOGGER = new ClientLogger(KeyForDiskEncryptionSet.class);
}


text:
package java.net;

/**
 * This class represents a datagram packet which contains data either to be sent
 * or received through a {@code DatagramSocket}. It holds additional information
 * such as its source or destination host.
 *
 * @see DatagramSocket
 */
public final class DatagramPacket {

    byte[] data;

    /**
     * Length of the data to be sent or size of data that was received via
     * DatagramSocket#receive() method call.
     */
    int length;

    /**
     * Size of internal buffer that is used to store received data. Should be
     * greater or equal to "length" field.
     */
    int capacity;

    InetAddress address;

    int port = -1; // The default port number is -1

    int offset = 0;

    /**
     * Constructs a new {@code DatagramPacket} object to receive data up to
     * {@code length} bytes.
     *
     * @param data
     *            a byte array to store the read characters.
     * @param length
     *            the length of the data buffer.
     */
    public DatagramPacket(byte[] data, int length) {
        this(data, 0, length);
    }

    /**
     * Constructs a new {@code DatagramPacket} object to receive data up to
     * {@code length} bytes with a specified buffer offset.
     *
     * @param data
     *            a byte array to store the read characters.
     * @param offset
     *            the offset of the byte array where the bytes is written.
     * @param length
     *            the length of the data.
     */
    public DatagramPacket(byte[] data, int offset, int length) {
        super();
        setData(data, offset, length);
    }

    /**
     * Constructs a new {@code DatagramPacket} object to send data to the port
     * {@code aPort} of the address {@code host}. The {@code length} must be
     * lesser than or equal to the size of {@code data}. The first {@code
     * length} bytes from the byte array position {@code offset} are sent.
     *
     * @param data
     *            a byte array which stores the characters to be sent.
     * @param offset
     *            the offset of {@code data} where to read from.
     * @param length
     *            the length of data.
     * @param host
     *            the address of the target host.
     * @param aPort
     *            the port of the target host.
     */
    public DatagramPacket(byte[] data, int offset, int length,
            InetAddress host, int aPort) {
        this(data, offset, length);
        setPort(aPort);
        address = host;
    }

    /**
     * Constructs a new {@code DatagramPacket} object to send data to the port
     * {@code aPort} of the address {@code host}. The {@code length} must be
     * lesser than or equal to the size of {@code data}. The first {@code
     * length} bytes are sent.
     *
     * @param data
     *            a byte array which stores the characters to be sent.
     * @param length
     *            the length of data.
     * @param host
     *            the address of the target host.
     * @param port
     *            the port of the target host.
     */
    public DatagramPacket(byte[] data, int length, InetAddress host, int port) {
        this(data, 0, length, host, port);
    }

    /**
     * Gets the sender or destination IP address of this datagram packet.
     *
     * @return the address from where the datagram was received or to which it
     *         is sent.
     */
    public synchronized InetAddress getAddress() {
        return address;
    }

    /**
     * Gets the data of this datagram packet.
     *
     * @return the received data or the data to be sent.
     */
    public synchronized byte[] getData() {
        return data;
    }

    /**
     * Gets the length of the data stored in this datagram packet.
     *
     * @return the length of the received data or the data to be sent.
     */
    public synchronized int getLength() {
        return length;
    }

    /**
     * Gets the offset of the data stored in this datagram packet.
     *
     * @return the position of the received data or the data to be sent.
     */
    public synchronized int getOffset() {
        return offset;
    }

    /**
     * Gets the port number of the target or sender host of this datagram
     * packet.
     *
     * @return the port number of the origin or target host.
     */
    public synchronized int getPort() {
        return port;
    }

    /**
     * Sets the IP address of the target host.
     *
     * @param addr
     *            the target host address.
     */
    public synchronized void setAddress(InetAddress addr) {
        address = addr;
    }

    /**
     * Sets the data buffer for this datagram packet.
     *
     * @param buf
     *            the buffer to store the data.
     * @param anOffset
     *            the buffer offset where the data is stored.
     * @param aLength
     *            the length of the data to be sent or the length of buffer to
     *            store the received data.
     */
    public synchronized void setData(byte[] buf, int anOffset, int aLength) {
        if (0 > anOffset || anOffset > buf.length || 0 > aLength
                || aLength > buf.length - anOffset) {
            throw new IllegalArgumentException();
        }
        data = buf;
        offset = anOffset;
        length = aLength;
        capacity = aLength;
    }

    /**
     * Sets the data buffer for this datagram packet. The length of the datagram
     * packet is set to the buffer length.
     *
     * @param buf
     *            the buffer to store the data.
     */
    public synchronized void setData(byte[] buf) {
        length = buf.length; // This will check for null
        capacity = buf.length;
        data = buf;
        offset = 0;
    }

    /**
     * Gets the current capacity value.
     *
     * @return the current capacity value
     */
    synchronized int getCapacity() {
        return capacity;
    }

    /**
     * Sets the length of the datagram packet. This length plus the offset must
     * be lesser than or equal to the buffer size.
     *
     * @param len
     *            the length of this datagram packet.
     */
    public synchronized void setLength(int len) {
        if (0 > len || offset + len > data.length) {
            throw new IndexOutOfBoundsException();
        }
        length = len;
        capacity = len;
    }

    /**
     * An alternative to {@link #setLength(int)}, that doesn't reset the {@link #capacity}
     * field.
     *
     * @param len the length of this datagram packet
     */
    synchronized void setLengthOnly(int len) {
        if (0 > len || offset + len > data.length) {
            throw new IndexOutOfBoundsException();
        }
        length = len;
    }

    /**
     * Sets the port number of the target host of this datagram packet.
     *
     * @param aPort
     *            the target host port number.
     */
    public synchronized void setPort(int aPort) {
        if (aPort < 0 || aPort > 65535) {
            throw new IllegalArgumentException("Port out of range: " + aPort);
        }
        port = aPort;
    }

    /**
     * Constructs a new {@code DatagramPacket} object to send data to the
     * address {@code sockAddr}. The {@code length} must be lesser than or equal
     * to the size of {@code data}. The first {@code length} bytes of the data
     * are sent.
     *
     * @param data
     *            the byte array to store the data.
     * @param length
     *            the length of the data.
     * @param sockAddr
     *            the target host address and port.
     * @throws SocketException
     *             if an error in the underlying protocol occurs.
     */
    public DatagramPacket(byte[] data, int length, SocketAddress sockAddr)
            throws SocketException {
        this(data, 0, length);
        setSocketAddress(sockAddr);
    }

    /**
     * Constructs a new {@code DatagramPacket} object to send data to the
     * address {@code sockAddr}. The {@code length} must be lesser than or equal
     * to the size of {@code data}. The first {@code length} bytes of the data
     * are sent.
     *
     * @param data
     *            the byte array to store the data.
     * @param offset
     *            the offset of the data.
     * @param length
     *            the length of the data.
     * @param sockAddr
     *            the target host address and port.
     * @throws SocketException
     *             if an error in the underlying protocol occurs.
     */
    public DatagramPacket(byte[] data, int offset, int length,
            SocketAddress sockAddr) throws SocketException {
        this(data, offset, length);
        setSocketAddress(sockAddr);
    }

    /**
     * Gets the host address and the port to which this datagram packet is sent
     * as a {@code SocketAddress} object.
     *
     * @return the SocketAddress of the target host.
     */
    public synchronized SocketAddress getSocketAddress() {
        return new InetSocketAddress(getAddress(), getPort());
    }

    /**
     * Sets the {@code SocketAddress} for this datagram packet.
     *
     * @param sockAddr
     *            the SocketAddress of the target host.
     */
    public synchronized void setSocketAddress(SocketAddress sockAddr) {
        if (!(sockAddr instanceof InetSocketAddress)) {
            throw new IllegalArgumentException("Socket address not an InetSocketAddress: " +
                    (sockAddr == null ? null : sockAddr.getClass()));
        }
        InetSocketAddress inetAddr = (InetSocketAddress) sockAddr;
        port = inetAddr.getPort();
        address = inetAddr.getAddress();
    }
}


text:
	core::logging::instance()->dispatch(\
	core::logging::ILog::Verbose,\
	core::str::format(__VA_ARGS__),\
	__FUNCTION__,\
	__FILE__,\
	__LINE__)

#define LOGW(...) \
	core::logging::instance()->dispatch(\
	core::logging::ILog::Warning,\
	core::str::format(__VA_ARGS__),\
	__FUNCTION__,\
	__FILE__,\
	__LINE__)

#define LOGE(...) \
	core::logging::instance()->dispatch(\
	core::logging::ILog::Error,\
	core::str::format(__VA_ARGS__),\
	__FUNCTION__,\
	__FILE__,\
	__LINE__)

#include <core/interface.h>

namespace core
{
	namespace logging
	{
		struct Handler
		{
			// called when the log should open
			// expects 0 on failure; 1 on success
			int (*open)(Handler* handler);

			// called when the log should close
			void (*close)(Handler* handler);

			// called when a log message is received
			void (*message)(struct Handler* handler, const char* message, const char* filename, const char* function, int line, int type);

			// userdata
			void* userdata;

			Handler() : open(0), close(0), message(0), userdata(0) {}
		};

		class ILog
		{
		public:
			enum MessageType
			{
				Invalid,
				Verbose,
				Warning,
				Error
			};

			enum class Flags
			{
				Uninitialized,
				Initialized
			};

		public:
			virtual ~ILog() {}

			/// @brief Dispatches a message to all handlers
			virtual void dispatch(ILog::MessageType type, const char* message, const char* function, const char* filename, int linenumber) = 0;

			/// @brief Add a log handler for dispatch
			/// @param handler Handler struct with pointers to functions
			virtual void add_handler(Handler* handler) = 0;

			/// @brief Remove a log handler
			/// @param handler Handler previously passed to add_handler
			virtual void remove_handler(Handler* handler) = 0;

			/// @brief Open the log handlers
			/// @returns The total number of successfully opened handlers
//			virtual uint32_t startup() = 0;

			/// @brief Shutdown the log handlers
//			virtual void shutdown() = 0;
		}; // ILog

		GEMINI_DECLARE_INTERFACE(ILog);
	} // namespace logging
} // namespace core


text:
require 'advent_of_code2017/day04'

RSpec.describe AdventOfCode2017::Day04 do
  describe '.solve_part_one' do
    subject { described_class.solve_part_one(input) }

    let(:input) do
      <<~INPUT
        aa bb cc dd ee
        aa bb cc dd aa
        aa bb cc dd aaa
      INPUT
    end

    it { is_expected.to eq(2) }
  end

  describe '.solve_part_two' do
    subject { described_class.solve_part_two(input) }

    let(:input) do
      <<~INPUT
        abcde fghij
        abcde xyz ecdab
        a ab abc abd abf abj
        iiii oiii ooii oooi oooo
        oiii ioii iioi iiio
      INPUT
    end

    it { is_expected.to eq(3) }
  end
end


text:
import _ from 'lodash'
import { isSingleDayTourType, isMultiDayTourType } from '@/transforms/tour'
import { commissionCalcMethod } from '@/constants/commission'

export const getFeeDetails = order => {
  const data = []
  if (order) {
    if (isSingleDayTourType(order.tourSchedule.tour)) {
      data.push({
        item: '基础团费',
        unitPrice: order.noRoomPrice,
        quantity: order.noRoomAmount
      })
    }

    if (isMultiDayTourType(order.tourSchedule.tour)) {
      if (order.singleRoomAmount > 0) {
        data.push({
          item: '单人房',
          unitPrice: order.singleRoomPrice,
          quantity: order.singleRoomAmount
        })
      }

      if (order.doubleRoomAmount > 0) {
        data.push({
          item: '双人房',
          unitPrice: order.doubleRoomPrice,
          quantity: order.doubleRoomAmount
        })
      }

      if (order.shareRoomAmount > 0) {
        data.push({
          item: '配房',
          unitPrice: order.shareRoomPrice,
          quantity: order.shareRoomAmount
        })
      }
    }

    data.push(
      ..._.map(order.services, s => {
        return {
          item: s.name,
          unitPrice: s.price,
          quantity: s.quantity
        }
      })
    )
  }

  return data
}

export const getTotalFee = order => {
  let totalFee = 0

  if (isSingleDayTourType(order.tourSchedule.tour)) {
    totalFee += order.noRoomPrice * order.noRoomAmount
  } else if (isMultiDayTourType(order.tourSchedule.tour)) {
    totalFee += order.singleRoomPrice * order.singleRoomAmount
    totalFee += order.doubleRoomPrice * order.doubleRoomAmount
    totalFee += order.shareRoomPrice * order.shareRoomAmount
  }

  _.forEach(order.services, s => {
    totalFee += s.price * s.quantity
  })

  return totalFee
}

export const getCommissionDetails = order => {
  const data = []

  if (order) {
    const calc = function (price) {
      const factor = order.commissionCalcValue
      if (order.commissionCalcValue === 0) {
        return 0
      }

      switch (order.commissionCalcMethod) {
        case commissionCalcMethod.PERCENTAGE:
          return price * factor / 100
        case commissionCalcMethod.QUOTA:
          return factor
        default:
          return 0
      }
    }

    if (isSingleDayTourType(order.tourSchedule.tour)) {
      data.push({
        item: '基础团费 - 佣金',
        unitPrice: calc(order.noRoomPrice),
        quantity: order.noRoomAmount,
        isCommission: true
      })
    }

    if (isMultiDayTourType(order.tourSchedule.tour)) {
      if (order.singleRoomAmount > 0) {
        data.push({
          item: '单人房 - 佣金',
          unitPrice: calc(order.singleRoomPrice),
          quantity: order.singleRoomAmount,
          isCommission: true
        })
      }

      if (order.doubleRoomAmount > 0) {
        data.push({
          item: '双人房 - 佣金',
          unitPrice: calc(order.doubleRoomPrice),
          quantity: order.doubleRoomAmount,
          isCommission: true
        })
      }

      if (order.shareRoomAmount > 0) {
        data.push({
          item: '配房基础费用 - 佣金',
          unitPrice: calc(order.shareRoomBasePrice),
          quantity: order.shareRoomAmount,
          isCommission: true
        })
      }
    }
  }

  return data
}

export const getTotalCommission = order => {
  const details = getCommissionDetails(order)
  return _.reduce(details, (total, detail) => (total += detail.unitPrice * detail.quantity), 0)
}


text:
<?php declare(strict_types=1);

namespace CleverAge\ProcessBundle\Task\File\Csv;

use CleverAge\ProcessBundle\Filesystem\CsvFile;
use CleverAge\ProcessBundle\Model\ProcessState;
use Symfony\Component\OptionsResolver\Exception\AccessException;
use Symfony\Component\OptionsResolver\Exception\ExceptionInterface;
use Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Reads the file path from configuration and iterates over it
 * Ignores any input
 *
 * @author Valentin Clavreul <vclavreul@clever-age.com>
 * @author Vincent Chalnot <vchalnot@clever-age.com>
 */
abstract class AbstractCsvTask extends AbstractCsvResourceTask
{
    /**
     * @param ProcessState $state
     *
     * @throws \UnexpectedValueException
     * @throws ExceptionInterface
     * @throws \RuntimeException
     */
    protected function initFile(ProcessState $state)
    {
        if ($this->csv) {
            return;
        }
        $options = $this->getOptions($state);
        $headers = $this->getHeaders($state, $options);
        $this->csv = new CsvFile(
            $options['file_path'],
            $options['delimiter'],
            $options['enclosure'],
            $options['escape'],
            $headers,
            $options['mode']
        );
    }

    /**
     * @param OptionsResolver $resolver
     *
     * @throws AccessException
     * @throws UndefinedOptionsException
     */
    protected function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);
        $resolver->setRequired(
            [
                'file_path',
            ]
        );
        $resolver->setAllowedTypes('file_path', ['string']);
        $resolver->setDefaults(
            [
                'mode' => 'rb',
            ]
        );
        $resolver->setAllowedTypes('mode', ['string']);
    }
}


text:
angular.module('dotjem.blog.portfolio', ['dotjem.routing', 'dotjem.blog.core']);

angular.module('dotjem.blog.portfolio').config([
    '$stateProvider', '$moduleProvider',
    function ($stateProvider, $moduleProvider) {
        $moduleProvider.register('portfolio', { title: 'Portfolio', root: '/portfolio' });

        $stateProvider.state('portfolio', {
            route: '/portfolio',
            views: {
                'root': { template: 'modules/portfolio/tpl/portfolio.html' }
            }
        });
    }]);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Trulioo.Client.V1.Model.BusinessSearch
{
    /// <summary>
    /// Name value pairs of address found from business search
    /// </summary>
    public class SearchResultAddress
    {
        /// <summary>
        /// Flat/Unit/Apartment number of address
        /// </summary>
        public string UnitNumber { get; set; }
        /// <summary>
        /// House / Civic / Building number of address
        /// </summary>
        public string BuildingNumber { get; set; }
        /// <summary>
        /// 	Name of building
        /// </summary>
        public string BuildingName { get; set; }
        /// <summary>
        /// Street name
        /// </summary>
        public string StreetName { get; set; }
        /// <summary>
        /// 	Street type of address (Typically St, Rd etc)
        /// </summary>
        public string StreetType { get; set; }
        /// <summary>
        /// City
        /// </summary>
        public string City { get; set; }
        /// <summary>
        /// Suburb / Subdivision / Municipality
        /// </summary>
        public string Suburb { get; set; }
        /// <summary>
        /// State or province of address. US sources expect 2 characters. Australian sources expect 2 or 3 characters.
        /// </summary>
        public string StateProvinceCode { get; set; }
        /// <summary>
        /// ZIP Code or Postal Code
        /// </summary>
        public string PostalCode { get; set; }
        /// <summary>
        /// Address Type
        /// </summary>
        public string AddressType { get; set; }
        /// <summary>
        /// Address1
        /// </summary>
        public string Address1 { get; set; }
        /// <summary>
        /// State or province of address
        /// </summary>
        public string StateProvince { get; set; }
    }
}


text:
using Alphaleonis.Vsx;
using Microsoft.CodeAnalysis;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;

namespace Alphaleonis.EventSourceGenerator
{
   partial class EventSourceGenerator
   {
      private class EventSourceTypeInfo
      {
         /// <summary>
         /// Initializes a new instance of the <see cref="EventSourceTypeInfo"/> class.
         /// </summary>
         public EventSourceTypeInfo(SemanticModel semanticModel, INamedTypeSymbol eventSourceClass)
         {
            if (eventSourceClass == null)
               throw new ArgumentNullException("eventSourceClass", "eventSourceClass is null.");

            INamedTypeSymbol eventSourceAttributeType = eventSourceClass.ContainingNamespace.GetTypeMembers("EventSourceAttribute", 0).Single();
            INamedTypeSymbol eventAttributeType = eventSourceClass.ContainingNamespace.GetTypeMembers("EventAttribute", 0).Single();

            EventSourceClass = eventSourceClass;
            EventAttributeType = eventAttributeType;
            EventSourceAttributeType = eventSourceAttributeType;
            EventSourceNamespace = eventSourceClass.ContainingNamespace;
            EventKeywordsType = semanticModel.Compilation.GetTypeByMetadataName(EventSourceNamespace.GetFullName() + ".EventKeywords");
            EventOpcodeType = semanticModel.Compilation.GetTypeByMetadataName(EventSourceNamespace.GetFullName() + ".EventOpcode");
            EventTaskType = semanticModel.Compilation.GetTypeByMetadataName(EventSourceNamespace.GetFullName() + ".EventTask");

            WriteEventOverloads = eventSourceClass.GetAllMembers()
               .OfType<IMethodSymbol>()
               .Where(method => method.Name.Equals("WriteEvent"))
               // Only add methods that have at least one parameter, and the first parameter is of type Int32.
               .Where(method => method.Parameters.Length >= 1 && method.Parameters[0].Type.SpecialType == SpecialType.System_Int32)
               // Only add methods that do not contain 'object' parameters or params parameters.
               .Where(method => method.Parameters.All(parameter => !parameter.IsParams && parameter.Type.SpecialType != SpecialType.System_Object))
               // Skip the first parameter, which should be (int eventId)
               .Select(method => method.Parameters.Skip(1).ToImmutableArray())
               .ToImmutableArray();
         }

         public ImmutableArray<ImmutableArray<IParameterSymbol>> WriteEventOverloads { get; }
         public INamedTypeSymbol EventSourceClass { get; }
         public INamedTypeSymbol EventAttributeType { get; }
         public INamedTypeSymbol EventSourceAttributeType { get; }
         public INamespaceSymbol EventSourceNamespace { get; }
         public INamedTypeSymbol EventKeywordsType { get; }
         public INamedTypeSymbol EventOpcodeType { get; }
         public INamedTypeSymbol EventTaskType { get; }
      }
   }
}


text:
/**
 * create an html partial
 */
var getProperty = require('../../lib/getProperty'),
    _ = require('underscore');

module.exports = function (Handlebars, getTemplate) {
  return function (templateName, options) {
    var data, html, context, template;

    template = getTemplate(templateName);
    context = options.hash || {};

    // First try to use Handlebars' hash arguments as the context for the
    // partial, if present.
    //
    // ex: `{{partial "users/photo" user=user}}`
    if (_.isEmpty(context)) {
      // If there are no hash arguments given, then inherit the parent context.
      //
      // ex: `{{partial "users/photo"}}`
      context = this;
    } else {
      // If a hash argument is given with key `context`, then use that as the context.
      //
      // ex: `{{partial "users/photo" context=user}}`
      if (context.hasOwnProperty('context')) {
        context = context.context;
      }
    }

    context = _.clone(context);
    context._app = getProperty('_app', this, options);
    if (_.isFunction(options.fn)) {
      context._block = options.fn(context);
    }

    html = template(context);
    return new Handlebars.SafeString(html);
  };
};