Using relative path in WPF xaml file with pythonnet - python-3.x

I am currently working on an application using WPF + pythonnet. And I encountered a problem of using relative path in the main xaml file to find the ResourceDictionary file. Here is a minimal example. There are three files in the app folder:
app/
|-main_window.py
|-main_window.xaml
|-resource.xaml
The main_window.py stores the python code that loads and shows the window layout from the xaml files:
import os
from pathlib import Path
import clr
clr.AddReference(r"wpf\PresentationFramework")
from System.Windows import Application
from System.IO import StreamReader
from System.Windows.Markup import XamlReader
from System.Threading import ApartmentState, Thread, ThreadStart
class MainWindow:
def __init__(self):
self.xamlFilePath = os.path.join(
Path(__file__).parent,
"main_window.xaml",
)
stream = StreamReader(self.xamlFilePath)
window = XamlReader.Load(stream.BaseStream)
Application().Run(window)
if __name__ == "__main__":
thread = Thread(ThreadStart(MainWindow))
thread.SetApartmentState(ApartmentState.STA)
thread.Start()
thread.Join()
The main_window.xaml file defines the layout of the application:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="200" Width="300">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="./resource.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<TextBlock>Test relative path for WPF + Pythonnet</TextBlock>
</Grid>
</Window>
And the resource.xaml stores the ResourceDictionary with the templates:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="Red" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</ResourceDictionary>
Ideally, main_window.xaml should be able to find resource.xaml and load the Style tags. It works well if I provide absolute path, but for relative path it did not work. It gave an Exception: Python.Runtime.PythonException: XamlParseException
Interestingly, if I load the xaml file from Kaxaml, the resource.xaml can be found without problem.
Thanks in advance!

Related

AppBar in Material ui is not reflecting in chrome browser

I am new to react.I am trying to display appbar using material ui in react project. but i can't see the output of it. I have the latest version of the material ui and react.
but the same code is running on codesand box ide on web.
I don't know why it is happening
this is my file structure:
[file structure][1]
These are the versions of the node modules:
[versions of my node modules][2]
The App.js file:
[App.js][3]
this is expected:
[Expected output screen][4]
but got this:
[obtained output screen][5]
this is my index.js file:
[index.js][6]
import React from 'react';
import AppBar from '#material-ui/core/AppBar';
import Typography from '#material-ui/core/Typography';
import VideoPlayer from './components/VideoPlayer';
import Notifications from "./components/Notifications";
import Options from "./components/Options";
const App=()=>{
return(
<div>
<AppBar position="static" color="inherit">
<Typography variant="h2" align="center">Video Chat</Typography>
</AppBar>
<VideoPlayer/>
<Options>
<Notifications/>
</Options>
</div>);
}
export default App;
Thanks in advance for who has replied for my post. thank you for getting me out of this error.
[1]: https://i.stack.imgur.com/ms4fI.png
[2]: https://i.stack.imgur.com/yxLnC.png
[3]: https://i.stack.imgur.com/4VfvN.png
[4]: https://i.stack.imgur.com/dFDg0.png
[5]: https://i.stack.imgur.com/MMK0E.jpg
[6]: https://i.stack.imgur.com/0GWKQ.png
This might be an import issue. Material UI is now MUI If you have the latest version of Material you might need to change the import.
import AppBar from '#mui/material/AppBar';
// or
import { AppBar } from '#mui/material';

Convert html to pdf using pyqt5 without showing a screen

I am trying to render html to pdf using QtWebEngineWidgets using the following code.
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
from tempfile import gettempdir
from pathlib import Path
def printhtmltopdf(html_in, callback):
tfile =Path(gettempdir(), 'printhtmltopdf.html')
with open(tfile, 'wb') as tempf:
tempf.write(html_in)
app = QtWidgets.QApplication(sys.argv)
loader = QtWebEngineWidgets.QWebEngineView()
loader.setZoomFactor(1)
loader.page().pdfPrintingFinished.connect(
lambda *args: print('finished:', args))
loader.load(QtCore.QUrl().fromLocalFile(str(tfile)))
def emit_pdf(finished):
loader.page().printToPdf(callback)
app.exit(0)
loader.loadFinished.connect(emit_pdf)
app.exec()
However the callback is never triggered. When I omit the app.exit(0) it works, but it will wait for user interaction which I do not want. In fact I would prefer to execute the routine without the eventloop at all.
You have to use a QWebEnginePage, also it is not necessary to create temporary files but you can load the HTML directly:
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
def printhtmltopdf(html_in, pdf_filename):
app = QtWidgets.QApplication([])
page = QtWebEngineWidgets.QWebEnginePage()
def handle_pdfPrintingFinished(*args):
print("finished: ", args)
app.quit()
def handle_loadFinished(finished):
page.printToPdf(pdf_filename)
page.pdfPrintingFinished.connect(handle_pdfPrintingFinished)
page.loadFinished.connect(handle_loadFinished)
page.setZoomFactor(1)
page.setHtml(html_in)
app.exec()
printhtmltopdf(
"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello!</title>
</head>
<body>
<h1>Hello World!</h1>
<p>This is a simple paragraph.</p>
</body>
</html>""",
"test.pdf",
)

Using Python pulling data from xml returned from a soap request to save to csv

I have zeep pulling soap data from a SOAP endpoint as:
'''<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetLogCategoriesResponse xmlns="http://mynamespace.net/client">
<GetLogCategoriesResult>
<IsSuccessful>true</IsSuccessful>
<Messages />
<Categories>
<LogCategory>
<Category>Client Call</Category>
<CategoryId>805</CategoryId>
<CategoryType>UDF</CategoryType>
</LogCategory>
<LogCategory>
<Category>Client Portal</Category>
<CategoryId>808</CategoryId>
<CategoryType>UDF</CategoryType>
</LogCategory>
<LogCategory>
<Category>Complaint Notes</Category>
<CategoryId>1255</CategoryId>
<CategoryType>UDF</CategoryType>
</LogCategory>
</Categories>
</GetLogCategoriesResult>
</GetLogCategoriesResponse>
</soap:Body>
</soap:Envelope>'''
I've tried pulling the data using Elementtree as below without success:
'''from zeep import Client, Transport
import xml.etree.ElementTree as ET
client = Client('http://sandbox.mynamespace.net/Client.asmx?wsdl')
with client.settings(raw_response=True):
soap_result = client.service.GetLogCategories(userName='user', password='pass')
namespaces = {
'soap': 'http://schemas.xmlsoap.org/soap/envelope/',
'a': 'http://mynamespace.net/client',
}
dom = ET.fromstring(soap_result.content)
print(dom)
names = dom.findall(
'./soap:Body'
'./a:GetLogCategoriesResponse'
'./a:GetLogCategoriesResult'
'./a:Categories'
'./a:LogCategory'
'./a:Category',
namespaces,)
print(names)
for name in names:
print('in For')
print(name.text)'''
I do have a partially working but it only pulls back the first instance of the data group, I need to pull back all groups:
'''from zeep import Client, Transport
from bs4 import BeautifulSoup
client = Client('http://sandbox.mynamespace.net/2.18/Client.asmx?wsdl')
with client.settings(raw_response=True):
soap_result = client.service.GetLogCategories(userName='uname', password='pass')
soup = BeautifulSoup(soap_result.text, 'html.parser')
searchTerms = ['Category','CategoryId','CategoryType']
for st in searchTerms:
print(st+'\t',)
print(soup.find(st.lower()).contents[0])'''
I am looking for any pointers or solutions that will work at this point.
Thanks again
Try this.
from simplified_scrapy.simplified_doc import SimplifiedDoc
html = '''<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetLogCategoriesResponse xmlns="http://mynamespace.net/client">
<GetLogCategoriesResult>
<IsSuccessful>true</IsSuccessful>
<Messages />
<Categories>
<LogCategory>
<Category>Client Call</Category>
<CategoryId>805</CategoryId>
<CategoryType>UDF</CategoryType>
</LogCategory>
<LogCategory>
<Category>Client Portal</Category>
<CategoryId>808</CategoryId>
<CategoryType>UDF</CategoryType>
</LogCategory>
<LogCategory>
<Category>Complaint Notes</Category>
<CategoryId>1255</CategoryId>
<CategoryType>UDF</CategoryType>
</LogCategory>
</Categories>
</GetLogCategoriesResult>
</GetLogCategoriesResponse>
</soap:Body>
</soap:Envelope>'''
doc = SimplifiedDoc(html)
Categories = doc.getElementsByTag('LogCategory')
print ([(c.Category.text,c.CategoryId.text,c.CategoryType.text) for c in Categories])
Result:
[('Client Call', '805', 'UDF'), ('Client Portal', '808', 'UDF'), ('Complaint Notes', '1255', 'UDF')]
Here are more examples of SimplifiedDoc here

plotly-dash on iis with flask and wfastcgi

I've configured IIS with python and wfastcgi.py, getting it working, mostly. When trying with simple stuff, it returns the expected content.
My issue now is with getting flask and plotly/dash working under IIS, using attribute routing.
My web.config is as follows:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python36\python.exe|C:\Python36\Scripts\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" />
</handlers>
</system.webServer>
<appSettings>
<!-- Required settings -->
<add key="WSGI_HANDLER" value="index.wsgi_app" />
<add key="PYTHONPATH" value="C:/inetpub/wwwroot/python/venv/Scripts/python36.zip;C:/inetpub/wwwroot/python/venv/DLLs;C:/inetpub/wwwroot/python/venv/lib;C:/inetpub/wwwroot/python/venv/Scripts;c:/python36/Lib', 'c:/python36/DLLs;C:/inetpub/wwwroot/python/venv;C:/inetpub/wwwroot/python/venv/lib/site-packages" />
<!-- Optional settings -->
<add key="WSGI_LOG" value="C:\temp\my_app.log" />
<add key="WSGI_RESTART_FILE_REGEX" value=".*((\.py)|(\.config))$" />
<add key="APPINSIGHTS_INSTRUMENTATIONKEY" value="__instrumentation_key__" />
<add key="WSGI_PTVSD_SECRET" value="__secret_code__" />
<add key="WSGI_PTVSD_ADDRESS" value="ipaddress:port" />
</appSettings>
</configuration>
I've created an index.py file and when I use
from flask import Flask
from SimpleDash1 import app as sd1
from WebAppExampleA import app as waea
app = Flask(__name__)
#app.route("/")
def hello():
response = ["Hello, world!\n"]
return (line.encode("utf-8") for line in response)
def wsgi_app(environ,start_response):
start_response('200 OK', [('Content-type', 'text/html'), ('Content-encoding', 'utf-8')])
return hello()
if __name__ == "__main__":
app.run()
It works fine, but it doesnt exactly serve up my plotly app.
To try and load my plotly app, I've used this instead:
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
from app import app
from apps import web_example_a
app.layout = html.Div([
dcc.Location(id='url', refresh=False),
html.Div(id='page-content')
])
#app.callback(Output('page-content', 'children'),
[Input('url', 'pathname')])
def display_page(pathname):
if pathname == '/apps/web_example_a':
return web_example_a.layout
#elif pathname == '/apps/app2':
# return app2.layout
else:
return '404'
if __name__ == '__main__':
app.run_server(debug=True)
But now I'm stumped as to what entrypoint I need to configure as my WSGI_HANDLER in web.config.
If I try to change the WSGI_HANDLER to "index.display_page" I get an error saying:
Error occurred:
Traceback (most recent call last): File
"C:\Python36\Scripts\wfastcgi.py", line 849, in main
for part in result: File "C:\python36\lib\site-packages\applicationinsights\requests\WSGIApplication.py",
line 70, in call
for part in self._wsgi_application(environ, status_interceptor): File "C:\python36\lib\site-packages\dash\dash.py", line 498, in
add_context
output_value = func(*args, **kwargs) TypeError: display_page() takes 1 positional argument but 2 were given
StdOut:
StdErr: C:\python36\lib\site-packages\plotly\tools.py:103:
UserWarning:
Looks like you don't have 'read-write' permission to your 'home' ('~')
directory or to our '~/.plotly' directory. That means plotly's python
api can't setup local configuration files. No problem though! You'll
just have to sign-in using 'plotly.plotly.sign_in()'. For help with
that: 'help(plotly.plotly.sign_in)'. Questions? Visit
https://support.plot.ly
The WSGI entry point for Dash apps is the Flask instance attached to the Dash instance. That means you want to point your WSGI handler at app.server (where app is the Dash instance).
WSGI servers often look for an attribute application when passed a module as an entry point. So a common thing to do is create a an entry-point file wsgi.py which in your case would simply have this:
from index import app
application = app.server

Fetch users in workflow definition

I am using Liferay 6.1.1CE with kaleo workflow.
I am created a new workflow definition,by editing singlelevel workflow.xml.
In my workflow definition,i had add a new transition "reference" and a task for the same.
In my reference task,i have to select a user from all users to send the reference.
How can i fetch the users..? Is it possible?
I am not entirely sure what you task is doing, but yeah, you could definitely access to portal service class by using groovy scripts. something like:
<task>
<name>Some task</name>
<actions>
<action>
<name>task action</name>
<script><![CDATA[
import com.liferay.portal.kernel.util.GetterUtil;
import java.util.List
import java.util.Map;
import java.util.Set;
import java.util.Iterator;
import com.liferay.portal.kernel.workflow.WorkflowConstants;
import com.liferay.portal.model.User;
import com.liferay.portal.service.UserLocalServiceUtil;
long companyId = GetterUtil.getLong((String)
workflowContext.get(WorkflowConstants.CONTEXT_COMPANY_ID));
ServiceContext serviceContext = (ServiceContext)
workflowContext.get(WorkflowConstants.CONTEXT_SERVICE_CONTEXT);
List<User> users = UserLocalServiceUtil.getUsers(start, end);
]]></script>
<script-language>groovy</script-language>
<execution-type>onEntry</execution-type>
</action>
</actions>
<assignments>
<roles>
<role>
<role-type>regular</role-type>
<name>Administrator</name>
</role>
</roles>
</assignments>
<transitions>
<transition>
<name>next</name>
<target>Next Task</target>
</transition>
</transitions>
</task>
and you could access to you workflow task in code use WorkflowInstanceManagerUtil and WorkflowTaskManagerUtil, I hope this helps, let me know if you have further questions

Resources