text:
package com.cloud.mom.rabbitmq;

import com.cloud.framework.events.Event;
import com.cloud.framework.events.EventBus;
import com.cloud.framework.events.EventBusException;
import com.cloud.framework.events.EventSubscriber;
import com.cloud.framework.events.EventTopic;
import com.cloud.managed.context.ManagedContextRunnable;
import com.cloud.utils.Ternary;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.exception.CloudRuntimeException;

import javax.naming.ConfigurationException;
import java.io.IOException;
import java.net.ConnectException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.AlreadyClosedException;
import com.rabbitmq.client.BlockedListener;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.MessageProperties;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RabbitMQEventBus extends ManagerBase implements EventBus {

    private static final Logger s_logger = LoggerFactory.getLogger(RabbitMQEventBus.class);
    private static String secureProtocol = "TLSv1";
    // AMQP server should consider messages acknowledged once delivered if _autoAck is true
    private static final boolean s_autoAck = true;
    // details of AMQP server
    private static String amqpHost;
    private static Integer port;
    private static String username;
    private static String password;
    private static String virtualHost;
    private static String useSsl;
    // AMQP exchange name where all CloudStack events will be published
    private static String amqpExchangeType = "topic";
    private static String amqpExchangeName = "";
    private static String amqpQueueName = "";

    private static Integer retryInterval;
    // hashmap to book keep the registered subscribers
    private static ConcurrentHashMap<String, Ternary<String, Channel, EventSubscriber>> s_subscribers;
    // connection to AMQP server,
    private static Connection s_connection = null;
    private static DisconnectHandler disconnectHandler;
    private static BlockedConnectionHandler blockedConnectionHandler;
    private ExecutorService executorService;

    public static void setServer(final String amqpHost) {
        RabbitMQEventBus.amqpHost = amqpHost;
    }

    public static void setUsername(final String username) {
        RabbitMQEventBus.username = username;
    }

    public static void setPassword(final String password) {
        RabbitMQEventBus.password = password;
    }

    public static void setPort(final Integer port) {
        RabbitMQEventBus.port = port;
    }

    public static void setSecureProtocol(final String protocol) {
        RabbitMQEventBus.secureProtocol = protocol;
    }

    public static void setExchange(final String exchange) {
        RabbitMQEventBus.amqpExchangeName = exchange;
    }

    public static void setQueue(final String amqpQueueName) {
        RabbitMQEventBus.amqpQueueName = amqpQueueName;
    }

    public static void setExchangetype(final String amqpExchangeType) {
        RabbitMQEventBus.amqpExchangeType = amqpExchangeType;
    }

    public static void setRetryInterval(final Integer retryInterval) {
        RabbitMQEventBus.retryInterval = retryInterval;
    }

    public synchronized static void setVirtualHost(final String virtualHost) {
        RabbitMQEventBus.virtualHost = virtualHost;
    }

    public static void setUseSsl(final String useSsl) {
        RabbitMQEventBus.useSsl = useSsl;
    }

    // publish event on to the exchange created on AMQP server
    @Override
    public void publish(final Event event) throws EventBusException {

        String routingKey = createRoutingKey(event);
        final String eventDescription = event.getDescription();

        try {
            final Connection connection = getConnection();
            final Channel channel = createChannel(connection);
            createExchange(channel, amqpExchangeName);
            if (!amqpQueueName.isEmpty()) {
                createQueue(channel, amqpQueueName);
                bindQueue(channel, amqpQueueName, amqpExchangeName);
                routingKey = amqpQueueName;
            }
            publishEventToExchange(channel, amqpExchangeName, routingKey, eventDescription);
            channel.close();
        } catch (final AlreadyClosedException e) {
            closeConnection();
            throw new EventBusException("Failed to publish event to message broker as connection to AMQP broker in lost");
        } catch (final Exception e) {
            throw new EventBusException("Failed to publish event to message broker due to " + e.getMessage());
        }
    }

    /**
     * Call to subscribe to interested set of events
     *
     * @param topic      defines category and type of the events being subscribed to
     * @param subscriber subscriber that intends to receive event notification
     * @return UUID that represents the subscription with event bus
     * @throws EventBusException
     */
    @Override
    public UUID subscribe(final EventTopic topic, final EventSubscriber subscriber) throws EventBusException {

        if (subscriber == null || topic == null) {
            throw new EventBusException("Invalid EventSubscriber/EventTopic object passed.");
        }

        // create a UUID, that will be used for managing subscriptions and also used as queue name
        // for on the queue used for the subscriber on the AMQP broker
        final UUID queueId = UUID.randomUUID();
        final String queueName = queueId.toString();

        try {
            final String bindingKey = createBindingKey(topic);

            // store the subscriber details before creating channel
            s_subscribers.put(queueName, new Ternary<>(bindingKey, null, subscriber));

            // create a channel dedicated for this subscription
            final Connection connection = getConnection();
            final Channel channel = createChannel(connection);

            // create a queue and bind it to the exchange with binding key formed from event topic
            createExchange(channel, amqpExchangeName);
            channel.queueDeclare(queueName, false, false, false, null);
            channel.queueBind(queueName, amqpExchangeName, bindingKey);

            // register a callback handler to receive the events that a subscriber subscribed to
            channel.basicConsume(queueName, s_autoAck, queueName, new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(final String queueName, final Envelope envelope, final AMQP.BasicProperties properties, final byte[] body) throws IOException {
                    RabbitMQEventBus.this.handleDelivery(queueName, envelope, body);
                }
            });

            // update the channel details for the subscription
            final Ternary<String, Channel, EventSubscriber> queueDetails = s_subscribers.get(queueName);
            queueDetails.second(channel);
            s_subscribers.put(queueName, queueDetails);
        } catch (final AlreadyClosedException | ConnectException | NoSuchAlgorithmException | KeyManagementException | TimeoutException e) {
            s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName + " will be active after reconnection", e);
        } catch (final IOException e) {
            throw new EventBusException("Failed to subscribe to event due to " + e.getMessage(), e);
        }

        return queueId;
    }

    @Override
    public void unsubscribe(final UUID subscriberId, final EventSubscriber subscriber) throws EventBusException {
        try {
            final String classname = subscriber.getClass().getName();
            final String queueName = UUID.nameUUIDFromBytes(classname.getBytes()).toString();
            final Ternary<String, Channel, EventSubscriber> queueDetails = s_subscribers.get(queueName);
            final Channel channel = queueDetails.second();
            channel.basicCancel(queueName);
            s_subscribers.remove(queueName, queueDetails);
        } catch (final IOException e) {
            throw new EventBusException("Failed to unsubscribe from event bus due to " + e.getMessage(), e);
        }
    }

    /**
     * creates a binding key from the event topic that subscriber specified
     * binding key will be used to bind the queue created for subscriber to exchange on AMQP server
     */
    private String createBindingKey(final EventTopic topic) {
        final String eventSource = makeKeyValue(topic.getEventSource());
        final String eventCategory = makeKeyValue(topic.getEventCategory());
        final String eventType = makeKeyValue(topic.getEventType());
        final String resourceType = makeKeyValue(topic.getResourceType());
        final String resourceUuid = makeKeyValue(topic.getResourceUUID());

        return buildKey(eventSource, eventCategory, eventType, resourceType, resourceUuid);
    }

    private void handleDelivery(final String queueName, final Envelope envelope, final byte[] body) {
        final Ternary<String, Channel, EventSubscriber> queueDetails = s_subscribers.get(queueName);
        if (queueDetails != null) {
            final EventSubscriber subscriber = queueDetails.third();
            final String routingKey = envelope.getRoutingKey();
            final String eventSource = getEventSourceFromRoutingKey(routingKey);
            final String eventCategory = getEventCategoryFromRoutingKey(routingKey);
            final String eventType = getEventTypeFromRoutingKey(routingKey);
            final String resourceType = getResourceTypeFromRoutingKey(routingKey);
            final String resourceUUID = getResourceUUIDFromRoutingKey(routingKey);
            final Event event = new Event(eventSource, eventCategory, eventType, resourceType, resourceUUID);
            event.setDescription(new String(body));

            // deliver the event to call back object provided by subscriber
            subscriber.onEvent(event);
        }
    }

    private String getEventSourceFromRoutingKey(final String routingKey) {
        final String[] keyParts = routingKey.split("\\.");
        return keyParts[0];
    }

    private String getEventCategoryFromRoutingKey(final String routingKey) {
        final String[] keyParts = routingKey.split("\\.");
        return keyParts[1];
    }

    private String getEventTypeFromRoutingKey(final String routingKey) {
        final String[] keyParts = routingKey.split("\\.");
        return keyParts[2];
    }

    private String getResourceTypeFromRoutingKey(final String routingKey) {
        final String[] keyParts = routingKey.split("\\.");
        return keyParts[3];
    }

    private String getResourceUUIDFromRoutingKey(final String routingKey) {
        final String[] keyParts = routingKey.split("\\.");
        return keyParts[4];
    }

    /**
     * creates a routing key from the event details.
     * created routing key will be used while publishing the message to exchange on AMQP server
     */
    private String createRoutingKey(final Event event) {
        final String eventSource = makeKeyValue(event.getEventSource());
        final String eventCategory = makeKeyValue(event.getEventCategory());
        final String eventType = makeKeyValue(event.getEventType());
        final String resourceType = makeKeyValue(event.getResourceType());
        final String resourceUuid = makeKeyValue(event.getResourceUUID());

        return buildKey(eventSource, eventCategory, eventType, resourceType, resourceUuid);
    }

    private synchronized Connection getConnection() throws IOException, TimeoutException, NoSuchAlgorithmException, KeyManagementException {
        if (s_connection == null) {
            try {
                return createConnection();
            } catch (KeyManagementException | NoSuchAlgorithmException | IOException | TimeoutException e) {
                s_logger.warn("Failed to create a connection to AMQP server due to " + e.getMessage());
                throw e;
            }
        } else {
            return s_connection;
        }
    }

    private Channel createChannel(final Connection connection) throws IOException {
        try {
            return connection.createChannel();
        } catch (final IOException e) {
            s_logger.warn("Failed to create a channel due to " + e.getMessage(), e);
            throw e;
        }
    }

    private void createExchange(final Channel channel, final String exchangeName) throws IOException {
        try {
            channel.exchangeDeclare(exchangeName, amqpExchangeType, true);
        } catch (final IOException e) {
            s_logger.warn("Failed to create exchange" + e + " on RabbitMQ server");
            throw e;
        }
    }

    private void createQueue(final Channel channel, final String queueName) throws IOException {
        try {
            channel.queueDeclare(queueName, true, false, false, null);
        } catch (final IOException e) {
            s_logger.warn("Failed to create queue" + e + " on RabbitMQ server");
            throw e;
        }
    }

    private void bindQueue(final Channel channel, final String queueName, final String exchangeName) throws IOException {
        try {
            channel.queueBind(queueName, exchangeName, queueName);
        } catch (final IOException e) {
            s_logger.warn("Failed to bind queue" + e + " on RabbitMQ server");
            throw e;
        }
    }

    private void publishEventToExchange(final Channel channel, final String exchangeName, final String routingKey, final String eventDescription) throws IOException {
        final byte[] messageBodyBytes = eventDescription.getBytes();
        try {
            channel.basicPublish(exchangeName, routingKey, MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes);
        } catch (final IOException e) {
            s_logger.warn("Failed to publish event " + routingKey + " on exchange " + exchangeName + "  of message broker due to " + e.getMessage(), e);
            throw e;
        }
    }

    private synchronized void closeConnection() {
        try {
            if (s_connection != null) {
                s_connection.close();
            }
        } catch (final Exception e) {
            s_logger.warn("Failed to close connection to AMQP server due to " + e.getMessage());
        }
        s_connection = null;
    }

    private String makeKeyValue(final String value) {
        return replaceNullWithWildcard(value).replace(".", "-");
    }

    private String buildKey(final String eventSource, final String eventCategory, final String eventType, final String resourceType, final String resourceUuid) {
        return eventSource + "." + eventCategory + "." + eventType + "." + resourceType + "." + resourceUuid;
    }

    private synchronized Connection createConnection() throws KeyManagementException, NoSuchAlgorithmException, IOException, TimeoutException {
        final ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(username);
        factory.setPassword(password);
        factory.setHost(amqpHost);
        factory.setPort(port);

        if (virtualHost != null && !virtualHost.isEmpty()) {
            factory.setVirtualHost(virtualHost);
        } else {
            factory.setVirtualHost("/");
        }

        if (useSsl != null && !useSsl.isEmpty() && useSsl.equalsIgnoreCase("true")) {
            factory.useSslProtocol(secureProtocol);
        }
        final Connection connection = factory.newConnection();
        connection.addShutdownListener(disconnectHandler);
        connection.addBlockedListener(blockedConnectionHandler);
        s_connection = connection;
        return s_connection;
    }

    private String replaceNullWithWildcard(final String key) {
        if (key == null || key.isEmpty()) {
            return "*";
        } else {
            return key;
        }
    }

    private synchronized void abortConnection() {
        if (s_connection == null) {
            return;
        }

        try {
            s_connection.abort();
        } catch (final Exception e) {
            s_logger.warn("Failed to abort connection due to " + e.getMessage());
        }
        s_connection = null;
    }

    @Override
    public String getName() {
        return _name;
    }

    @Override
    public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {

        try {
            if (amqpHost == null || amqpHost.isEmpty()) {
                throw new ConfigurationException("Unable to get the AMQP server details");
            }

            if (username == null || username.isEmpty()) {
                throw new ConfigurationException("Unable to get the username details");
            }

            if (password == null || password.isEmpty()) {
                throw new ConfigurationException("Unable to get the password details");
            }

            if (amqpExchangeName == null || amqpExchangeName.isEmpty()) {
                throw new ConfigurationException("Unable to get the _exchange details on the AMQP server");
            }

            if (port == null) {
                throw new ConfigurationException("Unable to get the port details of AMQP server");
            }

            if (useSsl != null && !useSsl.isEmpty()) {
                if (!useSsl.equalsIgnoreCase("true") && !useSsl.equalsIgnoreCase("false")) {
                    throw new ConfigurationException("Invalid configuration parameter for 'ssl'.");
                }
            }

            if (retryInterval == null) {
                retryInterval = 10000;// default to 10s to try out reconnect
            }
        } catch (final NumberFormatException e) {
            throw new ConfigurationException("Invalid port number/retry interval");
        }

        s_subscribers = new ConcurrentHashMap<>();
        executorService = Executors.newCachedThreadPool();
        disconnectHandler = new DisconnectHandler();
        blockedConnectionHandler = new BlockedConnectionHandler();

        return true;
    }

    @Override
    public boolean start() {
        final ReconnectionTask reconnect = new ReconnectionTask(); // initiate connection to AMQP server
        executorService.submit(reconnect);
        return true;
    }

    @Override
    public synchronized boolean stop() {
        if (s_connection.isOpen()) {
            for (final String subscriberId : s_subscribers.keySet()) {
                final Ternary<String, Channel, EventSubscriber> subscriberDetails = s_subscribers.get(subscriberId);
                final Channel channel = subscriberDetails.second();
                try {
                    channel.queueDelete(subscriberId);
                    channel.abort();
                } catch (final IOException ioe) {
                    s_logger.warn("Failed to delete queue: " + subscriberId + " on AMQP server due to " + ioe.getMessage());
                }
            }
        }

        closeConnection();
        return true;
    }

    //logic to deal with blocked connection. connections are blocked for example when the rabbitmq server is out of space. https://www.rabbitmq.com/connection-blocked.html
    private class BlockedConnectionHandler implements BlockedListener {

        @Override
        public void handleBlocked(final String reason) throws IOException {
            s_logger.error("rabbitmq connection is blocked with reason: " + reason);
            closeConnection();
            throw new CloudRuntimeException("unblocking the parent thread as publishing to rabbitmq server is blocked with reason: " + reason);
        }

        @Override
        public void handleUnblocked() throws IOException {
            s_logger.info("rabbitmq connection in unblocked");
        }
    }

    // logic to deal with loss of connection to AMQP server
    private class DisconnectHandler implements ShutdownListener {

        @Override
        public void shutdownCompleted(final ShutdownSignalException shutdownSignalException) {
            if (!shutdownSignalException.isInitiatedByApplication()) {

                for (final String subscriberId : s_subscribers.keySet()) {
                    final Ternary<String, Channel, EventSubscriber> subscriberDetails = s_subscribers.get(subscriberId);
                    subscriberDetails.second(null);
                    s_subscribers.put(subscriberId, subscriberDetails);
                }

                abortConnection(); // disconnected to AMQP server, so abort the connection and channels
                s_logger.warn("Connection has been shutdown by AMQP server. Attempting to reconnect.");

                // initiate re-connect process
                final ReconnectionTask reconnect = new ReconnectionTask();
                executorService.submit(reconnect);
            }
        }
    }

    // retry logic to connect back to AMQP server after loss of connection
    private class ReconnectionTask extends ManagedContextRunnable {

        boolean connected = false;
        Connection connection = null;

        @Override
        protected void runInContext() {

            while (!connected) {
                try {
                    Thread.sleep(retryInterval);
                } catch (final InterruptedException ie) {
                    // ignore timer interrupts
                }

                try {
                    try {
                        connection = createConnection();
                        connected = true;
                    } catch (final IOException | TimeoutException | NoSuchAlgorithmException | KeyManagementException e) {
                        s_logger.warn("Can't establish connection to AMQP server yet, so continue", e);
                        continue;
                    }

                    // prepare consumer on AMQP server for each of subscriber
                    for (final String subscriberId : s_subscribers.keySet()) {
                        final Ternary<String, Channel, EventSubscriber> subscriberDetails = s_subscribers.get(subscriberId);
                        final String bindingKey = subscriberDetails.first();

                        /** create a queue with subscriber ID as queue name and bind it to the exchange
                         *  with binding key formed from event topic
                         */
                        final Channel channel = createChannel(connection);
                        createExchange(channel, amqpExchangeName);
                        channel.queueDeclare(subscriberId, false, false, false, null);
                        channel.queueBind(subscriberId, amqpExchangeName, bindingKey);

                        // register a callback handler to receive the events that a subscriber subscribed to
                        channel.basicConsume(subscriberId, s_autoAck, subscriberId, new DefaultConsumer(channel) {
                            @Override
                            public void handleDelivery(final String queueName, final Envelope envelope, final AMQP.BasicProperties properties, final byte[] body) throws
                                    IOException {
                                RabbitMQEventBus.this.handleDelivery(queueName, envelope, body);
                            }
                        });

                        // update the channel details for the subscription
                        subscriberDetails.second(channel);
                        s_subscribers.put(subscriberId, subscriberDetails);
                    }
                } catch (final IOException e) {
                    s_logger.warn("Failed to recreate queues and binding for the subscribers due to " + e.getMessage(), e);
                }
            }
        }
    }
}


text:
/**
 * Remove the translation for a given locale
 *
 * @param     string $locale Locale to use for the translation, e.g. 'fr_FR'
 * @param     PropelPDO $con an optional connection object
 *
 * @return    <?php echo $objectClassname ?> The current object (for fluent API support)
 */
public function removeTranslation($locale = '<?php echo $defaultLocale ?>', PropelPDO $con = null)
{
	if (!$this->isNew()) {
		<?php echo $i18nQueryName ?>::create()
			->filterByPrimaryKey(array($this->getPrimaryKey(), $locale))
			->delete($con);
	}
	if (isset($this->currentTranslations[$locale])) {
		unset($this->currentTranslations[$locale]);
	}
	foreach ($this-><?php echo $i18nCollection ?> as $key => $translation) {
		if ($translation->get<?php echo $localeColumnName ?>() == $locale) {
			unset($this-><?php echo $i18nCollection ?>[$key]);
			break;
		}
	}

	return $this;
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace utest\authentication\unit\storage;

use umi\authentication\storage\SessionStorage;
use umi\session\ISession;
use umi\toolkit\Toolkit;
use utest\authentication\AuthenticationTestCase;

/**
 * Тесты storage на основе сессии
 */
class SessionTest extends AuthenticationTestCase
{
    /**
     * @var SessionStorage $storage
     */
    protected $storage;

    /**
     * @var Toolkit $manager менеджер инструментов
     */
    protected $manager;

    public function setUpFixtures()
    {
        $this->storage = new SessionStorage();
        $this->resolveOptionalDependencies($this->storage);
    }

    public function testIdentity()
    {
        $this->assertFalse($this->storage->hasIdentity(), 'Ожидается, что идентификатор не будет существовать');

        $e = null;
        try {
            $this->storage->getIdentity();
        } catch (\Exception $e) {}
        $this->assertInstanceOf('umi\authentication\exception\RuntimeException', $e, 'Ожидается, что идентификатор не был сохранен в сессию');

        $this->assertSame(
            $this->storage,
            $this->storage->setIdentity('identity'),
            'Ожидается, что будет возвращен $this'
        );

        $this->assertEquals('identity', $this->storage->getIdentity(), 'Ожидается, что идентификатор был сохранен');
        $this->assertTrue($this->storage->hasIdentity(), 'Ожидается, что идентификатор будет существовать');

        $this->assertSame($this->storage, $this->storage->clearIdentity(), 'Ожидается, что будет возвращен $this');
        $this->assertFalse($this->storage->hasIdentity(), 'Ожидается, что идентификатор не будет существовать');

    }

    public function testOptions()
    {

        $storage = new SessionStorage();
        $this->resolveOptionalDependencies($storage);
        $storage->setOptions(['namespace' => 'auth']);

        $storage->setIdentity(1);

        /**
         * @var ISession $session
         */
        $session = $this->getTestToolkit()->getService('umi\session\ISession');

        $this->assertEquals(1, $session->get('auth/identity'), 'Ожидается, что пространство имен не пустое.');
    }
}


text:
void expected_results()
{
   //
   // Define the max and mean errors expected for
   // various compilers and platforms.
   //
#ifdef BOOST_INTEL
   add_expected_result(
       ".*",               // compiler
       ".*",               // stdlib
       ".*",               // platform
       "float128",         // test type(s)
       ".*",               // test data group
       "hermite", 70, 25); // test function
#endif
   add_expected_result(
       ".*",              // compiler
       ".*",              // stdlib
       ".*",              // platform
       ".*",              // test type(s)
       ".*",              // test data group
       "hermite", 10, 5); // test function
   //
   // Finish off by printing out the compiler/stdlib/platform names,
   // we do this to make it easier to mark up expected error rates.
   //
   std::cout << "Tests run with " << BOOST_COMPILER << ", "
             << BOOST_STDLIB << ", " << BOOST_PLATFORM << std::endl;
}

template <class T>
void test(T t, const char* p)
{
   test_hermite(t, p);
}

BOOST_AUTO_TEST_CASE(test_main)
{
   using namespace boost::multiprecision;
   expected_results();
   //
   // Test at:
   // 18 decimal digits: tests 80-bit long double approximations
   // 30 decimal digits: tests 128-bit long double approximations
   // 35 decimal digits: tests arbitrary precision code
   //
   ALL_TESTS
}


text:
#pragma once

// ensure the MCU series is correct
#ifndef STM32PLUS_F1
#error This class can only be used with the STM32F1 series
#endif

namespace stm32plus {

  /**
   * Template feature class to support initialisation of analog input pins on the F1.
   * Multiple pins can be initialised in one instantiation
   */

  template<uint8_t... TPins>
  class AnalogInputFeature : public Gpio {

    public:

    /**
     * Constructor
     * @param port the port reference
     */

      AnalogInputFeature(GpioPortBase& port)
        : Gpio(port) {

        uint32_t pins;

        // recurse to get the pin mask

        pins=0;
        GpioPinMerge<TPins...>(pins);

        // do the initialisation

        initialise(pins);
      }

      /**
       * Alternative to template initialisation - initialise programatically
       * @param pinIds
       */

      void initialise(uint16_t pinIds) {

        uint8_t i;
        GPIO_InitTypeDef init;

        this->_pinIds=pinIds;

        init.GPIO_Pin=pinIds;
        init.GPIO_Mode=GPIO_Mode_AIN;

        GPIO_Init(_peripheralAddress,&init);

        // set ourselves as the pin handler in the port base

        for(i=0;i<16;i++)
          if((pinIds & (1<<i))!=0)
            _portBase.setPinHandler(i,this);
      }
  };
}


text:
describe('<md-chips>', function() {

  beforeEach(module('material.components.chips'));

  function compile (str, scope) {
    var container;
    inject(function ($compile) {
      container = $compile(str)(scope);
      scope.$apply();
    });
    return container;
  }

  function createScope () {
    var scope;
    var items = ['Apple', 'Banana', 'Orange'];
    inject(function ($rootScope) {
      scope = $rootScope.$new();
      scope.items = items;
    });
    return scope;
  }

  function getChipElements(root) {
    return angular.element(root[0].querySelectorAll('div.md-chip'));
  }

  describe('basic functionality', function () {
    it('should render a default input element', function() {
      var scope = createScope();
      var template = '<md-chips ng-model="items"></md-chips>';
      var element = compile(template, scope);
      var ctrl = element.controller('mdChips');

      element.scope().$apply();
      var input = element.find('input');
      expect(input.length).toBe(1);
      expect(input).toHaveClass('md-chip-input');
    });

    it('should render a list of chips', function() {
      var scope = createScope();
      var template = '<md-chips ng-model="items"></md-chips>';
      var element = compile(template, scope);
      var ctrl = element.controller('mdChips');

      element.scope().$apply();
      var chips = getChipElements(element);
      expect(chips.length).toBe(3);
      expect(chips[0].innerHTML).toContain('Apple');
      expect(chips[1].innerHTML).toContain('Banana');
      expect(chips[2].innerHTML).toContain('Orange');
    });

    it('should render a user-provided chip template', function() {
      var scope = createScope();
      var template =
          '<md-chips ng-model="items">' +
          '  <md-chip class="mychiptemplate"></md-chip>' +
          '</md-chips>';
      var element = compile(template, scope);
      var ctrl = element.controller('mdChips');

      element.scope().$apply();
      var chip = element.find('md-chip');
      expect(chip).toHaveClass('mychiptemplate');
    });

    it('should add a chip', function() {
      var scope = createScope();
      var template = '<md-chips ng-model="items"></md-chips>';
      var element = compile(template, scope);
      var ctrl = element.controller('mdChips');

      element.scope().$apply();
      ctrl.chipBuffer = 'Grape';
      element.scope().$apply();

      ctrl.appendChipBuffer();
      element.scope().$apply();

      var chips = getChipElements(element);
      expect(chips.length).toBe(4);
      expect(chips[0].innerHTML).toContain('Apple');
      expect(chips[1].innerHTML).toContain('Banana');
      expect(chips[2].innerHTML).toContain('Orange');
      expect(chips[3].innerHTML).toContain('Grape');
    });

    it('should remove a chip', function() {
      var scope = createScope();
      var template = '<md-chips ng-model="items"></md-chips>';
      var element = compile(template, scope);
      var ctrl = element.controller('mdChips');

      element.scope().$apply();

      // Remove "Banana"
      ctrl.removeChip(1);
      element.scope().$apply();

      var chips = getChipElements(element);
      expect(chips.length).toBe(2);
      expect(chips[0].innerHTML).toContain('Apple');
      expect(chips[1].innerHTML).toContain('Orange');
    });
  });

  describe('<md-chip-remove>', function() {
    it('should remove a chip', function() {
      var scope = createScope();
      var template = '<md-chips ng-model="items"></md-chips>';
      var element = compile(template, scope);
      var ctrl = element.controller('mdChips');
      element.scope().$apply();

      var chips = getChipElements(element);
      expect(chips.length).toBe(3);
      // Remove 'Banana'
      var db = angular.element(chips[1]).find('md-button');
      db[0].click();
      element.scope().$apply();

      chips = getChipElements(element);
      expect(chips.length).toBe(2);

      // Remove 'Orange'
      db = angular.element(chips[1]).find('md-button');
      db[0].click();
      element.scope().$apply();

      chips = getChipElements(element);
      expect(chips.length).toBe(1);
    });
  });

});


text:
class CreatePolicyRelations < ActiveRecord::Migration
  def change
    create_table :policy_relations do |t|
      t.references :policy
      t.references :related_policy
      t.timestamps null: false
    end

    add_index :policy_relations, :policy_id
    add_index :policy_relations, :related_policy_id
  end
end


text:
{% load i18n %}

    {% trans 'Row header' %}

            <input type="checkbox" id="{{ widget.attrs.id }}-handsontable-header" name="handsontable-header"/>

{% trans 'Display the first row as a header.' %}

    {% trans 'Column header' %}

            <input type="checkbox" id="{{ widget.attrs.id }}-handsontable-col-header" name="handsontable-col-header"/>

{% trans 'Display the first column as a header.' %}

{% include 'django/forms/widgets/hidden.html' %}


text:
package org.apache.cloudstack.api.command.admin.zone;

import com.cloud.exception.ConcurrentOperationException;
import com.cloud.hypervisor.vmware.VmwareDatacenterService;
import com.cloud.storage.StoragePool;
import org.apache.cloudstack.acl.RoleType;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.BaseListCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.ListResponse;
import org.apache.cloudstack.api.response.StoragePoolResponse;
import org.apache.cloudstack.api.response.VsphereStoragePoliciesResponse;
import org.apache.cloudstack.api.response.ZoneResponse;
import org.apache.cloudstack.context.CallContext;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

@APICommand(name = ListVsphereStoragePolicyCompatiblePoolsCmd.APINAME, description = "List storage pools compatible with a vSphere storage policy",
        responseObject = StoragePoolResponse.class,
        requestHasSensitiveInfo = false, responseHasSensitiveInfo = false,
        authorized = {RoleType.Admin})
public class ListVsphereStoragePolicyCompatiblePoolsCmd extends BaseListCmd {
    public static final String APINAME = "listVsphereStoragePolicyCompatiblePools";

    @Inject
    public VmwareDatacenterService vmwareDatacenterService;

    /////////////////////////////////////////////////////
    //////////////// API parameters /////////////////////
    /////////////////////////////////////////////////////

    @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class,
            description = "ID of the zone")
    private Long zoneId;

    @Parameter(name = ApiConstants.POLICY_ID, type = BaseCmd.CommandType.UUID, entityType = VsphereStoragePoliciesResponse.class,
            description = "ID of the storage policy")
    private Long policyId;

    /////////////////////////////////////////////////////
    /////////////// API Implementation///////////////////
    /////////////////////////////////////////////////////

    @Override
    public void execute() throws ServerApiException, ConcurrentOperationException {
        List<StoragePool> pools = vmwareDatacenterService.listVsphereStoragePolicyCompatibleStoragePools(this);
        ListResponse<StoragePoolResponse> response = new ListResponse<>();
        List<StoragePoolResponse> poolResponses = new ArrayList<>();
        for (StoragePool pool : pools) {
            StoragePoolResponse poolResponse = _responseGenerator.createStoragePoolForMigrationResponse(pool);
            poolResponse.setObjectName("storagepool");
            poolResponses.add(poolResponse);
        }
        response.setResponses(poolResponses);
        response.setResponseName(getCommandName());
        this.setResponseObject(response);
    }

    @Override
    public String getCommandName() {
        return APINAME.toLowerCase() + BaseCmd.RESPONSE_SUFFIX;
    }

    @Override
    public long getEntityOwnerId() {
        return CallContext.current().getCallingAccountId();
    }

    public Long getZoneId() {
        return zoneId;
    }

    public Long getPolicyId() {
        return policyId;
    }
}


text:
import { CacheModule as NestCacheModule, Global, Module } from '@nestjs/common';
import { ConfigModule } from '@server/common/config/ConfigModule';
import { CacheConfigService } from './CacheConfigService';
import { CacheService } from './CacheService';

/**
 * cache 模块
 *
 * @export
 * @class CacheModule
 */
@Global()
@Module({
	imports: [
		NestCacheModule.registerAsync({
			imports: [ConfigModule],
			useClass: CacheConfigService,
			inject: [CacheConfigService]
		})
	],
	providers: [CacheConfigService, CacheService],
	exports: [CacheService]
})
export class CacheModule {
	// hole
}


text:
import $ from 'jquery';
import _ from 'underscore';

class Jira {
  constructor() {
    this.masterTicketNumber = '';
    this.affectsVersion = '';
    this.targetBranches = [];

    this.MASTER_VERSION = 13;

    this.currentBranch = '';
  }

  propagate() {
    this.determineMasterTicketNumber();
    this.determineAffectsVersion();
    this.determineTargetBranches();
    console.log({
      affectsVersion: this.affectsVersion,
      targetBranches: this.targetBranches
    });
    this.createTicket();
  }

  determineMasterTicketNumber() {
    this.masterTicketNumber = $("#key-val").html();
  }

  determineAffectsVersion() {
    let versionFieldContent = $("#versions-field span").html();
    let version = parseInt(versionFieldContent.replace(/v/g, ''), 10);
    this.affectsVersion = version;
  }

  determineTargetBranches() {
    let targetVersions = _.range(this.affectsVersion, this.MASTER_VERSION);
    this.targetBranches = targetVersions.map((version) => `0${version}_release`);
    this.targetBranches.push("master");
  }

  createTicket() {
    $('#opsbar-operations_more .dropdown-text').click();
    setTimeout(() => {
      $('#create-subtask span').click();

      setTimeout(() => {
        this.fillTicket();
      }, 1000);
    }, 10);
  }

  fillTicket() {
    this.currentBranch = this.targetBranches.shift();
    this.fillSummary();
    this.fillTargetBranch();
    this.selectIssueType();
  }

  fillSummary() {
    let title = `Propagate ${this.masterTicketNumber} to ${this.currentBranch}`;
    $('#summary').val(title);
  }

  fillTargetBranch() {
    let selector = `#customfield_12905 option[title='${this.currentBranch}']`;
    $(selector).attr('selected', 'selected');
  }

  selectIssueType() {
    $('#issuetype-field').click();
    setTimeout(() => {
      $('.aui-list-item.aui-list-item-li-code-propagation').click();

      setTimeout(() => {
        this.submitTicket();
      }, 10)
    }, 20);
  }

  submitTicket() {
    $('#create-issue-submit').click();
    if(this.targetBranches.length > 0){
      setTimeout(() => {
        this.createTicket();
      }, 5000);
    } else {
      setTimeout(function(){ window.location = window.location }, 5000);
    }
  }
}

export default Jira;


text:
// @flow
/* eslint-env jest */
/* eslint-disable global-require */
import * as rules from "../rules";

it("should export Validator", () => {
  expect(typeof require("../index").default).toBe("function");
});

it("should export Validator", () => {
  expect(typeof require("../index").validator).toBe("function");
});

it("should export extender", () => {
  expect(typeof require("../index").extend).toBe("function");
});

it("should export rules", () => {
  expect(require("../index").rules).toBe(rules);
});


text:
/* Automatically generated code, don't edit ! */

package org.urish.gwtit.titanium.ui;

import org.urish.gwtit.titanium.ui.events.EmailDialogCompleteHandler;

import com.google.gwt.core.client.JavaScriptObject;

/**
 * The Email Dialog is created by
 * {@link org.urish.gwtit.titanium.ui.createEmailDialog} and allows you to send
 * in application emails on behalf of the application user.
 * <p>
 * Notes:
 *
 * @since 0.8
 */
public class EmailDialog extends org.urish.gwtit.titanium.Proxy {
	protected EmailDialog() {
	}

	private static native final int value_CANCELLED()
	/*-{
		return Titanium.UI.EmailDialog.CANCELLED;
	}-*/;

	public static final int CANCELLED = value_CANCELLED();

	private static native final int value_FAILED()
	/*-{
		return Titanium.UI.EmailDialog.FAILED;
	}-*/;

	public static final int FAILED = value_FAILED();

	private static native final int value_SAVED()
	/*-{
		return Titanium.UI.EmailDialog.SAVED;
	}-*/;

	public static final int SAVED = value_SAVED();

	private static native final int value_SENT()
	/*-{
		return Titanium.UI.EmailDialog.SENT;
	}-*/;

	public static final int SENT = value_SENT();

	/**
	 * @return The bar color of the email dialog window when opened
	 */
	public final native String getBarColor()
	/*-{
		return this.barColor;
	}-*/;

	public final native void setBarColor(String value)
	/*-{
		this.barColor = value;
	}-*/;

	/**
	 * @return Array of email BCC: recipients
	 */
	public final native String[] getBccRecipients()
	/*-{
		return this.bccRecipients;
	}-*/;

	public final native void setBccRecipients(String[] value)
	/*-{
		this.bccRecipients = value;
	}-*/;

	/**
	 * @return Array of email CC: recipients
	 */
	public final native String[] getCcRecipients()
	/*-{
		return this.ccRecipients;
	}-*/;

	public final native void setCcRecipients(String[] value)
	/*-{
		this.ccRecipients = value;
	}-*/;

	/**
	 * @return Boolean to indicate whether the email messageBody should be sent
	 *         as HTML content type. defaults to false. (Android note: you
	 *         should not use html messages in 1.6: after that is okay.)
	 */
	public final native boolean getHtml()
	/*-{
		return this.html;
	}-*/;

	public final native void setHtml(boolean value)
	/*-{
		this.html = value;
	}-*/;

	/**
	 * @return The email message body
	 */
	public final native String getMessageBody()
	/*-{
		return this.messageBody;
	}-*/;

	public final native void setMessageBody(String value)
	/*-{
		this.messageBody = value;
	}-*/;

	/**
	 * @return The subject line for the email
	 */
	public final native String getSubject()
	/*-{
		return this.subject;
	}-*/;

	public final native void setSubject(String value)
	/*-{
		this.subject = value;
	}-*/;

	/**
	 * @return Array of email recipients
	 */
	public final native String[] getToRecipients()
	/*-{
		return this.toRecipients;
	}-*/;

	public final native void setToRecipients(String[] value)
	/*-{
		this.toRecipients = value;
	}-*/;

	/**
	 * Add an attachment to the email. The attachment can either be a Blob or
	 * File object. Note: Versions before 1.7.1 will only support one attachment
	 * in Android. Since version 1.7.1, our Android implementation will accept
	 * multiple attachments, but multiple attachments will only work if the user
	 * chooses to send via the Android Gmail app; the Android "Mail" app (which
	 * is anyway not available on some handsets) will only accept one attachment
	 * from a Titanium app. K9 has also been tested successfully with multiple
	 * attachments.
	 *
	 * @param attachment
	 *            attachment object as either a Blob or File object
	 */
	public final native void addAttachment(JavaScriptObject attachment)
	/*-{
		return this.addAttachment(attachment);
	}-*/;

	/**
	 * Return whether or not sending email is supported
	 */
	public final native void isSupported()
	/*-{
		return this.isSupported();
	}-*/;

	/**
	 * Open the email dialog. the email dialog itself is a modal window
	 */
	public final native void open()
	/*-{
		return this.open();
	}-*/;

	/**
	 * Open the email dialog. the email dialog itself is a modal window
	 *
	 * @param properties
	 *            object of animation properties. pass `animated` property (as
	 *            boolean) to indicate if the dialog should be animated on open.
	 */
	public final native void open(JavaScriptObject properties)
	/*-{
		return this.open(properties);
	}-*/;

	public final native void addCompleteHandler(EmailDialogCompleteHandler handler)
	/*-{
		return this.addEventListener('complete', function(e) { handler.@org.urish.gwtit.titanium.ui.events.EmailDialogCompleteHandler::onEmailDialogComplete(Lorg/urish/gwtit/titanium/ui/events/EmailDialogCompleteEvent;)(e); } );
	}-*/;

}


text:
#ifndef NSYNC_PLATFORM_CYGWIN_PLATFORM_H_
#define NSYNC_PLATFORM_CYGWIN_PLATFORM_H_

#if !defined(_GNU_SOURCE)
#define _GNU_SOURCE
#endif
#include <errno.h>
#include <limits.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/timeb.h>
#include <unistd.h>

#endif /*NSYNC_PLATFORM_CYGWIN_PLATFORM_H_*/


text:
package com.thinkgem.jeesite.modules.cms.utils;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.modules.cms.entity.Article;
import com.thinkgem.jeesite.modules.cms.entity.Category;
import com.thinkgem.jeesite.modules.cms.entity.Link;
import com.thinkgem.jeesite.modules.cms.entity.Site;
import com.thinkgem.jeesite.modules.cms.service.ArticleService;
import com.thinkgem.jeesite.modules.cms.service.CategoryService;
import com.thinkgem.jeesite.modules.cms.service.LinkService;
import com.thinkgem.jeesite.modules.cms.service.SiteService;

/**
 * 内容管理工具类
 * @author ThinkGem
 * @version 2013-01-15
 */
@Service
public class CmsUtils implements ApplicationContextAware {

	private static final String CMS_CACHE = "cmsCache";

	private static SiteService siteService;
	private static CategoryService categoryService;
	private static ArticleService articleService;
	private static LinkService linkService;

	/**
	 * 获得站点信息
	 * @param id 站点编号
	 */
	public static Site getSite(long siteId){
		long id = 1L;
		if (siteId > 0){
			id = siteId;
		}
		Site site = (Site)CacheUtils.get(CMS_CACHE, "site_"+id);
		if (site==null){
			site = siteService.get(id);
			if (site!=null && Site.DEL_FLAG_NORMAL.equals(site.getDelFlag())){
				CacheUtils.put(CMS_CACHE, "site_"+id, site);
			}else{
				site = siteService.get(1L);
			}
		}
		return site;
	}

	/**
	 * 获得站点列表
	 */
	public static List<Site> getSiteList(){
		@SuppressWarnings("unchecked")
		List<Site> siteList = (List<Site>)CacheUtils.get(CMS_CACHE, "siteList");
		if (siteList == null){
			Page<Site> page = new Page<Site>(1, -1);
			page = siteService.find(page, new Site());
			siteList = page.getList();
			CacheUtils.put(CMS_CACHE, "siteList", siteList);
		}
		return siteList;
	}

	/**
	 * 获得主导航列表
	 * @param siteId 站点编号
	 */
	public static List<Category> getMainNavList(long siteId){
		@SuppressWarnings("unchecked")
		List<Category> mainNavList = (List<Category>)CacheUtils.get(CMS_CACHE, "mainNavList_"+siteId);
		if (mainNavList == null){
			Category category = new Category();
			category.setSite(new Site(siteId));
			category.setParent(new Category(1L));
			category.setInMenu(Category.SHOW);
			Page<Category> page = new Page<Category>(1, -1);
			page = categoryService.find(page, category);
			mainNavList = page.getList();
			CacheUtils.put(CMS_CACHE, "mainNavList_"+siteId, mainNavList);
		}
		return mainNavList;
	}

	/**
	 * 获得栏目列表
	 * @param siteId 站点编号
	 * @param parentId 分类父编号
	 * @param number 获取数目
	 * @param param  预留参数,例: key1:'value1', key2:'value2' ...
	 */
	public static List<Category> getCategoryList(long siteId, long parentId, int number, String param){
		Page<Category> page = new Page<Category>(1, number, -1);
		Category category = new Category();
		category.setSite(new Site(siteId));
		category.setParent(new Category(parentId));
		if (StringUtils.isNotBlank(param)){
			@SuppressWarnings({ "unused", "rawtypes" })
			Map map = JsonMapper.getInstance().fromJson("{"+param+"}", Map.class);
		}
		page = categoryService.find(page, category);
		return page.getList();
	}

	/**
	 * 获取文章
	 * @param id 文章编号
	 * @return
	 */
	public static Article getArticle(long articleId){
		return articleService.get(articleId);
	}

	/**
	 * 获取文章列表
	 * @param siteId 站点编号
	 * @param categoryId 分类编号
	 * @param number 获取数目
	 * @param param  预留参数,例: key1:'value1', key2:'value2' ...
	 * 			posid	推荐位(1:首页焦点图;2:栏目页文章推荐;)
	 * 			thumb	缩略图(1:有缩略图的文章)
	 * @return
	 */
	public static List<Article> getArticleList(long siteId, long categoryId, int number, String param){
		Page<Article> page = new Page<Article>(1, number, -1);
		Article article = new Article(new Category(categoryId, new Site(siteId)));
		if (StringUtils.isNotBlank(param)){
			@SuppressWarnings({ "rawtypes" })
			Map map = JsonMapper.getInstance().fromJson("{"+param+"}", Map.class);
			if (new Integer(1).equals(map.get("posid")) || new Integer(2).equals(map.get("posid"))){
				article.setPosid(String.valueOf(map.get("posid")));
			}
			if (new Integer(1).equals(map.get("thumb"))){
				article.setThumb("1");
			}
		}
		page = articleService.find(page, article);
		return page.getList();
	}

	/**
	 * 获取链接
	 * @param id 文章编号
	 * @return
	 */
	public static Link getLink(long linkId){
		return linkService.get(linkId);
	}

	/**
	 * 获取链接列表
	 * @param siteId 站点编号
	 * @param categoryId 分类编号
	 * @param number 获取数目
	 * @param param  预留参数,例: key1:'value1', key2:'value2' ...
	 * @return
	 */
	public static List<Link> getLinkList(long siteId, long categoryId, int number, String param){
		Page<Link> page = new Page<Link>(1, number, -1);
		Link link = new Link(new Category(categoryId, new Site(siteId)));
		if (StringUtils.isNotBlank(param)){
			@SuppressWarnings({ "unused", "rawtypes" })
			Map map = JsonMapper.getInstance().fromJson("{"+param+"}", Map.class);
		}
		page = linkService.find(page, link);
		return page.getList();
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext){
		siteService = (SiteService)applicationContext.getBean("siteService");
		categoryService = (CategoryService)applicationContext.getBean("categoryService");
		articleService = (ArticleService)applicationContext.getBean("articleService");
		linkService = (LinkService)applicationContext.getBean("linkService");
	}

	// ============== Cms Cache ==============

	public static Object getCache(String key) {
		return CacheUtils.get(CMS_CACHE, key);
	}

	public static void putCache(String key, Object value) {
		CacheUtils.put(CMS_CACHE, key, value);
	}

	public static void removeCache(String key) {
		CacheUtils.remove(CMS_CACHE, key);
	}
}


text:
import _ from 'lodash'
// import jetpack from 'fs-jetpack'
// import { remote } from 'electron'
// import db from '../../services/db'
import dataBase from '../../services/dataBase'
import CONSTS from '../../utils/constants'
import * as types from '../mutation-types'

// const userDataDir = remote.app.getPath('userData')

// initial state
const state = {
  github: '',
  user: {},
  repos: [],
  lazyRepos: [],
  langGroup: [],
  reposCount: '0',
  untaggedCount: '0',
  searchQuery: '',
  order: 1,
  activeLang: '',
  loadingRepos: false,
  tags: []
}

// actions
const actions = {
  async loadRepos ({ commit, dispatch, state }, payload) {
    const { repos } = payload
    // loading finish
    // if (_.size(repos) === 0) {
    //   commit(types.SET_GITHUB_STATE, {
    //     lazyRepos: state.repos,
    //     loadingRepos: false
    //   })
    //   return repos
    // }
    // insert repos
    let apiReposArray = []
    const initRepos = repos.map((v, i) => {
      const repo = {
        ...v,
        '_id': v.id,
        'repo_idx': parseInt(i),
        'owner_name': v.full_name.split('/').shift(),
        'repo_name': v.full_name.split('/').pop(),
        'downloads_url': v.html_url + '/archive/' + v.default_branch + '.zip',
        'language': v.language == null ? 'null' : v.language
      }
      dataBase.findOneRepo(v.id).then(res => {
        _.isUndefined(res) ? dataBase.addRepo(repo) : dataBase.updateRepo(repo)
      })
      apiReposArray.push(v.id)
      return repo
    })
    console.log('findOneAndUpdate [%d] repos', _.size(repos))

    // sync repos.db
    // let diffRepos = []
    // dataBase.fetchAllRepos().then(dbRepos => {
    //   console.log(dbRepos)
    //   const dbReposArray = dbRepos.map(v => v._id)
    //   // looking for difference
    //   diffRepos = _.xor(apiReposArray, dbReposArray)
    //   if (_.size(diffRepos) > 0) {
    //     for (let diff in diffRepos) {
    //       if (diffRepos.hasOwnProperty(diff) && _.includes(dbReposArray, diffRepos[diff])) {
    //         // remove the difference repos
    //         dataBase.removeRepo(diffRepos[diff])
    //       }
    //     }
    //   }
    // })

    const mergedRepos = [...state.repos, ...initRepos]

    commit(types.SET_REPOS, { repos: mergedRepos })

    return initRepos
  },
  // build lang_group
  async bulidLangGroup ({ commit, state }, payload) {
    const { repos } = state
    const devicons = CONSTS.DEVICONS
    const countedLangs = _.countBy(repos, 'language')
    const langGroup = Object.keys(countedLangs).map((v, i) => {
      return {
        lang: v,
        count: countedLangs[v],
        icon: devicons[v] || devicons['Default']
      }
    })
    // ordered by count desc & lang asc
    const orderedLangGroup = _.orderBy(langGroup, ['count', 'lang'], ['desc', 'asc'])
    // upsert the lang_group db
    orderedLangGroup.forEach((v, i) => {
      dataBase.findOneLangGroup(v.lang).then(data => {
        if (_.isUndefined(data)) {
          v._id = i + 1
          dataBase.addLangGroup(v)
        } else {
          dataBase.updateLangGroup(v)
        }
      })
    })
    commit(types.SET_GITHUB_STATE, { langGroup: orderedLangGroup })
  },
  async setUser ({ commit, state }, payload) {
    const { user } = payload
    dataBase.findOneUser(user.id).then(async res => {
      console.log(res)
      if (_.isUndefined(res)) {
        await dataBase.addUser(user)
        commit(types.SET_GITHUB_STATE, { user })
      } else {
        await dataBase.updateUser(user)
        commit(types.SET_GITHUB_STATE, { user })
      }
    })
  }
  // async addLangGroup ({ commit, state }, payload) {
  //   const { langGroup } = state
  //   const newTag = {
  //     _id: langGroup.length + 1,
  //     lang: payload,
  //     count: 0,
  //     icon: Constants.DEVICONS['Default']
  //   }
  //   commit(types.ADD_LANG_GROUP, { newTag })
  //   const res = db.addLangGroup(newTag, _ => {})
  //   return res
  // }
}

// mutations
const mutations = {
  [types.SET_GITHUB_STATE] (state, payload) {
    Object.assign(state, payload)
  },

  [types.SET_REPOS] (state, { repos }) {
    state.repos = repos
    state.reposCount = _.toString(_.size(repos))
    state.untaggedCount = _.toString(_.size(_.filter(repos, _.matches({ 'language': 'null' }))))
  },

  [types.FILTER_BY_LANGUAGE] (state, { lang }) {
    state.repos = _.isNull(lang)
      ? state.lazyRepos
      : _.filter(state.lazyRepos, _.matches({ 'language': lang }))
    state.activeLang = lang
  },

  [types.ORDERED_REPOS] (state, { orderField }) {
    state.repos = state.order > 0
      ? _.orderBy(state.repos, orderField)
      : _.orderBy(state.repos, orderField, 'desc')
    state.order = state.order * -1
  },

  [types.SET_SEARCH_QUERY] (state, { searchQuery }) {
    state.searchQuery = searchQuery
    state.repos = _.isNull(searchQuery) || searchQuery === ''
      ? state.lazyRepos
      : _.filter(state.repos, function (o) {
        return _.includes(o.repo_name, searchQuery) || _.includes(o.description, searchQuery)
      })
  },

  // [types.SET_LANG_GROUP] (state, payload) {
  //   const { langGroup } = state
  //   db.removeLangGroup()
  //   langGroup.forEach((v, i) => {
  //     v._id = i + 1
  //     db.addLangGroup(v, _ => {})
  //   })
  // },

  [types.ADD_LANG_GROUP] (state, payload) {
    state.langGroup.push(payload.newTag)
  }
}

export default {
  state,
  actions,
  mutations
}