Пример #1
0
    def __call__(self, environ, start_response):
        """ 
        Debug this request.
        """ 
        from dbgp import client
        if self.brk:
            # breaks on uncaught exceptions
            client.brkOnExcept(self.host, self.port, self.idekey)
        else:
            # breaks on the next executed line
            client.brk(self.host, self.port, self.idekey)

            # we might want to do this, but you end up in some random middleware
            # and it's not the best experience.  Instead, break here, go
            # set some breakpoints where you want to debug, the continue

            #c = client.backendCmd(self.idekey)
            #c.stdin_enabled = 0
            #c.connect(self.host, self.port, 'application', [__file__])
            #
            ## despite it's name, this is how to run a function, it does not
            ## start a thread
            #return c.runThread(self.app, (environ, start_response), {})

        # run the app now, if you've stopped here in a debugger, I suggest
        # you go set some breakpoints and continue to those.
        return self.app(environ, start_response)
Пример #2
0
    def __call__(self, environ, start_response):
        """ 
        Debug this request.
        """
        from dbgp import client
        if self.brk:
            # breaks on uncaught exceptions
            client.brkOnExcept(self.host, self.port, self.idekey)
        else:
            # breaks on the next executed line
            client.brk(self.host, self.port, self.idekey)

            # we might want to do this, but you end up in some random middleware
            # and it's not the best experience.  Instead, break here, go
            # set some breakpoints where you want to debug, the continue

            #c = client.backendCmd(self.idekey)
            #c.stdin_enabled = 0
            #c.connect(self.host, self.port, 'application', [__file__])
            #
            ## despite it's name, this is how to run a function, it does not
            ## start a thread
            #return c.runThread(self.app, (environ, start_response), {})

        # run the app now, if you've stopped here in a debugger, I suggest
        # you go set some breakpoints and continue to those.
        return self.app(environ, start_response)
Пример #3
0
def exprToDict(expr, query):
    try:
        t = translate(expr)
        rv = t.mongo(query)
        return rv
    except AttributeError:
        from dbgp.client import brk
        brk('127.0.0.1')
Пример #4
0
    def mongo(self, query, name=None):
        if name is None:
            name = self.mongoName(query)
        expr = str(self._ast)

        try:
            query.groupOptions['reduce'].append("out.%s = %s;" % (name, expr))
        except:
            from dbgp.client import brk
            brk('127.0.0.1')
Пример #5
0
 def setattr(self, info, object, name, value):
   """Update the inspector when the selected region changes."""
   ss = object.region.getSelf()
   ds = ss.dataSource
   #from dbgp.client import brk; brk(port=9011)
   if name == 'filePath':
     assert False
     from dbgp.client import brk; brk(port=9011)
   elif name == 'loadFile':
     ds.open(value)
     object.filePath = value
   else:
     RegionInspectorTabHandler.setattr(self, info, object, name, value)
  def _iteration_changed(self):
    """
    Called automatically by Traits when the iteration updates.

    Update the progress bar and check the conditions to see whether to stop or
    pause.
    """
    if self.showProgressBar:
      try:
        self._setProgress()
      except:
        # may fail when switching from training to inference
        from dbgp.client import brk; brk(port=9011)
        pass
    def _iteration_changed(self):
        """
    Called automatically by Traits when the iteration updates.

    Update the progress bar and check the conditions to see whether to stop or
    pause.
    """
        if self.showProgressBar:
            try:
                self._setProgress()
            except:
                # may fail when switching from training to inference
                from dbgp.client import brk
                brk(port=9011)
                pass
def moderate_comment(sender, comment, request, **kwargs): 
     if not comment.id:
         brk(host="localhost",port=53891)
         mail_managers("New comment posted", email_body % (comment.name, comment.content_object))

         entry = comment.content_object
         delta = datetime.datetime.now(timezone.utc) - entry.pub_date
         if delta.days > 30:
             comment.is_public = False
         else:
             akismet_api = Akismet(key=settings.AKISMET_API_KEY, blog_url="http:/%s/" %Site.objects.get_current().domain)
             if akismet_api.verify_key():
                 akismet_data = { 'comment_type': 'comment',
                                  'referrer': request.META['HTTP_REFERER'],
                                  'user_ip': comment.ip_address,
                                  'user-agent': request.META['HTTP_USER_AGENT'] }
                 if akismet_api.comment_check(smart_str(comment.comment),
                                             akismet_data,
                                             build_data=True):
                     comment.is_public = False
         email_body = "%s posted a new comment on the entry '%s'."
         mail_managers("New comment posted", email_body % (comment.name, comment.content_object))
Пример #9
0
class RepoPkgError(BaseException):
    pass



loglevel = logging.INFO
if os.environ.get('_DEBUG_',"False") == "True":   
    loglevel = logging.DEBUG
    
#KomodoIDE Remote Debugging
remote_brk = lambda: sys.stdout.write("remote break")
if os.environ.get("_REMOTE_DEBUG_",'False') == 'True':
    try:
        from dbgp.client import brk
        remote_brk = lambda: brk(host=os.environ.get("REMOTE_DEBUG_HOST","127.0.0.1"),
                                 port=int(os.environ.get("REMOTE_DEBUG_PORT",'9000')))
    except:
        pass

logging.basicConfig(level=loglevel)
LOG = logging.getLogger(__name__)


class RepoUser(object):
    _config_fields = []
    def __init__(self):
        self.login = os.environ.get("USERNAME",os.environ.get("USER"))
        self.home = os.environ.get("USERPROFILE",os.environ.get("HOME")).replace('\\','/')
        self.ssh_key = posixpath.join(self.home,".ssh","id_rsa").replace("\\","/")
        self.hostname = socket.gethostname()
        self.ip = socket.gethostbyname(self.hostname)
Пример #10
0
    def process_record(self, record):
        if record['type'].startswith('statement'):
            if 'create' in record['command'].lower():
                p = select_parser.create_stmt.parseString(record['command'])
                columns = p.columns.asList()
                table = p.asList()[2]
                self.columns[table] = columns

                cur = self.con.cursor()
                cur.execute(record['command'])
                cur.close()

            elif 'insert' in record['command'].lower():
                p = select_parser.insert_stmt.parseString(record['command'])
                table = p.asList()[2]
                columns = p.asList()[3]
                values = p.asList()[5]
                data = dict((str(c), v) for c, v in zip(columns, values))

                cur = self.con.cursor()
                cur.execute(record['command'])
                cur.close()

                self.db[str(table)].insert(data)
            else:
                # huhh?
                pass
        elif record['type'].startswith('query'):
            cur = self.con.cursor()
            cur.execute(record['command'])
            sresults = list(cur.fetchall())
            cur.close()

            typeparts = record['type'].split()
            query = typeparts[0]
            types = typeparts[1]
            sortnosort = typeparts[2]
            cmd = record['command']
            __traceback_info__ = pformat(record)
            ucmd = cmd.upper()
            for uns in UNSUPPORTED:
                if uns in ucmd:
                    self.counts['unsupported'] += 1
                    return
            if ucmd.count('SELECT') > 1:
                self.counts['unsupported'] += 1
                return

            try:
                q = tomongo.Query(record['command'])
            except tomongo.Unsupported:
                self.counts['unsupported'] += 1
                return
            record['debug'] = q.dump()
            __traceback_info__ = pformat(record)
            try:
                mresults = list(q.execute(self.db))
                mresults = list(q.sqlresults(mresults))
                if len(mresults) > 0:
                    first = mresults[0]
                    coltypes = ''.join([TYPE_TO_STR[type(fv)] for fv in first])
                    if coltypes != types:
                        print 'Column types mismatch expected: %s vs %s' % (
                            types, coltypes)
                        self.counts['failed'] += 1
                        raise ValueError()
            except tomongo.Unsupported:
                self.counts['unsupported'] += 1
                return
            except:
                print
                print q.dump()
                self.counts['failed'] += 1
                raise

            if sortnosort != 'nosort':
                print 'Dunno how to sort this'
                self.counts['failed'] += 1

            if 'hashing to' in record['results']:
                parts = record['results'].split()
                vcount = int(parts[0])
                rcount = vcount / len(types)
                if rcount != len(mresults):
                    print q.dump()
                    print 'Record count mismatch expected: %s vs %s' % (
                            rcount, len(mresults))
                    self.counts['failed'] += 1

                    raise ValueError()

                # looks like sqllogictest uses the raw bytes of the result
                # to MD5 check... that's going to be impossible to repro
                #hsh = md5()
                #for mr in mresults:
                #    hsh.update(str(mr))
                #    hsh.update('\n')
                #hsh = hsh.hexdigest()

                # let's compare the sqlite and mongo resultset
                haveerr = False
                for rowidx, (mrow, srow) in enumerate(zip(mresults, sresults)):
                    for itemidx, (mi, si) in enumerate(zip(mrow, srow)):
                        if mi != si:
                            print 'Result value mismatch at row %s, item %s, %r vs %r' % (rowidx+1, itemidx+1, mi, si)
                            haveerr = True
                if haveerr:
                    self.counts['failed'] += 1
                    raise ValueError()
            else:
                from dbgp.client import brk; brk('127.0.0.1')

        self.counts['done'] += 1
Пример #11
0
 def set_trace(self):
     from dbgp.client import brk
     if not self.started:
         print >> sys.stderr, 'Starting dbgp client (pid=%d)' % os.getpid()
         brk(host=self.host, port=self.port)
         self.started = True
Пример #12
0
def run_example():

    # setup
    print '** OAuth Python Library Example **'
    client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, AUTHORIZATION_URL)
    consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
    signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT()
    signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
    pause()

    # get request token
    print '* Obtain a request token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, callback=CALLBACK_URL, http_url=client.request_token_url)
    oauth_request.sign_request(signature_method_plaintext, consumer, None)
    print 'REQUEST (via headers)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    
    #from dbgp.client import brk; brk()
    
    token = client.fetch_request_token(oauth_request)
    print 'GOT'
    print 'key: %s' % str(token.key)
    print 'secret: %s' % str(token.secret)
    print 'callback confirmed? %s' % str(token.callback_confirmed)
    pause()

    print '* Authorize the request token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_token_and_callback(token=token, http_url=client.authorization_url)
    print 'REQUEST (via url query string)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    
    from dbgp.client import brk; brk()
    
    # this will actually occur only on some callback
    response = client.authorize_token(oauth_request)
    print 'GOT'
    print response
    
    
    
    # sad way to get the verifier
    import urlparse, cgi
    
    query = urlparse.urlparse(response)[4]
    params = cgi.parse_qs(query, keep_blank_values=False)
    
    verifier = params['oauth_verifier'][0]
    print 'verifier: %s' % verifier
    pause()

    # get access token
    print '* Obtain an access token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=token, verifier=verifier, http_url=client.access_token_url)
    oauth_request.sign_request(signature_method_plaintext, consumer, token)
    print 'REQUEST (via headers)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    token = client.fetch_access_token(oauth_request)
    print 'GOT'
    print 'key: %s' % str(token.key)
    print 'secret: %s' % str(token.secret)
    pause()

    # access some protected resources
    print '* Access protected resources ...'
    pause()
    #parameters = {'file': 'vacation.jpg', 'size': 'original'} # resource specific params
    
    parameters = {}
    
    url = RESOURCE_URL + "account.xml"
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=token, http_method='POST', http_url=url, parameters=parameters)
    oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
    print 'REQUEST (via post body)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    params = client.access_resource(oauth_request)
    print 'GOT'
    print 'non-oauth parameters: %s' % params
    pause()
Пример #13
0
data_folder = 'Data'
ANNOTATION_FILE_NAME = 'annotation2.png'
SETTINGS_TABLE = {
    'LOCAL_HOME': '',
    'LOCAL_DATA': '',
    'IM_DIR': '',
    'OS_TYPE': ''
}
settings_file = './settings.txt'

if (DEBUG_VERSION):  #for cgi debugging
    sys.path.append(
        'C:\\Komodo-PythonRemoteDebugging-8.5.3-83298-win32-x86\\pythonlib')
    from dbgp.client import brk
    brk(
        host="localhost", port=51460
    )  #sets hard breakpoint (port number should match value for Port from 'Debug->Listener Status' in Komodo)


def read_settings():
    try:
        f = open(settings_file, 'r')
    except (IOError):
        return 'Could not open ' + '"' + settings_file + '" for reading.\n'

    for line in f:
        line = line.strip()
        if (line and
                line[0] != '#'):  #ignore lines beginning with # as comments
            m = re.match(r'([A-Z_]+)\s*=\s*(.+)', line)
            if (m):
Пример #14
0
 def on_register(request):
     from dbgp.client import brk; brk("192.168.1.2", 9090)
     if not request.args.get('name', False):
         return "Missing name"
Пример #15
0
 def index(request):
     from dbgp.client import brk; brk("192.168.1.2", 9090)
     return "index"
Пример #16
0
    def process_record(self, record):
        if record['type'].startswith('statement'):
            if 'create' in record['command'].lower():
                p = select_parser.create_stmt.parseString(record['command'])
                columns = p.columns.asList()
                table = p.asList()[2]
                self.columns[table] = columns

                cur = self.con.cursor()
                cur.execute(record['command'])
                cur.close()

            elif 'insert' in record['command'].lower():
                p = select_parser.insert_stmt.parseString(record['command'])
                table = p.asList()[2]
                columns = p.asList()[3]
                values = p.asList()[5]
                data = dict((str(c), v) for c, v in zip(columns, values))

                cur = self.con.cursor()
                cur.execute(record['command'])
                cur.close()

                self.db[str(table)].insert(data)
            else:
                # huhh?
                pass
        elif record['type'].startswith('query'):
            cur = self.con.cursor()
            cur.execute(record['command'])
            sresults = list(cur.fetchall())
            cur.close()

            typeparts = record['type'].split()
            query = typeparts[0]
            types = typeparts[1]
            sortnosort = typeparts[2]
            cmd = record['command']
            __traceback_info__ = pformat(record)
            ucmd = cmd.upper()
            for uns in UNSUPPORTED:
                if uns in ucmd:
                    self.counts['unsupported'] += 1
                    return
            if ucmd.count('SELECT') > 1:
                self.counts['unsupported'] += 1
                return

            try:
                q = tomongo.Query(record['command'])
            except tomongo.Unsupported:
                self.counts['unsupported'] += 1
                return
            record['debug'] = q.dump()
            __traceback_info__ = pformat(record)
            try:
                mresults = list(q.execute(self.db))
                mresults = list(q.sqlresults(mresults))
                if len(mresults) > 0:
                    first = mresults[0]
                    coltypes = ''.join([TYPE_TO_STR[type(fv)] for fv in first])
                    if coltypes != types:
                        print 'Column types mismatch expected: %s vs %s' % (
                            types, coltypes)
                        self.counts['failed'] += 1
                        raise ValueError()
            except tomongo.Unsupported:
                self.counts['unsupported'] += 1
                return
            except:
                print
                print q.dump()
                self.counts['failed'] += 1
                raise

            if sortnosort != 'nosort':
                print 'Dunno how to sort this'
                self.counts['failed'] += 1

            if 'hashing to' in record['results']:
                parts = record['results'].split()
                vcount = int(parts[0])
                rcount = vcount / len(types)
                if rcount != len(mresults):
                    print q.dump()
                    print 'Record count mismatch expected: %s vs %s' % (
                        rcount, len(mresults))
                    self.counts['failed'] += 1

                    raise ValueError()

                # looks like sqllogictest uses the raw bytes of the result
                # to MD5 check... that's going to be impossible to repro
                #hsh = md5()
                #for mr in mresults:
                #    hsh.update(str(mr))
                #    hsh.update('\n')
                #hsh = hsh.hexdigest()

                # let's compare the sqlite and mongo resultset
                haveerr = False
                for rowidx, (mrow, srow) in enumerate(zip(mresults, sresults)):
                    for itemidx, (mi, si) in enumerate(zip(mrow, srow)):
                        if mi != si:
                            print 'Result value mismatch at row %s, item %s, %r vs %r' % (
                                rowidx + 1, itemidx + 1, mi, si)
                            haveerr = True
                if haveerr:
                    self.counts['failed'] += 1
                    raise ValueError()
            else:
                from dbgp.client import brk
                brk('127.0.0.1')

        self.counts['done'] += 1