handleJoint is called for every joint younger than mci
193998
function readJointsSinceMci(mci, handleJoint, onDone){
	db.query(
		"SELECT units.unit FROM units LEFT JOIN archived_joints USING(unit) \n\
		WHERE (is_stable=0 AND main_chain_index>=? OR main_chain_index IS NULL OR is_free=1) AND archived_joints.unit IS NULL \n\
		ORDER BY +level", 
		[mci], 
		function(rows){
			async.eachSeries(
				rows, 
				function(row, cb){
					storage.readJoint(db, row.unit, {
						ifNotFound: function(){
						//	throw Error("unit "+row.unit+" not found");
							breadcrumbs.add("unit "+row.unit+" not found");
							cb();
						},
						ifFound: function(objJoint){
							handleJoint(objJoint);
							cb();
						}
					});
				},
				onDone
			);
		}
	);
}
705786
def execute_cross_join(op, left, right, **kwargs):
    
    # generate a unique name for the temporary join key
    key = "cross_join_{}".format(ibis.util.guid())
    join_key = {key: True}
    new_left = left.assign(**join_key)
    new_right = right.assign(**join_key)

    # inner/outer doesn't matter because every row matches every other row
    result = pd.merge(
        new_left,
        new_right,
        how='inner',
        on=key,
        copy=False,
        suffixes=constants.JOIN_SUFFIXES,
    )

    # remove the generated key
    del result[key]

    return result
421418
private void involveMCInTran(MCWrapper mcWrapper, UOWCoordinator uowCoord, com.ibm.ejs.j2c.ConnectionManager inUseCM) throws ResourceException {

        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isEntryEnabled()) {
            Tr.entry(this, tc, "involveMCInTran", inUseCM.toString());
        }

        if (!mcWrapper.involvedInTransaction()) { // this whole first part of the if statement is new.

            // Not involved in transaction, need to get involved in transaction.
            // Set a Reference to this CM instance into the McWrapper
            mcWrapper.setConnectionManager(inUseCM);

            /*
             * If isEnlistmentDisabled is true, log a message and return.
             */
            if (mcWrapper.isEnlistmentDisabled()) {

                if (isTraceOn && tc.isDebugEnabled()) {
                    Tr.debug(this, tc, "Managed connection isEnlistmentDisabled is true.");
                    Tr.debug(this, tc, "Returning without calling method initializeForUOW.");
                }
                if (isTraceOn && tc.isEntryEnabled()) {
                    Tr.exit(this, tc, "involveMCInTran");
                }

                return;

            }
            mcWrapper.setUOWCoordinator(uowCoord);

            // Do the transactional setup if required.
            initializeForUOW(mcWrapper, false);

        }

        if (isTraceOn && tc.isEntryEnabled()) {
            Tr.exit(this, tc, "involveMCInTran");
        }

    }
951204
function handleDefinition(mycro, options, cb) {
        var self = this;
        asyncjs.auto({
            // validate arguments
            validate: function validateOptions(fn) {
                var valid = joi.object({
                    currentPath: joi.string().allow('').default(''),
                    defaultOptions: joi.object().default({}),
                    defaultPolicies: joi.array().items(joi.string(), joi.func()).default([]),
                    definition: joi.alternatives().try(joi.object(), joi.string()).required(),
                    isRegex: joi.boolean().default(false),
                    //path: joi.string().default(''),
                    regexPathDefinition: joi.string().allow('').default(''),
                    routes: joi.object().default({}),
                    version: joi.string().regex(/^v?\d+\.\d+\.\d+$/).default('1.0.0')
                }).required();

                joi.validate(options, valid, {}, function(err, validated) {
                    if (err) {
                        return fn(err);
                    }
                    options = validated;
                    fn();
                });
            },

            // process definition
            definition: ['validate', function processDefinition(fn) {
                var definition = options.definition;
                // handle string definition by looking up inclusion in available routes
                if (_.isString(definition)) {
                    definition = options.routes[options.definition];
                    if (_.isFunction(definition)) {
                        definition = definition(mycro);
                    }
                    return fn(null, definition);
                }

                // augment route definition with any specified includes
                if (definition.routes && _.isString(definition.routes)) {
                    var routesToInclude = options.routes[definition.routes];
                    if (_.isFunction(routesToInclude)) {
                        routesToInclude = routesToInclude(mycro);
                    }
                    _.defaults(definition, routesToInclude);
                }
                fn(null, options.definition);
            }],

            // process definition keys
            options: ['definition', function processDefnition(fn, r) {
                self.handleOptions(options, r.definition, fn);
            }],

            // bind routes defined at the current level
            routes: ['options', function bindRoutes(fn, r) {
                asyncjs.each(['del', 'get', 'head', 'patch', 'post', 'put'], function(verb, _fn) {
                    if (r.definition[verb]) {
                        var routeOptions = _.cloneDeep(options);
                        return self.handleRoute(mycro, verb, options.currentPath, r.definition[verb], routeOptions, _fn);
                    }
                    _fn();
                }, fn);
            }],

            // handle subpaths
            subpaths: ['routes', function bindSubPaths(fn, r) {
                asyncjs.each(_.keys(r.definition), function(key, _fn) {
                    if (!/^\//g.test(key)) {
                        return _fn();
                    }
                    var subOptions = _.cloneDeep(options);
                    subOptions.currentPath = key;
                    subOptions.definition = r.definition[key];
                    self.handleDefinition(mycro, subOptions, _fn);
                }, fn);
            }],

            // handle different versions
            versions: ['subpaths', function bindVersions(fn, r) {
                asyncjs.each(_.keys(r.definition), function(key, _fn) {
                    if (!/^v?\d+\.\d+\.\d+/g.test(key)) {
                        return _fn();
                    }
                    var subOptions = _.cloneDeep(options);
                    subOptions.version = key.replace(/v/g, '');
                    subOptions.definition = r.definition[key];
                    self.handleDefinition(mycro, subOptions, _fn);
                }, fn);
            }]
        }, cb);
    }
270156
function processPowWitnessProof( arrUnstableMcJoints, bFromCurrent, handleResult )
{
	//	unstable MC joints
	let arrParentUnits			= null;
	let arrFoundTrustMEAuthors		= [];
	let arrLastMajorityWitnessedBallUnits	= [];
	let assocLastBallByLastBallUnit		= {};
	let arrTrustMEJoints			= [];

	//
	//	arrUnstableMcJoints were collected by SQL below:
	//	SELECT unit, pow_type FROM units WHERE is_on_main_chain=1 AND is_stable=0 ORDER BY main_chain_index DESC
	//
	for ( let i = 0; i < arrUnstableMcJoints.length; i ++ )
	{
		let objJoint	= arrUnstableMcJoints[ i ];
		let objUnit	= objJoint.unit;

		if ( objJoint.ball )
		{
			return handleResult( "unstable mc but has ball" );
		}
		if ( ! _validation.hasValidHashes( objJoint ) )
		{
			return handleResult( "invalid hash" );
		}
		if ( arrParentUnits && arrParentUnits.indexOf( objUnit.unit ) === -1 )
		{
			return handleResult( "not in parents" );
		}

		//	...
		let bAddedJoint = false;
		if ( _constants.POW_TYPE_TRUSTME === objUnit.pow_type )
		{
			for ( let j = 0; j < objUnit.authors.length; j++ )
			{
				let address = objUnit.authors[ j ].address;

				if ( -1 === arrFoundTrustMEAuthors.indexOf( address ) )
				{
					arrFoundTrustMEAuthors.push( address );
				}

				//
				//	TODO
				//	@20180902 17:53 by XING
				//	move line "bAddedJoint = true;" into braces above
				//
				if ( ! bAddedJoint )
				{
					arrTrustMEJoints.push( objJoint );
				}
				bAddedJoint = true;
			}
		}

		arrParentUnits = objUnit.parent_units;
		if ( objUnit.last_ball_unit && arrFoundTrustMEAuthors.length >= _constants.MAJORITY_OF_WITNESSES )
		{
			arrLastMajorityWitnessedBallUnits.push( objUnit.last_ball_unit );
			assocLastBallByLastBallUnit[ objUnit.last_ball_unit ] = objUnit.last_ball;
		}
	}
	return handleResult(null, null, assocLastBallByLastBallUnit);
	//	end of forEach arrUnstableMcJoints


	if ( arrFoundTrustMEAuthors.length < _constants.MAJORITY_OF_WITNESSES )
	{
		return handleResult( "not enough witnesses" );
	}
	if ( 0 === arrLastMajorityWitnessedBallUnits.length )
	{
		throw Error( "processWitnessProof: no last ball units" );
	}


	let assocDefinitions		= {};	//	keyed by definition chash
	let assocDefinitionChashes	= {};	//	keyed by address

	//
	//	checks signatures and updates definitions
	//
	function validateUnit( objUnit, bRequireDefinitionOrChange, cb2 )
	{
		let bFound = false;
		_async.eachSeries
		(
			objUnit.authors,
			function( author, cb3 )
			{
				let sAddress = author.address;
				if ( -1 === arrFoundTrustMEAuthors.indexOf( sAddress ) )
				{
					//	not a witness - skip it
					return cb3();
				}

				//
				//	the latest definition chash of the witness
				//
				let definition_chash = assocDefinitionChashes[ sAddress ];
				if ( ! definition_chash )
				{
					throw Error( "definition chash not known for address " + sAddress );
				}
				if ( author.definition )
				{
					//
					//	do transaction for the first time
					//
					if ( _object_hash.getChash160( author.definition ) !== definition_chash )
					{
						return cb3( "definition doesn't hash to the expected value" );
					}

					assocDefinitions[ definition_chash ] = author.definition;
					bFound = true;
				}


				function handleAuthor()
				{
					//	FIX
					_validation.validateAuthorSignaturesWithoutReferences
					(
						author,
						objUnit,
						assocDefinitions[ definition_chash ],	//	definition JSON
						function( err )
						{
							if ( err )
							{
								return cb3( err );
							}

							//
							//	okay, definition is valid
							//
							for ( let i = 0; i < objUnit.messages.length; i++ )
							{
								let message = objUnit.messages[ i ];
								if ( 'address_definition_change' === message.app
									&& ( message.payload.address === sAddress ||
										1 === objUnit.authors.length && objUnit.authors[ 0 ].address === sAddress ) )
								{
									assocDefinitionChashes[ sAddress ] = message.payload.definition_chash;
									bFound = true;
								}
							}

							//	...
							cb3();
						}
					);
				}

				if ( assocDefinitions[ definition_chash ] )
				{
					return handleAuthor();
				}

				//
				//	only an address with money
				//	there is no transaction any more
				//
				_storage.readDefinition( _db, definition_chash,
				{
					ifFound : function( arrDefinition )
					{
						assocDefinitions[ definition_chash ] = arrDefinition;
						handleAuthor();
					},
					ifDefinitionNotFound : function( sDefinitionCHash )
					{
						throw Error( "definition " + definition_chash + " not found, address " + sAddress );
					}
				});
			},
			function( err )
			{
				if ( err )
				{
					return cb2( err );
				}

				if ( bRequireDefinitionOrChange && ! bFound )
				{
					//
					//	bRequireDefinitionOrChange always be false
					//	so, you will never arrive here so far
					//
					return cb2( "neither definition nor change" );
				}

				//	...
				cb2();
			}

		); // each authors
	}


	//
	//	...
	//
	let unlock = null;
	_async.series
	([
		function( cb )
		{
			//	read latest known definitions of witness addresses
			if ( ! bFromCurrent )
			{
				for ( let i = 0; i < arrFoundTrustMEAuthors.length; i ++ )
				{
					let address = arrFoundTrustMEAuthors[ i ];
					assocDefinitionChashes[ address ] = address;
				}
				return cb();
			}

			//
			//	try to obtain definitions
			//
			_async.eachSeries
			(
				arrFoundTrustMEAuthors,
				function( sAddress, cb2 )
				{
					_storage.readDefinitionByAddress( _db, sAddress, null,
					{
						ifFound : function( arrDefinition )
						{
							let definition_chash = _object_hash.getChash160( arrDefinition );
							assocDefinitions[ definition_chash ]	= arrDefinition;
							assocDefinitionChashes[ sAddress ]	= definition_chash;
							cb2();
						},
						ifDefinitionNotFound : function( definition_chash )
						{
							assocDefinitionChashes[ sAddress ]	= definition_chash;
							cb2();
						}
					});
				},
				cb
			);
		},
		function( cb )
		{
			//
			//	check signatures of unstable witness joints
			//
			_async.eachSeries
			(
				arrTrustMEJoints.reverse(),	//	they came in reverse chronological order, reverse() reverses in place
				function( objJoint, pfnEachNext )
				{
					validateUnit( objJoint.unit, false, pfnEachNext );
				},
				cb
			);
		},
	], function( err )
	{
		err ? handleResult( err ) : handleResult( null, arrLastMajorityWitnessedBallUnits, assocLastBallByLastBallUnit );
	});
}
1020365
@Override
    public void associateConnection( Object connection ) throws ResourceException {
        JcrSessionHandle handle = (JcrSessionHandle)connection;
        if (handle.getManagedConnection() != this) {
            handle.getManagedConnection().removeHandle(handle);
            handle.setManagedConnection(this);
            addHandle(handle);
        }
    }
283648
def simxSetJointPosition(clientID, jointHandle, position, operationMode):
    '''
    
    '''

    return c_SetJointPosition(clientID, jointHandle, position, operationMode)
1310705
private void handleJoinEvent(Node node) {
    GossipMember member = new GossipMember(MemberId.from(node.id().id()), node.address());
    if (!members.containsKey(member.id())) {
      sendHeartbeat(member);
    }
  }
976944
function parseMiddleware(ctx, next) {
      try {
        ctx.event = JSON.parse(ctx.content.toString());
        next();
      } catch (e) {
        throw e;
      }
    }
965455
function validateProposalJoint(objJoint, callbacks){
	var objUnit = objJoint.unit;
	if (typeof objUnit !== "object" || objUnit === null)
		return callbacks.ifInvalid("no unit object");
	
	console.log("\nvalidating joint identified by unit "+objJoint.unit.unit);
	
	if (!isStringOfLength(objUnit.unit, constants.HASH_LENGTH))
		return callbacks.ifInvalid("wrong unit length");
	
	// UnitError is linked to objUnit.unit, so we need to ensure objUnit.unit is true before we throw any UnitErrors
	if (objectHash.getProposalUnitHash(objUnit) !== objUnit.unit){
		// console.log("888888888888888888888888--Proposal joint : " + JSON.stringify(objJoint));
		return callbacks.ifInvalid("wrong proposal unit hash: "+objectHash.getProposalUnitHash(objUnit)+" != "+objUnit.unit);
	}
	

	if (hasFieldsExcept(objUnit, ["unit", "version", "alt" ,"round_index","pow_type","timestamp", "parent_units", "last_ball", "last_ball_unit", "messages", "hp"]))
		return callbacks.ifInvalid("unknown fields in nonserial unit");
	
	if (objUnit.version !== constants.version)
		return callbacks.ifInvalid("wrong version");
	if (objUnit.alt !== constants.alt)
		return callbacks.ifInvalid("wrong alt");
	if (typeof objUnit.round_index !== "number")
		return callbacks.ifInvalid("no round index");
	if (typeof objUnit.pow_type !== "number")
		return callbacks.ifInvalid("no pow_type type");
	if (typeof objUnit.hp !== "number")
		return callbacks.ifInvalid("no hp type");
	
	// pow_type type should be 2 for trustme 
	if ( objUnit.pow_type !==  constants.POW_TYPE_TRUSTME)
		return callbacks.ifInvalid("invalid unit type");
	// unity round index should be in range of [1,4204800]
	if ( objUnit.round_index < 1 || objUnit.round_index > 4204800)
		return callbacks.ifInvalid("invalid unit round index");
	
	if (!isNonemptyArray(objUnit.messages))
		return callbacks.ifInvalid("missing or empty messages array");
	// only one 'data_feed' message allowed in trust me units.
	if (objUnit.messages.length !== 1) 
		return callbacks.ifInvalid("only one message allowed in proposal unit");
	
	// Joint fields validation   add last_ball_mci for only proposal joint, used for final trustme unit
	if (hasFieldsExcept(objJoint, ["unit", "proposer", "phase", "address","last_ball_mci", "idv","vp","isValid","sig"]))
		return callbacks.ifInvalid("unknown fields in joint unit " + json.stringify(objJoint));
	
	if (typeof objJoint.phase !== "number" || objJoint.phase < 0 )
		return callbacks.ifInvalid("joint phase invalid");
	if(objJoint.proposer && objJoint.proposer.length !== 1)
		return callbacks.ifInvalid("multiple proposers are not allowed");
		
	var conn = null;
	var objValidationState = { };
	async.series(
		[
			function(cb){
				db.takeConnectionFromPool(function(new_conn){
					conn = new_conn;
					conn.query("BEGIN", function(){cb();});
				});
			},
			function(cb){
				//validate roundIndex and hp (mci) to see if I am sync with proposer mci
				//if not, return -1 to let caller knows .
				round.getCurrentRoundIndex(conn, function(curRoundIndex){
					if(objUnit.round_index < curRoundIndex)
						return cb("proposer's round_index is too old, curRoundIndex: " + curRoundIndex + " proposer round_index: " +objUnit.round_index );
					if(objUnit.round_index > curRoundIndex)
						return cb({error_code: "unresolved_dependency", errorMessage:"propose round_index is ahead of me , curRoundIndex: " + curRoundIndex + " proposer round_index: " +objUnit.round_index });
					storage.getMaxMci(conn,function(curMCI){
						if(objUnit.hp < curMCI + 1) // recieve old proposal
							return cb("proposal hp is old, will discard it");
						if(objUnit.hp > curMCI + 1 ) // propose mci is ahead of me 
							return cb({error_code: "unresolved_dependency", errorMessage:"propose mci is ahead of me, will handle it once come up with it " });
						cb();
					});
				});
			},
			function(cb){
				validateParents(conn, objJoint, objValidationState, cb);
			},
			// function(cb){
			// 	profiler.stop('validation-parents');
			// 	profiler.start();
			// 	!objJoint.skiplist_units
			// 		? cb()
			// 		: validateSkiplist(conn, objJoint.skiplist_units, cb);
			// },
			function(cb){
				// validate proposer ID
				byzantine.getCoordinators(conn, objUnit.hp, objJoint.phase, function(err, proposer, round_index, witnesses){	
					if(err)
						return cb("error occured when getCoordinators err:" + err);		
					if(proposer !== objJoint.proposer[0].address)
						return cb("proposer incorrect,Expected: "+ proposer +" Actual :" + objJoint.proposer[0].address);
					if(round_index !== objUnit.round_index)
						return cb("proposer round_index incorrect ,Expected: "+ round_index +" Actual :" + objUnit.round_index);
					objValidationState.unit_hash_to_sign = objectHash.getProposalHashToSign(objUnit);
					//validate proposer signature
					validateProposer(conn, objJoint.proposer[0], objUnit, objValidationState, cb);
				});
			},
			function(cb){ // check timestamp is near to mine in data feed message 
			 	validateDataFeedMessage(conn, objUnit.messages[0], objUnit, objValidationState, cb);
			},
		], 
		function(err){
			if(!err){
				conn.query("COMMIT", function(){
					conn.release();
					callbacks.ifOk();
				});
			}
			else{
			//Error occured here
			conn.query("ROLLBACK", function(){
				conn.release();
				if (typeof err === "object"){
					if (err.error_code === "unresolved_dependency"){
						console.log(err.errorMessage);
						callbacks.ifNeedWaiting(err.errorMessage);
					}
					else
						throw Error("unknown error code");
				}
				else
					callbacks.ifInvalid(err);
				});
			}
			
		}
	); // async.series
	
}
130782
def scanJoiner(self, xEUI='*', strPSKd='threadjpaketest'):
        
        print '%s call scanJoiner' % self.port
        if not isinstance(xEUI, str):
            eui64 = self.__convertLongToString(xEUI)

            # prepend 0 at the beginning
            if len(eui64) < 16:
                eui64 = eui64.zfill(16)
                print eui64
        else:
            eui64 = xEUI

        # long timeout value to avoid automatic joiner removal (in seconds)
        timeout = 500

        cmd = WPANCTL_CMD + 'commissioner joiner-add %s %s %s' % (eui64, str(timeout), strPSKd)
        print cmd
        if not self.isActiveCommissioner:
            self.startCollapsedCommissioner()
        if self.__sendCommand(cmd)[0] != 'Fail':
            return True
        else:
            return False
791243
@SuppressWarnings("unchecked")
    private void insertPair(ReflectedHandle<K, V> handle1, ReflectedHandle<K, V> handle2) {
        int c;
        if (comparator == null) {
            c = ((Comparable<? super K>) handle1.key).compareTo(handle2.key);
        } else {
            c = comparator.compare(handle1.key, handle2.key);
        }

        AddressableHeap.Handle<K, HandleMap<K, V>> innerHandle1;
        AddressableHeap.Handle<K, HandleMap<K, V>> innerHandle2;

        if (c <= 0) {
            innerHandle1 = minHeap.insert(handle1.key);
            handle1.minNotMax = true;
            innerHandle2 = maxHeap.insert(handle2.key);
            handle2.minNotMax = false;
        } else {
            innerHandle1 = maxHeap.insert(handle1.key);
            handle1.minNotMax = false;
            innerHandle2 = minHeap.insert(handle2.key);
            handle2.minNotMax = true;
        }
        handle1.inner = innerHandle1;
        handle2.inner = innerHandle2;

        innerHandle1.setValue(new HandleMap<K, V>(handle1, innerHandle2));
        innerHandle2.setValue(new HandleMap<K, V>(handle2, innerHandle1));
    }
719989
function FutureJoin(first) {
        Future.call(this);

        this.first = first;
        this.missing = first instanceof Future && first.state === STATE_LISTEN ? 1 : 0;
    }
928797
function readJointWithBall(conn, unit, handleJoint) {
	readJoint(conn, unit, {
		ifNotFound: function(){
			throw Error("joint not found, unit "+unit);
		},
		ifFound: function(objJoint){
			if (objJoint.ball)
				return handleJoint(objJoint);
			conn.query("SELECT ball FROM balls WHERE unit=?", [unit], function(rows){
				if (rows.length === 1)
					objJoint.ball = rows[0].ball;
				handleJoint(objJoint);
			});
		}
	});
}
554927
private void addJoinInfo(JoinType type, String localColumnName, String joinedColumnName,
			QueryBuilder<?, ?> joinedQueryBuilder, JoinWhereOperation operation) throws SQLException {
		JoinInfo joinInfo = new JoinInfo(type, joinedQueryBuilder, operation);
		if (localColumnName == null) {
			matchJoinedFields(joinInfo, joinedQueryBuilder);
		} else {
			matchJoinedFieldsByName(joinInfo, localColumnName, joinedColumnName, joinedQueryBuilder);
		}
		if (joinList == null) {
			joinList = new ArrayList<JoinInfo>();
		}
		joinList.add(joinInfo);
	}
677989
function Stack (middleware, context) {
  var handle = function (args, next) { next.call(context) }
  middleware.reverse().forEach(function (layer) {
    var child = handle
    handle = function (args, next) {
      layer(args, function () {
        child(args, next)
      })
    }
  })
  return handle
}
1157220
private int doJoin() {
        int s; Thread t; ForkJoinWorkerThread wt; ForkJoinPool.WorkQueue w;
        if ((s = status) >= 0) {
            if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)) {
                if (!(w = (wt = (ForkJoinWorkerThread)t).workQueue).
                    tryUnpush(this) || (s = doExec()) >= 0)
                    s = wt.pool.awaitJoin(w, this);
            }
            else
                s = externalAwaitDone();
        }
        return s;
    }