/////////////////////////////////////// StateMachine callbacks /////////////////////////////////////
168026
@Override public byte[] apply(byte[] data, int offset, int length) throws Exception {
        ByteArrayDataInputStream in=new ByteArrayDataInputStream(data, offset, length);
        byte command=in.readByte();
        switch(command) {
            case PUT:
                K key=Util.objectFromStream(in);
                V val=Util.objectFromStream(in);
                V old_val=map.put(key, val);
                notifyPut(key, val, old_val);
                return old_val == null? null : Util.objectToByteBuffer(old_val);
            case REMOVE:
                key=Util.objectFromStream(in);
                old_val=map.remove(key);
                notifyRemove(key, old_val);
                return old_val == null? null : Util.objectToByteBuffer(old_val);
            default:
                throw new IllegalArgumentException("command " + command + " is unknown");
        }
    }
96360
function readyStateChangeHandler(readyState){
    var xhr = this.xhr;

    // reset send delay timer
    this.sendDelayTimer_ = clearTimeout(this.sendDelayTimer_);

    if (!xhr)
      return;

    if (typeof readyState != 'number')
      readyState = xhr.readyState;

    // BUGFIX: IE & Gecko fire OPEN readyState twice
    if (readyState == this.prevReadyState_)
      return;

    this.prevReadyState_ = readyState;

    /** @cut */ if (this.debug)
    /** @cut */   basis.dev.log('State: (' + readyState + ') ' + ['UNSENT', 'OPENED', 'HEADERS_RECEIVED', 'LOADING', 'DONE'][readyState]);

    // dispatch self event
    this.emit_readyStateChanged(readyState);

    if (readyState == STATE_DONE)
    {
      // clean event handler
      xhr.onreadystatechange = basis.fn.$undef;
      // xhr.onabort = basis.fn.$undef;

      // delay process response since abort event fires after readyStateChanged
      this.clearTimeout();
      this.timer_ = setTimeout(processResponse.bind(this), 10);

      return;
    }

    // set new state
    this.setState(STATE.PROCESSING);
  }
108918
func (f *FSM) afterEventCallbacks(e *Event) {
	if fn, ok := f.callbacks[cKey{e.Event, callbackAfterEvent}]; ok {
		fn(e)
	}
	if fn, ok := f.callbacks[cKey{"", callbackAfterEvent}]; ok {
		fn(e)
	}
}
24804
func (s *StepFunctionsAction) SetStateMachineName(v string) *StepFunctionsAction {
	s.StateMachineName = &v
	return s
}
546335
@Override
    public boolean init() {

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "App channel called init: " + this);
        }
        int cbState = CALLBACK_STATE_IDLE;
        int myState = READ_STATE_IDLE;
        // grab the read-ahead states in a sync block to avoid timing windows
        // with the callback kicking in at the same time
        if (isReadAheadEnabled()) {
            getReadCancel().init();
            if (!super.cancelOutstandingRead()) {
                // failed to start (not supported at TCP layer perhaps)
                getReadCancel().clear();
                return false;
            } else if (!getReadCancel().block(2000L)) {
                // failed to succeed on the cancel attempt
                return false;
            }
            synchronized (this.stateSyncObject) {
                cbState = getCallbackState();
                myState = getReadState();
                setReadState(READ_STATE_TIME_RESET);
            }
        }
        if (CALLBACK_STATE_IDLE == cbState) {
            // no read ahead involved here
            return true;
        }
        if (CALLBACK_STATE_PENDING != cbState) {
            // read-ahead callback has already been triggered, this must fail
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Callback state indicates error: " + cbState);
            }
            return false;
        }
        if (READ_STATE_IDLE != myState) {
            // read-for-response thread state isn't valid for this method
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Read for response state indicates error: " + myState);
            }
            return false;
        }
        return true;
    }
232533
func NewStateMachine(p *Plugin) *StateMachine {
	sm := StateMachine{
		state:  0,
		plugin: p,
	}
	sm.states = map[string]int{}
	sm.resetFn = func(*Msg) {}
	return &sm
}
1211286
func (s *State) Callbacks() []Callback {
	s.mu.RLock()
	defer s.mu.RUnlock()

	return append([]Callback{}, s.callbacks...)
}
493209
function (state, action) {
    if (state) {
      let initialValue = state.value || {}
      if (state.baseModel) {
        initialValue = recursiveClean(initialValue, state.baseModel)
        state.baseModel = getDereferencedModelSchema(state.baseModel)
        state.model = evaluateConditions(state.baseModel, initialValue, undefined, initialValue)
        // leave this undefined to force consumers to go through the proper CHANGE_VALUE channel
        // for value changes
        state.value = undefined
      }
      if (state.view && !state.baseView) {
        state.baseView = state.view
      }
      if (state.baseView) {
        state.view = evaluateViewConditions(state.baseView, initialValue)
      }
    }

    const newState = initialState(state || {})
    newState.lastAction = 'INIT'
    newState.value = immutable(newState.value)
    return newState
  }
672725
function WorkflowProcessStepsController($scope, $state, wfmService, $timeout, $stateParams) {
  var self = this;
  var workorderId = $stateParams.workorderId;

  function updateWorkflowState(workorder) {
    //If the workflow is complete, then we can switch to the summary view.
    if (wfmService.isCompleted(workorder)) {
      return $state.go('app.workflowProcess.complete', {
        workorderId: workorder.id
      });
    }

    if (!wfmService.isOnStep(workorder)) {
      return $state.go('app.workflowProcess.begin', {
        workorderId: workorder.id
      });
    }

    $timeout(function() {
      self.workorder = workorder;
      self.workflow = workorder.workflow;
      self.result = workorder.results;
      self.stepIndex = wfmService.getCurrentStepIdx(workorder);
      self.stepCurrent = wfmService.getCurrentStep(workorder);
    });
  }

  self.back = function() {
    wfmService.previousStep(workorderId)
      .then(updateWorkflowState)
      .catch(console.error);
  };

  self.triggerCompleteStep = function(submission) {
    wfmService.completeStep(workorderId, submission)
      .then(updateWorkflowState)
      .catch(console.error);
  };

  self.triggerBackStep = function() {
    self.back();
  };

  wfmService.readWorkOrder(workorderId).then(updateWorkflowState);
}
1159692
function (callback) {
    var APIController = require('./controllers/api'),
      DefaultController = require('./controllers/index'),
      PackController = require('./controllers/pack'),
      CardController = require('./controllers/card'),
      WebHookController = require('./controllers/webhook'),
      ProxyController = require('./controllers/proxy'),
      JsonParser = BodyParser.json({strict: false});
    
    // Disable caching middleware.  
    var nocache = function (req, res, next) {
      res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
      res.header('Expires', '-1');
      res.header('Pragma', 'no-cache');
      next();
    };
    
    // Setup routes late to give implementers routes higher priority and allow middleware as well.
    App.get('/api/count', nocache, APIController.count);
    App.get('/api/cards', nocache, APIController.cards);
    App.get('/api/card', nocache, APIController.card);
    
    App.post('/api/card/state/save', APIController.saveState);
    App.post('/api/card/state/clear', APIController.clearState);
    App.post('/api/card/analytics', APIController.recordAnalyticEvents);

    // Proxy
    App.post('/proxy/:pack/:card', ProxyController.post);

    // Web Hooks
    App.post('/webhook/:pack/:card', WebHookController.process);

    // Card Routes
    App.post('/:pack/:card', JsonParser, CardController.post);
    App.get('/:pack/:card', CardController.get);
    
    App.get('/:pack', PackController);
    App.get('/', DefaultController);

    var exit = function () {
      HashDo.db.disconnect(function () {
        process.exit(0);
      });
    };
    
    // Gracefully disconnect from the database on expected exit.
    process.on('SIGINT', exit);
    process.on('SIGTERM', exit);
    
    // Global error handler (always exit for programmatic errors).
    process.on('uncaughtException', function (err) {
      console.error('FATAL: ', err.message);
      console.error(err.stack);
      process.exit(1);
    });
    
    // Connect to the database and start server on successful connection.
    HashDo.db.connect(function (err) {
      if (err) {
        console.error('FATAL: Could not connect to database.', err);
        process.exit(1);
      }
      else {
        console.log('WEB: Starting web server on port %d...', process.env.PORT);
        
        App.listen(process.env.PORT, function () {
          console.log();
          console.log('Let\'s #Do');
          
          callback && callback();
        });
      }
    });
  }
188102
function (params, state, cb) {
                  state = state || {};

                  if (Card.getCardData) {
                    Card.getCardData(params, state, function (err, viewModel, clientLocals) {
                      cb(err, params, state, viewModel, clientLocals);
                    });
                  }
                  else {
                    cb(null, params, state, null, null);
                  }
                }
557258
function(options) {
        this._transitions = {}
        this._states = {}
        options = options || {}
        this._bindStates()
        this._bindTransitions()
        if (options.debugStateMachine === true)
          StateMachine.DebugView.register(this)
        this.bind('all', this._onMachineEvent, this)
        this.currentState = INIT_STATE
        this.startStateMachine = function() {
          throw new Error('startStateMachine has been called twice!')
        }
      }
5651
function shouldCallLifecycleInitHook(view, initState, index) {
    if ((view.state & 1792 /* InitState_Mask */) === initState && view.initIndex <= index) {
        view.initIndex = index + 1;
        return true;
    }
    return false;
}
250643
private function createStateMachine($stateMachineName)
    {
        $stateMachine = new StateMachine($stateMachineName);
        $stateMachine->addState(new InitialState());
        $stateMachine->addState(new FinalState());
        $stateMachine->addState(new State(self::$STATE_START));
        $stateMachine->addTransition(
            $stateMachine->getState(StateInterface::STATE_INITIAL),
            new TransitionEvent(EventInterface::EVENT_START),
            $stateMachine->getState(self::$STATE_START),
            null,
            null
        );

        return $stateMachine;
    }
654141
function(state) {
    if (state == self.LOADING || self.readyState !== state) {
      self.readyState = state;

      if (settings.async || self.readyState < self.OPENED || self.readyState === self.DONE) {
        self.dispatchEvent("readystatechange");
      }

      if (self.readyState === self.DONE && !errorFlag) {
        self.dispatchEvent("load");
        // @TODO figure out InspectorInstrumentation::didLoadXHR(cookie)
        self.dispatchEvent("loadend");
      }
    }
  }
951232
function () {
            var currState = inputStateObj || new TextareaState(panels);

            if (!currState) {
                return false;
            }
            if (mode == "moving") {
                if (!lastState) {
                    lastState = currState;
                }
                return;
            }
            if (lastState) {
                if (undoStack[stackPtr - 1].text != lastState.text) {
                    undoStack[stackPtr++] = lastState;
                }
                lastState = null;
            }
            undoStack[stackPtr++] = currState;
            undoStack[stackPtr + 1] = null;
            if (callback) {
                callback();
            }
        }
243516
func (sm *StateMachine) StateMachineNamedDecorator(stepFunctionResourceName string) sparta.ServiceDecoratorHookFunc {
	return func(context map[string]interface{},
		serviceName string,
		template *gocf.Template,
		S3Bucket string,
		S3Key string,
		buildID string,
		awsSession *session.Session,
		noop bool,
		logger *logrus.Logger) error {

		machineErrors := sm.validate()
		if len(machineErrors) != 0 {
			errorText := make([]string, len(machineErrors))
			for index := range machineErrors {
				errorText[index] = machineErrors[index].Error()
			}
			return errors.Errorf("Invalid state machine. Errors: %s",
				strings.Join(errorText, ", "))
		}

		lambdaFunctionResourceNames := []string{}
		for _, eachState := range sm.uniqueStates {
			taskState, taskStateOk := eachState.(*LambdaTaskState)
			if taskStateOk {
				lambdaFunctionResourceNames = append(lambdaFunctionResourceNames,
					taskState.lambdaLogicalResourceName)
			}
		}

		// Assume policy document
		regionalPrincipal := gocf.Join(".",
			gocf.String("states"),
			gocf.Ref("AWS::Region"),
			gocf.String("amazonaws.com"))
		var AssumePolicyDocument = sparta.ArbitraryJSONObject{
			"Version": "2012-10-17",
			"Statement": []sparta.ArbitraryJSONObject{
				{
					"Effect": "Allow",
					"Principal": sparta.ArbitraryJSONObject{
						"Service": regionalPrincipal,
					},
					"Action": []string{"sts:AssumeRole"},
				},
			},
		}
		var iamRoleResourceName string
		if len(lambdaFunctionResourceNames) != 0 {
			statesIAMRole := &gocf.IAMRole{
				AssumeRolePolicyDocument: AssumePolicyDocument,
			}
			statements := make([]spartaIAM.PolicyStatement, 0)
			for _, eachLambdaName := range lambdaFunctionResourceNames {
				statements = append(statements,
					spartaIAM.PolicyStatement{
						Effect: "Allow",
						Action: []string{
							"lambda:InvokeFunction",
						},
						Resource: gocf.GetAtt(eachLambdaName, "Arn").String(),
					},
				)
			}
			iamPolicies := gocf.IAMRolePolicyList{}
			iamPolicies = append(iamPolicies, gocf.IAMRolePolicy{
				PolicyDocument: sparta.ArbitraryJSONObject{
					"Version":   "2012-10-17",
					"Statement": statements,
				},
				PolicyName: gocf.String("StatesExecutionPolicy"),
			})
			statesIAMRole.Policies = &iamPolicies
			iamRoleResourceName = sparta.CloudFormationResourceName("StatesIAMRole",
				"StatesIAMRole")
			template.AddResource(iamRoleResourceName, statesIAMRole)
		}

		// Sweet - serialize it without indentation so that the
		// ConvertToTemplateExpression can actually parse the inline `Ref` objects
		jsonBytes, jsonBytesErr := json.Marshal(sm)
		if jsonBytesErr != nil {
			return errors.Errorf("Failed to marshal: %s", jsonBytesErr.Error())
		}
		logger.WithFields(logrus.Fields{
			"StateMachine": string(jsonBytes),
		}).Debug("State machine definition")

		// Super, now parse this into an Fn::Join representation
		// so that we can get inline expansion of the AWS pseudo params
		smReader := bytes.NewReader(jsonBytes)
		templateExpr, templateExprErr := spartaCF.ConvertToInlineJSONTemplateExpression(smReader, nil)
		if nil != templateExprErr {
			return errors.Errorf("Failed to parser: %s", templateExprErr.Error())
		}

		// Awsome - add an AWS::StepFunction to the template with this info and roll with it...
		stepFunctionResource := &gocf.StepFunctionsStateMachine{
			StateMachineName: gocf.String(sm.name),
			DefinitionString: templateExpr,
		}
		if iamRoleResourceName != "" {
			stepFunctionResource.RoleArn = gocf.GetAtt(iamRoleResourceName, "Arn").String()
		} else if sm.roleArn != nil {
			stepFunctionResource.RoleArn = sm.roleArn.String()
		}
		template.AddResource(stepFunctionResourceName, stepFunctionResource)
		return nil
	}
}