I'm very new to Python programming and have a question about python-docx: where is the function add_r() in paragraph.py defined? - python-docx

add_r is called inside add_run in file paragraph.py
def add_run(self, text=None, style=None):
r = self._p.**add_r()**
run = Run(r, self)
if text:
run.text = text
if style:
run.style = style
return run

It is added to the docx.oxml.text.paragraph.CT_P class by its metaclass in response to this declaration in the class definition:
class CT_P(BaseOxmlElement):
"""
``<w:p>`` element, containing the properties and text for a paragraph.
"""
pPr = ZeroOrOne('w:pPr')
r = ZeroOrMore('w:r') # <--- this line causes the metaclass to create the .add_r() method
https://github.com/python-openxml/python-docx/blob/master/docx/oxml/text/paragraph.py#L16

Related

How to receive data from buildin function of another class in another module

I am programming a case manager (administration system). To build it constructively, I program in separate modules to keep an overview. Some modules contain a class-object where I build an small search engine including its own functions. The main program is the case form itself. Obviously, when the search engine finds an entry, it should fill in the case form. I am able to call the search engine (and the search engine works to), however I don't know how to return the results back to the main program/case form/module.
To give you a picture, I have added a image of the GUI, so you can see the case form and the search engine (which is a different module and class (inheriting tk.Toplevel)
The relevant code (case_form/main program):
import ReferenceSearch as rs #Own module
def search_ref(self):
#Function to call search engine
search_engine = rs.ReferenceSearch(self, self.csv_file.get(), self.references_list)
#Reveive data from search_engine and show it in case_form
self.title_var.set(search_engine) #DOES NOT WORK BECAUSE search_engine IS THE ACTUAL ENGINE NOT THE
DATA returned from its buildin function
Relevant code in ReferenceSearch module:
class ReferenceSearch(tk.Toplevel):
def __init__(self, parent, csv_file,references_list=[]):
super().__init__()
self.parent = parent
self.csv_file = csv_file
self.references_list = references_list
self.ref_search_entry = ttk.Entry(self.search_frame)
self.search_but = tk.Button(self.search_frame,
text=" Search ",
command=lambda:self.search_for_ref(self.ref_search_entry.get())
def search_for_ref(self, reference, csv_file="Cases.csv"):
#Function to read specific entry by reference
if reference in self.references_list:
with open(csv_file, "r", newline="") as file:
reader = csv.DictReader(file, delimiter="|")
for entry in reader:
if reference == entry["Reference"]:
data = entry["Title"] #By example
return data
How do I receive the data from the buildin function of the ReferenceSearch class and use it in the main module the case_form?
Keep in mind that the ReferenceSearch module is calling this function when the search button is pressed (and not the case_form module). However, the data is needed in the case_form module.
Change the ReferenceSearch module contents to:
class ReferenceSearch(tk.Toplevel):
def __init__(self, parent, csv_file,references_list=[]):
super().__init__()
self.data = ""
self.parent = parent
self.csv_file = csv_file
self.references_list = references_list
self.ref_search_entry = ttk.Entry(self.search_frame)
self.search_but = tk.Button(self.search_frame,
text=" Search ",
command=lambda:self.search_for_ref(self.ref_search_entry.get())
def search_for_ref(self, reference, csv_file="Cases.csv"):
#Function to read specific entry by reference
if reference in self.references_list:
with open(csv_file, "r", newline="") as file:
reader = csv.DictReader(file, delimiter="|")
for entry in reader:
if reference == entry["Reference"]:
data = entry["Title"] #By example
self.parent.title_var.set(data)
and case_form contents to:
import ReferenceSearch as rs
def search_ref(self):
#Function to call search engine
search_engine = rs.ReferenceSearch(self, self.csv_file.get(), self.references_list)

Tkinter calling functions within a class

Hi I am having trouble calling functions in tkinter
Here is the code
class Demo(tk.Frame):
def ShowOption(self):
print(self.v1.get())
def __init__(self,controller):
tk.Frame.__init__(self,width=800, height=600)
f = Frame(self)
optionList = ('A', 'B','C')
self.v1 = tk.StringVar()
self.v1.set(optionList[0])
Opt1 = tk.OptionMenu(f, self.v1, *optionList,command = self.ShowOption)
Opt1.grid(row=2,column=2,sticky='w')
f.place(relx = 0.5,rely=0.5,anchor='c')
The problem I have is if I use this method it states the function takes 1 postional argument and none were given but if I use
Opt1 = tk.OptionMenu(f, self.v1, *optionList,command = self.ShowOption() )
The function runs straight away when the class is created.
Any help greatly appreciated.
Callback for the command option of OptionMenu expects an argument which is the selected item.
So either you use lambda to skip the argument:
command=lambda v: self.ShowOption()
Or redefine ShowOption() to accept an argument:
def ShowOption(self, value):
...
do this
command = lambda : self.ShowOption()

Octave containers.map not working inside member function

I have the following test code which just creates an empty hashmap (containers.map) and fills it up afterwards:
hashtable = containers.Map('KeyType','char','ValueType','double');
hashtable('test') = 1.0;
as long as I use it in my "main" file, everything works fine...
But if I copy these 2 lines into a member function of an self created class, there comes the error:
error: class not found: MyClassName
error: called from
myMemberFunction at line 15 column 31
line 15 is the line where "hashtable('test') = 1.0;" stands.
If I remove this one line, everything works fine again.
I absolutly don't understand, why the error sais, it can not find my class...
I tested my class and everything works perfectly.
I set up the class in the following way:
1: created a folder named: "#MyClassName"
2: created a constructor file named: "MyClassName"
3: added a constructor function named: "function obj = MyClassName(obj)"
4: created a member function file named: "myMemberFunction"
5: created a member function within this file: "function obj = myMemberFunction(obj)
If this code (the hashmap) stands within my constructor it works fine.
Only if it stands inside my memberfunction line 15 "hashtable('test') = 1.0;" makes the error.
tl;dr - replace
hashtable('test') = 1.0;
with
subsasgn( hashtable, substruct( '()', {'test'} ), 1.0 );
Not sure if this is intended behaviour, or a side-effect of containers.Map being a classdef defined class, and whether or not this is because old and new style classes don't play well with each other. May be worth submitting a bug for this. But, seems like the problem is because hashtable('test') is not parsed as intended inside the method - presumably instead of validly treating it as a 'referencing' operation, it treats it as a function call?
In the interest of completeness, here's an MVCE:
% #MyClassName/MyClassName.m
function obj = MyClassName(obj)
obj = struct('myfield', []);
obj = class(obj, 'MyClassName');
end
% #MyClassName/display.m
function display( Obj );
display( [inputname(1), '.myfield = '] );
display( get( Obj, 'myfield' ) );
end
% #MyClassName/get.m
function Out = get( Obj, Field )
Out = struct(Obj).(Field);
end
% #MyClassName/set.m
function Obj = set( Obj, Field, Val )
Obj = struct(Obj);
Obj.(Field) = Val;
Obj = class( Obj, 'MyClassName' );
end
% #MyClassName/myMemberFunction.m
function obj = myMemberFunction(obj)
hashtable = containers.Map('KeyType', 'char', 'ValueType', 'double');
subsasgn( hashtable, substruct( '()', {'test'} ), 1.0 );
obj = set( obj, 'myfield', hashtable );
end
In terminal:
octave:1> a = MyClassName();
octave:2> a = myMemberFunction(a);
octave:3> a
a.myfield =
containers.Map object with properties:
Count : 1
KeyType : char
ValueType : double

how to get and set hyperparameter from a mlr Wrapper

I run the following to train a wrapped model from some task. I want to get the hyper-parameters from the wrapper. I tried the following
library(mlr)
lrn = makeLearner("classif.ksvm")
lrn = makeRemoveConstantFeaturesWrapper(lrn)
df = getTaskData(sonar.task)
df$constant = 1
task = makeClassifTask(data = df, target = "Class")
model = train(learner = lrn, task = sonar.task)
model
getHyperPars(model)
I got the following message.
Error in UseMethod("getHyperPars") :
no applicable method for 'getHyperPars' applied to an object of class "c('PreprocModel', 'BaseWrapperModel', 'WrappedModel')"
How can I get and set hyper-parameters for a wrapped model?
Thanks!
You have to apply it on the learner:
getHyperPars(lrn)
This only gives hyperparameters that are set explicitly.

How to combine binding fragments without wrapping them in an XML literal

I'm trying to combine 2 binding fragments into one without recourse to an englobing XML literal.
See the following code:
#dom def a = <div><p>a</p></div>
#dom def b = <div><p>b</p></div>
#dom def block = {
// <div>
{a.bind}
{b.bind}
// </div>
}
See ScalaFiddle
As expected, this does not work, only b is displayed.
What I'm looking for here is a way to combine 2 fragments into one, through a function with this signature (for example)
combine: Binding[Node] x Binding[Node] -> Binding[BindingSeq[Node]]
How is it possible ?
Thanks :)
https://scalafiddle.io/sf/9cLgxbN/1
def block = Binding(Constants(a.bind, b.bind))
or
https://scalafiddle.io/sf/9cLgxbN/6
def block = Binding(Constants(a, b).map(_.bind))
The latter one is able to partially update, while the former one is not.
For BindingSeq:
https://scalafiddle.io/sf/9cLgxbN/7
#dom def a = <div><p>a</p></div><div>b</div>
#dom def b = <div><p>c</p></div><div>d</div>
def block = Binding(Constants((a.bind.all.bind ++ b.bind.all.bind): _*))
or
https://scalafiddle.io/sf/9cLgxbN/8
def block = Binding(Constants(a, b).flatMap(_.bind))