Checks the internal consistency of the conversation object (temporary solution)
178350
void checkInternalConsistency() throws IllegalStateException {
		if (encryptionKey == null) {
			throw new IllegalStateException("Missing encryption key");
		}

		switch (state) {
			case LOGGED_IN:
				if (StringUtils.isNullOrEmpty(userId)) {
					throw new IllegalStateException("Missing user id");
				}
				break;
			case LOGGED_OUT:
				throw new IllegalStateException("Invalid conversation state: " + state);
			default:
				break;
		}
	}
1253206
def _match_dialog(self, query, dialogues=None):
        
        if dialogues is None:
            dialogues = self._dialogues

        # Try to match in the queries
        if query in dialogues:
            response = dialogues[query]
            logger.debug('Found response in queries: %s' % repr(response))

            return response
806853
function(messageContent, threadId) {
                /**
                 * + forwardInfo                  {object : forwardInfoVO}
                 *   - participant                {object : ParticipantVO}
                 *   - conversation               {object : ConversationSummary}
                 */

                var forwardInfo = {
                    participant: undefined,
                    conversation: undefined
                };

                if (messageContent.conversation) {
                    forwardInfo.conversation = formatDataToMakeConversation(messageContent.conversation);
                }

                if (messageContent.participant) {
                    forwardInfo.participant = formatDataToMakeParticipant(messageContent.participant, threadId);
                }

                return forwardInfo;
            }
1263970
def verify(self, otp, for_time=None, valid_window=0):
        
        if for_time is None:
            for_time = datetime.datetime.now()

        if valid_window:
            for i in range(-valid_window, valid_window + 1):
                if utils.strings_equal(str(otp), str(self.at(for_time, i))):
                    return True
            return False

        return utils.strings_equal(str(otp), str(self.at(for_time)))
1249942
def verify_consistency(self, expected_leaf_count) -> bool:
        
        if expected_leaf_count != self.leafCount:
            raise ConsistencyVerificationFailed()
        if self.get_expected_node_count(self.leafCount) != self.nodeCount:
            raise ConsistencyVerificationFailed()
        return True
796483
function(conversationId, properties, callback) {
      conversationId = utils.toUUID(conversationId);
      if (!conversationId) return callback(new Error(utils.i18n.conversations.id));
      utils.debug('Conversation deleteMetadataProperties: ' + conversationId);

      var operations = [];
      Object.keys(properties).forEach(function(property) {
        if (property !== 'metadata' && property.indexOf('metadata.') !== 0) {
          property = 'metadata.' + property;
        }
        operations.push({
          operation: 'delete',
          property: property,
        });
      });

      edit(conversationId, operations, callback);
    }
169543
def check_communication(attempt, must_try = false)
      attempt += 1
      begin
        if !must_try && (time = time_since_last_communication) < @options[:time_limit]
          @retry_timer.cancel if @retry_timer
          elapsed = elapsed(time)
          info("Passed communication check with activity as recently as #{elapsed} ago", to_console = !@options[:daemon])
          terminate unless @options[:daemon]
        elsif attempt <= @options[:max_attempts]
          debug("Trying communication" + (attempt > 1 ? ", attempt #{attempt}" : ""))
          try_communicating(attempt)
          @retry_timer = EM::Timer.new(@options[:retry_interval]) do
            error("Communication attempt #{attempt} timed out after #{elapsed(@options[:retry_interval])}")
            @agent = AgentConfig.agent_options('instance') # Reload in case not using right cookie
            check_communication(attempt)
          end
        else
          reenroll!
        end
      rescue SystemExit => e
        raise e
      rescue Exception => e
        abort = !@options[:daemon] && (attempt > @options[:max_attempts])
        error("Failed communication check", e, abort)
        check_communication(attempt)
      end
      true
    end
1062143
def get_statement_model(self):
        
        from chatterbot.conversation import Statement

        # Create a storage-aware statement
        statement = Statement
        statement.storage = self

        return statement
330874
def consistent_with_call(self, call):
        
        if len(self.calls) == 0:
            return True, ''

        msg = []

        if not _consistent_allow_none(call._axorder, self._axorder):
            msg.append('inconsistent axorder, {} != {}'.format(call.axorder, self.axorder))

        if not _consistent_allow_none(call._axpos, self._axpos):
            msg.append('inconsistent axpos, {} != {}'.format(call.axpos, self.axpos))

        if call._axorder == self._axorder and call._axorder is not None:
            # then despite other conflicts, attempt to put on same axes
            return True, ''

        if call._axpos == self._axpos and call._axpos is not None:
            # then despite other conflicts, attempt to put on same axes
            return True, ''

        # TODO: include s, c, fc, ec, etc and make these checks into loops
        if call.x.unit.physical_type != self.x.unit.physical_type:
            msg.append('inconsitent xunit, {} != {}'.format(call.x.unit, self.x.unit))
        if call.y.unit.physical_type != self.y.unit.physical_type:
            msg.append('inconsitent yunit, {} != {}'.format(call.y.unit, self.y.unit))
        if call.z.unit.physical_type != self.z.unit.physical_type:
            msg.append('inconsitent zunit, {} != {}'.format(call.z.unit, self.z.unit))
        if call.i.unit.physical_type != self.i.unit.physical_type:
            msg.append('inconsistent iunit, {} != {}'.format(call.i.unit, self.i.unit))
        if call.i.is_reference or self.i.is_reference:
            if call.i.reference != self.i.reference:
                msg.append('inconsistent i reference, {} != {}'.format(call.i.reference, self.i.reference))

        if not _consistent_allow_none(call.title, self.title):
            msg.append('inconsistent axes title, {} != {}'.format(call.title, self.title))

        # here we send the protected _label so that we get None instead of empty string
        if not _consistent_allow_none(call.x._label, self.x._label):
            msg.append('inconsitent xlabel, {} != {}'.format(call.x.label, self.x.label))
        if not _consistent_allow_none(call.y._label, self.y._label):
            msg.append('inconsitent ylabel, {} != {}'.format(call.y.label, self.y.label))
        if not _consistent_allow_none(call.z._label, self.z._label):
            msg.append('inconsitent zlabel, {} != {}'.format(call.z.label, self.z.label))


        if len(msg):
            return False, ', '.join(msg)
        else:
            return True, ''
254930
function(conversationId, callback) {
      conversationId = utils.toUUID(conversationId);
      if (!conversationId) return callback(new Error(utils.i18n.conversations.id));
      utils.debug('Conversation get: ' + conversationId);

      request.get({
        path: '/conversations/' + conversationId
      }, callback);
    }
988646
private void dumpMEtoMEConversations(final IncidentStream is) 
   {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "dumpMEtoMEConversations", is);
      
      final ServerConnectionManager scm = ServerConnectionManager.getRef();
      final List obc = scm.getActiveOutboundMEtoMEConversations();
      
      is.writeLine("", "");
      is.writeLine("\n------ ME to ME Conversation Dump ------ ", ">");
      
      if (obc != null)
      {
         //Build a map of connection -> conversation so that we can output the
         //connection information once per set of conversations.
         final Map<Object, LinkedList<Conversation>> connectionToConversationMap = convertToMap(is, obc);

         //Go through the map and dump out a connection - followed by its conversations
         for (final Iterator<Entry<Object,LinkedList<Conversation>>>i = connectionToConversationMap.entrySet().iterator(); i.hasNext();)
         {
            final Entry<Object, LinkedList<Conversation>>entry = i.next();
            is.writeLine("\nOutbound connection:", entry.getKey());

            final LinkedList conversationList = entry.getValue();
            while(!conversationList.isEmpty())
            {
               final Conversation c = (Conversation)conversationList.removeFirst();
               is.writeLine("\nOutbound Conversation[" + c.getId() + "]: ", c.getFullSummary());
               
               try
               {
                  dumpMEtoMEConversation(is, c);
               }
               catch(Throwable t)
               {
                  // No FFDC Code Needed
                  is.writeLine("\nUnable to dump conversation", t);
               }        
            }
         }
      }
      
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "dumpMEtoMEConversations");
   }
653462
public static void onApptimizeExperimentsProcessed() {
		dispatchConversationTask(new ConversationDispatchTask() {
			@Override
			protected boolean execute(Conversation conversation) {
				ApptentiveInternal instance = ObjectUtils.as(ApptentiveInternal.getInstance(), ApptentiveInternal.class);
				if (instance != null) {
					instance.tryUpdateApptimizeData();
					return true;
				}

				return false;
			}
		}, "update Apptimize experiments data");
	}
366648
Observable<ChatResult> handleConversationUpdated(ConversationUpdate request, ComapiResult<ConversationDetails> result) {

        if (result.isSuccessful()) {

            return persistenceController.upsertConversation(ChatConversation.builder().populate(result.getResult(), result.getETag()).build()).map(success -> adapter.adaptResult(result, success));
        }
        if (result.getCode() == ETAG_NOT_VALID) {

            return checkState().flatMap(client -> client.service().messaging().getConversation(request.getId())
                    .flatMap(newResult -> {
                        if (newResult.isSuccessful()) {

                            return persistenceController.upsertConversation(ChatConversation.builder().populate(newResult.getResult(), newResult.getETag()).build())
                                    .flatMap(success -> Observable.fromCallable(() -> new ChatResult(false, success ? new ChatResult.Error(ETAG_NOT_VALID, "Conversation updated, try delete again.", "Conversation "+request.getId()+" updated in response to  wrong eTag error when updating."): new ChatResult.Error(1500, "Error updating custom store.", null))));
                        } else {
                            return Observable.fromCallable(() -> adapter.adaptResult(newResult));
                        }
                    }));
        } else {

            return Observable.fromCallable(() -> adapter.adaptResult(result));
        }
    }
1167140
private void onConversationUpdated(ConversationUpdateEvent event) {
        handler.post(() -> listener.onConversationUpdated(event));
        log("Event published " + event.toString());
    }
1346043
def check_impl(self):
        

        c = False
        for change in self.collect():
            change.check()
            c = c or change.is_change()
        return c, None
776276
def flushing(self):
        
        try:
            yield
            self.session.flush()
        except (FlushError, IntegrityError) as error:
            error_message = str(error)
            # There ought to be a cleaner way to capture this condition
            if "duplicate" in error_message:
                raise DuplicateModelError(error)
            if "already exists" in error_message:
                raise DuplicateModelError(error)
            if "conflicts with" in error_message and "identity key" in error_message:
                raise DuplicateModelError(error)
            elif "still referenced" in error_message:
                raise ReferencedModelError(error)
            elif "is not present" in error_message:
                raise MissingDependencyError(error)
            else:
                raise ModelIntegrityError(error)
1319860
function correctReply(reply, msg) {
  if (!_.isPlainObject(reply)) {
    reply = { "output": reply }
  }
  // autofill if not already exist
  reply["to"] = reply["to"] || msg["from"]
  reply["from"] = reply["from"] || ioid
  reply["hash"] = reply["hash"] || msg["hash"]
  return reply
}