text:
    设备管理

        设备列表

        导入设备信息

        导入设备密码

          <select class="form-control"
            ng-model="filters.business"
            ng-options="row for row in businessList"
            ng-change="filtersChanged()">
            <option value="">-- 选择业务 --</option>
          </select>

          <select class="form-control"
            ng-model="filters.idc"
            ng-options="row for row in idcList"
            ng-change="filtersChanged()">
            <option value="">-- 选择机房 --</option>
          </select>

          <input class="form-control"
            ng-model="filters.ipText"
            ng-change="filtersChanged()"
            placeholder="输入一个或多个IP过滤">

          <button type="button" class="btn btn-default"
            id="btn-devices-copy"
            clip-copy="getIpsToCopy()"
            clip-click="copied('#btn-devices-copy')"
            ng-disabled="!checkedAtLeastOne">
            复制选中IP
          </button>
          <button type="button" class="btn btn-default"
            ng-click="editChecked()">
            修改选中
          </button>
          <button type="button" class="btn btn-danger"
            ng-click="removeChecked()">
            删除选中
          </button>

        <colgroup>
          <col style="width:10%">
          <col span="3">
          <col style="width:20%">
        </colgroup>

              <input type="checkbox" ng-model="all.checked" ng-change="allChecked()">

            IP
            业务
            机房
            操作

              <input type="checkbox" ng-model="row.checked" ng-change="rowChecked()">

            {{row.deviceId}}
            {{row.business}}
            {{row.idc}}

              <button type="button" class="btn btn-xs btn-default" ng-click="edit(row, $index)">修改</button>
              <button type="button" class="btn btn-xs btn-danger" ng-click="remove(row, $index)">删除</button>

            无设备

      <tars-pagination ng-model="filters.page" total-items="totalItems" items-per-page="itemsPerPage" num-pages="numPages"></tars-pagination>

        共 {{totalItems}} 台设备, {{filters.page}} / {{numPages}} 页


text:
#ifndef PWM_H
#define PWM_H

#include "sys_hw.h"

// PWM frequency sets time base (PTPER) as follows (in free running mode)
// PTPER = [Fcy / (Fpwm*PTMRpresc)] - 1
// but FULL_DUTY = 2*PTPER because McPWM has Tcy/2 resolution
#define FCY_PWM 20000
#define PWM_PRESC 1
#define FULL_DUTY ((FCY/(FCY_PWM*PWM_PRESC) - 1)*2)
//just in case H-Bridge is controlled in Locked Anti-phase mode..
#define ZERO_DUTY (FULL_DUTY/2)

//Functions and Variables with Global Scope:
void PWM_Init(void);
void __attribute__((interrupt,auto_psv)) _MPWM1Interrupt(void);
void __attribute__((interrupt,auto_psv)) _MPWM2Interrupt(void);

#endif

redpajama_set_name: RedPajamaGithub


text:
<?php

/*
 * Michael Zijlstra 11/14/2014
 */

// helper function to checks if user is logged in
function isLoggedIn() {
    if (!isset($_SESSION['user'])) {
        global $MY_BASE;
        global $MY_URI;

        // If the user requests a specific project store the request URL
        // That way we can go there after logging in
        if (preg_match("|project/(\d+)|", $MY_URI)) {
            $_SESSION['login_to'] = $MY_URI;
        }

        // Then show login page
        $_SESSION['error'] = "Please Login:";
        header("Location: ${MY_BASE}/login");
        exit();
    }
}

// find the security policy for the current URI using $security from context
$my_policy = "admin"; // default policy if no URI found
$sec_test = "$MY_METHOD@$MY_URI";
foreach ($security as $pattern => $policy) {
    if (preg_match($pattern, $sec_test)) {
        $my_policy = $policy;
        break;
    }
}

// apply the (found) security policy
switch ($my_policy) {
    case "none":
        break;
    case "user":
        isLoggedIn();
        break;
    case "admin":
    default:
        isLoggedIn();
        if ($_SESSION['user']['type'] !== 'admin') {
            require "view/error/403.php";
            exit();
        }
}


text:
  <title>Pipeline-Demo</title>

Error-Demo


text:
describe('Messages template', function() {
  function helper(name) {
    return Template.messages.helpers.firstCall.args[0][name];
  }

  beforeEach(function() {
    Messages = sinon.stub({
      find: function() {}
    });
  });

  it('finds all messages', function() {
    helper('messages')();
    expect(Messages.find.calledOnce).toBeTruthy();
  });

  it('sorts the messages based on their time', function() {
    helper('messages')();
    expect(Messages.find.getCall(0).args[1].sort.time).toBe(-1);
  });

  it('formats a date to a timestamp', function() {
    expect(helper('time')(moment('18:23:45', 'HH:mm:ss').toDate()))
      .toBe('18:23:45');
  });

  it('is the owner of the message if the user ID is the same as the owner property', function() {
    Meteor.userId.returns('123-456-789');
    expect(helper('isOwner')({
      message: 'Hi',
      date: new Date(),
      owner: '123-456-789'
    })).toBeTruthy();
  });

  it('is not the owner of the message if the user ID does not match', function() {
    Meteor.userId.returns('123-456-789');
    expect(helper('isOwner')({
      message: 'Hi',
      date: new Date(),
      owner: '456-789-123'
    })).toBeFalsy();
  });
});


text:
import os
from delphin import tdl
from coolisf.mappings import PredSense

lex = 'data/lexicon.tdl'
if not os.path.isfile(lex):
    print("data/lexicon.tdl is required")
    exit()
log = open('lex2wn.log', 'w')

f = open(lex, 'r')
# speed up search_pred_string by using a single transaction
ctx = PredSense.wn.ctx()

for l in tdl.parse(f):
    lid=l.identifier
    if 'SYNSEM' in [f for (f,v) in l.features()]:
        if 'LKEYS.KEYREL.PRED' in [f for (f,v) in l['SYNSEM'].features()]:
            if isinstance(l['SYNSEM']['LKEYS.KEYREL.PRED'],str):
                pred = l['SYNSEM']['LKEYS.KEYREL.PRED']
                synsets = PredSense.search_pred_string(pred, ctx=ctx)
                if synsets:
                    for ss in synsets:
                        print (lid, ss.synsetid,ss.lemmas)
                        print ('# {}\n'.format("; ".join(ss.defs)))
                else:
                    print ('No synsets for {}, {}, {}'.format(repr(l.identifier), repr(pred), repr(synsets)),
                           file=log)
            else:
                ### how do I get the type?
                # print(l.identifier,
                #       l['SYNSEM']['LKEYS.KEYREL.PRED'],
                #       l['SYNSEM']['LKEYS.KEYREL.PRED'].features(),
                #       l['SYNSEM']['LKEYS.KEYREL.PRED'].type)
                print ('LKEYS.KEYREL.PRED is type for {}'.format(lid), file=log)
        else:
            print ('No LKEYS.KEYREL.PRED for {}'.format(l.identifier), file=log)
    else:
        print ('No SYNSEM for {}'.format(l.identifier), file=log)
#    print (l.identifier, l.features(),l['SYNSEM'].features())


text:
namespace clang {

class Preprocessor;

namespace ento {

class PathDiagnosticConsumer;
typedef std::vector<PathDiagnosticConsumer*> PathDiagnosticConsumers;

void createHTMLDiagnosticConsumer(PathDiagnosticConsumers &C,
                                  const std::string& prefix,
                                  const Preprocessor &PP);

void createPlistDiagnosticConsumer(PathDiagnosticConsumers &C,
                                   const std::string& prefix,
                                   const Preprocessor &PP);

void createPlistMultiFileDiagnosticConsumer(PathDiagnosticConsumers &C,
                                            const std::string& prefix,
                                            const Preprocessor &PP);

void createTextPathDiagnosticConsumer(PathDiagnosticConsumers &C,
                                      const std::string& prefix,
                                      const Preprocessor &PP);

} // end 'ento' namespace
} // end 'clang' namespace

#endif


text:
//=================================================================================================

//=================================================================================================

#ifndef _BLAZE_MATH_ADAPTORS_STRICTLYUPPERMATRIX_UPPERPROXY_H_
#define _BLAZE_MATH_ADAPTORS_STRICTLYUPPERMATRIX_UPPERPROXY_H_

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <blaze/math/Aliases.h>
#include <blaze/math/constraints/Expression.h>
#include <blaze/math/constraints/Hermitian.h>
#include <blaze/math/constraints/Lower.h>
#include <blaze/math/constraints/Matrix.h>
#include <blaze/math/constraints/Symmetric.h>
#include <blaze/math/constraints/Upper.h>
#include <blaze/math/Exception.h>
#include <blaze/math/InitializerList.h>
#include <blaze/math/proxy/Proxy.h>
#include <blaze/math/shims/Clear.h>
#include <blaze/math/shims/IsDefault.h>
#include <blaze/math/shims/IsNaN.h>
#include <blaze/math/shims/IsOne.h>
#include <blaze/math/shims/IsReal.h>
#include <blaze/math/shims/IsZero.h>
#include <blaze/math/shims/Reset.h>
#include <blaze/util/constraints/Const.h>
#include <blaze/util/constraints/Pointer.h>
#include <blaze/util/constraints/Reference.h>
#include <blaze/util/constraints/Volatile.h>
#include <blaze/util/typetraits/AddConst.h>
#include <blaze/util/typetraits/AddReference.h>
#include <blaze/util/Types.h>

namespace blaze {

//=================================================================================================
//
//  CLASS DEFINITION
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Access proxy for strictly upper triangular matrices.
// \ingroup strictly_upper_matrix
//
// The StrictlyUpperProxy provides controlled access to the elements of a non-const strictly upper
// triangular matrix. It guarantees that the strictly upper matrix invariant is not violated, i.e.
// that elements on the diagonal and in the lower part of the matrix remain 0. The following
// example illustrates this by means of a \f$ 3 \times 3 \f$ dense strictly upper triangular
// matrix:

   \code
   // Creating a 3x3 strictly upper triangular dense matrix
   blaze::StrictlyUpperMatrix< blaze::DynamicMatrix<int> > A( 3UL );

   A(0,1) = -2;  //        ( 0 -2  3 )
   A(0,2) =  3;  // => A = ( 0  0  5 )
   A(1,2) =  5;  //        ( 0  0  0 )

   A(1,1) =  4;  // Invalid assignment to diagonal matrix element; results in an exception!
   A(2,0) =  7;  // Invalid assignment to lower matrix element; results in an exception!
   \endcode
*/
template< typename MT >  // Type of the adapted matrix
class StrictlyUpperProxy
   : public Proxy< StrictlyUpperProxy<MT>, ElementType_<MT> >
{
 private:
   //**Type definitions****************************************************************************
   //! Reference type of the underlying matrix type.
   using ReferenceType = AddConst_< Reference_<MT> >;
   //**********************************************************************************************

 public:
   //**Type definitions****************************************************************************
   using RepresentedType = ElementType_<MT>;              //!< Type of the represented matrix element.
   using RawReference    = AddReference_<ReferenceType>;  //!< Reference-to-non-const to the represented element.
   using ConstReference  = const RepresentedType&;        //!< Reference-to-const to the represented element.
   //**********************************************************************************************

   //**Constructors********************************************************************************
   /*!\name Constructors */
   //@{
   explicit inline StrictlyUpperProxy( MT& matrix, size_t row, size_t column );
            inline StrictlyUpperProxy( const StrictlyUpperProxy& uup );
   //@}
   //**********************************************************************************************

   //**Destructor**********************************************************************************
   // No explicitly declared destructor.
   //**********************************************************************************************

   //**Assignment operators************************************************************************
   /*!\name Assignment operators */
   //@{
   inline const StrictlyUpperProxy& operator= ( const StrictlyUpperProxy& uup ) const;

   template< typename T >
   inline const StrictlyUpperProxy& operator=( initializer_list<T> list ) const;

   template< typename T >
   inline const StrictlyUpperProxy& operator=( initializer_list< initializer_list<T> > list ) const;

   template< typename T > inline const StrictlyUpperProxy& operator= ( const T& value ) const;
   template< typename T > inline const StrictlyUpperProxy& operator+=( const T& value ) const;
   template< typename T > inline const StrictlyUpperProxy& operator-=( const T& value ) const;
   template< typename T > inline const StrictlyUpperProxy& operator*=( const T& value ) const;
   template< typename T > inline const StrictlyUpperProxy& operator/=( const T& value ) const;
   template< typename T > inline const StrictlyUpperProxy& operator%=( const T& value ) const;
   //@}
   //**********************************************************************************************

   //**Utility functions***************************************************************************
   /*!\name Utility functions */
   //@{
   inline RawReference get()          const noexcept;
   inline bool         isRestricted() const noexcept;
   //@}
   //**********************************************************************************************

   //**Conversion operator*************************************************************************
   /*!\name Conversion operator */
   //@{
   inline operator ConstReference() const noexcept;
   //@}
   //**********************************************************************************************

 private:
   //**Member variables****************************************************************************
   /*!\name Member variables */
   //@{
   ReferenceType value_;    //!< Reference to the accessed matrix element.
   const bool restricted_;  //!< Access flag for the accessed matrix element.
                            /*!< The flag indicates if access to the matrix element is
                                 restricted. It is \a true in case the proxy represents an
                                 element on the diagonal or in the lower part of the matrix. */
   //@}
   //**********************************************************************************************

   //**Compile time checks*************************************************************************
   /*! \cond BLAZE_INTERNAL */
   BLAZE_CONSTRAINT_MUST_BE_MATRIX_TYPE              ( MT );
   BLAZE_CONSTRAINT_MUST_NOT_BE_REFERENCE_TYPE       ( MT );
   BLAZE_CONSTRAINT_MUST_NOT_BE_POINTER_TYPE         ( MT );
   BLAZE_CONSTRAINT_MUST_NOT_BE_CONST                ( MT );
   BLAZE_CONSTRAINT_MUST_NOT_BE_VOLATILE             ( MT );
   BLAZE_CONSTRAINT_MUST_NOT_BE_EXPRESSION_TYPE      ( MT );
   BLAZE_CONSTRAINT_MUST_NOT_BE_SYMMETRIC_MATRIX_TYPE( MT );
   BLAZE_CONSTRAINT_MUST_NOT_BE_HERMITIAN_MATRIX_TYPE( MT );
   BLAZE_CONSTRAINT_MUST_NOT_BE_LOWER_MATRIX_TYPE    ( MT );
   BLAZE_CONSTRAINT_MUST_NOT_BE_UPPER_MATRIX_TYPE    ( MT );
   /*! \endcond */
   //**********************************************************************************************
};
//*************************************************************************************************

//=================================================================================================
//
//  CONSTRUCTORS
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Initialization constructor for a StrictlyUpperProxy.
//
// \param matrix Reference to the adapted matrix.
// \param row The row-index of the accessed matrix element.
// \param column The column-index of the accessed matrix element.
*/
template< typename MT >  // Type of the adapted matrix
inline StrictlyUpperProxy<MT>::StrictlyUpperProxy( MT& matrix, size_t row, size_t column )
   : value_     ( matrix( row, column ) )  // Reference to the accessed matrix element
   , restricted_( column <= row )          // Access flag for the accessed matrix element
{}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief The copy constructor for StrictlyUpperProxy.
//
// \param uup Proxy to be copied.
*/
template< typename MT >  // Type of the adapted matrix
inline StrictlyUpperProxy<MT>::StrictlyUpperProxy( const StrictlyUpperProxy& uup )
   : value_     ( uup.value_      )  // Reference to the accessed matrix element
   , restricted_( uup.restricted_ )  // Access flag for the accessed matrix element
{}
//*************************************************************************************************

//=================================================================================================
//
//  OPERATORS
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Copy assignment operator for StrictlyUpperProxy.
//
// \param uup Proxy to be copied.
// \return Reference to the assigned proxy.
// \exception std::invalid_argument Invalid assignment to diagonal or lower matrix element.
//
// In case the proxy represents an element on the diagonal or in the lower part of the matrix,
// a \a std::invalid_argument exception is thrown.
*/
template< typename MT >  // Type of the adapted matrix
inline const StrictlyUpperProxy<MT>& StrictlyUpperProxy<MT>::operator=( const StrictlyUpperProxy& uup ) const
{
   if( restricted_ ) {
      BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to diagonal or lower matrix element" );
   }

   value_ = uup.value_;

   return *this;
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Initializer list assignment to the accessed matrix element.
//
// \param list The list to be assigned to the matrix element.
// \return Reference to the assigned proxy.
// \exception std::invalid_argument Invalid assignment to diagonal or lower matrix element.
//
// In case the proxy represents an element on the diagonal or in the lower part of the matrix,
// a \a std::invalid_argument exception is thrown.
*/
template< typename MT >  // Type of the adapted matrix
template< typename T >   // Type of the right-hand side value
inline const StrictlyUpperProxy<MT>&
   StrictlyUpperProxy<MT>::operator=( initializer_list<T> list ) const
{
   if( restricted_ ) {
      BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to diagonal or lower matrix element" );
   }

   value_ = list;

   return *this;
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Initializer list assignment to the accessed matrix element.
//
// \param list The list to be assigned to the matrix element.
// \return Reference to the assigned proxy.
// \exception std::invalid_argument Invalid assignment to diagonal or lower matrix element.
//
// In case the proxy represents an element on the diagonal or in the lower part of the matrix,
// a \a std::invalid_argument exception is thrown.
*/
template< typename MT >  // Type of the adapted matrix
template< typename T >   // Type of the right-hand side value
inline const StrictlyUpperProxy<MT>&
   StrictlyUpperProxy<MT>::operator=( initializer_list< initializer_list<T> > list ) const
{
   if( restricted_ ) {
      BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to diagonal or lower matrix element" );
   }

   value_ = list;

   return *this;
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Assignment to the accessed matrix element.
//
// \param value The new value of the matrix element.
// \return Reference to the assigned proxy.
// \exception std::invalid_argument Invalid assignment to diagonal or lower matrix element.
//
// In case the proxy represents an element on the diagonal or in the lower part of the matrix,
// a \a std::invalid_argument exception is thrown.
*/
template< typename MT >  // Type of the adapted matrix
template< typename T >   // Type of the right-hand side value
inline const StrictlyUpperProxy<MT>& StrictlyUpperProxy<MT>::operator=( const T& value ) const
{
   if( restricted_ ) {
      BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to diagonal or lower matrix element" );
   }

   value_ = value;

   return *this;
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Addition assignment to the accessed matrix element.
//
// \param value The right-hand side value to be added to the matrix element.
// \return Reference to the assigned proxy.
// \exception std::invalid_argument Invalid assignment to diagonal or lower matrix element.
//
// In case the proxy represents an element on the diagonal or in the lower part of the matrix,
// a \a std::invalid_argument exception is thrown.
*/
template< typename MT >  // Type of the adapted matrix
template< typename T >   // Type of the right-hand side value
inline const StrictlyUpperProxy<MT>& StrictlyUpperProxy<MT>::operator+=( const T& value ) const
{
   if( restricted_ ) {
      BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to diagonal or lower matrix element" );
   }

   value_ += value;

   return *this;
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Subtraction assignment to the accessed matrix element.
//
// \param value The right-hand side value to be subtracted from the matrix element.
// \return Reference to the assigned proxy.
// \exception std::invalid_argument Invalid assignment to diagonal or lower matrix element.
//
// In case the proxy represents an element on the diagonal or in the lower part of the matrix,
// a \a std::invalid_argument exception is thrown.
*/
template< typename MT >  // Type of the adapted matrix
template< typename T >   // Type of the right-hand side value
inline const StrictlyUpperProxy<MT>& StrictlyUpperProxy<MT>::operator-=( const T& value ) const
{
   if( restricted_ ) {
      BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to diagonal or lower matrix element" );
   }

   value_ -= value;

   return *this;
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Multiplication assignment to the accessed matrix element.
//
// \param value The right-hand side value for the multiplication.
// \return Reference to the assigned proxy.
// \exception std::invalid_argument Invalid assignment to diagonal or lower matrix element.
//
// In case the proxy represents an element on the diagonal or in the lower part of the matrix,
// a \a std::invalid_argument exception is thrown.
*/
template< typename MT >  // Type of the adapted matrix
template< typename T >   // Type of the right-hand side value
inline const StrictlyUpperProxy<MT>& StrictlyUpperProxy<MT>::operator*=( const T& value ) const
{
   if( restricted_ ) {
      BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to diagonal or lower matrix element" );
   }

   value_ *= value;

   return *this;
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Division assignment to the accessed matrix element.
//
// \param value The right-hand side value for the division.
// \return Reference to the assigned proxy.
// \exception std::invalid_argument Invalid assignment to diagonal or lower matrix element.
//
// In case the proxy represents an element on the diagonal or in the lower part of the matrix,
// a \a std::invalid_argument exception is thrown.
*/
template< typename MT >  // Type of the adapted matrix
template< typename T >   // Type of the right-hand side value
inline const StrictlyUpperProxy<MT>& StrictlyUpperProxy<MT>::operator/=( const T& value ) const
{
   if( restricted_ ) {
      BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to diagonal or lower matrix element" );
   }

   value_ /= value;

   return *this;
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Modulo assignment to the accessed matrix element.
//
// \param value The right-hand side value for the modulo operation.
// \return Reference to the assigned proxy.
// \exception std::invalid_argument Invalid assignment to diagonal or lower matrix element.
//
// In case the proxy represents an element on the diagonal or in the lower part of the matrix,
// a \a std::invalid_argument exception is thrown.
*/
template< typename MT >  // Type of the adapted matrix
template< typename T >   // Type of the right-hand side value
inline const StrictlyUpperProxy<MT>& StrictlyUpperProxy<MT>::operator%=( const T& value ) const
{
   if( restricted_ ) {
      BLAZE_THROW_INVALID_ARGUMENT( "Invalid assignment to diagonal or lower matrix element" );
   }

   value_ %= value;

   return *this;
}
//*************************************************************************************************

//=================================================================================================
//
//  UTILITY FUNCTIONS
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Returning the value of the accessed matrix element.
//
// \return Direct/raw reference to the accessed matrix element.
*/
template< typename MT >  // Type of the adapted matrix
inline typename StrictlyUpperProxy<MT>::RawReference StrictlyUpperProxy<MT>::get() const noexcept
{
   return value_;
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Returns whether the proxy represents a restricted matrix element..
//
// \return \a true in case access to the matrix element is restricted, \a false if not.
*/
template< typename MT >  // Type of the adapted matrix
inline bool StrictlyUpperProxy<MT>::isRestricted() const noexcept
{
   return restricted_;
}
//*************************************************************************************************

//=================================================================================================
//
//  CONVERSION OPERATOR
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Conversion to the accessed matrix element.
//
// \return Reference-to-const to the accessed matrix element.
*/
template< typename MT >  // Type of the adapted matrix
inline StrictlyUpperProxy<MT>::operator ConstReference() const noexcept
{
   return static_cast<ConstReference>( value_ );
}
//*************************************************************************************************

//=================================================================================================
//
//  GLOBAL FUNCTIONS
//
//=================================================================================================

//*************************************************************************************************
/*!\name StrictlyUpperProxy global functions */
//@{
template< typename MT >
inline void reset( const StrictlyUpperProxy<MT>& proxy );

template< typename MT >
inline void clear( const StrictlyUpperProxy<MT>& proxy );

template< bool RF, typename MT >
inline bool isDefault( const StrictlyUpperProxy<MT>& proxy );

template< bool RF, typename MT >
inline bool isReal( const StrictlyUpperProxy<MT>& proxy );

template< bool RF, typename MT >
inline bool isZero( const StrictlyUpperProxy<MT>& proxy );

template< bool RF, typename MT >
inline bool isOne( const StrictlyUpperProxy<MT>& proxy );

template< typename MT >
inline bool isnan( const StrictlyUpperProxy<MT>& proxy );
//@}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Resetting the represented element to the default initial values.
// \ingroup strictly_upper_matrix
//
// \param proxy The given access proxy.
// \return void
//
// This function resets the element represented by the access proxy to its default initial
// value.
*/
template< typename MT >
inline void reset( const StrictlyUpperProxy<MT>& proxy )
{
   using blaze::reset;

   reset( proxy.get() );
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Clearing the represented element.
// \ingroup strictly_upper_matrix
//
// \param proxy The given access proxy.
// \return void
//
// This function clears the element represented by the access proxy to its default initial
// state.
*/
template< typename MT >
inline void clear( const StrictlyUpperProxy<MT>& proxy )
{
   using blaze::clear;

   clear( proxy.get() );
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Returns whether the represented element is in default state.
// \ingroup strictly_upper_matrix
//
// \param proxy The given access proxy
// \return \a true in case the represented element is in default state, \a false otherwise.
//
// This function checks whether the element represented by the access proxy is in default state.
// In case it is in default state, the function returns \a true, otherwise it returns \a false.
*/
template< bool RF, typename MT >
inline bool isDefault( const StrictlyUpperProxy<MT>& proxy )
{
   using blaze::isDefault;

   return isDefault<RF>( proxy.get() );
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Returns whether the matrix element represents a real number.
// \ingroup strictly_upper_matrix
//
// \param proxy The given access proxy.
// \return \a true in case the matrix element represents a real number, \a false otherwise.
//
// This function checks whether the element represented by the access proxy represents the a
// real number. In case the element is of built-in type, the function returns \a true. In case
// the element is of complex type, the function returns \a true if the imaginary part is equal
// to 0. Otherwise it returns \a false.
*/
template< bool RF, typename MT >
inline bool isReal( const StrictlyUpperProxy<MT>& proxy )
{
   using blaze::isReal;

   return isReal<RF>( proxy.get() );
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Returns whether the represented element is 0.
// \ingroup strictly_upper_matrix
//
// \param proxy The given access proxy.
// \return \a true in case the represented element is 0, \a false otherwise.
//
// This function checks whether the element represented by the access proxy represents the numeric
// value 0. In case it is 0, the function returns \a true, otherwise it returns \a false.
*/
template< bool RF, typename MT >
inline bool isZero( const StrictlyUpperProxy<MT>& proxy )
{
   using blaze::isZero;

   return isZero<RF>( proxy.get() );
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Returns whether the represented element is 1.
// \ingroup strictly_upper_matrix
//
// \param proxy The given access proxy.
// \return \a true in case the represented element is 1, \a false otherwise.
//
// This function checks whether the element represented by the access proxy represents the numeric
// value 1. In case it is 1, the function returns \a true, otherwise it returns \a false.
*/
template< bool RF, typename MT >
inline bool isOne( const StrictlyUpperProxy<MT>& proxy )
{
   using blaze::isOne;

   return isOne<RF>( proxy.get() );
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Returns whether the represented element is not a number.
// \ingroup strictly_upper_matrix
//
// \param proxy The given access proxy.
// \return \a true in case the represented element is in not a number, \a false otherwise.
//
// This function checks whether the element represented by the access proxy is not a number (NaN).
// In case it is not a number, the function returns \a true, otherwise it returns \a false.
*/
template< typename MT >
inline bool isnan( const StrictlyUpperProxy<MT>& proxy )
{
   using blaze::isnan;

   return isnan( proxy.get() );
}
//*************************************************************************************************

} // namespace blaze

#endif


text:
Set-StrictMode -Version latest
$ErrorAction = "Stop"
. $PSScriptRoot/config.ps1

<#
.SYNOPSIS
    Configure automatich shim generation.

.DESCRIPTION
    Per default, chocolatey installs shims for every executable found in the
    package installation folder. The shim generation can be configured on
    a file-to-file basis by creating appropriate *.ignore and *.gui files. This
    cmdlet simplifies this task.

    See also https://chocolatey.org/docs/features-shim.

.PARAMETER Pattern
    Pattern identifiying executables to be configured. Can be an array, too.

    A pattern is matched against the end of an executable's path relative to the
    target directory of the package being installed (e.g.
    C:\ProgramData\chocolatey\lib\shimgen.extension - this does not include the
    tools subdirectory!).
    Wildcards *, **, ? are supported:
        *  : matching 0 to n characters, but not path separators
        ** : matching 0 to n characters, including path separators
        ?  : matching a single character, but not path separators

.PARAMETER Mode
    Shim generation mode:
        - Ignore  : Don't generate a shim for matching files
        - Default : Restore default shim generation behavior for matching files.
                    That is: Generate a shim for matching executable,
                    autodetecting gui applications. If a gui application is
                    found, the shim does not wait for the application to exit.
                    Otherwise the shim keeps running.
        - Gui     : Generate a shim for matching files, that does not wait for
                    the shimed application to exit.

.PARAMETER Invert
    OPTIONAL - Match iall executables not matched by any of the $Pattern-s.

.OUTPUT
    All matching executables.

.LINK
    https://chocolatey.org/docs/features-shim
#>
function Set-AutoShim {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [String[]] $Pattern,

        [Parameter(Mandatory=$true)]
        [ValidateSet("Default", "Ignore", "Gui")]
        [String] $Mode,

        [Parameter(Mandatory=$false)]
        [Switch] $Invert = $false
    )

    $pkgFolder   = $env:chocolateyPackageFolder
    $executables = Get-ChildItem $pkgFolder -Filter "*.exe" -Recurse
    $processed   = @()

    $regexPattern = $Pattern | %{
        $r = [Regex]::Escape($_) `
            -replace "(\\\\|/)" , "[/\\]" `
            -replace "\\\*\\\*" , ".*" `
            -replace "\\\*"     , "[^/\\]*" `
            -replace "\\\?"     , "[^/\\]"
        return $r + "$"
    }

    ForEach ($exe in $executables) {
        $absPath = $exe.FullName

        Try {
            Push-Location
            Set-Location $pkgFolder

            $relPath = Resolve-Path -LiteralPath $absPath -Relative
        } Finally {
            Pop-Location
        }

        $isMatch = $Invert
        ForEach ($r in $regexPattern) {
            If ($relPath -match $r) {
                $isMatch = -not $Invert
                break
            }
        }

        If ($isMatch) {
            If ($Mode -eq "Ignore") {
                New-Item -Force "$absPath.ignore" | Out-Null
            } Else {
                Remove-Item -Force -LiteralPath "$absPath.ignore" -ErrorAction SilentlyContinue
            }

            If ($Mode -eq "Gui") {
                New-Item -Force "$absPath.gui" | Out-Null
            } Else {
                Remove-Item -Force -LiteralPath "$absPath.gui" -ErrorAction SilentlyContinue
            }

            $processed += $absPath
        }
    }

    return $processed
}


text:
use Modern::Perl;
use WWW::Mechanize::Firefox;
my $myurl       = 'http://google.com';
my $firefox_bin = 'C:/Program Files/Mozilla Firefox/firefox.exe';

#################### Open URL #########################
## creating firefox obj
my $mech = WWW::Mechanize::Firefox->new(
    launch    => $firefox_bin,
    create    => 1,
    autoclose => 0,
);

# open page/url
$mech->get($myurl);
print "\nRequest- sucessfully" if $mech->success();    ## Request status
my $http_status = $mech->status();                     ## http status
if ( $http_status eq 200 ) {
    print "\nHTTP_Status- OK";
}
elsif ( $http_status eq 404 ) {
    print "\nHTTP_Status- Not Found";
}
else {
    print "\nHTTP_Status- Error";
}
#######################################################

#######################################################

####### Profile and Tab list #######
# my $ffobj        = Firefox::Application->new();
# my $profile_name = $ffobj->current_profile->{name};
# # if ( $profile_name eq "yslow" ) {
    # # print "\nFirefox profile_name - $profile_name";
# # }
# # else { print "\nFirefox profile is wrong! will die\n"; exit(2); }
# ## tab list
# my @tab_info  = $ffobj->openTabs();
# my $tab_count = @tab_info;
# print "\nTotal no of Tab - $tab_count";
# if ( $tab_count > 50 ) {
    # print "\n Clossing the all Tabs";
    # foreach my $hash_tab (@tab_info) {
        # my ( $tab_title, $tab_location ) =
          # ( $hash_tab->{title}, $hash_tab->{location} );
        # print "\n $tab_title => $tab_location | $hash_tab";
        # shift(@tab_info);
        # $ffobj->closeTab( $ffobj->selectedTab() );
    # }
# }
# else {

    # #my $tabobj = $ffobj->addTab(autoclose => 0);
    # print "\nYou can create new Tab";
# }
# #### playing with firefox tab ####
# @tab_info = $ffobj->openTabs();
# my $arraySize = $#tab_info;
# my $LastTab   = $tab_info[$arraySize];
# print "\nSubmitting Yslow results to showslow...\n";
# my $LastTabRef = $LastTab->{'tab'};
# $ffobj->activateTab($LastTabRef);
####
#http://www.indiangnu.org/wp-content/uploads/2012/firefox-cli-for-yslow-url-pl.txt
# use WWW::Mechanize::Firefox;
# my $mech = WWW::Mechanize::Firefox->new(
# launch => 'C:/Program Files/Mozilla Firefox/firefox.exe',
# );
# $mech->get('http://google.com');
#http://www.perlmonks.org/?node_id=1021051
# $ff = Firefox::Application->new(
# launch => 'C:/Program Files/Mozilla Firefox/firefox.exe',
# );
# $ff->quit( restart => 1 ); # restart
# sleep 4;

# $ff->get('http://google.com');
#perlcritic


text:
"""
Logging facilities

This file should have an absolute minimum in imports. If you'd like to layer
additional functionality on top of some of the methods below, wrap them in
a higher layer module.
"""
from traceback import format_exc
from twisted.python import log

def log_trace(errmsg=None):
    """
    Log a traceback to the log. This should be called
    from within an exception. errmsg is optional and
    adds an extra line with added info.
    """
    tracestring = format_exc()
    try:
        if tracestring:
            for line in tracestring.splitlines():
                log.msg('[::] %s' % line)
        if errmsg:
            try:
                errmsg = str(errmsg)
            except Exception, e:
                errmsg = str(e)
            for line in errmsg.splitlines():
                log.msg('[EE] %s' % line)
    except Exception:
        log.msg('[EE] %s' % errmsg)

def log_errmsg(errmsg):
    """
    Prints/logs an error message to the server log.

    errormsg: (string) The message to be logged.
    """
    try:
        errmsg = str(errmsg)
    except Exception, e:
        errmsg = str(e)
    for line in errmsg.splitlines():
        log.msg('[EE] %s' % line)
    #log.err('ERROR: %s' % (errormsg,))

def log_warnmsg(warnmsg):
    """
    Prints/logs any warnings that aren't critical but should be noted.

    warnmsg: (string) The message to be logged.
    """
    try:
        warnmsg = str(warnmsg)
    except Exception, e:
        warnmsg = str(e)
    for line in warnmsg.splitlines():
        log.msg('[WW] %s' % line)
    #log.msg('WARNING: %s' % (warnmsg,))

def log_infomsg(infomsg):
    """
    Prints any generic debugging/informative info that should appear in the log.

    infomsg: (string) The message to be logged.
    """
    try:
        infomsg = str(infomsg)
    except Exception, e:
        infomsg = str(e)
    for line in infomsg.splitlines():
        log.msg('[..] %s' % line)

def log_depmsg(depmsg):
    """
    Prints a deprecation message
    """
    try:
        depmsg = str(depmsg)
    except Exception, e:
        depmsg = str(e)
    for line in depmsg.splitlines():
        log.msg('[DP] %s' % line)


text:
package io.cloudslang.content.jclouds.entities.inputs;

/**
 * Created by persdana on 7/13/2015.
 */
public class ListRegionsInputs extends CommonInputs {
    public static final String DELIMITER = "delimiter";
    private String delimiter;

    public ListRegionsInputs(String provider, String identity, String credential, String endpoint, String proxyHost, String proxyPort, String delimiter) {
        super(provider, identity, credential, endpoint, proxyHost, proxyPort);
        this.delimiter = delimiter;
    }

    public String getDelimiter() {
        return delimiter;
    }

    public void setDelimiter(String delimiter) {
        this.delimiter = delimiter;
    }
}


text:
require 'rails_helper'

RSpec.describe Rating, type: :model do

  it {should belong_to :course}
  it {should validate_inclusion_of(:rating).in_range(1..5)}
end


text:
<?php defined('C5_EXECUTE') or die('Access Denied.');
/**
 * @var Concrete\Core\Application\Service\Dashboard $dashboard
 * @var Concrete\Core\Form\Service\Form $form
 * @var Concrete\Core\Html\Service\Html $html
 * @var Concrete\Core\Application\Service\UserInterface $interface
 * @var Concrete\Core\Validation\CSRF\Token $token
 * @var Concrete\Controller\SinglePage\Dashboard\System\Registration\Profiles $controller
 * @var bool $publicProfiles
 * @var bool $gravatarFallback
 * @var bool $displayAccountMenu
 * @var string $gravatarMaxLevel
 * @var array $gravatarMaxLevels
 * @var string $gravatarImageSet
 * @var array $gravatarImageSets
 */
?>

<form method="POST" action="<?= $controller->action('update_profiles') ?>">
    <?php $token->output('update_profile') ?>

        <?= $form->label('public_profiles', t('Profile Options')) ?>

            <?= $form->checkbox('public_profiles', '1', $publicProfiles) ?>
            <?= t('Enable public profiles.') ?>

        <?= $form->label('display_account_menu', t('Account Menu')) ?>

            <?= $form->checkbox('display_account_menu', '1', $displayAccountMenu) ?>

                <?= t('Show the account menu when logged in.') ?>

                <?= t('Site themes may override this value.') ?>

        <?= $form->label('gravatar_fallback', t('Fall Back To Gravatar')) ?>

            <?= $form->checkbox('gravatar_fallback', 1, $gravatarFallback) ?>
            <?= t('Use image from gravatar.com if the user has not uploaded one.') ?>

        <?= $form->label('gravatar_max_level', t('Maximum Gravatar Rating')) ?>
        <?= $form->select('gravatar_max_level', $gravatarMaxLevels, $gravatarMaxLevel) ?>

    	<?= $form->label('gravatarImageSet', t('Gravatar Image Set')) ?>
        <?= $form->select('gravatar_image_set', $gravatarImageSets, $gravatarImageSet) ?>

            <button class="float-end btn btn-primary" type="submit" ><?=t('Save')?></button>

</form>


text:
<!DOCTYPE html>

        <meta charset="utf-8"/>
        <title>Test</title>
        <meta name="keywords" content=""/>
        <meta name="description" content="This is auto-generated by sublime-custom-insert"/>
        <meta name="revised" value="yanni4night,2015/12/18"/>

        <link rel="stylesheet" href="mocha.css"/>


text:
// Generated by LiveScript 1.4.0
var path, rework, reworkUrl, through, isDataUrl, isNetworkUrl, isRelative, isAbsolute, isIgnore, urlMap, urlConvert, cssUrlConvert;
path = require('path');
rework = require('rework');
reworkUrl = require('rework-plugin-url');
through = require('through2');
/*
 * options
 *   root 根目录
 *   path 路径
 *   type 转换到relative相对路径,absolute约对路径,network网络路径
 *   map 从一个类型映射到另一个类型
 *   ignore 过滤
 *
 */
isDataUrl = function(url){
  return /^data:image/.exec(url);
};
isNetworkUrl = function(url){
  return /^(?:http(?:s|):|)\/\//.exec(url);
};
isRelative = function(url){
  return !/^\./.test(url) || !/^(?:(?:http(?:s|):|)\/\/|data:|\/)/.test(url);
};
isAbsolute = function(url){
  return /^\//.exec(url);
};
isIgnore = function(url, rules){
  var i$, len$, key, rule;
  if (!rules) {
    return false;
  }
  if (!Array.isArray(rules)) {
    rules = [].concat(rules);
  }
  for (i$ = 0, len$ = rules.length; i$ < len$; ++i$) {
    key = i$;
    rule = rules[i$];
    if (typeof rule === 'string') {
      if (url === rule) {
        return true;
      }
    }
    if (typeof rule === 'object' && rule !== null && rule.constructor === RegExp) {
      if (rule.match(url) !== null) {
        return true;
      }
    }
  }
};
urlMap = function(url, maps){
  var i$, len$, key, map, mapMatch;
  if (!Array.isArray(maps)) {
    maps = [].concat(maps);
  }
  for (i$ = 0, len$ = maps.length; i$ < len$; ++i$) {
    key = i$;
    map = maps[i$];
    mapMatch = new RegExp("^" + key);
    if (reg.text(url) !== null) {
      return url.replace(mapMatch, map);
    }
  }
};
urlConvert = function(file, options){
  var cssPath, cssContent, replaceCount, urlReplace, newCssContent, e;
  cssPath = path.dirname(file.path);
  cssContent = file.contents.toString();
  replaceCount = 0;
  urlReplace = function(url){
    var baseName, urlPath, relativeUrlPath;
    if (isDataUrl(url)) {
      return url;
    }
    if (isIgnore(url, options.ignore)) {
      return url;
    }
    if (options.map) {
      url = urlMap(url, options.map);
    }
    if (options.type === 'network' || isNetworkUrl(options.path)) {
      if (isNetworkUrl(url)) {
        return url;
      }
      options.path = options.path.replace(/\/$/, '');
      if (isRelative(url)) {
        baseName = path.basename(url);
        urlPath = path.resolve(cssPath, path.dirname(url));
        relativeUrlPath = path.relative(options.root, urlPath);
        replaceCount += 1;
        return options.path + "/" + relativeUrlPath + "/" + baseName;
      } else if (isAbsolute(url)) {
        replaceCount += 1;
        return url.replace(/^\//, options.path);
      }
    } else if (options.type === 'absolute' || isAbsolute(options.path)) {
      if (isAbsolute(url) || isNetworkUrl(url)) {
        return url;
      }
      if (isRelative(url)) {
        baseName = path.basename(url);
        urlPath = path.resolve(cssPath, path.dirname(url));
        relativeUrlPath = path.relative(options.root, urlPath);
        replaceCount += 1;
        return options.path + "" + relativeUrlPath + "/" + baseName;
      }
    } else {
      return url;
    }
  };
  if (options.useRework) {
    try {
      newCssContent = rework(cssContent).use(reworkUrl(urlReplace)).toString();
    } catch (e$) {
      e = e$;
      console.error("css file: " + file.path);
      console.error(e.stack);
      throw new Error("rework error");
    }
  } else {
    try {
      newCssContent = cssContent.replace(/(url\(\s*['"]?)([^'"\)]*)(['"]?\s*\))/g, function(all, start, url, end){
        if (url.length) {
          url = urlReplace(url);
        }
        return start + "" + url + end;
      });
    } catch (e$) {}
  }
  if (replaceCount > 0) {
    return newCssContent;
  } else {
    return false;
  }
};
cssUrlConvert = function(options){
  options || (options = {});
  return through.obj(function(file, enc, cb){
    var cssContent;
    cssContent = urlConvert(file, options);
    if (cssContent) {
      file.contents = new Buffer(cssContent);
    }
    this.push(file);
    return cb();
  });
};
module.exports = cssUrlConvert;


text:
from __future__ import unicode_literals

import unittest, frappe, pyotp
from werkzeug.wrappers import Request
from werkzeug.test import EnvironBuilder
from frappe.auth import HTTPRequest
from frappe.utils import cint
from frappe.twofactor import (should_run_2fa, authenticate_for_2factor, get_cached_user_pass,
	two_factor_is_enabled_for_, confirm_otp_token, get_otpsecret_for_, get_verification_obj,
	render_string_template, two_factor_is_enabled)

import time

class TestTwoFactor(unittest.TestCase):
	def setUp(self):
		self.http_requests = create_http_request()
		self.login_manager = frappe.local.login_manager
		self.user = self.login_manager.user

	def tearDown(self):
		frappe.local.response['verification'] = None
		frappe.local.response['tmp_id'] = None
		disable_2fa()
		frappe.clear_cache(user=self.user)

	def test_should_run_2fa(self):
		'''Should return true if enabled.'''
		toggle_2fa_all_role(state=True)
		self.assertTrue(should_run_2fa(self.user))
		toggle_2fa_all_role(state=False)
		self.assertFalse(should_run_2fa(self.user))

	def test_get_cached_user_pass(self):
		'''Cached data should not contain user and pass before 2fa.'''
		user,pwd = get_cached_user_pass()
		self.assertTrue(all([not user, not pwd]))

	def test_authenticate_for_2factor(self):
		'''Verification obj and tmp_id should be set in frappe.local.'''
		authenticate_for_2factor(self.user)
		verification_obj = frappe.local.response['verification']
		tmp_id = frappe.local.response['tmp_id']
		self.assertTrue(verification_obj)
		self.assertTrue(tmp_id)
		for k in ['_usr','_pwd','_otp_secret']:
			self.assertTrue(frappe.cache().get('{0}{1}'.format(tmp_id,k)),
							'{} not available'.format(k))

	def test_two_factor_is_enabled(self):
		'''
		1. Should return true, if enabled and not bypass_2fa_for_retricted_ip_users
		2. Should return false, if not enabled
		3. Should return true, if enabled and not bypass_2fa_for_retricted_ip_users and ip in restrict_ip
		4. Should return true, if enabled and bypass_2fa_for_retricted_ip_users and not restrict_ip
		5. Should return false, if enabled and bypass_2fa_for_retricted_ip_users and ip in restrict_ip
		'''

		#Scenario 1
		enable_2fa()
		self.assertTrue(should_run_2fa(self.user))

		#Scenario 2
		disable_2fa()
		self.assertFalse(should_run_2fa(self.user))

		#Scenario 3
		enable_2fa()
		user = frappe.get_doc('User', self.user)
		user.restrict_ip = frappe.local.request_ip
		user.save()
		self.assertTrue(should_run_2fa(self.user))

		#Scenario 4
		user = frappe.get_doc('User', self.user)
		user.restrict_ip = ""
		user.save()
		enable_2fa(1)
		self.assertTrue(should_run_2fa(self.user))

		#Scenario 5
		user = frappe.get_doc('User', self.user)
		user.restrict_ip = frappe.local.request_ip
		user.save()
		enable_2fa(1)
		self.assertFalse(should_run_2fa(self.user))

	def test_two_factor_is_enabled_for_user(self):
		'''Should return true if enabled for user.'''
		toggle_2fa_all_role(state=True)
		self.assertTrue(two_factor_is_enabled_for_(self.user))
		self.assertFalse(two_factor_is_enabled_for_("Administrator"))
		toggle_2fa_all_role(state=False)
		self.assertFalse(two_factor_is_enabled_for_(self.user))

	def test_get_otpsecret_for_user(self):
		'''OTP secret should be set for user.'''
		self.assertTrue(get_otpsecret_for_(self.user))
		self.assertTrue(frappe.db.get_default(self.user + '_otpsecret'))

	def test_confirm_otp_token(self):
		'''Ensure otp is confirmed'''
		authenticate_for_2factor(self.user)
		tmp_id = frappe.local.response['tmp_id']
		otp = 'wrongotp'
		with self.assertRaises(frappe.AuthenticationError):
			confirm_otp_token(self.login_manager,otp=otp,tmp_id=tmp_id)
		otp = get_otp(self.user)
		self.assertTrue(confirm_otp_token(self.login_manager,otp=otp,tmp_id=tmp_id))
		if frappe.flags.tests_verbose:
			print('Sleeping for 30secs to confirm token expires..')
		time.sleep(30)
		with self.assertRaises(frappe.AuthenticationError):
			confirm_otp_token(self.login_manager,otp=otp,tmp_id=tmp_id)

	def test_get_verification_obj(self):
		'''Confirm verification object is returned.'''
		otp_secret = get_otpsecret_for_(self.user)
		token = int(pyotp.TOTP(otp_secret).now())
		self.assertTrue(get_verification_obj(self.user,token,otp_secret))

	def test_render_string_template(self):
		'''String template renders as expected with variables.'''
		args = {'issuer_name':'Frappe Technologies'}
		_str = 'Verification Code from {{issuer_name}}'
		_str = render_string_template(_str,args)
		self.assertEqual(_str,'Verification Code from Frappe Technologies')

	def test_bypass_restict_ip(self):
		'''
		1. Raise error if user not login from one of the restrict_ip, Bypass restrict ip check disabled by default
		2. Bypass restrict ip check enabled in System Settings
		3. Bypass restrict ip check enabled for User
		'''

		#1
		user = frappe.get_doc('User', self.user)
		user.restrict_ip = "192.168.255.254" #Dummy IP
		user.save()
		enable_2fa(bypass_restrict_ip_check=0)
		with self.assertRaises(frappe.AuthenticationError):
			self.login_manager.validate_ip_address()

		#2
		enable_2fa(bypass_restrict_ip_check=1)
		self.assertIsNone(self.login_manager.validate_ip_address())

		#3
		user = frappe.get_doc('User', self.user)
		user.bypass_restrict_ip_check_if_2fa_enabled = 1
		user.save()
		enable_2fa()
		self.assertIsNone(self.login_manager.validate_ip_address())

def set_request(**kwargs):
	builder = EnvironBuilder(**kwargs)
	frappe.local.request = Request(builder.get_environ())

def create_http_request():
	'''Get http request object.'''
	set_request(method='POST', path='login')
	enable_2fa()
	frappe.form_dict['usr'] = 'test@erpnext.com'
	frappe.form_dict['pwd'] = 'test'
	frappe.local.form_dict['cmd'] = 'login'
	http_requests = HTTPRequest()
	return http_requests

def enable_2fa(bypass_two_factor_auth=0, bypass_restrict_ip_check=0):
	'''Enable Two factor in system settings.'''
	system_settings = frappe.get_doc('System Settings')
	system_settings.enable_two_factor_auth = 1
	system_settings.bypass_2fa_for_retricted_ip_users = cint(bypass_two_factor_auth)
	system_settings.bypass_restrict_ip_check_if_2fa_enabled = cint(bypass_restrict_ip_check)
	system_settings.two_factor_method = 'OTP App'
	system_settings.save(ignore_permissions=True)
	frappe.db.commit()

def disable_2fa():
	system_settings = frappe.get_doc('System Settings')
	system_settings.enable_two_factor_auth = 0
	system_settings.save(ignore_permissions=True)
	frappe.db.commit()

def toggle_2fa_all_role(state=None):
	'''Enable or disable 2fa for 'all' role on the system.'''
	all_role = frappe.get_doc('Role','All')
	if state == None:
		state = False if all_role.two_factor_auth == True else False
	if state not in [True,False]:return
	all_role.two_factor_auth = state
	all_role.save(ignore_permissions=True)
	frappe.db.commit()

def get_otp(user):
	otp_secret = get_otpsecret_for_(user)
	otp = pyotp.TOTP(otp_secret)
	return otp.now()


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.wildfly.swarm.microprofile.faulttolerance.deployment.config (BOM:  * : All 2018.2.0 API)</title>
<meta name="date" content="2018-02-08">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

org.wildfly.swarm.microprofile.faulttolerance.deployment.config

Classes

BulkheadConfig

CircuitBreakerConfig

FallbackConfig

FaultToleranceOperation

GenericConfig

RetryConfig

TimeoutConfig


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using VR = UnityEngine.VR;

public class InputManager : MonoBehaviour {

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {
		if (OVRInput.GetDown(OVRInput.Button.One, OVRInput.Controller.RTouch) || Input.GetButtonDown("ResetWorld")) {
            VR.InputTracking.Recenter();
        }
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycotaxon 8(2): 335 (1979)

#### Original name
Humaria hydrophila (Peck) Sacc.

### Remarks
null


text:
To configure the client to use the staging environment for submitting solutions,
use the following command:

    exercism configure --key=abc --host=http://exercism-theory.herokuapp.com --api=http://x.exercism.io

You can also use a local copy of the x-api if you have specific problems you're testing there.
Or we can add exercism-xapi-theory as well.

## Deploying a branch to staging

If you have a branch that you want to test on staging, you can push that branch
to the remote master:

    git push -f heroku my-branch:master

## TODO

We may want to tweak the app so we can set RACK_ENV=staging and perhaps have a
specific header or different website colour (or at the very least a different
favicon colour), just so that we don't accidentally go to staging thinking it's
production.

We may want to add seed data in staging; It downloads some flat files, which I'm
not sure we can do. We'd have to try it.

## Creating the staging environment

This is a log of what I did in order to set up the staging environment.
It's a work in progress, and mostly just a "note to self" type thing.

Create the app:

```
heroku apps:create --app exercism-theory
git remote add theory git@heroku.com:exercism-theory.git
git push -f theory master
```

Add a couple of necessary addons:

```
heroku addons:add heroku-postgresql --app exercism-theory
heroku addons:add redistogo --app exercism-theory
```

Set some config vars:

```
heroku config:set --app exercism-theory EXERCISM_GITHUB_CLIENT_ID=abc123
heroku config:set --app exercism-theory EXERCISM_GITHUB_CLIENT_SECRET=abcdefg123456
heroku config:set --app exercism-theory RACK_ENV=production
```

Add a pre-push commit hook `.git/hooks/pre-push`:

```
#!/bin/bash

remote="$1"

if [[ $remote =~ theory ]]
then
        hash=$(git log -1 --format="%h")
        heroku config:set BUILD_ID=$hash
fi
exit 0
```

Migrate the database:

```
heroku run --app exercism-theory rake db:migrate
```


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Person Tests</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="person-widget/initializers/options/headline"
    content="HEADLINE!">

    <meta name="person-widget/initializers/options/question/summary"
    content="QUESTION_SUMMARY">

    <meta name="person-widget/initializers/options/question/body"
    content="QUESTION_BODY">

    <meta name="person-widget/initializers/options/partner/name"
    content="PARTNER_NAME">

    <meta name="person-widget/initializers/options/partner/url"
    content="PARTNER_URL">

    <meta name="person-widget/initializers/options/partner/logo"
    content="PARTNER_LOGO">

    <meta name="person-widget/initializers/options/person/id" content="S000033">

    {{content-for 'head'}}
    {{content-for 'test-head'}}

    <link rel="stylesheet" href="assets/vendor.css">
    <link rel="stylesheet" href="assets/person-widget.css">
    <link rel="stylesheet" href="assets/test-support.css">

    {{content-for 'head-footer'}}
    {{content-for 'test-head-footer'}}
  </head>
  <body>

    {{content-for 'body'}}
    {{content-for 'test-body'}}
    <script src="assets/vendor.js"></script>
    <script src="assets/test-support.js"></script>
    <script src="assets/person-widget.js"></script>
    <script src="testem.js"></script>
    <script src="assets/test-loader.js"></script>

    {{content-for 'body-footer'}}
    {{content-for 'test-body-footer'}}
  </body>
</html>


text:
'use strict';

require("./static/material.min.css");
require("./static/material.min.js");
require("./static/material_icons.css");

// Require index.html so it gets copied to dist
require('./index.html');

require('asciidoctor.js');

var Elm = require('./Main.elm');
var mountNode = document.getElementById('main');

var bookmarksItem = 'accu2017_bookmarks';

var bookmarks = localStorage.getItem(bookmarksItem);
if (bookmarks) {
    bookmarks = JSON.parse(bookmarks);
}
else {
    bookmarks = [];
}

var flags = {
    bookmarks: bookmarks,
    apiBaseUrl: process.env.API_BASE_URL
};

setTimeout(function() {
    var app = Elm.ACCUSchedule.embed(mountNode, flags);

    // handle "store" port to save bookmarks proposals
    app.ports.store.subscribe(function(bookmarks) {
        localStorage.setItem(bookmarksItem, JSON.stringify(bookmarks));
    });
});


text:
This package enables self-driving testing of Flutter code on devices and emulators.
It adapts flutter_test results into a format that is compatible with `flutter drive`
and native Android instrumentation testing.

## Usage

Add a dependency on the `integration_test` and `flutter_test` package in the
`dev_dependencies` section of `pubspec.yaml`. For plugins, do this in the
`pubspec.yaml` of the example app:

```yaml
integration_test:
  sdk: flutter
```

Create a `integration_test/` directory for your package. In this directory,
create a `<name>_test.dart`, using the following as a starting point to make
assertions.

```dart
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';

void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();

  testWidgets("failing test example", (WidgetTester tester) async {
    expect(2 + 2, equals(5));
  });
}
```

### Driver Entrypoint

An accompanying driver script will be needed that can be shared across all
integration tests. Create a file named `integration_test.dart` in the
`test_driver/` directory with the following contents:

```dart
import 'package:integration_test/integration_test_driver.dart';

Future<void> main() => integrationDriver();
```

You can also use different driver scripts to customize the behavior of the app
under test. For example, `FlutterDriver` can also be parameterized with
different [options](https://api.flutter.dev/flutter/flutter_driver/FlutterDriver/connect.html).
See the [extended driver](https://github.com/flutter/flutter/blob/master/packages/integration_test/example/test_driver/extended_integration_test.dart) for an example.

### Package Structure

Your package should have a structure that looks like this:

```
lib/
  ...
integration_test/
  foo_test.dart
  bar_test.dart
test/
  # Other unit tests go here.
test_driver/
  integration_test.dart
```

[Example](https://github.com/flutter/flutter/tree/master/packages/integration_test/example)

## Using Flutter Driver to Run Tests

These tests can be launched with the `flutter drive` command.

To run the `integration_test/foo_test.dart` test with the
`test_driver/integration_test.dart` driver, use the following command:

```sh
flutter drive \
  --driver=test_driver/integration_test.dart \
  --target=integration_test/foo_test.dart
```

### Web

Make sure you have [enabled web support](https://flutter.dev/docs/get-started/web#set-up)
then [download and run](https://flutter.dev/docs/cookbook/testing/integration/introduction#6b-web)
the web driver in another process.

Use following command to execute the tests:

```sh
flutter drive \
  --driver=test_driver/integration_test.dart \
  --target=integration_test/foo_test.dart \
  -d web-server
```

### Screenshots

You can use `integration_test` to take screenshots of the UI rendered on the mobile device or
Web browser at a specific time during the test.

This feature is currently supported on Android, iOS, and Web.

#### Android and iOS

**integration_test/screenshot_test.dart**

```dart
void main() {
  final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized()
      as IntegrationTestWidgetsFlutterBinding;

  testWidgets('screenshot', (WidgetTester tester) async {
    // Build the app.
    app.main();

    // This is required prior to taking the screenshot (Android only).
    await binding.convertFlutterSurfaceToImage();

    // Trigger a frame.
    await tester.pumpAndSettle();
    await binding.takeScreenshot('screenshot-1');
  });
}
```

You can use a driver script to pull in the screenshot from the device.
This way, you can store the images locally on your computer.  On iOS, the
screenshot will also be available in Xcode test results.

**test_driver/integration_test.dart**

```dart
import 'dart:io';
import 'package:integration_test/integration_test_driver_extended.dart';

Future<void> main() async {
  await integrationDriver(
    onScreenshot: (String screenshotName, List<int> screenshotBytes) async {
      final File image = File('$screenshotName.png');
      image.writeAsBytesSync(screenshotBytes);
      // Return false if the screenshot is invalid.
      return true;
    },
  );
}
```

#### Web

**integration_test/screenshot_test.dart**

```dart
void main() {
  final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized()
      as IntegrationTestWidgetsFlutterBinding;

  testWidgets('screenshot', (WidgetTester tester) async {
    // Build the app.
    app.main();

    // Trigger a frame.
    await tester.pumpAndSettle();
    await binding.takeScreenshot('screenshot-1');
  });
}
```

## Android Device Testing

Create an instrumentation test file in your application's
**android/app/src/androidTest/java/com/example/myapp/** directory (replacing
com, example, and myapp with values from your app's package name). You can name
this test file `MainActivityTest.java` or another name of your choice.

```java
package com.example.myapp;

import androidx.test.rule.ActivityTestRule;
import dev.flutter.plugins.integration_test.FlutterTestRunner;
import org.junit.Rule;
import org.junit.runner.RunWith;

@RunWith(FlutterTestRunner.class)
public class MainActivityTest {
  @Rule
  public ActivityTestRule<MainActivity> rule = new ActivityTestRule<>(MainActivity.class, true, false);
}
```

Update your application's **myapp/android/app/build.gradle** to make sure it
uses androidx's version of `AndroidJUnitRunner` and has androidx libraries as a
dependency.

```gradle
android {
  ...
  defaultConfig {
    ...
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
  }
}

dependencies {
    testImplementation 'junit:junit:4.12'

    // https://developer.android.com/jetpack/androidx/releases/test/#1.2.0
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
```

To run `integration_test/foo_test.dart` on a local Android device (emulated or
physical):

```sh
./gradlew app:connectedAndroidTest -Ptarget=`pwd`/../integration_test/foo_test.dart
```

## Firebase Test Lab

If this is your first time testing with Firebase Test Lab, you'll need to follow
the guides in the [Firebase test lab
documentation](https://firebase.google.com/docs/test-lab/?gclid=EAIaIQobChMIs5qVwqW25QIV8iCtBh3DrwyUEAAYASAAEgLFU_D_BwE)
to set up a project.

To run a test on Android devices using Firebase Test Lab, use gradle commands to build an
instrumentation test for Android, after creating `androidTest` as suggested in the last section.

```bash
pushd android
# flutter build generates files in android/ for building the app
flutter build apk
./gradlew app:assembleAndroidTest
./gradlew app:assembleDebug -Ptarget=<path_to_test>.dart
popd
```

Upload the build apks Firebase Test Lab, making sure to replace <PATH_TO_KEY_FILE>,
<PROJECT_NAME>, <RESULTS_BUCKET>, and <RESULTS_DIRECTORY> with your values.

```bash
gcloud auth activate-service-account --key-file=<PATH_TO_KEY_FILE>
gcloud --quiet config set project <PROJECT_NAME>
gcloud firebase test android run --type instrumentation \
  --app build/app/outputs/apk/debug/app-debug.apk \
  --test build/app/outputs/apk/androidTest/debug/app-debug-androidTest.apk\
  --timeout 2m \
  --results-bucket=<RESULTS_BUCKET> \
  --results-dir=<RESULTS_DIRECTORY>
```

You can pass additional parameters on the command line, such as the
devices you want to test on. See
[gcloud firebase test android run](https://cloud.google.com/sdk/gcloud/reference/firebase/test/android/run).

## iOS Device Testing

Open `ios/Runner.xcworkspace` in Xcode. Create a test target if you
do not already have one via `File > New > Target...` and select `Unit Testing Bundle`.
Change the `Product Name` to `RunnerTests`. Make sure `Target to be Tested` is set to `Runner` and language is set to `Objective-C`.
Select `Finish`.
Make sure that the **iOS Deployment Target** of `RunnerTests` within the **Build Settings** section is the same as `Runner`.

Add the new test target to `ios/Podfile` by embedding in the existing `Runner` target.

```ruby
target 'Runner' do
  # Do not change existing lines.
  ...

  target 'RunnerTests' do
    inherit! :search_paths
  end
end
```

To build `integration_test/foo_test.dart` from the command line, run:
```sh
flutter build ios --config-only integration_test/foo_test.dart
```

In Xcode, add a test file called `RunnerTests.m` (or any name of your choice) to the new target and
replace the file:

```objective-c
@import XCTest;
@import integration_test;

INTEGRATION_TEST_IOS_RUNNER(RunnerTests)
```

Run `Product > Test` to run the integration tests on your selected device.

To deploy it to Firebase Test Lab you can follow these steps:

Execute this script at the root of your Flutter app:

```sh
output="../build/ios_integ"
product="build/ios_integ/Build/Products"
dev_target="14.3"

# Pass --simulator if building for the simulator.
flutter build ios integration_test/foo_test.dart --release

pushd ios
xcodebuild -workspace Runner.xcworkspace -scheme Runner -config Flutter/Release.xcconfig -derivedDataPath $output -sdk iphoneos build-for-testing
popd

pushd $product
zip -r "ios_tests.zip" "Release-iphoneos" "Runner_iphoneos$dev_target-arm64.xctestrun"
popd
```

You can verify locally that your tests are successful by running the following command:

```sh
xcodebuild test-without-building -xctestrun "build/ios_integ/Build/Products/Runner_iphoneos14.3-arm64.xctestrun" -destination id=<YOUR_DEVICE_ID>
```

Once everything is ok, you can upload the resulting zip to Firebase Test Lab (change the model with your values):

```sh
gcloud firebase test ios run --test "build/ios_integ/Build/Products/ios_tests.zip" --device model=iphone11pro,version=14.1,locale=fr_FR,orientation=portrait
```


text:
package com.bizosys.hsearch.inpipe;

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

import com.bizosys.hsearch.filter.Storable;
import com.bizosys.hsearch.hbase.HWriter;
import com.bizosys.hsearch.hbase.NV;
import com.bizosys.hsearch.index.Doc;
import com.bizosys.hsearch.index.IndexLog;
import com.bizosys.hsearch.index.Term;
import com.bizosys.hsearch.index.TermColumns;
import com.bizosys.hsearch.index.TermFamilies;
import com.bizosys.hsearch.index.TermList;
import com.bizosys.hsearch.index.TermTables;
import com.bizosys.hsearch.schema.ILanguageMap;
import com.bizosys.hsearch.schema.SchemaManager;
import com.bizosys.hsearch.util.ObjectFactory;
import com.bizosys.hsearch.util.Record;
import com.bizosys.oneline.ApplicationFault;
import com.bizosys.oneline.SystemFault;
import com.bizosys.oneline.conf.Configuration;
import com.bizosys.oneline.pipes.PipeIn;

/**
 * Saves the term vector to the index table in a batch mode. In the batch mode, it expects
 * 1) Bunch comes under one bucket only
 * 2) Each bucket will be overriden with no merging
 * 3) At one time one client only operates on a bucket. So thread safety is not provided.
 * @author karan
 *
 */
public class SaveToIndexBatch implements PipeIn {

	int docMergeFactor = 1000;
	/** Arranged by document */
	Map<Long, TermTables> mergedTermTables = null;
	Map<Long, Map<String,byte[]>> mergedBytes =
		new HashMap<Long, Map<String,byte[]>>(2) ;
	int bufferSize = 0;
	boolean isIdMappingEnabled = true;

	public SaveToIndexBatch() {

	}

	public SaveToIndexBatch(int docMergeFactor, boolean isIdMappingEnabled) {
		this.docMergeFactor = docMergeFactor;
		this.isIdMappingEnabled = isIdMappingEnabled;
	}

	public void visit(Object docObj, boolean multiWriter) throws ApplicationFault, SystemFault {

		if ( null == docObj) throw new ApplicationFault("No document");
		Doc doc = (Doc) docObj;

		if ( null == doc.bucketId || null == doc.docSerialId )
			throw new ApplicationFault ("Ids missed from document :" + doc.toString());

		if ( null == doc.terms) return;
		if ( null == doc.terms.all) return;

		ILanguageMap map = SchemaManager.getInstance().getLanguageMap(doc.meta.locale);
		TermTables termTable = ( null == doc.bucketId ) ?
			new TermTables(multiWriter) : new TermTables( new Storable(doc.bucketId),multiWriter);

		short docId = doc.docSerialId;
		for (Term term : doc.terms.getTermList()) {
			term.setDocumentPosition(docId);
			termTable.add(term, map);
		}
		bufferSize = bufferSize + doc.terms.getTermList().size();
		doc.terms.closeTermList();

		/**
		 * We need to arrange all terms from documents to arrange in term buckets.
		 */
		if ( null == mergedTermTables)
			mergedTermTables = ObjectFactory.getInstance().getBucketTermTable();

		buildTermTables(doc.bucketId, mergedTermTables, termTable);

		/**
		 * ************** Check For Intermediate Flushing **************
		 */
		if ( bufferSize > 1000000) {
			if ( IndexLog.l.isInfoEnabled() )
				IndexLog.l.info("Flush Intermediate Size > " + bufferSize );
			flushIntermediate(this.mergedBytes, mergedTermTables);
		}
		/**
		 * ************** ----------------------- **************
		 */
	}

	/**
	 * Persist the Index
	 */
	public void commit(boolean multiWriter) throws ApplicationFault, SystemFault {
		if ( null == mergedTermTables) return;
		if ( IndexLog.l.isDebugEnabled()) printMergedTT(mergedTermTables);

		if ( mergedTermTables.size() > 0) {
			flushIntermediate(this.mergedBytes, mergedTermTables);
			this.mergedTermTables.clear();
		}

		if ( null != mergedTermTables) {
			ObjectFactory.getInstance().putBucketTermTable(mergedTermTables);
		}

		if ( this.mergedBytes.size() == 0 ) return;

		for (long bucketId : this.mergedBytes.keySet()) {
			if ( IndexLog.l.isInfoEnabled() )
				IndexLog.l.info("Commit > " + bucketId);
			Map<String,byte[]> values = this.mergedBytes.get(bucketId);
			Map<Character, List<NV>> tableNVs = new HashMap<Character, List<NV>>();
			for (String tfc : values.keySet()) {
				char tab = tfc.charAt(0);
				if (tableNVs.containsKey(tab) ) {
					List<NV> tabNvs = tableNVs.get(tab);
					tabNvs.add(new NV( new byte[]{(byte)tfc.charAt(1)},
						new byte[]{(byte)tfc.charAt(2)},
						new Storable(values.get(tfc))));
				} else {
					List<NV> nvs = ObjectFactory.getInstance().getNVList();
					nvs.add(new NV( new byte[]{(byte)tfc.charAt(1)},
							new byte[]{(byte)tfc.charAt(2)},
							new Storable(values.get(tfc))));
					tableNVs.put(tab, nvs);
				}
			}

			values.clear();
			try {
				for (Character tab : tableNVs.keySet()) {
					List<NV> tabNV = tableNVs.get(tab);
					Record rec = new Record(new Storable(bucketId),tabNV );
					HWriter.getInstance(multiWriter).insert(tab.toString(), rec);
					ObjectFactory.getInstance().putNVList(tabNV);
				}
			} catch (IOException ex) {
				throw new SystemFault(ex);
			} finally {
				for ( Map<String,byte[]> bucketM : mergedBytes.values()) {
					bucketM.clear();
				}
				mergedBytes.clear();
				tableNVs.clear();
			}
		}
	}

	/**
	 *
	 * @param mergedTermTables
	 * @param docTermTable
	 */
	private void buildTermTables( long bucketId,
		Map<Long, TermTables> mergedTermTables, TermTables docTermTable) {

		if ( mergedTermTables.containsKey(bucketId)) {
			TermTables mtt = mergedTermTables.get(bucketId);
			mtt.addInSameBucket(docTermTable);
		} else {
			mergedTermTables.put(bucketId, docTermTable);
		}
	}

	/**
	 * It transforms the term objects to a byte array.
	 * It saves pointed and allows more documents to get merged.
	 * @param allByteValues	All Bytes
	 * @param mtt	The merged term tables
	 */
	private void flushIntermediate( Map<Long, Map<String,byte[]>>
		allByteValues, Map<Long, TermTables> mtt) {

		if ( null == mtt) return;
		if ( 0 == mtt.size()) return;

		long s = System.currentTimeMillis();
		StringBuilder sb = new StringBuilder(10);
		for (long bucketId : mtt.keySet()) {

			TermTables termTables = mtt.get(bucketId);
			for ( char tableName : termTables.tables.keySet()) {
				TermFamilies tf = termTables.tables.get(tableName);
				for (char family : tf.families.keySet()) {
					TermColumns tcs = tf.families.get(family);
					for (char col : tcs.columns.keySet()) {
						sb.append(tableName).append(family).append(col);
						String tfc = sb.toString();
						sb.delete(0, 10);
						TermList tl = tcs.columns.get(col);
						Map<String,byte[]> bytesV = null;
						if ( allByteValues.containsKey(bucketId)) {
							bytesV = allByteValues.get(bucketId);
							if (bytesV.containsKey(tfc)) {
								byte[] tlB = bytesV.get(tfc);
								tl.setExistingBytes(tlB);
								byte[] newB = tl.toBytes();
								bytesV.put(tfc, newB);
								tlB = null;
							} else {
								bytesV.put(tfc, tl.toBytes());
							}
						} else {
							bytesV = new HashMap<String, byte[]>(1);
							bytesV.put(tfc, tl.toBytes());
							allByteValues.put(bucketId, bytesV);
						}

						tl.cleanup();
					}
				}
			}
			termTables.cleanup();
		}
		bufferSize = 0;
		if ( InpipeLog.l.isDebugEnabled()) InpipeLog.l.debug(
				"SaveToIndexBatch > flushIntermediate Executation Time " +
				(System.currentTimeMillis() - s) + " ms");
	}

	public void init(Configuration conf) throws ApplicationFault, SystemFault {
		this.docMergeFactor =
			conf.getInt("index.documents.merge", 10000);

		this.isIdMappingEnabled = conf.getBoolean("idmapping.enable", true);
	}

	public PipeIn getInstance() {
		return new SaveToIndexBatch(this.docMergeFactor, this.isIdMappingEnabled);
	}

	public String getName() {
		return "SaveToIndexBatch";
	}

	/**
	 * Creates a string representation of the table.
	 * @param mergedTermTables
	 * @return
	 */
	private String  printMergedTT(Map<Long, TermTables> mergedTermTables) {
		StringBuilder sb = new StringBuilder();
		for (long bucket : mergedTermTables.keySet()) {
			sb.append("Bucket:").append(bucket);
			TermTables tt =  mergedTermTables.get(bucket);
			for (char table: tt.tables.keySet()) {
				sb.append("\n\tTable:").append(table);
				TermFamilies tf = tt.tables.get(table);
				for (char family : tf.families.keySet()) {
					sb.append("\n\t\tfamily:").append(family);
					TermColumns tc = tf.families.get(family);
					for (char col : tc.columns.keySet()) {
						sb.append("\n\t\t\tColumn:").append(col);
						sb.append(tc.columns.get(col).toString());
					}
				}
			}
		}
		return sb.toString();
	}

}


text:
var Db = require('tingodb')().Db;
var homeDir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
var settingsDir = homeDir + '/.silk-gui';
var db = new Db(settingsDir + '/core/database', {});
module.exports = db;

module.exports.collections = {
  externalApps: db.collection('external_apps'),
  appId: db.collection('app_id'),
  finishedSetup: db.collection('appFinishedSetup')
};


text:
<?php

namespace BingAds\Reporting;

/**
 * Defines a product dimension performance report request that aggregates the performance data by product category, custom label, title, and type for a specified time period.
 *
 * @link http://msdn.microsoft.com/en-us/library/dn913141(v=msads.90).aspx ProductDimensionPerformanceReportRequest Data Object
 *
 * @uses ReportAggregation
 * @uses ProductDimensionPerformanceReportColumn
 * @uses ProductDimensionPerformanceReportFilter
 * @uses AccountThroughAdGroupReportScope
 * @uses ReportTime
 */
final class ProductDimensionPerformanceReportRequest extends ReportRequest
{
    /**
     * The type of aggregation to use to aggregate the report data.
     *
     * @var ReportAggregation
     */
    public $Aggregation;
    /**
     * The list of attributes and performance statistics to include in the report.
     *
     * @var ProductDimensionPerformanceReportColumn[]
     */
    public $Columns;
    /**
     * The filter information to use to filter the report data.
     *
     * @var ProductDimensionPerformanceReportFilter
     */
    public $Filter;
    /**
     * The scope of the report.
     *
     * @var AccountThroughAdGroupReportScope
     */
    public $Scope;
    /**
     * The time period to use for the report.
     *
     * @var ReportTime
     */
    public $Time;
}


text:
import { env, SourceControlResourceState, Uri, window } from 'vscode';
import { ScmResource } from '../@types/vscode.git.resources';
import { ScmResourceGroupType, ScmStatus } from '../@types/vscode.git.resources.enums';
import { Commands } from '../constants';
import type { Container } from '../container';
import { GitUri } from '../git/gitUri';
import { GitRevision } from '../git/models';
import { Logger } from '../logger';
import { Messages } from '../messages';
import { RepositoryPicker } from '../quickpicks/repositoryPicker';
import { filterMap } from '../system/array';
import { command } from '../system/command';
import {
	Command,
	CommandContext,
	isCommandContextViewNodeHasFileCommit,
	isCommandContextViewNodeHasFileRefs,
} from './base';

interface ExternalDiffFile {
	uri: Uri;
	staged: boolean;
	ref1?: string;
	ref2?: string;
}

export interface ExternalDiffCommandArgs {
	files?: ExternalDiffFile[];
}

@command()
export class ExternalDiffCommand extends Command {
	constructor(private readonly container: Container) {
		super([Commands.ExternalDiff, Commands.ExternalDiffAll]);
	}

	protected override async preExecute(context: CommandContext, args?: ExternalDiffCommandArgs) {
		args = { ...args };

		if (isCommandContextViewNodeHasFileCommit(context)) {
			const previousSha = await context.node.commit.getPreviousSha();
			const ref1 = GitRevision.isUncommitted(previousSha) ? '' : previousSha;
			const ref2 = context.node.commit.isUncommitted ? '' : context.node.commit.sha;

			args.files = [
				{
					uri: GitUri.fromFile(context.node.file, context.node.file.repoPath ?? context.node.repoPath),
					staged: context.node.commit.isUncommittedStaged || context.node.file.indexStatus != null,
					ref1: ref1,
					ref2: ref2,
				},
			];

			return this.execute(args);
		}

		if (isCommandContextViewNodeHasFileRefs(context)) {
			args.files = [
				{
					uri: GitUri.fromFile(context.node.file, context.node.file.repoPath ?? context.node.repoPath),
					staged: context.node.file.indexStatus != null,
					ref1: context.node.ref1,
					ref2: context.node.ref2,
				},
			];

			return this.execute(args);
		}

		if (args.files == null) {
			if (context.type === 'scm-states') {
				args.files = context.scmResourceStates.map(r => ({
					uri: r.resourceUri,
					staged: (r as ScmResource).resourceGroupType === ScmResourceGroupType.Index,
				}));
			} else if (context.type === 'scm-groups') {
				args.files = filterMap(context.scmResourceGroups[0].resourceStates, r =>
					this.isModified(r)
						? {
								uri: r.resourceUri,
								staged: (r as ScmResource).resourceGroupType === ScmResourceGroupType.Index,
						  }
						: undefined,
				);
			}
		}

		if (context.command === Commands.ExternalDiffAll) {
			if (args.files == null) {
				const repository = await RepositoryPicker.getRepositoryOrShow('Open All Changes (difftool)');
				if (repository == null) return undefined;

				const status = await this.container.git.getStatusForRepo(repository.uri);
				if (status == null) {
					return window.showInformationMessage("The repository doesn't have any changes");
				}

				args.files = [];

				for (const file of status.files) {
					if (file.indexStatus === 'M') {
						args.files.push({ uri: file.uri, staged: true });
					}

					if (file.workingTreeStatus === 'M') {
						args.files.push({ uri: file.uri, staged: false });
					}
				}
			}
		}

		return this.execute(args);
	}

	private isModified(resource: SourceControlResourceState) {
		const status = (resource as ScmResource).type;
		return (
			status === ScmStatus.BOTH_MODIFIED || status === ScmStatus.INDEX_MODIFIED || status === ScmStatus.MODIFIED
		);
	}

	async execute(args?: ExternalDiffCommandArgs) {
		args = { ...args };

		try {
			let repoPath;
			if (args.files == null) {
				const editor = window.activeTextEditor;
				if (editor == null) return;

				repoPath = this.container.git.getBestRepository(editor)?.path;
				if (!repoPath) return;

				const uri = editor.document.uri;
				const status = await this.container.git.getStatusForFile(repoPath, uri);
				if (status == null) {
					void window.showInformationMessage("The current file doesn't have any changes");

					return;
				}

				args.files = [];
				if (status.indexStatus === 'M') {
					args.files.push({ uri: status.uri, staged: true });
				}

				if (status.workingTreeStatus === 'M') {
					args.files.push({ uri: status.uri, staged: false });
				}
			} else {
				repoPath = (await this.container.git.getOrOpenRepository(args.files[0].uri))?.path;
				if (!repoPath) return;
			}

			const tool =
				this.container.config.advanced.externalDiffTool || (await this.container.git.getDiffTool(repoPath));
			if (!tool) {
				const viewDocs = 'View Git Docs';
				const result = await window.showWarningMessage(
					'Unable to open changes because no Git diff tool is configured',
					viewDocs,
				);
				if (result === viewDocs) {
					void env.openExternal(
						Uri.parse('https://git-scm.com/docs/git-config#Documentation/git-config.txt-difftool'),
					);
				}

				return;
			}

			for (const file of args.files) {
				void this.container.git.openDiffTool(repoPath, file.uri, {
					ref1: file.ref1,
					ref2: file.ref2,
					staged: file.staged,
					tool: tool,
				});
			}
		} catch (ex) {
			Logger.error(ex, 'ExternalDiffCommand');
			void Messages.showGenericErrorMessage('Unable to open changes in diff tool');
		}
	}
}


text:
const initState = core.createUser();

/**
* Reducer that sets OSF access infomation
* @param {Object} action.osfAccess - OSF Access information
* @return A new userState
*/
function setOsfAccess(state, action) {
	return Object.assign({}, state, {
		osfAccess: action.osfAccess
	});
}

/**
* Reducer that loads fetched user data from dynamoDB
* @param {Object} action.userState - fetched user data from dynamoDB
* @return A new userState
*/
function loadUserState(state, action) {
	return Object.assign({}, state, {
		...action.userState
	});
}

export default function userReducer(state = initState, action) {
	switch (action.type) {
		case actions.ActionTypes.LOAD_USER:
			return loadUserState(state, action);

		// cloud access information
		case actions.ActionTypes.SET_OSF_ACCESS:
			return setOsfAccess(state, action);

		default:
			return state;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="perfStats">%s-statistieken</string>
  <string name="viewTheGames">Bekijk de partijen</string>
  <string name="provisional">voorlopig</string>
  <string name="notEnoughRatedGames">Er zijn niet genoeg partijen met rating gespeeld om een betrouwbare rating vast te stellen.</string>
  <string name="progressOverLastXGames">Voortgang in de laatste %s partijen:</string>
  <string name="ratingDeviation">Rating deviatie: %s.</string>
  <string name="ratingDeviationTooltip" comment="ratingDeviationTooltip

This is a tooltip (appears on mouseover) for the rating deviation. Appears on performance statistics pages such as https://lichess.org/@/thibault/perf/ultraBullet

As of 2021-05-19, $1%s is set to 110.">Een lagere waarde betekent dat de rating stabieler is. Boven %1$s wordt de rating als voorlopig beschouwd. Om in de ranglijsten te worden opgenomen, moet deze waarde lager zijn dan %2$s (standaard schaken) of %3$s (varianten).</string>
  <string name="totalGames">Totaal aantal partijen</string>
  <string name="ratedGames">Partijen met rating</string>
  <string name="tournamentGames">Toernooipartijen</string>
  <string name="berserkedGames">Berserk partijen</string>
  <string name="timeSpentPlaying">Tijd schakend besteed</string>
  <string name="averageOpponent">Gemiddelde tegenstander</string>
  <string name="victories">Overwinningen</string>
  <string name="defeats">Nederlagen</string>
  <string name="disconnections">Verbroken verbindingen</string>
  <string name="notEnoughGames">Niet genoeg partijen gespeeld</string>
  <string name="highestRating">Hoogste rating: %s</string>
  <string name="lowestRating">Laagste rating: %s</string>
  <string name="fromXToY">van %1$s tot %2$s</string>
  <string name="winningStreak">Overwinningsreeks</string>
  <string name="losingStreak">Verliesreeks</string>
  <string name="longestStreak">Langste reeks: %s</string>
  <string name="currentStreak">Huidige reeks: %s</string>
  <string name="bestRated">Grootste overwinningen</string>
  <string name="worstRated">Grootste nederlagen</string>
  <string name="gamesInARow">Aaneengesloten partijen</string>
  <string name="lessThanOneHour">Minder dan een uur tussen de partijen</string>
  <string name="maxTimePlaying">Langste schaakpartij</string>
  <string name="now">nu</string>
</resources>


text:
package net.floodlightcontroller.core.util;

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

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import org.apache.thrift.TBase;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.transport.TIOStreamTransport;

/**
 * Slice and decode Thrift Serialized Messages from the channel, push a {@link List} of Messages upstream.
 *
 * Each message is preceeded by a four-byte length field.
 *
 * Subclasses should implement {@link #allocateMessage()} to allocate an instance of the
 * desired message type.
 *
 * Implementation note: this decoder class was initially built for netty3, and is unnecessarily
 * complex and inelegant. In particular, netty has efficient support for handling lists of messages
 * now, so this could be replaced by a plain {@link LengthFieldBasedFrameDecoder} to do the slicing
 * and then a simple ThriftDecoder that would just decode one message at a time.
 *
 * @author readams
 * @author Andreas Wundsam <andreas.wundsam@bigswitch.com>
 */
public abstract class ThriftFrameDecoder<T extends TBase<?,?>> extends LengthFieldBasedFrameDecoder {
    public ThriftFrameDecoder(int maxSize) {
        super(maxSize, 0, 4, 0, 4);
    }

    protected abstract T allocateMessage();

    @Override
    protected final Object decode(ChannelHandlerContext ctx,
                            ByteBuf buffer) throws Exception {
        /* This is initialized to null because the decode function must return
         * null if the buffer does not contain a complete frame and cannot be
         * decoded.
         */
        List<T> ms = null;
        ByteBuf frame = null;
        while (null != (frame = (ByteBuf) super.decode(ctx, buffer))) {
            if (ms == null) ms = new ArrayList<T>();
            ByteBufInputStream is = new ByteBufInputStream(frame);
            TCompactProtocol thriftProtocol =
                    new TCompactProtocol(new TIOStreamTransport(is));
            T message = allocateMessage();
            message.read(thriftProtocol);
            ms.add(message);
        }
        return ms;
    }

    @Override
    protected final ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index,
            int length) {
        return buffer.slice(index, length);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<item>
    <shape>
        <!-- set the shadow color here -->
        <stroke
            android:width="2dp"
            android:color="#F8F8F8" />

        <!-- setting the thickness of shadow (positive value will give shadow on that side) -->

        <padding
            android:bottom="2dp"
            android:left="2dp"
            android:right="2dp"
            android:top="2dp" />

        <corners android:radius="3dp" />
    </shape>
</item>

<!-- Background -->

<item>
    <shape>
        <solid android:color="#fff" />
        <corners android:radius="3dp" />
    </shape>
</item>
</layer-list>


text:
package org.ardverk.concurrent;

/**
 *
 */
public interface Scheduler {

  /**
   *
   */
  public boolean doNext(DefaultExecutorQueue group, int index, long timeStamp);
}


text:
package org.apache.jackrabbit.mk;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.jackrabbit.mk.core.MicroKernelImpl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

public class MicroKernelImplTest {

    private File homeDir;
    private MicroKernelImpl mk;

    @Before
    public void setup() throws Exception {
        homeDir = new File("target/mk");
        if (homeDir.exists()) {
            FileUtils.cleanDirectory(homeDir);
        }
        mk = new MicroKernelImpl(homeDir.getPath());
    }

    @After
    public void tearDown() throws Exception {
        if (mk != null) {
            mk.dispose();
        }
    }

    /**
     * OAK-276: potential clash of commit id's after restart.
     */
    @Test
    public void potentialClashOfCommitIds() {
        String headRev = mk.commit("/", "+\"a\" : {}", mk.getHeadRevision(), null);
        String branchRev = mk.branch(mk.getHeadRevision());

        mk.dispose();
        mk = new MicroKernelImpl(homeDir.getPath());
        assertEquals("Stored head should be equal", headRev, mk.getHeadRevision());

        headRev = mk.commit("/", "+\"b\" : {}", mk.getHeadRevision(), null);
        assertFalse("Commit must not have same id as branch", headRev.equals(branchRev));
    }

    @Test
    public void diffWithDepth() {
        String head = mk.getHeadRevision();
        String r1 = mk.commit("/", "+\"a\" : { \"l\": 1, \"x\": { \"l\": 2, \"y\": {} } }", head, null);
        String r2 = mk.commit("/", ">\"a\" : \"b\"", r1, null);
        assertEquals("+\"/b\":{\"l\":1}", mk.diff(r1, r2, "/b", 0).trim());
        assertEquals("+\"/b\":{\"l\":1,\"x\":{\"l\":2}}", mk.diff(r1, r2, "/b", 1).trim());
        assertEquals("+\"/b\":{\"l\":1,\"x\":{\"l\":2,\"y\":{}}}", mk.diff(r1, r2, "/b", -1).trim());
    }

}


text:
using System.Linq;

namespace VanEmdeBoasTree.Tests
{
    class RsVanEmdeBoasTreeTests : BoundedSetTests
    {
        protected override void AssertIsValidEmptySet(IBoundedSet<object> set, int expectedUniverse)
        {
            var tree = (RsVanEmdeBoasTree<object>) set;
            Assert(tree.Universe == expectedUniverse);
            Assert(!tree.Min.HasValue);
            Assert(!tree.Max.HasValue);
            Assert(tree.Summary == null);
            Assert(!tree.Clusters.Any());
        }

        protected override IBoundedSet<object> CreateSet(int universe)
        {
            return new RsVanEmdeBoasTree<object>(universe);
        }
    }
}


text:
/** @jsx React.DOM */

var meStore = require('../stores/me');

var youtubeSDK = require('require-sdk')('https://www.youtube.com/iframe_api', 'YT');
window.onYouTubeIframeAPIReady = youtubeSDK.trigger();
var youtube, player;

youtubeSDK(function(err, y) {
  if (err) {
    return;
  }
  youtube = y;
});

var React = require('react');

var triggerKeys = "wareagle";
module.exports = React.createClass({
  getInitialState: function() {
    return {keys: ""}
  },
  _ensurePlayer: function() {
    if(!player && youtube) {
      player = new youtube.Player('player', {
        width: '100%',
        height: '100%',
        videoId: '8GKmkD1pUG0',
        playerVars: {
          start: 10,
          end: 38,
          controls: 0,
          showinfo: 0,
        },
        events: {
          'onReady': this._onPlayerReady,
          'onStateChange': this._onPlayerStateChange
        }
      });
    }
  },
  _onPlayerReady: function(e) {
    e.target.setPlaybackQuality('large');
    e.target.playVideo();
  },
  _onPlayerStateChange: function(e) {
    if (e.data == youtube.PlayerState.ENDED) {
      this.setState({keys: ""});
    }
  },
  _onMeFinish: function() {
    this.setState({keys: triggerKeys});
  },
  _handleKeyPress: function(e) {
    var newKeys = this.state.keys + String.fromCharCode(e.which).toLowerCase();
    if (triggerKeys.indexOf(newKeys) === 0) {
      this.setState({keys: newKeys});
    } else {
      this.setState({keys: ""});
    }
  },
  _handleVideoEnd: function() {
    this.setState({keys: ""});
  },
  componentDidMount: function() {
    document.onkeypress = this._handleKeyPress;
    meStore.addFinishListener(this._onMeFinish);
  },
  componentWillUnmount: function() {
    document.onkeypress = null;
    if (player && player.destroy) {
      player.destroy();
    }
    meStore.removeFinishListener(this._onMeFinish);
  },
  render: function() {
    if (this.state.keys !== triggerKeys) {
      if (player && player.destroy) {
        player.destroy();
        player = null;
      }
      return

;
    }
    process.nextTick(this._ensurePlayer);
    return (

    );
  }
});