<commit_before>"""Simple wrapper for BambooHR API calls"""
import json
import requests
from collections import namedtuple
from datetime import date, datetime

Employee = namedtuple("Employee", "display first last nick")
Leave = namedtuple("Leave", "start end")

class BambooHrClient(object):
    """Simple wrapper for getting employees directory and a list of who's out"""

    def __init__(self, api_key, company, host=None):
        self._api_key = api_key
        host = host or "https://api.bamboohr.com"
        self._base_url = "{}/api/gateway.php/{}/v1/".format(host, company)

    @staticmethod
    def _get_date_from_string(date_string):
        return datetime.strptime(date_string, '%Y-%m-%d').date()

    def get_timeoff_whosout(self):
        """Gets a dictionary of current leaves, indexed by employee id"""
        response = requests.get(
            self._base_url + "time_off/whos_out/?end=" + str(date.today()),
            auth=(self._api_key, 'pass'),
            headers={'Accept': 'application/json'})
        leaves_json = json.loads(response.text)
        return {x['employeeId']: Leave(self._get_date_from_string(x['start']),
                                       self._get_date_from_string(x['end']))
                for x in leaves_json if 'employeeId' in x}

    def get_employees_directory(self):
        """Gets a dictionary of all Employees, indexed by employee id"""
        response = requests.get(self._base_url + "employees/directory",
                                auth=(self._api_key, "pass"),
                                headers={'Accept': 'application/json'})
        emps_json = json.loads(response.text)['employees']
        return {int(e['id']): Employee(e['displayName'],
                                       e['firstName'],
                                       e['lastName'],
                                       e['nickname']) for e in emps_json}
<commit_msg>Raise suitable exception for bad response codes<commit_after>"""Simple wrapper for BambooHR API calls"""
import json
import requests
from collections import namedtuple
from datetime import date, datetime

Employee = namedtuple("Employee", "display first last nick")
Leave = namedtuple("Leave", "start end")

class BambooHrClient(object):
    """Simple wrapper for getting employees directory and a list of who's out"""

    def __init__(self, api_key, company, host=None):
        self._api_key = api_key
        host = host or "https://api.bamboohr.com"
        self._base_url = "{}/api/gateway.php/{}/v1/".format(host, company)

    @staticmethod
    def _get_date_from_string(date_string):
        return datetime.strptime(date_string, '%Y-%m-%d').date()

    def get_timeoff_whosout(self):
        """Gets a dictionary of current leaves, indexed by employee id"""
        response = requests.get(
            self._base_url + "time_off/whos_out/?end=" + str(date.today()),
            auth=(self._api_key, 'pass'),
            headers={'Accept': 'application/json'})
        if response.status_code != 200:
            response.raise_for_status()
        leaves_json = json.loads(response.text)
        return {x['employeeId']: Leave(self._get_date_from_string(x['start']),
                                       self._get_date_from_string(x['end']))
                for x in leaves_json if 'employeeId' in x}

    def get_employees_directory(self):
        """Gets a dictionary of all Employees, indexed by employee id"""
        response = requests.get(self._base_url + "employees/directory",
                                auth=(self._api_key, "pass"),
                                headers={'Accept': 'application/json'})
        if response.status_code != 200:
            response.raise_for_status()
        emps_json = json.loads(response.text)['employees']
        return {int(e['id']): Employee(e['displayName'],
                                       e['firstName'],
                                       e['lastName'],
                                       e['nickname']) for e in emps_json}
<|endoftext|>


<commit_before>import random
import unittest

# Insertion

def insertion_sort(a):
    # see OpenJDK
    # http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/Arrays.java#1345
    n = len(a)
    for i in xrange(1, n):
        for j in xrange(i, 0, -1):
            if a[j - 1] <= a[j]:
                break
            a[j - 1], a[j] = a[j], a[j - 1]

def insertion_sort_memmove(a):
    n = len(a)
    for i in xrange(1, n):
        to_be_inserted = a[i]
        inserted = False
        for j in xrange(i - 1, -1, -1):
            if a[j] <= to_be_inserted:
                # memmove(a + j + 1, a + j, i - j)
                a[j + 2: i + 1] = a[j + 1: i]
                a[j + 1] = to_be_inserted
                inserted = True
                break
        if not inserted:
            a[1: i + 1] = a[0: i]
            a[0] = to_be_inserted

def binary_insertion_sort(a):
    n = len(a)
    for i in xrange(1, n):
        to_be_inserted = a[i]
        left = 0
        right = i - 1
        while left < right:
            middle = left + (right - left) // 2
            if to_be_inserted < a[middle]:
                right = middle - 1
            else:
                left = middle + 1
        if to_be_inserted < a[left]:
            a[left + 1: i + 1] = a[left: i]
            a[left] = to_be_inserted
        else:
            a[left + 2: i + 1] = a[left + 1: i]
            a[left + 1] = to_be_inserted

def _shell_gaps(n):
    gap = n // 2
    while gap > 0:
        yield gap
        gap //= 2

def shell_sort(a):
    n = len(a)
    for gap in _shell_gaps(n):
        for i in xrange(gap, n):
            to_be_inserted = a[i]
            j = i
            while j >= gap and a[j - gap] > to_be_inserted:
                a[j] = a[j - gap]
                j -= gap
            a[j] = to_be_inserted

# Swap

def bubble_sort(a):
    n = len(a)
    for i in xrange(n):
        for j in xrange(1, n - i):
            if a[j - 1] > a[j]:
                a[j - 1], a[j] = a[j], a[j - 1]

def _quick_sort(a, left, right):
    if left >= right:
        return
    middle = left + (right - left) // 2
    pivot = a[middle]
    i = left
    j = right
    while i <= j:
        while a[i] < pivot:
            i += 1
        while a[j] > pivot:
            j -= 1
        if i > j:
            break
        elif i < j:
            a[i], a[j] = a[j], a[i]
        i += 1
        j -= 1

    # Optimization: tail call
    # see CLR
    # https://github.com/kasicass/sscli20/blob/dc64e12c9b835d4d373aa04978c0e8f1763b2e1b/clr/src/vm/comarrayhelpers.h#L77
    # https://github.com/kasicass/sscli20/blob/dc64e12c9b835d4d373aa04978c0e8f1763b2e1b/clr/src/bcl/system/collections/generic/arraysorthelper.cs#L70
    _quick_sort(a, left, j)
    _quick_sort(a, i, right)

def quick_sort(a):
    _quick_sort(a, 0, len(a) - 1)

# Selection

def selection_sort(a):
    n = len(a)
    for i in xrange(n):
        min_val = a[i]
        min_val_index = i
        for j in xrange(i + 1, n):
            if a[j] < min_val:
                min_val = a[j]
                min_val_index = j
        a[i], a[min_val_index] = a[min_val_index], a[i]

# Merging

def _merge_sort(dest, src, low, high):
    # Optimization: using insertion sort on smallest arrays (length < 7)
    # see OpenJDK
    # http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/Arrays.java#1338
    if low >= high - 1:
        return

    mid = low + (high - low) // 2
    _merge_sort(src, dest, low, mid)
    _merge_sort(src, dest, mid, high)

    if src[mid - 1] < src[mid]:
        dest[low: high] = src[low: high]
        return

    p = low
    q = mid
    for i in xrange(low, high):
        if q >= high or p < mid and src[p] < src[q]:
            dest[i] = src[p]
            p += 1
        else:
            dest[i] = src[q]
            q += 1

def merge_sort(a):
    aux = list(a)
    _merge_sort(a, aux, 0, len(a))

# Misc

def _heapify(a, root, n):
    left = 2 * root + 1
    right = 2 * root + 2
    largest = root

    if left < n and a[left] > a[largest]:
        largest = left
    if right < n and a[right] > a[largest]:
        largest = right

    if largest != root:
        a[largest], a[root] = a[root], a[largest]
        _heapify(a, largest, n)

def heap_sort(a):
    n = len(a)

    for i in xrange(n // 2 - 1, -1, -1):
        _heapify(a, i, n)

    for i in xrange(n - 1, -1, -1):
        a[0], a[i] = a[i], a[0]
        _heapify(a, 0, i)

class Test(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(Test, self).__init__(*args, **kwargs)

        n = 10
        self.ordered = list(xrange(n))

        cloned = list(self.ordered)
        random_func = random.Random(1).random
        random.shuffle(cloned, random_func)
        self.unordered = cloned

    def test(self):
        self._test(insertion_sort)
        self._test(insertion_sort_memmove)
        self._test(binary_insertion_sort)
        self._test(shell_sort)
        self._test(bubble_sort)
        self._test(quick_sort)
        self._test(selection_sort)
        self._test(merge_sort)
        self._test(heap_sort)

    def _test(self, func):
        unordered = list(self.unordered)
        func(unordered)
        self.assertEqual(unordered, self.ordered)

if __name__ == '__main__':
    unittest.main()
<commit_msg>Radix sort<commit_after>import random
import unittest

# Insertion

def insertion_sort(a):
    # see OpenJDK
    # http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/Arrays.java#1345
    n = len(a)
    for i in xrange(1, n):
        for j in xrange(i, 0, -1):
            if a[j - 1] <= a[j]:
                break
            a[j - 1], a[j] = a[j], a[j - 1]

def insertion_sort_memmove(a):
    n = len(a)
    for i in xrange(1, n):
        to_be_inserted = a[i]
        inserted = False
        for j in xrange(i - 1, -1, -1):
            if a[j] <= to_be_inserted:
                # memmove(a + j + 1, a + j, i - j)
                a[j + 2: i + 1] = a[j + 1: i]
                a[j + 1] = to_be_inserted
                inserted = True
                break
        if not inserted:
            a[1: i + 1] = a[0: i]
            a[0] = to_be_inserted

def binary_insertion_sort(a):
    n = len(a)
    for i in xrange(1, n):
        to_be_inserted = a[i]
        left = 0
        right = i - 1
        while left < right:
            middle = left + (right - left) // 2
            if to_be_inserted < a[middle]:
                right = middle - 1
            else:
                left = middle + 1
        if to_be_inserted < a[left]:
            a[left + 1: i + 1] = a[left: i]
            a[left] = to_be_inserted
        else:
            a[left + 2: i + 1] = a[left + 1: i]
            a[left + 1] = to_be_inserted

def _shell_gaps(n):
    gap = n // 2
    while gap > 0:
        yield gap
        gap //= 2

def shell_sort(a):
    n = len(a)
    for gap in _shell_gaps(n):
        for i in xrange(gap, n):
            to_be_inserted = a[i]
            j = i
            while j >= gap and a[j - gap] > to_be_inserted:
                a[j] = a[j - gap]
                j -= gap
            a[j] = to_be_inserted

# Swap

def bubble_sort(a):
    n = len(a)
    for i in xrange(n):
        for j in xrange(1, n - i):
            if a[j - 1] > a[j]:
                a[j - 1], a[j] = a[j], a[j - 1]

def _quick_sort(a, left, right):
    if left >= right:
        return
    middle = left + (right - left) // 2
    pivot = a[middle]
    i = left
    j = right
    while i <= j:
        while a[i] < pivot:
            i += 1
        while a[j] > pivot:
            j -= 1
        if i > j:
            break
        elif i < j:
            a[i], a[j] = a[j], a[i]
        i += 1
        j -= 1

    # Optimization: tail call
    # see CLR
    # https://github.com/kasicass/sscli20/blob/dc64e12c9b835d4d373aa04978c0e8f1763b2e1b/clr/src/vm/comarrayhelpers.h#L77
    # https://github.com/kasicass/sscli20/blob/dc64e12c9b835d4d373aa04978c0e8f1763b2e1b/clr/src/bcl/system/collections/generic/arraysorthelper.cs#L70
    _quick_sort(a, left, j)
    _quick_sort(a, i, right)

def quick_sort(a):
    _quick_sort(a, 0, len(a) - 1)

# Selection

def selection_sort(a):
    n = len(a)
    for i in xrange(n):
        min_val = a[i]
        min_val_index = i
        for j in xrange(i + 1, n):
            if a[j] < min_val:
                min_val = a[j]
                min_val_index = j
        a[i], a[min_val_index] = a[min_val_index], a[i]

# Merging

def _merge_sort(dest, src, low, high):
    # Optimization: using insertion sort on smallest arrays (length < 7)
    # see OpenJDK
    # http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/Arrays.java#1338
    if low >= high - 1:
        return

    mid = low + (high - low) // 2
    _merge_sort(src, dest, low, mid)
    _merge_sort(src, dest, mid, high)

    if src[mid - 1] < src[mid]:
        dest[low: high] = src[low: high]
        return

    p = low
    q = mid
    for i in xrange(low, high):
        if q >= high or p < mid and src[p] < src[q]:
            dest[i] = src[p]
            p += 1
        else:
            dest[i] = src[q]
            q += 1

def merge_sort(a):
    aux = list(a)
    _merge_sort(a, aux, 0, len(a))

# Misc

def _heapify(a, root, n):
    left = 2 * root + 1
    right = 2 * root + 2
    largest = root

    if left < n and a[left] > a[largest]:
        largest = left
    if right < n and a[right] > a[largest]:
        largest = right

    if largest != root:
        a[largest], a[root] = a[root], a[largest]
        # Optimization: tail call
        _heapify(a, largest, n)

def heap_sort(a):
    n = len(a)

    for i in xrange(n // 2 - 1, -1, -1):
        _heapify(a, i, n)

    for i in xrange(n - 1, -1, -1):
        a[0], a[i] = a[i], a[0]
        _heapify(a, 0, i)

def radix_sort(a):
    # see com.indeed.util.core.sort.RadixSort
    # http://grepcode.com/file/repo1.maven.org/maven2/com.indeed/util-core/1.0.14/com/indeed/util/core/sort/RadixSort.java#7
    n = len(a)
    count_scratch = [0] * 0x10000
    scratch = [0] * n
    sum_ = 0
    for num in a:
        radix = num & 0xFFFF
        count_scratch[radix] += 1
    for i in xrange(0x10000):
        tmp = count_scratch[i]
        count_scratch[i] = sum_
        sum_ += tmp
    for i in xrange(n):
        num = a[i]
        radix = num & 0xFFFF
        offset = count_scratch[radix]
        scratch[offset] = a[i]
        count_scratch[radix] += 1

    count_scratch = [0] * 0x10000
    sum_ = 0
    for num in a:
        radix = (num >> 16) + 0x8000
        count_scratch[radix] += 1
    for i in xrange(0x10000):
        tmp = count_scratch[i]
        count_scratch[i] = sum_
        sum_ += tmp
    for i in xrange(n):
        num = scratch[i]
        radix = (num >> 16) + 0x8000
        offset = count_scratch[radix]
        a[offset] = scratch[i]
        count_scratch[radix] += 1

class Test(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(Test, self).__init__(*args, **kwargs)

        start = -5
        end = 5
        self.ordered = list(xrange(start, end))

        cloned = list(self.ordered)
        random_func = random.Random(1).random
        random.shuffle(cloned, random_func)
        self.unordered = cloned

    def test(self):
        self._test(insertion_sort)
        self._test(insertion_sort_memmove)
        self._test(binary_insertion_sort)
        self._test(shell_sort)
        self._test(bubble_sort)
        self._test(quick_sort)
        self._test(selection_sort)
        self._test(merge_sort)
        self._test(heap_sort)
        self._test(radix_sort)

    def _test(self, func):
        unordered = list(self.unordered)
        func(unordered)
        self.assertEqual(unordered, self.ordered)

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before>#!/usr/bin/python

#
# Python Freifunk Heat Map
#

import datetime
import StringIO
import json
import csv
import web

#web.config.debug = False

# file format constants
FILE_FORMAT_WIFI_LL_CSV = 1

db = web.database(dbn="sqlite", db="scanresults.db")
render = web.template.render("templates/")

urls = (
    "/", "Index",
    "/map", "Map",
    "/mapdata/(.+)/(.+)/(.+)/(.+)", "MapData",
    "/upload", "Upload",
    )

app = web.application(urls, globals())

class Index:
    def GET(self):
        return render.index()

class Map:
    def GET(self):
        return render.mapview()

class MapData:
    def GET(self, west, east, north, south):

        scans = db.query("select * from scans where scans.lon >= $west and scans.lon <= $east and scans.lat >= $south and scans.lat <= $north",
            vars={"west": float(west), "east": float(east), "north": float(north), "south": float(south)})

        jsonData = []
        for row in scans:
            hotspots = db.query("select * from hotspots where scanid = $scanid",
                vars={"scanid": row["id"]})

            hotspots = list(hotspots)
            if not(hotspots):
                continue

            maxLevel = max([ h["level"] for h in hotspots] )

            ssids = set([ h["ssid"] for h in hotspots ])
            bssids = [ h["bssid"] for h in hotspots ]
            desc = "%s: %s" % (", ".join(ssids), ", ".join(bssids))

            point = {
                "lat": row["lat"],
                "lon": row["lon"],
                "quality": maxLevel+100,
                "text": desc,
            }
            jsonData.append(point)
        print "num points: %d" % len(jsonData)

        web.header("Content-Type", "application/json")
        return json.dumps(jsonData)

class Upload:
    def GET(self):
        return render.upload("")

    def POST(self):
        #values = web.input(f={})
        values = web.input()

        if len(values.keys()) != 1:
            # there must be exactly one form field in the request
            raise web.webapi.BadRequest()

        for key in values:
            contents = values[key]

        if not(contents):
            message = "ignoring empty file."
        else:
            # save raw file contents for debugging:
            fd = open("/tmp/uploaded.bin", "wb")
            fd.write(contents)
            fd.close()

            try:
                # assume that uploaded files are in CSV format
                # TODO: detect file type
                self.parseWifiLLCSVFile(contents)
            except Exception, e:
                message = "error handling uploaded file (%s)" % e
            else:
                message = "file was uploaded (%d bytes)!" % len(contents)

        #raise web.seeother("/finished")
        return render.upload(message)

    def parseWifiLLCSVFile(self, s):
        "read WifiLocationLogger CSV file (version 1) and add contents to database"

        transaction = db.transaction()

        # data of "current" scan (used for cumulating multiple hotspots at same location into single scan entry):
        currentScan = {
            "ts": None,
            "lat": None,
            "lon": None,
            "alt": None,
            "accuracy": None
        }
        currentHotspots = []

        def addScan(fileId, scan, hotspots):
            scanId = db.insert("scans", fileid=fileId, scantime=scan["ts"], lat=scan["lat"], lon=scan["lon"], alt=scan["alt"], accuracy=scan["accuracy"])
            for h in hotspots:
                db.insert("hotspots", scanid=scanId, ssid=h[0], bssid=h[1], channel=h[2], level=h[3])

        fileId = None
        reader = csv.reader(StringIO.StringIO(s))
        for row in reader:
            #print row
            if len(row) != 16 or row[1] != "1":
                print "invalid data in line %d (num columns: %d; format version: '%s')" % (reader.line_num, len(row), row[1])
                continue

            (timestamp, formatVersion, deviceModel, sessionId, lat, lon, alt, accuracy, speed, specialCode, timeSinceLastLocUpdate, ssid, bssid, signalLevel, channel, filterRE) = row

            if not(fileId):
                fileId = db.insert("files", sessionid=sessionId, upload_date=datetime.datetime.now(), format=FILE_FORMAT_WIFI_LL_CSV, formatversion=int(formatVersion), device=deviceModel)

            dotPos = timestamp.rindex(".")
            timestampDt = datetime.datetime.strptime(timestamp[:dotPos], "%Y-%m-%d %H:%M:%S")

            newScan = {
                "ts": timestampDt,
                "lat": float(lat),
                "lon": float(lon),
                "alt": float(alt),
                "accuracy": float(accuracy),
            }

            if newScan != currentScan:
                # create new scan entry
                if currentScan["ts"] is not None:
                    # save old scan entry first
                    addScan(fileId, currentScan, currentHotspots)
                currentScan = newScan
                currentHotspots = []

            if int(specialCode) == 0 and ssid.find("freifunk") != -1: # row actually contains a hotspot, and it's a FF node
                currentHotspots.append( (ssid.decode("utf-8", "replace"), bssid, int(channel), int(signalLevel)) )

        # save last scan entry
        if currentScan["ts"] is not None:
            addScan(fileId, currentScan, currentHotspots)

        transaction.commit()

if __name__ == "__main__":
    app.run()
<commit_msg>speed up MapData.GET: don't query hotspots table for empty scans<commit_after>#!/usr/bin/python

#
# Python Freifunk Heat Map
#

import datetime
import StringIO
import json
import csv
import web

#web.config.debug = False

# file format constants
FILE_FORMAT_WIFI_LL_CSV = 1

db = web.database(dbn="sqlite", db="scanresults.db")
render = web.template.render("templates/")

urls = (
    "/", "Index",
    "/map", "Map",
    "/mapdata/(.+)/(.+)/(.+)/(.+)", "MapData",
    "/upload", "Upload",
    )

app = web.application(urls, globals())

class Index:
    def GET(self):
        return render.index()

class Map:
    def GET(self):
        return render.mapview()

class MapData:
    def GET(self, west, east, north, south):

        scans = db.query("select *, (select count(*) from hotspots where scans.id = hotspots.scanid) as hscount from scans where scans.lon >= $west and scans.lon <= $east and scans.lat >= $south and scans.lat <= $north and hscount > 0",
            vars={"west": float(west), "east": float(east), "north": float(north), "south": float(south)})

        jsonData = []
        for row in scans:
            hotspots = db.query("select * from hotspots where scanid = $scanid",
                vars={"scanid": row["id"]})

            hotspots = list(hotspots)

            maxLevel = max([ h["level"] for h in hotspots] )

            ssids = set([ h["ssid"] for h in hotspots ])
            bssids = [ h["bssid"] for h in hotspots ]
            desc = "%s: %s" % (", ".join(ssids), ", ".join(bssids))

            point = {
                "lat": row["lat"],
                "lon": row["lon"],
                "quality": maxLevel+100,
                "text": desc,
            }
            jsonData.append(point)
        print "num points: %d" % len(jsonData)

        web.header("Content-Type", "application/json")
        return json.dumps(jsonData)

class Upload:
    def GET(self):
        return render.upload("")

    def POST(self):
        #values = web.input(f={})
        values = web.input()

        if len(values.keys()) != 1:
            # there must be exactly one form field in the request
            raise web.webapi.BadRequest()

        for key in values:
            contents = values[key]

        if not(contents):
            message = "ignoring empty file."
        else:
            # save raw file contents for debugging:
            fd = open("/tmp/uploaded.bin", "wb")
            fd.write(contents)
            fd.close()

            try:
                # assume that uploaded files are in CSV format
                # TODO: detect file type
                self.parseWifiLLCSVFile(contents)
            except Exception, e:
                message = "error handling uploaded file (%s)" % e
            else:
                message = "file was uploaded (%d bytes)!" % len(contents)

        #raise web.seeother("/finished")
        return render.upload(message)

    def parseWifiLLCSVFile(self, s):
        "read WifiLocationLogger CSV file (version 1) and add contents to database"

        transaction = db.transaction()

        # data of "current" scan (used for cumulating multiple hotspots at same location into single scan entry):
        currentScan = {
            "ts": None,
            "lat": None,
            "lon": None,
            "alt": None,
            "accuracy": None
        }
        currentHotspots = []

        def addScan(fileId, scan, hotspots):
            scanId = db.insert("scans", fileid=fileId, scantime=scan["ts"], lat=scan["lat"], lon=scan["lon"], alt=scan["alt"], accuracy=scan["accuracy"])
            for h in hotspots:
                db.insert("hotspots", scanid=scanId, ssid=h[0], bssid=h[1], channel=h[2], level=h[3])

        fileId = None
        reader = csv.reader(StringIO.StringIO(s))
        for row in reader:
            #print row
            if len(row) != 16 or row[1] != "1":
                print "invalid data in line %d (num columns: %d; format version: '%s')" % (reader.line_num, len(row), row[1])
                continue

            (timestamp, formatVersion, deviceModel, sessionId, lat, lon, alt, accuracy, speed, specialCode, timeSinceLastLocUpdate, ssid, bssid, signalLevel, channel, filterRE) = row

            if not(fileId):
                fileId = db.insert("files", sessionid=sessionId, upload_date=datetime.datetime.now(), format=FILE_FORMAT_WIFI_LL_CSV, formatversion=int(formatVersion), device=deviceModel)

            dotPos = timestamp.rindex(".")
            timestampDt = datetime.datetime.strptime(timestamp[:dotPos], "%Y-%m-%d %H:%M:%S")

            newScan = {
                "ts": timestampDt,
                "lat": float(lat),
                "lon": float(lon),
                "alt": float(alt),
                "accuracy": float(accuracy),
            }

            if newScan != currentScan:
                # create new scan entry
                if currentScan["ts"] is not None:
                    # save old scan entry first
                    addScan(fileId, currentScan, currentHotspots)
                currentScan = newScan
                currentHotspots = []

            if int(specialCode) == 0 and ssid.find("freifunk") != -1: # row actually contains a hotspot, and it's a FF node
                currentHotspots.append( (ssid.decode("utf-8", "replace"), bssid, int(channel), int(signalLevel)) )

        # save last scan entry
        if currentScan["ts"] is not None:
            addScan(fileId, currentScan, currentHotspots)

        transaction.commit()

if __name__ == "__main__":
    app.run()
<|endoftext|>


<commit_before>
from flask import Flask,jsonify,request
import hashlib,json, sqlite3, uuid

app=Flask(__name__)

@app.route('/',methods=["GET","POST"])
def main():
    return "It's a server!"

@app.route('/login', methods=["GET","POST"])
def login():
    userInfo = request.get_json(force = True)
    #Create HashLib Obj
    hasher = hashlib.sha256()

    sqlite_file = "db/server.db"
    table_name = "namePass"
    username_column = "username"
    pass_col = "password"
    usernameIn = userInfo['username']
    passwordIn = userInfo['password']
    conn = sqlite3.connect(sqlite_file)
    c = conn.cursor()
    c.execute("SELECT * FROM namePass WHERE %s=?" % username_column,(usernameIn,))
    id_exists = c.fetchone()
    if id_exists:
        print(id_exists[0])
        #Encode the passowed the user entered
        hasher.update(passwordIn)
        entered = hasher.hexdigest()
        #Get Expected Password
        expected = id_exists[1]

        if entered == expected:
            retMessage = {"message" : "You have logged in","code":200}
        else:
            retMessage = {"message":"Invalid Log in","code":403}
    else:
        retMessage = {"message":"Invalid Log in","code":403}

    conn.close()
    return jsonify(retMessage)

@app.route('/create-user',methods=["POST"])
def create_user():
    #Get Request
    data = request.get_json(force = True)
    print data["username"]
    #connect to db
    connection = sqlite3.connect('db/server.db')

    #generate unique id
    u_id = str(uuid.uuid4())

    #Create Hash Object
    hasher = hashlib.sha256()
    #Hash the password
    hasher.update(data["password"])
    data["password"] = hasher.hexdigest()
    #format data for insertions
    user = ((data["username"],data["password"],"","","","","","","","",u_id),)

    with connection:
        cur = connection.cursor()
        search = cur.execute("SELECT * FROM namePass WHERE %s=?" % "username",(data["username"],))
        exists = seach.fetchone()
        if exists:
            response = {"code": 403, "message": "This Username already exists in the database."}
            return jsonify(response)

        cur.executemany("INSERT INTO namePass VALUES (?,?,?,?,?,?,?,?,?,?,?)", user)
        connection.commit()

    #Create Response
    response = {"message": "A new user has successfully been added to the database. ",
                "code": 200}

    print "[POST] NEW USER CREATION: New user has been added to the database"
    return jsonify(response)

    """
        @Desc: Handles Requests for events
        @Param: id: str- id of event to retrieve
        @Returns: JSON Object containing data and server response codes
    """
    @app.route('/get-event/<id>')
    def get_event(id):
        #Connect to DB
        connection = sqlite('db/server.db')
        #Initialize Response
        response = {"code": 400, "message": "Could not retreive event."}

        with connection:
            #Query DB for Event
            cur = connection.cursor()
            search = cur.execute("SELECT * FROM events WHERE %s=?" % "id", (id,))
            exists = search.fetchone()
            #If event is found
            if exists:
                #Format Event
                cols = [description[0] for description in cursor.description]
                event = {key: value for (key,value) in cols}

                #Generate Response
                response["code"] = 200
                response["message"] = "Event Retrieved"
                response["event"] = event

        return jsonify(response)

@app.route('/create-event',methods=["POST"])
def create_event():
    #Get Request
    data = request.get_json(force = True)
    #connect to db
    connection = sqlite3.connect('db/server.db')

    #generate unique id
    u_id = str(uuid.uuid4())

    #format data for insertions
    user = ((data["date"],data["time"],data["location"],data["name"],data["description"],data["listofPart"],data["image"],data["owner"],data["arrivalNot"],u_id),)

    with connection:
        cur = connection.cursor()
        cur.executemany("INSERT INTO events VALUES (?,?,?,?,?,?,?,?,?,?)", user)
        connection.commit()

    #Create Response
    response = {"message": "A new event has successfully been added to the database. ",
                "code": 200}

    print "[POST] NEW EVENT CREATION: New event has been added to the database"
    return jsonify(response)
<commit_msg>Fixed Spelling Error<commit_after>
from flask import Flask,jsonify,request
import hashlib,json, sqlite3, uuid

app=Flask(__name__)

@app.route('/',methods=["GET","POST"])
def main():
    return "It's a server!"

@app.route('/login', methods=["GET","POST"])
def login():
    userInfo = request.get_json(force = True)
    #Create HashLib Obj
    hasher = hashlib.sha256()

    sqlite_file = "db/server.db"
    table_name = "namePass"
    username_column = "username"
    pass_col = "password"
    usernameIn = userInfo['username']
    passwordIn = userInfo['password']
    conn = sqlite3.connect(sqlite_file)
    c = conn.cursor()
    c.execute("SELECT * FROM namePass WHERE %s=?" % username_column,(usernameIn,))
    id_exists = c.fetchone()
    if id_exists:
        print(id_exists[0])
        #Encode the passowed the user entered
        hasher.update(passwordIn)
        entered = hasher.hexdigest()
        #Get Expected Password
        expected = id_exists[1]

        if entered == expected:
            retMessage = {"message" : "You have logged in","code":200}
        else:
            retMessage = {"message":"Invalid Log in","code":403}
    else:
        retMessage = {"message":"Invalid Log in","code":403}

    conn.close()
    return jsonify(retMessage)

@app.route('/create-user',methods=["POST"])
def create_user():
    #Get Request
    data = request.get_json(force = True)
    print data["username"]
    #connect to db
    connection = sqlite3.connect('db/server.db')

    #generate unique id
    u_id = str(uuid.uuid4())

    #Create Hash Object
    hasher = hashlib.sha256()
    #Hash the password
    hasher.update(data["password"])
    data["password"] = hasher.hexdigest()
    #format data for insertions
    user = ((data["username"],data["password"],"","","","","","","","",u_id),)

    with connection:
        cur = connection.cursor()
        search = cur.execute("SELECT * FROM namePass WHERE %s=?" % "username",(data["username"],))
        exists = search.fetchone()
        if exists:
            response = {"code": 403, "message": "This Username already exists in the database."}
            return jsonify(response)

        cur.executemany("INSERT INTO namePass VALUES (?,?,?,?,?,?,?,?,?,?,?)", user)
        connection.commit()

    #Create Response
    response = {"message": "A new user has successfully been added to the database. ",
                "code": 200}

    print "[POST] NEW USER CREATION: New user has been added to the database"
    return jsonify(response)

    """
        @Desc: Handles Requests for events
        @Param: id: str- id of event to retrieve
        @Returns: JSON Object containing data and server response codes
    """
    @app.route('/get-event/<id>')
    def get_event(id):
        #Connect to DB
        connection = sqlite('db/server.db')
        #Initialize Response
        response = {"code": 400, "message": "Could not retreive event."}

        with connection:
            #Query DB for Event
            cur = connection.cursor()
            search = cur.execute("SELECT * FROM events WHERE %s=?" % "id", (id,))
            exists = search.fetchone()
            #If event is found
            if exists:
                #Format Event
                cols = [description[0] for description in cursor.description]
                event = {key: value for (key,value) in cols}

                #Generate Response
                response["code"] = 200
                response["message"] = "Event Retrieved"
                response["event"] = event

        return jsonify(response)

@app.route('/create-event',methods=["POST"])
def create_event():
    #Get Request
    data = request.get_json(force = True)
    #connect to db
    connection = sqlite3.connect('db/server.db')

    #generate unique id
    u_id = str(uuid.uuid4())

    #format data for insertions
    user = ((data["date"],data["time"],data["location"],data["name"],data["description"],data["listofPart"],data["image"],data["owner"],data["arrivalNot"],u_id),)

    with connection:
        cur = connection.cursor()
        cur.executemany("INSERT INTO events VALUES (?,?,?,?,?,?,?,?,?,?)", user)
        connection.commit()

    #Create Response
    response = {"message": "A new event has successfully been added to the database. ",
                "code": 200}

    print "[POST] NEW EVENT CREATION: New event has been added to the database"
    return jsonify(response)
<|endoftext|>


<commit_before>#!/usr/bin/env python3

import os, logging, argparse, json, datetime
import requests
import dns.resolver
from bottle import route, request, response, redirect, hook, error, default_app, view, static_file, template

def resolveDomain(domain, recordType, dnsAddr):
	try:
		records = []

		resolver = dns.resolver.Resolver()
		resolver.nameservers = dnsAddr.split(',')

		if recordType in args.records.split(','):
			lookup = resolver.query(domain, recordType)
			for data in lookup:
				if recordType in ['A', 'AAAA']:
					records.append(data.address)
				elif recordType in ['TXT']:
					for rec in data.strings:
						records.append(rec.decode("utf-8").replace('"', '').strip())
				else:
					records.append(str(data).replace('"', '').strip())
		return records
	except dns.resolver.NXDOMAIN:
		return records
	except dns.resolver.NoAnswer:
		return records
	except dns.exception.Timeout:
		return records
	except dns.resolver.NoNameservers:
		return records

@error('404')
@error('403')
def returnError(code, msg, contentType="text/plain"):
	response.status = int(code)
	response.content_type = contentType
	return template('error')

@hook('before_request')
def determine_content_type():
	if request.headers.get('Accept') == "application/json":
		response.content_type = 'application/json'
	elif request.headers.get('Accept') == "text/plain":
		response.content_type = 'text/plain'

@hook('after_request')
def log_to_console():
	log.info("{} {} {}".format(
		datetime.datetime.now(),
		response.status_code,
		request.url
	))

@route('/static/<filepath:path>')
def server_static(filepath):
	return static_file(filepath, root='views/static')

@route('/servers')
def return_servers():
	try:
		response.content_type = 'text/plain'
		return "\r\n".join(args.resolver.split(","))
	except:
		return "Unable to open servers file."

@route('/version')
def return_version():
	try:
		dirname, filename = os.path.split(os.path.abspath(__file__))
		del filename
		f = open(os.getenv('VERSION_PATH', dirname + '/.git/refs/heads/master'), 'r')
		content = f.read()
		response.content_type = 'text/plain'
		return content
	except:
		return "Unable to open version file."

@route('/<record>')
@route('/<record>/<type>')
@route('/<record>/<type>.<ext>')
def loadRecord(record="", type="", ext="html"):
	try:
		if record == "" or type == "":
			raise ValueError
		if not type.upper() in args.records.split(','):
			raise ValueError
		if not ext in ["html","txt", "text","json"]:
			ext = "html"
		if ext == "json":
			response.content_type = 'application/json'
		elif ext in ["txt","text"]:
			response.content_type = 'text/plain'
	except ValueError:
		return returnError(404, "Not Found", "text/html")

	# We make a request to get information
	data = resolveDomain(record, type.upper(), args.resolver)

	if not len(data) > 0:
		data.append("Unable to identify any records with type: {}".format(type))

	content = {
		'name': record,
		'type': type.upper(),
		'records': data,
		'recTypes': args.records.split(',')
	}

	if ext == "json" or response.content_type == 'application/json' :
		del content['recTypes']

		jsonContent = {
			"results": content
		}

		return json.dumps(jsonContent)
	elif ext in ["txt","text"] or response.content_type == "text/plain":
		return "\r\n".join(data)
	else:
		return template('rec', content)

@route('/', method="POST")
def postIndex():

	try:
		recordName = request.forms.get('recordName')
		recordType = request.forms.get('recordType')

		if not recordType == "Type" and not recordType in args.records.split(','):
			raise ValueError
		if recordName == "" or recordType == "Type":
			raise ValueError
		return redirect("/{}/{}".format(recordName, recordType))
	except ValueError:
		return returnError(404, "Not Found", "text/html")
	except AttributeError:
		return returnError(404, "Not Found", "text/html")

@route('/')
def index():
	content = {
		'recTypes': args.records.split(',')
	}
	return template("home", content)

if __name__ == '__main__':

	parser = argparse.ArgumentParser()

	# Server settings
	parser.add_argument("-i", "--host", default=os.getenv('IP', '127.0.0.1'), help="server ip")
	parser.add_argument("-p", "--port", default=os.getenv('PORT', 5000), help="server port")

	# Redis settings
	parser.add_argument("--redis-host", default=os.getenv('REDIS_HOST', 'redis'), help="redis hostname")
	parser.add_argument("--redis-port", default=os.getenv('REDIS_PORT', 6379), help="redis port")
	parser.add_argument("--redis-pw", default=os.getenv('REDIS_PW', ''), help="redis password")
	parser.add_argument("--redis-ttl", default=os.getenv('REDIS_TTL', 60), help="redis time to cache records")

	# Application settings
	parser.add_argument("--records", default=os.getenv('APP_RECORDS', "A,AAAA,CNAME,DS,DNSKEY,MX,NS,NSEC,NSEC3,RRSIG,SOA,TXT"), help="supported records")
	parser.add_argument("--resolver", default=os.getenv('APP_RESOLVER', '8.8.8.8'), help="resolver address")

	# Verbose mode
	parser.add_argument("--verbose", "-v", help="increase output verbosity", action="store_true")
	args = parser.parse_args()

	if args.verbose:
		logging.basicConfig(level=logging.DEBUG)
	else:
		logging.basicConfig(level=logging.INFO)
	log = logging.getLogger(__name__)

	try:
		app = default_app()
		app.run(host=args.host, port=args.port, server='tornado')
	except:
		log.error("Unable to start server on {}:{}".format(args.host, args.port))<commit_msg>Enabled CORS on /<record>/<type> endpoint<commit_after>#!/usr/bin/env python3

import os, logging, argparse, json, datetime
import requests
import dns.resolver
from bottle import route, request, response, redirect, hook, error, default_app, view, static_file, template

def set_content_type(fn):
	def _return_json(*args, **kwargs):
		response.headers['Content-Type'] = 'application/json'
		if request.method != 'OPTIONS':
			return fn(*args, **kwargs)
	return _return_json

def enable_cors(fn):
	def _enable_cors(*args, **kwargs):
		response.headers['Access-Control-Allow-Origin'] = '*'
		response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
		response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

		if request.method != 'OPTIONS':
			return fn(*args, **kwargs)
	return _enable_cors

def resolveDomain(domain, recordType, dnsAddr):
	try:
		records = []

		resolver = dns.resolver.Resolver()
		resolver.nameservers = dnsAddr.split(',')

		if recordType in args.records.split(','):
			lookup = resolver.query(domain, recordType)
			for data in lookup:
				if recordType in ['A', 'AAAA']:
					records.append(data.address)
				elif recordType in ['TXT']:
					for rec in data.strings:
						records.append(rec.decode("utf-8").replace('"', '').strip())
				else:
					records.append(str(data).replace('"', '').strip())
		return records
	except dns.resolver.NXDOMAIN:
		return records
	except dns.resolver.NoAnswer:
		return records
	except dns.exception.Timeout:
		return records
	except dns.resolver.NoNameservers:
		return records

@error('404')
@error('403')
def returnError(code, msg, contentType="text/plain"):
	response.status = int(code)
	response.content_type = contentType
	return template('error')

@hook('before_request')
def determine_content_type():
	if request.headers.get('Accept') == "application/json":
		response.content_type = 'application/json'
	elif request.headers.get('Accept') == "text/plain":
		response.content_type = 'text/plain'

@hook('after_request')
def log_to_console():
	log.info("{} {} {}".format(
		datetime.datetime.now(),
		response.status_code,
		request.url
	))

@route('/static/<filepath:path>')
def server_static(filepath):
	return static_file(filepath, root='views/static')

@route('/servers')
def return_servers():
	try:
		response.content_type = 'text/plain'
		return "\r\n".join(args.resolver.split(","))
	except:
		return "Unable to open servers file."

@route('/version')
def return_version():
	try:
		dirname, filename = os.path.split(os.path.abspath(__file__))
		del filename
		f = open(os.getenv('VERSION_PATH', dirname + '/.git/refs/heads/master'), 'r')
		content = f.read()
		response.content_type = 'text/plain'
		return content
	except:
		return "Unable to open version file."

@route('/<record>')
@route('/<record>/<type>')
@route('/<record>/<type>.<ext>')
@enable_cors
def loadRecord(record="", type="", ext="html"):
	try:
		if record == "" or type == "":
			raise ValueError
		if not type.upper() in args.records.split(','):
			raise ValueError
		if not ext in ["html","txt", "text","json"]:
			ext = "html"
		if ext == "json":
			response.content_type = 'application/json'
		elif ext in ["txt","text"]:
			response.content_type = 'text/plain'
	except ValueError:
		return returnError(404, "Not Found", "text/html")

	# We make a request to get information
	data = resolveDomain(record, type.upper(), args.resolver)

	if not len(data) > 0:
		data.append("Unable to identify any records with type: {}".format(type))

	content = {
		'name': record,
		'type': type.upper(),
		'records': data,
		'recTypes': args.records.split(',')
	}

	if ext == "json" or response.content_type == 'application/json' :
		del content['recTypes']

		jsonContent = {
			"results": content
		}

		return json.dumps(jsonContent)
	elif ext in ["txt","text"] or response.content_type == "text/plain":
		return "\r\n".join(data)
	else:
		return template('rec', content)

@route('/', method="POST")
def postIndex():

	try:
		recordName = request.forms.get('recordName')
		recordType = request.forms.get('recordType')

		if not recordType == "Type" and not recordType in args.records.split(','):
			raise ValueError
		if recordName == "" or recordType == "Type":
			raise ValueError
		return redirect("/{}/{}".format(recordName, recordType))
	except ValueError:
		return returnError(404, "Not Found", "text/html")
	except AttributeError:
		return returnError(404, "Not Found", "text/html")

@route('/')
def index():
	content = {
		'recTypes': args.records.split(',')
	}
	return template("home", content)

if __name__ == '__main__':

	parser = argparse.ArgumentParser()

	# Server settings
	parser.add_argument("-i", "--host", default=os.getenv('IP', '127.0.0.1'), help="server ip")
	parser.add_argument("-p", "--port", default=os.getenv('PORT', 5000), help="server port")

	# Redis settings
	parser.add_argument("--redis-host", default=os.getenv('REDIS_HOST', 'redis'), help="redis hostname")
	parser.add_argument("--redis-port", default=os.getenv('REDIS_PORT', 6379), help="redis port")
	parser.add_argument("--redis-pw", default=os.getenv('REDIS_PW', ''), help="redis password")
	parser.add_argument("--redis-ttl", default=os.getenv('REDIS_TTL', 60), help="redis time to cache records")

	# Application settings
	parser.add_argument("--records", default=os.getenv('APP_RECORDS', "A,AAAA,CNAME,DS,DNSKEY,MX,NS,NSEC,NSEC3,RRSIG,SOA,TXT"), help="supported records")
	parser.add_argument("--resolver", default=os.getenv('APP_RESOLVER', '8.8.8.8'), help="resolver address")

	# Verbose mode
	parser.add_argument("--verbose", "-v", help="increase output verbosity", action="store_true")
	args = parser.parse_args()

	if args.verbose:
		logging.basicConfig(level=logging.DEBUG)
	else:
		logging.basicConfig(level=logging.INFO)
	log = logging.getLogger(__name__)

	try:
		app = default_app()
		app.run(host=args.host, port=args.port, server='tornado')
	except:
		log.error("Unable to start server on {}:{}".format(args.host, args.port))<|endoftext|>


<commit_before>import requests
from requests.auth import HTTPBasicAuth
from flask import Flask, request, render_template, jsonify
from flask.ext.cache import Cache

import config

app = Flask(__name__)
cache = Cache(app, config=config.CACHE)

@app.route("/")
def index():
    return render_template('index.html')

@app.route("/search")
def search():
    search_term = request.args.get('q')
    response = _search_for_term(search_term)
    return jsonify(response)

def _search_for_term(search_term):
    cache_key = 's-{}'.format(search_term)
    response = cache.get(cache_key)
    if not response:
        response = _make_request(search_term)
    cache.set(cache_key, response, 300)
    return response

def _make_request(search_term):
    basic_auth = HTTPBasicAuth(config.GITHUB_TOKEN, 'x-oauth-basic')
    url = ('https://api.github.com/search/repositories?q="cookiecutter%20'
           'template"+{term}+in:description&sort=stars&order=desc')

    github_response = requests.get(url.format(term=search_term),
                                   auth=basic_auth)

    if github_response.status_code == 401:
        response = {
            'error': "We're over quota. Please come back after a few minutes :)"
        }
    elif github_response.status_code == 200:
        response = _transform_response(github_response)
    else:
        response = {
            'error': 'An unknown error ocurred: {}'.format(github_response.status_code)
        }

    return response

def _transform_response(github_response):
    response = []
    items = github_response.json().get('items', [])
    for item in items:
        response.append({
            'name': item['full_name'],
            'description': item['description'],
            'url': item['html_url'],
        })
    return {'results': response}

if __name__ == "__main__":
    app.debug = config.DEBUG
    app.run()
<commit_msg>Don't cache error responses<commit_after>import requests
from requests.auth import HTTPBasicAuth
from flask import Flask, request, render_template, jsonify
from flask.ext.cache import Cache

import config

app = Flask(__name__)
cache = Cache(app, config=config.CACHE)

@app.route("/")
def index():
    return render_template('index.html')

@app.route("/search")
def search():
    search_term = request.args.get('q')
    response = _search_for_term(search_term)
    return jsonify(response)

def _search_for_term(search_term):
    response = _make_request(search_term)
    return _parse_response(response)

@cache.memoize(timeout=300)
def _make_request(search_term):
    basic_auth = HTTPBasicAuth(config.GITHUB_TOKEN, 'x-oauth-basic')
    url = ('https://api.github.com/search/repositories?q="cookiecutter%20'
           'template"+{term}+in:description&sort=stars&order=desc')

    return requests.get(url.format(term=search_term), auth=basic_auth)

def _parse_response(response):
    if response.status_code == 401:
        response = {
            'error': "We're over quota. Please come back after a few minutes :)"
        }
    elif response.status_code == 200:
        response = _transform_response(response)
    else:
        response = {
            'error': 'An unknown error ocurred: {}'.format(response.status_code)
        }

    return response

def _transform_response(github_response):
    response = []
    items = github_response.json().get('items', [])
    for item in items:
        response.append({
            'name': item['full_name'],
            'description': item['description'],
            'url': item['html_url'],
        })
    return {'results': response}

if __name__ == "__main__":
    app.debug = config.DEBUG
    app.run()
<|endoftext|>


<commit_before>#!/usr/bin/env python

import urllib
import json
import os
import urllib.request

from flask import Flask
from flask import request
from flask import make_response

# Flask app should start in global layout
app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(silent=True, force=True)

    print("Request:")
    print(json.dumps(req, indent=4))

    res = makeWebhookResult(req)

    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

# http://90.73.151.42:8085/remoteControl/cmd?operation=10
    liveboxIp = '90.73.15.218:8085';
    # url = 'http://' + liveboxIp + '/remoteControl/cmd?operation=';
    url2 = 'http://' + liveboxIp + '/remoteControl/cmd?operation=01&key=116&mode=0';

def makeWebhookResult(req):
    if req.get("result").get("action") == "Livebox-chaine":
        liveboxIp = '90.73.151.42:8085'
        url2 = 'http://' + liveboxIp + '/remoteControl/cmd?operation=01&key=116&mode=0'
        url2 = 'http://' + liveboxIp + '/remoteControl/cmd?operation=01&key='
        result = req.get("result")
        parameters = result.get("parameters")
        zone = parameters.get("ListeDesChaines")
        zone1 = zone[0]

        cost = {'c1':'TF1', 'c2':'France 2', 'c3':'France 3', 'c4':'Canal plus', 'c5':'France 5', 'c6':'M 6'}
        speech = "La chaîne " + str(cost[zone1]) + " va être lancé."

        zone1 = zone1.replace("c", "")
        zone2 = int(zone1)

        code = {0:'512', 1:'513', 2:'514', 3:'515', 4:'516', 5:'517', 6:'518', 7:'519', 8:'520', 9:'521'}

        unite = zone2 % 10
        dizaine = (zone2 % 100) / 10
        centaine = (zone2 % 1000) / 100

        if centaine > 0.9:
            codeA = code[centaine]
            url = url2 + codeA + '&mode=0'
            page = urllib.request.urlopen(url)
            strpage = page.read()

        if dizaine > 0.9:
            codeA = code[dizaine]
            url = url2 + codeA + '&mode=0'
            page = urllib.request.urlopen(url)
            strpage = page.read()

        codeA = code[unite]
        url = url2 + codeA + '&mode=0'
        page = urllib.request.urlopen(url)
        strpage = page.read()

        print("Response:")
        print(speech)

        return {
            "speech": speech,
            "displayText": speech,
            #"data": {},
            # "contextOut": [],
            "source": "apiai-worganic-livebox",
            "urlA": url
        }
    elif req.get("result").get("action") == "Livebox-action":
        result = req.get("result")
        parameters = result.get("parameters")
        zone = parameters.get("LActions")
        print(zone)
        print(zone[0])

        cost = {'act1':'116', 'act2':'116', 'act3':'352', 'act4':'139', 'act5':'115', 'act6':'114'}
        speech = "l'action à été lancé."

        if parameters.get("LActionPlus") == "actP2":#Diminuer le volume.
            code = cost['act6']
        elif parameters.get("LActionPlus") == "actP1":#Augmenter le volume.
            code = cost['act5']
        else:
            code = cost[zone[0]]

        liveboxIp = '90.73.151.42:8085'
        url2 = 'http://' + liveboxIp + '/remoteControl/cmd?operation=01&key='

        url = url2 + code + '&mode=0'
        page = urllib.request.urlopen(url)
        strpage = page.read()

        print("Response:")
        print(speech)

        return {
            "speech": speech,
            "displayText": speech,
            #"data": {},
            # "contextOut": [],
            "source": "apiai-worganic-livebox",
            "urlA": url
        }

    else:
        return {}

if __name__ == '__main__':
    port = int(os.getenv('PORT', 5000))

    #print("Starting aa app on port %d" % port)

    app.run(debug=True, port=port, host='0.0.0.0')
<commit_msg>MAJ - ip<commit_after>#!/usr/bin/env python

import urllib
import json
import os
import urllib.request

from flask import Flask
from flask import request
from flask import make_response

# Flask app should start in global layout
app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(silent=True, force=True)

    print("Request:")
    print(json.dumps(req, indent=4))

    res = makeWebhookResult(req)

    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

# http://90.73.151.42:8085/remoteControl/cmd?operation=10
    liveboxIp = '90.73.15.218:8085';
    # url = 'http://' + liveboxIp + '/remoteControl/cmd?operation=';
    url2 = 'http://' + liveboxIp + '/remoteControl/cmd?operation=01&key=116&mode=0';

def makeWebhookResult(req):
    if req.get("result").get("action") == "Livebox-chaine":
        liveboxIp = '90.73.15.218:8085';
        url2 = 'http://' + liveboxIp + '/remoteControl/cmd?operation=01&key=116&mode=0'
        url2 = 'http://' + liveboxIp + '/remoteControl/cmd?operation=01&key='
        result = req.get("result")
        parameters = result.get("parameters")
        zone = parameters.get("ListeDesChaines")
        zone1 = zone[0]

        cost = {'c1':'TF1', 'c2':'France 2', 'c3':'France 3', 'c4':'Canal plus', 'c5':'France 5', 'c6':'M 6'}
        speech = "La chaîne " + str(cost[zone1]) + " va être lancé."

        zone1 = zone1.replace("c", "")
        zone2 = int(zone1)

        code = {0:'512', 1:'513', 2:'514', 3:'515', 4:'516', 5:'517', 6:'518', 7:'519', 8:'520', 9:'521'}

        unite = zone2 % 10
        dizaine = (zone2 % 100) / 10
        centaine = (zone2 % 1000) / 100

        if centaine > 0.9:
            codeA = code[centaine]
            url = url2 + codeA + '&mode=0'
            page = urllib.request.urlopen(url)
            strpage = page.read()

        if dizaine > 0.9:
            codeA = code[dizaine]
            url = url2 + codeA + '&mode=0'
            page = urllib.request.urlopen(url)
            strpage = page.read()

        codeA = code[unite]
        url = url2 + codeA + '&mode=0'
        page = urllib.request.urlopen(url)
        strpage = page.read()

        print("Response:")
        print(speech)

        return {
            "speech": speech,
            "displayText": speech,
            #"data": {},
            # "contextOut": [],
            "source": "apiai-worganic-livebox",
            "urlA": url
        }
    elif req.get("result").get("action") == "Livebox-action":
        result = req.get("result")
        parameters = result.get("parameters")
        zone = parameters.get("LActions")
        print(zone)
        print(zone[0])

        cost = {'act1':'116', 'act2':'116', 'act3':'352', 'act4':'139', 'act5':'115', 'act6':'114'}
        speech = "l'action à été lancé."

        if parameters.get("LActionPlus") == "actP2":#Diminuer le volume.
            code = cost['act6']
        elif parameters.get("LActionPlus") == "actP1":#Augmenter le volume.
            code = cost['act5']
        else:
            code = cost[zone[0]]

        liveboxIp = '90.73.151.42:8085'
        url2 = 'http://' + liveboxIp + '/remoteControl/cmd?operation=01&key='

        url = url2 + code + '&mode=0'
        page = urllib.request.urlopen(url)
        strpage = page.read()

        print("Response:")
        print(speech)

        return {
            "speech": speech,
            "displayText": speech,
            #"data": {},
            # "contextOut": [],
            "source": "apiai-worganic-livebox",
            "urlA": url
        }

    else:
        return {}

if __name__ == '__main__':
    port = int(os.getenv('PORT', 5000))

    #print("Starting aa app on port %d" % port)

    app.run(debug=True, port=port, host='0.0.0.0')
<|endoftext|>


<commit_before>import time

import flask

import mcbench.client
import mcbench.highlighters
import mcbench.xpath

EXAMPLE_QUERIES = (
    ('Calls to eval', "//ParameterizedExpr[is_call('eval')]"),
    ('Calls to feval with a string literal target',
     "//ParameterizedExpr[is_call('feval') and ./*[position()=2 and name(.)='StringLiteralExpr']]"),
    ('Copy statements inside loops', "//ForStmt//AssignStmt[./*[position()=1 and name(.)='NameExpr'] and ./*[position()=2 and name(.)='NameExpr' and ./@kind='VAR']]"),
    ('Recursive calls', '//ParameterizedExpr[is_call(ancestor::Function/@name)]'),
    ('Functions with multiple return values',
     "//Function[./OutputParamList[count(Name) > 1]]"),
)

mcbench.xpath.register_extensions()

app = flask.Flask(__name__)
app.config.from_object('settings')
app.jinja_env.filters['highlight_matlab'] = mcbench.highlighters.matlab
app.jinja_env.filters['highlight_xml'] = mcbench.highlighters.xml
app.jinja_env.filters['pluralize'] = lambda n, s='s': s if n != 1 else ''

mcbench_client = mcbench.client.create_for_app(app)

def redirect(url_name, *args, **kwargs):
    return flask.redirect(flask.url_for(url_name, *args, **kwargs))

def get_valid_query_or_throw():
    query = flask.request.args.get('query') or None
    if query is None:
        return None
    mcbench.xpath.compile(query)
    return query

@app.route('/', methods=['GET'])
def index():
    return flask.render_template('index.html', examples=EXAMPLE_QUERIES)

@app.route('/help', methods=['GET'])
def help():
    return flask.render_template('help.html')

@app.route('/list', methods=['GET'])
def benchmark_list():
    try:
        query = get_valid_query_or_throw()
    except mcbench.xpath.XPathError as e:
        flask.flash(str(e))
        return redirect('index', query=e.query)

    all_benchmarks = mcbench_client.get_all_benchmarks()

    if query is None:
        return flask.render_template('list.html', benchmarks=all_benchmarks)

    start = time.time()
    benchmarks, matches_by_benchmark, num_matches = (
        all_benchmarks.get_num_matches(query))
    elapsed_time = time.time() - start
    benchmarks.sort(key=lambda b: matches_by_benchmark[b.name], reverse=True)

    return flask.render_template(
        'list.html',
        benchmarks=benchmarks,
        elapsed_time=elapsed_time,
        matches_by_benchmark=matches_by_benchmark,
        num_matches=num_matches)

@app.route('/benchmark/<name>', methods=['GET'])
def benchmark(name):
    benchmark = mcbench_client.get_benchmark_by_name(name)

    try:
        query = get_valid_query_or_throw()
        hl_lines = benchmark.get_matching_lines(query)
    except mcbench.xpath.XPathError as e:
        flask.flash(str(e))
        query = None
        hl_lines = benchmark.get_matching_lines(None)

    files = list(benchmark.get_files())
    num_matches = sum(len(v['m']) for v in hl_lines.values())

    return flask.render_template(
        'benchmark.html',
        benchmark=benchmark,
        hl_lines=hl_lines,
        num_matches=num_matches,
        files=files,
    )

if __name__ == "__main__":
    app.run(debug=True)
<commit_msg>Catch XPathError when searching.<commit_after>import time

import flask

import mcbench.client
import mcbench.highlighters
import mcbench.xpath

EXAMPLE_QUERIES = (
    ('Calls to eval', "//ParameterizedExpr[is_call('eval')]"),
    ('Calls to feval with a string literal target',
     "//ParameterizedExpr[is_call('feval') and ./*[position()=2 and name(.)='StringLiteralExpr']]"),
    ('Copy statements inside loops', "//ForStmt//AssignStmt[./*[position()=1 and name(.)='NameExpr'] and ./*[position()=2 and name(.)='NameExpr' and ./@kind='VAR']]"),
    ('Recursive calls', '//ParameterizedExpr[is_call(ancestor::Function/@name)]'),
    ('Functions with multiple return values',
     "//Function[./OutputParamList[count(Name) > 1]]"),
)

mcbench.xpath.register_extensions()

app = flask.Flask(__name__)
app.config.from_object('settings')
app.jinja_env.filters['highlight_matlab'] = mcbench.highlighters.matlab
app.jinja_env.filters['highlight_xml'] = mcbench.highlighters.xml
app.jinja_env.filters['pluralize'] = lambda n, s='s': s if n != 1 else ''

mcbench_client = mcbench.client.create_for_app(app)

def redirect(url_name, *args, **kwargs):
    return flask.redirect(flask.url_for(url_name, *args, **kwargs))

def get_valid_query_or_throw():
    query = flask.request.args.get('query') or None
    if query is None:
        return None
    mcbench.xpath.compile(query)
    return query

@app.route('/', methods=['GET'])
def index():
    return flask.render_template('index.html', examples=EXAMPLE_QUERIES)

@app.route('/help', methods=['GET'])
def help():
    return flask.render_template('help.html')

@app.route('/list', methods=['GET'])
def benchmark_list():
    try:
        query = get_valid_query_or_throw()
    except mcbench.xpath.XPathError as e:
        flask.flash(str(e))
        return redirect('index', query=e.query)

    all_benchmarks = mcbench_client.get_all_benchmarks()

    if query is None:
        return flask.render_template('list.html', benchmarks=all_benchmarks)

    start = time.time()
    try:
        benchmarks, matches_by_benchmark, num_matches = (
            all_benchmarks.get_num_matches(query))
    except mcbench.xpath.XPathError as e:
        flask.flash(str(e))
        return redirect('index', query=e.query)

    elapsed_time = time.time() - start
    benchmarks.sort(key=lambda b: matches_by_benchmark[b.name], reverse=True)

    return flask.render_template(
        'list.html',
        benchmarks=benchmarks,
        elapsed_time=elapsed_time,
        matches_by_benchmark=matches_by_benchmark,
        num_matches=num_matches)

@app.route('/benchmark/<name>', methods=['GET'])
def benchmark(name):
    benchmark = mcbench_client.get_benchmark_by_name(name)

    try:
        query = get_valid_query_or_throw()
        hl_lines = benchmark.get_matching_lines(query)
    except mcbench.xpath.XPathError as e:
        flask.flash(str(e))
        query = None
        hl_lines = benchmark.get_matching_lines(None)

    files = list(benchmark.get_files())
    num_matches = sum(len(v['m']) for v in hl_lines.values())

    return flask.render_template(
        'benchmark.html',
        benchmark=benchmark,
        hl_lines=hl_lines,
        num_matches=num_matches,
        files=files,
    )

if __name__ == "__main__":
    app.run(debug=True)
<|endoftext|>


<commit_before>#!/usr/bin/env python

from __future__ import print_function
from future.standard_library import install_aliases
install_aliases()

from urllib.parse import urlparse, urlencode
from urllib.request import urlopen, Request
from urllib.error import HTTPError

import json
import os
import random

import re #retira etiquetas HTML de la descripción

from flask import Flask
from flask import request
from flask import make_response

# Flask app should start in global layout
app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(silent=True, force=True)

    print("Request:")
    print(json.dumps(req, indent=4))

    res = makeWebhookResult(req)#Invoca función de consulta y muestra speech al situr3

    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

def listadoBusqueda(urlBaseJson):
    pruebatitulos = ""
    varComa = 0
    for x in range(0,len(urlBaseJson)):
        tituloItem = urlBaseJson[x]['title']['rendered']
        imagenDefAtractivos = urlBaseJson[x]['better_featured_image']['media_details']['sizes']['medium']['source_url']
#        descripcionItem = re.sub("<.*?>", "", (urlBaseJson[x]['excerpt']['rendered'])[0:85])#Descripción del atractivo eliminando etiquetas
        if varComa < len(urlBaseJson)-1:
            varComa = varComa +1
            print (varComa)
            comaJson = ","
        else:
            comaJson = ""
        pruebatitulos = pruebatitulos + ("""                            {
                                "title" : \""""+tituloItem+"""\",
                                "image_url" : \""""+imagenDefAtractivos+"""\",
                                "subtitle": \""""+tituloItem+"""\",
                                "buttons":  [
                                    {
                                        "type":"web_url",
                                        "url": \""""+urlBaseJson[x]['link']+"""\",
                                        "title": "Ver en SITUR"
                                    }
                                ]
                            }""" + str(comaJson) + """""")

    resultadoMauricio = inicioFBCard+pruebatitulos+finFBCard
#    resultadoMauricio = json.dumps(resultadoMauricio)
    resultadoMauricio = json.loads(resultadoMauricio)
    return resultadoMauricio

inicioFBCard = '{"facebook" : {"attachment" : {"type" : "template","payload" : {"template_type" : "generic","elements" : ['

finFBCard = ']}}}}'

def

def makeWebhookResult(req):
    accionEntrante=req.get("result").get("action")
    if accionEntrante == "buscarAtractivos":
        result = req.get("result")#invocar el result del json
        parameters = result.get("parameters")#invocar el parameters dentro de result
        atractivos = parameters.get("atractivos")#DATO TRAÍDO DE API.AI - ATRACTIVOS

        #URL BASE CONSULTA ATRACTIVOS JSON
        baseUrlAtractivos = "http://situr.boyaca.gov.co/wp-json/wp/v2/atractivo_turistico?per_page=10&orderby=relevance&search="#URL Base Atractivos

        speech = "Mira 😃, soy un atractivo conocido como: " + accionEntrante

    mensajeuno = ["msg1","msg2","msg3"]
    mensajebusqueda="random.choice(mensajeuno)"

    retirarEspacios = atractivos.replace(" ",  "%20")#Retirar Espacios Atractivos

    leerAtractivo = json.loads(urlopen(baseUrlAtractivos + retirarEspacios).read())
    cantidadResultados = str(len(leerAtractivo))#Contar Cantidad de Resultados Encontrados

#    speech = "Mira 😃, encontré " + cantidadResultados+ " resultados"

    ##### ACA DEBE TERMINARSE LA FUNCIÓN LOCAL

    print("Response:")
    print(speech)

    return {
        "speech": "",
        "messages": [
        {
        "type": 0,
        "platform": "facebook",
        "speech": mensajebusqueda
#        "speech": "Dame un momento, estoy buscando entre mis archivos...🔍"
        },
        {
        "type": 0,
        "platform": "facebook",
        "speech": speech
        },
        {
          "type": 4,
          "platform": "facebook",
          "payload": listadoBusqueda(leerAtractivo)
        }
#        {
#          "type": 2,
#          "platform": "facebook",
#          "title": "Por favor escoge un elemento",
#          "replies": [
#            "Ver más"
#          ]
#        },
#        {
#          "type": 2,
#          "platform": "facebook",
#          "title": "Por favor escoge un elemento",
#         "replies": [
#            "Ver más"
#          ]
#        }
        ],
#        "speech": speech,
#        "displayText": speech,
#        "data" :listadoBusqueda(leerAtractivo),
#        "data" :fbMsg2,
#        "contextOut": [],
        "contextOut": [{"name":"desdepython", "lifespan":2}],
        "source": "soy-un-dato-irrelevante"
#        "source": listadoBusqueda(leerAtractivo)
    }

"""    return {
        "speech": "",
        "messages": [
        {
        "type": 0,
        "platform": "facebook",
        "speech": "Dame un momento, estoy buscando entre mis archivos..."
        },
        {
        "type": 0,
        "platform": "facebook",
        "speech": speech
        },
        {
          "type": 4,
          "platform": "facebook",
          "payload": {
            "facebook": {
              "attachment": {
                "type": "template",
                "payload": {
                  "template_type": "generic",
                  "elements": [
                    {
                      "title": "HE VUELTO y con más",
                      "image_url": "http://www.boyaca.gov.co/SecCultura/images/MARCA%20REGION%20BOYACA%20ES%20PARA%20VIVIRLA-1.jpg",
                      "subtitle": "soy la descripcion",
                      "buttons": [
                        {
                          "type": "web_url",
                          "url": "http://situr.boyaca.gov.co",
                          "title": "boton1"
                        },
                        {
                          "type": "web_url",
                          "url": "http://situr.boyaca.gov.co",
                          "title": "boton2"
                        },
                        {
                          "type": "web_url",
                          "url": "http://situr.boyaca.gov.co",
                          "title": "boton3"
                        }
                      ]
                    },
                    {
                      "title": "soy el otro titulo",
                      "image_url": "https://www.dondevive.org/wp-content/uploads/2015/08/donde-viven-los-conejos.jpg",
                      "subtitle": "soy la descripción",
                      "default_action": {
                        "type": "web_url",
                        "url": "https://www.moovrika.com/m/4167",
                        "webview_height_ratio": "tall"
                      },
                      "buttons": [
                        {
                          "title": "más info",
                          "type": "web_url",
                          "url": "https://www.moovrika.com/m/4082",
                          "webview_height_ratio": "tall"
                        },
                        {
                          "type": "web_url",
                          "url": "http://situr.boyaca.gov.co",
                          "title": "boton2"
                        },
                        {
                          "type": "web_url",
                          "url": "http://situr.boyaca.gov.co",
                          "title": "boton3"
                        }
                      ]
                    }
                  ]
                }
              }
            }
          }
        },
        {
          "type": 2,
          "platform": "facebook",
          "title": "Por favor escoge un elemento",
          "replies": [
            "blanco",
            "gris",
            "negro"
          ]
        }
        ],
#        "speech": speech,
#        "displayText": speech,
#        "data" :listadoBusqueda(leerAtractivo),
#        "data" :fbMsg2,
#        "contextOut": [],
        "contextOut": [{"name":"desdepython", "lifespan":2}],
        "source": "soy-un-dato-irrelevante"
#        "source": listadoBusqueda(leerAtractivo)
    }"""

if __name__ == '__main__':
    port = int(os.getenv('PORT', 5000))

    print("Starting app on port %d" % port)

    app.run(debug=False, port=port, host='0.0.0.0')
<commit_msg>sdfdsf<commit_after>#!/usr/bin/env python

from __future__ import print_function
from future.standard_library import install_aliases
install_aliases()

from urllib.parse import urlparse, urlencode
from urllib.request import urlopen, Request
from urllib.error import HTTPError

import json
import os
import random

import re #retira etiquetas HTML de la descripción

from flask import Flask
from flask import request
from flask import make_response

# Flask app should start in global layout
app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(silent=True, force=True)

    print("Request:")
    print(json.dumps(req, indent=4))

    res = makeWebhookResult(req)#Invoca función de consulta y muestra speech al situr3

    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

def listadoBusqueda(urlBaseJson):
    pruebatitulos = ""
    varComa = 0
    for x in range(0,len(urlBaseJson)):
        tituloItem = urlBaseJson[x]['title']['rendered']
        imagenDefAtractivos = urlBaseJson[x]['better_featured_image']['media_details']['sizes']['medium']['source_url']
#        descripcionItem = re.sub("<.*?>", "", (urlBaseJson[x]['excerpt']['rendered'])[0:85])#Descripción del atractivo eliminando etiquetas
        if varComa < len(urlBaseJson)-1:
            varComa = varComa +1
            print (varComa)
            comaJson = ","
        else:
            comaJson = ""
        pruebatitulos = pruebatitulos + ("""                            {
                                "title" : \""""+tituloItem+"""\",
                                "image_url" : \""""+imagenDefAtractivos+"""\",
                                "subtitle": \""""+tituloItem+"""\",
                                "buttons":  [
                                    {
                                        "type":"web_url",
                                        "url": \""""+urlBaseJson[x]['link']+"""\",
                                        "title": "Ver en SITUR"
                                    }
                                ]
                            }""" + str(comaJson) + """""")

    resultadoMauricio = inicioFBCard+pruebatitulos+finFBCard
#    resultadoMauricio = json.dumps(resultadoMauricio)
    resultadoMauricio = json.loads(resultadoMauricio)
    return resultadoMauricio

inicioFBCard = '{"facebook" : {"attachment" : {"type" : "template","payload" : {"template_type" : "generic","elements" : ['

finFBCard = ']}}}}'

def

def makeWebhookResult(req):
    accionEntrante=req.get("result").get("action")
    if accionEntrante == "buscarAtractivos":
        result = req.get("result")#invocar el result del json
        parameters = result.get("parameters")#invocar el parameters dentro de result
        atractivos = parameters.get("atractivos")#DATO TRAÍDO DE API.AI - ATRACTIVOS

        #URL BASE CONSULTA ATRACTIVOS JSON
        baseUrlAtractivos = "http://situr.boyaca.gov.co/wp-json/wp/v2/atractivo_turistico?per_page=10&orderby=relevance&search="#URL Base Atractivos

        speech = "Mira 😃, soy un atractivo conocido como: " + accionEntrante
        speech5 = "Soy el mensaje de entrada "

#    mensajeuno = ["msg1","msg2","msg3"]

    retirarEspacios = atractivos.replace(" ",  "%20")#Retirar Espacios Atractivos

    leerAtractivo = json.loads(urlopen(baseUrlAtractivos + retirarEspacios).read())
    cantidadResultados = str(len(leerAtractivo))#Contar Cantidad de Resultados Encontrados

#    speech = "Mira 😃, encontré " + cantidadResultados+ " resultados"

    ##### ACA DEBE TERMINARSE LA FUNCIÓN LOCAL

    print("Response:")
    print(speech)

    return {
        "speech": "",
        "messages": [
        {
        "type": 0,
        "platform": "facebook",
        "speech": speech5
#        "speech": "Dame un momento, estoy buscando entre mis archivos...🔍"
        },
        {
        "type": 0,
        "platform": "facebook",
        "speech": speech
        },
        {
          "type": 4,
          "platform": "facebook",
          "payload": listadoBusqueda(leerAtractivo)
        }
#        {
#          "type": 2,
#          "platform": "facebook",
#          "title": "Por favor escoge un elemento",
#          "replies": [
#            "Ver más"
#          ]
#        },
#        {
#          "type": 2,
#          "platform": "facebook",
#          "title": "Por favor escoge un elemento",
#         "replies": [
#            "Ver más"
#          ]
#        }
        ],
#        "speech": speech,
#        "displayText": speech,
#        "data" :listadoBusqueda(leerAtractivo),
#        "data" :fbMsg2,
#        "contextOut": [],
        "contextOut": [{"name":"desdepython", "lifespan":2}],
        "source": "soy-un-dato-irrelevante"
#        "source": listadoBusqueda(leerAtractivo)
    }

"""    return {
        "speech": "",
        "messages": [
        {
        "type": 0,
        "platform": "facebook",
        "speech": "Dame un momento, estoy buscando entre mis archivos..."
        },
        {
        "type": 0,
        "platform": "facebook",
        "speech": speech
        },
        {
          "type": 4,
          "platform": "facebook",
          "payload": {
            "facebook": {
              "attachment": {
                "type": "template",
                "payload": {
                  "template_type": "generic",
                  "elements": [
                    {
                      "title": "HE VUELTO y con más",
                      "image_url": "http://www.boyaca.gov.co/SecCultura/images/MARCA%20REGION%20BOYACA%20ES%20PARA%20VIVIRLA-1.jpg",
                      "subtitle": "soy la descripcion",
                      "buttons": [
                        {
                          "type": "web_url",
                          "url": "http://situr.boyaca.gov.co",
                          "title": "boton1"
                        },
                        {
                          "type": "web_url",
                          "url": "http://situr.boyaca.gov.co",
                          "title": "boton2"
                        },
                        {
                          "type": "web_url",
                          "url": "http://situr.boyaca.gov.co",
                          "title": "boton3"
                        }
                      ]
                    },
                    {
                      "title": "soy el otro titulo",
                      "image_url": "https://www.dondevive.org/wp-content/uploads/2015/08/donde-viven-los-conejos.jpg",
                      "subtitle": "soy la descripción",
                      "default_action": {
                        "type": "web_url",
                        "url": "https://www.moovrika.com/m/4167",
                        "webview_height_ratio": "tall"
                      },
                      "buttons": [
                        {
                          "title": "más info",
                          "type": "web_url",
                          "url": "https://www.moovrika.com/m/4082",
                          "webview_height_ratio": "tall"
                        },
                        {
                          "type": "web_url",
                          "url": "http://situr.boyaca.gov.co",
                          "title": "boton2"
                        },
                        {
                          "type": "web_url",
                          "url": "http://situr.boyaca.gov.co",
                          "title": "boton3"
                        }
                      ]
                    }
                  ]
                }
              }
            }
          }
        },
        {
          "type": 2,
          "platform": "facebook",
          "title": "Por favor escoge un elemento",
          "replies": [
            "blanco",
            "gris",
            "negro"
          ]
        }
        ],
#        "speech": speech,
#        "displayText": speech,
#        "data" :listadoBusqueda(leerAtractivo),
#        "data" :fbMsg2,
#        "contextOut": [],
        "contextOut": [{"name":"desdepython", "lifespan":2}],
        "source": "soy-un-dato-irrelevante"
#        "source": listadoBusqueda(leerAtractivo)
    }"""

if __name__ == '__main__':
    port = int(os.getenv('PORT', 5000))

    print("Starting app on port %d" % port)

    app.run(debug=False, port=port, host='0.0.0.0')
<|endoftext|>