So, using PyQt5's QWebEngineView and the .setHTML and .setContent methods have a 2 MB size limitation. When googling for solutions around this, I found two methods:
Use SimpleHTTPServer to serve the file. This however gets nuked by a firewall employed in the company.
Use File Urls and point to local files. This however is a rather bad solution, as the HTML contains confidential data and I can't leave it on the harddrive, under any circumstance.
The best solution I currently see is to use file urls, and get rid of the file on program exit/when loadCompleted reports it is done, whichever comes first.
This is however not a great solution and I wanted to ask if there is a solution I'm overlooking that would be better?
Why don't you load/link most of the content through a custom url scheme handler?
webEngineView->page()->profile()->installUrlSchemeHandler("app", new UrlSchemeHandler(e));
class UrlSchemeHandler : public QWebEngineUrlSchemeHandler
{ Q_OBJECT
public:
void requestStarted(QWebEngineUrlRequestJob *request) {
QUrl url = request->requestUrl();
QString filePath = url.path().mid(1);
// get the data for this url
QByteArray data = ..
//
if (!data.isEmpty())
{
QMimeDatabase db;
QString contentType = db.mimeTypeForFileNameAndData(filePath,data).name();
QBuffer *buffer = new QBuffer();
buffer->open(QIODevice::WriteOnly);
buffer->write(data);
buffer->close();
connect(request, SIGNAL(destroyed()), buffer, SLOT(deleteLater()));
request->reply(contentType.toUtf8(), buffer);
} else {
request->fail(QWebEngineUrlRequestJob::UrlNotFound);
}
}
};
you can then load a website by webEngineView->load(new QUrl("app://start.html"));
All relative pathes from inside will also be forwarded to your UrlSchemeHandler..
And rember to add the respective includes
#include <QWebEngineUrlRequestJob>
#include <QWebEngineUrlSchemeHandler>
#include <QBuffer>
One way you can go around this is to use requests and QWebEnginePage's method runJavaScript:
web_engine = QWebEngineView()
web_page = web_engine.page()
web_page.setHtml('')
url = 'https://youtube.com'
page_content = requests.get(url).text
# document.write writes a string of text to a document stream
# https://developer.mozilla.org/en-US/docs/Web/API/Document/write
# And backtick symbol(``) is for multiline strings
web_page.runJavaScript('document.write(`{}`);'.format(page_content))
I try to extract two kind of value from a txt file and write them to two separate txt files. I know that my functions work properly and I cannot figure out any mistake in my code. I realised that both two languages do not read the text file as it is. What I mean by that is for example normally the txt file has 10367 lines in it but when I count the lines in the code, there are 20735 lines in python. I cannot understand why this happens. I do not have an in-depth knowledge about how programming languages read the files. Please give me some information about the possible causes of this situation.
thanks in advance...
This is the pyhton code:
def main():
serverSpeedsList=list()
totalSpeedsList=list()
ssString=str()
stString=str()
with open("C:\\Users\\yusuf\\OneDrive\\Masaüstü\\SpeedTests\\Logs\\log100.txt",'r') as inFile:
for line in inFile:
i+=1
ss=speedOfServer(line)
st=speedOfTotal(line)
if ss!="":
ssString+=ss+"\n"
serverSpeedsList.append(ss)
if st!="":
stString+=st+"\n"
totalSpeedsList.append(st)
with open("C:\\Users\\yusuf\\OneDrive\\Masaüstü\\SpeedTests\\Results\\server100.txt",'w') as outFile:
outFile.write(ssString)
with open("C:\\Users\\yusuf\\OneDrive\\Masaüstü\\SpeedTests\\Results\\total100.txt",'w') as outFile:
outFile.write(ssString)
def speedOfServer(text):
startStr="time\":\""
endStr=" ms"
result=str()
startIx=text.find(startStr)
endIx=text.find(endStr)
if startIx>=0 and endIx>=0:
result=text[startIx+len(startStr) : endIx]
return result
def speedOfTotal(text):
startStr="showProfile.php ("
endStr="ms"
result=str()
startIx=text.find(startStr)
endIx=text.find(endStr)
if startIx>=0 and endIx>=0:
result=text[startIx+len(startStr) : endIx]
return result
main()
and this is the java code to do the same
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
private static String serverSpeedFileName="C:\\Users\\yusuf\\OneDrive\\Masaüstü\\JavaSpeedAnalyser\\Results\\Server\\serverSpeed100.txt";
private static String responseSpeedFileName="C:\\Users\\yusuf\\OneDrive\\Masaüstü\\JavaSpeedAnalyser\\Results\\Total\\responseSpeed100.txt";
private static String logFilePath="C:\\Users\\yusuf\\OneDrive\\Masaüstü\\JavaSpeedAnalyser\\Logs\\log100.txt";
public static void main(String[] args){
StringBuilder serverSpeeds=new StringBuilder();
StringBuilder responseSpeeds=new StringBuilder();
try{
File file = new File(logFilePath);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null){
String serverSpeed=speedOfServer(line);
if(!serverSpeed.isEmpty()){
System.out.println(serverSpeed);
serverSpeeds.append(serverSpeed+"\n");
}
String responseSpeed=speedOfResponses(line);
if(!responseSpeed.isEmpty()){
responseSpeeds.append(responseSpeed+"\n");
}
}
br.close();
}catch(IOException e){
e.printStackTrace();
}
writeToFile(serverSpeedFileName, serverSpeeds.toString());
writeToFile(responseSpeedFileName, responseSpeeds.toString());
}
private static String speedOfServer(String text){
String start="time\":\"";
String end=" ms";
String result="";
int startIndex=text.indexOf(start);
int endIndex=text.indexOf(end);
if(startIndex>=0 && endIndex>=0 ){
result=text.substring(startIndex+start.length(),endIndex);
}
return result;
}
private static String speedOfResponses(String text){
String start="%5bF%5dshowProfile.php (";
String end="ms)";
String result="";
int startIndex=text.indexOf(start);
int endIndex=text.indexOf(end);
if(startIndex>=0 && endIndex>=0){
result=text.substring(startIndex+start.length(),endIndex);
}
return result;
}
}
I try to analyse a logcat file from an android phone, this is why I try to do that but I cannot manage it. Please help me
I have been working on a problem for a while now which I cannot seem to resolve so I need some help! The problem is that I am writing a program in C# but I require a function from a Python file I created. This in itself is no problem:
...Usual Stuff
using IronPython.Hosting;
using IronPython.Runtime;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
namespace Program
{
public partial class Form1 : Form
{
Microsoft.Scripting.Hosting.ScriptEngine py;
Microsoft.Scripting.Hosting.ScriptScope s;
public Form1()
{
InitializeComponent();
py = Python.CreateEngine(); // allow us to run ironpython programs
s = py.CreateScope(); // you need this to get the variables
}
private void doPython()
{
//Step 1:
//Creating a new script runtime
var ironPythonRuntime = Python.CreateRuntime();
//Step 2:
//Load the Iron Python file/script into the memory
//Should be resolve at runtime
dynamic loadIPython = ironPythonRuntime.;
//Step 3:
//Invoke the method and print the result
double n = loadIPython.add(100, 200);
numericUpDown1.Value = (decimal)n;
}
}
}
However, this requires for the file 'first.py' to be wherever the program is once compiled. So if I wanted to share my program I would have to send both the executable and the python files which is very inconvenient. One way I thought to resolve this is by adding the 'first.py' file to the resources and running from there... but I don't know how to do this or even if it is possible.
Naturally the above code will not work for this as .UseFile method takes string arguments not byte[]. Does anyone know how I may progress?
Lets start with the simplest thing that could possibly work, you've got some code that looks a little like the following:
// ...
py = Python.CreateEngine(); // allow us to run ironpython programs
s = py.CreateScope(); // you need this to get the variables
var ironPythonRuntime = Python.CreateRuntime();
var x = py.CreateScriptSourceFromFile("SomeCode.py");
x.Execute(s);
var myFoo = s.GetVariable("myFoo");
var n = (double)myFoo.add(100, 200);
// ...
and we'd like to replace the line var x = py.CreateScriptSourceFromFile(... with something else; If we could get the embedded resource as a string, we could use ScriptingEngine.CreateScriptSourceFromString().
Cribbing this fine answer, we can get something that looks a bit like this:
string pySrc;
var resourceName = "ConsoleApplication1.SomeCode.py";
using (var stream = System.Reflection.Assembly.GetExecutingAssembly()
.GetManifestResourceStream(resourceName))
using (var reader = new System.IO.StreamReader(stream))
{
pySrc = reader.ReadToEnd();
}
var x = py.CreateScriptSourceFromString(pySrc);
I'm calling into Obj from Python using this code:
print "Login begin";
nc = Foundation.NSDistributedNotificationCenter.defaultCenter();
userInfo = NSDictionary.dictionaryWithObjectsAndKeys_("7","operation",user,"username",password,"password",None);
nc.postNotificationName_object_userInfo_deliverImmediately_(SIMULATOR_NOTIFICATION,"",userInfo,1);
return;
The ObjC receives it thusly:
- (void) recievedNotification:(NSNotification *) notification
{
NSDictionary *userInfo = [notification userInfo];
NSControl *postingObject = [notification object]; // the object that posted the notification
NSMutableDictionary *response = [NSMutableDictionary dictionaryWithCapacity:1];
int switcher = [[userInfo objectForKey:#"operation"] intValue];
switch (switcher) {
My question is: how do I return a value (such as a success/failure boolean) back to my Python code?
BTW it's not my code, and yes I can see various problems with it, but that dev left and now I've been asked to update it. You know how it is.
Refering to a previously asked question, I would like to know how to get the title of the current active document.
I tried the script mention in the answers to the question above. This works, but only gives me the name of the application. For example, I am writing this question: When I fire up the script it gives me the name of the application, i.e. "Firefox". This is pretty neat, but does not really help. I would rather like to capture the title of my current active document. See the image.
Firefox title http://img.skitch.com/20090126-nq2egknhjr928d1s74i9xixckf.jpg
I am using Leopard, so no backward compatibility needed. Also I am using Python's Appkit to gain access to the NSWorkspace class, but if you tell me the Objective-C code, I could figure out the translation to Python.
Ok, I've got a solution which is not very satisfing, thats why I don't mark Koen Bok's answer. At least not yet.
tell application "System Events"
set frontApp to name of first application process whose frontmost is true
end tell
tell application frontApp
if the (count of windows) is not 0 then
set window_name to name of front window
end if
end tell
Save as script and invoke it with osascript from the shell.
As far as I know your best bet is wrapping an AppleScript. But AppleScript is magic to me so I leave it as an exercise for the questioner :-)
This might help a little: A script to resize frontmost two windows to fill screen - Mac OS X Hints
In Objective-C, the short answer, using a little Cocoa and mostly the Carbon Accessibility API is:
// Get the process ID of the frontmost application.
NSRunningApplication* app = [[NSWorkspace sharedWorkspace]
frontmostApplication];
pid_t pid = [app processIdentifier];
// See if we have accessibility permissions, and if not, prompt the user to
// visit System Preferences.
NSDictionary *options = #{(id)kAXTrustedCheckOptionPrompt: #YES};
Boolean appHasPermission = AXIsProcessTrustedWithOptions(
(__bridge CFDictionaryRef)options);
if (!appHasPermission) {
return; // we don't have accessibility permissions
// Get the accessibility element corresponding to the frontmost application.
AXUIElementRef appElem = AXUIElementCreateApplication(pid);
if (!appElem) {
return;
}
// Get the accessibility element corresponding to the frontmost window
// of the frontmost application.
AXUIElementRef window = NULL;
if (AXUIElementCopyAttributeValue(appElem,
kAXFocusedWindowAttribute, (CFTypeRef*)&window) != kAXErrorSuccess) {
CFRelease(appElem);
return;
}
// Finally, get the title of the frontmost window.
CFStringRef title = NULL;
AXError result = AXUIElementCopyAttributeValue(window, kAXTitleAttribute,
(CFTypeRef*)&title);
// At this point, we don't need window and appElem anymore.
CFRelease(window);
CFRelease(appElem);
if (result != kAXErrorSuccess) {
// Failed to get the window title.
return;
}
// Success! Now, do something with the title, e.g. copy it somewhere.
// Once we're done with the title, release it.
CFRelease(title);
Alternatively, it may be simpler to use the CGWindow API, as alluded to in this StackOverflow answer.
refered to https://stackoverflow.com/a/23451568/11185460
package main
/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework Cocoa
#import <Cocoa/Cocoa.h>
int
GetFrontMostAppPid(void){
NSRunningApplication* app = [[NSWorkspace sharedWorkspace]
frontmostApplication];
pid_t pid = [app processIdentifier];
return pid;
}
CFStringRef
GetAppTitle(pid_t pid) {
CFStringRef title = NULL;
// Get the process ID of the frontmost application.
// NSRunningApplication* app = [[NSWorkspace sharedWorkspace]
// frontmostApplication];
// pid_t pid = [app processIdentifier];
// See if we have accessibility permissions, and if not, prompt the user to
// visit System Preferences.
NSDictionary *options = #{(id)kAXTrustedCheckOptionPrompt: #YES};
Boolean appHasPermission = AXIsProcessTrustedWithOptions(
(__bridge CFDictionaryRef)options);
if (!appHasPermission) {
return title; // we don't have accessibility permissions
}
// Get the accessibility element corresponding to the frontmost application.
AXUIElementRef appElem = AXUIElementCreateApplication(pid);
if (!appElem) {
return title;
}
// Get the accessibility element corresponding to the frontmost window
// of the frontmost application.
AXUIElementRef window = NULL;
if (AXUIElementCopyAttributeValue(appElem,
kAXFocusedWindowAttribute, (CFTypeRef*)&window) != kAXErrorSuccess) {
CFRelease(appElem);
return title;
}
// Finally, get the title of the frontmost window.
AXError result = AXUIElementCopyAttributeValue(window, kAXTitleAttribute,
(CFTypeRef*)&title);
// At this point, we don't need window and appElem anymore.
CFRelease(window);
CFRelease(appElem);
if (result != kAXErrorSuccess) {
// Failed to get the window title.
return title;
}
// Success! Now, do something with the title, e.g. copy it somewhere.
// Once we're done with the title, release it.
CFRelease(title);
return title;
}
static inline CFIndex cfstring_utf8_length(CFStringRef str, CFIndex *need) {
CFIndex n, usedBufLen;
CFRange rng = CFRangeMake(0, CFStringGetLength(str));
return CFStringGetBytes(str, rng, kCFStringEncodingUTF8, 0, 0, NULL, 0, need);
}
*/
import "C"
import (
"github.com/shirou/gopsutil/v3/process"
"reflect"
"unsafe"
)
//import "github.com/shirou/gopsutil/v3/process"
func cfstringGo(cfs C.CFStringRef) string {
var usedBufLen C.CFIndex
n := C.cfstring_utf8_length(cfs, &usedBufLen)
if n <= 0 {
return ""
}
rng := C.CFRange{location: C.CFIndex(0), length: n}
buf := make([]byte, int(usedBufLen))
bufp := unsafe.Pointer(&buf[0])
C.CFStringGetBytes(cfs, rng, C.kCFStringEncodingUTF8, 0, 0, (*C.UInt8)(bufp), C.CFIndex(len(buf)), &usedBufLen)
sh := &reflect.StringHeader{
Data: uintptr(bufp),
Len: int(usedBufLen),
}
return *(*string)(unsafe.Pointer(sh))
}
func main() {
pid := C.GetFrontMostAppPid()
ps, _ := process.NewProcess(int32(pid))
title_ref := C.CFStringRef(C.GetAppTitle(pid))
println(pid) // pid
println(ps.Name()) // process name
println(cfstringGo(title_ref)) // active window title
}
I then found this property wont change after it is called.
By this, only after we implement NSWorkspaceDidActivateApplicationNotification, we can monitor the change of activity window. But I didn't find any solution which can implement NSWorkspaceDidActivateApplicationNotification in golang.
A workaround method is compile one go program and call it by another go program. I then try full Objective-C code in here