<commit_before># *****************************************************************************
# Copyright (c) 2018 IBM Corporation and other Contributors.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html 
#
# *****************************************************************************

import getopt
import json
import logging
import os
import signal
import sys
import time

from flask import Flask

try:
    import ibmiotf.application
except ImportError:
    # This part is only required to run the sample from within the samples
    # directory when the module itself is not installed.
    #
    # If you have the module installed, just use "import ibmiotf"
    import os
    import inspect
    cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"../../src")))
    if cmd_subfolder not in sys.path:
        sys.path.insert(0, cmd_subfolder)
    import ibmiotf.application

logger = logging.getLogger('wiotp.deviceconnstate')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)

TABLE_ROW_TEMPLATE = "%-33s%-30s%s"
NEVER_CONNECTED_REASON  = "Never Connected"

# The dict where the device connection state is stored deviceId -> status payload message
# No locking necessary 
deviceConnStateMap = {}

def usage():
    print(
        "deviceStatus: Basic Flask application to report device connection status." + "\n" +
        "\n" +
        "Options: " + "\n" +
        "  -h, --help          Display help information" + "\n" + 
        "  -o, --organization  Connect to the specified organization" + "\n" + 
        "  -i, --id            Application identifier" + "\n" + 
        "  -k, --key           API key used to connect" + "\n" + 
        "  -t, --token         Authentication token for the API key specified" + "\n" + 
        "  -c, --config        Load application configuration file (ignore -o, -i, -k, -t options)" + "\n" 
    )

#####################################################################################
# IoTP Functions
#####################################################################################
        
def statusCallback(status):
    if status.action == "Disconnect":
        summaryText = "%s %s (%s)" % (status.action, status.clientAddr, status.reason)
    else:
        summaryText = "%s %s" % (status.action, status.clientAddr)
    
    logger.debug(TABLE_ROW_TEMPLATE % (status.time.isoformat(), status.device, summaryText))
    if status.closeCode == 288:
        # "Action":"Disconnect", "CloseCode":288,"Reason":"The client ID was reused."
        # These status messages are ignored because it is possible this application
        # will receive the disconnect status message after the connect status message,
        # which would led to the wrong status in the map.
        # (Both a connect and disconnect happen when a client ID is reused)
        logger.debug("Ignoring client ID reused")
    else:
        deviceConnStateMap[status.clientId] = status

def interruptHandler(signal, frame):
    client.disconnect()
    sys.exit(0)
    
#####################################################################################
# Flask Endpoints
#####################################################################################
app = Flask(__name__)

@app.route('/<type>/<id>', methods=['GET'])
def getDeviceStatus(type, id):
    clientId = "d:%s:%s:%s" % (client.organization, type, id)
    if clientId in deviceConnStateMap:
        status = deviceConnStateMap[clientId]
        return json.dumps(status.payload)
    else:
        neverConnectedStatus = {"ClientID": clientId, "Reason": NEVER_CONNECTED_REASON}
        return json.dumps(neverConnectedStatus)
    

#####################################################################################
# MAIN
#####################################################################################
if __name__ == "__main__":
    <commit_msg>Use Action instead of Reason<commit_after># *****************************************************************************
# Copyright (c) 2018 IBM Corporation and other Contributors.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html 
#
# *****************************************************************************

import getopt
import json
import logging
import os
import signal
import sys
import time

from flask import Flask

try:
    import ibmiotf.application
except ImportError:
    # This part is only required to run the sample from within the samples
    # directory when the module itself is not installed.
    #
    # If you have the module installed, just use "import ibmiotf"
    import os
    import inspect
    cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"../../src")))
    if cmd_subfolder not in sys.path:
        sys.path.insert(0, cmd_subfolder)
    import ibmiotf.application

logger = logging.getLogger('wiotp.deviceconnstate')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)

TABLE_ROW_TEMPLATE = "%-33s%-30s%s"
NEVER_CONNECTED_ACTION  = "Never Connected"

# The dict where the device connection state is stored deviceId -> status payload message
# No locking necessary 
deviceConnStateMap = {}

def usage():
    print(
        "deviceStatus: Basic Flask application to report device connection status." + "\n" +
        "\n" +
        "Options: " + "\n" +
        "  -h, --help          Display help information" + "\n" + 
        "  -o, --organization  Connect to the specified organization" + "\n" + 
        "  -i, --id            Application identifier" + "\n" + 
        "  -k, --key           API key used to connect" + "\n" + 
        "  -t, --token         Authentication token for the API key specified" + "\n" + 
        "  -c, --config        Load application configuration file (ignore -o, -i, -k, -t options)" + "\n" 
    )

#####################################################################################
# IoTP Functions
#####################################################################################
        
def statusCallback(status):
    if status.action == "Disconnect":
        summaryText = "%s %s (%s)" % (status.action, status.clientAddr, status.reason)
    else:
        summaryText = "%s %s" % (status.action, status.clientAddr)
    
    logger.debug(TABLE_ROW_TEMPLATE % (status.time.isoformat(), status.device, summaryText))
    if status.closeCode == 288:
        # "Action":"Disconnect", "CloseCode":288,"Reason":"The client ID was reused."
        # These status messages are ignored because it is possible this application
        # will receive the disconnect status message after the connect status message,
        # which would led to the wrong status in the map.
        # (Both a connect and disconnect happen when a client ID is reused)
        logger.debug("Ignoring client ID reused")
    else:
        deviceConnStateMap[status.clientId] = status

def interruptHandler(signal, frame):
    client.disconnect()
    sys.exit(0)
    
#####################################################################################
# Flask Endpoints
#####################################################################################
app = Flask(__name__)

@app.route('/<type>/<id>', methods=['GET'])
def getDeviceStatus(type, id):
    clientId = "d:%s:%s:%s" % (client.organization, type, id)
    if clientId in deviceConnStateMap:
        status = deviceConnStateMap[clientId]
        return json.dumps(status.payload)
    else:
        neverConnectedStatus = {"ClientID": clientId, "Action": NEVER_CONNECTED_ACTION}
        return json.dumps(neverConnectedStatus)
    

#####################################################################################
# MAIN
#####################################################################################
if __name__ == "__main__":
    
{'fraction_non_alphanumeric': 0.2513125656282814, 'fraction_numerical': 0.004900245012250612, 'mean_word_length': 3.796866256295467, 'pattern_counts': {'":': 14, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '517418', 'n_tokens_mistral': 2310, 'n_tokens_neox': 2196, 'n_words': 672}