Why does my value of image variable change? - python-2.7

I don't know what happened with my variable. When the variable "amarilloSegm" is inside in the method "Suma_Manchas(amarilloSegm, NecrosadoSegm) it change its value. The strange is that my variable is not modify in all the method.
This is my code, when I call the method:
...
imgManchasUnidas = Suma_Manchas(amarilloSegm, necrosadoSegm)
...
And this is my body of method:
def Suma_Manchas(imagen_1, imagen_2):
imgAma = imagen_1
imgNecro = imagen_2
manchasUnidas = imgAma
y, x = manchasUnidas.shape
for fil in range (0, y):
for col in range (0, x):
# print "x: " + str(fil) + " y: " + str(col)
valUmbral = imgNecro[fil, col]
if (valUmbral > BLANCO-20):
manchasUnidas.itemset((fil, col), BLANCO)
return manchasUnidas

You do imgAma = imagen_1 and then, manchasUnidas = imgAma, and finally modify manchasUnidas, which ends up modifying imagen_1, since it copies the references instead of creating a new object in the memory.
You can do copy.deepcopy() if you want have a brand new object in another part of the memory, so that when you change one, the other one will not be modified.
More specifically:
import copy
def Suma_Manchas(imagen_1, imagen_2):
imgAma = copy.deepcopy(imagen_1)
...

Related

How to add value to matrix

I want to add value to matrix.
But, I could not do it.
I made the stepfunction for reinforcement learning and I calculated value which named R.
I want to gather R of value and add to matrix named RR.
However, all the calculated values are not added.
Is this because it's done inside a function? If it's not in a function, it works.
Please someone tell me the way to fix it.
% Define the step function
function [NextObservation, Reward, IsDone, LoggedSignals] =
myStepfunction(Action,LoggedSignals,SimplePendulum)
% get the pre statement
statePre = [-pi/2;0];
statePre(1) = SimplePendulum.Theta;
statePre(2) = SimplePendulum.AngularVelocity;
IsDone = false;
% updating states
SimplePendulum.pstep(Action);
% get the statement after updating
state = [-pi/2;0];
state(1) = SimplePendulum.Theta;
state(2) = SimplePendulum.AngularVelocity;
RR = [];
Ball_Target = 10;
Ball_Distance = Ballfunction(SimplePendulum);
R = -abs(Ball_Distance -Ball_Target); ← this the calculated value
RR = [RR,R]; ← I want to add R to RR
if (state(2) > 0) || (SimplePendulum.Y_Position < 0)
IsDone = true;
[InitialObservation, LoggedSignal] = myResetFunction(SimplePendulum);
LoggedSignal.State = [-pi/2 ; 0];
InitialObservation = LoggedSignal.State;
state = InitialObservation;
SimplePendulum.Theta =-pi/2;
SimplePendulum.AngularVelocity = 0;
end
LoggedSignals.State = state;
NextObservation = LoggedSignals.State;
Reward = +max(R);
end
If I understand you correctly, you are trying update RR with this function, and then use/see it outside the loop. This means you need to make two edits:
a) You need to pass RR in and out of the function to update it. You will need to change the first line of your code as shown here, but you will also need to change how you call the function:
function [NextObservation, Reward, IsDone, LoggedSignals, RR] =
myStepfunction(Action,LoggedSignals,SimplePendulum, RR)
b) When you do this RR = [] you delete the content of RR. To initialise RR you will need to move this line to the script that calls this function, making sure it is called before this function is ever called.

NoSuchMethodError. The method "add" was called on null even after initializing List

I have created a TextFormField in flutter. I have a class named ParticipantsData with a few properties listed. I can access and store values in all of those properties by making an object of ParticipantsData class in another class named "RegistrationForm". However I am unable to store data in the properties that are of type List even after having initialized them.
I have tried:
- List.filled()
- =[]
- =[""]
- List.generate()
- List()
- List<String>()
- List<String>(length)
I have changed my code multiple times over and tried many methods but nothing seems to work. I don't post here much because I usually find solutions on stackoverflow but this time I couldn't find anything.
Unable to post the whole code because it is too long. Below is the relevant code:
ParticipantsData class:
class ParticipantsData {
List name = []; //members
bool paymentstatus = false; //payment
String email = ""; //email
String address = ""; //address
List contact = []; //contact
String collegename = ""; //collegename
String password = ""; //password
String teamname = ""; //teamname
var modules = List<String>(6); //modules
ParticipantsData({
this.name,
this.email,
this.contact,
this.collegename,
this.address,
this.modules,
this.password,
this.paymentstatus,
this.teamname,
});
}
Below is the relevant code for Register class:
class _RegistrationForm extends State<RegistrationForm> {
final ParticipantsData data = new ParticipantsData();
//This is the onSaved method of a TextFormField, which is in a loop.
(String value) { //Tried this...
data.name[i + 1] = value;
print('${data.name[i + 1]}');
}),
(String value) { //And this too...
data.name.add(value);
print('${data.name[i + 1]}');
}),
The assigned values become null when initialized inside the constructor. If you don't include the fields in the constructor, they will not reset to null.
However, you may want to assign the values in the constructor and want some default value if the field is not provided while creating the instance. Here is how to do so:
class MyClass {
// Don't initialize here
List x;
int y;
MyClass({
this.x,
this.y = 10, // If y is not assigned, it will take a default value of 10
}) {
// Constructor body
this.x = this.x ?? []; // If x is not assigned, it will take a value of []
}
}
Notice that y can be provided with the default value directly as 10 is a constant value. You can only assign constant default values in the constructor parameter list. Since [ ] is not a constant expression or value, it can't be directly assigned as the default value hence, you need to define the constructor body assigning x = [ ] if x is null.
this.x = this.x ?? [];
You can initialize the others in a similar way.

Access instance variable from instance method in python

class SimpleBond(object):
def__init__(self,OriginationDate,SettleDate,Coupon,CouponFreq,Maturity,Par,StartingPrice = None):
self.CouponCFDaysFromOrigination = np.arange(1,self.NumCouponCFs + 1) * self.CashFlowDelta
self.OriginationCashFlowDates = np.array([self.StartDate + np.timedelta64(int(i),'D') for i in self.CouponCFDaysFromOrigination])
self.StartDate = OriginationDate
def GenerateCashFlowsAndDates(self):
CashFlowDates = self.OriginationCashFlowDates
self.CashFlowDates = CashFlowDates[(CashFlowDates >= self.SettleDate) & (CashFlowDates <=self.MaturityDate)]
I have a class definition as above. Some where else I instantiate the class as below:
BondObj = SimpleBond(OriginationDate = InceptionDate,SettleDate= np.datetime64('2008-02-15'),Coupon = 8.875,CouponFreq = 2,Maturity = 9.5,Par = 100.)
BondObj.GenerateCashFlowsAndDates()
The issue is with the call to GenerateCashFlowDates() as shown above, Once the BondObj is assigned to an instantiation of the SimpleBond class with the arguments to set the state.
When I step inside the call BondObj.GenerateCashFlowsAndDates()....I can see the following state variables
self.StartDate.....its shows the actual state
where
self.OriginationCashFlowDates shows no value. It is none
As a matter of fact, all other instance variables that were set in the constructor are visible from BondObj.GenerateCashFlowAndDates() call
Many thanks

Change value of parameter in NSubstitute

I have this method to mock with NSubstitute:
public T VoerStoredProcedureUit<T>(string naam, params SqlParameter[] parameters)
The test method using it sends 2 SqlParameters to this method. VoerStoredProcedureUit is supposed to change the values of these parameters so the tested method can extract that.
I created the following with NSubstitute:
SqlParameter[] param =
{
new SqlParameter("#pat_id", SqlDbType.BigInt) {Direction = ParameterDirection.Output, Value = "Melding"},
new SqlParameter("#Melding", SqlDbType.VarChar, 4096) {Direction = ParameterDirection.Output, Value = 2}
};
productieVerbinding.VoerStoredProcedureUit<PatientNieuwResultaat>(Arg.Any<string>(),
Arg.Any<SqlParameter[]>()).ReturnsForAnyArgs(x =>
{
x[1] = param;
return PatientNieuwResultaat.Succes;
});
The setup however rises an exception:
A first chance exception of type 'NSubstitute.Exceptions.ArgumentIsNotOutOrRefException' occurred in NSubstitute.dll
Additional information: Could not set argument 1 (SqlParameter[]) as it is not an out or ref argument.
How do you return a value if the method uses implicitly by reference values?
If I understand your question correctly, you're trying to return the contents of param when VoerStoredProcedureUit<PatientNieuwResultaat> is called.
In ReturnsForAnyArgs, x[1] refers to the second parameter which is an SqlParameter[]. This isn't a ref/out parameter so you can't reassign it in the caller, which is why you get an error. Instead, you need to copy the elements from your template, into the supplied array. Something like this:
productieVerbinding.VoerStoredProcedureUit<PatientNieuwResultaat>(Arg.Any<string>(),
Arg.Any<SqlParameter[]>()).ReturnsForAnyArgs((x) =>
{
for (int i = 0; i < param.Length; i++)
{
((SqlParameter[])x[1])[i] = param[i];
}
return PatientNieuwResultaat.Succes;
});
You could obviously remove the for loop, since you know how many parameters you need to copy...
productieVerbinding.VoerStoredProcedureUit<PatientNieuwResultaat>(Arg.Any<string>(),
Arg.Any<SqlParameter[]>()).ReturnsForAnyArgs((x) =>
{
((SqlParameter[])x[1])[0] = param[0];
((SqlParameter[])x[1])[1] = param[1];
return PatientNieuwResultaat.Succes;
});
I found a working solution. Assigning a new variable to the parameters did't work somehow, but changing them does. Also, the second of the method parameter is an array, so it should be treated as such.
productieVerbinding.VoerStoredProcedureUit<PatientNieuwResultaat>(Arg.Any<string>(),
Arg.Any<SqlParameter[]>()).ReturnsForAnyArgs(x =>
{
paramPatId = ((SqlParameter[])x[1])[0];
paramMelding = ((SqlParameter[])x[1])[1];
paramPatId.Value = (long)2;
paramMelding.Value = "Melding";
return PatientNieuwResultaat.Succes;
});

docx4j create unnumbered / bullet list

I would like to create an unnumbered list with bullets using docx4j in my Word document. I have found the following code that is supposed to do the work. But whatever I try, the generated list is a numbered list! I use Word 2010, German version and docx4j-2.8.1.
wordMLPackage = WordprocessingMLPackage.createPackage();
ObjectFactory factory = new org.docx4j.wml.ObjectFactory();
P p = factory.createP();
org.docx4j.wml.Text t = factory.createText();
t.setValue(text);
org.docx4j.wml.R run = factory.createR();
run.getContent().add(t);
p.getContent().add(run);
org.docx4j.wml.PPr ppr = factory.createPPr();
p.setPPr(ppr);
// Create and add <w:numPr>
NumPr numPr = factory.createPPrBaseNumPr();
ppr.setNumPr(numPr);
// The <w:ilvl> element
Ilvl ilvlElement = factory.createPPrBaseNumPrIlvl();
numPr.setIlvl(ilvlElement);
ilvlElement.setVal(BigInteger.valueOf(0));
// The <w:numId> element
NumId numIdElement = factory.createPPrBaseNumPrNumId();
numPr.setNumId(numIdElement);
numIdElement.setVal(BigInteger.valueOf(1));
wordMLPackage.getMainDocumentPart().addObject(p);
Can someone help me to generate a real unordered, buletted list?!
Hope this helps you.
import org.docx4j.XmlUtils;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.NumberingDefinitionsPart;
import org.docx4j.wml.*;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.math.BigInteger;
public class GenerateBulletedList {
private static final String BULLET_TEMPLATE ="<w:numbering xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">" +
"<w:abstractNum w:abstractNumId=\"0\">" +
"<w:nsid w:val=\"12D402B7\"/>" +
"<w:multiLevelType w:val=\"hybridMultilevel\"/>" +
"<w:tmpl w:val=\"AECAFC2E\"/>" +
"<w:lvl w:ilvl=\"0\" w:tplc=\"04090001\">" +
"<w:start w:val=\"1\"/>" +
"<w:numFmt w:val=\"bullet\"/>" +
"<w:lvlText w:val=\"\uF0B7\"/>" +
"<w:lvlJc w:val=\"left\"/>" +
"<w:pPr>" +
"<w:ind w:left=\"360\" w:hanging=\"360\"/>" +
"</w:pPr>" +
"<w:rPr>" +
"<w:rFonts w:ascii=\"Symbol\" w:hAnsi=\"Symbol\" w:hint=\"default\"/>" +
"</w:rPr>" +
"</w:lvl>" +
"</w:abstractNum>"+
"<w:num w:numId=\"1\">" +
"<w:abstractNumId w:val=\"0\"/>" +
"</w:num>" +
"</w:numbering>";
public static void main(String[] args) throws Exception{
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
createBulletedList(wordMLPackage);
wordMLPackage.save(new File("Output.docx"));
}
private static void createBulletedList(WordprocessingMLPackage wordMLPackage)throws Exception{
NumberingDefinitionsPart ndp = new NumberingDefinitionsPart();
wordMLPackage.getMainDocumentPart().addTargetPart(ndp);
ndp.setJaxbElement((Numbering) XmlUtils.unmarshalString(BULLET_TEMPLATE));
wordMLPackage.getMainDocumentPart().addObject(createParagraph("India"));
wordMLPackage.getMainDocumentPart().addObject(createParagraph("United Kingdom"));
wordMLPackage.getMainDocumentPart().addObject(createParagraph("France"));
}
private static P createParagraph(String country) throws JAXBException {
ObjectFactory factory = new org.docx4j.wml.ObjectFactory();
P p = factory.createP();
String text =
"<w:r xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">" +
" <w:rPr>" +
"<w:b/>" +
" <w:rFonts w:ascii=\"Arial\" w:cs=\"Arial\"/><w:sz w:val=\"16\"/>" +
" </w:rPr>" +
"<w:t>" + country + "</w:t>" +
"</w:r>";
R r = (R) XmlUtils.unmarshalString(text);
org.docx4j.wml.R run = factory.createR();
run.getContent().add(r);
p.getContent().add(run);
org.docx4j.wml.PPr ppr = factory.createPPr();
p.setPPr(ppr);
// Create and add <w:numPr>
PPrBase.NumPr numPr = factory.createPPrBaseNumPr();
ppr.setNumPr(numPr);
// The <w:numId> element
PPrBase.NumPr.NumId numIdElement = factory.createPPrBaseNumPrNumId();
numPr.setNumId(numIdElement);
numIdElement.setVal(BigInteger.valueOf(1));
return p;
}
}
The code you have posted says "use list number 1, level 0".
Evidently that list is a numbered list.
Have a look in your numbering definitions part for a bulleted list, and use that one.
If you don't have a bulleted list there, you'll need to add it. You can upload a sample docx to the docx4j online demo, to have it generate appropriate content for you. Or see ListHelper for an example of how it can be done.
private static P getBulletedParagraph(Text text, int i) {
ObjectFactory objCreator = Context.getWmlObjectFactory(); // Object used to
create other Docx4j Objects
P paragraph = objCreator.createP(); // create Paragraph object
PPr ppr = objCreator.createPPr(); // create ppr
NumPr numpr = objCreator.createPPrBaseNumPr();
PStyle style = objCreator.createPPrBasePStyle();// create Pstyle
NumId numId = objCreator.createPPrBaseNumPrNumId();
numId.setVal(BigInteger.valueOf(6));
numpr.setNumId(numId);
R run = objCreator.createR();
Br br = objCreator.createBr();
run.getContent().add(text);
Ilvl iLevel = objCreator.createPPrBaseNumPrIlvl(); // create Ilvl Object
numpr.setIlvl(iLevel);
iLevel.setVal(BigInteger.valueOf(i)); // Set ilvl value
ppr.setNumPr(numpr);
style.setVal("ListParagraph"); // set value to ListParagraph
ppr.setPStyle(style);
paragraph.setPPr(ppr);
paragraph.getContent().add(run);
// paragraph.getContent().add(br); Adds line breaks
return paragraph;
}
I believe this is what you're looking for. This method will return you a paragraph object that has bullets. If you uncomment out the last line before returning paragraph, your paragraph object will also contain line breaks. If you didn't know, "Ilvl", or "eye-level" means indentation. Its the same as clicking the tab button when typing to a document the conventional way. Setting the ilvl element to 1 is the same as clicking tab 1 time. Setting it to 2 is the same as clicking the tab button 2 times, and so on. So it doesn't matter what number you give it. Although it will change the type of bullet you get. What really matters is the numid. Setting the numid to 6 will give you bullets instead of numbers. You will also need to set the PPr style to "ListParagraph". I hope this helps.