# Path: pystil/utils.py
# def try_decode(astring):
#     """Try decoding a string in various encodings, with a fallback to good old
#     ascii."""
#     if isinstance(astring, str):
#         return astring
#     for encoding in ('utf8', 'latin'):
#         try:
#             return astring.decode(encoding)
#         except UnicodeDecodeError:
#             pass
#     return astring.decode('ascii', 'ignore')
# 
# def parse_ua(user_agent):
#     """Parse the user agent to return the platform, browser and version"""
#     for platform, regex in PLATFORMS:
#         match = regex.search(user_agent)
#         if match is not None:
#             break
#     else:
#         platform = ''
#     for browser, regex in BROWSERS:
#         match = regex.search(user_agent)
#         if match is not None:
#             version = match.group(1)
#             break
#     else:
#         browser = version = ''
#     return platform, browser, version
# 
# def parse_referrer(referrer, with_query=False, host_only=False,
#                    second_pass=False):
#     """Return a pretty format for most search engines"""
#     if referrer:
#         up = urlparse(referrer)
#         netloc = up.netloc
#         if not netloc:
#             if with_query:
#                 return u"Local: %s" % up.path
#             if second_pass:
#                 return referrer
#             return "Local"
# 
#         query = up.query
#         parsed = parse_qs(query)
#         search = parsed.get('q', parsed.get('p', parsed.get('rdata', None)))
#         if search:
#             # TODO Yahoo variable encoding
#             if with_query:
#                 return u"Organic: %s %s" % (netloc, try_decode(search[0]))
#             return u"Organic: %s" % netloc
#         if host_only:
#             return netloc
#         return referrer
#     return "Direct"
# 
# def parse_domain(referrer):
#     """Return the domain of the given referrer."""
#     if referrer:
#         up = urlparse(referrer)
#         netloc = up.netloc
#         return netloc or "Local"
#     return "Direct"
# 
# Path: pystil/db.py
# def string(pkey=False):
# def integer(pkey=False):
# def decimal():
# def datetime():
# def date_column(pkey=False):
# class Visit(Base):
# class CriterionView(Base):


from pystil.utils import (
    try_decode, parse_ua, parse_referrer, parse_domain)
from pystil.db import Visit, country, city, asn, VisitIdSeq
from datetime import datetime, timedelta
from sqlalchemy import desc, select
                     'browser_name': browser,
                     'browser_version': version,
                     'platform': platform}

            lat = None
            lng = None
            city_name = None
            country_code = None
            country_name = None
            asn_name = None

            if self.ip.startswith('::ffff'):
                self.ip = self.ip.replace('::ffff:', '')

            if (self.ip == '127.0.0.1' or
                    self.ip.startswith('192.168.') or
                    self.ip.startswith('10.')):
                city_name = 'Local'
                country_name = 'Local'
                asn_name = 'Local'
            elif self.ip != 'unknown':
                countries = list(db.execute(
                    country.select().where(
                        country.c.ipr.op('>>=')(visit['ip']))))

                if len(countries) > 0:
                    country_name = countries[0].country_name
                    country_code = countries[0].country_code
                    cities = list(db.execute(
                        city.select().where(

# Path: pystil/utils.py
# def try_decode(astring):
#     """Try decoding a string in various encodings, with a fallback to good old
#     ascii."""
#     if isinstance(astring, str):
#         return astring
#     for encoding in ('utf8', 'latin'):
#         try:
#             return astring.decode(encoding)
#         except UnicodeDecodeError:
#             pass
#     return astring.decode('ascii', 'ignore')
# 
# def parse_ua(user_agent):
#     """Parse the user agent to return the platform, browser and version"""
#     for platform, regex in PLATFORMS:
#         match = regex.search(user_agent)
#         if match is not None:
#             break
#     else:
#         platform = ''
#     for browser, regex in BROWSERS:
#         match = regex.search(user_agent)
#         if match is not None:
#             version = match.group(1)
#             break
#     else:
#         browser = version = ''
#     return platform, browser, version
# 
# def parse_referrer(referrer, with_query=False, host_only=False,
#                    second_pass=False):
#     """Return a pretty format for most search engines"""
#     if referrer:
#         up = urlparse(referrer)
#         netloc = up.netloc
#         if not netloc:
#             if with_query:
#                 return u"Local: %s" % up.path
#             if second_pass:
#                 return referrer
#             return "Local"
# 
#         query = up.query
#         parsed = parse_qs(query)
#         search = parsed.get('q', parsed.get('p', parsed.get('rdata', None)))
#         if search:
#             # TODO Yahoo variable encoding
#             if with_query:
#                 return u"Organic: %s %s" % (netloc, try_decode(search[0]))
#             return u"Organic: %s" % netloc
#         if host_only:
#             return netloc
#         return referrer
#     return "Direct"
# 
# def parse_domain(referrer):
#     """Return the domain of the given referrer."""
#     if referrer:
#         up = urlparse(referrer)
#         netloc = up.netloc
#         return netloc or "Local"
#     return "Direct"
# 
# Path: pystil/db.py
# def string(pkey=False):
# def integer(pkey=False):
# def decimal():
# def datetime():
# def date_column(pkey=False):
# class Visit(Base):
# class CriterionView(Base):


# Path: pystil/tracking.py
from pystil.utils import (
    try_decode, parse_ua, parse_referrer, parse_domain)
from pystil.db import Visit, country, city, asn, VisitIdSeq
from datetime import datetime, timedelta
from sqlalchemy import desc, select

                     'browser_name': browser,
                     'browser_version': version,
                     'platform': platform}

            lat = None
            lng = None
            city_name = None
            country_code = None
            country_name = None
            asn_name = None

            if self.ip.startswith('::ffff'):
                self.ip = self.ip.replace('::ffff:', '')

            if (self.ip == '127.0.0.1' or
                    self.ip.startswith('192.168.') or
                    self.ip.startswith('10.')):
                city_name = 'Local'
                country_name = 'Local'
                asn_name = 'Local'
            elif self.ip != 'unknown':
                countries = list(db.execute(
                    country.select().where(
                        country.c.ipr.op('>>=')(visit['ip']))))

                if len(countries) > 0:
                    country_name = countries[0].country_name
                    country_code = countries[0].country_code
                    cities = list(db.execute(
                        city.select().where(

                            city.c.ipr.op('>>=')(visit['ip']))))