$client = new Client();
$a = 'https://scholar.google.com/citations?user=';
$gscID = 'EnegzCwAAAAJ';//for eg
$b = '&hl=en&oi=ao';
$url = $a . $gscID . $b;
$crawler = $client->request('GET', $url);
//python script
$process = new Process(['python', public_path() . '\ext.py'], null, ['SYSTEMROOT' => getenv('SYSTEMROOT'), 'PATH' => getenv("PATH")]);
$process->run();
// executes after the command finishes
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
$out[] = $process->getOutput();
dd($out);
Extracting the tables from the given url webpage
Now I want to pass the $url variable to the python script stored in my public folder because everytime my url changes with different person's ID.
Any help would be really appreciated
Found out an easy solution
$output = shell_exec("python ext.py $url");//ext.py is name of my script and $url is my variable which I want to pass
And then in python script write
import sys
url = sys.argv[1]
You can add script parameters in the array that you are passing to Process.
Here is the doc.https://symfony.com/doc/current/components/process.html#using-features-from-the-os-shell
I have a Bokeh directory format like below.
BTSapp.py is my equivalent of 'main.py'
In data folder, I have 1 input (excel) file and 1 output (excel) file. I wrote a script to transform the data from the input file and write it to the output file. I would like to create a bokeh button, which when the end users click they can download the output file.
Can someone please help me? I found this question also on stackoverflow: send file from server to client on bokeh but I couldn't make it work in my case. I kept getting syntax error for JScode_xhr.
Thank you in advance.
I tried myself and below is the correct code. It will also fix the issue of double alert and of the generation of 2 excel files after the js code is activated.
Note: this is an adjusted version from this post
JScode_fetch = """
var filename = 'my_BSS_result.xlsx';
fetch('/app/static/output.xlsx', {cache: "no-store"}).then(response => response.blob())
.then(blob => {
//addresses IE
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, filename);
}
else {
var link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = filename;
link.target = "_blank";
link.style.visibility = 'hidden';
link.dispatchEvent(new MouseEvent('click'))
URL.revokeObjectURL(url);
}
return response.text();
});
"""
Ia have serwer in Python on my Raspberry Pi and Android application in QT (C++). I wan to send some data (lines) from my serwer (from csv file) to client application and save it in QListWidget. Client can connect by Bluetooth or TCP (I created 2 servers on RPi).
I tried to send line by line in loop, beacuse I don't know if it's any way to send whole list or something like that. I reade about pickle in Python, but I don't know if I can read this in QT.
Client in QT:
if(typ=="BT") line = sBT->readLine();
if(typ=="TCP") line = sTCP->readLine();
line = line.trimmed();
while(line!="koniec")
{
ui->wflista->addItem(line);
if(typ=="BT") line = sBT->readLine();
if(typ=="TCP") line = sTCP->readLine();
line = line.trimmed();
}
Server in Python:
if(data=="logi"):
globalvar.conn.send("logi\n")
print("Klient pyta o logi")
with open('/home/pi/Projekt/log.csv', 'rb') as logi:
csvreader = csv.reader(logi, delimiter=' ', quotechar='|')
for row in csvreader:
globalvar.conn.send(' - '.join(row)+"\n")
print('-'.join(row) +"\n")
globalvar.conn.send("koniec")
print("Wyslalem wszystko")
I would like to get lines from file on RPi to my QListWidget (wflista), but unfortunatelly something is wrong.
When Itry to do it, server display every line from csv file and "Wysłałem wszystko", so it ended loop. on client side QListWidget is empty and it jams. I think that it is in infinite loop, beacuse it can't read "koniec" (argument of while loop.
If I change this argument from "koniec" to "" it sometimes does nothing, sometimes gets lines as it should or sometimes gets only a part of it and part is lost.
What should I do in this case?
Can you try something like this on the C++ side instead and see what happens? (This would be instead of the whole C++ example block you posted in the question.)
QIODevice *sock = (typ == "BT" ? qobject_cast<QIODevice*>(sBT) : qobject_cast<QIODevice*>(sTCP));
while (sock->canReadLine()) {
line = sock->readLine();
line = line.trimmed();
ui->wflista->addItem(line);
}
P.S. I assume this part is being triggered by a signal from the socket, like readyRead(), or is placed after a waitForReadyRead().
ADDED: Debug code:
QIODevice *sock = (typ == "BT" ? qobject_cast<QIODevice*>(sBT) : qobject_cast<QIODevice*>(sTCP));
while (sock->bytesAvailable()) {
const QByteArray data = sock->readAll();
qDebug() << data << '\n' << data.toHex(':');
}
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