def process_requirements_txt(self, repo: Addon, data: QtCore.QByteArray): """Process the requirements.txt metadata file""" self.status_message.emit( translate( "AddonsInstaller", "Downloaded requirements.txt for {}", ).format(repo.display_name) ) f = io.StringIO(data.data().decode("utf8")) lines = f.readlines() for line in lines: break_chars = " <>=~!+#" package = line for n, c in enumerate(line): if c in break_chars: package = line[:n].strip() break if package: repo.python_requires.add(package) # For review and debugging purposes, store the file locally package_cache_directory = os.path.join(self.store, repo.name) if not os.path.exists(package_cache_directory): os.makedirs(package_cache_directory) new_xml_file = os.path.join(package_cache_directory, "requirements.txt") with open(new_xml_file, "wb") as f: f.write(data.data())
def testIt(self): w = QGLWidget() w.makeCurrent() b = QGLBuffer() b.setUsagePattern(QGLBuffer.DynamicDraw) self.assertTrue(b.create()) self.assertTrue(b.bufferId() != 0) self.assertTrue(b.bind()) data = QByteArray("12345") b.allocate(data) self.assertEqual(b.size(), data.size()) m = b.map(QGLBuffer.ReadOnly) if m: self.assertEqual(m, py3k.buffer(py3k.b(data.data()))) b.unmap() m = b.map(QGLBuffer.ReadWrite) m[3] = py3k.b('A') b.unmap() result, rdata = b.read(3, 1) self.assertTrue(result) self.assertEqual(py3k.b('A'), rdata.data()) else: print(" memory mapping is not possible in this OpenGL implementation.") b.release()
def exportDipsToURL(self, dipoles, directoryURL, fileName, addDateToExport=True): dateStr = ("-" + QDate.currentDate().toString(Qt.ISODate) ) if addDateToExport else "" filename = QUrl(directoryURL).toLocalFile() + ( QDir.separator() + fileName + dateStr + ".csv").replace(" ", "_") file = QSaveFile(filename) file.open(QIODevice.WriteOnly) file.write( QByteArray( bytearray("x,y,z,phi (°),theta (°),moment (mu_B)\n", 'utf-8'))) for dip in dipoles: angles = anglesQuaternionToSph(dip.quaternion) line = str(dip.position.x()) + "," + str( dip.position.y()) + "," + str(dip.position.z()) + "," + str( degrees(angles[0])) + "," + str(degrees( angles[1])) + "," + str(dip.moment) + "\n" line = QByteArray(bytearray(line, 'utf-8')) file.write(line) file.commit() if (file.errorString() == "Unknown error"): return True else: return False
def __init__(self, format, durationUs, sampleRate, parent): super(Generator, self).__init__(parent) self.m_pos = 0 self.m_buffer = QByteArray() self.generateData(format, durationUs, sampleRate)
def to_base64(self, w=32, h=32): """Return icon as base64 to make it work with html""" pix = self.pixmap(w, h) data = QByteArray() buff = QBuffer(data) pix.save(buff, "PNG") return data.toBase64().data().decode()
def testIt(self): w = QGLWidget() w.makeCurrent() b = QGLBuffer() b.setUsagePattern(QGLBuffer.DynamicDraw) self.assertTrue(b.create()) self.assertTrue(b.bufferId() != 0) self.assertTrue(b.bind()) data = QByteArray(py3k.b("12345")) b.allocate(data) self.assertEqual(b.size(), data.size()) m = b.map(QGLBuffer.ReadOnly) if m: self.assertEqual(m, py3k.buffer(py3k.b(data.data()))) b.unmap() m = b.map(QGLBuffer.ReadWrite) m[3] = py3k.b('A')[0] b.unmap() result, rdata = b.read(3, 1) self.assertTrue(result) self.assertEqual(py3k.b('A'), rdata.data()) else: print(" memory mapping is not possible in this OpenGL implementation.") b.release()
def _loadSettings(self): settings = QSettings() # Recent documents size = settings.beginReadArray("RecentDocuments") for idx in range(size-1, -1, -1): settings.setArrayIndex(idx) canonicalName = QFileInfo(settings.value("Document")).canonicalFilePath() self._updateRecentDocuments(canonicalName) settings.endArray() # Application properties: Geometry geometry = settings.value("Application/Geometry", QByteArray()) if self._preferences.restoreApplicationGeometry() else QByteArray() if not geometry.isEmpty(): self.restoreGeometry(geometry) else: availableGeometry = self.screen().availableGeometry() self.resize(availableGeometry.width() * 2/3, availableGeometry.height() * 2/3) self.move((availableGeometry.width() - self.width()) / 2, (availableGeometry.height() - self.height()) / 2) # Application properties: State state = settings.value("Application/State", QByteArray()) if self._preferences.restoreApplicationState() else QByteArray() if not state.isEmpty(): self.restoreState(state) else: self._toolbarApplication.setVisible(True) self._toolbarDocument.setVisible(True) self._toolbarEdit.setVisible(True) self._toolbarTools.setVisible(True) self._toolbarView.setVisible(False) self._toolbarHelp.setVisible(False)
def testVoidPtr(self): # Creating a VoidPtr object requires an address of # a C++ object, a wrapped Shiboken Object type, # an object implementing the Python Buffer interface, # or another VoidPtr object. # Original content b = b"Hello world" ba = QByteArray(b) vp = VoidPtr(ba, ba.size()) self.assertIsInstance(vp, shiboken.VoidPtr) # Create QByteArray from voidptr byte interpretation nba = QByteArray.fromRawData(vp.toBytes()) # Compare original bytes to toBytes() self.assertTrue(b, vp.toBytes()) # Compare original with new QByteArray data self.assertTrue(b, nba.data()) # Convert original and new to str self.assertTrue(str(b), str(nba)) # Modify nba through a memoryview of vp mv = memoryview(vp) self.assertFalse(mv.readonly) mv[6:11] = b'void*' self.assertEqual(str(ba), str(b"Hello void*"))
def testSliceAssignmentByteArray(self): b = QByteArray(py3k.b('0123456789')) # replace b[2:8] = bytearray(py3k.b('abcdef')) self.assertEqual(b[2:8], py3k.b('abcdef')) # shrink b[2:8] = bytearray(py3k.b('aaa')) self.assertEqual(b, py3k.b('01aaa89')) # expanse b[2:5] = bytearray(py3k.b('uvwxyz')) self.assertEqual(b, py3k.b('01uvwxyz89')) # Delete behavior b[2:8] = bytearray(py3k.b('')) self.assertEqual(b, py3k.b('0189')) b = QByteArray(py3k.b('0123456789')) # reverse assginment b[5:2:-1] = bytearray(py3k.b('ABC')) self.assertEqual(b, py3k.b('012CBA6789')) # step is not 1 b[2:9:3] = bytearray(py3k.b('XYZ')) self.assertEqual(b, py3k.b('01XCBY67Z9')) b = QByteArray(py3k.b('0123456789')) b[9:2:-3] = bytearray(py3k.b('XYZ')) self.assertEqual(b, py3k.b('012Z45Y78X'))
def testQByteArrayValid(self): '''QDataStream <<>> QByteArray - valid''' self.stream << QByteArray("hello") res = QByteArray() self.read_stream >> res self.assertEqual(res, QByteArray("hello"))
def load_finished(self, state): pixmap = self.engine.grab() self.image = QByteArray() buf = QBuffer(self.image) buf.open(QIODevice.WriteOnly) pixmap.save(buf, "PNG") buf.close() self.quit()
def roleNames(self) -> typing.Dict: """Returns dict with role numbers and role names for default and custom roles together""" # Append custom roles to the default roles and give them names for a usage in the QML roles = super().roleNames() roles[self.Roles.LOCATION.value] = QByteArray(b'location') roles[self.Roles.ID.value] = QByteArray(b'id') print(roles) return roles
def roleNames(self): roles = { UserModel.RoleName: QByteArray(b'name'), UserModel.RoleActive: QByteArray(b'active') } return roles
def run(self): # Try to connect to an incomming tcp socket using its socket descriptor tcpSocket = QTcpSocket() if not tcpSocket.setSocketDescriptor(self.socketDescriptor): FreeCAD.Console.PrintError("Socket not accepted.\n") return # Wait for an incomming message if not tcpSocket.waitForReadyRead(msecs=WAIT_TIME_MS): FreeCAD.Console.PrintError("No request send.\n") return # Make an input data stream instr = QDataStream(tcpSocket) instr.setVersion(QDataStream.Qt_4_0) # Try to read the message size if self.blockSize == 0: if tcpSocket.bytesAvailable() < 2: return self.blockSize = instr.readUInt16() # Check message is sent complete if tcpSocket.bytesAvailable() < self.blockSize: return # Read message and inform about it instr = instr.readString() FreeCAD.Console.PrintLog("CommandServer received> " + str(instr) + "\n") # Try to execute the message string and prepare a response try: exec(str(instr)) except Exception as e: FreeCAD.Console.PrintError("Executing external command failed:" + str(e) + "\n") message = "Command failed - " + str(e) else: FreeCAD.Console.PrintLog("Executing external command succeded!\n") message = COMMAND_EXECUTED_CONFIRMATION_MESSAGE # Prepare the data block to send back and inform about it FreeCAD.Console.PrintLog("CommandServer sending> " + message + " \n") block = QByteArray() outstr = QDataStream(block, QIODevice.WriteOnly) outstr.setVersion(QDataStream.Qt_4_0) outstr.writeUInt16(0) outstr.writeQString(message) outstr.device().seek(0) outstr.writeUInt16(block.size() - 2) # Send the block, disconnect from the socket and terminate the QThread tcpSocket.write(block) tcpSocket.disconnectFromHost() tcpSocket.waitForDisconnected()
def testQByteArrayNull(self): '''QDataStream <<>> QByteArray - null''' self.stream << QByteArray() res = QByteArray() self.read_stream >> res self.assertEqual(res, QByteArray()) self.assertTrue(res.isEmpty()) self.assertTrue(res.isNull())
def testReader(self): ba = QByteArray() writer = QCborStreamWriter(ba) writer.append(42) del writer self.assertTrue(not ba.isEmpty()) reader = QCborStreamReader(ba) self.assertTrue(reader.hasNext()) value = reader.toInteger() self.assertEqual(value, 42)
def testQByteArrayEmpty(self): '''QDataStream <<>> QByteArray - empty''' self.stream << QByteArray("") res = QByteArray() self.read_stream >> res self.assertEqual(res, QByteArray("")) self.assertTrue(res.isEmpty()) self.assertFalse(res.isNull())
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'))
def readData(self, maxlen): data = QByteArray() total = 0 while maxlen > total: chunk = min(self.m_buffer.size() - self.m_pos, maxlen - total) data.append(self.m_buffer.mid(self.m_pos, chunk)) self.m_pos = (self.m_pos + chunk) % self.m_buffer.size() total += chunk return data.data()
def encode_image(image: QImage) -> str: image_bytes = QByteArray() buffer = QBuffer(image_bytes) buffer.open(QIODevice.WriteOnly) # writes pixmap into bytes in PNG format image.save(buffer, "PNG") # type: ignore encoded_bytes = image_bytes.toBase64() codec = QTextCodec.codecForName(b"UTF-8") encoded_string = codec.toUnicode(encoded_bytes) return encoded_string
def preparar_favicon(self, url): try: archivo_ico = backend.descargar_favico(url) except Exception: # Si lo que se ingreso era un link pero no se consiguio favicon with open("media/favicons/domain.ico") as ico: return QByteArray(ico.read()) # Si no se consiguio la imagen if archivo_ico is None: return None with open(archivo_ico, "rb") as ico: return QByteArray(ico.read())
def __init__(self, model, *args, **kwargs): super().__init__(*args, **kwargs) self.model = model # Inicializace socketu self.socket = QTcpSocket(self) self.socket.readyRead.connect(self.read) self.socket.stateChanged.connect(self.socketStateChanged) # Příprava pro čtení dat self.readBuffer = QByteArray() self.textCodec = QTextCodec.codecForName("UTF-8")
def testSetNum(self): b = QByteArray() b.setNum(py3k.long(-124124)) self.assertEqual(b, "-124124") b = QByteArray() b.setNum(-124124) self.assertEqual(b, "-124124") b = QByteArray() b.setNum(-0.5) self.assertEqual(b, "-0.5")
def run(self): self.mutex.lock() serverName = self.hostName serverPort = self.port self.mutex.unlock() while not self.quit: Timeout = 5 * 1000 socket = QTcpSocket() socket.connectToHost(serverName, serverPort) if not socket.waitForConnected(Timeout): self.error.emit(socket.error(), socket.errorString()) return while socket.bytesAvailable() < 2: if not socket.waitForReadyRead(Timeout): self.error.emit(socket.error(), socket.errorString()) return instr = QDataStream(socket) instr.setVersion(QDataStream.Qt_4_0) blockSize = instr.readUInt16() block = QByteArray() outstr = QDataStream(block, QIODevice.WriteOnly) outstr.setVersion(QDataStream.Qt_4_0) while socket.bytesAvailable() < blockSize: if not socket.waitForReadyRead(Timeout): self.error.emit(socket.error(), socket.errorString()) return self.mutex.lock() outstr.writeUInt16(0) outstr.writeQString("Message to Server") outstr.device().seek(0) outstr.writeUInt16(block.size() - 2) socket.write(block) # socket.write(block) fortune = instr.readQString() self.newFortune.emit(fortune) self.cond.wait(self.mutex) serverName = self.hostName serverPort = self.port self.mutex.unlock()
def send_file(self): self._transaction.set_status(TransactionStatus.SENDING) file_to_byte_array = QByteArray() data = QByteArray() stream = QDataStream(data, QIODevice.WriteOnly) QFile.open(self._file, QIODevice.ReadOnly) stream.writeUInt32(0) stream.writeString(self._file_name) print("size of name ", getsizeof(self._file_name)) file_to_byte_array = self._file.readAll() data.append(file_to_byte_array) self._file.close() stream.device().seek(0) stream.writeUInt32(data.size() - getsizeof(self._file_name)) print("total ", data.size() - getsizeof(self._file_name)) x = 0 while (x < data.size()): y = self._socket.write(data) print("poslato ", y) x += y print("x ", x) self._transaction.set_status(TransactionStatus.FINISHED)
def RecieveData(self): #self.CommandSocket.receiveDatagram(20) HEADER = QByteArray() HEADER.resize(2) if self.bytesAvailable < self.LimitBufferSize - self.MaxTransferUnit: #check that memory for packet available if self.BufferWrite.pos( ) < self.LimitBufferSize - self.MaxTransferUnit: (newData, sender, senderPort) = self.CommandSocket.readDatagram(20) #newData = self.CommandSocket.read(self.LimitBufferSize - self.bytesAvailable) #print(" NEW DATA - ",newData.toHex(),"to POS - ",self.BufferWrite.pos()) self.BufferWrite.write(newData) self.bytesAvailable += newData.size() print(self.Timer.restart()) #print("REC ",data) #print(" BUFFER - ",self.BufferWrite.data().toHex()) else: H1 = 0 H2 = 0 while self.CommandSocket.bytesAvailable() > 0: H1 = H2 H2 = self.SocketDataStream.readInt16() if H1 == 0xF1 and (H2 == 0xD1 or H2 == 0xD2 or H2 == 0xD3 or H2 == 0xC1): self.BufferWrite.seek(0) newData = self.CommandSocket.read( self.LimitBufferSize - self.bytesAvailable) self.WriteDataStream.writeInt16(H1) self.WriteDataStream.writeInt16(H2) print( "==============================================================" ) print("SEEK TO 0") print("NEW DATA - ", newData, "to POS - ", self.BufferWrite.pos() - 4) self.BufferWrite.write(newData) self.bytesAvailable += (4 + newData.size()) #print("BUFFER - ",self.NetworkDataArray.toHex()) break else: self.WriteDataStream.writeInt16(H2) self.bytesAvailable += 1 #self.SignalDataRec.emit("BYTES IN REC BUFFER - " + str(self.bytesAvailable)) if (self.bytesAvailable >= self.MinTransferUnit): self.SignalFrameDataAvailable.emit()
def testPastEnd(self): '''QDataStream >> QBitArray reading past the end of the data''' data = [] data.append((QByteArray(), QDataStream.ReadPastEnd, QBitArray())) data.append( (QByteArray(py3k.b('\x00')), QDataStream.ReadPastEnd, QBitArray())) data.append((QByteArray(py3k.b('\x00\x00')), QDataStream.ReadPastEnd, QBitArray())) data.append( (QByteArray(py3k.b('\x00\x00\x00')), QDataStream.ReadPastEnd, QBitArray())) data.append( (QByteArray(py3k.b('\x00\x00\x00\x01')), QDataStream.ReadPastEnd, QBitArray())) data.append( (QByteArray(py3k.b('\x00\x00\x00\x02')), QDataStream.ReadPastEnd, QBitArray())) data.append( (QByteArray(py3k.b('\x00\x00\x00\x03')), QDataStream.ReadPastEnd, QBitArray())) data.append( (QByteArray(py3k.b('\x00\x00\x00\x04')), QDataStream.ReadPastEnd, QBitArray())) self._check_bitarray(data)
def process_metadata_txt(self, repo: Addon, data: QtCore.QByteArray): """Process the metadata.txt metadata file""" self.status_message.emit( translate("AddonsInstaller", "Downloaded metadata.txt for {}").format( repo.display_name ) ) f = io.StringIO(data.data().decode("utf8")) while True: line = f.readline() if not line: break if line.startswith("workbenches="): depswb = line.split("=")[1].split(",") for wb in depswb: wb_name = wb.strip() if wb_name: repo.requires.add(wb_name) FreeCAD.Console.PrintLog( f"{repo.display_name} requires FreeCAD Addon '{wb_name}'\n" ) elif line.startswith("pylibs="): depspy = line.split("=")[1].split(",") for pl in depspy: dep = pl.strip() if dep: repo.python_requires.add(dep) FreeCAD.Console.PrintLog( f"{repo.display_name} requires python package '{dep}'\n" ) elif line.startswith("optionalpylibs="): opspy = line.split("=")[1].split(",") for pl in opspy: dep = pl.strip() if dep: repo.python_optional.add(dep) FreeCAD.Console.PrintLog( f"{repo.display_name} optionally imports python package" + f" '{pl.strip()}'\n" ) # For review and debugging purposes, store the file locally package_cache_directory = os.path.join(self.store, repo.name) if not os.path.exists(package_cache_directory): os.makedirs(package_cache_directory) new_xml_file = os.path.join(package_cache_directory, "metadata.txt") with open(new_xml_file, "wb") as f: f.write(data.data())
def QImageToBase64(image: QImage, format: str = "jpeg", width: int = 1080, with_header: bool = True) -> str: byte_array = QByteArray() buffer = QBuffer(byte_array) image.scaledToWidth(width).save(buffer, format) result = "" if with_header: result += "data:image/%s;base64," % format result += str(byte_array.toBase64())[2:-1] return result
def setUp(self): self.dom = QDomDocument() self.goodXmlData = QByteArray(''' <typesystem package="PySide2.QtXml"> <value-type name="QDomDocument"/> <value-type name="QDomElement"/> </typesystem> ''') self.badXmlData = QByteArray(''' <typesystem package="PySide2.QtXml"> <value-type name="QDomDocument"> </typesystem> ''')
def __init__(self, parent=None): super(NetworkConnectionClass, self).__init__(parent=parent) #self.CommandSocket = QTcpSocket() self.CommandSocket = QUdpSocket() self.CommandSocket.bind(QHostAddress("192.168.100.2"), 2323) self.CommandSocket.connected.connect(self.EventConnectedHandle) self.CommandSocket.readyRead.connect(self.RecieveData) #self.CommandSocket.connectToHost("192.168.100.5",2323,QIODevice.ReadWrite) #self.CommandSocket.connectToHost("127.0.0.1",2323,QIODevice.ReadWrite) #self.CommandSocket.connectToHost("192.168.20.196",2323,QIODevice.ReadWrite) #print("NETWORK - ",self.CommandSocket.localAddress(),self.CommandSocket.peerAddress()) self.Display = WindowNetworkConnection() self.NetworkDataArray = QByteArray() self.NetworkDataArray.resize(2000) self.SignalDataRec.connect(self.Display.PrintData) self.BufferWrite = QBuffer(self.NetworkDataArray) self.BufferWrite.open(QBuffer.WriteOnly) self.BufferRead = QBuffer(self.NetworkDataArray) self.BufferRead.open(QBuffer.ReadOnly) self.ReadDataStream = QDataStream(self.BufferRead) self.ReadDataStream.setByteOrder(QDataStream.LittleEndian) self.WriteDataStream = QDataStream(self.BufferWrite) self.WriteDataStream.setByteOrder(QDataStream.LittleEndian) self.SocketDataStream = QDataStream(self.CommandSocket) self.SocketDataStream.setByteOrder(QDataStream.LittleEndian) self.Timer = QTime() self.Timer.start() self.BufferRead.seek(0) self.BufferWrite.seek(0) self.LimitBufferSize = 2000 self.MinTransferUnit = 7 self.MaxTransferUnit = 18 self.bytesAvailable = 0 self.Display.ui.pushButton.clicked.connect(self.SendData) #===================================================== WRITE BUFFER self.SendBuffer = QByteArray()
def findIcons(self): if hou.applicationVersion()[0] < 15: for category in os.listdir(self.path): for ico in os.listdir(os.path.join(self.path, category)): iconPath = os.path.join( os.path.join(self.path, category, ico)) iconName = '_'.join([category, os.path.splitext(ico)[0]]) self.icons[iconName] = QPixmap(iconPath) else: zf = zipfile.ZipFile(self.path, 'r') for f in zf.namelist(): if f.startswith('old'): continue if os.path.splitext(f)[-1] == '.svg': svg = QSvgRenderer(QByteArray(zf.read(f))) if not svg.isValid(): continue pixmap = QPixmap(iconSize, iconSize) painter = QPainter() painter.begin(pixmap) pixmap.fill(QColor(Qt.black)) svg.render(painter) painter.end() category, ico = f.split('/') iconName = '_'.join([category, os.path.splitext(ico)[0]]) self.icons[iconName] = pixmap zf.close()
def testConcatPythonStringAndQByteArray(self): #Test concatenation of a Python string with a QByteArray, in this order concat_python_string_add_qbytearray_worked = True qba = QByteArray('foo') result = 'bar\x00' + qba self.assertEqual(type(result), QByteArray) self.assertEqual(result, 'bar\x00foo')
def refresh(self, defaultviewsize=False): xml = self.getSvgXML() svg_ba = QByteArray(bytes(xml, 'utf-8')) self.load(svg_ba) if defaultviewsize: # This will make sure diagram is shown full scale. self.resize(self.sizeHint())
def run(self): tcpSocket = QTcpSocket() if not tcpSocket.setSocketDescriptor(self.socketDescriptor): self.error.emit(tcpSocket.error()) return block = QByteArray() outstr = QDataStream(block, QIODevice.WriteOnly) outstr.setVersion(QDataStream.Qt_4_0) outstr.writeUInt16(0) outstr.writeQString(self.text) outstr.device().seek(0) outstr.writeUInt16(block.size() - 2) tcpSocket.write(block) tcpSocket.disconnectFromHost() tcpSocket.waitForDisconnected()
def testToNumberFloat(self): obj = QByteArray('37.109') self.assertEqual((ctypes.c_float(37.109).value, True), obj.toFloat())
def testNullStrings(self): ba = QByteArray('\x00') self.assertEqual(ba.at(0), '\x00') self.assertEqual(ba[0], py3k.b('\x00'))
class Generator(QIODevice): def __init__(self, format, durationUs, sampleRate, parent): super(Generator, self).__init__(parent) self.m_pos = 0 self.m_buffer = QByteArray() self.generateData(format, durationUs, sampleRate) def start(self): self.open(QIODevice.ReadOnly) def stop(self): self.m_pos = 0 self.close() def generateData(self, format, durationUs, sampleRate): pack_format = '' if format.sampleSize() == 8: if format.sampleType() == QAudioFormat.UnSignedInt: scaler = lambda x: ((1.0 + x) / 2 * 255) pack_format = 'B' elif format.sampleType() == QAudioFormat.SignedInt: scaler = lambda x: x * 127 pack_format = 'b' elif format.sampleSize() == 16: if format.sampleType() == QAudioFormat.UnSignedInt: scaler = lambda x: (1.0 + x) / 2 * 65535 pack_format = '<H' if format.byteOrder() == QAudioFormat.LittleEndian else '>H' elif format.sampleType() == QAudioFormat.SignedInt: scaler = lambda x: x * 32767 pack_format = '<h' if format.byteOrder() == QAudioFormat.LittleEndian else '>h' assert(pack_format != '') channelBytes = format.sampleSize() // 8 sampleBytes = format.channelCount() * channelBytes length = (format.sampleRate() * format.channelCount() * (format.sampleSize() // 8)) * durationUs // 100000 self.m_buffer.clear() sampleIndex = 0 factor = 2 * pi * sampleRate / format.sampleRate() while length != 0: x = sin((sampleIndex % format.sampleRate()) * factor) packed = pack(pack_format, int(scaler(x))) for _ in range(format.channelCount()): self.m_buffer.append(packed) length -= channelBytes sampleIndex += 1 def readData(self, maxlen): data = QByteArray() total = 0 while maxlen > total: chunk = min(self.m_buffer.size() - self.m_pos, maxlen - total) data.append(self.m_buffer.mid(self.m_pos, chunk)) self.m_pos = (self.m_pos + chunk) % self.m_buffer.size() total += chunk return data.data() def writeData(self, data): return 0 def bytesAvailable(self): return self.m_buffer.size() + super(Generator, self).bytesAvailable()
def testToNumberUShort(self): obj = QByteArray('37') self.assertEqual((37, True), obj.toUShort())
def testIt(self): data = py3k.b("foobar") a = QByteArray.fromRawData(data) self.assertEqual(type(a), QByteArray) self.assertEqual(a.data(), data)
def testToNumberDouble(self): obj = QByteArray('37.109') self.assertEqual((ctypes.c_double(37.109).value, True), obj.toDouble())
def testAppend(self): b = QByteArray() b.append("A") self.assertEqual(b.size(), 1) b.append("AB") self.assertEqual(b.size(), 3)
def testPathSeparator(self): #QByteArray.split('/') obj = QByteArray(unittest.__file__) self.assertEqual(obj.split('/'), unittest.__file__.split('/'))
def testData(self): url = QByteArray("http://web.openbossa.org/") self.assertEqual(url.data(), py3k.b("http://web.openbossa.org/"))
def testDataWithZeros(self): s1 = "123\000321" ba = QByteArray(s1) s2 = ba.data() self.assertEqual(py3k.b(s1), s2) self.assertEqual(s1, ba)