text:
function [d imFnames]=pipes5()
full_fname = 'pipes5.mat';
fname = '/home/drc/code/crazyflie-tools/logs/cf2/tests0423/pipes5.mat';
if (exist(full_fname,'file'))
    filename = full_fname;
else
    filename = fname;
end
d = load(filename);

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

// System.IAsyncResult
struct IAsyncResult_t2754620036;
// System.AsyncCallback
struct AsyncCallback_t1369114871;
// System.Object
struct Il2CppObject;

#include "mscorlib_System_MulticastDelegate3389745971.h"
#include "mscorlib_System_Void2863195528.h"
#include "UnityEngine_UnityEngine_Vector24282066565.h"

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// UnityEngine.Events.UnityAction`1<UnityEngine.Vector2>
struct  UnityAction_1_t4176246568  : public MulticastDelegate_t3389745971
{
public:

public:
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
class Chat {
    static sendMessage (socket, room, text) {
        const message = {
            room: room,
            text: text
        };
        socket.emit('message', message);
    };

    static changeRoom (socket, room) {
        socket.emit('join', {
            newRoom: room
        });
    };

    static processCommand (socket, command) {
        let words = command.split(' ');
        command = words[0]
            .substring(1, words[0].length)
            .toLowerCase();
        let message = false;

        switch(command) {
            case 'join':
                words.shift();
                let room = words.join(' ');
                this.changeRoom(socket, room);
                break;
            case 'nick':
                words.shift();
                let name = words.join(' ');
                socket.emit('nameAttempt', name);
                break;
            default:
                message = 'Unknown command.';
                break;
        }

        return message;
    };
}

export default Chat;


text:
'use strict';

const moment = require('moment');

module.exports = function(date, format) {
    return moment(date).format(format);
}


text:
<?php

class SV_AttachmentImprovements_Installer
{
    const AddonNameSpace = 'SV_AttachmentImprovements_';

    public static function install($existingAddOn, $addOnData)
    {
        $version = isset($existingAddOn['version_id']) ? $existingAddOn['version_id'] : 0;

        if ($version && $version < 1000300)
        {
            // migrate to remove the 'use' from the bad tag list
            $tags = XenForo_Application::getOptions()->SV_AttachImpro_badTags;
            $tags = explode(',', $tags);
            if(($key = array_search('use', $tags)) !== false)
            {
                unset($tags[$key]);
            }
            $dw = XenForo_DataWriter::create('XenForo_DataWriter_Option', XenForo_DataWriter::ERROR_SILENT);
            $dw->setExistingData('SV_AttachImpro_badTags');
            $dw->setOption(XenForo_DataWriter_Option::OPTION_REBUILD_CACHE, false);
            $dw->set('option_value', implode(',', $tags));
            $dw->save();

            XenForo_Application::defer(self::AddonNameSpace.'Deferred_SVGAttachmentThumb', array());
        }
        else if ($version == 0)
        {
            $addon = XenForo_Model::create('XenForo_Model_AddOn')->getAddOnById('SV_SVGAttachment');
            if (!empty($addon))
            {
                XenForo_Application::defer(self::AddonNameSpace.'Deferred_SVGAttachmentThumb', array());
            }
        }

        $addonsToUninstall = array('SV_SVGAttachment' => array(),
                                   'SV_XARAttachment' => array());
        SV_Utils_Install::removeOldAddons($addonsToUninstall);

        return true;
    }

    public static function uninstall()
    {
        $db = XenForo_Application::get('db');

        $db->query("
            DELETE FROM xf_permission_entry
            WHERE permission_id in ('attach_count', 'attach_size')
        ");
        $db->query("
            DELETE FROM xf_permission_entry_content
            WHERE permission_id in ('attach_count', 'attach_size')
        ");

        return true;
    }
}


text:
layout: page
show_meta: false
title: "Basic"
subheadline: "开源项目 算法心得"
permalink: "/basic/"
---
{% include list-posts.html category='basic' %}


text:
class InputClass
{
public:
	InputClass();
	InputClass(const InputClass&);
	~InputClass();

	void Initialize();

	void KeyDown(unsigned int);
	void KeyUp(unsigned int);

	bool IsKeyDown(unsigned int);

private:
	bool m_keys[256];
};

#endif


text:
<?php

namespace Oro\Bundle\ApiBundle\Provider;

use Doctrine\Common\Cache\CacheProvider;

use Oro\Bundle\ApiBundle\Request\ApiActions;
use Oro\Bundle\ApiBundle\Request\ApiResource;
use Oro\Bundle\ApiBundle\Request\ApiResourceSubresources;
use Oro\Bundle\ApiBundle\Request\RequestType;

class ResourcesCache
{
    const RESOURCES_KEY_PREFIX            = 'resources_';
    const SUBRESOURCE_KEY_PREFIX          = 'subresource_';
    const ACCESSIBLE_RESOURCES_KEY_PREFIX = 'accessible_';

    /** @var CacheProvider */
    protected $cache;

    /**
     * @param CacheProvider $cache
     */
    public function __construct(CacheProvider $cache)
    {
        $this->cache = $cache;
    }

    /**
     * Fetches a list of entity classes accessible through Data API from the cache.
     *
     * @param string      $version     The Data API version
     * @param RequestType $requestType The request type, for example "rest", "soap", etc.
     *
     * @return string[]|null The list of entity classes accessible through Data API or NULL if it is not cached yet
     */
    public function getAccessibleResources($version, RequestType $requestType)
    {
        $resources = $this->cache->fetch(
            self::ACCESSIBLE_RESOURCES_KEY_PREFIX . $this->getCacheKeyIndex($version, $requestType)
        );

        return false !== $resources
            ? $resources
            : null;
    }

    /**
     * Fetches all Data API resources from the cache.
     *
     * @param string      $version     The Data API version
     * @param RequestType $requestType The request type, for example "rest", "soap", etc.
     *
     * @return ApiResource[]|null The list of Data API resources or NULL if it is not cached yet
     */
    public function getResources($version, RequestType $requestType)
    {
        $resources = $this->cache->fetch(
            self::RESOURCES_KEY_PREFIX . $this->getCacheKeyIndex($version, $requestType)
        );
        if (false === $resources) {
            return null;
        }

        $result = [];
        foreach ($resources as $entityClass => $cachedData) {
            $result[] = $this->unserializeApiResource($entityClass, $cachedData);
        }

        return $result;
    }

    /**
     * Fetches an entity sub-resources from the cache.
     *
     * @param string      $entityClass The FQCN of an entity
     * @param string      $version     The Data API version
     * @param RequestType $requestType The request type, for example "rest", "soap", etc.
     *
     * @return ApiResourceSubresources[]|null The list of sub-resources or NULL if it is not cached yet
     */
    public function getSubresources($entityClass, $version, RequestType $requestType)
    {
        $cachedData = $this->cache->fetch(
            self::SUBRESOURCE_KEY_PREFIX . $this->getCacheKeyIndex($version, $requestType) . $entityClass
        );
        if (false === $cachedData) {
            return null;
        }

        return $this->unserializeApiResourceSubresources($entityClass, $cachedData);
    }

    /**
     * Puts Data API resources into the cache.
     *
     * @param string        $version     The Data API version
     * @param RequestType   $requestType The request type, for example "rest", "soap", etc.
     * @param ApiResource[] $resources   The list of Data API resources
     */
    public function saveResources($version, RequestType $requestType, array $resources)
    {
        $allResources = [];
        $accessibleResources = [];
        foreach ($resources as $resource) {
            $entityClass = $resource->getEntityClass();
            $allResources[$entityClass] = $this->serializeApiResource($resource);
            if (!in_array(ApiActions::GET, $resource->getExcludedActions(), true)) {
                $accessibleResources[] = $entityClass;
            }
        }

        $keyIndex = $this->getCacheKeyIndex($version, $requestType);
        $this->cache->save(self::RESOURCES_KEY_PREFIX . $keyIndex, $allResources);
        $this->cache->save(self::ACCESSIBLE_RESOURCES_KEY_PREFIX . $keyIndex, $accessibleResources);
    }

    /**
     * Puts sub-resources for all entities into the cache.
     *
     * @param string                    $version      The Data API version
     * @param RequestType               $requestType  The request type, for example "rest", "soap", etc.
     * @param ApiResourceSubresources[] $subresources The list of sub-resources
     */
    public function saveSubresources($version, RequestType $requestType, array $subresources)
    {
        $keyIndex = self::SUBRESOURCE_KEY_PREFIX . $this->getCacheKeyIndex($version, $requestType);
        foreach ($subresources as $entitySubresources) {
            $this->cache->save(
                $keyIndex . $entitySubresources->getEntityClass(),
                $this->serializeApiResourceSubresources($entitySubresources)
            );
        }
    }

    /**
     * Deletes all Data API resources from the cache.
     */
    public function clear()
    {
        $this->cache->deleteAll();
    }

    /**
     * @param string      $version
     * @param RequestType $requestType
     *
     * @return string
     */
    protected function getCacheKeyIndex($version, RequestType $requestType)
    {
        return $version . (string)$requestType;
    }

    /**
     * @param string $entityClass
     * @param array  $cachedData
     *
     * @return ApiResource
     */
    protected function unserializeApiResource($entityClass, array $cachedData)
    {
        $resource = new ApiResource($entityClass);
        $resource->setExcludedActions($cachedData[0]);

        return $resource;
    }

    /**
     * @param ApiResource $resource
     *
     * @return array
     */
    protected function serializeApiResource(ApiResource $resource)
    {
        return [
            $resource->getExcludedActions()
        ];
    }

    /**
     * @param string $entityClass
     * @param array  $cachedData
     *
     * @return ApiResourceSubresources
     */
    protected function unserializeApiResourceSubresources($entityClass, array $cachedData)
    {
        $resource = new ApiResourceSubresources($entityClass);
        foreach ($cachedData[0] as $associationName => $serializedSubresource) {
            $subresource = $resource->addSubresource($associationName);
            $subresource->setTargetClassName($serializedSubresource[0]);
            $subresource->setAcceptableTargetClassNames($serializedSubresource[1]);
            $subresource->setIsCollection($serializedSubresource[2]);
            $subresource->setExcludedActions($serializedSubresource[3]);
        }

        return $resource;
    }

    /**
     * @param ApiResourceSubresources $entitySubresources
     *
     * @return array
     */
    protected function serializeApiResourceSubresources(ApiResourceSubresources $entitySubresources)
    {
        $serializedSubresources = [];
        $subresources = $entitySubresources->getSubresources();
        foreach ($subresources as $associationName => $subresource) {
            $serializedSubresources[$associationName] = [
                $subresource->getTargetClassName(),
                $subresource->getAcceptableTargetClassNames(),
                $subresource->isCollection(),
                $subresource->getExcludedActions()
            ];
        }

        return [
            $serializedSubresources
        ];
    }
}


text:
package com.mitchellbosecke.pebble.node.expression;

import com.mitchellbosecke.pebble.error.PebbleException;
import com.mitchellbosecke.pebble.template.EvaluationContext;
import com.mitchellbosecke.pebble.template.PebbleTemplateImpl;
import com.mitchellbosecke.pebble.utils.OperatorUtils;

public class ModulusExpression extends BinaryExpression<Object> {

    @Override
    public Object evaluate(PebbleTemplateImpl self, EvaluationContext context) throws PebbleException {
        try {
            return OperatorUtils.mod(getLeftExpression().evaluate(self, context),
                    getRightExpression().evaluate(self, context));
        } catch (Exception ex) {
            throw new PebbleException(ex, "Could not perform greater modulus", getLineNumber(), self
                    .getName());
        }
    }
}


text:
package interview.fileCrawler;

import java.io.File;

public interface FileAction
{
     public void actOnFile(File file);
}


text:
package org.apache.logging.log4j.core.net;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetHeaders;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource;
import javax.net.ssl.SSLSocketFactory;

import org.apache.logging.log4j.LoggingException;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.layout.AbstractStringLayout.Serializer;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.apache.logging.log4j.core.net.ssl.SslConfiguration;
import org.apache.logging.log4j.core.util.CyclicBuffer;
import org.apache.logging.log4j.core.util.NetUtils;
import org.apache.logging.log4j.util.PropertiesUtil;

/**
 * Manager for sending SMTP events.
 */
public class SmtpManager extends MailManager {
    public static final SMTPManagerFactory FACTORY = new SMTPManagerFactory();

    private final Session session;

    private final CyclicBuffer<LogEvent> buffer;

    private volatile MimeMessage message;

    private final FactoryData data;

    private static MimeMessage createMimeMessage(final FactoryData data, final Session session, final LogEvent appendEvent)
            throws MessagingException {
        return new MimeMessageBuilder(session).setFrom(data.getFrom())
                .setReplyTo(data.getReplyTo())
                .setRecipients(Message.RecipientType.TO, data.getTo())
                .setRecipients(Message.RecipientType.CC, data.getCc())
                .setRecipients(Message.RecipientType.BCC, data.getBcc())
                .setSubject(data.getSubjectSerializer().toSerializable(appendEvent))
                .build();
    }

    protected SmtpManager(final String name, final Session session, final MimeMessage message,
                          final FactoryData data) {
        super(null, name);
        this.session = session;
        this.message = message;
        this.data = data;
        this.buffer = new CyclicBuffer<>(LogEvent.class, data.getBufferSize());
    }

    @Override
    public void add(LogEvent event) {
        buffer.add(event.toImmutable());
    }

    @Deprecated
    public static SmtpManager getSmtpManager(
                                             final Configuration config,
                                             final String to, final String cc, final String bcc,
                                             final String from, final String replyTo,
                                             final String subject, String protocol, final String host,
                                             final int port, final String username, final String password,
                                             final boolean isDebug, final String filterName, final int numElements,
                                             final SslConfiguration sslConfiguration) {
        final Serializer subjectSerializer = PatternLayout.newSerializerBuilder()
                .setConfiguration(config)
                .setPattern(subject)
                .build();
        final FactoryData data = new FactoryData(to, cc, bcc, from, replyTo, subject, subjectSerializer, protocol, host,
                port, username, password, isDebug, numElements, sslConfiguration, filterName);

        return (SmtpManager) getManager(data.getManagerName(), FACTORY, data);

    }

    @Override
    public void sendEvents(final Layout<?> layout, final LogEvent appendEvent) {
        if (message == null) {
            connect(appendEvent);
        }
        try {
            final LogEvent[] priorEvents = removeAllBufferedEvents();
            // LOG4J-310: log appendEvent even if priorEvents is empty

            final byte[] rawBytes = formatContentToBytes(priorEvents, appendEvent, layout);

            final String contentType = layout.getContentType();
            final String encoding = getEncoding(rawBytes, contentType);
            final byte[] encodedBytes = encodeContentToBytes(rawBytes, encoding);

            final InternetHeaders headers = getHeaders(contentType, encoding);
            final MimeMultipart mp = getMimeMultipart(encodedBytes, headers);

            final String subject = data.getSubjectSerializer().toSerializable(appendEvent);

            sendMultipartMessage(message, mp, subject);
        } catch (final MessagingException | IOException | RuntimeException e) {
            logError("Caught exception while sending e-mail notification.", e);
            throw new LoggingException("Error occurred while sending email", e);
        }
    }

    LogEvent[] removeAllBufferedEvents() {
        return buffer.removeAll();
    }

    protected byte[] formatContentToBytes(final LogEvent[] priorEvents, final LogEvent appendEvent,
                                          final Layout<?> layout) throws IOException {
        final ByteArrayOutputStream raw = new ByteArrayOutputStream();
        writeContent(priorEvents, appendEvent, layout, raw);
        return raw.toByteArray();
    }

    private void writeContent(final LogEvent[] priorEvents, final LogEvent appendEvent, final Layout<?> layout,
                              final ByteArrayOutputStream out)
        throws IOException {
        writeHeader(layout, out);
        writeBuffer(priorEvents, appendEvent, layout, out);
        writeFooter(layout, out);
    }

    protected void writeHeader(final Layout<?> layout, final OutputStream out) throws IOException {
        final byte[] header = layout.getHeader();
        if (header != null) {
            out.write(header);
        }
    }

    protected void writeBuffer(final LogEvent[] priorEvents, final LogEvent appendEvent, final Layout<?> layout,
                               final OutputStream out) throws IOException {
        for (final LogEvent priorEvent : priorEvents) {
            final byte[] bytes = layout.toByteArray(priorEvent);
            out.write(bytes);
        }

        final byte[] bytes = layout.toByteArray(appendEvent);
        out.write(bytes);
    }

    protected void writeFooter(final Layout<?> layout, final OutputStream out) throws IOException {
        final byte[] footer = layout.getFooter();
        if (footer != null) {
            out.write(footer);
        }
    }

    protected String getEncoding(final byte[] rawBytes, final String contentType) {
        final DataSource dataSource = new ByteArrayDataSource(rawBytes, contentType);
        return MimeUtility.getEncoding(dataSource);
    }

    protected byte[] encodeContentToBytes(final byte[] rawBytes, final String encoding)
        throws MessagingException, IOException {
        final ByteArrayOutputStream encoded = new ByteArrayOutputStream();
        encodeContent(rawBytes, encoding, encoded);
        return encoded.toByteArray();
    }

    protected void encodeContent(final byte[] bytes, final String encoding, final ByteArrayOutputStream out)
            throws MessagingException, IOException {
        try (final OutputStream encoder = MimeUtility.encode(out, encoding)) {
            encoder.write(bytes);
        }
    }

    protected InternetHeaders getHeaders(final String contentType, final String encoding) {
        final InternetHeaders headers = new InternetHeaders();
        headers.setHeader("Content-Type", contentType + "; charset=UTF-8");
        headers.setHeader("Content-Transfer-Encoding", encoding);
        return headers;
    }

    protected MimeMultipart getMimeMultipart(final byte[] encodedBytes, final InternetHeaders headers)
        throws MessagingException {
        final MimeMultipart mp = new MimeMultipart();
        final MimeBodyPart part = new MimeBodyPart(headers, encodedBytes);
        mp.addBodyPart(part);
        return mp;
    }

    /**
     * @deprecated Please use the {@link #sendMultipartMessage(MimeMessage, MimeMultipart, String)} method instead.
     */
    @Deprecated
    protected void sendMultipartMessage(final MimeMessage msg, final MimeMultipart mp) throws MessagingException {
        synchronized (msg) {
            msg.setContent(mp);
            msg.setSentDate(new Date());
            Transport.send(msg);
        }
    }

    protected void sendMultipartMessage(final MimeMessage msg, final MimeMultipart mp, final String subject) throws MessagingException {
        synchronized (msg) {
            msg.setContent(mp);
            msg.setSentDate(new Date());
            msg.setSubject(subject);
            Transport.send(msg);
        }
    }

    private synchronized void connect(final LogEvent appendEvent) {
        if (message != null) {
            return;
        }
        try {
            message = createMimeMessage(data, session, appendEvent);
        } catch (final MessagingException e) {
            logError("Could not set SmtpAppender message options", e);
            message = null;
        }
    }

    /**
     * Factory to create the SMTP Manager.
     */
    public static class SMTPManagerFactory implements MailManagerFactory {

        @Override
        public SmtpManager createManager(final String name, final FactoryData data) {
            final String smtpProtocol = data.getSmtpProtocol();
            final String prefix = "mail." + smtpProtocol;

            final Properties properties = PropertiesUtil.getSystemProperties();
            properties.setProperty("mail.transport.protocol", smtpProtocol);
            if (properties.getProperty("mail.host") == null) {
                // Prevent an UnknownHostException in Java 7
                properties.setProperty("mail.host", NetUtils.getLocalHostname());
            }

            final String smtpHost = data.getSmtpHost();
            if (null != smtpHost) {
                properties.setProperty(prefix + ".host", smtpHost);
            }
            if (data.getSmtpPort() > 0) {
                properties.setProperty(prefix + ".port", String.valueOf(data.getSmtpPort()));
            }

            final Authenticator authenticator = buildAuthenticator(data.getSmtpUsername(), data.getSmtpPassword());
            if (null != authenticator) {
                properties.setProperty(prefix + ".auth", "true");
            }

            if (smtpProtocol.equals("smtps")) {
                final SslConfiguration sslConfiguration = data.getSslConfiguration();
                if (sslConfiguration != null) {
                    final SSLSocketFactory sslSocketFactory = sslConfiguration.getSslSocketFactory();
                    properties.put(prefix + ".ssl.socketFactory", sslSocketFactory);
                    properties.setProperty(prefix + ".ssl.checkserveridentity", Boolean.toString(sslConfiguration.isVerifyHostName()));
                }
            }

            final Session session = Session.getInstance(properties, authenticator);
            session.setProtocolForAddress("rfc822", smtpProtocol);
            session.setDebug(data.isSmtpDebug());
            return new SmtpManager(name, session, null, data);
        }

        private Authenticator buildAuthenticator(final String username, final String password) {
            if (null != password && null != username) {
                return new Authenticator() {
                    private final PasswordAuthentication passwordAuthentication =
                        new PasswordAuthentication(username, password);

                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return passwordAuthentication;
                    }
                };
            }
            return null;
        }
    }
}


text:
using System;

namespace Castle.Windsor.MsDependencyInjection
{
    /// <summary>
    /// This class can be used to provide an action when
    /// Dispose method is called.
    /// </summary>
    internal class DisposeAction : IDisposable
    {
        private readonly Action _action;

        /// <summary>
        /// Creates a new <see cref="DisposeAction"/> object.
        /// </summary>
        /// <param name="action">Action to be executed when this object is disposed.</param>
        public DisposeAction(Action action)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            _action = action;
        }

        public void Dispose()
        {
            _action();
        }
    }
}


text:
package org.killbill.clients.feedzai;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class PreviousPaymentResponse {

    private final String label;
    private final PaymentRequest payment;
    private final PaymentResponse score;

    @JsonCreator
    public PreviousPaymentResponse(@JsonProperty("label") String label,
                                   @JsonProperty("payment") PaymentRequest payment,
                                   @JsonProperty("score") PaymentResponse score) {
        this.label = label;
        this.payment = payment;
        this.score = score;
    }

    public String getLabel() {
        return label;
    }

    public PaymentRequest getPayment() {
        return payment;
    }

    public PaymentResponse getScore() {
        return score;
    }
}


text:
using NUnit.Framework;

namespace Jarvis.Framework.Tests.EngineTests.Unfolder
{
	/// <summary>
	/// TODO NSTORE: Please use the StreamProcessor from NSTORE
	/// </summary>
	[TestFixture]
    public class EventUnfolderTests
    {
        //private TestProjector sut;

        //[SetUp]
        //public void SetUp()
        //{
        //    sut = new TestProjector();
        //}

        //[Test]
        //public void Basic_apply_event_on_unfolder()
        //{
        //    sut.ApplyEvent(new TestDomainEvent() { Value = 42 });
        //    Assert.That(sut.GetProjection().Sum, Is.EqualTo(42));
        //}

        //[Test]
        //public void Basic_memento_restore()
        //{
        //    sut.ApplyEvent(new TestDomainEvent() { Value = 42 });
        //    var memento = sut.GetSnapshot();

        //    var newSut1 = new TestProjector();
        //    newSut1.Restore(memento);

        //    var newSut2 = new TestProjector();
        //    newSut2.Restore(memento);

        //    newSut1.ApplyEvent(new TestDomainEvent() { Value = 1 });
        //    Assert.That(newSut1.GetProjection().Sum, Is.EqualTo(43));

        //    newSut2.ApplyEvent(new TestDomainEvent() { Value = 2 });
        //    Assert.That(newSut2.GetProjection().Sum, Is.EqualTo(44), "State shared instances between events");
        //}
    }

    //[TestFixture]
    //public class InMemoryAggregateReadModelTest
    //{
    //    private TestAggregateQueryModel sut;

    //    [SetUp]
    //    public void SetUp()
    //    {
    //        sut = new TestAggregateQueryModel();
    //    }

    //    [Test]
    //    public void verify_deep_cloning_base_capabilities()
    //    {
    //        sut.ListOfInt.Add(1);
    //        var cloned = (TestAggregateQueryModel)sut.Clone();
    //        cloned.ListOfInt.Add(2);

    //        Assert.That(sut.ListOfInt, Is.EquivalentTo(new[] { 1 }));
    //        Assert.That(cloned.ListOfInt, Is.EquivalentTo(new[] { 1, 2 }));
    //    }

    //}

    //[TestFixture]
    //public class EventUnfolderRepositoryTests
    //{
    //    QueryModelRepository sut;

    //    private IMongoDatabase _db;
    //    private IPersistence _persistence;

    //    private IdentityManager _identityConverter;
    //    private AggregateFactoryEx _aggregateFactory = new AggregateFactoryEx(null);
    //    ProjectorFactory _factory;

    //    [OneTimeSetUp]
    //    public void TestFixtureSetUp()
    //    {
    //        var connectionString = ConfigurationManager.ConnectionStrings["eventstore"].ConnectionString;
    //        var url = new MongoUrl(connectionString);
    //        var client = new MongoClient(url);
    //        _db = client.GetDatabase(url.DatabaseName);
    //        client.DropDatabase(url.DatabaseName);

    //        _identityConverter = new IdentityManager(new InMemoryCounterService());
    //        _identityConverter.RegisterIdentitiesFromAssembly(GetType().Assembly);
    //        var loggerFactory = Substitute.For<INStoreLoggerFactory>();
    //        loggerFactory
    //            .CreateLogger(Arg.Any<String>())
    //            .Returns(NStoreNullLogger.Instance);
    //        _persistence = new EventStoreFactory(loggerFactory)
    //            .BuildEventStore(connectionString)
    //            .Result;

    //        _factory = new ProjectorFactory(Substitute.For<IKernel>());
    //    }

    //    ISnapshotStore _snapshotStore;

    //    [SetUp]
    //    public void SetUp()
    //    {
    //        _snapshotStore = Substitute.For<ISnapshotStore>();
    //        sut = new QueryModelRepository(_factory, _persistence, _snapshotStore);
    //    }

    //    Int64 progressive = 0;

    //    [Test]
    //    public void verify_basic_in_memory_projection()
    //    {
    //        var id = new TestEventUnfolderId(Interlocked.Increment(ref progressive));
    //        using (var stream = _persistence.OpenStream("BLAH", id.AsString(), 0, Int32.MaxValue))
    //        {
    //            CommitOneValue(stream, 42);
    //        }

    //        var unfolder = sut.GetById<TestProjector, TestAggregateQueryModel>(id, Int32.MaxValue);
    //        var rm = unfolder.GetProjection();
    //        Assert.That(rm.Sum, Is.EqualTo(42));
    //        Assert.That(rm.ListOfInt, Is.EquivalentTo(new[] { 42 }));
    //    }

    //    [Test]
    //    public void verify_snapshot_usage()
    //    {
    //        var id = new TestEventUnfolderId(Interlocked.Increment(ref progressive));
    //        using (var stream = _persistence.OpenStream("BLAH", id.AsString(), 0, Int32.MaxValue))
    //        {
    //            CommitOneValue(stream, 1);
    //            CommitOneValue(stream, 2);
    //        }

    //        var unfolder = sut.GetById<TestProjector, TestAggregateQueryModel>(id, 1);
    //        var memento = unfolder.GetSnapshot();
    //        Snapshot s = new Snapshot(id.AsString(), 2, memento);

    //        using (var stream = _persistence.OpenStream("BLAH", id.AsString(), 0, Int32.MaxValue))
    //        {
    //            CommitOneValue(stream, 3);
    //        }
    //        _snapshotStore.Load(null, 1, null).ReturnsForAnyArgs(s);

    //        unfolder = sut.GetById<TestProjector, TestAggregateQueryModel>(id, Int32.MaxValue);
    //        var rm = unfolder.GetProjection();
    //        Assert.That(rm.Sum, Is.EqualTo(6));
    //        Assert.That(rm.ListOfInt, Is.EquivalentTo(new[] { 1, 2, 3 }));
    //    }

    //    [Test]
    //    public void verify_use_snapshot_strategy()
    //    {
    //        var id = new TestEventUnfolderId(Interlocked.Increment(ref progressive));
    //        using (var stream = _persistence.OpenStream(id.AsString()))
    //        {
    //            CommitOneValue(stream, 42);
    //        }
    //        TestProjector.ShouldSnapshotReturn = true;
    //        sut.GetById<TestProjector, TestAggregateQueryModel>(id, Int32.MaxValue);
    //        TestProjector.ShouldSnapshotReturn = false;
    //        _snapshotStore.Received().Persist(Arg.Any<ISnapshot>(), Arg.Any<String>());
    //    }

    //    [Test]
    //    public void verify_projection_up_to_certain_event()
    //    {
    //        var id = new TestEventUnfolderId(Interlocked.Increment(ref progressive));
    //        using (var stream = _persistence.OpenStream("BLAH", id.AsString(), 0, Int32.MaxValue))
    //        {
    //            CommitOneValue(stream, 1);
    //            CommitOneValue(stream, 2);
    //            CommitOneValue(stream, 3);
    //        }

    //        var unfolder = sut.GetById<TestProjector, TestAggregateQueryModel>(id, 1);
    //        var rm = unfolder.GetProjection();
    //        Assert.That(rm.Sum, Is.EqualTo(1));
    //        Assert.That(rm.ListOfInt, Is.EquivalentTo(new[] { 1 }));

    //        unfolder = sut.GetById<TestProjector, TestAggregateQueryModel>(id, 2);
    //        rm = unfolder.GetProjection();
    //        Assert.That(rm.Sum, Is.EqualTo(3));
    //        Assert.That(rm.ListOfInt, Is.EquivalentTo(new[] { 1, 2 }));

    //        unfolder = sut.GetById<TestProjector, TestAggregateQueryModel>(id, 3);
    //        rm = unfolder.GetProjection();
    //        Assert.That(rm.Sum, Is.EqualTo(6));
    //        Assert.That(rm.ListOfInt, Is.EquivalentTo(new[] { 1, 2, 3 }));
    //    }

    //    private static void CommitOneValue(IEventStream stream, int value)
    //    {
    //        stream.Add(new EventMessage()
    //        {
    //            Body = new TestDomainEvent() { Value = value }
    //        });
    //        stream.CommitChanges(Guid.NewGuid());
    //    }
    //}

    //[TestFixture]
    //public class EventUnfolderRepositoryTestsWithFakeStoreEvents
    //{
    //    QueryModelRepository sut;

    //    private IMongoDatabase _db;
    //    private IStoreEvents _eventStore;

    //    private IdentityManager _identityConverter;
    //    private AggregateFactory _aggregateFactory = new AggregateFactory(null);
    //    ProjectorFactory _factory;

    //    [OneTimeSetUp]
    //    public void TestFixtureSetUp()
    //    {
    //        var connectionString = ConfigurationManager.ConnectionStrings["eventstore"].ConnectionString;
    //        var url = new MongoUrl(connectionString);
    //        var client = new MongoClient(url);
    //        _db = client.GetDatabase(url.DatabaseName);
    //        client.DropDatabase(url.DatabaseName);

    //        _identityConverter = new IdentityManager(new InMemoryCounterService());
    //        _identityConverter.RegisterIdentitiesFromAssembly(GetType().Assembly);
    //        var loggerFactory = Substitute.For<ILoggerFactory>();
    //        loggerFactory.Create(Arg.Any<Type>()).Returns(NullLogger.Instance);
    //        _eventStore = Substitute.For<IStoreEvents>();

    //        _factory = new ProjectorFactory(Substitute.For<IKernel>());
    //    }

    //    ISnapshotPersister _persister;

    //    [SetUp]
    //    public void SetUp()
    //    {
    //        _persister = Substitute.For<ISnapshotPersister>();
    //        sut = new QueryModelRepository(_factory, _eventStore, _persister);
    //    }

    //    [Test]
    //    public void verify_snapshot_check_version()
    //    {
    //        var id = new TestEventUnfolderId(1);
    //        var unfolder = new TestProjector();
    //        var memento = (EventUnfolderMemento) unfolder.GetSnapshot();
    //        memento.Signature = "OTHER"; //change the version of the memento.
    //        Snapshot s = new Snapshot(id, 2, memento);
    //        _persister.Load("", 1, "").ReturnsForAnyArgs(s);
    //        sut.GetById<TestProjector, TestAggregateQueryModel>(id, 200);
    //        _eventStore.Received().OpenStream("BLAH", id, 0, 200);
    //    }

    //    [Test]
    //    public void verify_snapshot_wrong_version_gets_deleted()
    //    {
    //        var id = new TestEventUnfolderId(1);
    //        var unfolder = new TestProjector();
    //        var memento = (EventUnfolderMemento)unfolder.GetSnapshot();
    //        memento.Signature = "OTHER"; //change the version of the memento.
    //        Snapshot s = new Snapshot(id, 2, memento);
    //        _persister.Load("", 1, "").ReturnsForAnyArgs(s);
    //        sut.GetById<TestProjector, TestAggregateQueryModel>(id, 200);
    //        _persister.Received().Clear(id, memento.Version, typeof(TestProjector).Name);
    //    }
    //}

    //[Serializable]
    //public class TestAggregateQueryModel : BaseAggregateQueryModel
    //{
    //    public Int32 Sum { get; set; }

    //    public List<Int32> ListOfInt { get; set; }

    //    public TestAggregateQueryModel()
    //    {
    //        Sum = 0;
    //        ListOfInt = new List<int>();
    //    }

    //    protected void When(TestDomainEvent evt)
    //    {
    //        Sum += evt.Value;
    //        ListOfInt.Add(evt.Value);
    //    }
    //}

    //public class TestEventUnfolderId : EventStoreIdentity
    //{
    //    public TestEventUnfolderId(long id) : base(id)
    //    {
    //    }

    //    public TestEventUnfolderId(string id) : base(id)
    //    {
    //    }
    //}

    //public class TestProjector : Projector<TestAggregateQueryModel>
    //{
    //    public static Boolean ShouldSnapshotReturn { get; set; }

    //    public TestProjector() : base()
    //    {

    //    }

    //    public override string Signature
    //    {
    //        get
    //        {
    //            return "TEST";
    //        }
    //    }

    //    public override string BucketId
    //    {
    //        get
    //        {
    //            return "BLAH";
    //        }
    //    }

    //    public override bool ShouldSnapshot(int numOfEventsLoaded)
    //    {
    //        return ShouldSnapshotReturn;
    //    }
    //}

    //public class TestDomainEvent : DomainEvent
    //{
    //    public Int32 Value { get; set; }
    //}
}


text:
// +k8s:deepcopy-gen=package

// Package admissionregistration is the internal version of the API.
// AdmissionConfiguration and AdmissionPluginConfiguration are legacy static admission plugin configuration
// InitializerConfiguration, ValidatingWebhookConfiguration, and MutatingWebhookConfiguration are for the
// new dynamic admission controller configuration.
// +groupName=admissionregistration.k8s.io
package admissionregistration


text:
//
//  SmartNotificationDelegate
//  appez
//
//  Created by Transility on 01/08/12.
//
//

#import <Foundation/Foundation.h>

@protocol SmartNotificationDelegate <NSObject>
@optional
-(void)showPopOverViewController;
-(void)hidePopOverViewController;
-(void)sendDataToMaster:(NSString*)data;
-(void)sendDataToDetail:(NSString*)data;
-(void)sendActionInfo:(NSString*)actionName;
-(void)didResponseDataReceived:(NSString*)imageResponse;
-(void)didResponseDataReceivedInBytes:(NSData*)imageResponse;
/** Notifies SmartServiceListener about unsuccessful completion of HTTP operation
 *
 * @param exceptionData : Exception type
 *
 */

-(void)didResponseErrorReceived:(int)exceptionData WithMessage:(NSString*)exceptionMessage;

@end


text:
layout: user-guide
---

# Basic Convenience Features

This topic covers a series of nice-to-have language features in Slang. These features are not supported by HLSL but are introduced to Slang to simplify code development. Many of these features are added to Slang per request of our users.

## Type Inference in Variable Definitions
Slang supports automatic variable type inference:
```csharp
var a = 1; // OK, `a` is an `int`.
var b = float3(0, 1, 2); // OK, `b` is a `float3`.
```
Automatic type inference require an initialization expression to present. Without an initial value, the compiler is not able to infer the type of the variable. The following code will result a compiler error:
```csharp
var a; // Error, cannot infer the type of `a`.
```

You may use the `var` keyword to define a variable in a modern syntax:
```csharp
var a : int = 1; // OK.
var b : int; // OK.
```

## Immutable Values
The `var` syntax and the traditional C-style variable definition introduces a _mutable_ variable whose value can be changed after its definition. If you wish to introduce an immutable or constant value, you may use the `let` keyword:
```rust
let a = 5; // OK, `a` is `int`.
let b : int = 5; // OK.
```
Attempting to change an immutable value will result in a compiler error:
```rust
let a = 5;
a = 6; // Error, `a` is immutable.
```

## Member functions

Slang supports defining member functions in `struct`s. For example, it is allowed to write:

```hlsl
struct Foo
{
    int compute(int a, int b)
    {
        return a + b;
    }
}
```

You can use the `.` syntax to invoke member functions:

```hlsl
Foo foo;
int rs = foo.compute(1,2);
```

Slang also supports static member functions, For example:
```
struct Foo
{
    static int staticMethod(int a, int b)
    {
        return a + b;
    }
}
```

Static member functions are accessed the same way as other static members, via either the type name or an instance of the type:

```hlsl
int rs = Foo.staticMethod(a, b);
```

or

```hlsl
Foo foo;
...
int rs = foo.staticMethod(a,b);
```

### Mutability of member function

For GPU performance considerations, the `this` argument in a member function is immutable by default. If you modify the content in `this` argument, the modification will be discarded after the call and does not affect the input object. If you intend to define a member function that mutates the object, use `[mutating]` attribute on the member function as shown in the following example.

```hlsl
struct Foo
{
    int count;

    [mutating]
    void setCount(int x) { count = x; }

    void setCount2(int x) { count = x; }
}

void test()
{
    Foo f;
    f.setCount(1); // f.count is 1 after the call.
    f.setCount2(2); // f.count is still 1 after the call.
}
```

## Properties

Properties provide a convenient way to access values exposed by a type, where the logic behind accessing the value is defined in `getter` and `setter` function pairs. Slang's `property` feature is similar to C# and Swift.
```csharp
struct MyType
{
    uint flag;

    property uint highBits
    {
        get { return flag >> 16; }
        set { flag = (flag & 0xFF) + (newValue << 16); }
    }
};
```

Or equivalently in a "modern" syntax:

```csharp
struct MyType
{
    uint flag;

    property highBits : uint
    {
        get { return flag >> 16; }
        set { flag = (flag & 0xFF) + (newValue << 16); }
    }
};
```

You may also use an explicit parameter for the setter method:
```csharp
property uint highBits
{
    set(uint x) { flag = (flag & 0xFF) + (x << 16);  }
}
```

> #### Note ####
> Slang currently does not support automatically synthesized `getter` and `setter` methods. For example,
> the following code is not supported:
> ```
> property uint highBits {get;set;} // Not supported yet.
> ```

## Initializers
> #### Note ####
> The syntax for defining initializers are subject to future change.

Slang supports defining initializers in `struct` types. You can write:
```csharp
struct MyType
{
    int myVal;
    __init(int a, int b)
    {
        myVal = a + b;
    }
}
```

You can use an initializer to construct a new instance by using the type name in a function call expression:
```csharp
MyType instance = MyType(1,2);  // instance.myVal is 3.
```

You may also use C++ style initializer list to invoke an initializer:
```csharp
MyType instance = {1, 2};
```

If an initializer does not define any parameters, it will be recognized as *default* initializer that will be automatically called at the definition of a variable:

```csharp
struct MyType
{
    int myVal;
    __init(i)
    {
        myVal = 10;
    }
};

int test()
{
    MyType test;
    return test.myVal; // returns 10.
}
```

## Operator Overloading

Slang allows defining operator overloads as global methods:
```csharp
struct MyType
{
    int val;
    __init(int x) { val = x; }
}

MyType operator+(MyType a, MyType b)
{
    return MyType(a.val + b.val);
}

int test()
{
    MyType rs = MyType(1) + MyType(2);
    return rs.val; // returns 3.
}
```

Slang currently supports overloading the following operators: `+`, `-`, `*`, `/`, `%`, `&`, `|`, `<`, `>`, `<=`, `>=`, `==`, `!=`, unary `-`, `~` and `!`. Please note that the `&&` and `||` operators are not supported.

## `struct` inheritance (limited)

Slang supports a limited form of inheritance. A derived `struct` type has all the members defined in the base type it is inherited from:

```csharp
struct Base
{
    int a;
    void method() {}
}

struct Derived : Base { int b; }

void test()
{
    Derived c;
    c.a = 1;  // OK, a is inherited from `Base`.
    c.b = 2;
    c.method(); // OK, `method` is inherited from `Base`.
}
```

A derived type can be implicitly casted to its base type:
```csharp
void acceptBase(Base b) { ... }
void test()
{
    Derived c;
    acceptBase(c); // OK, c is implicitly casted to `Base`.
}
```

Slang supports controlling whether a type can be inherited from with `[sealed]` and `[open]` attributes on types.
If a base type is marked as `[sealed]`, then inheritance from the type is not allowed anywhere outside the same module (file) that is defining the base type. If a base type is marked as `[open]`, then inheritance is allowed regardless of the location of the derived type. By default, a type is `[sealed]` if no attributes are declared, which means the type can only be inherited by other types in the same module.

### Limitations

Please note that the support for inheritance is currently very limited. Common features that comes with inheritance, such as `virtual` functions and multiple inheritance are not supported by the Slang compiler. Implicit down-casting to the base type and use the result as a `mutable` argument in a function call is also not supported.

Extensions
--------------------
Slang allows defining additional members for a type outside its initial definition. For example, suppose we already have a type defined:

```csharp
struct MyType
{
    int field;
    int get() { return field; }
}
```

You can extend `MyType` with new members:
```csharp
extension MyType
{
    float newField;
    float getNewField() { return newField; }
}
```

All locations that sees the definition of the `extension` can access the new members:

```csharp
void test()
{
    MyType t;
    t.newField = 1.0;
    float val = t.getNewField();
}
```

This feature is similar to extensions in Swift and partial classes in C#.

Modules
-------

While you can still organize code using preprocessor `#include`s, Slang also supports a _module_ system.

### Importing a Module

At the global scope of a Slang file, you can use the `import` keyword to import another module by name:

```hlsl
// MyShader.slang

import YourLibrary;
```

This `import` declaration will cause the compiler to look for a module named `YourLibrary` and make its declarations visible in the current scope.
Currently, the compiler will load the module by looking for source file with a matching name (`YourLibrary.slang`) in any of its configured search paths.

Multiple `import`s of the same module from different input files will only cause the module to be loaded once (there is no need for "include guards" or `#pragma once`).
Note that preprocessor definitions in the current file will not affect the compilation of `import`ed code.

> #### Note ####
> Future versions of the Slang system will support loading of modules from pre-compiled binaries instead of source code.
> The same `import` keyword will continue to work in that case.

### Defining a Module

If you decide to organize your code into modules, then the simplest way is to have each module consist of a single `.slang` file.
Any declarations in your module -- types, functions, etc. -- will be visible to clients that `import` it.

> #### Note ####
> Any preprocessor definitions inside your module will not be visible to clients;
> as a result you may find it best to switch to `static const` for defining constants.

> #### Note ####
> A future version of the Slang compiler may support using access-control keywords (such a `public`) to control which declarations in a module are visible to clients.

Your module may depend on other modules using `import`.
By default, the symbols that are imported into your module are *not* made visible to clients who `import` your module.
You can override this default by using an _exported_ `import`:

```hlsl
__export import SomeOtherModule;
```

This line imports `SomeOtherModule` into the current module, and also re-exports all of the imported symbols from the current module, so that they appear as part of its public interface.


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- This is an unmanaged datasource. It should be used for proofs of concept
   or testing only. It uses H2, a lightweight, in-memory, example database that
   ships with JBoss EAP. It is not robust or scalable, is not supported,
   and should NOT be used in a production environment! -->
<datasources xmlns="http://www.jboss.org/ironjacamar/schema"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.jboss.org/ironjacamar/schema http://docs.jboss.org/ironjacamar/schema/datasources_1_0.xsd">
   <!-- The datasource is bound into JNDI at this location. We reference
      this in META-INF/test-persistence.xml -->
   <datasource jndi-name="java:jboss/datasources/${parentArtifactId}TestDS"
      pool-name="${parentArtifactId}-test" enabled="true"
      use-java-context="true">
      <connection-url>jdbc:h2:mem:${parentArtifactId}-test;DB_CLOSE_DELAY=-1</connection-url>
      <driver>h2</driver>
      <security>
         <user-name>sa</user-name>
         <password>sa</password>
      </security>
   </datasource>
</datasources>


text:
package resources

import (
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/iam"
	"github.com/rebuy-de/aws-nuke/v2/pkg/types"
)

type IAMGroup struct {
	svc  *iam.IAM
	id   string
	name string
	path string
}

func init() {
	register("IAMGroup", ListIAMGroups)
}

func ListIAMGroups(sess *session.Session) ([]Resource, error) {
	svc := iam.New(sess)

	resp, err := svc.ListGroups(nil)
	if err != nil {
		return nil, err
	}

	resources := make([]Resource, 0)
	for _, out := range resp.Groups {
		resources = append(resources, &IAMGroup{
			svc:  svc,
			id:   *out.GroupId,
			name: *out.GroupName,
			path: *out.Path,
		})
	}

	return resources, nil
}

func (e *IAMGroup) Remove() error {
	_, err := e.svc.DeleteGroup(&iam.DeleteGroupInput{
		GroupName: &e.name,
	})
	if err != nil {
		return err
	}

	return nil
}

func (e *IAMGroup) String() string {
	return e.name
}

func (e *IAMGroup) Properties() types.Properties {
	return types.NewProperties().
		Set("Name", e.name).
		Set("Path", e.path).
		Set("ID", e.id)
}


text:
def accountability(group)
  groups = group.shuffle.each_slice(5).to_a
  p groups
end

#Notes:
# tried to insert 'groups = group.shuffle' at the beginning at first.  VERY weird... this just returns the elements in their regular order if i call shuffle up here instead of between group & #each_slice below
# i wonder why i can use #shuffle there but not #sample... i'd guess it's because sample TAKES a random element, whereas shuffle simply makes all the elements random

#Refactored Solution

# I went with .each_slice straight away because I'd read about it so much for the past exercises. The use of 'groups' becomes vestigial when I'm just using an enumerator, vs. going the more basic route of iterating and preserving the original by .dup'ing it. For now, my refactored solution will just be:

def accountability(group)
  group.shuffle.each_slice(5).to_a
end

# ...and I will try the method without using .each_slice to enumerate if I have extra time.

group = ["Jack Abernethy", "Mohammad Amin", "Zollie Barnes", "Reuben Brandt", "Dana Breen", "Breton Burnett", "Saundra Vanessa Castaneda", "Luis De Castro", "Nicolette Chambers", "Kerry Choy", "Nick Davies", "Katherine DiAngelo", "Adrian Diaz", "David Diaz", "Bob Dorff", "Michael Du", "Paul Dynowski", "Jenna Espezua", "Sean Fleming", "Jennifer Gilbert","Marcel Haesok", "Arthur Head", "Jonathan Huang", "Thomas Huang", "Alex Jamar","Kevin Jones", "Steven Jones", "Cole Kent", "Caroline Kenworthy", "Calvin Lang", "Yi Lu", "David Ma", "Charlotte Manetta", "Sean Massih", "Tom McHenry", "Alex Mitzman", "Lydia Nash", "Brenda Nguyen", "Matthew Oppenheimer", "Mason Pierce", "Joe Plonsker", "Mira Scarvalone", "Joseph Scott", "Chris Shahin", "Benjamin Shpringer", "Lindsey Stevenson", "Phil Thomas", "Gary Tso", "Ting Wang", "Clinton Weber", "Monique Williamson", "Regina Wong", "Hanah Yendler" ]

p accountability(group)

# What was the most interesting and most difficult part of this challenge?
# => Well the most interesting part was dropping the .each_slice bomb! Such simplicity with enumeration! I had to do so much reading just to barely start wrapping my head around an enumerators, and I'm nowhere near finishing yet. :P It's a rabbit hole that leads to learning how to make classes....

# Do you feel you are improving in your ability to write pseudocode and break the problem down?
# => Yup! Although here I think I lucked out and didn't need to go through the full gamut of regular iteration.

# Was your approach for automating this task a good solution? What could have made it even better?
# => It sure as heck was good, if I do say so myself! I suppose there might be room for some kind of erroneous randomization or grouping with a total student # whose modulo (%) remainder != 0, but I'm not informed enough yet to test whether that's an actual issue or not.

# What data structure did you decide to store the accountability groups in and why?
# => An array, because it's enumerable. Strings aren't and I just abandoned the extra lines converting an inputted string :( . Via SE:
# "The reason why String is not enumerable is because there are no 'natural' units to enumerate, should it be on a character basis or a line basis? Because of this String does not have an #each String instead provides the #each_char and #each_byte and #each_line methods for iteration in the way that you choose."

# What did you learn in the process of refactoring your initial solution? Did you learn any new Ruby methods?
# => #shuffle and #sample! Well, again, as of the time of writing this, I used an enumerator initially. So I'm sure I'll frustratedly find a new method or two trying to do it the clunkier iteration route later.


text:
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports Csla
Imports Csla.Data

Namespace Invoices.Business

    '''
    ''' SupplierProductColl (editable child list).

    ''' This is a generated base class of <see cref="SupplierProductColl"/> business object.
    '''
    ''' <remarks>
    ''' This class is child of <see cref="SupplierEdit"/> editable root object.

    ''' The items of the collection are <see cref="SupplierProductItem"/> objects.
    ''' </remarks>
    <Serializable>
    Public Partial Class SupplierProductColl
#If WINFORMS Then
        Inherits BusinessBindingListBase(Of SupplierProductColl, SupplierProductItem)
#Else
        Inherits BusinessListBase(Of SupplierProductColl, SupplierProductItem)
#End If

        #Region " Collection Business Methods "

        '''
        ''' Removes a <see cref="SupplierProductItem"/> item from the collection.
        '''
        ''' <param name="productSupplierId">The ProductSupplierId of the item to be removed.</param>
        Public Overloads Sub Remove(productSupplierId As Integer)
            For Each item As SupplierProductItem In Me
                If item.ProductSupplierId = productSupplierId Then
                    MyBase.Remove(item)
                    Exit For
                End If
            Next
        End Sub

        '''
        ''' Determines whether a <see cref="SupplierProductItem"/> item is in the collection.
        '''
        ''' <param name="productSupplierId">The ProductSupplierId of the item to search for.</param>
        ''' <returns><c>True</c> if the SupplierProductItem is a collection item; otherwise, <c>false</c>.</returns>
        Public Overloads Function Contains(productSupplierId As Integer) As Boolean
            For Each item As SupplierProductItem In Me
                If item.ProductSupplierId = productSupplierId Then
                    Return True
                End If
            Next
            Return False
        End Function

        '''
        ''' Determines whether a <see cref="SupplierProductItem"/> item is in the collection's DeletedList.
        '''
        ''' <param name="productSupplierId">The ProductSupplierId of the item to search for.</param>
        ''' <returns><c>True</c> if the SupplierProductItem is a deleted collection item; otherwise, <c>false</c>.</returns>
        Public Overloads Function ContainsDeleted(productSupplierId As Integer) As Boolean
            For Each item As SupplierProductItem In DeletedList
                If item.ProductSupplierId = productSupplierId Then
                    Return True
                End If
            Next
            Return False
        End Function

        #End Region

        #Region " Constructor "

        '''
        ''' Initializes a new instance of the <see cref="SupplierProductColl"/> class.
        '''
        ''' <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
        <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
        Public Sub New()
            ' Use factory methods and do not use direct creation.

            ' show the framework that this is a child object
            MarkAsChild()

            Dim rlce = RaiseListChangedEvents
            RaiseListChangedEvents = False
            AllowNew = True
            AllowEdit = True
            AllowRemove = True
            RaiseListChangedEvents = rlce
        End Sub

        #End Region

        #Region " Data Access "

        '''
        ''' Loads a <see cref="SupplierProductColl"/> collection from the database, based on given criteria.
        '''
        ''' <param name="supplierId">The Supplier Id.</param>
        Protected Overloads Sub DataPortal_Fetch(supplierId As Integer)
            Using ctx = ConnectionManager(Of SqlConnection).GetManager(Database.InvoicesConnection, False)
                Using cmd = New SqlCommand("dbo.GetSupplierProductColl", ctx.Connection)
                    cmd.CommandType = CommandType.StoredProcedure
                    cmd.Parameters.AddWithValue("@SupplierId", supplierId).DbType = DbType.Int32
                    Dim args As New DataPortalHookArgs(cmd, supplierId)
                    OnFetchPre(args)
                    LoadCollection(cmd)
                    OnFetchPost(args)
                End Using
            End Using
        End Sub

        Private Sub LoadCollection(cmd As SqlCommand)
            Using dr As New SafeDataReader(cmd.ExecuteReader())
                Fetch(dr)
            End Using
        End Sub

        '''
        ''' Loads all <see cref="SupplierProductColl"/> collection items from the given SafeDataReader.
        '''
        ''' <param name="dr">The SafeDataReader to use.</param>
        Private Sub Fetch(dr As SafeDataReader)
            Dim rlce = RaiseListChangedEvents
            RaiseListChangedEvents = False
            While dr.Read()
                Add(DataPortal.FetchChild(Of SupplierProductItem)(dr))
            End While
            RaiseListChangedEvents = rlce
        End Sub

        #End Region

        #Region " DataPortal Hooks "

        '''
        ''' Occurs after setting query parameters and before the fetch operation.
        '''
        Partial Private Sub OnFetchPre(args As DataPortalHookArgs)
        End Sub

        '''
        ''' Occurs after the fetch operation (object or collection is fully loaded and set up).
        '''
        Partial Private Sub OnFetchPost(args As DataPortalHookArgs)
        End Sub

        #End Region

    End Class

End Namespace


text:
'use strict';

angular.module('classifieds-app.common', [
    'classifieds-app.common.features',
    'classifieds-app.common.components'
]);


text:
namespace flutter {

class Plugin;

// A object managing the registration of a plugin for various events.
//
// Currently this class has very limited functionality, but is expected to
// expand over time to more closely match the functionality of
// the Flutter mobile plugin APIs' plugin registrars.
class PluginRegistrar {
 public:
  // Creates a new PluginRegistrar. |core_registrar| and the messenger it
  // provides must remain valid as long as this object exists.
  explicit PluginRegistrar(FlPluginRegistrar *core_registrar);

  virtual ~PluginRegistrar();

  // Prevent copying.
  PluginRegistrar(PluginRegistrar const&) = delete;
  PluginRegistrar& operator=(PluginRegistrar const&) = delete;

  // Returns the messenger to use for creating channels to communicate with the
  // Flutter engine.
  //
  // This pointer will remain valid for the lifetime of this instance.
  BinaryMessenger* messenger() { return messenger_.get(); }

  // Returns the texture registrar to use for the plugin to render a pixel
  // buffer.
  TextureRegistrar* texture_registrar() { return texture_registrar_.get(); }

  // Takes ownership of |plugin|.
  //
  // Plugins are not required to call this method if they have other lifetime
  // management, but this is a convient place for plugins to be owned to ensure
  // that they stay valid for any registered callbacks.
  void AddPlugin(std::unique_ptr<Plugin> plugin);

 protected:
  FlPluginRegistrar *registrar() { return registrar_; }

  // Destroys all owned plugins. Subclasses should call this at the beginning of
  // their destructors to prevent the possibility of an owned plugin trying to
  // access destroyed state during its own destruction.
  void ClearPlugins();

 private:
  // Handle for interacting with the C API's registrar.
  FlPluginRegistrar *registrar_;

  std::unique_ptr<BinaryMessenger> messenger_;

  std::unique_ptr<TextureRegistrar> texture_registrar_;

  // Plugins registered for ownership.
  std::set<std::unique_ptr<Plugin>> plugins_;
};

// A plugin that can be registered for ownership by a PluginRegistrar.
class Plugin {
 public:
  virtual ~Plugin() = default;
};

// A singleton to own PluginRegistrars. This is intended for use in plugins,
// where there is no higher-level object to own a PluginRegistrar that can
// own plugin instances and ensure that they live as long as the engine they
// are registered with.
class PluginRegistrarManager {
 public:
  static PluginRegistrarManager* GetInstance();

  // Prevent copying.
  PluginRegistrarManager(PluginRegistrarManager const&) = delete;
  PluginRegistrarManager& operator=(PluginRegistrarManager const&) = delete;

  // Returns a plugin registrar wrapper of type T, which must be a kind of
  // PluginRegistrar, creating it if necessary. The returned registrar will
  // live as long as the underlying FlutterDesktopPluginRegistrarRef, so
  // can be used to own plugin instances.
  //
  // Calling this multiple times for the same registrar_ref with different
  // template types results in undefined behavior.
  template <class T>
  T* GetRegistrar(FlPluginRegistrar *registrar_ref) {
    auto insert_result =
        registrars_.emplace(registrar_ref, std::make_unique<T>(registrar_ref));
    auto& registrar_pair = *(insert_result.first);
    FlutterDesktopPluginRegistrarSetDestructionHandler(registrar_pair.first,
                                                       OnRegistrarDestroyed);
    return static_cast<T*>(registrar_pair.second.get());
  }

  // Destroys all registrar wrappers created by the manager.
  //
  // This is intended primarily for use in tests.
  void Reset() { registrars_.clear(); }

 private:
  PluginRegistrarManager();

  using WrapperMap = std::map<FlPluginRegistrar*,
                              std::unique_ptr<PluginRegistrar>>;

  static void OnRegistrarDestroyed(FlPluginRegistrar *registrar);

  WrapperMap* registrars() { return &registrars_; }

  WrapperMap registrars_;
};

}  // namespace flutter

#endif  // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.percent.PercentRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    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"
    android:background="@drawable/create_user_bg"
    tools:context="ca.com.androidbinnersproject.activities.ForgotPasswordActivity">

    <TextView
        android:id="@+id/forgot_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/forgotPasswordTitle"
        android:textSize="28sp"
        android:gravity="center_horizontal"
        android:textColor="#ffffff"
        app:layout_marginTopPercent="3%"/>

    <TextView
        android:id="@+id/forgot_body"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/forgot_title"
        android:text="@string/forgotPasswordBody"
        android:textSize="20sp"
        android:gravity="center_horizontal"
        android:textColor="#bbbbbb"
        app:layout_marginTopPercent="5%"/>

    <EditText
        android:id="@+id/forgot_email_field"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/forgot_body"
        android:gravity="center_horizontal"
        android:hint="Email"
        android:inputType="textEmailAddress"
        android:maxLines="1"
        app:layout_marginTopPercent="6%" />

    <Button
        android:id="@+id/forgot_submit_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/forgot_email_field"
        android:background="@drawable/submit_button"
        app:layout_heightPercent="7%"
        app:layout_marginTopPercent="3%"/>

</android.support.percent.PercentRelativeLayout>


text:
const PreloadVideo = function(
	ele,
	progressCb,
	loadCb,
	preloadSkipCb,
	preloadCb
) {
	this.xhr = new XMLHttpRequest()
	this.video = ele
	this.progressCb = progressCb
	this.loadCb = loadCb
	this.preloadSkipCb = preloadSkipCb
	this.preloadCb = preloadCb

	if (!this.video) {
		return
	}

	if (this.video.preload == 'none') {
		this.video.src = this.video.getAttribute('data-src')
		this.video.addEventListener('play', this.preloadSkipCb)
		return
	}

	this.xhr.open('GET', this.video.getAttribute('data-src'), true)
	this.xhr.responseType = 'blob'

	this.xhr.onload = function(e) {
		if (this.status == 200) {
			var myBlob = this.response
			var vid = (window.URL ? URL : URL).createObjectURL(myBlob)
			this.video.src = vid
		}
	}

	this.xhr.addEventListener('progress', this.progressCb)

	this.xhr.addEventListener('load', this.loadCb)

	this.xhr.send()
}

export default PreloadVideo


text:
package org.opensaml.xml.schema.impl;

import org.opensaml.xml.XMLObject;
import org.opensaml.xml.io.AbstractXMLObjectMarshaller;
import org.opensaml.xml.io.MarshallingException;
import org.opensaml.xml.schema.XSBase64Binary;
import org.opensaml.xml.util.XMLHelper;
import org.w3c.dom.Element;

/**
 * Thread-safe marshaller of {@link org.opensaml.xml.schema.XSBase64Binary} objects.
 */
public class XSBase64BinaryMarshaller extends AbstractXMLObjectMarshaller {

    /** {@inheritDoc} */
    protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException {
        // no attributes
    }

    /** {@inheritDoc} */
    protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException {
        XSBase64Binary xsBase64Binary = (XSBase64Binary) xmlObject;

        XMLHelper.appendTextContent(domElement, xsBase64Binary.getValue());
    }
}


text:
import * as React from "react";
import req from 'utils/requireContext';

interface DummySlideProps {
  isFullscreen?: boolean;
  slide: any;
  slidesDimension?: any;
}

const DummySlide = ({
  isFullscreen,
  slide,
  slidesDimension
}: DummySlideProps) => (

    {
      slide.plugins.map((plugin: any, key: number) => {
        // When plugin is deleted from plugins array, their position is not
        // removed rather the value is set to null
        if (!plugin) return null;

        const { moduleName, state: { width, height, left, top } } = plugin;
        const Plugin = req(moduleName).component;

        return (

            <Plugin
              disabled={true}
              isFullscreen={isFullscreen}
              pluginState={slide.plugins[key].state} />

        );
      })
    }

);

export { DummySlide };


text:
package com.vaadin.client.renderers;

import java.util.Collection;
import java.util.Collections;

import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Node;
import com.google.gwt.dom.client.Style.Visibility;
import com.vaadin.client.widget.escalator.Cell;
import com.vaadin.client.widget.escalator.FlyweightCell;
import com.vaadin.client.widget.grid.CellReference;
import com.vaadin.client.widget.grid.RendererCellReference;

/**
 * Base class for renderers that needs initialization and destruction logic
 * (override {@link #init(FlyweightCell)} and {@link #destroy(FlyweightCell) }
 * and event handling (see {@link #onBrowserEvent(Cell, NativeEvent)},
 * {@link #getConsumedEvents()} and {@link #onActivate()}.
 *
 *

 * Also provides a helper method for hiding the cell contents by overriding
 * {@link #setContentVisible(FlyweightCell, boolean)}
 *
 * @since 7.4.0
 * @author Vaadin Ltd
 */
public abstract class ComplexRenderer<T> implements Renderer<T> {

    /**
     * Called at initialization stage. Perform any initialization here e.g.
     * attach handlers, attach widgets etc.
     *
     * @param cell
     *            The cell. Note that the cell is not to be stored outside of
     *            the method as the cell instance will change. See
     *            {@link FlyweightCell}
     */
    public abstract void init(RendererCellReference cell);

    /**
     * Called after the cell is deemed to be destroyed and no longer used by the
     * Grid. Called after the cell element is detached from the DOM.
     *

     * The row object in the cell reference will be null since the
     * row might no longer be present in the data source.
     *
     * @param cell
     *            The cell. Note that the cell is not to be stored outside of
     *            the method as the cell instance will change. See
     *            {@link FlyweightCell}
     */
    public void destroy(RendererCellReference cell) {
        // Implement if needed
    }

    /**
     * Returns the events that the renderer should consume. These are also the
     * events that the Grid will pass to
     * {@link #onBrowserEvent(Cell, NativeEvent)} when they occur.
     *
     * @return a list of consumed events
     *
     * @see com.google.gwt.dom.client.BrowserEvents
     */
    public Collection<String> getConsumedEvents() {
        return Collections.emptyList();
    }

    /**
     * Called whenever a registered event is triggered in the column the
     * renderer renders.
     *

     * The events that triggers this needs to be returned by the
     * {@link #getConsumedEvents()} method.
     *

     * Returns boolean telling if the event has been completely handled and
     * should not cause any other actions.
     *
     * @param cell
     *            Object containing information about the cell the event was
     *            triggered on.
     *
     * @param event
     *            The original DOM event
     * @return true if event should not be handled by grid
     */
    public boolean onBrowserEvent(CellReference<?> cell, NativeEvent event) {
        return false;
    }

    /**
     * Used by Grid to toggle whether to show actual data or just an empty
     * placeholder while data is loading. This method is invoked whenever a cell
     * changes between data being available and data missing.
     *

     * Default implementation hides content by setting visibility: hidden to all
     * elements inside the cell. Text nodes are left as is - renderers that add
     * such to the root element need to implement explicit support hiding them.
     *
     * @param cell
     *            The cell
     * @param hasData
     *            Has the cell content been loaded from the data source
     *
     */
    public void setContentVisible(RendererCellReference cell, boolean hasData) {
        Element cellElement = cell.getElement();
        for (int n = 0; n < cellElement.getChildCount(); n++) {
            Node node = cellElement.getChild(n);
            if (Element.is(node)) {
                Element e = Element.as(node);
                if (hasData) {
                    e.getStyle().clearVisibility();
                } else {
                    e.getStyle().setVisibility(Visibility.HIDDEN);
                }
            }
        }
    }

    /**
     * Called when the cell is activated by pressing enter, double
     * clicking or performing a double tap on the cell.
     *
     * @param cell
     *            the activated cell
     * @return true if event was handled and should not be
     *         interpreted as a generic gesture by Grid.
     */
    public boolean onActivate(CellReference<?> cell) {
        return false;
    }

    /**
     * Called when the renderer is deemed to be destroyed and no longer used by
     * the Grid.
     */
    public void destroy() {
        // Implement if needed
    }
}


text:
#ifndef _NXT_MAIN_PROCESS_H_INCLUDED_
#define _NXT_MAIN_PROCESS_H_INCLUDED_

typedef enum {
    NXT_SOCKET_ERROR_SYSTEM = 0,
    NXT_SOCKET_ERROR_NOINET6,
    NXT_SOCKET_ERROR_PORT,
    NXT_SOCKET_ERROR_INUSE,
    NXT_SOCKET_ERROR_NOADDR,
    NXT_SOCKET_ERROR_ACCESS,
    NXT_SOCKET_ERROR_PATH,
} nxt_socket_error_t;

nxt_int_t nxt_main_process_start(nxt_thread_t *thr, nxt_task_t *task,
    nxt_runtime_t *runtime);

NXT_EXPORT extern nxt_uint_t                nxt_conf_ver;
NXT_EXPORT extern const nxt_process_init_t  nxt_discovery_process;
NXT_EXPORT extern const nxt_process_init_t  nxt_controller_process;
NXT_EXPORT extern const nxt_process_init_t  nxt_router_process;
NXT_EXPORT extern const nxt_process_init_t  nxt_proto_process;
NXT_EXPORT extern const nxt_process_init_t  nxt_app_process;

extern const nxt_sig_event_t  nxt_main_process_signals[];
extern const nxt_sig_event_t  nxt_process_signals[];

#endif /* _NXT_MAIN_PROCESS_H_INCLUDED_ */


text:
from openstack import exceptions
from openstack import resource

from openstack.dns.v2 import _base

class ZoneImport(_base.Resource):
    """DNS Zone Import Resource"""
    resource_key = ''
    resources_key = 'imports'
    base_path = '/zones/tasks/import'

    # capabilities
    allow_create = True
    allow_fetch = True
    allow_delete = True
    allow_list = True

    _query_mapping = resource.QueryParameters(
        'zone_id', 'message', 'status'
    )

    #: Properties
    #: Timestamp when the zone was created
    created_at = resource.Body('created_at')
    #: Links contains a `self` pertaining to this zone or a `next` pertaining
    #: to next page
    links = resource.Body('links', type=dict)
    #: Message
    message = resource.Body('message')
    #: Returns the total_count of resources matching this filter
    metadata = resource.Body('metadata', type=list)
    #: The project id which the zone belongs to
    project_id = resource.Body('project_id')
    #: Current status of the zone import
    status = resource.Body('status')
    #: Timestamp when the zone was last updated
    updated_at = resource.Body('updated_at')
    #: Version of the resource
    version = resource.Body('version', type=int)
    #: ID for the zone that was created by this import
    zone_id = resource.Body('zone_id')

    def create(self, session, prepend_key=True, base_path=None):
        """Create a remote resource based on this instance.

        :param session: The session to use for making this request.
        :type session: :class:`~keystoneauth1.adapter.Adapter`
        :param prepend_key: A boolean indicating whether the resource_key
                            should be prepended in a resource creation
                            request. Default to True.
        :param str base_path: Base part of the URI for creating resources, if
                              different from
                              :data:`~openstack.resource.Resource.base_path`.
        :return: This :class:`Resource` instance.
        :raises: :exc:`~openstack.exceptions.MethodNotSupported` if
                 :data:`Resource.allow_create` is not set to ``True``.
        """
        if not self.allow_create:
            raise exceptions.MethodNotSupported(self, "create")

        session = self._get_session(session)
        microversion = self._get_microversion_for(session, 'create')
        # Create ZoneImport requires empty body and 'text/dns' as content-type
        # skip _prepare_request completely, since we need just empty body
        request = resource._Request(
            self.base_path,
            None,
            {'content-type': 'text/dns'}
        )
        response = session.post(request.url,
                                json=request.body, headers=request.headers,
                                microversion=microversion)

        self.microversion = microversion
        self._translate_response(response)
        return self


text:
package org.camunda.bpm.model.dmn.instance;

import java.util.Arrays;
import java.util.Collection;

public class InvocationTest extends DmnModelElementInstanceTest {

  public TypeAssumption getTypeAssumption() {
    return new TypeAssumption(Expression.class, false);
  }

  public Collection<ChildElementAssumption> getChildElementAssumptions() {
    return Arrays.asList(
      new ChildElementAssumption(Expression.class, 0, 1),
      new ChildElementAssumption(Binding.class)
    );
  }

  public Collection<AttributeAssumption> getAttributesAssumptions() {
    return null;
  }

}


text:
'use strict';

var express = require('express'),
    router  = express.Router();

/**
 * GET /
 */
router.get('/:url', function (request, response) {
    var url = new Buffer(request.params.url, 'base64').toString('ascii');
});

/**
 *
 */
module.exports = function (app) {
    app.use('/proxy', router);
};


text:
package com.raizlabs.android.databasecomparison.ormlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
import com.raizlabs.android.databasecomparison.Generator;
import com.raizlabs.android.databasecomparison.Verificator;
import com.raizlabs.android.databasecomparison.MainActivity;
import com.raizlabs.android.databasecomparison.events.LogTestDataEvent;

import java.sql.SQLException;
import java.util.Collection;

import de.greenrobot.event.EventBus;

/**
 * Runs benchmarks for OrmLite
 */
public class OrmLiteTester {
    public static final  String FRAMEWORK_NAME = "OrmLite";

    public static void testAddressBooks(Context context) {
        DatabaseHelper dbHelper = OpenHelperManager.getHelper(context, DatabaseHelper.class);

        try {
            dbHelper.getAddressBookDao().deleteBuilder().delete();
            dbHelper.getAddressItemDao().deleteBuilder().delete();
            dbHelper.getContactDao().deleteBuilder().delete();
        } catch (SQLException e) {
            Log.e(FRAMEWORK_NAME, "Error clearing DB", e);
        }

        final Collection<AddressBook> addressBooks = Generator.createAddressBooks(AddressBook.class, Contact.class, AddressItem.class, MainActivity.COMPLEX_LOOP_COUNT, true);
        long startTime = System.currentTimeMillis();

        try {
            Dao<AddressBook, Integer> addressBookDao = dbHelper.getAddressBookDao();
            Dao<AddressItem, Integer> addressItemDao = dbHelper.getAddressItemDao();
            Dao<Contact, Integer> contactDao = dbHelper.getContactDao();

            final SQLiteDatabase db = dbHelper.getWritableDatabase();
            db.beginTransaction();
            try {
                // see http://stackoverflow.com/questions/17456321/how-to-insert-bulk-data-in-android-sqlite-database-using-ormlite-efficiently
                for (AddressBook addressBook : addressBooks) {
                    // OrmLite isn't that smart, so we have to insert the root object and then we can add the children
                    addressBookDao.create(addressBook);
                    addressBook.insertNewAddresses(addressBookDao, addressItemDao);
                    addressBook.insertNewContacts(addressBookDao, contactDao);
                }

                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }
            EventBus.getDefault().post(new LogTestDataEvent(startTime, System.currentTimeMillis(), FRAMEWORK_NAME, MainActivity.SAVE_TIME));

        } catch (SQLException e) {
            Log.e(FRAMEWORK_NAME, "Error clearing DB", e);
        }

        OpenHelperManager.releaseHelper();
    }

    public static void testAddressItems(Context context) {
        DatabaseHelper dbHelper = OpenHelperManager.getHelper(context, DatabaseHelper.class);

        try {
            dbHelper.getSimpleAddressItemDao().deleteBuilder().delete();
        } catch (SQLException e) {
            Log.e(FRAMEWORK_NAME, "Error clearing DB", e);
        }

        Collection<SimpleAddressItem> simpleAddressItems = Generator.getAddresses(SimpleAddressItem.class, MainActivity.SIMPLE_LOOP_COUNT);
        long startTime = System.currentTimeMillis();

        try {
            Dao<SimpleAddressItem, Integer> simpleItemDao = dbHelper.getSimpleAddressItemDao();
            final SQLiteDatabase db = dbHelper.getWritableDatabase();
            db.beginTransaction();
            try {
                // see http://stackoverflow.com/questions/17456321/how-to-insert-bulk-data-in-android-sqlite-database-using-ormlite-efficiently
                for (SimpleAddressItem simpleAddressItem : simpleAddressItems) {
                    simpleItemDao.create(simpleAddressItem);
                }

                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }
            EventBus.getDefault().post(new LogTestDataEvent(startTime, System.currentTimeMillis(), FRAMEWORK_NAME, MainActivity.SAVE_TIME));

        } catch (SQLException e) {
            Log.e(FRAMEWORK_NAME, "Error clearing DB", e);
        }

        OpenHelperManager.releaseHelper();
    }

    public static void testAddressBooksRead(Context context) {
        DatabaseHelper dbHelper = OpenHelperManager.getHelper(context, DatabaseHelper.class);

        try {
            Dao<AddressBook, Integer> addressBookDao = dbHelper.getAddressBookDao();
            long startTime = System.currentTimeMillis();
            Collection<AddressBook> addressBooks = addressBookDao.queryForAll();
            Verificator.verify(FRAMEWORK_NAME, addressBooks);
            EventBus.getDefault().post(new LogTestDataEvent(startTime, System.currentTimeMillis(), FRAMEWORK_NAME, MainActivity.LOAD_TIME));
        } catch (SQLException e) {
            Log.e(FRAMEWORK_NAME, "Error clearing DB", e);
        }

        OpenHelperManager.releaseHelper();
    }

    public static void testAddressItemsRead(Context context) {
        DatabaseHelper dbHelper = OpenHelperManager.getHelper(context, DatabaseHelper.class);

        try {
            Dao<SimpleAddressItem, Integer> simpleItemDao = dbHelper.getSimpleAddressItemDao();
            long startTime = System.currentTimeMillis();
            Collection<SimpleAddressItem> simpleAddressItems = simpleItemDao.queryForAll();
            Verificator.verifySimple(FRAMEWORK_NAME, simpleAddressItems);
            EventBus.getDefault().post(new LogTestDataEvent(startTime, System.currentTimeMillis(), FRAMEWORK_NAME, MainActivity.LOAD_TIME));
        } catch (SQLException e) {
            Log.e(FRAMEWORK_NAME, "Error clearing DB", e);
        }

        OpenHelperManager.releaseHelper();
    }
}


text:
 * [Animated demos](http://www.wei-wang.com/ExplainGitWithD3/) of fundamental **`git`** commands
 * [How to fix](http://justinhileman.info/article/git-pretty/) your **`git`** mistakes. Not that you'd ever make any
 * [An in-browser, **`git`** intro](https://try.github.io) for friends and co-workers starting **`git`**
 * [Scott Chacon's ProGit book](https://git-scm.com/book/en/v2). Read it and learn. I bought a copy, even though it's free.

---

#### Great non-gratis git goo

 * [A fine suite of courses](https://www.codeschool.com/paths/git) on how to use **`git`** by the Codeschool folks
 * My [*Git Under The Hood*](http://goo.gl/QJIFxo) videos


text:
package springfox.documentation.spring.web.dummy.models;

import com.fasterxml.jackson.databind.node.ObjectNode;

public class ModelWithObjectNode {
  private ObjectNode anyObject;

  public ObjectNode getAnyObject() {
    return anyObject;
  }

  public void setAnyObject(ObjectNode anyObject) {
    this.anyObject = anyObject;
  }
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Base controller class for Grador project
 *
 * This is the common base class for all controllers in Grador project.
 *
 * @package core
 * @author  Ashar Fuadi <fushar@gmail.com>
 * @author  Pusaka Kaleb Setyabudi <sokokaleb@gmail.com>
 */
class MY_Controller extends CI_Controller
{
	/**
	 * The view data for each page
	 *
	 * This view data consists of the following pairs:
	 * - 'header'  => The view data for the page header an array of <name> => <value> pairs. Some required pairs:
	 *                - 'title' => The page title to be shown in the browser.
	 *                - 'name'  => The page name.
	 * - 'content' => The view data for the page content an array of <name> => <value> pairs.
	 * - 'footer'  => The view data for the page footer an array of <name> => <value> pairs.
	 *
	 * @var array
	 */
	protected $ui;

	/**
	 * Constructs a new controller object
	 *
	 * This function constructs a new controller.
	 */
	public function __construct()
	{
		parent::__construct();
		$this->load->language('common');

		$this->ui['header']['web_name'] = $this->setting->get('web_name');
		$this->ui['header']['top_name'] = $this->setting->get('top_name');
		$this->ui['header']['bottom_name'] = $this->setting->get('bottom_name');
		$this->ui['header']['left_logo'] = $this->setting->get('left_logo');
		$this->ui['header']['right_logo1'] = $this->setting->get('right_logo1');
		$this->ui['header']['right_logo2'] = $this->setting->get('right_logo2');
		$this->ui['content'] = array();
		$this->ui['footer'] = array();

	}
}

/**
 * Base controller class for administrators
 *
 * This is the common base class for all controllers that can only be accessed by administrators; i.e., users whose
 * category is Administrator.
 *
 * @package core
 * @author Ashar Fuadi <fushar@gmail.com>
 */
class Admin_Controller extends MY_Controller
{
	/**
	 * Constructs a new administrator controller object
	 *
	 * This function constructs a new administrator controller. It also checks whether the user accessing it is an
	 * administrator. If not, the user will be redirected to the login page.
	 */
	public function __construct()
	{
		parent::__construct();

		if ( ! $this->identity->is_admin())
			redirect('site/login');

		$this->load->model('clarification_manager');

		$this->identity->checkin();

		$unread_clar_cnt = $this->clarification_manager->count_admin_unread();

		$this->ui['header']['active_user_name'] = $this->identity->get_user_name();
		$this->ui['header']['custom_css'] = array();
		$this->ui['header']['custom_js'] = array();
		$this->ui['header']['unread_clar_cnt'] = $unread_clar_cnt;
	}
}

/**
 * Base controller class for contestants
 *
 * This is the common base class for all controllers that can only be accessed by contestants; i.e., users whose
 * category is not Administrator.
 *
 * @package core
 * @author Ashar Fuadi <fushar@gmail.com>
 */
class Contestant_Controller extends MY_Controller
{
	/**
	 * Constructs a new contestant controller object
	 *
	 * This function constructs a new contestant controller. It also checks whether the user accessing it is a
	 * contestant. If not, the user will be redirected to the login page.
	 */
	public function __construct()
	{
		parent::__construct();

		if ( ! $this->identity->is_contestant())
			redirect('site/login');

		$this->load->model('user_manager');
		$this->load->model('contest_manager');
		$this->load->model('clarification_manager');

		$this->identity->checkin();

		$user_id = $this->identity->get_user_id();
		$user = $this->user_manager->get_row($user_id);

		$contest_id = $this->identity->get_current_contest_id();
		$contest = $this->contest_manager->get_row($contest_id);
		$unread_clar_cnt = $this->clarification_manager->count_contestant_unread($user_id, $contest_id);

		$this->ui['header']['custom_css'] = array();
		$this->ui['header']['custom_js'] = array();
		$this->ui['header']['active_user_name'] = $user['name'];
		$this->ui['header']['active_contest_name'] = $contest['name'];
		$this->ui['header']['active_contest_end_time'] = $contest['end_time'];
		$this->ui['header']['unread_clar_cnt'] = $unread_clar_cnt;
		$this->ui['footer']['active_contest_end_time'] = $contest['end_time'];
	}
}

/* End of file MY_Controller.php */
/* Location: ./application/core/MY_Controller.php */