text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/modules/taggenerationandmusicreco.iml" filepath="$PROJECT_DIR$/.idea/modules/taggenerationandmusicreco.iml" />
      <module fileurl="file://$PROJECT_DIR$/.idea/modules/taggenerationandmusicreco-build.iml" filepath="$PROJECT_DIR$/.idea/modules/taggenerationandmusicreco-build.iml" />
    </modules>
  </component>
</project>


text:
<component name="libraryTable">
  <library name="SBT: org.apache.httpcomponents:httpmime:4.5.2:jar">
    <CLASSES>
      <root url="jar://$USER_HOME$/.ivy2/cache/org.apache.httpcomponents/httpmime/jars/httpmime-4.5.2.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$USER_HOME$/.ivy2/cache/org.apache.httpcomponents/httpmime/srcs/httpmime-4.5.2-sources.jar!/" />
    </SOURCES>
  </library>
</component>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;

namespace Alachisoft.NCache.SocketServer.EventTask
{
    /// <summary>
    /// This event is fired when cache is stoped
    /// </summary>
	internal sealed class CacheStoppedEvent : IEventTask
	{
		private string _cacheId;
        private string _clientId;

		internal CacheStoppedEvent(string cacheId,string clientId)
		{
			_cacheId = cacheId;
            _clientId = clientId;
		}

        public void Process()
        {
            ClientManager clientManager = null;

            lock (ConnectionManager.ConnectionTable) clientManager = (ClientManager)ConnectionManager.ConnectionTable[_clientId];
            if (clientManager != null)
            {
                Alachisoft.NCache.Common.Protobuf.Response response = new Alachisoft.NCache.Common.Protobuf.Response();
                response.cacheStopped = Alachisoft.NCache.SocketServer.Util.EventHelper.GetCacheStoppedEventResponse(_cacheId);
                response.responseType = Alachisoft.NCache.Common.Protobuf.Response.Type.CACHE_STOPPED_EVENT;
                IList serializedResponse = Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response,Common.Protobuf.Response.Type.CACHE_STOPPED_EVENT);

                ConnectionManager.AssureSend(clientManager, serializedResponse, false);
            }
        }
    }
}


text:
package com.baidubce.services.ses.model;

/**
 * Response object of getting failed reason, which contains all of reasons while sending email failure.
 */
public class GetFailedReasonResponse extends SesResponse {
    private Integer accsize;
    private Integer address;
    private Integer quotaoverflow;
    private Integer recptcnt;
    private Integer spammail;
    private Integer title;
    private Integer verification;
    private Integer virusmail;
    private Integer emptysender;

    public GetFailedReasonResponse() {
    }

    public GetFailedReasonResponse(Integer accsize, Integer address, Integer quotaoverflow, Integer recptcnt,
            Integer spammail, Integer title, Integer verification, Integer virusmail, Integer emptysender) {
        this.accsize = accsize;
        this.address = address;
        this.quotaoverflow = quotaoverflow;
        this.recptcnt = recptcnt;
        this.spammail = spammail;
        this.title = title;
        this.verification = verification;
        this.virusmail = virusmail;
        this.emptysender = emptysender;
    }

    public Integer getAccsize() {
        return accsize;
    }

    public void setAccsize(Integer accsize) {
        this.accsize = accsize;
    }

    public Integer getAddress() {
        return address;
    }

    public void setAddress(Integer address) {
        this.address = address;
    }

    public Integer getQuotaoverflow() {
        return quotaoverflow;
    }

    public void setQuotaoverflow(Integer quotaoverflow) {
        this.quotaoverflow = quotaoverflow;
    }

    public Integer getRecptcnt() {
        return recptcnt;
    }

    public void setRecptcnt(Integer recptcnt) {
        this.recptcnt = recptcnt;
    }

    public Integer getSpammail() {
        return spammail;
    }

    public void setSpammail(Integer spammail) {
        this.spammail = spammail;
    }

    public Integer getTitle() {
        return title;
    }

    public void setTitle(Integer title) {
        this.title = title;
    }

    public Integer getVerification() {
        return verification;
    }

    public void setVerification(Integer verification) {
        this.verification = verification;
    }

    public Integer getVirusmail() {
        return virusmail;
    }

    public void setVirusmail(Integer virusmail) {
        this.virusmail = virusmail;
    }

    public Integer getEmptysender() {
        return emptysender;
    }

    public void setEmptysender(Integer emptysender) {
        this.emptysender = emptysender;
    }

    @Override
    public String toString() {
        return "GetFailedReasonResponse [accsize=" + accsize + ", address=" + address + ", quotaoverflow="
                + quotaoverflow + ", recptcnt=" + recptcnt + ", spammail=" + spammail + ", title=" + title
                + ", verification=" + verification + ", virusmail=" + virusmail + ", emptysender=" + emptysender + "]";
    }

}


text:
package com.atinternet.tracker;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

@Config(sdk = 21)
@RunWith(RobolectricTestRunner.class)
public class LiveVideosTest extends AbstractTestClass {

    private LiveVideos liveVideos;

    @Before
    public void setUp() throws Exception {
        super.setUp();
        MediaPlayer player = new MediaPlayer(tracker);
        liveVideos = new LiveVideos(player);
    }

    @Test
    public void initTest() {
        assertTrue(true);
    }

    @Test
    public void addOneTest() {
        liveVideos.add("name");
        assertEquals(1, liveVideos.list.size());
    }

    @Test
    public void addTwoTest() {
        liveVideos.add("name", "chapter1");
        assertEquals(1, liveVideos.list.size());
    }

    @Test
    public void addThreeTest() {
        liveVideos.add("name", "chapter1", "chapter2");
        assertEquals(1, liveVideos.list.size());
    }

    @Test
    public void addFourTest() {
        liveVideos.add("name", "chapter1", "chapter2", "chapter3");
        assertEquals(1, liveVideos.list.size());
    }

    @Test
    public void removeTest() {
        LiveVideo v1 = liveVideos.add("name");
        LiveVideo v2 = liveVideos.add("other");
        liveVideos.add("lv3");
        assertEquals(3, liveVideos.list.size());

        liveVideos.remove("name");
        assertEquals(2, liveVideos.list.size());
        assertFalse(liveVideos.list.contains(v1));
        assertTrue(liveVideos.list.contains(v2));
    }

    @Test
    public void removeAllTest() {
        liveVideos.add("name");
        liveVideos.add("toto");
        liveVideos.add("titi");
        assertEquals(3, liveVideos.list.size());

        liveVideos.removeAll();
        assertEquals(0, liveVideos.list.size());

    }
}


text:
package org.apache.predictionio.examples.classification

import org.apache.predictionio.controller.EngineFactory
import org.apache.predictionio.controller.Engine

// MODIFIED
case class Query(
  featureA : Double,
  featureB : Double,
  featureC : Double,
  featureD : Double
)

case class PredictedResult(
  label: Double
)

case class ActualResult(
  label: Double
)

object ClassificationEngine extends EngineFactory {
  def apply() = {
    new Engine(
      classOf[DataSource],
      classOf[Preparator],
      Map("naive" -> classOf[NaiveBayesAlgorithm]),
      classOf[Serving])
  }
}


text:
#include "test_ni_pointer.nit.h"

/*
C implementation of test_ni_pointer::A::init
*/
A new_A___impl(  )
{
	int* v = (int*)malloc( sizeof(int) );
	(*v) = 123;
	return (A)v;
}

/*
C implementation of test_ni_pointer::A::(string::Object::to_s)

Imported methods signatures:
	String NativeString_to_s( char * str ) for string::NativeString::to_s
*/
String A_to_s___impl( A recv )
{
	char* s = calloc( 256, sizeof(char) );
	sprintf( s, "%d", *((int*)recv) );
	return NativeString_to_s( s );
}


text:
/*
 * File:   P3.h
 * Author: Rolando Martins (rolando.martins@gmail.com)
 *
 * Created on April 30, 2010, 11:50 AM
 */

#ifndef P3_H
#define	P3_H
#include "ace/svc_export.h"
#include "ace/Service_Config.h"
#include <stheno/core/p2p/Overlay.h>

class Stheno;

class P3Mesh;
class P3Discovery;
class P3FaultTolerance;
class SuperPeerDiscovery;
class P3 : public Overlay {
public:
    P3(){}
    P3(SthenoCoreInterface* runtime);
    virtual ~P3();

    //virtual SuperPeerDiscovery* getP3Discovery();
    //virtual P3Mesh* getP3MeshService();

protected:
    //SuperPeerDiscovery* m_discoveryService;
    //P3Mesh* m_meshService;
};

#endif	/* P3_H */


text:
@class DBTEAMMembersListArg;

#pragma mark - API Object

///
/// The `MembersListArg` struct.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBTEAMMembersListArg : NSObject <DBSerializable, NSCopying>

#pragma mark - Instance fields

/// Number of results to return per call.
@property (nonatomic, readonly) NSNumber * _Nonnull limit;

/// Whether to return removed members.
@property (nonatomic, readonly) NSNumber * _Nonnull includeRemoved;

#pragma mark - Constructors

///
/// Full constructor for the struct (exposes all instance variables).
///
/// @param limit Number of results to return per call.
/// @param includeRemoved Whether to return removed members.
///
/// @return An initialized instance.
///
- (nonnull instancetype)initWithLimit:(NSNumber * _Nullable)limit includeRemoved:(NSNumber * _Nullable)includeRemoved;

///
/// Convenience constructor (exposes only non-nullable instance variables with
/// no default value).
///
///
/// @return An initialized instance.
///
- (nonnull instancetype)initDefault;

- (nonnull instancetype)init NS_UNAVAILABLE;

@end

#pragma mark - Serializer Object

///
/// The serialization class for the `MembersListArg` struct.
///
@interface DBTEAMMembersListArgSerializer : NSObject

///
/// Serializes `DBTEAMMembersListArg` instances.
///
/// @param instance An instance of the `DBTEAMMembersListArg` API object.
///
/// @return A json-compatible dictionary representation of the
/// `DBTEAMMembersListArg` API object.
///
+ (NSDictionary * _Nonnull)serialize:(DBTEAMMembersListArg * _Nonnull)instance;

///
/// Deserializes `DBTEAMMembersListArg` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBTEAMMembersListArg` API object.
///
/// @return An instantiation of the `DBTEAMMembersListArg` object.
///
+ (DBTEAMMembersListArg * _Nonnull)deserialize:(NSDictionary * _Nonnull)dict;

@end


text:
#include <aws/docdb/model/CreateDBClusterRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::DocDB::Model;
using namespace Aws::Utils;

CreateDBClusterRequest::CreateDBClusterRequest() :
    m_availabilityZonesHasBeenSet(false),
    m_backupRetentionPeriod(0),
    m_backupRetentionPeriodHasBeenSet(false),
    m_dBClusterIdentifierHasBeenSet(false),
    m_dBClusterParameterGroupNameHasBeenSet(false),
    m_vpcSecurityGroupIdsHasBeenSet(false),
    m_dBSubnetGroupNameHasBeenSet(false),
    m_engineHasBeenSet(false),
    m_engineVersionHasBeenSet(false),
    m_port(0),
    m_portHasBeenSet(false),
    m_masterUsernameHasBeenSet(false),
    m_masterUserPasswordHasBeenSet(false),
    m_preferredBackupWindowHasBeenSet(false),
    m_preferredMaintenanceWindowHasBeenSet(false),
    m_tagsHasBeenSet(false),
    m_storageEncrypted(false),
    m_storageEncryptedHasBeenSet(false),
    m_kmsKeyIdHasBeenSet(false),
    m_preSignedUrlHasBeenSet(false),
    m_enableCloudwatchLogsExportsHasBeenSet(false),
    m_deletionProtection(false),
    m_deletionProtectionHasBeenSet(false),
    m_globalClusterIdentifierHasBeenSet(false),
    m_sourceRegionHasBeenSet(false)
{
}

Aws::String CreateDBClusterRequest::SerializePayload() const
{
  Aws::StringStream ss;
  ss << "Action=CreateDBCluster&";
  if(m_availabilityZonesHasBeenSet)
  {
    unsigned availabilityZonesCount = 1;
    for(auto& item : m_availabilityZones)
    {
      ss << "AvailabilityZones.member." << availabilityZonesCount << "="
          << StringUtils::URLEncode(item.c_str()) << "&";
      availabilityZonesCount++;
    }
  }

  if(m_backupRetentionPeriodHasBeenSet)
  {
    ss << "BackupRetentionPeriod=" << m_backupRetentionPeriod << "&";
  }

  if(m_dBClusterIdentifierHasBeenSet)
  {
    ss << "DBClusterIdentifier=" << StringUtils::URLEncode(m_dBClusterIdentifier.c_str()) << "&";
  }

  if(m_dBClusterParameterGroupNameHasBeenSet)
  {
    ss << "DBClusterParameterGroupName=" << StringUtils::URLEncode(m_dBClusterParameterGroupName.c_str()) << "&";
  }

  if(m_vpcSecurityGroupIdsHasBeenSet)
  {
    unsigned vpcSecurityGroupIdsCount = 1;
    for(auto& item : m_vpcSecurityGroupIds)
    {
      ss << "VpcSecurityGroupIds.member." << vpcSecurityGroupIdsCount << "="
          << StringUtils::URLEncode(item.c_str()) << "&";
      vpcSecurityGroupIdsCount++;
    }
  }

  if(m_dBSubnetGroupNameHasBeenSet)
  {
    ss << "DBSubnetGroupName=" << StringUtils::URLEncode(m_dBSubnetGroupName.c_str()) << "&";
  }

  if(m_engineHasBeenSet)
  {
    ss << "Engine=" << StringUtils::URLEncode(m_engine.c_str()) << "&";
  }

  if(m_engineVersionHasBeenSet)
  {
    ss << "EngineVersion=" << StringUtils::URLEncode(m_engineVersion.c_str()) << "&";
  }

  if(m_portHasBeenSet)
  {
    ss << "Port=" << m_port << "&";
  }

  if(m_masterUsernameHasBeenSet)
  {
    ss << "MasterUsername=" << StringUtils::URLEncode(m_masterUsername.c_str()) << "&";
  }

  if(m_masterUserPasswordHasBeenSet)
  {
    ss << "MasterUserPassword=" << StringUtils::URLEncode(m_masterUserPassword.c_str()) << "&";
  }

  if(m_preferredBackupWindowHasBeenSet)
  {
    ss << "PreferredBackupWindow=" << StringUtils::URLEncode(m_preferredBackupWindow.c_str()) << "&";
  }

  if(m_preferredMaintenanceWindowHasBeenSet)
  {
    ss << "PreferredMaintenanceWindow=" << StringUtils::URLEncode(m_preferredMaintenanceWindow.c_str()) << "&";
  }

  if(m_tagsHasBeenSet)
  {
    unsigned tagsCount = 1;
    for(auto& item : m_tags)
    {
      item.OutputToStream(ss, "Tags.member.", tagsCount, "");
      tagsCount++;
    }
  }

  if(m_storageEncryptedHasBeenSet)
  {
    ss << "StorageEncrypted=" << std::boolalpha << m_storageEncrypted << "&";
  }

  if(m_kmsKeyIdHasBeenSet)
  {
    ss << "KmsKeyId=" << StringUtils::URLEncode(m_kmsKeyId.c_str()) << "&";
  }

  if(m_preSignedUrlHasBeenSet)
  {
    ss << "PreSignedUrl=" << StringUtils::URLEncode(m_preSignedUrl.c_str()) << "&";
  }

  if(m_enableCloudwatchLogsExportsHasBeenSet)
  {
    unsigned enableCloudwatchLogsExportsCount = 1;
    for(auto& item : m_enableCloudwatchLogsExports)
    {
      ss << "EnableCloudwatchLogsExports.member." << enableCloudwatchLogsExportsCount << "="
          << StringUtils::URLEncode(item.c_str()) << "&";
      enableCloudwatchLogsExportsCount++;
    }
  }

  if(m_deletionProtectionHasBeenSet)
  {
    ss << "DeletionProtection=" << std::boolalpha << m_deletionProtection << "&";
  }

  if(m_globalClusterIdentifierHasBeenSet)
  {
    ss << "GlobalClusterIdentifier=" << StringUtils::URLEncode(m_globalClusterIdentifier.c_str()) << "&";
  }

  ss << "Version=2014-10-31";
  return ss.str();
}

void  CreateDBClusterRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
{
  uri.SetQueryString(SerializePayload());
}


text:
<?php

namespace dektrium\user;

use Yii;
use yii\authclient\Collection;
use yii\base\BootstrapInterface;
use yii\console\Application as ConsoleApplication;
use yii\i18n\PhpMessageSource;

/**
 * Bootstrap class registers module and user application component. It also creates some url rules which will be applied
 * when UrlManager.enablePrettyUrl is enabled.
 *
 * @author Dmitry Erofeev <dmeroff@gmail.com>
 */
class Bootstrap implements BootstrapInterface
{
    /** @var array Model's map */
    private $_modelMap = [
        'User'             => 'dektrium\user\models\User',
        'Account'          => 'dektrium\user\models\Account',
        'Profile'          => 'dektrium\user\models\Profile',
        'Token'            => 'dektrium\user\models\Token',
        'RegistrationForm' => 'dektrium\user\models\RegistrationForm',
        'ResendForm'       => 'dektrium\user\models\ResendForm',
        'LoginForm'        => 'dektrium\user\models\LoginForm',
        'SettingsForm'     => 'dektrium\user\models\SettingsForm',
        'RecoveryForm'     => 'dektrium\user\models\RecoveryForm',
        'UserSearch'       => 'dektrium\user\models\UserSearch',
    ];

    /** @inheritdoc */
    public function bootstrap($app)
    {
        /** @var Module $module */
        /** @var \yii\db\ActiveRecord $modelName */
        if ($app->hasModule('user') && ($module = $app->getModule('user')) instanceof Module) {
            $this->_modelMap = array_merge($this->_modelMap, $module->modelMap);
            foreach ($this->_modelMap as $name => $definition) {
                $class = "dektrium\\user\\models\\" . $name;
                Yii::$container->set($class, $definition);
                $modelName = is_array($definition) ? $definition['class'] : $definition;
                $module->modelMap[$name] = $modelName;
                if (in_array($name, ['User', 'Profile', 'Token', 'Account'])) {
                    Yii::$container->set($name . 'Query', function () use ($modelName) {
                        return $modelName::find();
                    });
                }
            }

            Yii::$container->setSingleton(Finder::className(), [
                'userQuery'    => Yii::$container->get('UserQuery'),
                'profileQuery' => Yii::$container->get('ProfileQuery'),
                'tokenQuery'   => Yii::$container->get('TokenQuery'),
                'accountQuery' => Yii::$container->get('AccountQuery'),
            ]);

            if ($app instanceof ConsoleApplication) {
                $module->controllerNamespace = 'dektrium\user\commands';
            } else {
                Yii::$container->set('yii\web\User', [
                    'enableAutoLogin' => true,
                    'loginUrl' => ['/user/security/login'],
                    'identityClass' => $module->modelMap['User'],
                ]);

                $configUrlRule = [
                    'prefix' => $module->urlPrefix,
                    'rules'  => $module->urlRules,
                ];

                if ($module->urlPrefix != 'user') {
                    $configUrlRule['routePrefix'] = 'user';
                }

                $configUrlRule['class'] = 'yii\web\GroupUrlRule';
                $rule = Yii::createObject($configUrlRule);

                $app->urlManager->addRules([$rule], false);

                if (!$app->has('authClientCollection')) {
                    $app->set('authClientCollection', [
                        'class' => Collection::className(),
                    ]);
                }
            }

            if (!isset($app->get('i18n')->translations['user*'])) {
                $app->get('i18n')->translations['user*'] = [
                    'class' => PhpMessageSource::className(),
                    'basePath' => __DIR__ . '/messages',
                    'sourceLanguage' => 'en-US'
                ];
            }

            Yii::$container->set('dektrium\user\Mailer', $module->mailer);

            $module->debug = $this->ensureCorrectDebugSetting();
        }
    }

    /** Ensure the module is not in DEBUG mode on production environments */
    public function ensureCorrectDebugSetting()
    {
        if (!defined('YII_DEBUG')) {
            return false;
        }
        if (!defined('YII_ENV')) {
            return false;
        }
        if (defined('YII_ENV') && YII_ENV !== 'dev') {
            return false;
        }
        if (defined('YII_DEBUG') && YII_DEBUG !== true) {
            return false;
        }

        return Yii::$app->getModule('user')->debug;
    }
}


text:
#if !defined(BOOST_SPIRIT_ISTREAM_POLICY_JAN_04_2010_0130PM)
#define BOOST_SPIRIT_ISTREAM_POLICY_JAN_04_2010_0130PM

#include <boost/spirit/home/support/iterators/multi_pass_fwd.hpp>
#include <boost/spirit/home/support/iterators/detail/multi_pass.hpp>

namespace boost { namespace spirit { namespace iterator_policies
{
    ///////////////////////////////////////////////////////////////////////////
    //  class istream
    //  Implementation of the InputPolicy used by multi_pass
    //
    //  The istream encapsulates an std::basic_istream
    ///////////////////////////////////////////////////////////////////////////
    struct istream
    {
        ///////////////////////////////////////////////////////////////////////
        template <typename T>
        class unique // : public detail::default_input_policy
        {
        private:
            typedef typename T::char_type result_type;

        public:
            typedef typename T::off_type difference_type;
            typedef typename T::off_type distance_type;
            typedef result_type const* pointer;
            typedef result_type const& reference;
            typedef result_type value_type;

        protected:
            unique() {}
            explicit unique(T&) {}

            void swap(unique&) {}

        public:
            template <typename MultiPass>
            static void destroy(MultiPass&) {}

            template <typename MultiPass>
            static typename MultiPass::reference get_input(MultiPass& mp)
            {
                if (!mp.shared()->initialized_)
                    mp.shared()->read_one();
                return mp.shared()->curtok_;
            }

            template <typename MultiPass>
            static void advance_input(MultiPass& mp)
            {
                // We invalidate the currently cached input character to avoid
                // reading more input from the underlying iterator than
                // required. Without this we would always read ahead one
                // character, even if this character never gets consumed by the
                // client.
                mp.shared()->peek_one();
            }

            // test, whether we reached the end of the underlying stream
            template <typename MultiPass>
            static bool input_at_eof(MultiPass const& mp)
            {
                return mp.shared()->eof_reached_;
            }

            template <typename MultiPass>
            static bool input_is_valid(MultiPass const& mp, value_type const& t)
            {
                return mp.shared()->initialized_;
            }

            // no unique data elements
        };

        ///////////////////////////////////////////////////////////////////////
        template <typename T>
        struct shared
        {
        private:
            typedef typename T::char_type result_type;

        public:
            explicit shared(T& input)
              : input_(input), curtok_(-1)
              , initialized_(false), eof_reached_(false)
            {}

            void read_one()
            {
                if (!(input_ >> curtok_)) {
                    initialized_ = false;
                    eof_reached_ = true;
                }
                else {
                    initialized_ = true;
                }
            }

            void peek_one()
            {
                input_.peek();    // try for eof
                initialized_ = false;
                eof_reached_ = input_.eof();
            }

            T& input_;
            result_type curtok_;
            bool initialized_;
            bool eof_reached_;
        };
    };

}}}

#endif


text:
package fed.fdbs;

/**
 * It implements the Runnable interface. A thread is created by FDBSFacade and added to the ShutdownHook.
 * This thread will then be executed at the end of the java application. This component calls the method
 * to drop all the temporal tables.
 *
 */
public class FedShutdown implements Runnable {

    /* (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run () {
        if (FedConfig.getDb1Name() != null) {
            FedCatalog.dropTempTables();
        }
    }

}


text:
namespace dm_robotics {
namespace {

// Constructs an LsqpStackOfTasksSolver::Parameters object from
// a Cartesian6dToJointVelocityMapper::Parameters object.
LsqpStackOfTasksSolver::Parameters ToLsqpParams(
    const Cartesian6dToJointVelocityMapper::Parameters& params) {
  LsqpStackOfTasksSolver::Parameters output_params;
  output_params.absolute_tolerance = params.solution_tolerance;
  output_params.relative_tolerance = 0.0;
  output_params.hierarchical_projection_slack =
      params.nullspace_projection_slack;
  output_params.use_adaptive_rho = params.use_adaptive_step_size;

  // We always ensure that the infeasibility tolerance is less than the absolute
  // tolerance, by making them a tenth of the absolute tolerance. This prevents
  // the optimizer from thinking a solution is infeasible too easily.
  output_params.primal_infeasibility_tolerance =
      0.1 * params.solution_tolerance;
  output_params.dual_infeasibility_tolerance = 0.1 * params.solution_tolerance;

  // If nullspace failures do not return an error, add a warning when it fails
  // if `log_nullspace_failure_warnings` is `true`.
  output_params.return_error_on_nullspace_failure =
      params.return_error_on_nullspace_failure;
  if (!params.return_error_on_nullspace_failure &&
      params.log_nullspace_failure_warnings) {
    output_params.verbosity =
        LsqpStackOfTasksSolver::Parameters::VerboseFlags::kNullspaceWarnings;
  } else {
    output_params.verbosity =
        LsqpStackOfTasksSolver::Parameters::VerboseFlags::kNone;
  }
  return output_params;
}

// Constructs a Cartesian6dVelocityTaskParameters object from
// a Cartesian6dToJointVelocityMapper::Parameters object.
Cartesian6dVelocityTask::Parameters ToCartesianVelocityParams(
    const Cartesian6dToJointVelocityMapper::Parameters& params) {
  Cartesian6dVelocityTask::Parameters output_params;
  output_params.lib = params.lib;
  output_params.model = params.model;
  output_params.joint_ids = params.joint_ids;
  output_params.object_type = params.object_type;
  output_params.object_name = params.object_name;
  output_params.weighting_matrix =
      params.cartesian_velocity_task_weighting_matrix;
  return output_params;
}

// Constructs a CollisionAvoidanceConstraintParameters object from
// a Cartesian6dToJointVelocityMapper::Parameters object.
CollisionAvoidanceConstraint::Parameters ToCollisionAvoidanceParams(
    const Cartesian6dToJointVelocityMapper::Parameters& params) {
  CollisionAvoidanceConstraint::Parameters output_params;
  output_params.lib = params.lib;
  output_params.model = params.model;
  output_params.collision_detection_distance =
      params.collision_detection_distance;
  output_params.minimum_normal_distance =
      params.minimum_distance_from_collisions;
  output_params.gain = params.collision_avoidance_normal_velocity_scale /
                       absl::ToDoubleSeconds(params.integration_timestep);

  // We add a negative offset on the upper bound of each collision avoidance
  // constraint to prevent violations due to numerical errors. This is because
  // OSQP constraint violations depend on the solution tolerance, and thus the
  // computed velocities may result in the normal velocity penetrating the
  // minimum allowable distance.
  // Although this effectively removes the zero-vector as an always valid
  // solution to the optimization problem, we found in practice that it prevents
  // collisions due to compounded numerical integration errors without
  // noticeably making the problem more difficult to solve.
  output_params.bound_relaxation = -params.solution_tolerance;

  output_params.joint_ids = params.joint_ids;

  // Similar to MuJoCo, we do not allow parent-child collisions. However, unlike
  // MuJoCo, we only allow collisions with the worldbody geoms if the pair is
  // explicitly specified. This is because in robot environments, the first body
  // of the kinematic chain may be welded to the worldbody, and MuJoCo's default
  // behaviour would result in collisions between this first body and its child,
  // even though they have a parent-child relationship. This is not necessary
  // for most robot environments, as joint limits are such that parent-children
  // cannot collide.
  output_params.geom_pairs = CollisionPairsToGeomIdPairs(
      *params.lib, *params.model, params.collision_pairs, false, false);
  return output_params;
}

// Constructs a JointPositionLimitConstraintParameters object from
// a Cartesian6dToJointVelocityMapper::Parameters object.
JointPositionLimitConstraint::Parameters ToJointPositionLimitParams(
    const Cartesian6dToJointVelocityMapper::Parameters& params) {
  JointPositionLimitConstraint::Parameters output_params;
  output_params.model = params.model;
  output_params.min_distance_from_limits =
      params.minimum_distance_from_joint_position_limit;
  output_params.gain = params.joint_position_limit_velocity_scale /
                       absl::ToDoubleSeconds(params.integration_timestep);
  output_params.joint_ids = params.joint_ids;
  return output_params;
}

// Constructs a JointAccelerationConstraintParameters object from
// a Cartesian6dToJointVelocityMapper::Parameters object.
JointAccelerationConstraint::Parameters ToJointAccelerationLimitParams(
    const Cartesian6dToJointVelocityMapper::Parameters& params) {
  JointAccelerationConstraint::Parameters output_params;
  output_params.model = params.model;
  output_params.joint_ids = params.joint_ids;
  output_params.integration_timestep = params.integration_timestep;
  output_params.acceleration_magnitude_limits =
      params.joint_acceleration_magnitude_limits;
  return output_params;
}

// Clips each element in `values` to be within the respective elements in
// `lower_bound` and `upper_bound`. All arrays are assumed to be the same size.
void ClipToBounds(absl::Span<const double> lower_bound,
                  absl::Span<const double> upper_bound,
                  absl::Span<double> values) {
  for (int i = 0; i < values.size(); ++i) {
    values[i] = std::clamp(values[i], lower_bound[i], upper_bound[i]);
  }
}

// For each pair of geoms, computes the minimum distance between both geoms by
// using MuJoCo's collision detection mechanism with
// `collision_detection_distance` as the margin. If several contacts are
// detected, only the smallest distance is saved. If no contacts are detected,
// no value will be set for that pair.
void ComputeGeomPairDist(
    const MjLib& lib, const mjModel& model, const mjData& data,
    double collision_detection_distance,
    absl::btree_map<std::pair<int, int>, absl::optional<double>>*
        geom_pair_dist) {
  for (auto& [pair, maybe_dist] : *geom_pair_dist) {
    maybe_dist =
        ComputeMinimumContactDistance(lib, model, data, pair.first, pair.second,
                                      collision_detection_distance);
  }
}

// Integrates MuJoCo positions with an array of `joint_velocities`, ordered
// according to the `joint_dof_ids` object.
void IntegrateQpos(const MjLib& lib, const mjModel& model,
                   absl::Duration integration_timestep,
                   const absl::btree_set<int>& joint_dof_ids,
                   absl::Span<const double> joint_velocities, mjData* data) {
  int joint_velocity_idx = 0;
  for (int dof_id : joint_dof_ids) {
    data->qvel[dof_id] = joint_velocities[joint_velocity_idx];
    ++joint_velocity_idx;
  }
  lib.mj_integratePos(&model, data->qpos, data->qvel,
                      absl::ToDoubleSeconds(integration_timestep));
}

// Returns true if penetration is increased for any geom pair, false otherwise.
// Penetration is increased if the objects are penetrating and the distance
// becomes more negative, or if the objects were not penetrating and start
// panetrating after. If this function returns true, penetrating_pair is filled
// with the offending geoms IDs.
//
// Assumes both maps have exactly the same keys.
bool IsPenetrationIncreased(
    double minimum_distance_from_collisions,
    const absl::btree_map<std::pair<int, int>, absl::optional<double>>&
        geom_pair_dist_before,
    const absl::btree_map<std::pair<int, int>, absl::optional<double>>&
        geom_pair_dist_after,
    std::pair<int, int>* penetrating_pair) {
  auto before = geom_pair_dist_before.begin();
  auto after = geom_pair_dist_after.begin();
  while (before != geom_pair_dist_before.end()) {
    const auto& [pair_after, maybe_dist_after] = *after;
    const auto& [pair_before, maybe_dist_before] = *before;
    bool has_penetration_after =
        maybe_dist_after.has_value() &&
        maybe_dist_after.value() < minimum_distance_from_collisions;
    bool penetration_increased =
        has_penetration_after &&
        (!maybe_dist_before.has_value() ||
         maybe_dist_before.value() > maybe_dist_after.value());
    if (penetration_increased) {
      *penetrating_pair = pair_after;
      return true;
    }
    ++before;
    ++after;
  }
  return false;
}

// Returns an OK status if all the geoms in `group` are valid geoms in `model`.
absl::Status ValidateGeomGroup(const MjLib& lib, const mjModel& model,
                               const GeomGroup& group) {
  for (const auto& name : group) {
    bool is_name_found =
        lib.mj_name2id(&model, mjtObj::mjOBJ_GEOM, name.c_str()) >= 0;
    if (!is_name_found) {
      return absl::NotFoundError(
          absl::Substitute("ValidateGeomGroup: Could not find MuJoCo geom with "
                           "name [$0] in the provided model.",
                           name));
    }
  }
  return absl::OkStatus();
}

}  // namespace

absl::Status Cartesian6dToJointVelocityMapper::ValidateParameters(
    const Parameters& params) {
  if (params.lib == nullptr) {
    return absl::InvalidArgumentError(
        "ValidateParameters: `lib` cannot be null.");
  }
  if (params.model == nullptr) {
    return absl::InvalidArgumentError(
        "ValidateParameters: `model` cannot be null.");
  }
  if (params.joint_ids.empty()) {
    return absl::InvalidArgumentError(
        "ValidateParameters: `joint_ids` cannot be empty.");
  }

  for (int joint_id : params.joint_ids) {
    if (joint_id < 0 || joint_id >= params.model->njnt)
      return absl::OutOfRangeError(absl::Substitute(
          "ValidateParameters: Provided joint_id [$0] is invalid for the "
          "provided model, which has [$1] joints.",
          joint_id, params.model->njnt));
  }

  int number_of_dof = JointIdsToDofIds(*params.model, params.joint_ids).size();
  if (number_of_dof != params.joint_ids.size()) {
    return absl::InvalidArgumentError(absl::Substitute(
        "ValidateParameters: `joint_ids` must only contain 1 DoF joints. "
        "Number of joints [$0]; number of DoF [$1].",
        params.joint_ids.size(), number_of_dof));
  }

  bool is_object_type_valid = params.object_type == mjtObj::mjOBJ_BODY ||
                              params.object_type == mjtObj::mjOBJ_GEOM ||
                              params.object_type == mjtObj::mjOBJ_SITE;
  if (!is_object_type_valid)
    return absl::InvalidArgumentError(absl::Substitute(
        "ValidateParameters: Objects of type [$0] are not supported. Only "
        "bodies, geoms, and sites are supported.",
        params.lib->mju_type2Str(params.object_type)));

  bool is_object_found =
      params.lib->mj_name2id(params.model, params.object_type,
                             params.object_name.c_str()) >= 0;
  if (!is_object_found)
    return absl::NotFoundError(absl::Substitute(
        "ValidateParameters: Could not find MuJoCo object with name [$0] and "
        "type [$1] in the provided model.",
        params.object_name, params.lib->mju_type2Str(params.object_type)));

  if (params.integration_timestep <= absl::ZeroDuration()) {
    return absl::InvalidArgumentError(
        absl::Substitute("ValidateParameters: `integration_timestep` [$0 s] "
                         "must be a positive duration.",
                         absl::ToDoubleSeconds(params.integration_timestep)));
  }

  if (params.enable_joint_velocity_limits) {
    if (params.joint_velocity_magnitude_limits.size() != number_of_dof) {
      return absl::InvalidArgumentError(absl::Substitute(
          "ValidateParameters: joint velocity limits are enabled but size of "
          "`joint_velocity_magnitude_limits` [$0] does not match the number of "
          "DoF [$1].",
          params.joint_velocity_magnitude_limits.size(), number_of_dof));
    }
  }

  if (params.enable_joint_acceleration_limits) {
    if (params.joint_acceleration_magnitude_limits.size() != number_of_dof) {
      return absl::InvalidArgumentError(absl::Substitute(
          "ValidateParameters: joint acceleration limits are enabled but size "
          "of `joint_acceleration_magnitude_limits` [$0] does not match the "
          "number of DoF [$1].",
          params.joint_acceleration_magnitude_limits.size(), number_of_dof));
    }
  }

  for (const auto& collision_pair : params.collision_pairs) {
    RETURN_IF_ERROR(
        ValidateGeomGroup(*params.lib, *params.model, collision_pair.first));
    RETURN_IF_ERROR(
        ValidateGeomGroup(*params.lib, *params.model, collision_pair.second));
  }

  if (params.max_cartesian_velocity_control_iterations <= 0) {
    return absl::InvalidArgumentError(absl::Substitute(
        "ValidateParameters: `max_cartesian_velocity_control_iterations` [$0] "
        "must be positive.",
        params.max_cartesian_velocity_control_iterations));
  }

  if (params.solution_tolerance <= 0.0) {
    return absl::InvalidArgumentError(absl::Substitute(
        "ValidateParameters: `solution_tolerance` [$0] must be positive.",
        params.solution_tolerance));
  }

  if (params.enable_nullspace_control) {
    if (params.max_nullspace_control_iterations <= 0) {
      return absl::InvalidArgumentError(absl::Substitute(
          "ValidateParameters: `max_nullspace_control_iterations` [$0] must be "
          "positive if nullspace control is enabled.",
          params.max_nullspace_control_iterations));
    }
    if (params.nullspace_projection_slack <= 0) {
      return absl::InvalidArgumentError(absl::Substitute(
          "ValidateParameters: `nullspace_projection_slack` [$0] must be "
          "positive if nullspace control is enabled.",
          params.nullspace_projection_slack));
    }
  }
  return absl::OkStatus();
}

Cartesian6dToJointVelocityMapper::Cartesian6dToJointVelocityMapper(
    const Parameters& params)
    : lib_(*DieIfNull(params.lib)),
      model_(*DieIfNull(params.model)),
      data_(lib_.mj_makeData(&model_), lib_.mj_deleteData),
      joint_dof_ids_(JointIdsToDofIds(model_, params.joint_ids)),
      integration_timestep_(params.integration_timestep),
      clamp_nullspace_bias_to_feasible_space_(
          params.clamp_nullspace_bias_to_feasible_space),
      remove_joint_acceleration_limits_if_in_conflict_(
          params.remove_joint_acceleration_limits_if_in_conflict),
      minimum_distance_from_collisions_(
          params.minimum_distance_from_collisions),
      qp_solver_(ToLsqpParams(params)),
      solution_(joint_dof_ids_.size()),
      check_solution_validity_(params.check_solution_validity),
      log_collision_warnings_(params.log_collision_warnings &&
                              params.enable_collision_avoidance),
      cartesian_velocity_task_(nullptr),
      nullspace_task_(nullptr),
      joint_kinematic_constraints_(nullptr),
      collision_avoidance_constraint_(nullptr) {
  CHECK(params.integration_timestep > absl::ZeroDuration())
      << "Cartesian6dToJointVelocityMapper: `integration_timestep` ["
      << params.integration_timestep << "] must be a positive duration.";

  // Ensure data is in a valid state.
  std::fill_n(data_->qvel, model_.nv, 0.0);
  lib_.mj_fwdPosition(&model_, data_.get());

  // First hierarchy has the Cartesian velocity task and the regularization
  // task for singularity robustness. The weight for the Cartesian velocity task
  // is always 1.0, and the regularization weight is defined relative to this.
  auto first_hierarchy = qp_solver_.AddNewTaskHierarchy(
      params.max_cartesian_velocity_control_iterations);
  cartesian_velocity_task_ =
      first_hierarchy
          ->InsertOrAssignTask("CartesianVelocity",
                               absl::make_unique<Cartesian6dVelocityTask>(
                                   ToCartesianVelocityParams(params), *data_,
                                   std::array<double, 6>()),
                               1.0, false)
          .first;
  first_hierarchy->InsertOrAssignTask(
      "Regularization",
      absl::make_unique<MinimizeNormTask>(joint_dof_ids_.size()),
      params.regularization_weight, true);

  // Second hierarchy has the nullspace task. This is created only if the user
  // enables nullspace control. The weight for the nullspace task is always 1.0,
  // as it is the only task.
  if (params.enable_nullspace_control) {
    nullspace_task_ =
        qp_solver_.AddNewTaskHierarchy(params.max_nullspace_control_iterations)
            ->InsertOrAssignTask(
                "NullspaceBias",
                absl::make_unique<IdentityTask>(
                    std::vector<double>(joint_dof_ids_.size(), 0.0)),
                1.0, true)
            .first;
    clipped_nullspace_bias_.resize(joint_dof_ids_.size());
  }

  // The LSQP solver only owns two constraints. A union of identity constraints
  // (which will combine all joint constraints into one), and the collision
  // avoidance constraint.
  // Add collision avoidance constraint if enabled.
  if (params.enable_collision_avoidance) {
    CollisionAvoidanceConstraint::Parameters collision_params =
        ToCollisionAvoidanceParams(params);
    collision_avoidance_constraint_ =
        qp_solver_
            .InsertOrAssignConstraint(
                "CollisionAvoidance",
                absl::make_unique<CollisionAvoidanceConstraint>(
                    collision_params, *data_))
            .first;

    // We use this to sanity-check the solution and ensure it is never in
    // collision. This is because MuJoCo's computed normals are sometimes
    // inaccurate, and the computed velocity may thus result in collisions when
    // integrated.
    for (auto geom_pair : collision_params.geom_pairs) {
      geom_pair_to_dist_curr_[geom_pair] = absl::nullopt;
      geom_pair_to_dist_after_[geom_pair] = absl::nullopt;
    }
  }

  // Create the joint position limit constraint if enabled, and push it into the
  // enabled identity constraints vector.
  if (params.enable_joint_position_limits) {
    joint_position_limit_constraint_ =
        absl::make_unique<JointPositionLimitConstraint>(
            ToJointPositionLimitParams(params), *data_);
    enabled_joint_kinematic_constraints_.push_back(
        joint_position_limit_constraint_.get());
  }

  // Create the joint velocity limit constraint if enabled, and push it into the
  // enabled identity constraints vector.
  if (params.enable_joint_velocity_limits) {
    std::vector<double> lower_bound(joint_dof_ids_.size());
    std::vector<double> upper_bound(joint_dof_ids_.size());
    for (int i = 0; i < params.joint_velocity_magnitude_limits.size(); ++i) {
      lower_bound[i] = -std::abs(params.joint_velocity_magnitude_limits[i]);
      upper_bound[i] = std::abs(params.joint_velocity_magnitude_limits[i]);
    }

    joint_velocity_limit_constraint_ =
        absl::make_unique<BoxConstraint>(lower_bound, upper_bound);
    enabled_joint_kinematic_constraints_.push_back(
        joint_velocity_limit_constraint_.get());
  }

  // Create the joint acceleration limit constraint if enabled, and push it into
  // the enabled identity constraints vector.
  if (params.enable_joint_acceleration_limits) {
    joint_acceleration_limit_constraint_ =
        absl::make_unique<JointAccelerationConstraint>(
            ToJointAccelerationLimitParams(params), *data_);
    enabled_joint_kinematic_constraints_.push_back(
        joint_acceleration_limit_constraint_.get());
  }

  // Create a union for merging the joint kinematic constraints, if at least one
  // is enabled.
  if (!enabled_joint_kinematic_constraints_.empty()) {
    joint_kinematic_constraints_ =
        qp_solver_
            .InsertOrAssignConstraint(
                "JointLimitConstraints",
                absl::make_unique<IdentityConstraintUnion>(
                    joint_dof_ids_.size()))
            .first;
  }

  // Resize solution buffer and setup problem.
  CHECK_EQ(qp_solver_.SetupProblem(), absl::OkStatus())
      << "Cartesian6dToJointVelocityMapper: Unable to setup problem. This "
         "should never happen. Please contact the developers for more "
         "information.";
}

absl::StatusOr<absl::Span<const double>>
Cartesian6dToJointVelocityMapper::ComputeJointVelocities(
    const mjData& data, absl::Span<const double> target_6d_cartesian_velocity,
    absl::Span<const double> nullspace_bias) {
  CHECK(nullspace_task_ != nullptr)
      << "Cartesian6dToJointVelocityMapper::ComputeJointVelocities: Function "
         "overload with `nullspace_bias` parameter must not be called when "
         "`enable_nullspace_control` is false.";
  CHECK(nullspace_bias.size() == joint_dof_ids_.size())
      << "Cartesian6dToJointVelocityMapper::ComputeJointVelocities: Size "
         "of the `nullspace_bias` array ["
      << nullspace_bias.size()
      << "] does not match the number of DoF being controlled ["
      << joint_dof_ids_.size() << "].";
  return ComputeJointVelocitiesImpl(data, target_6d_cartesian_velocity,
                                    nullspace_bias);
}

absl::StatusOr<absl::Span<const double>>
Cartesian6dToJointVelocityMapper::ComputeJointVelocities(
    const mjData& data, absl::Span<const double> target_6d_cartesian_velocity) {
  CHECK(nullspace_task_ == nullptr)
      << "Cartesian6dToJointVelocityMapper::ComputeJointVelocities: Function "
         "overload without `nullspace_bias` parameter must not be called when "
         "`enable_nullspace_control` is true.";
  return ComputeJointVelocitiesImpl(data, target_6d_cartesian_velocity,
                                    absl::Span<const double>());
}

absl::StatusOr<absl::Span<const double>>
Cartesian6dToJointVelocityMapper::ComputeJointVelocitiesImpl(
    const mjData& data, absl::Span<const double> target_6d_cartesian_velocity,
    absl::Span<const double> nullspace_bias) {
  // Update internal mjData and run necessary MuJoCo routines.
  std::copy_n(data.qpos, model_.nq, data_->qpos);
  std::copy_n(data.qvel, model_.nv, data_->qvel);
  lib_.mj_kinematics(&model_, data_.get());
  lib_.mj_comPos(&model_, data_.get());

  // We update the constraints first, as we need to clip the nullspace bias to
  // the resulting kinematic constraint bounds.
  RETURN_IF_ERROR(UpdateConstraints());
  RETURN_IF_ERROR(UpdateTasks(target_6d_cartesian_velocity, nullspace_bias));

  // Solve, copy solution into internal buffer, and clip to kinematic
  // constraints to prevent constraint violations due to numerical errors.
  ASSIGN_OR_RETURN(absl::Span<const double> solution, qp_solver_.Solve());
  std::copy(solution.begin(), solution.end(), solution_.begin());
  if (!enabled_joint_kinematic_constraints_.empty()) {
    ClipToBounds(joint_kinematic_constraints_->GetLowerBound(),
                 joint_kinematic_constraints_->GetUpperBound(),
                 absl::MakeSpan(solution_));
  }

  // Check solution validity if necessary.
  if (check_solution_validity_) {
    RETURN_IF_ERROR(CheckSolutionValidity());
  }

  return solution_;
}

// Assumes all tasks have been initialized, and that `UpdateConstraints` has
// been called.
absl::Status Cartesian6dToJointVelocityMapper::UpdateTasks(
    absl::Span<const double> target_6d_cartesian_velocity,
    absl::Span<const double> nullspace_bias) {
  // Update Cartesian task.
  cartesian_velocity_task_->UpdateCoefficientsAndBias(
      *data_, target_6d_cartesian_velocity);

  // Update nullspace task if it exists, with the clipped bounds.
  if (nullspace_task_ != nullptr) {
    std::copy(nullspace_bias.begin(), nullspace_bias.end(),
              clipped_nullspace_bias_.begin());

    // Clip nullspace to merged kinematic bounds, if they exist. This makes the
    // nullspace problem easier.
    if (clamp_nullspace_bias_to_feasible_space_ &&
        !enabled_joint_kinematic_constraints_.empty()) {
      ClipToBounds(joint_kinematic_constraints_->GetLowerBound(),
                   joint_kinematic_constraints_->GetUpperBound(),
                   absl::MakeSpan(clipped_nullspace_bias_));
    }
    nullspace_task_->SetTarget(clipped_nullspace_bias_);
  }
  return absl::OkStatus();
}

// Assumes all constraints are initialized, and `data_` has been updated with
// the latest joint positions and joint velocities.
absl::Status Cartesian6dToJointVelocityMapper::UpdateConstraints() {
  bool has_joint_position_limit = joint_position_limit_constraint_ != nullptr;
  bool has_joint_acceleration_limit =
      joint_acceleration_limit_constraint_ != nullptr;
  bool has_joint_kinematic_constraint =
      !enabled_joint_kinematic_constraints_.empty();
  bool has_collision_avoidance_constraint =
      collision_avoidance_constraint_ != nullptr;

  if (has_joint_kinematic_constraint) {
    // Update each joint kinematic constraint, if they exist, and merge them
    // into a single identity constraint. Note that the joint velocity limit
    // constraint does not need to be updated, as it is constant.
    if (has_joint_position_limit) {
      joint_position_limit_constraint_->UpdateBounds(*data_);
    }
    if (has_joint_acceleration_limit) {
      joint_acceleration_limit_constraint_->UpdateBounds(*data_);
    }
    absl::Status kinematic_constraints_status =
        joint_kinematic_constraints_->UpdateFeasibleSpace(
            enabled_joint_kinematic_constraints_);

    // If joint acceleration limits are not enabled, updating the feasible space
    // must never fail. If it does, there is an internal programming bug
    // somewhere. Note that the joint position limits and joint velocity limits
    // constraint must never conflict, as the zero-vector will always be a
    // solution.
    if (!has_joint_acceleration_limit) {
      CHECK_EQ(kinematic_constraints_status, absl::OkStatus())
          << "Cartesian6dToJointVelocityMapper::UpdateConstraints: The "
             "joint position limit and joint velocity limit constraints "
             "are in conflict ["
          << kinematic_constraints_status.ToString()
          << "]. This should never happen; please "
             "contact the developers for more information.";
    }

    // The acceleration limit must be the cause of the confict iff:
    //   * The kinematic constraints are in conflict;
    //   * The acceleration limit exists;
    //   * The acceleration limit is not the only kinematic constraint.
    bool acceleration_limit_conflicts =
        !kinematic_constraints_status.ok() && has_joint_acceleration_limit &&
        enabled_joint_kinematic_constraints_.size() != 1;

    // If solver is not asked to remove the conflict, return an error instead.
    if (acceleration_limit_conflicts &&
        !remove_joint_acceleration_limits_if_in_conflict_) {
      return absl::NotFoundError(absl::Substitute(
          "Cartesian6dToJointVelocityMapper::UpdateConstraints: The joint "
          "acceleration limit constraint is in conflict with one or more joint "
          "limit constraints in this configuration. The resulting optimization "
          "problem is infeasible [$0]. To prevent this error, the user may "
          "want to increase the acceleration limits or set the "
          "`remove_joint_acceleration_limits_if_in_conflict` parameter to "
          "true.",
          kinematic_constraints_status.ToString()));
    } else if (acceleration_limit_conflicts &&
               remove_joint_acceleration_limits_if_in_conflict_) {
      // The acceleration limit constraint will always be the last constraint in
      // the array. If after removing the acceleration limit, the union still
      // fails to find a feasible space, then we have an internal programming
      // bug somewhere.
      CHECK_EQ(joint_kinematic_constraints_->UpdateFeasibleSpace(absl::MakeSpan(
                   enabled_joint_kinematic_constraints_.data(),
                   enabled_joint_kinematic_constraints_.size() - 1)),
               absl::OkStatus())
          << "Cartesian6dToJointVelocityMapper::UpdateConstraints: The "
             "joint position limit and joint velocity limit constraints "
             "are in conflict after removing the joint acceleration "
             "constraint ["
          << kinematic_constraints_status.ToString()
          << "]. This should never happen; please contact "
             "the developers for more information.";
    }
  }

  // Update collision avoidance.
  if (has_collision_avoidance_constraint) {
    collision_avoidance_constraint_->UpdateCoefficientsAndBounds(*data_);
  }
  if (log_collision_warnings_) {
    auto contact_debug_str =
        collision_avoidance_constraint_->GetContactDebugString(*data_);
    LOG_IF(WARNING, !contact_debug_str.empty()) << contact_debug_str;
  }
  return absl::OkStatus();
}

// Assumes solution_ has the computed values to be checked for validity.
absl::Status Cartesian6dToJointVelocityMapper::CheckSolutionValidity() {
  // If collision avoidance is not active, no need to check.
  if (collision_avoidance_constraint_ == nullptr) {
    return absl::OkStatus();
  }

  // If collision avoidance is active, do a sanity check to ensure that the
  // integrated velocities do not increase penetration. This is because the
  // computed velocities may result in penetration after integration, even if
  // they are in the feasible space.
  //
  // At the moment, we assume that all joints that are not being controlled are
  // fixed, but the collision avoidance constraint may be able to support other
  // moving joints in the future.
  //
  // We have identified 2 main reasons why this can happen:
  //   * Errors due to the local Jacobian linearization about the current
  //     configuration;
  //   * MuJoCo's collision detection is sometimes flaky between certain geom
  //     types, and the computed normal distance/direction may be wrong.
  ComputeGeomPairDist(lib_, model_, *data_, minimum_distance_from_collisions_,
                      &geom_pair_to_dist_curr_);
  std::fill_n(data_->qvel, model_.nv, 0.0);  // Assume everything else is fixed.
  IntegrateQpos(lib_, model_, integration_timestep_, joint_dof_ids_, solution_,
                data_.get());
  lib_.mj_kinematics(&model_, data_.get());
  ComputeGeomPairDist(lib_, model_, *data_, minimum_distance_from_collisions_,
                      &geom_pair_to_dist_after_);
  std::pair<int, int> penetrating_pair;
  if (IsPenetrationIncreased(minimum_distance_from_collisions_,
                             geom_pair_to_dist_curr_, geom_pair_to_dist_after_,
                             &penetrating_pair)) {
    // The current distance may or may not have a value, as it could be the case
    // that no collision was detected before and then suddenly it was
    // penetrating. If that's the case, we instead print
    // ">[`min_distance_from_collision`]".
    std::optional<double> dist_before =
        geom_pair_to_dist_curr_.at(penetrating_pair);
    std::string dist_before_msg =
        dist_before.has_value()
            ? std::to_string(dist_before.value())
            : absl::StrCat(">", minimum_distance_from_collisions_);

    return absl::InternalError(absl::Substitute(
        "Cartesian6dToJointVelocityMapper::ComputeJointVelocities: Computed "
        "joint velocities resulted in increased penetration when integrated. "
        "This can happen if the `collision_detection_distance` is too small, "
        "`collision_avoidance_normal_velocity_scale` is too large, or if "
        "MuJoCo's collision detection mechanism outputs the wrong normal or "
        "distance between geoms. Increasing `collision_detection_distance` and "
        "decreasing `collision_avoidance_normal_velocity_scale` may help. "
        "Specifically, normal distance between geom with name [$0] and geom "
        "with name [$1] decreased from a current value of [$2] to a value of "
        "[$3] after integration, with a user-defined minimum distance from "
        "collisions of [$4].",
        lib_.mj_id2name(&model_, mjOBJ_GEOM, penetrating_pair.first),
        lib_.mj_id2name(&model_, mjOBJ_GEOM, penetrating_pair.second),
        dist_before_msg, *geom_pair_to_dist_after_.at(penetrating_pair),
        minimum_distance_from_collisions_));
  }
  return absl::OkStatus();
}

}  // namespace dm_robotics


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Stat',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('date', models.DateTimeField(auto_now_add=True)),
                ('up', models.BigIntegerField()),
                ('down', models.BigIntegerField()),
                ('live_time', models.BigIntegerField()),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


text:
package io.github.tailhq.dynaml.examples

import breeze.linalg.{DenseMatrix, DenseVector}
import io.github.tailhq.dynaml.graphics.charts.Highcharts._
import io.github.tailhq.dynaml.DynaMLPipe
import io.github.tailhq.dynaml.evaluation.RegressionMetrics
import io.github.tailhq.dynaml.kernels.{
  CovarianceFunction,
  LocalScalarKernel
}
import io.github.tailhq.dynaml.models.svm.DLSSVM
import io.github.tailhq.dynaml.optimization.{
  GradBasedGlobalOptimizer,
  GridSearch
}
import io.github.tailhq.dynaml.pipes._
import org.apache.log4j.Logger

/**
  * Created by mandar on 4/3/16.
  */
object DaisyPowerPlant {
  def apply(
    kernel: LocalScalarKernel[DenseVector[Double]],
    deltaT: Int = 2,
    timelag: Int = 0,
    stepPred: Int = 3,
    num_training: Int = 150,
    column: Int = 7,
    opt: Map[String, String]
  ) =
    runExperiment(kernel, deltaT, timelag, stepPred, num_training, column, opt)

  def runExperiment(
    kernel: LocalScalarKernel[DenseVector[Double]],
    deltaT: Int = 2,
    timelag: Int = 0,
    stepPred: Int = 3,
    num_training: Int = 150,
    column: Int = 7,
    opt: Map[String, String]
  ): Seq[Seq[AnyVal]] = {
    //Load Daisy data into a stream
    //Extract the time and Dst values

    val logger = Logger.getLogger(this.getClass)

    val names = Map(
      6 -> "steam pressure",
      7 -> "main stem temperature",
      8 -> "reheat steam temperature"
    )

    //pipe training data to model and then generate test predictions
    //create RegressionMetrics instance and produce plots
    val modelTrainTest =
      (trainTest: (
        (
          Iterable[(DenseVector[Double], Double)],
          Iterable[(DenseVector[Double], Double)]
        ),
        (DenseVector[Double], DenseVector[Double])
      )) => {

        val model = new DLSSVM(trainTest._1._1.toStream, num_training, kernel)

        val gs = opt("globalOpt") match {
          case "GS" =>
            new GridSearch[model.type](model)
              .setGridSize(opt("grid").toInt)
              .setStepSize(opt("step").toDouble)
              .setLogScale(false)

          case "ML" => new GradBasedGlobalOptimizer[DLSSVM](model)
        }

        val startConf = kernel.state ++ Map(
          "regularization" ->
            opt("regularization").toDouble
        )

        val (_, conf) = gs.optimize(startConf, opt)

        model.setRegParam(opt("regularization").toDouble).learn()

        val res = trainTest._1._2
          .map(testpoint => (model.predict(testpoint._1), testpoint._2))

        val scoresAndLabelsPipe = DataPipe(
          (list: List[(Double, Double)]) =>
            list.map { l =>
              (
                l._1 * trainTest._2._2(-1) + trainTest._2._1(-1),
                l._2 * trainTest._2._2(-1) + trainTest._2._1(-1)
              )
            }
        )

        val scoresAndLabels = scoresAndLabelsPipe.run(res.toList)

        val metrics =
          new RegressionMetrics(scoresAndLabels, scoresAndLabels.length)
        metrics.setName(names(column))

        metrics.print()
        metrics.generatePlots()

        //Plotting time series prediction comparisons
        line((1 to scoresAndLabels.length).toList, scoresAndLabels.map(_._2))
        hold()
        line((1 to scoresAndLabels.length).toList, scoresAndLabels.map(_._1))
        legend(
          List(
            names(column),
            "Predicted " + names(column) + " (one hour ahead)"
          )
        )
        title("Pont-sur-Sambre 120 MW power plant: " + names(column))
        unhold()

        Seq(
          Seq(
            deltaT,
            1,
            num_training,
            200 - num_training,
            metrics.mae,
            metrics.rmse,
            metrics.Rsq,
            metrics.corr,
            metrics.modelYield
          )
        )
      }

    val preProcessPipe = DynaMLPipe.fileToStream >
      DynaMLPipe.trimLines >
      DynaMLPipe.replaceWhiteSpaces >
      DynaMLPipe.extractTrainingFeatures(
        List(0, column, 1, 2, 3, 4, 5),
        Map()
      ) >
      DynaMLPipe.removeMissingLines >
      IterableDataPipe((line: String) => {
        val splits    = line.split(",")
        val timestamp = splits.head.toDouble
        val feat      = DenseVector(splits.tail.map(_.toDouble))
        (timestamp, feat)
      }) >
      DynaMLPipe.deltaOperationVec(deltaT)

    val trainTestPipe = DynaMLPipe.duplicate(preProcessPipe) >
      DynaMLPipe.splitTrainingTest(num_training, 200 - num_training) >
      DynaMLPipe.trainTestGaussianStandardization >
      DataPipe(modelTrainTest)

    val dataFile = dataDir + "/powerplant.csv"
    trainTestPipe((dataFile, dataFile))

  }
}


text:
**CHANGES**
{% for commit in commits %}
- {{ commit.commit.message }}
{% endfor %}
**DOWNLOAD**

- [OS X](https://s3.amazonaws.com/hawkthorne.journey.builds/{{version}}/hawkthorne-osx.zip)
- [Windows 32-bit](https://s3.amazonaws.com/hawkthorne.journey.builds/{{version}}/hawkthorne-win-x86.zip)
- [Windows 64-bit](https://s3.amazonaws.com/hawkthorne.journey.builds/{{version}}/hawkthorne-win-x64.zip)
- [hawkthorne.love](https://s3.amazonaws.com/hawkthorne.journey.builds/{{version}}/hawkthorne.love) for those on Linux.
  You'll need to install the [love](http://love2d.org) framework as well.

**Found a bug? [Report it here](https://docs.google.com/spreadsheet/viewform?pli=1&formkey=dFh5bmRNVWZrdlBHbUVmcmZNczJoaXc6MQ#gid=0)**


text: export const paragraph: string;


text:
title: Spacer
description: Vertical spacing in emails is inconsistent. The spacer component will help you create the space you need, the same on every device and client.
tags:
  - spacing
  - height
  - margin
  - padding
---

## Basics

Vertical spacing between email clients is not as simple as it sounds, in fact, it's consistently inconsistent. Versions of Outlook don't respect margin and padding the same and `<br>`'s are different all over the place.

The spacer is used to create vertical spacing between elements. The size `size="x"` attribute allows you to set the height in pixels of vertical spacing you need.

When using [Inky](inky.html) HTML, the `<spacer>` tag will create this structure for you. You can use them between rows, containers or inside wrappers, rows, columns, and containers. In this example, this spacer will create 100px of vertical spacing:

```inky_example
<p>Stuff on top</p>
<spacer size="100"></spacer>
<p>Stuff on bottom</p>
```

The Inky `<spacer>` tag also allows you to specify contextual spacer sizes for small or large screens. In the example below, there will be 40px of vertical spacing on small screens, and 100px of spacing on large screens.

```inky_example
<p>Stuff above...</p>
<spacer size-sm="40" size-lg="100"></spacer>
<p>...stuff below.</p>
```

Specify both `size-sm` and `size-lg` or use just one of those attributes to render a spacer only on the corresponding size screen.


text:
<?php

namespace WSSC\Components;

use WSSC\Contracts\CommonsContract;
use WSSC\Exceptions\BadOpcodeException;
use WSSC\Exceptions\BadUriException;
use WSSC\Exceptions\ConnectionException;

trait WSClientTrait
{
    /**
     * Validates whether server sent valid upgrade response
     *
     * @param ClientConfig $config
     * @param string $pathWithQuery
     * @param string $key
     * @throws ConnectionException
     */
    private function validateResponse(ClientConfig $config, string $pathWithQuery, string $key)
    {
        $response = stream_get_line($this->socket, self::DEFAULT_RESPONSE_HEADER, "\r\n\r\n");
        if (!preg_match(self::SEC_WEBSOCKET_ACCEPT_PTTRN, $response, $matches)) {
            $address = $config->getScheme() . '://' . $config->getHost() . ':' . $config->getPort() . $pathWithQuery;
            throw new ConnectionException(
                "Connection to '{$address}' failed: Server sent invalid upgrade response:\n"
                . $response, CommonsContract::CLIENT_INVALID_UPGRADE_RESPONSE
            );
        }

        $keyAccept = trim($matches[1]);
        $expectedResponse = base64_encode(pack('H*', sha1($key . self::SERVER_KEY_ACCEPT)));
        if ($keyAccept !== $expectedResponse) {
            throw new ConnectionException('Server sent bad upgrade response.',
                CommonsContract::CLIENT_INVALID_UPGRADE_RESPONSE);
        }
    }

    /**
     *  Gets host uri based on protocol
     *
     * @param ClientConfig $config
     * @return string
     * @throws BadUriException
     */
    private function getHostUri(ClientConfig $config): string
    {
        if (in_array($config->getScheme(), ['ws', 'wss'], true) === false) {
            throw new BadUriException(
                "Url should have scheme ws or wss, not '{$config->getScheme()}' from URI '$this->socketUrl' .",
                CommonsContract::CLIENT_INCORRECT_SCHEME
            );
        }

        return ($config->getScheme() === 'wss' ? 'ssl' : 'tcp') . '://' . $config->getHost();
    }

    /**
     * @param string $data
     * @return float|int
     * @throws ConnectionException
     */
    private function getPayloadLength(string $data)
    {
        $payloadLength = (int)ord($data[1]) & self::MASK_127; // Bits 1-7 in byte 1
        if ($payloadLength > self::MASK_125) {
            if ($payloadLength === self::MASK_126) {
                $data = $this->read(2); // 126: Payload is a 16-bit unsigned int
            } else {
                $data = $this->read(8); // 127: Payload is a 64-bit unsigned int
            }
            $payloadLength = bindec(self::sprintB($data));
        }

        return $payloadLength;
    }

    /**
     * @param string $data
     * @param int $payloadLength
     * @return string
     * @throws ConnectionException
     */
    private function getPayloadData(string $data, int $payloadLength): string
    {
        // Masking?
        $mask = (bool)(ord($data[1]) >> 7);  // Bit 0 in byte 1
        $payload = '';
        $maskingKey = '';

        // Get masking key.
        if ($mask) {
            $maskingKey = $this->read(4);
        }

        // Get the actual payload, if any (might not be for e.g. close frames.
        if ($payloadLength > 0) {
            $data = $this->read($payloadLength);

            if ($mask) {
                // Unmask payload.
                for ($i = 0; $i < $payloadLength; $i++) {
                    $payload .= ($data[$i] ^ $maskingKey[$i % 4]);
                }
            } else {
                $payload = $data;
            }
        }

        return $payload;
    }

    /**
     * @return null|string
     * @throws \WSSC\Exceptions\BadOpcodeException
     * @throws \InvalidArgumentException
     * @throws BadOpcodeException
     * @throws BadUriException
     * @throws ConnectionException
     * @throws \Exception
     */
    protected function receiveFragment(): ?string
    {
        // Just read the main fragment information first.
        $data = $this->read(2);

        // Is this the final fragment?  // Bit 0 in byte 0
        /// @todo Handle huge payloads with multiple fragments.
        $final = (bool)(ord($data[0]) & 1 << 7);

        // Parse opcode
        $opcodeInt = ord($data[0]) & 31; // Bits 4-7
        $opcodeInts = array_flip(self::$opcodes);
        if (!array_key_exists($opcodeInt, $opcodeInts)) {
            throw new ConnectionException("Bad opcode in websocket frame: $opcodeInt",
                CommonsContract::CLIENT_BAD_OPCODE);
        }

        $opcode = $opcodeInts[$opcodeInt];

        // record the opcode if we are not receiving a continutation fragment
        if ($opcode !== 'continuation') {
            $this->lastOpcode = $opcode;
        }

        $payloadLength = $this->getPayloadLength($data);
        $payload = $this->getPayloadData($data, $payloadLength);

        if ($opcode === CommonsContract::EVENT_TYPE_CLOSE) {
            // Get the close status.
            if ($payloadLength >= 2) {
                $statusBin = $payload[0] . $payload[1];
                $status = bindec(sprintf('%08b%08b', ord($payload[0]), ord($payload[1])));
                $this->closeStatus = $status;
                $payload = substr($payload, 2);

                if (!$this->isClosing) {
                    $this->send($statusBin . 'Close acknowledged: ' . $status,
                        CommonsContract::EVENT_TYPE_CLOSE); // Respond.
                }
            }

            if ($this->isClosing) {
                $this->isClosing = false; // A close response, all done.
            }

            fclose($this->socket);
            $this->isConnected = false;
        }

        if (!$final) {
            $this->hugePayload .= $payload;

            return NULL;
        } // this is the last fragment, and we are processing a huge_payload

        if ($this->hugePayload) {
            $payload = $this->hugePayload .= $payload;
            $this->hugePayload = NULL;
        }

        return $payload;
    }

    /**
     * @param $final
     * @param $payload
     * @param $opcode
     * @param $masked
     * @throws ConnectionException
     * @throws \Exception
     */
    protected function sendFragment($final, $payload, $opcode, $masked)
    {
        // Binary string for header.
        $frameHeadBin = '';
        // Write FIN, final fragment bit.
        $frameHeadBin .= (bool)$final ? '1' : '0';
        // RSV 1, 2, & 3 false and unused.
        $frameHeadBin .= '000';
        // Opcode rest of the byte.
        $frameHeadBin .= sprintf('%04b', self::$opcodes[$opcode]);
        // Use masking?
        $frameHeadBin .= $masked ? '1' : '0';

        // 7 bits of payload length...
        $payloadLen = strlen($payload);
        if ($payloadLen > self::MAX_BYTES_READ) {
            $frameHeadBin .= decbin(self::MASK_127);
            $frameHeadBin .= sprintf('%064b', $payloadLen);
        } else if ($payloadLen > self::MASK_125) {
            $frameHeadBin .= decbin(self::MASK_126);
            $frameHeadBin .= sprintf('%016b', $payloadLen);
        } else {
            $frameHeadBin .= sprintf('%07b', $payloadLen);
        }

        $frame = '';

        // Write frame head to frame.
        foreach (str_split($frameHeadBin, 8) as $binstr) {
            $frame .= chr(bindec($binstr));
        }
        // Handle masking
        if ($masked) {
            // generate a random mask:
            $mask = '';
            for ($i = 0; $i < 4; $i++) {
                $mask .= chr(random_int(0, 255));
            }
            $frame .= $mask;
        }

        // Append payload to frame:
        for ($i = 0; $i < $payloadLen; $i++) {
            $frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
        }

        $this->write($frame);
    }
}


text:
<?php

declare(strict_types=1);

namespace Phan\Tests;

/**
 * Unit tests for the expected behavior when Phan analyzes code using the SOAP extension.
 *
 * @requires extension soap
 */
final class SoapTest extends AbstractPhanFileTest
{

    /**
     * This reads all files in `tests/files/src`, runs
     * the analyzer on each and compares the output
     * to the files' counterpart in
     * `tests/files/expected`
     *
     * @param string[] $test_file_list
     * @param string $expected_file_path
     *
     * @dataProvider getTestFiles
     */
    public function testFiles(array $test_file_list, string $expected_file_path, ?string $config_file_path = null): void
    {
        parent::testFiles($test_file_list, $expected_file_path, $config_file_path);
    }

    /**
     * @suppress PhanUndeclaredConstant
     */
    public function getTestFiles(): array
    {
        return $this->scanSourceFilesDir(\SOAP_TEST_FILE_DIR, \SOAP_EXPECTED_DIR);
    }
}


text:
/**
 * @fileoverview Rule to flag the generator functions that does not have yield.
 * @author Toru Nagashima
 */

"use strict";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = {
    meta: {
        docs: {
            description: "require generator functions to contain `yield`",
            category: "ECMAScript 6",
            recommended: true
        },

        schema: []
    },

    create: function(context) {
        const stack = [];

        /**
         * If the node is a generator function, start counting `yield` keywords.
         * @param {Node} node - A function node to check.
         * @returns {void}
         */
        function beginChecking(node) {
            if (node.generator) {
                stack.push(0);
            }
        }

        /**
         * If the node is a generator function, end counting `yield` keywords, then
         * reports result.
         * @param {Node} node - A function node to check.
         * @returns {void}
         */
        function endChecking(node) {
            if (!node.generator) {
                return;
            }

            const countYield = stack.pop();

            if (countYield === 0 && node.body.body.length > 0) {
                context.report(
                    node,
                    "This generator function does not have 'yield'.");
            }
        }

        return {
            FunctionDeclaration: beginChecking,
            "FunctionDeclaration:exit": endChecking,
            FunctionExpression: beginChecking,
            "FunctionExpression:exit": endChecking,

            // Increases the count of `yield` keyword.
            YieldExpression: function() {

                /* istanbul ignore else */
                if (stack.length > 0) {
                    stack[stack.length - 1] += 1;
                }
            }
        };
    }
};


text:
var _ = require("lodash");
var validate = require("./validate");

/**
 * Utility module for dealing with rectangles.
 *
 * @module decks/utils/rect
 */
module.exports = {
  /**
   * Normalizes an object that has top, bottom, left, and right properties, to a plain
   * object with top, bottom, left, right, width, and height properties.
   *
   * @param {*} r object that has top, bottom, left, right properties.  If r is an Element, r will be the
   * result of r.getBoundingClientRect()
   * @return {undefined}
   */
  normalize: function normalize(r) {
    validate(r, "rect#normalize: r (rectangle object)", { isRequired: true });

    if (r.isNormalized) {
      return r;
    }

    if (_.isElement(r)) {
      r = this.getElementRect(r);
    }

    // TODO: should this check for correctness of all values?  E.g. top < bottom, left < right, width === right - left, etc.

    var top = _.isFinite(r.top) ? r.top : 0;
    var bottom = _.isFinite(r.bottom) ? r.bottom : 0;
    var left = _.isFinite(r.left) ? r.left : 0;
    var right = _.isFinite(r.right) ? r.right : 0;
    var width = _.isFinite(r.width) ? r.width : (right - left);
    var height = _.isFinite(r.height) ? r.height : (bottom - top);

    return {
      isNormalized: true,
      top: top,
      bottom: bottom,
      left: left,
      right: right,
      width: width,
      height: height
    };
  },

  /**
   * Gets a bounding client rect for an element, with respect to the document coordinate
   * system (not the window coordinate system).
   *
   * @param {HTMLElement} element - the element for which to find the rect
   * @return {Object} - the calculated rect, with respect to the document coordinate system
   */
  getElementRect: function getElementRect(element) {
    validate(element, "rect#getElementRect: element", { isElement: true });
    return element.getBoundingClientRect();
  },

  /**
   * Indicates if two rects are equal in all dimensions/values.
   *
   * @param r1
   * @param r2
   * @return {undefined}
   */
  isEqual: function isEqual(r1, r2) {
    if (!r1 && !r2) {
      return true;
    }
    if (!r1 || !r2) {
      return false;
    }
    r1 = this.normalize(r1);
    r2 = this.normalize(r2);
    return _.isEqual(r1, r2);
  },

  /**
   * Indicates if the rect is empty (null, undefined, or or has all values equal to 0)
   *
   * @param r
   * @return {undefined}
   */
  isEmpty: function isEmpty(r) {
    if (_.isNull(r) || _.isUndefined(r)) {
      return true;
    }

    return _.all(["left", "right", "top", "bottom", "width", "height"], function(key) {
      return r[key] === 0;
    });
  },

  /**
   * Indicates whether rectangle r1 intersects rectangle r2
   *
   * @param {*} r1 first rectangle
   * @param {*} r2 second rectangle
   * @return {boolean} true if r1 intersects r2, otherwise false
   */
  intersects: function intersects(r1, r2) {
    r1 = this.normalize(r1);
    r2 = this.normalize(r2);
    return !(r2.left > r1.right ||
      r2.right < r1.left ||
      r2.top > r1.bottom ||
      r2.bottom < r1.top);
  },

  /**
   * Returns a new rectangle which is the union of rectangles r1 and r2
   *
   * @param {*} r1 rectangle 1
   * @param {*} r2 rectangle 2
   * @return {*} New rectangle that is the union of r1 and r2
   */
  union: function union(r1, r2) {
    r1 = this.normalize(r1);
    r2 = this.normalize(r2);
    return this.normalize({
      top: Math.min(r1.top, r2.top),
      bottom: Math.max(r1.bottom, r2.bottom),
      left: Math.min(r1.left, r2.left),
      right: Math.max(r1.right, r2.right)
    });
  },

  /**
   * Returns a new rectangle which is the union of all the given rectangles
   *
   * @param {Array} rects
   * @return {*} New rectangle
   */
  unionAll: function unionAll(rects) {
    validate(rects, "rect#unionAll: rects", { isArray: true });

    // Initial accumulator allows the first rectangle to win the union
    var acc = {
      top: Infinity,
      bottom: -Infinity,
      left: Infinity,
      right: -Infinity
    };
    return _.reduce(rects, function(acc, rect) {
      return this.union(acc, rect);
    }, acc, this);
  },

  /**
   * Resizes a rect by adding the specified width and height values, and adjusting
   * the right and bottom dimensions, based on the current top/left and new width/height.
   *
   * Use negative width and height to shrink the rect.
   *
   * This does not change top and left.
   *
   * @param {!Object} r - rectangle-like object
   * @param {?number} [width=0] - delta value for width
   * @param {?number} [height=0] - delta value for height
   * @return {Object} resulting normalized rectangle object
   */
  resize: function resize(r, deltaWidth, deltaHeight) {
    r = this.normalize(r);
    deltaWidth = deltaWidth || 0;
    deltaHeight = deltaHeight || 0;
    return this.normalize({
      left: r.left,
      right: r.right + deltaWidth,
      top: r.top,
      bottom: r.bottom + deltaHeight,
      width: r.width + deltaWidth,
      height: r.height + deltaHeight
    });
  },

  /**
   * Resizes a rect with a delta width (changes width and right)
   *
   * @param r
   * @param deltaWidth
   * @return {undefined}
   */
  resizeWidth: function resizeWidth(r, deltaWidth) {
    return this.resize(r, deltaWidth, 0);
  },

  /**
   * Resizes a rect with a delta height (changes height and bottom)
   *
   * @param r
   * @param deltaHeight
   * @return {undefined}
   */
  resizeHeight: function resizeHeight(r, deltaHeight) {
    return this.resize(r, 0, deltaHeight);
  },

  /**
   * Resizes a rect to an absolute width and height (not delta values)
   *
   * @param r
   * @param width
   * @param height
   * @return {undefined}
   */
  resizeTo: function resizeTo(r, width, height) {
    r = this.normalize(r);
    width = width || r.width;
    height = height || r.height;
    return this.normalize({
      left: r.left,
      right: r.left + width,
      top: r.top,
      bottom: r.top + height,
      width: width,
      height: height
    });
  },

  /**
   * Resizes a rect to an absolute width (not delta value)
   *
   * @param r
   * @param width
   * @return {undefined}
   */
  resizeToWidth: function resizeToWidth(r, width) {
    return this.resizeTo(r, width, null);
  },

  /**
   * Resizes to rect to an absolute height (not delta value)
   *
   * @param r
   * @param height
   * @return {undefined}
   */
  resizeToHeight: function resizeToHeight(r, height) {
    return this.resizeTo(r, null, height);
  },

  /**
   * Moves a rect by adding the specified x and y values to left and top.
   *
   * The width and height are not changed, but the right and bottom values are changed based
   * on the new left/top and current width/height.
   *
   * This does not change width and height;
   *
   * @param {!Object} r - rectangle-like object
   * @param {?number} [x=0] - delta value for left
   * @param {?number} [y=0] - delta value for top
   * @return {Object} - resulting normalized rectangle object
   */
  move: function move(r, deltaX, deltaY) {
    r = this.normalize(r);
    deltaX = deltaX || 0;
    deltaY = deltaY || 0;
    return this.normalize({
      left: r.left + deltaX,
      right: r.right + deltaX,
      top: r.top + deltaY,
      bottom: r.bottom + deltaY,
      width: r.width,
      height: r.height
    });
  },

  /**
   * Moves a rect by a delta x value.
   *
   * @param r
   * @param deltaX
   * @return {undefined}
   */
  moveX: function moveX(r, deltaX) {
    return this.move(r, deltaX, 0);
  },

  /**
   * Moves a rect by a delta y value.
   *
   * @param r
   * @param deltaY
   * @return {undefined}
   */
  moveY: function moveY(r, deltaY) {
    return this.move(r, 0, deltaY);
  },

  /**
   * Moves a rect to an absolute x and y location.
   *
   * @param r
   * @param x
   * @param y
   * @return {undefined}
   */
  moveTo: function moveTo(r, x, y) {
    r = this.normalize(r);
    x = x || r.left;
    y = y || r.top;
    return this.normalize({
      left: x,
      right: x + r.width,
      top: y,
      bottom: y + r.height,
      width: r.width,
      height: r.height
    });
  },

  /**
   * Moves a rect to an absolute x location.
   *
   * @param r
   * @param x
   * @return {undefined}
   */
  moveToX: function moveToX(r, x) {
    return this.moveTo(r, x, null);
  },

  /**
   * Moves a rect to an absolute y location.
   *
   * @param r
   * @param y
   * @return {undefined}
   */
  moveToY: function moveToY(r, y) {
    return this.moveTo(r, null, y);
  },

  /**
   * Calculates the distance between two points.  Points can be expressed with top and left values,
   * or x and y values.
   *
   * @param {!Object} point1 - first point
   * @param {!Object} point2 - second point
   * @return {number} - the distance between the points
   */
  distance: function distance(point1, point2) {
    var x1 = point1.left || point1.x || 0;
    var y1 = point1.top || point1.y || 0;
    var x2 = point2.left || point2.x || 0;
    var y2 = point2.top || point2.y || 0;
    return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
  }
};


text:
package com.bjlx.QinShihuang.core.formatter.misc;

import com.bjlx.QinShihuang.model.misc.ColumnCommodity;
import com.bjlx.QinShihuang.model.marketplace.Commodity;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.util.List;

/**
 * 首页商品序列化
 * Created by pengyt on 2016/11/12.
 */
public class ColumnCommoditySerializer extends JsonSerializer<ColumnCommodity> {

    @Override
    public void serialize(ColumnCommodity columnCommodity, JsonGenerator gen, SerializerProvider serializers) {
        try {
            gen.writeStartObject();
            gen.writeStringField(ColumnCommodity.fd_id, columnCommodity.getId() == null ? "" : columnCommodity.getId().toString());
            gen.writeStringField(ColumnCommodity.fd_category, columnCommodity.getCategory() == null ? "" : columnCommodity.getCategory());
            List<Commodity> commodities = columnCommodity.getCommodities();
            gen.writeFieldName(ColumnCommodity.fd_commodities);
            if (commodities != null && !commodities.isEmpty()) {
                gen.writeStartArray();
                JsonSerializer<Object> ret = serializers.findValueSerializer(Commodity.class, null);
                for (Commodity commodity : commodities)
                    ret.serialize(commodity, gen, serializers);
                gen.writeEndArray();
            }
            gen.writeEndObject();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}