text:
#include <graphene/chain/account_object.hpp>
#include <graphene/chain/asset_object.hpp>
#include <graphene/chain/market_object.hpp>

#include <graphene/chain/market_evaluator.hpp>

#include <graphene/chain/database.hpp>
#include <graphene/chain/exceptions.hpp>
#include <graphene/chain/hardfork.hpp>
#include <graphene/chain/is_authorized_asset.hpp>

#include <graphene/protocol/market.hpp>

namespace graphene { namespace chain {
void_result limit_order_create_evaluator::do_evaluate(const limit_order_create_operation& op)
{ try {
   const database& d = db();

   FC_ASSERT( op.expiration >= d.head_block_time() );

   _seller        = this->fee_paying_account;
   _sell_asset    = &op.amount_to_sell.asset_id(d);
   _receive_asset = &op.min_to_receive.asset_id(d);

   if( _sell_asset->options.whitelist_markets.size() )
   {
      GRAPHENE_ASSERT( _sell_asset->options.whitelist_markets.find(_receive_asset->id)
                          != _sell_asset->options.whitelist_markets.end(),
                       limit_order_create_market_not_whitelisted,
                       "This market has not been whitelisted by the selling asset", );
   }
   if( _sell_asset->options.blacklist_markets.size() )
   {
      GRAPHENE_ASSERT( _sell_asset->options.blacklist_markets.find(_receive_asset->id)
                          == _sell_asset->options.blacklist_markets.end(),
                       limit_order_create_market_blacklisted,
                       "This market has been blacklisted by the selling asset", );
   }

   GRAPHENE_ASSERT( is_authorized_asset( d, *_seller, *_sell_asset ),
                    limit_order_create_selling_asset_unauthorized,
                    "The account is not allowed to transact the selling asset", );

   GRAPHENE_ASSERT( is_authorized_asset( d, *_seller, *_receive_asset ),
                    limit_order_create_receiving_asset_unauthorized,
                    "The account is not allowed to transact the receiving asset", );

   GRAPHENE_ASSERT( d.get_balance( *_seller, *_sell_asset ) >= op.amount_to_sell,
                    limit_order_create_insufficient_balance,
                    "insufficient balance",
                    ("balance",d.get_balance(*_seller,*_sell_asset))("amount_to_sell",op.amount_to_sell) );

   return void_result();
} FC_CAPTURE_AND_RETHROW( (op) ) }

void limit_order_create_evaluator::convert_fee()
{
   if( db().head_block_time() <= HARDFORK_CORE_604_TIME )
      generic_evaluator::convert_fee();
   else
      if( !trx_state->skip_fee )
      {
         if( fee_asset->get_id() != asset_id_type() )
         {
            db().modify(*fee_asset_dyn_data, [this](asset_dynamic_data_object& d) {
               d.fee_pool -= core_fee_paid;
            });
         }
      }
}

void limit_order_create_evaluator::pay_fee()
{
   if( db().head_block_time() <= HARDFORK_445_TIME )
      generic_evaluator::pay_fee();
   else
   {
      _deferred_fee = core_fee_paid;
      if( db().head_block_time() > HARDFORK_CORE_604_TIME && fee_asset->get_id() != asset_id_type() )
         _deferred_paid_fee = fee_from_account;
   }
}

object_id_type limit_order_create_evaluator::do_apply(const limit_order_create_operation& op)
{ try {
   if( op.amount_to_sell.asset_id == asset_id_type() )
   {
      db().modify( _seller->statistics(db()), [&op](account_statistics_object& bal) {
         bal.total_core_in_orders += op.amount_to_sell.amount;
      });
   }

   db().adjust_balance(op.seller, -op.amount_to_sell);

   const auto& new_order_object = db().create<limit_order_object>([&](limit_order_object& obj){
       obj.seller   = _seller->id;
       obj.for_sale = op.amount_to_sell.amount;
       obj.sell_price = op.get_price();
       obj.expiration = op.expiration;
       obj.deferred_fee = _deferred_fee;
       obj.deferred_paid_fee = _deferred_paid_fee;
   });
   limit_order_id_type order_id = new_order_object.id; // save this because we may remove the object by filling it
   bool filled;
   if( db().get_dynamic_global_properties().next_maintenance_time <= HARDFORK_CORE_625_TIME )
      filled = db().apply_order_before_hardfork_625( new_order_object );
   else
      filled = db().apply_order( new_order_object );

   GRAPHENE_ASSERT( !op.fill_or_kill || filled,
                    limit_order_create_kill_unfilled,
                    "Killing limit order ${op} due to unable to fill",
                    ("op",op) );

   return order_id;
} FC_CAPTURE_AND_RETHROW( (op) ) }

void_result limit_order_cancel_evaluator::do_evaluate(const limit_order_cancel_operation& o)
{ try {
   database& d = db();

   _order = d.find( o.order );

   GRAPHENE_ASSERT( _order != nullptr,
                    limit_order_cancel_nonexist_order,
                    "Limit order ${oid} does not exist",
                    ("oid", o.order) );

   GRAPHENE_ASSERT( _order->seller == o.fee_paying_account,
                    limit_order_cancel_owner_mismatch,
                    "Limit order ${oid} is owned by someone else",
                    ("oid", o.order) );

   return void_result();
} FC_CAPTURE_AND_RETHROW( (o) ) }

asset limit_order_cancel_evaluator::do_apply(const limit_order_cancel_operation& o)
{ try {
   database& d = db();

   auto base_asset = _order->sell_price.base.asset_id;
   auto quote_asset = _order->sell_price.quote.asset_id;
   auto refunded = _order->amount_for_sale();

   d.cancel_limit_order(*_order, false /* don't create a virtual op*/);

   if( d.get_dynamic_global_properties().next_maintenance_time <= HARDFORK_CORE_606_TIME )
   {
      // Possible optimization: order can be called by canceling a limit order iff the canceled order was at the top of the book.
      // Do I need to check calls in both assets?
      d.check_call_orders(base_asset(d));
      d.check_call_orders(quote_asset(d));
   }

   return refunded;
} FC_CAPTURE_AND_RETHROW( (o) ) }

void_result call_order_update_evaluator::do_evaluate(const call_order_update_operation& o)
{ try {
   database& d = db();

   auto next_maintenance_time = d.get_dynamic_global_properties().next_maintenance_time;

   _paying_account = &o.funding_account(d);
   _debt_asset     = &o.delta_debt.asset_id(d);
   FC_ASSERT( _debt_asset->is_market_issued(), "Unable to cover ${sym} as it is not a collateralized asset.",
              ("sym", _debt_asset->symbol) );

   FC_ASSERT( o.delta_debt.amount <= 0 || _debt_asset->can_create_new_supply(), "Can not create new supply" );

   _dynamic_data_obj = &_debt_asset->dynamic_asset_data_id(d);

   /***
    * There are instances of assets exceeding max_supply before hf 1465, therefore this code must remain.
    */
   if (next_maintenance_time > HARDFORK_CORE_1465_TIME)
   {
      FC_ASSERT( _dynamic_data_obj->current_supply + o.delta_debt.amount <= _debt_asset->options.max_supply,
            "Borrowing this quantity would exceed MAX_SUPPLY" );
   }

   FC_ASSERT( _dynamic_data_obj->current_supply + o.delta_debt.amount >= 0,
         "This transaction would bring current supply below zero.");

   _bitasset_data  = &_debt_asset->bitasset_data(d);

   /// if there is a settlement for this asset, then no further margin positions may be taken and
   /// all existing margin positions should have been closed va database::globally_settle_asset
   FC_ASSERT( !_bitasset_data->has_settlement(), "Cannot update debt position when the asset has been globally settled" );

   FC_ASSERT( o.delta_collateral.asset_id == _bitasset_data->options.short_backing_asset,
              "Collateral asset type should be same as backing asset of debt asset" );

   if( _bitasset_data->is_prediction_market )
      FC_ASSERT( o.delta_collateral.amount == o.delta_debt.amount,
                 "Debt amount and collateral amount should be same when updating debt position in a prediction market" );
   else if( _bitasset_data->current_feed.settlement_price.is_null() )
      FC_THROW_EXCEPTION(insufficient_feeds, "Cannot borrow asset with no price feed.");

   // Note: there was code here checking whether the account has enough balance to increase delta collateral,
   //       which is now removed since the check is implicitly done later by `adjust_balance()` in `do_apply()`.

   return void_result();
} FC_CAPTURE_AND_RETHROW( (o) ) }

object_id_type call_order_update_evaluator::do_apply(const call_order_update_operation& o)
{ try {
   database& d = db();

   if( o.delta_debt.amount != 0 )
   {
      d.adjust_balance( o.funding_account, o.delta_debt );

      // Deduct the debt paid from the total supply of the debt asset.
      d.modify(*_dynamic_data_obj, [&](asset_dynamic_data_object& dynamic_asset) {
         dynamic_asset.current_supply += o.delta_debt.amount;
      });
   }

   if( o.delta_collateral.amount != 0 )
   {
      d.adjust_balance( o.funding_account, -o.delta_collateral  );

      // Adjust the total core in orders accodingly
      if( o.delta_collateral.asset_id == asset_id_type() )
      {
         d.modify(_paying_account->statistics(d), [&](account_statistics_object& stats) {
               stats.total_core_in_orders += o.delta_collateral.amount;
         });
      }
   }

   const auto next_maint_time = d.get_dynamic_global_properties().next_maintenance_time;
   bool before_core_hardfork_1270 = ( next_maint_time <= HARDFORK_CORE_1270_TIME ); // call price caching issue

   auto& call_idx = d.get_index_type<call_order_index>().indices().get<by_account>();
   auto itr = call_idx.find( boost::make_tuple(o.funding_account, o.delta_debt.asset_id) );
   const call_order_object* call_obj = nullptr;
   call_order_id_type call_order_id;

   optional<price> old_collateralization;
   optional<share_type> old_debt;

   if( itr == call_idx.end() ) // creating new debt position
   {
      FC_ASSERT( o.delta_collateral.amount > 0, "Delta collateral amount of new debt position should be positive" );
      FC_ASSERT( o.delta_debt.amount > 0, "Delta debt amount of new debt position should be positive" );

      call_obj = &d.create<call_order_object>( [&o,this,before_core_hardfork_1270]( call_order_object& call ){
         call.borrower = o.funding_account;
         call.collateral = o.delta_collateral.amount;
         call.debt = o.delta_debt.amount;
         if( before_core_hardfork_1270 ) // before core-1270 hard fork, calculate call_price here and cache it
            call.call_price = price::call_price( o.delta_debt, o.delta_collateral,
                                                 _bitasset_data->current_feed.maintenance_collateral_ratio );
         else // after core-1270 hard fork, set call_price to 1
            call.call_price = price( asset( 1, o.delta_collateral.asset_id ), asset( 1, o.delta_debt.asset_id ) );
         call.target_collateral_ratio = o.extensions.value.target_collateral_ratio;
      });
      call_order_id = call_obj->id;
   }
   else // updating existing debt position
   {
      call_obj = &*itr;
      auto new_collateral = call_obj->collateral + o.delta_collateral.amount;
      auto new_debt = call_obj->debt + o.delta_debt.amount;
      call_order_id = call_obj->id;

      if( new_debt == 0 )
      {
         FC_ASSERT( new_collateral == 0, "Should claim all collateral when closing debt position" );
         d.remove( *call_obj );
         return call_order_id;
      }

      FC_ASSERT( new_collateral > 0 && new_debt > 0,
                 "Both collateral and debt should be positive after updated a debt position if not to close it" );

      old_collateralization = call_obj->collateralization();
      old_debt = call_obj->debt;

      d.modify( *call_obj, [&o,new_debt,new_collateral,this,before_core_hardfork_1270]( call_order_object& call ){
         call.collateral = new_collateral;
         call.debt       = new_debt;
         if( before_core_hardfork_1270 ) // don't update call_price after core-1270 hard fork
         {
            call.call_price  =  price::call_price( call.get_debt(), call.get_collateral(),
                                                   _bitasset_data->current_feed.maintenance_collateral_ratio );
         }
         call.target_collateral_ratio = o.extensions.value.target_collateral_ratio;
      });
   }

   // then we must check for margin calls and other issues
   if( !_bitasset_data->is_prediction_market )
   {
      // check to see if the order needs to be margin called now, but don't allow black swans and require there to be
      // limit orders available that could be used to fill the order.
      // Note: due to https://github.com/bitshares/bitshares-core/issues/649, before core-343 hard fork,
      //       the first call order may be unable to be updated if the second one is undercollateralized.
      if( d.check_call_orders( *_debt_asset, false, false, _bitasset_data ) ) // don't allow black swan, not for new limit order
      {
         call_obj = d.find(call_order_id);
         // before hard fork core-583: if we filled at least one call order, we are OK if we totally filled.
         // after hard fork core-583: we want to allow increasing collateral
         //   Note: increasing collateral won't get the call order itself matched (instantly margin called)
         //   if there is at least a call order get matched but didn't cause a black swan event,
         //   current order must have got matched. in this case, it's OK if it's totally filled.
         GRAPHENE_ASSERT(
            !call_obj,
            call_order_update_unfilled_margin_call,
            "Updating call order would trigger a margin call that cannot be fully filled"
            );
      }
      else
      {
         call_obj = d.find(call_order_id);
         // we know no black swan event has occurred
         FC_ASSERT( call_obj, "no margin call was executed and yet the call object was deleted" );
         // this HF must remain as-is, as the assert inside the "if" was triggered during push_proposal()
         if( d.head_block_time() <= HARDFORK_CORE_583_TIME )
         {
            // We didn't fill any call orders.  This may be because we
            // aren't in margin call territory, or it may be because there
            // were no matching orders.  In the latter case, we throw.
            GRAPHENE_ASSERT(
               // we know core-583 hard fork is before core-1270 hard fork, it's ok to use call_price here
               ~call_obj->call_price < _bitasset_data->current_feed.settlement_price,
               call_order_update_unfilled_margin_call,
               "Updating call order would trigger a margin call that cannot be fully filled",
               // we know core-583 hard fork is before core-1270 hard fork, it's ok to use call_price here
               ("a", ~call_obj->call_price )("b", _bitasset_data->current_feed.settlement_price)
               );
         }
         else // after hard fork core-583, always allow call order to be updated if collateral ratio
              // is increased and debt is not increased
         {
            // We didn't fill any call orders.  This may be because we
            // aren't in margin call territory, or it may be because there
            // were no matching orders. In the latter case,
            // if collateral ratio is not increased or debt is increased, we throw.
            // be here, we know no margin call was executed,
            // so call_obj's collateral ratio should be set only by op
            // ------
            // Before BSIP77, CR of the new/updated position is required to be above MCR;
            // after BSIP77, CR of the new/updated position is required to be above max(ICR,MCR).
            // The `current_initial_collateralization` variable has been initialized according to the logic,
            // so we directly use it here.
            bool check = ( !before_core_hardfork_1270
                            && call_obj->collateralization() > _bitasset_data->current_initial_collateralization )
                       || ( before_core_hardfork_1270
                            && ~call_obj->call_price < _bitasset_data->current_feed.settlement_price )
                       || ( old_collateralization.valid() && call_obj->debt <= *old_debt
                                                          && call_obj->collateralization() > *old_collateralization );
            FC_ASSERT( check,
               "Can only increase collateral ratio without increasing debt when the debt position's "
               "collateral ratio is lower than required initial collateral ratio (ICR), "
               "if not to trigger a margin call that be fully filled immediately",
               ("old_debt", old_debt)
               ("new_debt", call_obj->debt)
               ("old_collateralization", old_collateralization)
               ("new_collateralization", call_obj->collateralization() )
               );
         }
      }
   }

   return call_order_id;
} FC_CAPTURE_AND_RETHROW( (o) ) }

void_result bid_collateral_evaluator::do_evaluate(const bid_collateral_operation& o)
{ try {
   database& d = db();

   FC_ASSERT( d.head_block_time() > HARDFORK_CORE_216_TIME, "Not yet!" );

   _paying_account = &o.bidder(d);
   _debt_asset     = &o.debt_covered.asset_id(d);
   FC_ASSERT( _debt_asset->is_market_issued(), "Unable to cover ${sym} as it is not a collateralized asset.",
              ("sym", _debt_asset->symbol) );

   _bitasset_data  = &_debt_asset->bitasset_data(d);

   FC_ASSERT( _bitasset_data->has_settlement() );

   FC_ASSERT( o.additional_collateral.asset_id == _bitasset_data->options.short_backing_asset );

   FC_ASSERT( !_bitasset_data->is_prediction_market, "Cannot bid on a prediction market!" );

   const collateral_bid_index& bids = d.get_index_type<collateral_bid_index>();
   const auto& index = bids.indices().get<by_account>();
   const auto& bid = index.find( boost::make_tuple( o.debt_covered.asset_id, o.bidder ) );
   if( bid != index.end() )
      _bid = &(*bid);
   else
       FC_ASSERT( o.debt_covered.amount > 0, "Can't find bid to cancel?!");

   if( o.additional_collateral.amount > 0 )
   {
      if( _bid && d.head_block_time() >= HARDFORK_CORE_1692_TIME ) // TODO: see if HF check can be removed after HF
      {
         asset delta = o.additional_collateral - _bid->get_additional_collateral();
         FC_ASSERT( d.get_balance(*_paying_account, _bitasset_data->options.short_backing_asset(d)) >= delta,
                    "Cannot increase bid from ${oc} to ${nc} collateral when payer only has ${b}",
                    ("oc", _bid->get_additional_collateral().amount)("nc", o.additional_collateral.amount)
                    ("b", d.get_balance(*_paying_account, o.additional_collateral.asset_id(d)).amount) );
      } else
         FC_ASSERT( d.get_balance( *_paying_account,
                                   _bitasset_data->options.short_backing_asset(d) ) >= o.additional_collateral,
                    "Cannot bid ${c} collateral when payer only has ${b}", ("c", o.additional_collateral.amount)
                    ("b", d.get_balance(*_paying_account, o.additional_collateral.asset_id(d)).amount) );
   }

   return void_result();
} FC_CAPTURE_AND_RETHROW( (o) ) }

void_result bid_collateral_evaluator::do_apply(const bid_collateral_operation& o)
{ try {
   database& d = db();

   if( _bid )
      d.cancel_bid( *_bid, false );

   if( o.debt_covered.amount == 0 ) return void_result();

   d.adjust_balance( o.bidder, -o.additional_collateral  );

   _bid = &d.create<collateral_bid_object>([&]( collateral_bid_object& bid ) {
      bid.bidder = o.bidder;
      bid.inv_swan_price = o.additional_collateral / o.debt_covered;
   });

   // Note: CORE asset in collateral_bid_object is not counted in account_stats.total_core_in_orders

   return void_result();
} FC_CAPTURE_AND_RETHROW( (o) ) }

} } // graphene::chain


text:
package com.listener;

import java.util.Locale;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

import org.apache.commons.lang3.StringUtils;

import com.constant.SessionCONST;
import com.i18n.HttpMessages;
import com.i18n.LocaleResourceBundle;

/**
 * Application Lifecycle Listener implementation class HttpLifecycleListener
 *
 */
@WebListener
public class SessionLocaleListener implements HttpSessionAttributeListener, ServletRequestListener {

    /**
     * Default constructor.
     */
    public SessionLocaleListener() {
        // TODO Auto-generated constructor stub
    }

	/**
     * @see ServletRequestListener#requestDestroyed(ServletRequestEvent)
     */
    public void requestDestroyed(ServletRequestEvent e)  {
         // TODO Auto-generated method stub

    }

	/**
     * @see ServletRequestListener#requestInitialized(ServletRequestEvent)
     */
    public void requestInitialized(ServletRequestEvent e)  {
         // TODO Auto-generated method stub
    	HttpServletRequest req = (HttpServletRequest) e.getServletRequest();
    	Locale locale = req.getLocale();
    	req.getSession().setAttribute(SessionCONST.LOCALE, locale);
    }

	@Override
	public void attributeAdded(HttpSessionBindingEvent e) {
		// TODO Auto-generated method stub
		String attrName = e.getName();
		if (StringUtils.equals(attrName, SessionCONST.LOCALE)) {
			Locale locale = (Locale) e.getValue();
			HttpSession session = e.getSession();
			HttpMessages messages = new HttpMessages(LocaleResourceBundle.get(locale));
			session.setAttribute(SessionCONST.MESSAGES, messages);
		}
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent e) {
		// TODO Auto-generated method stub
	}

}

redpajama_set_name: RedPajamaGithub


text:
Ext.require( [ 'ASPIREdb.view.LabelApplyGrid' ] );

/**
 * Displays the list of genes which have two or more mutations at unique positions in the same subject.
 */
Ext.define( "ASPIREdb.view.VariantCompoundHeterozygoteWindow", {
   extend : 'Ext.Window',
   layout : 'fit',
   itemId : 'variantCompoundHeterozygoteWindow',
   title : 'Potential compound heterozygote variants',
   header: {
      items: [{
          xtype: 'image',
          style:'right: auto; left: 0px; top: 6px;',
          src: 'scripts/ASPIREdb/resources/images/qmark.png',
          listeners: {
             afterrender: function(c) {
                 Ext.create('Ext.tip.ToolTip', {
                     target: c.getEl(),
                     html: 'From the selected variants, identifies genes which have more than one variant in the same subject. Right-click on the compound heterozygotes of interest to create a variant label for the affected variants listed in the current row. Click here for more information.'
                 });
             }
         }
      }],
      layout: 'fit'
  },
   width : 530,
   height : 400,
   closable : true,
   modal : true,

   initComponent : function() {
      this.callParent();
   },

   // variantGenes = Map<String.PatientId, Map<GeneValueObject, Collection<VariantValueObject>>>
   constructData : function(variantStore, variantGenes) {
      var data = [];

      for (patientId in variantGenes) {
         for (gene in variantGenes[patientId]) { // dwr converted gene to a string

            var variantList = variantGenes[patientId][gene];

            data.push( [ patientId, gene, variantList ] );
         }

      }

      // console.log( Ext.JSON.encode( data ) );
      return data;
   },

   constructFields : function() {
      var fields = [ 'patientId', 'gene', 'variants', ];
      return fields;
   },

   constructColumns : function() {
      var columns = [ {
         header : 'Patient Id',
         dataIndex : 'patientId',
         flex : 0.7,
      }, {
         header : 'Gene',
         dataIndex : 'gene',
         flex : 1.5,
         renderer : function(value, meta, rec, rowIndex, colIndex, store) {
            meta.tdAttr = 'data-qtip="Right-click to apply variant labels"';
            // return value + "   ";
            return value;
         }
      }, {
         header : 'Genome Coordinates',
         dataIndex : 'variants',
         flex : 1,
         renderer : function(variantList, meta, rec, rowIndex, colIndex, store) {
            var coords = [];
            for (i = 0; i < variantList.length; i++) {
               coords.push( variantList[i]['genomeCoordinates'] );
            }
            return coords.join( '
' );
         }
      }, ];

      return columns;
   },

   getSelectedIds : function(index) {

      if ( index == null ) {
         console.log( 'Warning index is null!' )
         return;
      }

      var store = Ext.StoreManager.lookup( '#cmpHetStore' );

      var variants = store.getAt( index ).get( 'variants' )

      if ( variants.length == 0 ) {
         return;
      }

      var ids = [];

      for (var i = 0; i < variants.length; i++) {
         ids.push( variants[i].id );
      }

      // console.log( 'return selected ids from VariantCompound! ' + Ext.JSON.encode( ids ) );

      return ids;
   },

   initGridAndShow : function(variantStore, variantGenes) {
      var me = this;

      // var data = [ ["991","45_L","CNV","6:32450499-32565205","RNU1-61P"] ];
      var data = me.constructData( variantStore, variantGenes );
      var fields = me.constructFields();
      var columns = me.constructColumns();

      var store = Ext.create( 'Ext.data.ArrayStore', {
         fields : fields,
         data : data,
         autoLoad : true,
         autoSync : true,
         storeId : '#cmpHetStore',
      } );

      var grid = Ext.create( 'ASPIREdb.view.LabelApplyGrid', {
         store : store,
         columns : columns,
         getSelectedIds : me.getSelectedIds,
         isSubjectLabel : false,
         itemId : '#cmpHetGrid',
         scope : me,
      } );

      me.add( grid );
      me.show();
   },

} );


text:
package org.apache.gobblin.data.management.copy;

import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.Lists;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.configuration.SourceState;
import org.apache.gobblin.data.management.copy.hive.HiveDataset;
import org.apache.gobblin.data.management.copy.hive.HiveDatasetFinder;
import org.apache.gobblin.data.management.copy.hive.HiveTargetPathHelper;
import org.apache.gobblin.hive.HiveMetastoreClientPool;
import org.apache.gobblin.metrics.event.EventSubmitter;
import org.apache.hadoop.fs.LocalFileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.metadata.Table;

public class MockHiveDatasetFinder extends HiveDatasetFinder {

  Path tempDirRoot;
  SourceState state;

  public MockHiveDatasetFinder(LocalFileSystem fs, Properties properties,
      EventSubmitter eventSubmitter) throws IOException {
    super(fs, properties, eventSubmitter);
    this.tempDirRoot = new Path(properties.getProperty("tempDirRoot"));
  }

  public Collection<DbAndTable> getTables() throws IOException {
    List<DbAndTable> tables = Lists.newArrayList();

    for (int i = 0; i < 3; i++) {
      tables.add(new DbAndTable("testDB", "table" + i));
    }

    return tables;
  }

  @Override
  public Iterator<HiveDataset> getDatasetsIterator() throws IOException {

    return new AbstractIterator<HiveDataset>() {
      private Iterator<DbAndTable> tables = getTables().iterator();

      @Override
      protected HiveDataset computeNext() {
        try {
          while (this.tables.hasNext()) {
            DbAndTable dbAndTable = this.tables.next();
            File dbPath = new File(tempDirRoot + "/testPath/testDB/" + dbAndTable.getTable());
            fs.mkdirs(new Path(dbPath.getAbsolutePath()));
            Properties hiveProperties = new Properties();
            hiveProperties.setProperty(ConfigurationKeys.USE_DATASET_LOCAL_WORK_DIR, "true");
            hiveProperties.setProperty(HiveTargetPathHelper.COPY_TARGET_TABLE_PREFIX_TOBE_REPLACED, tempDirRoot + "/testPath");
            hiveProperties.setProperty(HiveTargetPathHelper.COPY_TARGET_TABLE_PREFIX_REPLACEMENT, tempDirRoot + "/targetPath");
            Table table = new Table(Table.getEmptyTable(dbAndTable.getDb(), dbAndTable.getTable()));
            table.setDataLocation(new Path(dbPath.getPath()));
            HiveMetastoreClientPool pool = HiveMetastoreClientPool.get(new Properties(), Optional.absent());
            HiveDataset dataset = new HiveDataset(new LocalFileSystem(), pool, table, hiveProperties);
            return dataset;
          }
        } catch (IOException e) {
          Throwables.propagate(e);
        }
        return endOfData();
      }
    };
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.guilhermesgb.robospiceretrofit" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:name="com.activeandroid.app.Application"
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name=".view.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".presenter.network.WordPressCMSRetrofitSpiceService"
            android:exported="false" />

        <service
            android:name=".model.storage.OfflineSpiceService"
            android:exported="false" />

        <meta-data
            android:name="AA_DB_NAME"
            android:value="oviajante.db" />
        <meta-data
            android:name="AA_DB_VERSION"
            android:value="2" />
        <meta-data
            android:name="AA_MODELS"
            android:value="com.guilhermesgb.robospiceretrofit.model.GuideItem" />

    </application>

</manifest>


text:
package org.consec.oauth2.authzserver.jpa.entities;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serializable;

@Embeddable
public class OrganizationTrustPK implements Serializable {
    @Basic(optional = false)
    @Column(name = "owner_id", nullable = false)
    private int ownerId;
    @Basic(optional = false)
    @Column(name = "organization_id", nullable = false)
    private int organizationId;

    public OrganizationTrustPK() {
    }

    public OrganizationTrustPK(int ownerId, int organizationId) {
        this.ownerId = ownerId;
        this.organizationId = organizationId;
    }

    public int getOwnerId() {
        return ownerId;
    }

    public void setOwnerId(int ownerId) {
        this.ownerId = ownerId;
    }

    public int getOrganizationId() {
        return organizationId;
    }

    public void setOrganizationId(int organizationId) {
        this.organizationId = organizationId;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (int) ownerId;
        hash += (int) organizationId;
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof OrganizationTrustPK)) {
            return false;
        }
        OrganizationTrustPK other = (OrganizationTrustPK) object;
        if (this.ownerId != other.ownerId) {
            return false;
        }
        if (this.organizationId != other.organizationId) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.consec.oauth2.authzserver.jpa.entities.OrganizationTrustPK[ ownerId=" + ownerId + ", organizationId=" + organizationId + " ]";
    }

}


text:
package org.maera.plugin.hostcontainer;

/**
 * Interface into the host application's dependency injection system.  The implementation will be expected to be able
 * to instantiate modules and possibly {@link org.maera.plugin.ModuleDescriptor} instances via constructor
 * injection, matching the constructor with the largest number of arguments first.
 *
 * @since 2.2.0
 */
public interface HostContainer {
    /**
     * Constructs an instance of a class, matching the constructor with the largest number of arguments first, and
     * autowires as appropriate.  Actual method of autowiring may vary between implementations, though all should
     * support constructor injection.
     *
     * @param moduleClass The class
     * @return An instance of the passed class
     * @throws IllegalArgumentException If unable to instantiate the class
     */
    <T> T create(Class<T> moduleClass) throws IllegalArgumentException;
}


text:
This is a set of whole-program tests, like the 'test-suite' project in LLVM.
The test script runs these programs for the target and compares the output
to regular expressions embedded in source code comments prefixed with 'CHECK:'.
This is similar to DejaGnu and llvm-lit. Each file is a standalone program.

I've grabbed snippets of code from a variety of open source projects to get
coverage of different coding styles and idioms. 3rd party programs retain
their own licenses, which are indicated in the top of each file. These
tests are all single threaded.

To run all tests:

    ./runtest.py

To run a specific test:

    ./runtest.py *program names*

To run only on emulator:

    ./runtest.py --target emulator *program names*

- The test script skips filenames that begin with underscore, which is
  useful for known failing cases.
- This skips tests with "noverilator" in the filename (used for tests that
  take too long to run in verilator).
- This runtest script supports '--target host' to run on host machine.
  Some tests fail in this configuration because they use intrinsics
  that exist only for Nyuzi.
- The Csmith random generation tool generated The csmith* tests:
  <http://embed.cs.utah.edu/csmith/>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Travaux Scientifiques du Musée National d'Histoire Naturelle de Luxembourg 14: 252 (1989)

#### Original name
Taeniolella trapeliopses Diederich

### Remarks
null


text:
<?php

require_once(dirname(__FILE__).'/sfGeneratorBaseTask.class.php');

/**
 * Generates a new project.
 *
 * @package    symfony
 * @subpackage task
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id$
 */
class sfGenerateProjectTask extends sfGeneratorBaseTask
{
  /**
   * @see sfTask
   */
  protected function doRun(sfCommandManager $commandManager, $options)
  {
    $this->process($commandManager, $options);

    return $this->execute($commandManager->getArgumentValues(), $commandManager->getOptionValues());
  }

  /**
   * @see sfTask
   */
  protected function configure()
  {
    $this->addArguments(array(
      new sfCommandArgument('name', sfCommandArgument::REQUIRED, 'The project name'),
      new sfCommandArgument('author', sfCommandArgument::OPTIONAL, 'The project author', 'Your name here'),
    ));

    $this->addOptions(array(
      new sfCommandOption('orm', null, sfCommandOption::PARAMETER_REQUIRED, 'The ORM to use by default', 'Doctrine'),
      new sfCommandOption('installer', null, sfCommandOption::PARAMETER_REQUIRED, 'An installer script to execute', null),
    ));

    $this->namespace = 'generate';
    $this->name = 'project';

    $this->briefDescription = 'Generates a new project';

    $this->detailedDescription = <<<EOF
The [generate:project|INFO] task creates the basic directory structure
for a new project in the current directory:

  [./symfony generate:project blog|INFO]

If the current directory already contains a symfony project,
it throws a [sfCommandException|COMMENT].

By default, the task configures Doctrine as the ORM. If you want to use
Propel, use the [--orm|COMMENT] option:

  [./symfony generate:project blog --orm=Propel|INFO]

If you don't want to use an ORM, pass [none|COMMENT] to [--orm|COMMENT] option:

  [./symfony generate:project blog --orm=none|INFO]

You can also pass the [--installer|COMMENT] option to further customize the
project:

  [./symfony generate:project blog --installer=./installer.php|INFO]

You can optionally include a second [author|COMMENT] argument to specify what name to
use as author when symfony generates new classes:

  [./symfony generate:project blog "Jack Doe"|INFO]
EOF;
  }

  /**
   * @see sfTask
   */
  protected function execute($arguments = array(), $options = array())
  {
    if (file_exists('symfony'))
    {
      throw new sfCommandException(sprintf('A symfony project already exists in this directory (%s).', getcwd()));
    }

    if (!in_array(strtolower($options['orm']), array('propel', 'doctrine', 'none')))
    {
      throw new InvalidArgumentException(sprintf('Invalid ORM name "%s".', $options['orm']));
    }

    if ($options['installer'] && $this->commandApplication && !file_exists($options['installer']))
    {
      throw new InvalidArgumentException(sprintf('The installer "%s" does not exist.', $options['installer']));
    }

    // clean orm option
    $options['orm'] = ucfirst(strtolower($options['orm']));

    $this->arguments = $arguments;
    $this->options = $options;

    // create basic project structure
    $this->installDir(dirname(__FILE__).'/skeleton/project');

    // update ProjectConfiguration class (use a relative path when the symfony core is nested within the project)
    $symfonyCoreAutoload = 0 === strpos(sfConfig::get('sf_symfony_lib_dir'), sfConfig::get('sf_root_dir')) ?
      sprintf('dirname(__FILE__).\'/..%s/autoload/sfCoreAutoload.class.php\'', str_replace(sfConfig::get('sf_root_dir'), '', sfConfig::get('sf_symfony_lib_dir'))) :
      var_export(sfConfig::get('sf_symfony_lib_dir').'/autoload/sfCoreAutoload.class.php', true);

    $this->replaceTokens(array(sfConfig::get('sf_config_dir')), array('SYMFONY_CORE_AUTOLOAD' => str_replace('\\', '/', $symfonyCoreAutoload)));

    $this->tokens = array(
      'ORM'          => $this->options['orm'],
      'PROJECT_NAME' => $this->arguments['name'],
      'AUTHOR_NAME'  => $this->arguments['author'],
      'PROJECT_DIR'  => sfConfig::get('sf_root_dir'),
    );

    $this->replaceTokens();

    // execute the choosen ORM installer script
    if (in_array($options['orm'], array('Doctrine', 'Propel')))
    {
      include dirname(__FILE__).'/../../plugins/sf'.$options['orm'].'Plugin/config/installer.php';
    }

    // execute a custom installer
    if ($options['installer'] && $this->commandApplication)
    {
      if ($this->canRunInstaller($options['installer']))
      {
        $this->reloadTasks();
        include $options['installer'];
      }
    }

    // fix permission for common directories
    $fixPerms = new sfProjectPermissionsTask($this->dispatcher, $this->formatter);
    $fixPerms->setCommandApplication($this->commandApplication);
    $fixPerms->setConfiguration($this->configuration);
    $fixPerms->run();

    $this->replaceTokens();
  }

  protected function canRunInstaller($installer)
  {
    if (preg_match('#^(https?|ftps?)://#', $installer))
    {
      if (ini_get('allow_url_fopen') === false)
      {
        $this->logSection('generate', sprintf('Cannot run remote installer "%s" because "allow_url_fopen" is off', $installer));
      }
      if (ini_get('allow_url_include') === false)
      {
        $this->logSection('generate', sprintf('Cannot run remote installer "%s" because "allow_url_include" is off', $installer));
      }
      return ini_get('allow_url_fopen') && ini_get('allow_url_include');
    }
    return true;
  }
}


text:
#include <aws/acm-pca/model/IssueCertificateRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/utils/HashingUtils.h>

#include <utility>

using namespace Aws::ACMPCA::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

IssueCertificateRequest::IssueCertificateRequest() :
    m_certificateAuthorityArnHasBeenSet(false),
    m_csrHasBeenSet(false),
    m_signingAlgorithm(SigningAlgorithm::NOT_SET),
    m_signingAlgorithmHasBeenSet(false),
    m_validityHasBeenSet(false),
    m_idempotencyTokenHasBeenSet(false)
{
}

Aws::String IssueCertificateRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_certificateAuthorityArnHasBeenSet)
  {
   payload.WithString("CertificateAuthorityArn", m_certificateAuthorityArn);

  }

  if(m_csrHasBeenSet)
  {
   payload.WithString("Csr", HashingUtils::Base64Encode(m_csr));
  }

  if(m_signingAlgorithmHasBeenSet)
  {
   payload.WithString("SigningAlgorithm", SigningAlgorithmMapper::GetNameForSigningAlgorithm(m_signingAlgorithm));
  }

  if(m_validityHasBeenSet)
  {
   payload.WithObject("Validity", m_validity.Jsonize());

  }

  if(m_idempotencyTokenHasBeenSet)
  {
   payload.WithString("IdempotencyToken", m_idempotencyToken);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection IssueCertificateRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "ACMPrivateCA.IssueCertificate"));
  return headers;

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.oakeel.front.service.borrow;

import com.oakeel.front.domain.FrontUserHoldBond;
import com.oakeel.front.domain.PlatformFund;
import com.oakeel.front.enums.SplitUnit;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import javax.faces.bean.ManagedBean;

/**
 *
 * @author zmr
 */
@ManagedBean(name = "borrowCashService")
public class BorrowCashService {
    public List<PlatformFund> find(){
       PlatformFund pl = null;
       List<PlatformFund> listpl = new ArrayList<>();
       //初始化数据
       for(int i=0;i<5;i++){
           pl = new PlatformFund();
           int amount = new Random().nextInt(1000000);
           pl.setBaseAmount(amount);
           pl.setName("倒卖小孩儿燕子"+i+1+"号");
           pl.setRepayCycle(SplitUnit.周);
           pl.setRepayCycleNumber(new Random().nextInt(12)+1);
           pl.setBondNumber("201504150208"+i);
           pl.setYearRate(new BigDecimal(1));
           int number = new Random().nextInt(10) + 1;
           FrontUserHoldBond  bf = null;
           Set<FrontUserHoldBond> bfset = new HashSet<>();
           int issueC = new Random().nextInt(1000);
           int transact = new Random().nextInt(1000);
           while(true){
               if(transact>issueC)
               {
                   issueC = new Random().nextInt(1000);
                   transact = new Random().nextInt(1000);
               }
               else
                break;
           }
            pl.setIssueCopiesNum(issueC);
           pl.setTransactionCopiesNum(transact);
           for(int k=0;k<number;k++){
               bf = new FrontUserHoldBond();
               bfset.add(bf);
           }
           pl.setFrontUserHoldBonds(bfset);
           listpl.add(pl);
       }

       return listpl;
    }
}


text:
Vtiger_List_Js("Campaigns_List_Js",{},{

	readSelectedIds : function(decode){
		var view = jQuery('#view').val();
		if(view != "Detail"){
			return this._super(decode);
		}
		var selectedIdsElement = jQuery('#selectedIds');
		var selectedIdsDataAttr = 'selectedIds';
		var selectedIdsElementDataAttributes = selectedIdsElement.data();
		var selectedIds = selectedIdsElementDataAttributes[selectedIdsDataAttr];
		if (selectedIds == "") {
			selectedIds = new Array();
			this.writeSelectedIds(selectedIds);
		} else {
			selectedIds = selectedIdsElementDataAttributes[selectedIdsDataAttr];
		}
		if(decode == true){
			if(typeof selectedIds == 'object'){
				return JSON.stringify(selectedIds);
			}
		}
		return selectedIds;
	},

	readExcludedIds : function(decode){
		var view = jQuery('#view').val();
		if(view != "Detail"){
			return this._super(decode);
		}
		var exlcudedIdsElement = jQuery('#excludedIds');
		var excludedIdsDataAttr = 'excludedIds';
		var excludedIdsElementDataAttributes = exlcudedIdsElement.data();
		var excludedIds = excludedIdsElementDataAttributes[excludedIdsDataAttr];
		if (excludedIds == "") {
			excludedIds = new Array();
			this.writeExcludedIds(excludedIds);
		}else{
			excludedIds = excludedIdsElementDataAttributes[excludedIdsDataAttr];
		}
		if(decode == true){
			if(typeof excludedIds == 'object') {
				return JSON.stringify(excludedIds);
			}
		}
		return excludedIds;
	},

	writeSelectedIds : function(selectedIds){
		var view = jQuery('#view').val();
		if(view != "Detail"){
			this._super(selectedIds);
			return;
		}
		jQuery('#selectedIds').data('selectedIds',selectedIds);
	},

	writeExcludedIds : function(excludedIds){
		var view = jQuery('#view').val();
		if(view != "Detail"){
			this._super(excludedIds);
			return;
		}
		jQuery('#excludedIds').data('excludedIds',excludedIds);
	},

	/**
	 * Function to mark selected records
	 */
	markSelectedRecords : function(){
		var thisInstance = this;
		var selectedIds = this.readSelectedIds();
		if(selectedIds != ''){
			if(selectedIds == 'all'){
				jQuery('.listViewEntriesCheckBox').each( function(index,element) {
					jQuery(this).attr('checked', true).closest('tr').addClass('highlightBackgroundColor');
				});
				jQuery('#deSelectAllMsgDiv').show();
				var excludedIds = jQuery('[name="excludedIds"]').data('excludedIds');
				if(excludedIds != ''){
					jQuery('#listViewEntriesMainCheckBox').attr('checked',false);
					jQuery('.listViewEntriesCheckBox').each( function(index,element) {
						if(jQuery.inArray(jQuery(element).val(),excludedIds) != -1){
							jQuery(element).attr('checked', false).closest('tr').removeClass('highlightBackgroundColor');
						}
					});
				}
			} else {
				jQuery('.listViewEntriesCheckBox').each( function(index,element) {
					if(jQuery.inArray(jQuery(element).val(),selectedIds) != -1){
						jQuery(this).attr('checked', true).closest('tr').addClass('highlightBackgroundColor');
					}
				});
			}
			thisInstance.checkSelectAll();
		}
	},

	getRecordsCount : function(){
		var aDeferred = jQuery.Deferred();
		var view = jQuery('#view').val();
		if(view != "Detail"){
			return this._super();
		}
		var recordCountVal = jQuery("#recordsCount").val();
		if(recordCountVal != ''){
			aDeferred.resolve(recordCountVal);
		} else {
			var count = '';
			var cvId = this.getCurrentCvId();
			var module = app.getModuleName();
			var parent = app.getParentModuleName();
			var relatedModuleName = jQuery('[name="relatedModuleName"]').val();
			var recordId = jQuery('#recordId').val();
			var tab_label = jQuery('div.related').find('li.active').data('labelKey');
			var postData = {
				"module": module,
				"parent": parent,
				"action": "DetailAjax",
				"viewname": cvId,
				"mode": "getRecordsCount",
				"relatedModule" : relatedModuleName,
				'record' : recordId,
				'tab_label' : tab_label
			}
			AppConnector.request(postData).then(
				function(data) {
					jQuery("#recordsCount").val(data['result']['count']);
					count =  data['result']['count'];
					aDeferred.resolve(count);
				},
				function(error,err){

				}
			);
		}

		return aDeferred.promise();
	},

	/**
	 * Function to register events
	 */
	registerEvents : function(){
		var view = jQuery('#view').val();
		if(view != "Detail"){
			this._super();
			return;
		}
		this.registerMainCheckBoxClickEvent();
		this.registerCheckBoxClickEvent();
		this.registerSelectAllClickEvent();
		this.registerDeselectAllClickEvent();
	}
})


text:
package deviceLayer;

// it represents the Response type and format, made from Smart Devices as answers to Internet Clients Requests
public class Response {

	private String deviceID;	// Identity of the Smart Device which answered the request
	private String serviceName;	// Service which was previously requested for execution
	private String command;		// Command operated
	private Object result;		// Result of Service invocation, return value
	private long   requestID;	// used to identify the Thread which caused this request to be sent to the Smart Device,
								// in order to send the Response back to the appropriate Internet Client who requested it

	// default constructor
	public Response(){}

	public Response(String deviceID, String serviceName, String command, Object result){
		this.deviceID    = deviceID;
		this.serviceName = serviceName;
		this.command     = command;
		this.result		 = result;
	}

	// Getter & Setter Functions

	public void setRequestID(long requestID){
		this.requestID = requestID;
	}

	public long getRequestID(){
		return this.requestID;
	}

	// mark the Response with the corresponding Smart Device, from where it was produced
	public void setDeviceID(String deviceID){
		this.deviceID = deviceID;
	}

	public String getDeviceID(){
		return deviceID;
	}

	public void setServiceName(String serviceName){
		this.serviceName = serviceName;
	}

	public String getServiceName(){
		return serviceName;
	}

	public void setCommand(String command){
		this.command = command;
	}

	public String getCommand(){
		return command;
	}

	public void setResult(Object result){
		this.result = result;
	}

	public Object getResult(){
		return result;
	}
}


text:
define([
	"dojo/_base/declare",
	"dojo/_base/lang",
	"dojo/_base/Deferred",
	"dojo/dom-construct",
	"dojo/dom-geometry",
	"dojo/dom-class",
	"dojo/dom-style",
	"dojo/dom",
	"dojo/_base/window",
	"dojo/_base/sniff",
	"dojo/dnd/Source",
	"dojo/dnd/Manager",
	"../../core/_Module",
	"../AutoScroll"
], function(declare, lang, Deferred, domConstruct, domGeometry, domClass, domStyle, dom, win, has,
	Source, DndManager, _Module){

/*=====
	return declare(_Module, {
		_fixFF: function(source){
			// summary:
			//		Fix FireFox not firing onmouseover/onmousemove events during dnd.
			//		Can use this function when drag to/from non-grid sources.
		}
	});
=====*/

	var hitch = lang.hitch;

	return _Module.register(
	declare(_Module, {
		name: '_dnd',

		optional: ['selectRow', 'selectColumn'],

		constructor: function(){
			var t = this,
				g = t.grid,
				doc = win.doc;
			t.accept = [];
			t._profiles = {};
			t._selectStatus = {};
			t._node = domConstruct.create('div');
			t.batchConnect(
				[g, 'onCellMouseOver', '_checkDndReady'],
				[g, 'onCellMouseOut', '_dismissDndReady'],
				[g, 'onCellMouseDown', '_beginDnd'],
				[doc, 'onmouseup', '_endDnd'],
				[doc, 'onmousemove', '_onMouseMove'],
				[g, 'onCellMouseUp', function(evt){
					//FIXME: this is ugly.
					//selection end event fires on document, so it always after onCellMouseUp.
					//But dnd should check the selection result in order to show dnd cursor,
					//so do some setTimeout here.
					setTimeout(function(){
						t._checkDndReady(evt);
					}, 0);
				}]
			);
			t.subscribe("/dnd/cancel", '_endDnd');
		},

		load: function(args){
			var t = this,
				n = t.arg('sourceNode', t.grid.mainNode);
			t._source = new Source(n, {
				isSource: false,
				accept: t.accept,
				getSelectedNodes: function(){return [0];},
				getItem: hitch(t, '_getItem'),
				onSelectStart: function(){
					//Source stops text selecting on anything inside its domnode,
					//but we still need that when not dnding.
					if(this.notSelectText){
						Source.prototype.onSelectStart.apply(this, arguments);
					}
				},
				checkAcceptance: hitch(t, '_checkAcceptance'),
				onDraggingOver: hitch(t, '_onDraggingOver'),
				onDraggingOut: hitch(t, '_onDraggingOut'),
				onDropExternal: hitch(t, '_onDropExternal'),
				onDropInternal: hitch(t, '_onDropInternal')
			});
			if(has('ff')){
				t._fixFF(t._source, n);
			}
			t._source.grid = t.grid;
			t._saveSelectStatus();
			t.loaded.callback();
		},

		destroy: function(){
			this.inherited(arguments);
			this._source.destroy();
			domConstruct.destroy(this._node);
		},

		getAPIPath: function(){
			return {
				dnd: {
					_dnd: this
				}
			};
		},

		//Public----------------------------------------------------------------------
		profile: null,

		register: function(name, profile){
			this._profiles[name] = profile;
			[].push.apply(this.accept, profile.arg('accept'));
		},

		//Private-----------------------------------------------------------------
		_fixFF: function(source){
			return this.connect(win.doc, 'onmousemove', function(evt){
				var pos = domGeometry.position(source.node),
					x = evt.clientX,
					y = evt.clientY,
					alreadyIn = source._alreadyIn,
					isIn = y >= pos.y && y <= pos.y + pos.h && x >= pos.x && x <= pos.x + pos.w;
				if(!alreadyIn && isIn){
					source._alreadyIn = 1;	//1 as true
					source.onOverEvent();
				}else if(alreadyIn && !isIn){
					source._alreadyIn = 0;	//0 as false
					source.onOutEvent();
				}
			});
		},

		_onMouseMove: function(evt){
			var t = this;
			if(t._alreadyIn && (t._dnding || t._extDnding)){
				t._markTargetAnchor(evt);
			}
		},

		_saveSelectStatus: function(enabled){
			var name, selector, selectors = this.grid.select;
			if(selectors){
				for(name in selectors){
					selector = selectors[name];
					if(selector && lang.isObject(selector)){
						this._selectStatus[name] = selector.arg('enabled');
						if(enabled !== undefined){
							selector.enabled = enabled;
						}
					}
				}
			}
		},

		_loadSelectStatus: function(){
			var name, selector, selectors = this.grid.select;
			if(selectors){
				for(name in selectors){
					selector = selectors[name];
					if(selector && lang.isObject(selector)){
						selector.enabled = this._selectStatus[name];
					}
				}
			}
		},

		_checkDndReady: function(evt){
			var t = this, name, p;
			if(!t._dndReady && !t._dnding && !t._extDnding){
				for(name in t._profiles){
					p = t._profiles[name];
					if(p.arg('enabled') && p._checkDndReady(evt)){
						t.profile = p;
						// t._saveSelectStatus(false);
						domClass.add(win.body(), 'gridxDnDReadyCursor');
						t._source.notSelectText = 1;
						t._dndReady = 1;
						return;
					}
				}
			}
		},

		_dismissDndReady: function(){
			if(this._dndReady && !this._dndBegun){
				this._loadSelectStatus();
				this._dndReady = 0;	//0 as false
				domClass.remove(win.body(), 'gridxDnDReadyCursor');
			}
		},

		_beginDnd: function(evt){
			var t = this;
			t._checkDndReady(evt);
			if(t._dndReady){
				var p = t.profile,
					m = DndManager.manager();
				t._dndBegun = 1;
				t._source.isSource = true;
				t._source.canNotDragOut = !p.arg('provide').length;
				t._node.innerHTML = p._buildDndNodes();
				t._oldStartDrag = m.startDrag;
				m.startDrag = hitch(t, '_startDrag', evt);

				if(t.avatar){
					t._oldMakeAvatar = m.makeAvatar;
					m.makeAvatar = function(){
						return new t.avatar(m);
					};
				}
				m._dndInfo = {
					grid: t.grid,
					cssName: p._cssName,
					count: p._getDndCount()
				};
				t.grid.vScrollerNode.focus();
				p._onBeginDnd(t._source);
				dom.setSelectable(t.grid.domNode, false);
				t._saveSelectStatus(false);

			}
		},

		_endDnd: function(){
			var t = this,
				m = DndManager.manager();
			t._source.isSource = false;
			t._alreadyIn = 0;	//0 as false
			t._dndBegun = 0;
			delete m._dndInfo;
			if(t._oldStartDrag){
				m.startDrag = t._oldStartDrag;
				delete t._oldStartDrag;
			}
			if(t._oldMakeAvatar){
				m.makeAvatar = t._oldMakeAvatar;
				delete t._oldMakeAvatar;
			}
			if(t._dndReady || t._dnding || t._extDnding){
				t._dnding = t._extDnding = 0;	//0 as false
				t._destroyUI();
				dom.setSelectable(t.grid.domNode, true);
				domClass.remove(win.body(), 'gridxDnDReadyCursor');
				t.profile._onEndDnd();
				t._source.notSelectText = 0;
				t._loadSelectStatus();
			}
		},

		_createUI: function(){
			domClass.add(win.body(), 'gridxDnDCursor');
			if(this.grid.autoScroll){
				this.profile._onBeginAutoScroll();
				this.grid.autoScroll.enabled = true;
			}
		},

		_destroyUI: function(){
			var t = this;
			t._unmarkTargetAnchor();
			domClass.remove(win.body(), 'gridxDnDCursor');
			if(t.grid.autoScroll){
				t.profile._onEndAutoScroll();
				t.grid.autoScroll.enabled = false;
			}
		},

		_createTargetAnchor: function(){
			return domConstruct.create("div", {
				"class": "gridxDnDAnchor"
			});
		},

		_markTargetAnchor: function(evt){
			var t = this;
			if(t._extDnding || t.profile.arg('canRearrange')){
				var targetAnchor = t._targetAnchor,
					containerPos = domGeometry.position(t.grid.mainNode);
				if(!targetAnchor){
					targetAnchor = t._targetAnchor = t._createTargetAnchor();
					targetAnchor.style.display = "none";
					t.grid.mainNode.appendChild(targetAnchor);
				}
				domClass.add(targetAnchor, 'gridxDnDAnchor' + t.profile._cssName);
				var pos = t.profile._calcTargetAnchorPos(evt, containerPos);
				if(pos){
					domStyle.set(targetAnchor, pos);
					targetAnchor.style.display = "block";
				}else{
					targetAnchor.style.display = "none";
				}
			}
		},

		_unmarkTargetAnchor: function(){
			var targetAnchor = this._targetAnchor;
			if(targetAnchor){
				targetAnchor.style.display = "none";
				domClass.remove(targetAnchor, 'gridxDnDAnchor' + this.profile._cssName);
			}
		},

		//---------------------------------------------------------------------------------
		_startDrag: function(evt, source, nodes, copy){
			var t = this;
			if(t._dndReady && source === t._source){
				t._oldStartDrag.call(DndManager.manager(), source, t._node.childNodes, copy);
				t._dndReady = 0;	//0 as false
				t._dnding = t._alreadyIn = 1;	//1 as true
				t._createUI();
				t._markTargetAnchor(evt);
			}
		},

		_getItem: function(id){
			return {
				type: this.profile.arg('provide'),
				data: this.profile._getItemData(id)
			};
		},

		_checkAcceptance: function(source, nodes){
			var t = this,
				getHash = function(arr){
					var res = {};
					for(var i = arr.length - 1; i >= 0; --i){
						res[arr[i]] = 1;
					}
					return res;
				},
				checkAcceptance = Source.prototype.checkAcceptance,
				res = checkAcceptance.apply(t._source, arguments);
			if(res){
				if(source.grid === t.grid){
					return t.profile.arg('canRearrange');
				}
				if(!source.canNotDragOut){
					for(var name in t._profiles){
						var p = t._profiles[name];
						var accepted = checkAcceptance.apply({
							accept: getHash(p.arg('accept'))
						}, arguments);
						if(p.arg('enabled') && accepted &&
							(!p.checkAcceptance || p.checkAcceptance.apply(p, arguments))){
							t.profile = p;
							t._extDnding = 1;	//1 as true
							return true;
						}
					}
				}
			}
			return false;
		},

		_onDraggingOver: function(){
			var t = this;
			if(t._dnding || t._extDnding){
				t._alreadyIn = 1;	//1 as true
				t._createUI();
			}
		},

		_onDraggingOut: function(){
			var t = this;
			if(t._dnding || t._extDnding){
				t._alreadyIn = 0;	//0 as false
				t._destroyUI();
			}
		},

		_onDropInternal: function(nodes, copy){
			this.profile._onDropInternal(nodes, copy);
			//
			// Fix IE anchor not hide when drop
			//
			this._endDnd();
		},

		_onDropExternal: function(source, nodes, copy){
			var t = this, dropped = t.profile._onDropExternal(source, nodes, copy);
			Deferred.when(dropped, function(){
				if(!copy){
					if(source.grid){
						source.grid.dnd._dnd.profile.onDraggedOut(t._source);
					}else{
						source.deleteSelectedNodes();
					}
				}
			});
		}
	}));
});


text:
using namespace v8;
using namespace std;
using namespace Graphos;

namespace Graphos
{
	namespace Content
	{
		class ScriptController
		{
		public:
			bool				Initialize( void );
			void				Shutdown( void );

			Script*				CreateObjectInstance( string className, unsigned int ownerID, GameObject* owner = nullptr );

			static
			ScriptController&	Get( void )
			{
				static ScriptController instance;
				return instance;
			}

		private:
								ScriptController( void ) : isInitialized( false ) { }
								ScriptController( const ScriptController& );
			void				operator=( const ScriptController& );

			HandleScope			handleScope;
			Persistent<Context>	context;
			Local<Object>		globalObject;

			bool				isInitialized;
		};
	}
}

#endif//_SCRIPTCONTROLLER_H_


text:
class Dir

  def self.walk(start_dir, &blk)
    Dir["#{start_dir}/{*,.*}"].each do |item|
      blk.call item
      if File.directory?(item) && !(item =~ /\/\.$/) && !(item =~ /\/\.\.$/)
        walk(item, &blk)
      end
    end
  end

end

module Calatrava

  class Template

    def initialize(directory)
      @directory = directory
    end

    def target_name(item)
      item.sub("#{@directory}/", "")
    end

    def walk_directories(&blk)
      Dir.walk(@directory) do |item|
        if File.directory?(item)
          blk.call target_name(item)
        end
      end
    end

    def walk_files(&blk)
      Dir.walk(@directory) do |item|
        if File.file? item
          blk.call(:path => item, :name => target_name(item))
        end
      end
    end

  end

end


text:
"""
test_skdata
----------------------------------

Tests for `skdata` module.
"""
# from contextlib import contextmanager
# local
from skdata import cleaning

import os
import sys
import pandas as pd
import unittest

class TestCleaning(unittest.TestCase):
    data = None

    def setUp(self):
        data_path = os.path.dirname(os.path.dirname(__file__))
        data_path = os.path.join(data_path, 'data', 'train.csv')
        self.data = pd.read_csv(data_path, index_col='PassengerId')

    def tearDown(self):
        pass

    def test_000_categorize(self):
        _data = self.data.copy()

        survived_dict = {0: 'Died', 1: 'Survived'}
        pclass_dict = {1: 'Upper Class', 2: 'Middle Class', 3: 'Lower Class'}
        embarked_dict = {
            'C': 'Cherbourg', 'Q': 'Queenstown', 'S': 'Southampton'
        }

        _data.Embarked.replace(embarked_dict, inplace=True)

        cleaning.categorize(
            data=_data, col_name='Survived', categories=survived_dict
        )
        cleaning.categorize(
            data=_data, col_name='Pclass', categories=pclass_dict
        )
        cleaning.categorize(data=_data, col_name='Sex')
        cleaning.categorize(data=_data, col_name='Embarked')

        assert _data.Survived.dtype == 'category'
        assert _data.Pclass.dtype == 'category'
        assert _data.Sex.dtype == 'category'
        assert _data.Embarked.dtype == 'category'

    def test_001_drop_columns_with_unique_values(self):
        _data = self.data.copy()

        assert 'Name' in _data.keys()
        assert 'Ticket' in _data.keys()

        cleaning.drop_columns_with_unique_values(data=_data, max_unique_values=0.3)

        assert 'Name' not in _data.keys()
        assert 'Ticket' not in _data.keys()

    def test_002(self):
        _data = self.data.copy()

        assert 'Age' in _data

        cleaning.dropna_columns(data=_data, max_na_values=0.1)

        assert 'Age' not in _data

if __name__ == '__main__':
    sys.exit(unittest.main())


text:
/** \file
Allow interaction with Python iterables.
*/

#ifndef RANGE_PYTHON_PYTHON_RANGE_HPP_INCLUDED
#define RANGE_PYTHON_PYTHON_RANGE_HPP_INCLUDED

// Include the Python C API, safely.
#include <boost/python/detail/wrap_python.hpp>

#include <boost/python/object.hpp>
#include <boost/python/handle.hpp>
#include <boost/python/errors.hpp>
#include <boost/python/extract.hpp>
#include <boost/python/converter/registry.hpp>

#include "range/core.hpp"

namespace range {

/** \brief
Represent a Python iterable as a range.

Python iterables are such things as lists, tuples, and generators.
The range is lazy; the length of the iterable is not checked.
The elements are extracted as the correct type only as they are queried.

If its elements should be returned as \c boost::python::object, then give no
template parameters.
If its elements are all one type, then give that type as the template parameter.
If its elements have different types, then give the sequence of types as
template parameters.

Even if a sequence of types is given, empty() will happily return \c true when
the Python iterable is exhausted.

To use this class, it must be registered with Boost.Python.
For example, your \c BOOST_PYTHON_MODULE could contain:

\code
using namespace range;
python::convert_object_to_range <python_range <double>>();
def <void (python_range <double>)> ("my_function", my_function);
\endcode

\tparam Types
    The types that the iterable contains.
    If none are given, \c first() will return values of
    \c boost::python::object.
    If one or more are given, those types will be extracted from the Python
    iterable in order.
    The last type will be repeated indefinitely.

Python exceptions are propagated.

This class is defined to call next() on the Python iterator lazily.
However, it is not defined when it is called exactly; it may be called earlier
than expected.
This may yield unexpected results if the Python iterator has side effects or
raises exceptions.

\internal
This uses the APIs at
http://docs.python.org/2/c-api/iter.html: PyIter_Check, PyIter_Next
https://docs.python.org/2/c-api/object.html: PyObject_GetIter

This class has two attributes: iterator_ and first_.
iterator_ holds the current iterator; if it has been moved or copied out from,
it is null (not None); otherwise it is a Python iterator.
first_ caches the first object.
It is either null, or holds the first object, if next() has been called on the
Python iterator already.
first_ is necessary because all operations can need to call next() on the
Python iterator, because of how the Python iterator protocol works: next() tells
whether the range is empty and if so returns the first element.
*/
template <class ... Types> class python_range;

namespace python_range_operation {
    struct python_range_tag {};
} // namespace python_range_operation

template <class ... Types>
    struct tag_of_qualified <python_range <Types ...>>
{ typedef python_range_operation::python_range_tag type; };

namespace python {
namespace detail {

    class python_range_base {
    protected:
        explicit python_range_base (boost::python::object const & iterable)
        // PyObject_GetIter is equivalent to iter(o).
        : iterator_ (PyObject_GetIter (iterable.ptr()))
        {
            if (!iterator_ && PyErr_Occurred())
                boost::python::throw_error_already_set();
        }

        python_range_base (python_range_base const & that) {
            // Steal the iterator from "that".
            using std::swap;
            swap (this->iterator_, that.iterator_);
            swap (this->first_, that.first_);
        }

        python_range_base (boost::python::handle<> && iterator)
        : iterator_ (iterator.release()) {}

    private:
        // Both the iterator and the cached first element are handles, so that
        // they can be null.
        // boost::python::object's can be None, but we want to distinguish
        // between None in a range and a range being invalid.
        mutable boost::python::handle<> iterator_;
        mutable boost::python::handle<> first_;

    protected:
        /**
        Return a boost::python::object that contains the iterator starting at
        the next element.
        */
        boost::python::object next_iterator() {
            fill_first();
            return boost::python::object (iterator_);
        }

        /**
        Retrieve the first element from the Python iterator.
        Do nothing if the first element has already been retrieved.

        \return A reference to the handle holding the first element.
            If the handle is empty, the iterator was empty.

        \throw boost::python::error_already_set iff a Python exception is
            thrown while retrieving the element.
        */
        boost::python::handle<> & fill_first() const {
            if (!first_) {
                assert (iterator_.get() != nullptr
                    && "The iterable should not have been pilfered.");
                // PyIter_Next() is like next() except it does not raise a
                // StopIteration exception if the iterator is exhausted.
                // Instead, PyIter_Next returns NULL with no exception set.
                // If another exception is thrown, PyIter_Next returns NULL and
                // an exception is set.
                first_ = boost::python::handle<> (boost::python::allow_null (
                    PyIter_Next (iterator_.get())));
                if (PyErr_Occurred())
                    boost::python::throw_error_already_set();
            }
            return first_;
        }
    };

    template <class Range> inline
        boost::python::object next_iterator (Range & range)
    { return range.next_iterator(); }

} // namespace detail

} // namespace python

template <class ... Types> class python_range
: python::detail::python_range_base
{
    typedef python::detail::python_range_base base_type;
public:
    /**
    Construct from a Python iterable.
    Note that this does not have to be an iterator: the equivalent of
    <c>iter (iterable)</c> is called.

    \throw boost::python::error_already_set if a Python exception is raised.
        For example, if the object is not an iterable, the call to \c iter
        raises a ValueError.
    */
    explicit python_range (boost::python::object const & iterable)
    : base_type (iterable) {}

    /**
    Construct from another python_range, stealing its state.
    That means that its first element becomes the first element of this.
    This should really be the move constructor, but Boost.Python is not happy
    with that.
    */
    python_range (python_range const & that) = default;

private:
    friend boost::python::object
        python::detail::next_iterator <python_range> (python_range &);

    /**
    Construct from a Python iterator with the first element it will produce as
    the first element of the range.
    */
    python_range (boost::python::handle<> && iterator)
    : base_type (std::move (iterator)) {}

private:
    friend class helper::member_access;

    /* empty. */
    bool empty (direction::front) const { return !fill_first(); }

    /* first. */
    /// Extract the first type (if any) from a boost::python::object.
    template <class ... Types2> struct extract_first {
        typedef boost::python::object result_type;

        result_type && operator() (result_type && object) const
        { return std::move (object); }
    };

    template <class FirstType, class ... Rest>
        struct extract_first <FirstType, Rest ...>
    {
        typedef FirstType result_type;

        FirstType operator() (boost::python::object && object) const
        { return boost::python::extract <FirstType> (std::move (object)); }
    };

    typename extract_first <Types ...>::result_type
        first (direction::front) const
    {
        boost::python::handle<> & first = fill_first();
        assert (!!first || "This range is empty.");
        return extract_first <Types ...>() (boost::python::object (first));
    }

    /* chop_in_place. */
    class unavailable_type;
    typedef typename std::conditional <(sizeof ... (Types) <= 1),
        direction::front, unavailable_type>::type front_if_homogeneous;

    // This is the natural way of using a Python iterator.
    typename extract_first <Types ...>::result_type
        chop_in_place (front_if_homogeneous)
    {
        boost::python::handle<> & first = fill_first();
        assert (!!first || "This range is empty.");
        // Set first to 0 and return as an object.
        return extract_first <Types ...>() (boost::python::object (
            boost::python::handle<> (first.release())));
    }
};

namespace python_range_operation {

    // drop_one: only defined for rvalue references.
    // For zero or one types, return the same range type.
    template <class ... Types>
        inline python_range <Types ...> implement_drop_one (
            python_range_tag const &, python_range <Types ...> && range,
            direction::front)
    {
        return python_range <Types ...> (
            ::range::python::detail::next_iterator (range));
    }

    // For two or more types, remove the first type.
    template <class FirstType, class SecondType, class ... Types>
        inline python_range <SecondType, Types ...> implement_drop_one (
            python_range_tag const &,
            python_range <FirstType, SecondType, Types ...> && range,
            direction::front)
    {
        return python_range <SecondType, Types ...> (
            ::range::python::detail::next_iterator (range));
    }

    // chop is implemented automatically.

} // namespace python_range_operation

namespace python {

/**
Construct an object of this class to register a python_range.
This should be done in the BOOST_PYTHON_MODULE function.
\tparam Range
    The python_range to register.
*/
template <class Range> class convert_object_to_range;

template <class ... Types>
    class convert_object_to_range <python_range <Types ...>>
{
public:
    convert_object_to_range() {
        boost::python::converter::registry::push_back (
            &convertible, &construct,
            boost::python::type_id <python_range <Types ...>>());
    }

private:
    // Always convertible.
    static void * convertible (PyObject * pointer)
    { return pointer /*PyIter_Check (pointer) ? pointer : nullptr*/; }

    static void construct (PyObject* python_object,
        boost::python::converter::rvalue_from_python_stage1_data * data)
    {
        typedef python_range <Types ...> range;
        boost::python::object object (boost::python::handle<> (
            boost::python::borrowed (python_object)));
        typedef boost::python::converter::rvalue_from_python_storage <range>
            storage_type;
        void * storage = reinterpret_cast <storage_type*> (data)->storage.bytes;

        new (storage) range (object);

        data->convertible = storage;
    }
};

} // namespace python

} // namespace range

#endif // RANGE_PYTHON_PYTHON_RANGE_HPP_INCLUDED


text:
startdate: 2-11-2020
remoteurl: "http://supernemo.org"
location: "Bratislava, Slovakia"
thumbnail: "https://cdn.pixabay.com/photo/2016/12/13/23/56/bratislava-1905408_960_720.jpg"
abstract: |
  Pawel and his team will kindly host us in Bratislava for our autumn meeting. The meeting will be in the first week of November, with exact dates to be confirmed closer to the time.
---


text:
```
$ npm install codekit-scanner
```

Scans Codekit dependencies of a core JS file like

```
// @codekit-prepend 'js/framework.utilities.js'
// @codekit-prepend 'js/framework.file.js'
// @codekit-prepend 'core.config.js'
(function(){
  console.log("Hello World, I am core.js");
})()
// @codekit-append 'modules/module.js'

// @codekit-append 'views/view.js'
```
Resolves dependencies by local JS directory and framework directory just like Codekit does.

## Gulp Integration

```
var codekit = require('codekit-scanner');

gulp.task('default', function () {
    codekit({file: 'js/core.js', fw: 'external/UIFramework', jsDir : 'js'}, function(files){
        console.log('files',files);
        gulp.src(files)
            .pipe(sourcemaps.init())
            .pipe(uglify())
            .pipe(concat('core-min.js'))
            .pipe(sourcemaps.write('.'))
            .pipe(gulp.dest('dist/js'));
    });
});
```


text:
Space Invaders Blast Down for {{initiativeName}}

Features:

{{feature.feature.Name}}


text:
<!DOCTYPE html>

    <title>404 - Page not found –  – </title>

        <meta charset="utf-8" />
    <meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0'>

    <meta name="description" content="">
    <meta property="og:description" content="" />

    <meta name="author" content="" />

    <meta property="og:title" content="404 - Page not found" />
    <meta property="twitter:title" content="404 - Page not found" />

    <link rel="stylesheet" type="text/css" href="/style.css" />
    <link rel="alternate" type="application/rss+xml" title=" - " href="/feed.xml" />

            about DesignAnd.VC…

How design and venture capital (VC) work together

404 - Page not found

Sorry, we can't find that page that you're looking for. You can try again by going back to the homepage.


text:
<?php

namespace Mage\SalesRule\Test\Constraint;

use Magento\Mtf\Constraint\AbstractAssertForm;
use Mage\SalesRule\Test\Page\Adminhtml\PromoQuoteIndex;
use Mage\SalesRule\Test\Page\Adminhtml\PromoQuoteEdit;
use Mage\SalesRule\Test\Fixture\SalesRule;

/**
 * Assert that displayed sales rule data on edit page equals passed from fixture.
 */
class AssertCartPriceRuleForm extends AbstractAssertForm
{
    /* tags */
    const SEVERITY = 'low';
    /* end tags */

    /**
     * Skipped fields for verify data.
     *
     * @var array
     */
    protected $skippedFields = ['conditions_serialized'];

    /**
     * Assert that displayed sales rule data on edit page equals passed from fixture.
     *
     * @param PromoQuoteIndex $promoQuoteIndex
     * @param PromoQuoteEdit $promoQuoteEdit
     * @param SalesRule $salesRule
     * @return void
     */
    public function processAssert(
        PromoQuoteIndex $promoQuoteIndex,
        PromoQuoteEdit $promoQuoteEdit,
        SalesRule $salesRule
    ) {
        $promoQuoteIndex->open();
        $promoQuoteIndex->getPromoQuoteGrid()->searchAndOpen(['name' => $salesRule->getName()]);
        $formData = $promoQuoteEdit->getSalesRuleForm()->getData($salesRule);
        $errors = $this->verifyData($salesRule->getData(), $formData);
        \PHPUnit_Framework_Assert::assertEmpty($errors, $errors);
    }

    /**
     * Returns a string representation of the object.
     *
     * @return string
     */
    public function toString()
    {
        return 'Displayed sales rule data on edit page equals to passed from fixture.';
    }
}


text:
package com.yahoo.sketches.hive.frequencies;

import java.util.Arrays;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator.Mode;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFParameterInfo;
import org.apache.hadoop.hive.ql.udf.generic.SimpleGenericUDAFParameterInfo;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.IntWritable;
import org.testng.Assert;
import org.testng.annotations.Test;

import com.yahoo.memory.Memory;
import com.yahoo.sketches.ArrayOfItemsSerDe;
import com.yahoo.sketches.ArrayOfStringsSerDe;
import com.yahoo.sketches.frequencies.ItemsSketch;

public class DataToStringsSketchUDAFTest {

  static final ArrayOfItemsSerDe<String> serDe = new ArrayOfStringsSerDe();

  static final ObjectInspector stringInspector =
    PrimitiveObjectInspectorFactory.getPrimitiveWritableObjectInspector(PrimitiveCategory.STRING);

  static final ObjectInspector intInspector =
      PrimitiveObjectInspectorFactory.getPrimitiveWritableObjectInspector(PrimitiveCategory.INT);

  static final ObjectInspector binaryInspector =
      PrimitiveObjectInspectorFactory.getPrimitiveWritableObjectInspector(PrimitiveCategory.BINARY);

  @Test(expectedExceptions = UDFArgumentException.class)
  public void getEvaluatorTooFewInspectors() throws Exception {
    ObjectInspector[] inspectors = new ObjectInspector[] { stringInspector };
    GenericUDAFParameterInfo info = new SimpleGenericUDAFParameterInfo(inspectors, false, false, false);
    new DataToStringsSketchUDAF().getEvaluator(info);
  }

  @Test(expectedExceptions = UDFArgumentException.class)
  public void getEvaluatorTooManyInspectors() throws Exception {
    ObjectInspector[] inspectors = new ObjectInspector[] { stringInspector, intInspector, intInspector };
    GenericUDAFParameterInfo info = new SimpleGenericUDAFParameterInfo(inspectors, false, false, false);
    new DataToStringsSketchUDAF().getEvaluator(info);
  }

  static final ObjectInspector structInspector = ObjectInspectorFactory.getStandardStructObjectInspector(
    Arrays.asList("a"),
    Arrays.asList(intInspector)
  );

  @Test(expectedExceptions = UDFArgumentException.class)
  public void getEvaluatorWrongCategoryArg1() throws Exception {
    ObjectInspector[] inspectors = new ObjectInspector[] { structInspector };
    GenericUDAFParameterInfo info = new SimpleGenericUDAFParameterInfo(inspectors, false, false, false);
    new DataToStringsSketchUDAF().getEvaluator(info);
  }

  @Test(expectedExceptions = UDFArgumentException.class)
  public void getEvaluatorWrongCategoryArg2() throws Exception {
    ObjectInspector[] inspectors = new ObjectInspector[] { stringInspector, structInspector };
    GenericUDAFParameterInfo info = new SimpleGenericUDAFParameterInfo(inspectors, false, false, false);
    new DataToStringsSketchUDAF().getEvaluator(info);
  }

  @Test(expectedExceptions = UDFArgumentException.class)
  public void getEvaluatorWrongTypeArg2() throws Exception {
    ObjectInspector[] inspectors = new ObjectInspector[] { stringInspector, stringInspector };
    GenericUDAFParameterInfo info = new SimpleGenericUDAFParameterInfo(inspectors, false, false, false);
    new DataToStringsSketchUDAF().getEvaluator(info);
  }

  @Test
  public void iterateTerminatePartial() throws Exception {
    ObjectInspector[] inspectors = new ObjectInspector[] { stringInspector, intInspector };
    GenericUDAFParameterInfo info = new SimpleGenericUDAFParameterInfo(inspectors, false, false, false);
    try (GenericUDAFEvaluator eval = new DataToStringsSketchUDAF().getEvaluator(info)) {
      ObjectInspector resultInspector = eval.init(Mode.PARTIAL1, inspectors);
      checkResultInspector(resultInspector);

      @SuppressWarnings("unchecked")
      ItemsState<String> state = (ItemsState<String>) eval.getNewAggregationBuffer();
      eval.iterate(state, new Object[] { new org.apache.hadoop.io.Text("a"), new IntWritable(256) });
      eval.iterate(state, new Object[] { new org.apache.hadoop.io.Text("b"), new IntWritable(256) });

      BytesWritable bytes = (BytesWritable) eval.terminatePartial(state);
      ItemsSketch<String> resultSketch = ItemsSketch.getInstance(Memory.wrap(bytes.getBytes()), serDe);
      Assert.assertEquals(resultSketch.getStreamLength(), 2);
      Assert.assertEquals(resultSketch.getNumActiveItems(), 2);
      Assert.assertEquals(resultSketch.getEstimate("a"), 1);
      Assert.assertEquals(resultSketch.getEstimate("b"), 1);
    }
  }

  @Test
  public void mergeTerminateEmptyState() throws Exception {
    ObjectInspector[] inspectors = new ObjectInspector[] { stringInspector, intInspector };
    GenericUDAFParameterInfo info = new SimpleGenericUDAFParameterInfo(inspectors, false, false, false);
    try (GenericUDAFEvaluator eval = new DataToStringsSketchUDAF().getEvaluator(info)) {
      ObjectInspector resultInspector = eval.init(Mode.PARTIAL2, new ObjectInspector[] { binaryInspector });
      checkResultInspector(resultInspector);

      @SuppressWarnings("unchecked")
      ItemsState<String> state = (ItemsState<String>) eval.getNewAggregationBuffer();

      ItemsSketch<String> sketch1 = new ItemsSketch<String>(256);
      sketch1.update("a");
      eval.merge(state, new BytesWritable(sketch1.toByteArray(serDe)));

      ItemsSketch<String> sketch2 = new ItemsSketch<String>(256);
      sketch2.update("b");
      eval.merge(state, new BytesWritable(sketch2.toByteArray(serDe)));

      BytesWritable bytes = (BytesWritable) eval.terminate(state);
      ItemsSketch<String> resultSketch = ItemsSketch.getInstance(Memory.wrap(bytes.getBytes()), serDe);
      Assert.assertEquals(resultSketch.getStreamLength(), 2);
      Assert.assertEquals(resultSketch.getNumActiveItems(), 2);
      Assert.assertEquals(resultSketch.getEstimate("a"), 1);
      Assert.assertEquals(resultSketch.getEstimate("b"), 1);
    }
  }

  @Test
  public void mergeTerminate() throws Exception {
    ObjectInspector[] inspectors = new ObjectInspector[] { stringInspector, intInspector };
    GenericUDAFParameterInfo info = new SimpleGenericUDAFParameterInfo(inspectors, false, false, false);
    try (GenericUDAFEvaluator eval = new DataToStringsSketchUDAF().getEvaluator(info)) {
      ObjectInspector resultInspector = eval.init(Mode.PARTIAL2, new ObjectInspector[] { binaryInspector });
      checkResultInspector(resultInspector);

      @SuppressWarnings("unchecked")
      ItemsState<String> state = (ItemsState<String>) eval.getNewAggregationBuffer();
      state.init(256);
      state.update("a");

      ItemsSketch<String> sketch = new ItemsSketch<String>(256);
      sketch.update("b");

      eval.merge(state, new BytesWritable(sketch.toByteArray(serDe)));

      BytesWritable bytes = (BytesWritable) eval.terminate(state);
      ItemsSketch<String> resultSketch = ItemsSketch.getInstance(Memory.wrap(bytes.getBytes()), serDe);
      Assert.assertEquals(resultSketch.getStreamLength(), 2);
      Assert.assertEquals(resultSketch.getNumActiveItems(), 2);
      Assert.assertEquals(resultSketch.getEstimate("a"), 1);
      Assert.assertEquals(resultSketch.getEstimate("b"), 1);
    }
  }

  private static void checkResultInspector(ObjectInspector resultInspector) {
    Assert.assertNotNull(resultInspector);
    Assert.assertEquals(resultInspector.getCategory(), ObjectInspector.Category.PRIMITIVE);
    Assert.assertEquals(
      ((PrimitiveObjectInspector) resultInspector).getPrimitiveCategory(),
      PrimitiveObjectInspector.PrimitiveCategory.BINARY
    );
  }

}