问:
How do I suppress a thread.abort() error C#?
I am showing a splash screen on a background thread while my program loads.  Once it loads I am aborting the Thread as it's only purpose was to show a Now Loading splash form.

My problem is that when aborting a Thread it throws a ThreadAbortException that the user can just click Continue on.

How do I deal with this?  I was trying to suppress it like so -->

```<code>            try
        {
            Program.splashThread.Abort();
        }
        catch(Exception ex)
        {

        }
</code>```

but I have a feeling that is going to get me yelled at here and it doesn't work any way.

Thanks!

答:
Try this code. It's working fine for me.</p>

```<code>void splash()
{
    try {
        SplashScreen.SplashForm frm = new SplashScreen.SplashForm();
        frm.AppName = "HR";

        Application.Run(frm);
    }
    catch (ThreadAbortException ex)
    {
        Thread.ResetAbort();
    }
}
</code>```

Body:
I am showing a splash screen on a background thread while my program loads.  Once it loads I am aborting the Thread as it's only purpose was to show a Now Loading splash form.

My problem is that when aborting a Thread it throws a ThreadAbortException that the user can just click Continue on.

How do I deal with this?  I was trying to suppress it like so -->

            try
        {
            Program.splashThread.Abort();
        }
        catch(Exception ex)
        {

        }

but I have a feeling that is going to get me yelled at here and it doesn't work any way.

Thanks!

Body:
Try this code. It's working fine for me.

void splash()
{
    try {
        SplashScreen.SplashForm frm = new SplashScreen.SplashForm();
        frm.AppName = "HR";

        Application.Run(frm);
    }
    catch (ThreadAbortException ex)
    {
        Thread.ResetAbort();
    }
}


来源: stackexchange

问:
Java | Get column keys from a row key
I have Table like     Table<String, String, String> distributions = HashBasedTable.create();

```<code>|----------------------------------------------|
| Row             | Column   | Value           |
|----------------------------------------------|
| aaa             | a        | Hard Rock       |
| aaa             | n        | Art Pop         |
| abc             | b        | Surrealist Film |
| abc             | c        | Blockbuster     |
|----------------------------------------------|
</code>```

My Column values are all unique but my Row values can be repeated.

so How can I get all the Column keys given a Row key?

答: If you want values based on rows. it will give you multiple values

ContentLicense: CC BY-SA 3.0

Title: Java | Get column keys from a row key

Body:
I have Table like     Table<String, String, String> distributions = HashBasedTable.create();

|----------------------------------------------|
| Row             | Column   | Value           |
|----------------------------------------------|
| aaa             | a        | Hard Rock       |
| aaa             | n        | Art Pop         |
| abc             | b        | Surrealist Film |
| abc             | c        | Blockbuster     |
|----------------------------------------------|

My Column values are all unique but my Row values can be repeated.

so How can I get all the Column keys given a Row key?


问:
Scraping data with python
I'm working on a program to scrape address data from companies from a website. For this, I already have built a list with the links where this data can be found. On each of those links, the page source of the data I need looks like this:

http://imgur.com/a/V0kBK

For some reason though, I cannot seem to fetch the first line of the address, in this case "'t walletje 104 101"

All the other information comes through fine, as you can see here:

http://imgur.com/a/aUmSI

This is my code:

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
import string
import urllib

urllist=[]
url1="http://www.bisy.be/"

fname = "test2.txt"
fh = open(fname)
for line in fh:
    line = line.rstrip()
    if line.startswith(" <tr class="):
        words= line.split()
        url2 = words[6]
        url3 = url1 + url2[1:48]
        urllist.append(url3)

for link in urllist:
    document = urllib.request.urlopen(link)
    html = document.read()
    soup = BeautifulSoup(html,"html.parser")
    name = soup.find("br")
    name2 = name.text.strip()
    print (name2)
</code>```

This code is doing the basics so far. Once everything works I will clean it and finetune it a bit. Is there anyone who can help me?
An example link for the people who want to check out the page source: http://www.bisy.be/?q=nl/bedrijf_fiche&id=KNO01C2015&nr=2027420160

Is there anyone who can point me in the right direction?

答:
your can't select text in br it new line not like p, span div or others. you can try using BeautifulSoup above or use regex below which is faster

```<code>import re

for link in urllist:
  document = urllib.request.urlopen(link)
  html = document.read().decode('utf-8')
  name = re.compile(r"9pt; font-family: Arial;'>(.*?)<a",  re.DOTALL).findall(html)
  # clean html tag
  name = re.sub('<[^>]*>', '', name[0])
  print(name)
</code>```

Title: Scraping data with python

Body:
I'm working on a program to scrape address data from companies from a website. For this, I already have built a list with the links where this data can be found. On each of those links, the page source of the data I need looks like this:

http://imgur.com/a/V0kBK

For some reason though, I cannot seem to fetch the first line of the address, in this case "'t walletje 104 101"

All the other information comes through fine, as you can see here:

http://imgur.com/a/aUmSI

This is my code:

from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
import string
import urllib

urllist=[]
url1="http://www.bisy.be/"

fname = "test2.txt"
fh = open(fname)
for line in fh:
    line = line.rstrip()
    if line.startswith(" <tr class="):
        words= line.split()
        url2 = words[6]
        url3 = url1 + url2[1:48]
        urllist.append(url3)

for link in urllist:
    document = urllib.request.urlopen(link)
    html = document.read()
    soup = BeautifulSoup(html,"html.parser")
    name = soup.find("br")
    name2 = name.text.strip()
    print (name2)

This code is doing the basics so far. Once everything works I will clean it and finetune it a bit. Is there anyone who can help me?
An example link for the people who want to check out the page source: http://www.bisy.be/?q=nl/bedrijf_fiche&id=KNO01C2015&nr=2027420160

Is there anyone who can point me in the right direction?

Body:
your can't select text in br it new line not like p, span div or others. you can try using BeautifulSoup above or use regex below which is faster

import re

for link in urllist:
  document = urllib.request.urlopen(link)
  html = document.read().decode('utf-8')
  name = re.compile(r"9pt; font-family: Arial;'>(.*?)<a",  re.DOTALL).findall(html)
  # clean html tag
  name = re.sub('<[^>]*>', '', name[0])
  print(name)


问:
checking whether a value of a variables belong to a set bootstrap
I have an array of integer say

```<code>theIndex = [ 1 2 6 7 17 2]
</code>```

I have a dataframe with one column dataset[:id] containing integers say

```<code>dataset = DataFrame(id=[ 1, 1, 2, 2, 3, 3, 3, 4, 4, 4])
</code>```

I want to select all observations in dataset that belongs to the index. and if they appear twice (or more) in the index, I want to select them twice (or more)

At the moment, I am doing it the dumb way.

```<code>theIndex = [ 1 2 6 7 17 2]
dataset = DataFrame(id=[ 1, 1, 2, 2, 3, 3, 3, 4, 4, 4])
dataset2 = DataFrame(id=Int64[])
for ii1=1:size(theIndex,2)
    for ii2=1:size(dataset[:id],1)
        any(i->i.==dataset[ii2,:id],theIndex[ii1]) ?
        push!(dataset2,dataset[ii2,:id]) : nothing
    end
end
</code>```

any more elegant solution?

答:
As per my earlier comment, you're looking for the findin function.

julia> Ind = findin( dataset[:id], theIndex); # return indices of elements in
                                              # dataset[:id] that occur in
                                              # theIndex

julia> dataset[:id][Ind]
4-element DataArrays.DataArray{Int64,1}:
 1
 1
 2
 2
```

<p>(or if you wanted your result back in the form of a SubDataFrame / view into your dataset, you could do <code>SubDataFrame(dataset, Ind)</code> etc)</p>

<p><strong>EDIT:</strong> as per comments, to ensure repetitions in <code>theIndex</code> are taken into account, the sample for each element needs to be appended separately:</p>

<pre class="lang-julia prettyprint-override"><code>Ind = []; for i in theIndex; append!(Ind, findin(dataset[:id], i)); end
</code>```

Ind can then be used to create an array or SubDataFrame as above.

EDIT 2:

julia> @time dataset2 = DataFrame(id=Int64[])
       for ii1=1:size(theIndex,2)
           for ii2=1:size(dataset[:id],1)
               any(i->i.==dataset[ii2,:id],theIndex[ii1]) &&
               push!(dataset2,dataset[ii2,:id])
           end
       end
  0.000016 seconds (24 allocations: 1.594 KiB)

julia> @time Ind = []; for i in theIndex; append!(Ind, findin(dataset[:id], i)); end
  0.000002 seconds (5 allocations: 240 bytes)
```

(usual cautionary rant about benchmarking in global scope bla bla)

Body:
I have an array of integer say

theIndex = [ 1 2 6 7 17 2]

I have a dataframe with one column dataset[:id] containing integers say

dataset = DataFrame(id=[ 1, 1, 2, 2, 3, 3, 3, 4, 4, 4])

I want to select all observations in dataset that belongs to the index. and if they appear twice (or more) in the index, I want to select them twice (or more)

At the moment, I am doing it the dumb way.

theIndex = [ 1 2 6 7 17 2]
dataset = DataFrame(id=[ 1, 1, 2, 2, 3, 3, 3, 4, 4, 4])
dataset2 = DataFrame(id=Int64[])
for ii1=1:size(theIndex,2)
    for ii2=1:size(dataset[:id],1)
        any(i->i.==dataset[ii2,:id],theIndex[ii1]) ?
        push!(dataset2,dataset[ii2,:id]) : nothing
    end
end

any more elegant solution?

Body:
As per my earlier comment, you're looking for the findin function.

julia> Ind = findin( dataset[:id], theIndex); # return indices of elements in
                                              # dataset[:id] that occur in
                                              # theIndex

julia> dataset[:id][Ind]
4-element DataArrays.DataArray{Int64,1}:
 1
 1
 2
 2

(or if you wanted your result back in the form of a SubDataFrame / view into your dataset, you could do SubDataFrame(dataset, Ind) etc)

EDIT: as per comments, to ensure repetitions in theIndex are taken into account, the sample for each element needs to be appended separately:

Ind = []; for i in theIndex; append!(Ind, findin(dataset[:id], i)); end

Ind can then be used to create an array or SubDataFrame as above.

EDIT 2:

julia> @time dataset2 = DataFrame(id=Int64[])
       for ii1=1:size(theIndex,2)
           for ii2=1:size(dataset[:id],1)
               any(i->i.==dataset[ii2,:id],theIndex[ii1]) &&
               push!(dataset2,dataset[ii2,:id])
           end
       end
  0.000016 seconds (24 allocations: 1.594 KiB)

julia> @time Ind = []; for i in theIndex; append!(Ind, findin(dataset[:id], i)); end
  0.000002 seconds (5 allocations: 240 bytes)

(usual cautionary rant about benchmarking in global scope bla bla)


问:
Adb install progress bar
I'm a beginner at this so just mind me if I ask anything obvious. I'm trying to install an apk to my device using adb install apk.apk however, the apk is around a few hundred MB big and it takes some time. Is there some sort of progress bar that I could implement in the command window to show the progress? I've seen stuff for adb push/pull . I'm not sure if it's the same. I'm running this in Windows 8.1. I also have an adb environment variable set up.

Thanks so much.

答:
Well, adb install apk.apk is just a glorified shortcut for:

```<code>adb push apk.apk /data/local/tmp
adb shell pm install /data/local/tmp/apk.apk
adb shell rm /data/local/tmp/apk.apk
</code>```

So if you are so inclined to see the upload progress bar - just adb push -p your apk first and then adb shell pm install it either manually or with a simple script.

Title: Adb install progress bar

Body:
Well, adb install apk.apk is just a glorified shortcut for:

adb push apk.apk /data/local/tmp
adb shell pm install /data/local/tmp/apk.apk
adb shell rm /data/local/tmp/apk.apk

So if you are so inclined to see the upload progress bar - just adb push -p your apk first and then adb shell pm install it either manually or with a simple script.


问:
Java Jackson serialization handle on getter throws exception
I use an external library that has a method:

```<code>public class CustomUserDetails implements UserDetails {

    private final User principal;
    private final Collection<GrantedAuthority> authorities;

    //constructor, getters, setters

    @Override
    public String getPassword() {
        throw new UnsupportedOperationException("Not allowed");
    }
}
</code>```

And I have a @RequestMapping that returns an instance of that object:

```<code>@RequestMapping(value = "/authorities", method = GET)
    public ResponseEntity getAuthorities() {
        return new ResponseEntity<>(authenticatedUser.getAuthentication(), HttpStatus.OK); //getAuthentication returns CustomUserDetails instance
    }
</code>```

And I'm getting
org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: Not allowed.

How can I handle this? Ingore or set some default value to this property.

UPD I cannot add @JsonIngore to that class because it's not my library, I don't have access to its source.

答:
You can write JsonIgnore annotation on top of getPassword() method.This way you tell Jackon to not attempt serialization of that field

https://fasterxml.github.io/jackson-annotations/javadoc/2.4/com/fasterxml/jackson/annotation/JsonIgnore.html

Body:
I use an external library that has a method:

public class CustomUserDetails implements UserDetails {

    private final User principal;
    private final Collection<GrantedAuthority> authorities;

    //constructor, getters, setters

    @Override
    public String getPassword() {
        throw new UnsupportedOperationException("Not allowed");
    }
}

And I have a @RequestMapping that returns an instance of that object:

@RequestMapping(value = "/authorities", method = GET)
    public ResponseEntity getAuthorities() {
        return new ResponseEntity<>(authenticatedUser.getAuthentication(), HttpStatus.OK); //getAuthentication returns CustomUserDetails instance
    }

And I'm getting
org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: Not allowed.

How can I handle this? Ingore or set some default value to this property.

UPD I cannot add @JsonIngore to that class because it's not my library, I don't have access to its source.


问:
AsyncTask only returns first JSONObject in JSONArray
I have a problem with json object in android application from php script. On Log.i(finalJson,"json object") i see i logcat that json async task return only first element from list. I test my php in POSTMAN and it looks like:

```<code>    [
        {
            "ID": "1",
            "Description": "Plisani meda",
            "Price": "1000",
            "Image": "http://www.volimsvojdom.rs/wf-proizvodiPics/47188/plisana-igracka-mis-u-pantalonama-LB80322.jpg"
        },
        {
            "ID": "2",
            "Description": "poni",
            "Price": "2000",
            "Image": "http://www.volimsvojdom.rs/wf-proizvodiPics/47188/plisana-igracka-mis-u-pantalonama-LB80322.jpg"
        }
    ]
</code>```

```<code>public class JSONTask extends AsyncTask<String,String,List<Prozivod>>
{

   @Override
    protected List<Prozivod> doInBackground(String... params) {
       HttpURLConnection connection=null;
       BufferedReader reader=null;

       try {
           URL url=new URL(params[0]);
           connection=(HttpURLConnection)url.openConnection();
           connection.connect();
           InputStream stream=connection.getInputStream();
           reader=new BufferedReader(new InputStreamReader(stream));
           StringBuffer buffer=new StringBuffer();
           String line="";
           while((line=reader.readLine())!=null)
           {
            buffer.append(line);

           }

           String finalJson=buffer.toString();
           JSONArray jsonArray=new JSONArray(finalJson);
           Log.i(finalJson,"json object");
           List<Products> listOfItems=new ArrayList<>();
           for(int i=0;i<jsonArray.length();i++)
           {
               JSONObject itemJson=jsonArray.getJSONObject(i);
               Products p=new Products();
               p.setProizvodID(proizvodJson.getInt("ID"));
               p.setCena(proizvodJson.getInt("Price"));
               p.setOpis(proizvodJson.getString("Description"));
               p.setSlika(proizvodJson.getString("Image"));
               listOfItems.add(p);
               return  listOfItems;

           }
       } catch (MalformedURLException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }
       catch (JSONException e) {
           e.printStackTrace();
       }finally {
           if(connection!=null){connection.disconnect();}
       }
       try{if(reader!=null){reader.close();}}
       catch (IOException e) {
           e.printStackTrace();
       }
       return null ;
   }
</code>```

Thank's for any help!

答:
You are returning the list just after it iterates once. Try this :

```<code>for(int i=0;i<jsonArray.length();i++)
       {
           JSONObject itemJson=jsonArray.getJSONObject(i);
           Products p=new Products();
           p.setProizvodID(proizvodJson.getInt("ID"));
           p.setCena(proizvodJson.getInt("Price"));
           p.setOpis(proizvodJson.getString("Description"));
           p.setSlika(proizvodJson.getString("Image"));
           listOfItems.add(p);
       }
       return  listOfItems;
</code>```

Hope this helps.

Body:
I have a problem with json object in android application from php script. On Log.i(finalJson,"json object") i see i logcat that json async task return only first element from list. I test my php in POSTMAN and it looks like:

    [
        {
            "ID": "1",
            "Description": "Plisani meda",
            "Price": "1000",
            "Image": "http://www.volimsvojdom.rs/wf-proizvodiPics/47188/plisana-igracka-mis-u-pantalonama-LB80322.jpg"
        },
        {
            "ID": "2",
            "Description": "poni",
            "Price": "2000",
            "Image": "http://www.volimsvojdom.rs/wf-proizvodiPics/47188/plisana-igracka-mis-u-pantalonama-LB80322.jpg"
        }
    ]

public class JSONTask extends AsyncTask<String,String,List<Prozivod>>
{

   @Override
    protected List<Prozivod> doInBackground(String... params) {
       HttpURLConnection connection=null;
       BufferedReader reader=null;

       try {
           URL url=new URL(params[0]);
           connection=(HttpURLConnection)url.openConnection();
           connection.connect();
           InputStream stream=connection.getInputStream();
           reader=new BufferedReader(new InputStreamReader(stream));
           StringBuffer buffer=new StringBuffer();
           String line="";
           while((line=reader.readLine())!=null)
           {
            buffer.append(line);

           }

           String finalJson=buffer.toString();
           JSONArray jsonArray=new JSONArray(finalJson);
           Log.i(finalJson,"json object");
           List<Products> listOfItems=new ArrayList<>();
           for(int i=0;i<jsonArray.length();i++)
           {
               JSONObject itemJson=jsonArray.getJSONObject(i);
               Products p=new Products();
               p.setProizvodID(proizvodJson.getInt("ID"));
               p.setCena(proizvodJson.getInt("Price"));
               p.setOpis(proizvodJson.getString("Description"));
               p.setSlika(proizvodJson.getString("Image"));
               listOfItems.add(p);
               return  listOfItems;

           }
       } catch (MalformedURLException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }
       catch (JSONException e) {
           e.printStackTrace();
       }finally {
           if(connection!=null){connection.disconnect();}
       }
       try{if(reader!=null){reader.close();}}
       catch (IOException e) {
           e.printStackTrace();
       }
       return null ;
   }

Thank's for any help!

Body:
You are returning the list just after it iterates once. Try this :

for(int i=0;i<jsonArray.length();i++)
       {
           JSONObject itemJson=jsonArray.getJSONObject(i);
           Products p=new Products();
           p.setProizvodID(proizvodJson.getInt("ID"));
           p.setCena(proizvodJson.getInt("Price"));
           p.setOpis(proizvodJson.getString("Description"));
           p.setSlika(proizvodJson.getString("Image"));
           listOfItems.add(p);
       }
       return  listOfItems;

Hope this helps.


问:
Flash CS, reference root from external class
I made this class and I put it in the same package of Timeline.as (the Document Class):

```<code>package {
    import flash.utils.Timer;
    import flash.events.TimerEvent;

    public class Counter2 extends Timer {

        public function Counter2(delay:Number, repeatCount:int=0) {
            super(delay, repeatCount);
            super.addEventListener(TimerEvent.TIMER, timerHandler);
        }

        public override function start():void {
            super.start();
        }
        public override function stop():void {
            super.stop();
        }
        public function timerHandler(evt:TimerEvent) {
            trace(evt.target.currentCount);
        }
    }
}
</code>```

This class is instanciated in Timeline.as constructor.
Is there any way to reference Timeline(root) from this class? And, if so, how?

Thanks!

答:
The static Stage object is only accessible to objects on the display list. Try creating a public method in your custom timer class & use that to pass (and store) a reference to the stage.... like so:

Document class (or another object currently on the display list):

```<code>package {
    import TestDependency;
    import flash.display.MovieClip;

    public class Main extends MovieClip
    {
        public var td:TestDependency;

        function Main() {
            td = new TestDependency(1000);
            td.bindToStage(this.stage);
        }
    }
}
</code>```

Your custom class (not in the display list:

```<code>package {
    import flash.display.Stage;
    import flash.utils.Timer;
    public class TestDependency extends Timer
    {
        private var stageRef:Stage;

        function TestDependency(delay) {
            super(delay);
        }

        public function bindToStage($stageRef:Stage)
        {
            this.stageRef = $stageRef;
            trace(this.stageRef.stageWidth);
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I made this class and I put it in the same package of Timeline.as (the Document Class):

package {
    import flash.utils.Timer;
    import flash.events.TimerEvent;

    public class Counter2 extends Timer {

        public function Counter2(delay:Number, repeatCount:int=0) {
            super(delay, repeatCount);
            super.addEventListener(TimerEvent.TIMER, timerHandler);
        }

        public override function start():void {
            super.start();
        }
        public override function stop():void {
            super.stop();
        }
        public function timerHandler(evt:TimerEvent) {
            trace(evt.target.currentCount);
        }
    }
}

This class is instanciated in Timeline.as constructor.
Is there any way to reference Timeline(root) from this class? And, if so, how?

Thanks!

Body:
The static Stage object is only accessible to objects on the display list. Try creating a public method in your custom timer class & use that to pass (and store) a reference to the stage.... like so:

Document class (or another object currently on the display list):

package {
    import TestDependency;
    import flash.display.MovieClip;

    public class Main extends MovieClip
    {
        public var td:TestDependency;

        function Main() {
            td = new TestDependency(1000);
            td.bindToStage(this.stage);
        }
    }
}

Your custom class (not in the display list:

package {
    import flash.display.Stage;
    import flash.utils.Timer;
    public class TestDependency extends Timer
    {
        private var stageRef:Stage;

        function TestDependency(delay) {
            super(delay);
        }

        public function bindToStage($stageRef:Stage)
        {
            this.stageRef = $stageRef;
            trace(this.stageRef.stageWidth);
        }
    }
}


问:
Opencv-Python input array error
I recently started to explore OpenCV and I am very knew to this. I am having trouble displaying an scaled video frame inside a original video frame. Hope this makes sense. everything works fine but when i tried to change the color of the scaled video, I get an error. Here is my code hopefully its self explanatory.

```<code>import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while True:
    #"ret" returns a frame
    ret, frame = cap.read()

    #Draw a rectangle at given location
    cv2.rectangle(frame,(500,80),(800,380),(0,255,0),5)

    #takes a sample of the frame marked by the rectangle area(y,x)
    face_track = frame[80:380, 500:800]
    #converts the sample to gray
    grayscaled = cv2.cvtColor(face_track,cv2.COLOR_BGR2GRAY)
    #threshold range of sample
    retvl, threshold = cv2.threshold(grayscaled,125,125,cv2.THRESH_BINARY)

    #overwrites/display a new area with the sample taken by face_track in the left top corner of the frame
    frame[0:300, 0:300] = threshold

    #displays the frames captured by cap
    cv2.imshow('frame',frame)
    #cv2.imshow('frame',threshold)

    #if key stroke is 'q' break and terminate
    if cv2.waitKey(0) & 0xff == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
</code>```

the following is the error:

frame[0:300, 0:300] = threshold
  ValueError: could not broadcast input array from shape (300,300) into shape (300,300,3)

If I change it to this:

frame[0:300, 0:300] = face_track

It works. But is not what I want.

Also if I output threshold instead, as such,
cv2.imshow('frame',threshold),
it would also work. But again not what I want.

Is there any other function besides cv2.cvtColor that does not change the array shape.

答:
convert thresh gray to BGR

cv2.cvtColor(threshold,cv2.COLOR_GRAY2BGR)

Title: Opencv-Python input array error

Body:
I recently started to explore OpenCV and I am very knew to this. I am having trouble displaying an scaled video frame inside a original video frame. Hope this makes sense. everything works fine but when i tried to change the color of the scaled video, I get an error. Here is my code hopefully its self explanatory.

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while True:
    #"ret" returns a frame
    ret, frame = cap.read()

    #Draw a rectangle at given location
    cv2.rectangle(frame,(500,80),(800,380),(0,255,0),5)

    #takes a sample of the frame marked by the rectangle area(y,x)
    face_track = frame[80:380, 500:800]
    #converts the sample to gray
    grayscaled = cv2.cvtColor(face_track,cv2.COLOR_BGR2GRAY)
    #threshold range of sample
    retvl, threshold = cv2.threshold(grayscaled,125,125,cv2.THRESH_BINARY)

    #overwrites/display a new area with the sample taken by face_track in the left top corner of the frame
    frame[0:300, 0:300] = threshold

    #displays the frames captured by cap
    cv2.imshow('frame',frame)
    #cv2.imshow('frame',threshold)

    #if key stroke is 'q' break and terminate
    if cv2.waitKey(0) & 0xff == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

the following is the error:

frame[0:300, 0:300] = threshold
  ValueError: could not broadcast input array from shape (300,300) into shape (300,300,3)

If I change it to this:

frame[0:300, 0:300] = face_track

It works. But is not what I want.

Also if I output threshold instead, as such,
cv2.imshow('frame',threshold),
it would also work. But again not what I want.

Is there any other function besides cv2.cvtColor that does not change the array shape.


问:
C program calling a string to int function, I am unable to convert the input
I would like to convert a string to an int and calling the function from main. Where the first character is a letter declaring the base of the number and the rest of the characters in the string are the number. I am able to get the function to work separately, but when using the main function to call it will not print out the correct values.

Example of  user input using binary:

```<code>b1000
b1010
</code>```

result should be:

```<code>b
b
1000
1010
</code>```

Here is the code:

```<code>#include <stdio.h>
#include <string.h>
#include <math.h>

int str_to_int(inputbase) {
    char num1[50];
    num1[50] = inputbase;

    char numcpy1[sizeof(num1) - 1];

    int  i, len1;
    int result1 = 0;

    //printf("String: ");
    //gets(num1);

    //Access first character for base
    printf("%c \n", num1[0]);

    //Remove first character for number1 and number 2
    if (strlen(num1) > 0) {
        strcpy(numcpy1, &(num1[1]));
    } else {
        strcpy(numcpy1, num1);
    }
    len1 = strlen(numcpy1);

    //Turn remaining string characters into an int
    for (i = 0; i < len1; i++) {
        result1 = result1 * 10 + ( numcpy1[i] - '0' );
    }

    printf("%d \n", result1);
    return result1;
}

int main() {
    char *number1[50], *number2[50];
    int one, two;

    printf("\nAsk numbers: \n");

    gets(number1);
    gets(number2);

    one = str_to_int(number1);
    two = str_to_int(number2);

    printf("\nVerifying...\n");
    printf("%d\n", one);
    printf("%d\n", two);

    return 0;
}
</code>```

答:
I suppose your code cannot be compiled because some errors.

The first one is in the line

```<code> int str_to_int(inputbase)
</code>```

where inputbase are defined without type.

If this changed to

```<code> int str_to_int(char * inputbase)
</code>```

the next point for improvement is in line

```<code> num1[50] = inputbase;
</code>```

assignement like that has set of errors:

num1[50] means access to 51th item, but there is only 50 items indexed from 0 to 49

statement num1[0] = inputbase; (as well as with any other correct index) is wrong because of difference in types: num1[0] is char, but inputbase is pointer

num1 = inputbase; will be also wrong (for copying string = cannot be used in C, so consider making loop or using standard library function strncpy)

And since this is only the beginning of problems, I suggest starting from decimal input using some standard function for conversion char* string to int (e.g. atoi, or sscanf), then after you check the program and find it correct if it is required you can avoid using standard conversion and write your own str_to_int

Body:
I would like to convert a string to an int and calling the function from main. Where the first character is a letter declaring the base of the number and the rest of the characters in the string are the number. I am able to get the function to work separately, but when using the main function to call it will not print out the correct values.

Example of  user input using binary:

b1000
b1010

result should be:

b
b
1000
1010

Here is the code:

#include <stdio.h>
#include <string.h>
#include <math.h>

int str_to_int(inputbase) {
    char num1[50];
    num1[50] = inputbase;

    char numcpy1[sizeof(num1) - 1];

    int  i, len1;
    int result1 = 0;

    //printf("String: ");
    //gets(num1);

    //Access first character for base
    printf("%c \n", num1[0]);

    //Remove first character for number1 and number 2
    if (strlen(num1) > 0) {
        strcpy(numcpy1, &(num1[1]));
    } else {
        strcpy(numcpy1, num1);
    }
    len1 = strlen(numcpy1);

    //Turn remaining string characters into an int
    for (i = 0; i < len1; i++) {
        result1 = result1 * 10 + ( numcpy1[i] - '0' );
    }

    printf("%d \n", result1);
    return result1;
}

int main() {
    char *number1[50], *number2[50];
    int one, two;

    printf("\nAsk numbers: \n");

    gets(number1);
    gets(number2);

    one = str_to_int(number1);
    two = str_to_int(number2);

    printf("\nVerifying...\n");
    printf("%d\n", one);
    printf("%d\n", two);

    return 0;
}

Body:
I suppose your code cannot be compiled because some errors.

The first one is in the line

 int str_to_int(inputbase)

where inputbase are defined without type.

If this changed to

 int str_to_int(char * inputbase)

the next point for improvement is in line

 num1[50] = inputbase;

assignement like that has set of errors:

num1[50] means access to 51th item, but there is only 50 items indexed from 0 to 49

statement num1[0] = inputbase; (as well as with any other correct index) is wrong because of difference in types: num1[0] is char, but inputbase is pointer

num1 = inputbase; will be also wrong (for copying string = cannot be used in C, so consider making loop or using standard library function strncpy)

And since this is only the beginning of problems, I suggest starting from decimal input using some standard function for conversion char* string to int (e.g. atoi, or sscanf), then after you check the program and find it correct if it is required you can avoid using standard conversion and write your own str_to_int


问:
Interactively add shapes to Three.js scene
I would like to interactively draw/delete custom shapes (rectangle, circle) using the mouse on a Three.js scene. Can you please let me know if it is possible?</p>

答:
Yes, it is possible.

There are official examples (at least for cubes) you could use for a base to build upon. Here is the voxel painter which gives the creation/interaction you may be looking for:

https://threejs.org/examples/webgl_interactive_voxelpainter.html


问:
Viewing Serialized Hash Rails
I am trying to build a default checklist for my application by serializing a hash. I don't know how to pull the information in my setup_checklist hash to my views. Any help is appreciated.

Here is my user model

```<code>class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :confirmable

  serialize :checklist, Hash

  before_create :setup_checklist

  private

  def setup_checklist
    self.checklist = {
      "Organize Your Finances" => false,
      "Approval Letter" => false,
      "Get a Real Estate Agent and look for houses" => false,
      "Find lawyer" => false,
      "Get the mortgage" => false,
      "Apprisal and inspection" => false,
      "Close the deal" => false
    }
  end
end
</code>```

my view.html.erb

```<code><%= form_for :checklist do |f| %>
  <%= f.check_box :checklist %>
<% end %>
</code>```

I know I am not even close but a steer in the right direction would be great

答:
May not be the prettiest, but this seems to be working for me

view.html.erb

```<code><%= form_for @user do |f| %>
  <%= f.fields_for :checklist do |c| %>
    <% @user.checklist.each do |todo, completed| %>
      <%= c.check_box todo %> <%= c.label todo %><br />
    <% end %>
  <% end %>

  <%= f.submit %>
<% end %>
</code>```

and then in the controller

```<code>def update
  @user = User.find(params[:id])
  @user.checklist.each do |todo, completed|
    @user.checklist[todo] = params[:user][:checklist][todo] == "1"
  end
  @user.save

  redirect_to action: :show, id: params[:id]
end
</code>```

you could, of course, move that controller code into something like an update_checklist method on your model or refactor however works for you, but this should get you started.

If you use strong params, you'll need to permit each possible checklist value and it'll set them to '0' or '1' instead of true or false, but the controller could be

```<code>    @user.update(params.required(:user).permit(checklist: ["Organize Your Finances", ...]))
</code>```

Title: Viewing Serialized Hash Rails

Body:
I am trying to build a default checklist for my application by serializing a hash. I don't know how to pull the information in my setup_checklist hash to my views. Any help is appreciated.

Here is my user model

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :confirmable

  serialize :checklist, Hash

  before_create :setup_checklist

  private

  def setup_checklist
    self.checklist = {
      "Organize Your Finances" => false,
      "Approval Letter" => false,
      "Get a Real Estate Agent and look for houses" => false,
      "Find lawyer" => false,
      "Get the mortgage" => false,
      "Apprisal and inspection" => false,
      "Close the deal" => false
    }
  end
end

my view.html.erb

<%= form_for :checklist do |f| %>
  <%= f.check_box :checklist %>
<% end %>

I know I am not even close but a steer in the right direction would be great

Body:
May not be the prettiest, but this seems to be working for me

view.html.erb

<%= form_for @user do |f| %>
  <%= f.fields_for :checklist do |c| %>
    <% @user.checklist.each do |todo, completed| %>
      <%= c.check_box todo %>&nbsp;<%= c.label todo %><br />
    <% end %>
  <% end %>

  <%= f.submit %>
<% end %>

and then in the controller

def update
  @user = User.find(params[:id])
  @user.checklist.each do |todo, completed|
    @user.checklist[todo] = params[:user][:checklist][todo] == "1"
  end
  @user.save

  redirect_to action: :show, id: params[:id]
end

you could, of course, move that controller code into something like an update_checklist method on your model or refactor however works for you, but this should get you started.

If you use strong params, you'll need to permit each possible checklist value and it'll set them to '0' or '1' instead of true or false, but the controller could be

    @user.update(params.required(:user).permit(checklist: ["Organize Your Finances", ...]))


问:
CMake linking Windows SDK
I have a project in CLion in which I need to include a library from the Windows 8.1 SDK, so I attempted to use CMake to link it.

I don't have any .so or .dll, but .lib (or directly the .h file).

Specifically, this library is dsound.h.

I tried to look for related questions, but none of the solutions I found works for me: how can I do it?

My current CMakeLists.txt is

```<code>cmake_minimum_required(VERSION 3.7)

project(Project)

set(CMAKE_CXX_STANDARD 11)

include_directories(${WinSDK})

set(SOURCE_FILES main.cpp file1.h file1.cpp)
add_executable(Project ${SOURCE_FILES})
target_link_libraries(Project ${WinSDK})
</code>```

where WinSDK is the variable containing the location of the Windows SDK.

The error I get is the following:

```<code>[ 33%] Building CXX object CMakeFiles/Project.dir/main.cpp.obj
[ 66%] Building CXX object CMakeFiles/Project.dir/soundclass.cpp.obj
In file included from C:\projectPath\soundclass.cpp:4:0:
C:\projectPath\soundclass.h:21:24: fatal error: dsound.h: No such file or directory
In file included from C:\projectPath\main.cpp:5:0:
C:\projectPath\soundclass.h:21:24: fatal error: dsound.h: No such file or directory
compilation terminated.
compilation terminated.
CMakeFiles\Project.dir\build.make:61: recipe for target 'CMakeFiles/Project.dir/main.cpp.obj' failed
CMakeFiles\Project.dir\build.make:85: recipe for target 'CMakeFiles/Project.dir/soundclass.cpp.obj' failed
CMakeFiles\Makefile2:66: recipe for target 'CMakeFiles/Project.dir/all' failed
mingw32-make.exe[3]: *** [CMakeFiles/Project.dir/main.cpp.obj] Error 1
mingw32-make.exe[3]: *** Waiting for unfinished jobs....
mingw32-make.exe[3]: *** [CMakeFiles/Project.dir/soundclass.cpp.obj] Error 1
mingw32-make.exe[2]: *** [CMakeFiles/Project.dir/all] Error 2
CMakeFiles\Makefile2:78: recipe for target 'CMakeFiles/Project.dir/rule' failed
Makefile:117: recipe for target 'Project' failed
mingw32-make.exe[1]: *** [CMakeFiles/Project.dir/rule] Error 2
mingw32-make.exe: *** [Project] Error 2
</code>```

答:
${WinSDK} cannot be set correctly since you are using the same variable in the same way for both include and library.

Other tips:

CMAKE_CXX_STANDARD does nothing for the MSVC compiler

it is better to use target_include_directories() than include_directories() to keep target information cleaner

Title: CMake linking Windows SDK

Body:
I have a project in CLion in which I need to include a library from the Windows 8.1 SDK, so I attempted to use CMake to link it.

I don't have any .so or .dll, but .lib (or directly the .h file).

Specifically, this library is dsound.h.

I tried to look for related questions, but none of the solutions I found works for me: how can I do it?

My current CMakeLists.txt is

cmake_minimum_required(VERSION 3.7)

project(Project)

set(CMAKE_CXX_STANDARD 11)

include_directories(${WinSDK})

set(SOURCE_FILES main.cpp file1.h file1.cpp)
add_executable(Project ${SOURCE_FILES})
target_link_libraries(Project ${WinSDK})

where WinSDK is the variable containing the location of the Windows SDK.

The error I get is the following:

[ 33%] Building CXX object CMakeFiles/Project.dir/main.cpp.obj
[ 66%] Building CXX object CMakeFiles/Project.dir/soundclass.cpp.obj
In file included from C:\projectPath\soundclass.cpp:4:0:
C:\projectPath\soundclass.h:21:24: fatal error: dsound.h: No such file or directory
In file included from C:\projectPath\main.cpp:5:0:
C:\projectPath\soundclass.h:21:24: fatal error: dsound.h: No such file or directory
compilation terminated.
compilation terminated.
CMakeFiles\Project.dir\build.make:61: recipe for target 'CMakeFiles/Project.dir/main.cpp.obj' failed
CMakeFiles\Project.dir\build.make:85: recipe for target 'CMakeFiles/Project.dir/soundclass.cpp.obj' failed
CMakeFiles\Makefile2:66: recipe for target 'CMakeFiles/Project.dir/all' failed
mingw32-make.exe[3]: *** [CMakeFiles/Project.dir/main.cpp.obj] Error 1
mingw32-make.exe[3]: *** Waiting for unfinished jobs....
mingw32-make.exe[3]: *** [CMakeFiles/Project.dir/soundclass.cpp.obj] Error 1
mingw32-make.exe[2]: *** [CMakeFiles/Project.dir/all] Error 2
CMakeFiles\Makefile2:78: recipe for target 'CMakeFiles/Project.dir/rule' failed
Makefile:117: recipe for target 'Project' failed
mingw32-make.exe[1]: *** [CMakeFiles/Project.dir/rule] Error 2
mingw32-make.exe: *** [Project] Error 2


问:
.htaccess too many redirect after a END flag and Require all denied command
I'm trying to secure a sensible wordpress install, I need to make wp-login.php unreachable but last WordPress rewrite rule always being called even if a blocking rule it's on top of the .htaccess

```<code># BEGIN LETSENCRYPT AND COMODO
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} ^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} ^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteCond %{REQUEST_URI} ^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$
RewriteRule .* - [L]
# END LETSENCRYPT AND COMODO

<FilesMatch wp-login\.php>
  Require all denied
</FilesMatch>

#ADDED AS BACKUP PLAN, BUT DID NOT WORK EITHER
RewriteRule wp-login\.php$ - [END,R=403]

# BEGIN WordPress

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteRule ^index\.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^(.+)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^(.+)?(.*\.php)$ $2 [L]

#If I comment this rule the wp-login.php file it's protected
RewriteRule . index.php [L]

</IfModule>

# END WordPress
</code>```

I've tried with R=404 or redirect to real file instead of R=403 but last rule always take on my redirect

to be clear:
I expect a forbidden page on:
https://example.com/wp-login.php
 and
https://example.com/subsite/wp-login.php

instead a 404 Wordpress page is returned in both case

答:
Ok, I've found the solution:

```<code>RewriteRule wp-login\.php$ - [END,R=403]
</code>```

don't work 'cause the previous rule already change the status, so we can use the status to prevent other rule to override our result:

```<code>RewriteCond "%{ENV:REDIRECT_STATUS}" "=403"
RewriteRule . - [L]
</code>```

We can add a rule to catch the wp-login in multisite configuration
RewriteRule .*wp-login.php wp-login.php

The complete .htaccess now is:

```<code># BEGIN LETSENCRYPT AND COMODO
#
# PREVENT SSL REDIRECT FOR CERTIFICATES PROCESS
#

RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} ^/[0-9]+\..+\.cpaneldcv$ [OR]
RewriteCond %{REQUEST_URI} ^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$ [OR]
RewriteCond %{REQUEST_URI} ^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$
RewriteRule .* - [L]
# END LETSENCRYPT AND COMODO

#BEGIN PROTECT WP-LOGIN

#MULTISITE WP
#this rule it's only for multisite install
RewriteRule .*wp-login\.php wp-login.php

#THIS RULES PREVENT SERVER LOAD ON A wp-login ATTACK
<FilesMatch wp-login\.php>
  Require all denied
</FilesMatch>

RewriteCond "%{ENV:REDIRECT_STATUS}" "=403"
RewriteRule . - [L]
#END PROTECT WP-LOGIN

#FORCE SSL
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [R,L]

# BEGIN WordPress
#
# WORDPRESS MULTISITE WITH CUSTOM SUNRISE SETTING
#

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteRule ^index\.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^(.+)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^(.+)?(.*\.php)$ $2 [L]

RewriteRule . index.php [L]

</IfModule>
</code>```

Body:
I'm trying to secure a sensible wordpress install, I need to make wp-login.php unreachable but last WordPress rewrite rule always being called even if a blocking rule it's on top of the .htaccess

# BEGIN LETSENCRYPT AND COMODO
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} ^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} ^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteCond %{REQUEST_URI} ^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$
RewriteRule .* - [L]
# END LETSENCRYPT AND COMODO

<FilesMatch wp-login\.php>
  Require all denied
</FilesMatch>

#ADDED AS BACKUP PLAN, BUT DID NOT WORK EITHER
RewriteRule wp-login\.php$ - [END,R=403]

# BEGIN WordPress

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteRule ^index\.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^(.+)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^(.+)?(.*\.php)$ $2 [L]

#If I comment this rule the wp-login.php file it's protected
RewriteRule . index.php [L]

</IfModule>

# END WordPress

I've tried with R=404 or redirect to real file instead of R=403 but last rule always take on my redirect

to be clear:
I expect a forbidden page on:
https://example.com/wp-login.php
 and
https://example.com/subsite/wp-login.php

instead a 404 Wordpress page is returned in both case

Body:
Ok, I've found the solution:

RewriteRule wp-login\.php$ - [END,R=403]

don't work 'cause the previous rule already change the status, so we can use the status to prevent other rule to override our result:

RewriteCond "%{ENV:REDIRECT_STATUS}" "=403"
RewriteRule . - [L]

We can add a rule to catch the wp-login in multisite configuration
RewriteRule .*wp-login.php wp-login.php

The complete .htaccess now is:

# BEGIN LETSENCRYPT AND COMODO
#
# PREVENT SSL REDIRECT FOR CERTIFICATES PROCESS
#

RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} ^/[0-9]+\..+\.cpaneldcv$ [OR]
RewriteCond %{REQUEST_URI} ^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$ [OR]
RewriteCond %{REQUEST_URI} ^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$
RewriteRule .* - [L]
# END LETSENCRYPT AND COMODO

#BEGIN PROTECT WP-LOGIN

#MULTISITE WP
#this rule it's only for multisite install
RewriteRule .*wp-login\.php wp-login.php

#THIS RULES PREVENT SERVER LOAD ON A wp-login ATTACK
<FilesMatch wp-login\.php>
  Require all denied
</FilesMatch>

RewriteCond "%{ENV:REDIRECT_STATUS}" "=403"
RewriteRule . - [L]
#END PROTECT WP-LOGIN

#FORCE SSL
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [R,L]

# BEGIN WordPress
#
# WORDPRESS MULTISITE WITH CUSTOM SUNRISE SETTING
#

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteRule ^index\.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^(.+)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^(.+)?(.*\.php)$ $2 [L]

RewriteRule . index.php [L]

</IfModule>


问:
Android Non Touch Consuming Dialog
How would I create a dialog which does not consume touch events. Ie. I want to be able to interact with the underlying activity as normal.

```<code>public class LoadingDialog extends Dialog {

    public LoadingDialog(Context context) {
        super(context);
        setContentView(R.layout.loading_dialog);
        setCanceledOnTouchOutside(false);
        getWindow().setBackgroundDrawable(new
            ColorDrawable(android.graphics.Color.TRANSPARENT));
    }
}
</code>```

I tried the following with no success

```<code>@Override
    public boolean dispatchTouchEvent(@NonNull MotionEvent ev) {
       return false;
}
</code>```

Thanks

答: Rather than use a dialogue, you can use a view that covers the whole screen with a tint and another view that looks like a dialogue on top of the tint and pass all touch events to the view below. Remove and show the dialogue by toggling the visibility of the view.</p>

Title: Android Non Touch Consuming Dialog

Body:
How would I create a dialog which does not consume touch events. Ie. I want to be able to interact with the underlying activity as normal.

public class LoadingDialog extends Dialog {

    public LoadingDialog(Context context) {
        super(context);
        setContentView(R.layout.loading_dialog);
        setCanceledOnTouchOutside(false);
        getWindow().setBackgroundDrawable(new
            ColorDrawable(android.graphics.Color.TRANSPARENT));
    }
}

I tried the following with no success

@Override
    public boolean dispatchTouchEvent(@NonNull MotionEvent ev) {
       return false;
}

Thanks


问:
Mockito : AssertionError expecting True but gives False
It seems that when both f.isColored() && fm.isColored() are together the method returns false, but if i use them separately the method returns correctly true.

This method 0 doesn't pass the test

```<code> @Override
    public boolean colorConstraint(ActionSpace as, FamilyMember fm) {
        for (FamilyMember f : as.getFamilyMembers()) {
            if (true && f.isColored() && fm.isColored()) //this does not work
                return false;
        }
        return true;
    }
</code>```

Test passes with this method 1

```<code>@Override
    public boolean colorConstraint(ActionSpace as, FamilyMember fm) {
        for (FamilyMember f : as.getFamilyMembers()) {
            if (true && false && fm.isColored())
                return false;
        }
        return true;
    }
</code>```

Test passes with this method 2

```<code>@Override
public boolean colorConstraint(ActionSpace as, FamilyMember fm) {
    for (FamilyMember f : as.getFamilyMembers()) {
        if (true && f.isColored() && true)
            return false;
    }
    return true;
}
</code>```

Test method

```<code> @Test
    public void neutralFMInASAndSameOwner() {
        //given
        List<FamilyMember> familyMemberList;
        familyMemberList = Arrays.asList(fm);
        when(as.getFamilyMembers()).thenReturn(familyMemberList);

/*this is commented when using method 1 */
        //family member in action space is neutral
        when(familyMemberList.get(0).isColored()).thenReturn(false);

/*this is commented when using method 2 */
        //fm to place is colored
        when(fm.isColored()).thenReturn(true);
        //when
        Boolean bool;
        bool = harvestProductionASController.colorConstraint(as, fm);
        //then
        assertTrue(bool); //AssertionError when using method 0
    }
</code>```

答:
```<code> List<FamilyMember> familyMemberList;
 familyMemberList = Arrays.asList(fm);
 when(as.getFamilyMembers()).thenReturn(familyMemberList);

/*this is commented when using method 1 */
 //family member in action space is neutral
 when(familyMemberList.get(0).isColored()).thenReturn(false);
</code>```

where is familyMemberList.get(0) it's fm , it's the same as

```<code>when(fm.isColored()).thenReturn(false);
</code>```

as you add as zero element fm  into familyMemberList

so in your code it's:

when(fm.isColored()).thenReturn(false);--for first call return false
when(fm.isColored()).thenReturn(true); --for second call return true

fm - it's mocked object , for mock object mockito can works like : if call method first time then retuns X , if call method second time then returns Y.....
and it your case you applyed this behaviour.

in method colorConstraint you have check :

```<code>if (f.isColored() && fm.isColored()) //this does not work
   return false;
</code>```

f.isColored()  has value - false
fm.isColored() has result - true

so result for this method, for your test,  is false .

fix : (don't use same object)

```<code> List<FamilyMember> familyMemberList;
 FamilyMember fmNew= new ();
 familyMemberList = Arrays.asList(fmNew);
</code>```

just remark :

change
if (true && f.isColored() && fm.isColored()) -->(f.isColored() && fm.isColored())

if (true && false && fm.isColored()) -->if (!fm.isColored())

if (true && f.isColored() && true) -->if (f.isColored())

Body:
It seems that when both f.isColored() && fm.isColored() are together the method returns false, but if i use them separately the method returns correctly true.

This method 0 doesn't pass the test

 @Override
    public boolean colorConstraint(ActionSpace as, FamilyMember fm) {
        for (FamilyMember f : as.getFamilyMembers()) {
            if (true && f.isColored() && fm.isColored()) //this does not work
                return false;
        }
        return true;
    }

Test passes with this method 1

@Override
    public boolean colorConstraint(ActionSpace as, FamilyMember fm) {
        for (FamilyMember f : as.getFamilyMembers()) {
            if (true && false && fm.isColored())
                return false;
        }
        return true;
    }

Test passes with this method 2

@Override
public boolean colorConstraint(ActionSpace as, FamilyMember fm) {
    for (FamilyMember f : as.getFamilyMembers()) {
        if (true && f.isColored() && true)
            return false;
    }
    return true;
}

Test method

 @Test
    public void neutralFMInASAndSameOwner() {
        //given
        List<FamilyMember> familyMemberList;
        familyMemberList = Arrays.asList(fm);
        when(as.getFamilyMembers()).thenReturn(familyMemberList);

/*this is commented when using method 1 */
        //family member in action space is neutral
        when(familyMemberList.get(0).isColored()).thenReturn(false);

/*this is commented when using method 2 */
        //fm to place is colored
        when(fm.isColored()).thenReturn(true);
        //when
        Boolean bool;
        bool = harvestProductionASController.colorConstraint(as, fm);
        //then
        assertTrue(bool); //AssertionError when using method 0
    }

Body:
 List<FamilyMember> familyMemberList;
 familyMemberList = Arrays.asList(fm);
 when(as.getFamilyMembers()).thenReturn(familyMemberList);

/*this is commented when using method 1 */
 //family member in action space is neutral
 when(familyMemberList.get(0).isColored()).thenReturn(false);

where is familyMemberList.get(0) it's fm , it's the same as

when(fm.isColored()).thenReturn(false);

as you add as zero element fm  into familyMemberList

so in your code it's:

when(fm.isColored()).thenReturn(false);--for first call return false
when(fm.isColored()).thenReturn(true); --for second call return true

fm - it's mocked object , for mock object mockito can works like : if call method first time then retuns X , if call method second time then returns Y.....
and it your case you applyed this behaviour.

in method colorConstraint you have check :

if (f.isColored() && fm.isColored()) //this does not work
   return false;

f.isColored()  has value - false
fm.isColored() has result - true

so result for this method, for your test,  is false .

fix : (don't use same object)

 List<FamilyMember> familyMemberList;
 FamilyMember fmNew= new ();
 familyMemberList = Arrays.asList(fmNew);

just remark :

change
if (true && f.isColored() && fm.isColored()) -->(f.isColored() && fm.isColored())

if (true && false && fm.isColored()) -->if (!fm.isColored())

if (true && f.isColored() && true) -->if (f.isColored())


问:
How to avoid TransientPropertyValueException
I have class Anagrafica (Account, in english) and I need to set, from a form, ID_Tipo_Anagrafica (Account type, in english). I made a form which can get list of ID_Tipo_Anagrafica but I can't create final object in order to put it in database.

anagrafica class

```<code>public class Anagrafica {
    private int ID_Anagrafica;
    private int ID_Tipo_Anagrafica;
    private String Nome;
    private String Cognome;
    private String Provincia;
    private String Codice_fiscale;
    private Ruolo Ruolo;
    private Utenza utenza;
    private Tessera tessera;
    private Set<Scontrino> scontrini = new HashSet<>(0);

    public Anagrafica() {
        super();
    }

    public Anagrafica(String nome, String cognome, String provincia, String codice_fiscale, Ruolo ruolo) {
        super();
        this.Nome = nome;
        this.Cognome = cognome;
        this.Provincia = provincia;
        this.Codice_fiscale = codice_fiscale;
        this.Ruolo = ruolo;
    }

    public int getID_Anagrafica() {
        return ID_Anagrafica;
    }
    public void setID_Anagrafica(int iD_Anagrafica) {
        ID_Anagrafica = iD_Anagrafica;
    }
    public String getNome() {
        return Nome;
    }
    public void setNome(String nome) {
        Nome = nome;
    }
    public String getCognome() {
        return Cognome;
    }
    public void setCognome(String cognome) {
        Cognome = cognome;
    }
    public String getProvincia() {
        return Provincia;
    }
    public void setProvincia(String provincia) {
        Provincia = provincia;
    }
    public String getCodice_fiscale() {
        return Codice_fiscale;
    }
    public void setCodice_fiscale(String codice_fiscale) {
        Codice_fiscale = codice_fiscale;
    }
    public Ruolo getRuolo() {
        return Ruolo;
    }
    public void setRuolo(Ruolo ruolo) {
        Ruolo = ruolo;
    }
    public Utenza getUtenza() {
        return utenza;
    }
    public void setUtenza(Utenza utenza) {
        this.utenza = utenza;
    }

    public Set<Scontrino> getScontrini() {
        return scontrini;
    }

    public void setScontrini (Set<Scontrino> scontrini) {
        this.scontrini = scontrini;
    }

    public Tessera getTessera() {
        return tessera;
    }

    public void setTessera(Tessera tessera) {
        this.tessera = tessera;
    }

    public int getID_Tipo_Anagrafica() {
        return ID_Tipo_Anagrafica;
    }

    public void setID_Tipo_Anagrafica(int ID_Tipo_Anagrafica) {
        this.ID_Tipo_Anagrafica = ID_Tipo_Anagrafica;
    }

}
</code>```

anagrafica action

```<code>public class AnagraficaStruts extends ActionSupport implements UserAware, ModelDriven<Anagrafica> {
    private static final long serialVersionUID = 1L;

    private Anagrafica anagrafica = new Anagrafica();
    private AnagraficaDAO dao = AnagraficaDAOFactory.getDAO();
    private List<Anagrafica> anagrafiche = null;

    private List<Ruolo> ruoli = null;
    private RuoloDAO ruoloDAO = RuoloDAOFactory.getDAO();

    public List<Ruolo> getRuoli() {
        return ruoli;
    }

    public void setRuoli(List<Ruolo> ruoli) {
        this.ruoli = ruoli;
    }

    public Anagrafica getAnagrafica() {
        return anagrafica;
    }

    public void setAnagrafica(Anagrafica anagrafica) {
        this.anagrafica = anagrafica;
    }

    public List<Anagrafica> getAnagrafiche() {
        return anagrafiche;
    }

    public void setAnagrafiche(List<Anagrafica> anagrafiche) {
        this.anagrafiche = anagrafiche;
    }

    public String listAnagrafiche(){
        ruoli = new ArrayList<Ruolo>();
        setAnagrafiche(dao.getAnagrafiche());
        for (int i=0; i<anagrafiche.size(); i++){
            anagrafica = anagrafiche.get(i);
            ruoli.add(anagrafica.getRuolo());
        }
        return SUCCESS;
    }

    public String addAnagrafica(){
        //anagrafica.setRuolo(ruolo);
        //dao.salvaAnagrafica(anagrafica);
        return "success";
    }

    @Override
    public Anagrafica getModel() {
        return anagrafica;
    }

}
</code>```

form in jsp

```<code><s:form action="addAnagrafica">
    <s:textfield name="Nome" label="Nome" />
    <s:textfield name="Cognome" label="Cognome" />
    <s:textfield name="Provincia" label="Provincia" />
    <s:textfield name="Codice_fiscale" label="Codice_fiscale" />
    <s:select label="Ruolo" headerKey="-1"
        headerValue="Seleziona il ruolo" list="ruoli" listKey="id"
        listValue="descrizione" name="Ruolo.id"/>
    <s:submit />
    <hr />
</s:form>
</code>```

error i get after submit insert

```<code>org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved beforeQuery current operation : it.unirc.pjam.Anagrafica.Model.Anagrafica.ruolo -> it.unirc.pjam.Ruolo.Model.Ruolo
    at org.hibernate.action.internal.UnresolvedEntityInsertActions.checkNoUnresolvedActionsAfterOperation(UnresolvedEntityInsertActions.java:122)
    at org.hibernate.engine.spi.ActionQueue.checkNoUnresolvedActionsAfterOperation(ActionQueue.java:418)
    at org.hibernate.internal.SessionImpl.checkNoUnresolvedActionsAfterOperation(SessionImpl.java:621)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:684)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
    at it.unirc.pjam.Anagrafica.DAO.AnagraficaDAOHibernateImpl.salvaAnagrafica(AnagraficaDAOHibernateImpl.java:42)
    at it.unirc.pjam.Action.AnagraficaStruts.addAnagrafica(AnagraficaStruts.java:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:873)
    at ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1539)
    at ognl.ObjectMethodAccessor.callMethod(ObjectMethodAccessor.java:68)
    at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethodWithDebugInfo(XWorkMethodAccessor.java:96)
    at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethod(XWorkMethodAccessor.java:88)
    at ognl.OgnlRuntime.callMethod(OgnlRuntime.java:1615)
    at ognl.ASTMethod.getValueBody(ASTMethod.java:91)
    at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
    at ognl.SimpleNode.getValue(SimpleNode.java:258)
    at ognl.Ognl.getValue(Ognl.java:467)
    at ognl.Ognl.getValue(Ognl.java:431)
    at com.opensymphony.xwork2.ognl.OgnlUtil$3.execute(OgnlUtil.java:351)
    at com.opensymphony.xwork2.ognl.OgnlUtil.compileAndExecuteMethod(OgnlUtil.java:403)
    at com.opensymphony.xwork2.ognl.OgnlUtil.callMethod(OgnlUtil.java:349)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:436)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:253)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:177)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:260)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:73)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.doIntercept(ConversionErrorInterceptor.java:139)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:133)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:133)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:192)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:69)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.DateTextFieldInterceptor.intercept(DateTextFieldInterceptor.java:115)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:88)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:246)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:99)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:139)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:155)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:174)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:120)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:171)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:195)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:193)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at it.unirc.pjam.utils.AuthenticationInterceptor.intercept(AuthenticationInterceptor.java:43)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.factory.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:564)
    at org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:81)
    at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:143)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:341)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:498)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:796)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1368)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
</code>```

答:
It looks like there is an Entity of type Ruolo assigned to your Anagrafica instance, but the Ruolo is still in transient state (new). This means, the Ruolo - where ever it's coming from - is not "known" within your current persistence context, yet. The Ruolo property on Anagrafica seems also mandatory (not null constraint), so at flush time you necessarily get following exception:

[...] TransientPropertyValueException: Not-null property references a transient value [...]

To solve this, you would either have to save the Ruolo before saving the Anagrafica or define a strategy for transitive persistence, a.k.a CascadeType. You have to decide what fits your use cases.

Find out more about Entity states and
transitive persistence in the docs or check out Vlad's beginners's guides about Entity state transitions with JPA and Hibernate and Hibernate Cascade Types.

Body:
I have class Anagrafica (Account, in english) and I need to set, from a form, ID_Tipo_Anagrafica (Account type, in english). I made a form which can get list of ID_Tipo_Anagrafica but I can't create final object in order to put it in database.

anagrafica class

public class Anagrafica {
    private int ID_Anagrafica;
    private int ID_Tipo_Anagrafica;
    private String Nome;
    private String Cognome;
    private String Provincia;
    private String Codice_fiscale;
    private Ruolo Ruolo;
    private Utenza utenza;
    private Tessera tessera;
    private Set<Scontrino> scontrini = new HashSet<>(0);

    public Anagrafica() {
        super();
    }

    public Anagrafica(String nome, String cognome, String provincia, String codice_fiscale, Ruolo ruolo) {
        super();
        this.Nome = nome;
        this.Cognome = cognome;
        this.Provincia = provincia;
        this.Codice_fiscale = codice_fiscale;
        this.Ruolo = ruolo;
    }

    public int getID_Anagrafica() {
        return ID_Anagrafica;
    }
    public void setID_Anagrafica(int iD_Anagrafica) {
        ID_Anagrafica = iD_Anagrafica;
    }
    public String getNome() {
        return Nome;
    }
    public void setNome(String nome) {
        Nome = nome;
    }
    public String getCognome() {
        return Cognome;
    }
    public void setCognome(String cognome) {
        Cognome = cognome;
    }
    public String getProvincia() {
        return Provincia;
    }
    public void setProvincia(String provincia) {
        Provincia = provincia;
    }
    public String getCodice_fiscale() {
        return Codice_fiscale;
    }
    public void setCodice_fiscale(String codice_fiscale) {
        Codice_fiscale = codice_fiscale;
    }
    public Ruolo getRuolo() {
        return Ruolo;
    }
    public void setRuolo(Ruolo ruolo) {
        Ruolo = ruolo;
    }
    public Utenza getUtenza() {
        return utenza;
    }
    public void setUtenza(Utenza utenza) {
        this.utenza = utenza;
    }

    public Set<Scontrino> getScontrini() {
        return scontrini;
    }

    public void setScontrini (Set<Scontrino> scontrini) {
        this.scontrini = scontrini;
    }

    public Tessera getTessera() {
        return tessera;
    }

    public void setTessera(Tessera tessera) {
        this.tessera = tessera;
    }

    public int getID_Tipo_Anagrafica() {
        return ID_Tipo_Anagrafica;
    }

    public void setID_Tipo_Anagrafica(int ID_Tipo_Anagrafica) {
        this.ID_Tipo_Anagrafica = ID_Tipo_Anagrafica;
    }

}

anagrafica action

public class AnagraficaStruts extends ActionSupport implements UserAware, ModelDriven<Anagrafica> {
    private static final long serialVersionUID = 1L;

    private Anagrafica anagrafica = new Anagrafica();
    private AnagraficaDAO dao = AnagraficaDAOFactory.getDAO();
    private List<Anagrafica> anagrafiche = null;

    private List<Ruolo> ruoli = null;
    private RuoloDAO ruoloDAO = RuoloDAOFactory.getDAO();

    public List<Ruolo> getRuoli() {
        return ruoli;
    }

    public void setRuoli(List<Ruolo> ruoli) {
        this.ruoli = ruoli;
    }

    public Anagrafica getAnagrafica() {
        return anagrafica;
    }

    public void setAnagrafica(Anagrafica anagrafica) {
        this.anagrafica = anagrafica;
    }

    public List<Anagrafica> getAnagrafiche() {
        return anagrafiche;
    }

    public void setAnagrafiche(List<Anagrafica> anagrafiche) {
        this.anagrafiche = anagrafiche;
    }

    public String listAnagrafiche(){
        ruoli = new ArrayList<Ruolo>();
        setAnagrafiche(dao.getAnagrafiche());
        for (int i=0; i<anagrafiche.size(); i++){
            anagrafica = anagrafiche.get(i);
            ruoli.add(anagrafica.getRuolo());
        }
        return SUCCESS;
    }

    public String addAnagrafica(){
        //anagrafica.setRuolo(ruolo);
        //dao.salvaAnagrafica(anagrafica);
        return "success";
    }

    @Override
    public Anagrafica getModel() {
        return anagrafica;
    }

}

form in jsp

<s:form action="addAnagrafica">
    <s:textfield name="Nome" label="Nome" />
    <s:textfield name="Cognome" label="Cognome" />
    <s:textfield name="Provincia" label="Provincia" />
    <s:textfield name="Codice_fiscale" label="Codice_fiscale" />
    <s:select label="Ruolo" headerKey="-1"
        headerValue="Seleziona il ruolo" list="ruoli" listKey="id"
        listValue="descrizione" name="Ruolo.id"/>
    <s:submit />

</s:form>

error i get after submit insert

org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved beforeQuery current operation : it.unirc.pjam.Anagrafica.Model.Anagrafica.ruolo -> it.unirc.pjam.Ruolo.Model.Ruolo
    at org.hibernate.action.internal.UnresolvedEntityInsertActions.checkNoUnresolvedActionsAfterOperation(UnresolvedEntityInsertActions.java:122)
    at org.hibernate.engine.spi.ActionQueue.checkNoUnresolvedActionsAfterOperation(ActionQueue.java:418)
    at org.hibernate.internal.SessionImpl.checkNoUnresolvedActionsAfterOperation(SessionImpl.java:621)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:684)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
    at it.unirc.pjam.Anagrafica.DAO.AnagraficaDAOHibernateImpl.salvaAnagrafica(AnagraficaDAOHibernateImpl.java:42)
    at it.unirc.pjam.Action.AnagraficaStruts.addAnagrafica(AnagraficaStruts.java:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:873)
    at ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1539)
    at ognl.ObjectMethodAccessor.callMethod(ObjectMethodAccessor.java:68)
    at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethodWithDebugInfo(XWorkMethodAccessor.java:96)
    at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethod(XWorkMethodAccessor.java:88)
    at ognl.OgnlRuntime.callMethod(OgnlRuntime.java:1615)
    at ognl.ASTMethod.getValueBody(ASTMethod.java:91)
    at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
    at ognl.SimpleNode.getValue(SimpleNode.java:258)
    at ognl.Ognl.getValue(Ognl.java:467)
    at ognl.Ognl.getValue(Ognl.java:431)
    at com.opensymphony.xwork2.ognl.OgnlUtil$3.execute(OgnlUtil.java:351)
    at com.opensymphony.xwork2.ognl.OgnlUtil.compileAndExecuteMethod(OgnlUtil.java:403)
    at com.opensymphony.xwork2.ognl.OgnlUtil.callMethod(OgnlUtil.java:349)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:436)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:253)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:177)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:260)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:73)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.doIntercept(ConversionErrorInterceptor.java:139)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:133)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:133)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:192)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:69)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.DateTextFieldInterceptor.intercept(DateTextFieldInterceptor.java:115)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:88)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:246)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:99)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:139)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:155)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:174)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:120)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:171)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:195)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:193)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at it.unirc.pjam.utils.AuthenticationInterceptor.intercept(AuthenticationInterceptor.java:43)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
    at org.apache.struts2.factory.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:564)
    at org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:81)
    at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:143)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:341)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:498)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:796)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1368)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)


问:
Using scripts in a master page with ASP.NET MVC
I'm fairly new to ASP.NET MVC, and I'm having a little trouble with scripts... in particular, I want to use jQuery in most pages, so it makes sense to put it in the master page. However, if I do (from my ~/Views/Shared/Site.Master):

```<code><script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
</code>```

Then that is literally what goes down to the client - which of course only works if our current route happens to have the right number of levels. Starting with ~/Scripts/... doesn't work. Starting with /Scripts/... would only work if the project was at the site root (which I don't want to assume).

I have one working approach (I'll post below) - but: am I missing something?

I'd rather not have to involve a script-manager, as that seems to defeat the simplicity of the ASP.NET MVC model... or am I worrying too much?

Here's the way I can get it working, which works also for non-trivial virtuals - but it seems over-complicated:

```<code><script src="<%=Url.Content("~/Scripts/jquery-1.2.6.js")%>" type="text/javascript"></script>
</code>```

答:
At work we are doing something like this from the ASP code behind:

```<code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  Const jQuery As String = "jQuery"

  With Me.Page.ClientScript
    If Not .IsClientScriptIncludeRegistered(jQuery) Then
      .RegisterClientScriptInclude(jQuery, VirtualPathUtility.ToAbsolute("~/Includes/jQuery-1.2.6.js"))
    End If
  End With
End Sub
</code>```

I don't know if it's possible to do that with ASP.NET MVC.

OwnerDisplayName: Marc Gravell

Body:
I'm fairly new to ASP.NET MVC, and I'm having a little trouble with scripts... in particular, I want to use jQuery in most pages, so it makes sense to put it in the master page. However, if I do (from my ~/Views/Shared/Site.Master):

Then that is literally what goes down to the client - which of course only works if our current route happens to have the right number of levels. Starting with ~/Scripts/... doesn't work. Starting with /Scripts/... would only work if the project was at the site root (which I don't want to assume).

I have one working approach (I'll post below) - but: am I missing something?

I'd rather not have to involve a script-manager, as that seems to defeat the simplicity of the ASP.NET MVC model... or am I worrying too much?

Here's the way I can get it working, which works also for non-trivial virtuals - but it seems over-complicated:

LastEditorDisplayName: Marc Gravell

Body:
At work we are doing something like this from the ASP code behind:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  Const jQuery As String = "jQuery"

  With Me.Page.ClientScript
    If Not .IsClientScriptIncludeRegistered(jQuery) Then
      .RegisterClientScriptInclude(jQuery, VirtualPathUtility.ToAbsolute("~/Includes/jQuery-1.2.6.js"))
    End If
  End With
End Sub

I don't know if it's possible to do that with ASP.NET MVC.

OwnerDisplayName: Leandro López


问:
Android Studio BottomNavigationView show fragment
I'm starting JAVA studies for the android platform. (Sorry for bad english, I'm using the translator).I would like to know how I can show a fragment when selecting an item in the toolbar.

Fragment Java Files:

VisaoGeralFragment

AgendaFragment

MuralFragment

Fragment Layout Files:

fragment_visao_geral.xml

fragment_agenda.xml

fragment_mural.xml

MainActivity:

```<code>public class MainActivity extends AppCompatActivity {

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment fragment = null;
            switch (item.getItemId()) {
                case R.id.navigation_vgeral:
                // Show VisaoGeralFragment
                return true;
                case R.id.navigation_agenda:
                // Show AgendaFragment
                return true;
                case R.id.navigation_mural:
                // Show MuralFragment
                return true;
            }

            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
</code>```

Thanks in advance.

答:
Firstly, in your activity_main you should create a Layout( preferably Frame Layout) where your fragments will appear when you navigate on navigator. Also,
 you have to set an id for that layout.

Below is the code that you will use:

```<code>Fragment frag = new YourFragment();

FragmentManager fm = getFragmentManager();
FragmentTransaction trans = fm.beginTransaction();
trans.replace(R.id.id_of_your_frame, frag);
trans.commit();
</code>```

You have to place this code for every case, by changing YourFragment() part with related fragment class.
Do not forget to change the id_of_your_frame with yours.

Body:
I'm starting JAVA studies for the android platform. (Sorry for bad english, I'm using the translator).I would like to know how I can show a fragment when selecting an item in the toolbar.

Fragment Java Files:

VisaoGeralFragment

AgendaFragment

MuralFragment

Fragment Layout Files:

fragment_visao_geral.xml

fragment_agenda.xml

fragment_mural.xml

MainActivity:

public class MainActivity extends AppCompatActivity {

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment fragment = null;
            switch (item.getItemId()) {
                case R.id.navigation_vgeral:
                // Show VisaoGeralFragment
                return true;
                case R.id.navigation_agenda:
                // Show AgendaFragment
                return true;
                case R.id.navigation_mural:
                // Show MuralFragment
                return true;
            }

            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Thanks in advance.

Body:
Firstly, in your activity_main you should create a Layout( preferably Frame Layout) where your fragments will appear when you navigate on navigator. Also,
 you have to set an id for that layout.

Below is the code that you will use:

Fragment frag = new YourFragment();

FragmentManager fm = getFragmentManager();
FragmentTransaction trans = fm.beginTransaction();
trans.replace(R.id.id_of_your_frame, frag);
trans.commit();

You have to place this code for every case, by changing YourFragment() part with related fragment class.
Do not forget to change the id_of_your_frame with yours.


问:
How to get path to add number of Images that are in the resource to be displayed in the WebView in objective-c
I am added image to my application but I want to display them into my web view. I tried but not succeeded. how can I set the path for those images in html in image tag and how to display them.

Please help me out of this.

Thank you,
Madan Mohan.

答:
In your HTML for the webview do

Where imagename is the filename of the image. The iPhone doesn't have any folder structures or anything like that. That means that even if you have groups or folders set up in XCode, at runtime they are all lumped into one, giant directory.

If that doesn't work right away, look at what your are setting your base url to be. It might be that you need to set the baseURL to nil to remind the phone to look locally.

Body:
In your HTML for the webview do

<img src="imagename">

Where imagename is the filename of the image. The iPhone doesn't have any folder structures or anything like that. That means that even if you have groups or folders set up in XCode, at runtime they are all lumped into one, giant directory.

If that doesn't work right away, look at what your are setting your base url to be. It might be that you need to set the baseURL to nil to remind the phone to look locally.


问:
How to access Vuex module getters and mutations?
I'm trying to switch to using Vuex instead of my homegrown store object, and I must say I'm not finding the docs as clear as elsewhere in the Vue.js world. Let's say I have a Vuex module called 'products', with its own state, mutations, getters, etc. How do I reference an action in that module called, say, 'clearWorking Data'? The docs give this example of accessing a module's state:

```<code>store.state.a // -> moduleA's state
</code>```

But nothing I can see about getters, mutations, actions, etc.

答:
In Addition to the accepted answer I wanna provide you with a workarround for the getter which is missing in the answer.

Debug the Store

In any case you can call console.log(this.$store) to debug the Store.

If you do so you will see the getters are prefixed with the namespace in their name.

Access namespaced getter

```<code>this.$store.getters['yourModuleName/someGetterMethod']
</code>```

Dispatch namespaced

```<code>this.$store.dispatch('yourModuleName/doSomething')
</code>```

Dispatch namespaced with params

```<code>this.$store.getters['yourModuleName/someGetterMethod'](myParam)
</code>```

Conclusion

The key is to handle the namespace like a file System like Justin explained.

Edit: found a nice library for handling vuex Store

In addition to the basic knowledge I'd like to add this vuex library as a nice addition for working effectivly and fast with the vuex store. https://github.com/davestewart/vuex-pathify .

It looks pretty interesting and cares much of the configuration for you and also allows you to handle 2waybinding directly with vuex.

** Edit: Thanks to the other Answers. Added Dispatching method with params for wholeness.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to switch to using Vuex instead of my homegrown store object, and I must say I'm not finding the docs as clear as elsewhere in the Vue.js world. Let's say I have a Vuex module called 'products', with its own state, mutations, getters, etc. How do I reference an action in that module called, say, 'clearWorking Data'? The docs give this example of accessing a module's state:

store.state.a // -> moduleA's state

But nothing I can see about getters, mutations, actions, etc.

Body:
In Addition to the accepted answer I wanna provide you with a workarround for the getter which is missing in the answer.

Debug the Store

In any case you can call console.log(this.$store) to debug the Store.

If you do so you will see the getters are prefixed with the namespace in their name.

Access namespaced getter

this.$store.getters['yourModuleName/someGetterMethod']

Dispatch namespaced

this.$store.dispatch('yourModuleName/doSomething')

Dispatch namespaced with params

this.$store.getters['yourModuleName/someGetterMethod'](myParam)

Conclusion

The key is to handle the namespace like a file System like Justin explained.

Edit: found a nice library for handling vuex Store

In addition to the basic knowledge I'd like to add this vuex library as a nice addition for working effectivly and fast with the vuex store. https://github.com/davestewart/vuex-pathify .

It looks pretty interesting and cares much of the configuration for you and also allows you to handle 2waybinding directly with vuex.

** Edit: Thanks to the other Answers. Added Dispatching method with params for wholeness.