def setUp(self):
     super(QPixmapQDatastream, self).setUp()
     self.source_pixmap = QPixmap(100, 100)
     self.source_pixmap.fill(Qt.red)
     self.output_pixmap = QPixmap()
     self.buffer = QByteArray()
     self.read_stream = QDataStream(self.buffer, QIODevice.ReadOnly)
     self.write_stream = QDataStream(self.buffer, QIODevice.WriteOnly)
Exemplo n.º 2
0
    def testRawData(self):
        data = QDataStream()
        self.assertEqual(data.readRawData(4), None)

        ba = QByteArray()
        data = QDataStream(ba, QIODevice.WriteOnly)
        data.writeRawData('AB\x00C')
        self.assertEqual(ba.data(), py3k.b('AB\x00C'))

        data = QDataStream(ba)
        self.assertEqual(data.readRawData(4), py3k.b('AB\x00C'))
Exemplo n.º 3
0
def qvariant_encode(value):
    buffer = QBuffer()
    buffer.open(QIODevice.ReadWrite)
    stream = QDataStream(buffer)
    stream.writeQVariant(value)
    buffer.close()
    return buffer.buffer().toBase64().data().strip()
Exemplo n.º 4
0
    def preparePacket(self, action, *args, **kwargs):

        reply = QByteArray()
        stream = QDataStream(reply, QIODevice.WriteOnly)
        stream.setVersion(QDataStream.Qt_4_2)
        stream.writeUInt32(0)

        stream.writeQString(action)

        for arg in args:
            if type(arg) is LongType:
                stream.writeQString(str(arg))
            elif type(arg) is IntType:
                stream.writeInt(arg)
            elif isinstance(arg, basestring):
                stream.writeQString(arg)
            elif type(arg) is StringType:
                stream.writeQString(arg)
            elif type(arg) is FloatType:
                stream.writeFloat(arg)
            elif type(arg) is ListType:
                stream.writeQString(str(arg))

        stream.device().seek(0)

        stream.writeUInt32(reply.size() - 4)

        return reply
Exemplo n.º 5
0
 def readDatas(self):
     if self.socket != None :
         if self.socket.isValid() :
             ins = QDataStream(self.socket)
             ins.setVersion(QDataStream.Qt_4_2)
             loop = 0
             while ins.atEnd() == False :
                 QCoreApplication.processEvents()
                 loop = loop + 1
                 if self.socket != None :               
                     if self.socket.isValid() :
                         if self.blockSize == 0:
                             if self.socket.isValid() :
                                 if self.socket.bytesAvailable() < 4:
                                     return
                                 self.blockSize = ins.readUInt32()
                             else :
                                 return
                         if self.socket.isValid() :
                             if self.socket.bytesAvailable() < self.blockSize:
                                 bytesReceived = str(self.socket.bytesAvailable())
                                 return
                             bytesReceived = str(self.socket.bytesAvailable())
                         else :
                             return  
                         action = ins.readQString()
                         self.handleAction(action, ins)
                         self.blockSize = 0
                     else : 
                         return    
                 else :
                     return
             return
    def sendReply(self, action, *args, **kwargs):

        try:

            if hasattr(self, "socket"):

                reply = QByteArray()
                stream = QDataStream(reply, QIODevice.WriteOnly)
                stream.setVersion(QDataStream.Qt_4_2)
                stream.writeUInt32(0)

                stream.writeQString(action)

                for arg in args:
                    if isinstance(arg, int):
                        stream.writeInt(int(arg))
                    elif isinstance(arg, str):
                        stream.writeQString(arg)
                    elif isinstance(arg, list):
                        stream.writeQString(str(arg))

                #stream << action << options
                stream.device().seek(0)

                stream.writeUInt32(reply.size() - 4)

                self.socket.write(reply)

#            else :
#                # no socket !?
#                self.quit()

        except:
            self.log.exception("Something awful happened when sending reply !")
Exemplo n.º 7
0
def qvariant_decode(data):
    byteArray = QByteArray.fromBase64(data)
    buffer = QBuffer(byteArray)
    buffer.open(QIODevice.ReadOnly)
    stream = QDataStream(buffer)
    result = stream.readQVariant()
    buffer.close()
    return result
Exemplo n.º 8
0
    def _check_bitarray(self, data_set):
        '''Check the >> operator for the given data set'''

        for data, expectedStatus, expectedString in data_set:
            stream = QDataStream(data, QIODevice.ReadOnly)
            string = QBitArray()
            stream >> string

            self.assertEqual(stream.status(), expectedStatus)
            self.assertEqual(string.size(), expectedString.size())
            self.assertEqual(string, expectedString)
Exemplo n.º 9
0
    def sendReply(self, action, *args, **kwargs):

        try:

            if hasattr(self, "socket"):

                reply = QByteArray()
                stream = QDataStream(reply, QIODevice.WriteOnly)
                stream.setVersion(QDataStream.Qt_4_2)
                stream.writeUInt32(0)

                stream.writeQString(action)

                for arg in args:
                    if type(arg) is LongType:
                        stream.writeQString(str(arg))
                    if type(arg) is IntType:
                        stream.writeInt(int(arg))
                    elif type(arg) is StringType:
                        stream.writeQString(arg)
                    elif isinstance(arg, basestring):
                        stream.writeQString(arg)
                    elif type(arg) is FloatType:
                        stream.writeFloat(arg)
                    elif type(arg) is ListType:
                        stream.writeQString(str(arg))
                    elif type(arg) is QFile:
                        arg.open(QIODevice.ReadOnly)
                        fileDatas = QByteArray(arg.readAll())
                        stream.writeInt32(fileDatas.size())
                        stream.writeRawData(fileDatas.data())
                        arg.close()
                #stream << action << options
                stream.device().seek(0)

                stream.writeUInt32(reply.size() - 4)

                self.socket.write(reply)

#            else :
#                # no socket !?
#                self.quit()

        except:
            self.log.exception("Something awful happened when sending reply !")
Exemplo n.º 10
0
    def readDatas(self):
        try:
            self.log.debug("receiving data")

            if self.socket.bytesAvailable() == 0:
                return
            ins = QDataStream(self.socket)
            ins.setVersion(QDataStream.Qt_4_2)
            while ins.atEnd() == False:
                if self.blockSize == 0:
                    if self.socket.bytesAvailable() < 4:
                        return
                    self.blockSize = ins.readUInt32()
                if self.socket.bytesAvailable() < self.blockSize:
                    return
                action = ins.readQString()
                self.log.info(action)
                self.handleAction(action, ins)
                self.blockSize = 0
        except:
            self.log.exception("Something awful happened in a gw thread !")
Exemplo n.º 11
0
    def sendReply(self, action, *args, **kwargs):

        if self in self.parent.recorders:

            reply = QByteArray()
            stream = QDataStream(reply, QIODevice.WriteOnly)
            stream.setVersion(QDataStream.Qt_4_2)
            stream.writeUInt32(0)

            stream.writeQString(action)

            for arg in args:
                if type(arg) is LongType:
                    stream.writeQString(str(arg))
                elif type(arg) is IntType:
                    stream.writeInt(arg)
                elif isinstance(arg, basestring):
                    stream.writeQString(arg)
                elif type(arg) is StringType:
                    stream.writeQString(arg)
                elif type(arg) is FloatType:
                    stream.writeFloat(arg)
                elif type(arg) is ListType:
                    stream.writeQString(str(arg))

            stream.device().seek(0)

            stream.writeUInt32(reply.size() - 4)

            if self.socket.isValid() and self.socket.state() == 3:

                if self.socket.write(reply) == -1:
                    self.log.debug("error socket write")
                    self.socket.abort()
            else:
                self.log.debug("send reply - incorrect socket to write")
                self.socket.abort()
Exemplo n.º 12
0
 def setUp(self):
     self.ba = QByteArray()
     self.stream = QDataStream(self.ba, QIODevice.WriteOnly)
     self.read_stream = QDataStream(self.ba, QIODevice.ReadOnly)
Exemplo n.º 13
0
def runparser(filelistdirs,logdir):
  print 'Start running the Translator'
  #os.chdir(logdir)
  filelistdirs=filter(None,filelistdirs)
  print 'D1',filelistdirs
  for dir in xrange(len(filelistdirs)):
    curdir=filelistdirs[dir]
    print 'D2',curdir
    newdir=os.path.join(logdir,os.path.basename(curdir)).replace('\\','/')
    if not os.path.exists(newdir): 
          os.mkdir(newdir)
    filelist = os.listdir(curdir) 
    print filelist 
    os.chdir(curdir)
    for z in xrange(len(filelist)):
        ### Start the xml parser 
        tree = ET.parse(filelist[z])
        root = tree.getroot()
        
        '''create a html result file '''
        filename= os.path.basename(filelist[z])
        logfile=os.path.join(newdir,filename.replace('.onb','.html')).replace('\\','/')   
        print logfile  
        f=open(logfile,'w')
        headers='''  
<!doctype html>
<head>
  <title>OMWEBbook</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="../jquery.min1.10.2.js"></script>
  <script src='../dygraph-combined.js'></script>
  <link rel="stylesheet" href="../bootstrap.min.css">
  <script src="../bootstrap.min.js"></script>
  <link rel="stylesheet" href="../codemirror.css">
 <script src="../codemirror.js"></script>
 <script src="../modelica.js"></script>
 <link rel="stylesheet" href="../custom.css">
  <script src="../autorefresh.js"></script>
  <script src="../evalnotebook.js"></script>
</head>


<body>
<div class="navbar navbar-default navbar-fixed-top">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">OMWebBook</a>
    </div>
     <button id="evaluate" type="button" class="btn btn-success navbar-btn">Evaluate Cell</button>
    <button id="evaluateall" type="button" class="btn btn-success navbar-btn">Eval All</button>
    <img id="progressbar" src="../ajax-loader.gif" class="img-rounded" alt="Cinque Terre">
  </div>
</div>
<div class="container">
<br> <br> <br>

'''
        f.write(headers)
        count=0
        check=0
        sectioncount=1      
        subsectioncount=0.01
        sectioncheck=False
        subsectioncheck=False
        currentlevel=''
        g=1
        g1=1        
        for node in tree.iter():
           if (node.tag=='TextCell'):
              imagelist=node.findall('Image')
              html=node.find('Text').text
              soup = BeautifulSoup(html)
              for a in soup.findAll('a'):
                 staticlink="".join(['static','/',a['href']]).replace('.onb','.html')
                 a['href']=a['href'].replace(a['href'], staticlink)                 
                 #print staticlink
                  
              findp=[]
              for p in soup.findAll('p'):
                 checkempty=p['style'].replace(' ','').split(";")
                 val="-qt-paragraph-type:empty" in checkempty
                 if (val==False):
                    # if (p.find('img')==None):
                        # findp.append(p)
                    # else:
                        findp.append(p)
              for i in xrange(len(findp)):
                   #x=findp[i].text
                   x=findp[i]
                   if(x.find('img')is None):
                       if(x!=''):
                         if(node.attrib['style']=='Text'):
                            #partext='\n'.join(['<p align="justify" contenteditable=False>',str(x),'</p>'])
                            #x["align"]='justify'
                            x=re.sub(r'[^\x00-\x7F]+',' ', str(x))
                            partext='\n'.join([str(x)])
                            f.write(partext)
                            f.write('<br>')
                            f.write('\n')
                         
                         elif(node.attrib['style']=='Title'):
                            print 'title'
                            t=findp[i].text
                            t=re.sub(r'[^\x00-\x7F]+',' ', str(t))
                            htmltext='\n'.join(['<h1>',t,'</h1>'])
                            #htmltext='\n'.join([str(x)])
                            f.write(htmltext)
                            f.write('\n')
                         
                         elif(node.attrib['style']=='Section'):
                            print 'section'
                            t=findp[i].text
                            t=re.sub(r'[^\x00-\x7F]+',' ', str(t))
                            sectioncheck=True
                            htmltext='\n'.join(['<h2>',str(sectioncount),t,'</h2>'])
                            sectioncount+=1
                            #htmltext='\n'.join([str(x)])
                            f.write(htmltext)
                            f.write('\n')
                         elif(node.attrib['style']=='Subsection'):
                            if(sectioncheck==True):
                                g=1
                            g+=1
                            sectioncheck=False
                            #print 'subsection',sectioncheck,(sectioncount-1),'.',(g-1)
                            subsec=findp[i].text
                            subsec=re.sub(r'[^\x00-\x7F]+',' ', str(subsec))
                            #scount=(sectioncount-1)+subsectioncount
                            scount=str((sectioncount-1))+'.'+str((g-1))
                            subsectioncheck=True
                            currentlevel=scount
                            #print str((sectioncount-1)),'.',g
                            #print 'subsection',scount
                            htmltext='\n'.join(['<h3>',str(scount),subsec,'</h3>'])
                            subsectioncount+=0.01
                            #htmltext='\n'.join([str(x)])
                            f.write(htmltext)
                            f.write('\n')
                         elif(node.attrib['style']=='Subsubsection'):
                            if(subsectioncheck==True):
                                g1=1
                            g1+=1
                            subsectioncheck=False
                            #print 'subsection',sectioncheck,(sectioncount-1),'.',(g-1)
                            subsec=findp[i].text
                            subsec=re.sub(r'[^\x00-\x7F]+',' ', str(subsec))
                            #scount=(sectioncount-1)+subsectioncount
                            scount=str(currentlevel)+'.'+str((g1-1))
                            print 'subsubsection',scount
                            #print str((sectioncount-1)),'.',g
                            #print 'subsection',scount
                            htmltext='\n'.join(['<h4>',str(scount),subsec,'</h4>'])
                            subsectioncount+=0.01
                            #htmltext='\n'.join([str(x)])
                            f.write(htmltext)
                            f.write('\n')
                         else:
                            htmltext='\n'.join(['<h1>',str(x),'</h1>'])
                            #htmltext='\n'.join([str(x)])
                            f.write(htmltext)
                            f.write('\n')
                   else:
                       try:
                           imagedir=os.path.join(newdir,"Images").replace('\\','/')
                           if not os.path.exists(imagedir): 
                               os.mkdir(imagedir)
                           os.chdir(imagedir)
                           y=imagelist[0]
                           image=y.text
                           unique_filename = str(uuid.uuid4())
                           img = QtGui.QImage()
                           #image=node.find('Image').text
                           byteArray = QByteArray.fromBase64(image)
                           buffer = QBuffer(byteArray)
                           buffer.open(QIODevice.ReadOnly)
                           data   = QDataStream(buffer)
                           data >> img
                           buffer.close()
                           filename=".".join([unique_filename,"png"])
                           imgpath="/".join(['static',os.path.basename(newdir),'Images/'])
                           imgsrc=imgpath+filename
                           img.save(filename)
                           imgtag="".join(["<div align=\"center\">","<img src=",imgsrc,">","</div>"])
                           #print filename
                           f.write(imgtag)
                           del imagelist[0]
                       except:
                           pass                   
           if (node.tag=='GraphCell' or node.tag=='InputCell'):
              ## catch the input text
            inputtext=node.find('Input').text
            '''
            if ('simulate' in inputtext):
                  text='\n'.join(['<p> <b>',inputtext,'</b> </p>']) 
                  f.write(text)
                  f.write('\n')''' 
            #print 'arun', inputtext
            if(inputtext!=None):
                  linecount=string.split(inputtext, '\n')            
                  '''
                  if ('plot(' in inputtext):
                  text='\n'.join(['<p> <b>',inputtext,'</b> </p> <br>'])  
                  f.write(text)
                  f.write('\n') 
                  ## code to automatically generate plot variable and button in html  
                  plotvar=inputtext.replace('plot','').replace('(','').replace(')','').replace('{','').replace('}','')
                  listplotvar=plotvar.split(',')  
                  plotid='simulatebutton'+str(count)+'plot'
                  buttonid='simulatebutton'+str(count)
                  graphdivid='simulatebutton'+str(count)+'graphdiv'
                  plotheader="\n".join(['<div>','<select id='+ plotid +' size=5 multiple>', '<option ><b>Select Plot Variables</b> </option>'])       
                  f.write(str(plotheader))
                  f.write('\n')
                  for i in xrange(len(listplotvar)):
                     varname='<option selected>'+ str(listplotvar[i]) + '</option>'
                     f.write(varname)
                     f.write('\n')             
                  closeoption="\n".join(['</select> <br>','<button id='+buttonid+'>Simulate</button> <br> <br>' ,'</div>'])
                  f.write(closeoption)
                  count=count+1;
                  else:'''
                  textid='check'+str(check)+'textarea'
                  divid='check'+str(check)+'div'
                  if ('plot(' in inputtext):
                     text='\n'.join(['<textarea id='+ str(textid)+'>',inputtext,'</textarea> <br> <div id='+divid+'> </div> <br>'])
                  else:
                     text='\n'.join(['<textarea id='+ str(textid)+'>',inputtext,'</textarea>  <div id='+divid+'> </div> <br>'])
                  check=check+1
                  f.write(text)
                  f.write('\n')
                  ## catch the OMCPLOT datas
                  curve=node.find('OMCPlot')
                  
                  if curve!=None:
                     #count=count+1;
                     print count
                     try:
                       #scriptdata=makeplot(curve,count)
                       scriptdata=makeplot(curve,divid)
                       f.write(scriptdata)
                       f.write('\n')
                     except:
                       f.write("No data found")
                       f.write('\n')
            else:
              textid='check'+str(check)+'textarea'
              divid='check'+str(check)+'div'
              inputtext=''
              text='\n'.join(['<textarea id='+ str(textid)+'>',inputtext,'</textarea>  <div id='+divid+'> </div> <br>'])
              check=check+1
              f.write(text)
              f.write('\n')

              print "Empty Graph cells"
        f.write('</div></body></html>')
        f.close()         
    print 'Completed'