I am in the process of programming a simple program that deals with object recognition. What causes problem is that I am considering and making a gui, but the problem here is that it won't let me call a method. I've looked around the site, but got no luck. Tried different suggestions from others, still nothing. I just don't know how I should call a method with different parameters. Here's what I've tried.. public class Main {      private static ImageProcessor ip;     public static void main(String[] args) {         Main_ m = new Main_();         m.main(ip);     } }  Here's the desired method that I am trying to call.. public class Main_ implements PlugInFilter{  ......      public static String launch(ImageProcessor ip){             ip  = FiltreGaussien_.apply(ip, 3);             ImageProcessor result = Otsu_.apply(ip);             Canny_ cannyFilter = new Canny_(result);             result = cannyFilter.apply(5);                  Hough_ houghFilter = new Hough_(result);             List&lt;Line&gt; lines = houghFilter.apply();                       try{                 Card card = new Card(lines);                 ip = card.extractCorner(ip);                 ImagePlus imp = new ImagePlus(&quot;...&quot;, ip);                 new ImageWindow(imp);             }             catch(RuntimeException e){                  }                  ip = Otsu_.apply(ip);             TemplateMatching_ matcher = new TemplateMatching_();             return matcher.launch(ip);         } }  And my console gives me this.. Exception in thread &quot;main&quot; java.lang.NullPointerException     at ij.process.ByteProcessor.&lt;init&gt;(ByteProcessor.java:96)     at main.mean.FiltreGaussien_.apply(FiltreGaussien_.java:69)     at main.card_detection.Main_.launch(Main_.java:30)     at main.card_detection.Main_.main(Main_.java:22)     at main.Main.main(Main.java:11)  Process finished with exit code 1  What am I doing wrong?
129
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?  What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
11190
When building console applications that take parameters, you can use the arguments passed to Main(string[] args).   In the past I've simply indexed/looped that array and done a few regular expressions to extract the values. However, when the commands get more complicated, the parsing can get pretty ugly.    So I'm interested in:   Libraries that you use Patterns that you use   Assume the commands always adhere to common standards such as .
102393
What would you consider to be the best exception type to throw when an extension method is called on a null instance (where the extension method does not allow it)? Since extension methods are nothing but static methods you could argue that it should be ArgumentNullException, but on the other hand they're used like instance methods so it might be more natural to use the NullReferenceException. Let's take the following example:  public static string ToInvariantString(this IFormattable value, string format) {     return value.ToString(format, CultureInfo.InvariantCulture); }   This way a NullReferenceException will be thrown if the value parameter is null.   The other example would be:  public static string ToInvariantString(this IFormattable value, string format) {     if (value == null) throw new ArgumentNullException("value");     return value.ToString(format, CultureInfo.InvariantCulture); }   EDIT: In some of the answers you have pointed out that an extension methods can be called like a static method and in those cases a null reference exception would be wrong, which is a great point, and actually one of my concerns, not sure why I forgot to mention that in the question in the first place.   Someone also pointed out that it's wrong to throw a NullReferenceException, and yes, it is. That's why I don't throw it, I just let it happen (let the CLR throw it) by not guarding the method.  I think I favor the ArgumentNullException (that's what I've use so far) but I still think there is at least room to argue for an against the NullReferenceException since it seems more natural in most places where the method is going to be used.
81630
Why does this test program result in a java.lang.IllegalMonitorStateException?  public class test {     static Integer foo = new Integer(1);     public static void main(String[] args) {         synchronized(foo) {             foo++;             foo.notifyAll();         }         System.err.println("Success");     } }   Result:  Exception in thread "main" java.lang.IllegalMonitorStateException         at java.lang.Object.notifyAll(Native Method)         at test.main(test.java:6)
101466
I have the following situation I think would be best to show in sample program code.  I have a Java class that extends JPanel.  In this class are two objects which are two more JPanels.  In one of the JPanel objects is a JTable object.  I added a listener to this JTable that detects a double click.  When it detects a double click, I want to fire a method in the top class.  How do I reference this method in Java?  public class TopPanel extends JPanel {    JPanel OnePanel;   JPanel TwoPanel;    public void MethodToFire;  }  public class OnePanel extends JPanel {    JTable TheTable;  }  public class TheTable extends JTable {    public TheTable {     this.addMouseListener(new MouseAdapter(){       public void mouseClicked(MouseEvent e){           if (e.getClickCount() == 2){ SYNTAX CALLING THE METHOD IN TopPanel  }       }     } );   } }
18339
I was hoping to do something like this, but it appears to be illegal in C#: public Collection MethodThatFetchesSomething&lt;T&gt;()     where T : SomeBaseClass {     return T.StaticMethodOnSomeBaseClassThatReturnsCollection(); }  I get a compile-time error:  'T' is a 'type parameter', which is not valid in the given context.  Given a generic type parameter, how can I call a static method on the generic class?  The static method has to be available, given the constraint.
44193
I'm making a call:  myResult = MakeMyCall(inputParams, out messages);   but I don't actually care about the messages.  If it was an input parameter I didn't care about I'd just pass in a null.  If it was the return I didn't care about I'd just leave it off.    Is there a way to do something similar with an out, or do I need to declare a variable that I will then ignore?
30789
It is my understanding that I can test that a method call will occur if I call a higher level method, i.e.:  public abstract class SomeClass() {         public void SomeMehod()     {         SomeOtherMethod();     }      internal abstract void SomeOtherMethod(); }   I want to test that if I call SomeMethod() then I expect that SomeOtherMethod() will be called.   Am I right in thinking this sort of test is available in a mocking framework?
79610
an example code what I try to do will surely do better than my english:  public bool IsNumericValueInBounds (string value, Type numericType) {   double d = double.NaN;         bool inBounds = (bool)numericType.GetMethod ("TryParse").Invoke (null, new object[] { value, d });    return inBounds; }   Unfortunately the TryParse method needs an out parameter so this doesn't work. any ideas how to solve this?  (ps.: would'nt this be a nice example for duck typing? - because i know every numericType has an "TryParse" or I am mistaken?)
103112
When and why would somebody do the following:  doSomething( (MyClass) null );   Have you ever done this? Could you please share your experience?
118553
In C++ I can't use a method if I declare it after the calling method.    Does this order matter in other languages like Java or C#?
6182
I have written the following batch apex class and corresponding test class. Tests are successful but the execute method is never called. I have attempted to debug to try to pinpoint the problem but have had no luck.   Batch Class  global class BatchAddToCampaign implements Database.Batchable&lt;sObject&gt;,  Database.Stateful {     global final Id campaignId;     global final Set&lt;Id&gt; qKeys;      global BatchAddToCampaign(Id campaignId, Set&lt;Id&gt; qKeys){         this.campaignId = campaignId;         this.qKeys = qKeys;     System.Debug('this.campaignId is ' + campaignId);              System.Debug('this.qkeys is ' + qKeys);                       }      global Database.QueryLocator start(Database.BatchableContext BC) {         return Database.getQueryLocator('Select Id From Lead Where Id In :qKeys');     }      global void execute(Database.BatchableContext BC, List&lt;Lead&gt; scope) {         System.Debug('Starting Execute Method!');                  Integer collsize;          List&lt;CampaignMember&gt; cm = new List&lt;CampaignMember&gt;();            Map&lt;Id, Campaign&gt; cmMap = new Map&lt;Id, Campaign&gt;([Select (Select LeadId From CampaignMembers) From Campaign c Where Id = :campaignId]);          for(Lead myLeads : scope) {              CampaignMember newCM = new CampaignMember(              CampaignId = campaignId,              LeadId = myLeads.Id,              status = 'Added' );                   if (!cmMap.containsKey(myLeads.Id)) {                      cm.add(newCM);                       collsize = cm.size();                  }          }           try {              Database.insert(cm);           } catch (DmlException ex) {             System.Debug('Insert failed ' + ex);          }             }      global void finish(Database.BatchableContext BC) {         AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,  TotalJobItems, CreatedBy.Email From AsyncApexJob Where Id = :BC.getJobId()];         // Send an email to the Apex job's submitter notifying of job completion.         Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();         String[] toAddresses = new String[] {a.CreatedBy.Email};         mail.setToAddresses(toAddresses);         mail.setSubject('Add to Campaign ' + a.Status);         String campaignURL = URL.getSalesforceBaseUrl().toExternalForm() + '/' + campaignId;         mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems + ' batches with '+ a.NumberOfErrors + ' failures. ' + 'Link to Campaign: ' + campaignURL);         Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });     } }   Test Class  @isTest public class BatchAddToCampaignTest {     static testMethod void testMethod1()     {         List&lt;Lead&gt; lstCM= new List&lt;Lead&gt;();         for(Integer i=0 ;i &lt;1;i++){             Lead myLead = new Lead();             myLead.Id = '00Q1U00000KqFcDUAV';             lstCM.add(myLead);             Integer collSize = lstCM.size();              System.debug('List Collection Size is ' + collSize);                 {                  System.debug('Start Set');                 Set&lt;Id&gt; leadIds = (new Map&lt;Id,SObject&gt;(lstCM)).keySet();                 System.debug('End Set');                 Integer collSizeSet = leadIds.size();                  System.debug('Set Collection Size is ' + collSizeSet);                 Id workingCampaignId = '7011U000000RWRAQA4';                  Test.startTest();                  //BatchAddToCampaign ba = new BatchAddToCampaign(workingCampaignId, leadIds);                 DataBase.executeBatch(new BatchAddToCampaign(workingCampaignId, leadIds));                  Test.stopTest();                   }             }      } }
103588
In Java, if I call List.toString(), it will automatically call the toString() method on each object inside the List. For example, if my list contains objects o1, o2, and o3, list.toString() would look something like this:  "[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]"   Is there a way to get similar behavior in Python? I implemented a __str__() method in my class, but when I print out a list of objects, using:  print 'my list is %s'%(list)   it looks something like this:  [&lt;__main__.cell instance at 0x2a955e95f0&gt;, &lt;__main__.cell instance at 0x2a955e9638&gt;, &lt;__main__.cell instance at 0x2a955e9680&gt;]   how can I get python to call my __str__ automatically for each element inside the list (or dict for that matter)?
120233
I would like to be able to pass aarguments to operators that I am calling from panels/buttons but I do not know how to do that. At the moment I use "global" variables but they tend to make the code a bit like a puzzle since I need to constantly update them.  See the code below, in that example I would like to pass an argument (like ARG) to "object.simple_operator" when the button is clicked.  import bpy     def DO_SOMETHING(arg):      print(arg)  return  class SimpleOperator(bpy.types.Operator):     """Tooltip"""     bl_idname = "object.simple_operator"     bl_label = "Simple Object Operator"      @classmethod     def poll(cls, context):         return context.active_object is not None      def execute(self, context):         DO_SOMETHING(ARG)         return {'FINISHED'}    class MyPanel(bpy.types.Panel):      bl_label = "mypanel"     bl_idname = "OBJECT_PT_MyPanel"      def draw(self, context):          layout = self.layout          wm = context.window_manager          obj = context.object          row = layout.row()         row.operator('object.simple_operator')
81621
If I write the following class:  public class Example {        int j;       int k;        public Example(int j, int k) {            j = j;            k = k;       }        public static void main(String[] args) {            Example exm = new Example(1,2);            System.out.println(exm.j);            System.out.println(exm.k);       }  }   The program compiles, but when I run the program, the main method will print out two 0s. I know that in order to say that I want to initialize the instance variables in the constructor I have to write:  this.j = j; this.k = k;   But if I don't write it, then which variable is evaluated (or considered) in the constructor (on the left and on the write hand side of the expressions)? Is is the argument or the instance variable? Does it make a difference?  Are there other cases where the use of this is obligatory?
117179
I'm trying to pass one method to another in elisp, and then have that method execute it.  Here is an example:  (defun t1 ()   "t1")  (defun t2 ()   "t1")  (defun call-t (t)   ; how do I execute "t"?   (t))  ; How do I pass in method reference? (call-t 't1)
16290
This is a canonical question and answer developed by the community to help address common questions. If you've been directed here, or your question has been closed as a duplicate, please look through the resources here and use them to shape more specific questions. To browse all canonical questions and answers, navigate to the  tag. This question and answer is owned by the community! If you can improve it and make it more useful, you're welcome to edit it. I am building a trigger, a unit test, or other Apex code. I'm working with sObject records, and trying to access related record information. For example, I might have a structure like this: Account a = new Account(Name = 'Test'); insert a;  Opportunity o = new Opportunity(Name = 'Donation', AccountId = a.Id); insert o;  System.assertEquals(o.Account.Name, 'Test', 'Correct Account associated'); // Assertion fails!  Or, in a trigger, I might be aiming for something like this: trigger ContactTrigger on Contact (after insert) {     for (Contact c : Trigger.new) {         if (c.Account.Name == 'Test') {             // Take some action here         }      } }  Why doesn't this work? Why am I getting null values, or NullPointerExceptions?