问:
MFMessageComposeViewController presented without recipient field (iOS 11)
When I present MFMessageComposeViewController on an iOS 11 device it's presented mysteriously missing the recipient field. The same code works on an iPhone 6 running iOS 10.

答:
After a lot of messing around, I found that if I remove my project-wide hiding of the status bar in my info.plist: View controller-based status bar appearance: NO
and instead manually prefer that the status bar is hidden in each of my own view controllers I got the correct behavior. This seems like a bug to me so I plan on filing a radar.

You need to set the below in each of your UIViewController subclasses if you want to retain the status bar behavior:

```<code>override var prefersStatusBarHidden: Bool {
    return true
}
</code>```

Body:
After a lot of messing around, I found that if I remove my project-wide hiding of the status bar in my info.plist: View controller-based status bar appearance: NO
and instead manually prefer that the status bar is hidden in each of my own view controllers I got the correct behavior. This seems like a bug to me so I plan on filing a radar.

You need to set the below in each of your UIViewController subclasses if you want to retain the status bar behavior:

override var prefersStatusBarHidden: Bool {
    return true
}


来源: stackexchange

问:
fetch post always pass null to the parameters
There's a fetch post with "userid" as a parameter. I've tested the url and parameter in native android, it works there but here it doesn't take the parameter. It always sends the null value to "userid" parameter. Am I doing smthing wrong here?</p>

```<code>fetch('http://zzz.com/zzz/api/battery/gpswithbattery', {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        userid: '404',
    })
})
    .then((response) => response.json())
    .then((responseJson) => {
        console.log(responseJson);
         //return responseJson.message;
        this.setState({
            data: responseJson.message
        })
    })
    .catch((error) => {
        console.error(error);
    });
</code>```

答:
I see no mistake you are doing here, and start using es7 syntax, as that'll be even cleaner and easy to find mistakes,
pro-tip: use prettier that'll make to look your code better.</p>

```<code>  const method = async () => {
    const reponse = await fetch("http://zzz.com/zzz/api/battery/gpswithbattery", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        userid: "404"
      })
    });
    const responseJson = await response.json();
    this.setState({ data: responseJson.message });
  };
</code>```

ContentLicense: CC BY-SA 3.0

Body:
There's a fetch post with "userid" as a parameter. I've tested the url and parameter in native android, it works there but here it doesn't take the parameter. It always sends the null value to "userid" parameter. Am I doing smthing wrong here?

fetch('http://zzz.com/zzz/api/battery/gpswithbattery', {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        userid: '404',
    })
})
    .then((response) => response.json())
    .then((responseJson) => {
        console.log(responseJson);
         //return responseJson.message;
        this.setState({
            data: responseJson.message
        })
    })
    .catch((error) => {
        console.error(error);
    });

Body:
I see no mistake you are doing here, and start using es7 syntax, as that'll be even cleaner and easy to find mistakes,
pro-tip: use prettier that'll make to look your code better.

  const method = async () => {
    const reponse = await fetch("http://zzz.com/zzz/api/battery/gpswithbattery", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        userid: "404"
      })
    });
    const responseJson = await response.json();
    this.setState({ data: responseJson.message });
  };


问:
Swift push notifications delegate debug mode behavior
I have APNS connected to my app.

The problem is in different behavior of system delegate didReceiveRemoteNotification. It is working properly only when the debugger is attached to the app, otherwise, it is not called when the app is in the background state. For example, the delegate is called if test phone is connected to the mac via USB cable and app is being debugged. Right after cable disconnection delegate is not called anymore.

The question is how app state (debugged or not) influence on didReceiveRemoteNotification behavior. (both IOS 10 and 11)

To detect delegate call I make backend requests and I'm sure there is no problem with call detection.

答:
I had the same problem, spent a lot of time looking for a solution. I found a workaround mentioned in the Apple forums.

Make the class where you handle the push notifications a delegate of UNUserNotificationCenter

```<code>if #available(iOS 10.0, *) {
    UNUserNotificationCenter.current().delegate = self
}
</code>```

and then implement the willPresent notification: UNNotification method

```<code>@available(iOS 10.0, *)
extension APNSService: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        Log.debug?.message("Received push in foreground through UserNotificationCenter, calling Inbox.incrementalSync")
        ...
        completionHandler([])
    }
}
</code>```

Body:
I had the same problem, spent a lot of time looking for a solution. I found a workaround mentioned in the Apple forums.

Make the class where you handle the push notifications a delegate of UNUserNotificationCenter

if #available(iOS 10.0, *) {
    UNUserNotificationCenter.current().delegate = self
}

and then implement the willPresent notification: UNNotification method

@available(iOS 10.0, *)
extension APNSService: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        Log.debug?.message("Received push in foreground through UserNotificationCenter, calling Inbox.incrementalSync")
        ...
        completionHandler([])
    }
}


问:
Does glob work with pdf files?
I am new to python and I am trying to create a code that will search through thousands of pdf files that are organized and titled by 3 different numbers, township, range, and section (file looks like: 07N06E08_4200).  I have been trying to get glob to read my pdf files, as I have used glob for excel files, but I haven't had any luck.

This is the command so far to bring in the data:
         glob.glob('./C:/Users/green_000/Documents/Alyssa/Python/FinalProject/Python_Data/SacramentoCounty')

And that reutrns: []

I then have:

```<code>collectData=[]

for filename in glob.glob('./C:/Users/green_000/Documents/Alyssa/Python/FinalProject/Python_Data/SacramentoCounty'):
print('processing {:s}'.format(filename))
data = pd.read_pdf(filename)
collectData.append(data)
AllData = pd.concat(collectData)
AllData.columns=['Township','Range','Section']
AllData.to_pdf('AllData.csv',mode='w')
</code>```

And I get the error: No objects to concatenate

thanks for any help!

答:
Your path indicates that you are searching a relative path (starts with .) and also an absolute path (starts with C:). You can't do both simultaneously.

Try:

```<code>for filename in glob.glob('C:/Users/green_000/Documents/Alyssa/Python/FinalProject/Python_Data/SacramentoCounty'):
</code>```

Title: Does glob work with pdf files?

Body:
I am new to python and I am trying to create a code that will search through thousands of pdf files that are organized and titled by 3 different numbers, township, range, and section (file looks like: 07N06E08_4200).  I have been trying to get glob to read my pdf files, as I have used glob for excel files, but I haven't had any luck.

This is the command so far to bring in the data:
         glob.glob('./C:/Users/green_000/Documents/Alyssa/Python/FinalProject/Python_Data/SacramentoCounty')

And that reutrns: []

I then have:

collectData=[]

for filename in glob.glob('./C:/Users/green_000/Documents/Alyssa/Python/FinalProject/Python_Data/SacramentoCounty'):
print('processing {:s}'.format(filename))
data = pd.read_pdf(filename)
collectData.append(data)
AllData = pd.concat(collectData)
AllData.columns=['Township','Range','Section']
AllData.to_pdf('AllData.csv',mode='w')

And I get the error: No objects to concatenate

thanks for any help!

Body:
Your path indicates that you are searching a relative path (starts with .) and also an absolute path (starts with C:). You can't do both simultaneously.

Try:

for filename in glob.glob('C:/Users/green_000/Documents/Alyssa/Python/FinalProject/Python_Data/SacramentoCounty'):


问:
Best way to protect video from downloading
What is the best way to make it harder for the user to download videos from my website?. I know it is impossible to prevent it at all. But I just want to make it more difficult than just secondary click, save as. I'm rendering as html5 video tag. I'm using  to remove download button from controls. But still can save the video using secondary click and save video as. There is an effective way to make it a little bit difficult to the user from downloading videos from my website?.</p>

答:
This question where answered before but I post here the solution that I got from Clayton Graul here :)

This is a simple solution for those wishing to simply remove the right-click "save" option from the html5 videos

```<code>$(document).ready(function(){
   $('#videoElementID').bind('contextmenu',function() { return false; });
});
</code>```

Body:
This question where answered before but I post here the solution that I got from Clayton Graul here :)

This is a simple solution for those wishing to simply remove the right-click "save" option from the html5 videos

$(document).ready(function(){
   $('#videoElementID').bind('contextmenu',function() { return false; });
});


问:
I want to convert this Cos up -1 to Tcl
can anyone tell me how can I convert this cos-1 to TCL, due to in TCL
just work with normal cos, not like this cos-1, also it calls "The inverse cosine".

答:
If you want the reverse cosine in degree, you could use this:

```<code>expr {acos($x)*180/acos(-1)}
</code>```

acos(-1) is pi.

Title: I want to convert this Cos up -1 to Tcl

Body:
If you want the reverse cosine in degree, you could use this:

expr {acos($x)*180/acos(-1)}

acos(-1) is pi.


问:
Where is Url.Action getting these values from?
I'm trying to create a link to the following GET action with Url.Action:

```<code>public class FooController : Controller
{
    [HttpGet]
    [Route("Foo/Apply/BarDetails/Part/{id}")]
    public IActionResult BarDetails(int id)
    {
    }
}
</code>```

And in my view I'm creating a URL with

```<code>Url.Action("BarDetails", "Foo", new {id = 1})
</code>```

However this generates the URL Foo/Apply/BarDetails/Part/10?id=1 which is definitely not what I want! Removing the values parameter simply removes the query string part of the URL. The only route I have registered at startup is

```<code>app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});
</code>```

I've had a look at the ASP.NET Core source and I suspect that the "10" part of the URL is coming from a "1" + "0" operation somewhere as the routing code is split across 2+ repos it's hard to follow. Does anyone know how the last part of this URL is being generated and how I can fix it to match the id provided in the route values?

答:
You can set maximum and minimum range of optional route parameter in  attribute based routing. Follow the code below </p>

```<code>enter code here [Route("Licence/Apply/Details/Part/{id:int:max(1000):min(10)}}")]
</code>```

Body:
I'm trying to create a link to the following GET action with Url.Action:

public class FooController : Controller
{
    [HttpGet]
    [Route("Foo/Apply/BarDetails/Part/{id}")]
    public IActionResult BarDetails(int id)
    {
    }
}

And in my view I'm creating a URL with

Url.Action("BarDetails", "Foo", new {id = 1})

However this generates the URL Foo/Apply/BarDetails/Part/10?id=1 which is definitely not what I want! Removing the values parameter simply removes the query string part of the URL. The only route I have registered at startup is

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

I've had a look at the ASP.NET Core source and I suspect that the "10" part of the URL is coming from a "1" + "0" operation somewhere as the routing code is split across 2+ repos it's hard to follow. Does anyone know how the last part of this URL is being generated and how I can fix it to match the id provided in the route values?

Body:
You can set maximum and minimum range of optional route parameter in  attribute based routing. Follow the code below

enter code here [Route("Licence/Apply/Details/Part/{id:int:max(1000):min(10)}}")]


问:
regex ^ and $ are not working
I'm trying to  write a regex that matches a number with commas for
every three digits? It must match the following:

```<code>'42'
'1,234'
'6,368,745'
</code>```

but not the following:

```<code>'12,34,567' (which has only two digits between the commas)
'1234' (which lacks commas)
</code>```

so I have tried the following

```<code>((^\d{1,3})((\,\d{3})*$))
^\d{1,3}(,{3})*$
^(\d{1,3}(,{3})*)$
</code>```

but it didn't match anything.
when I tried without ^ and $ then it is not matching the exact pattern.

答:
Code

See regex in use here

```<code>^\d{1,3}(?:,\d{3})*$
</code>```

Assuming you don't want to allow 0,123 you can use ^[1-9]{1,3}(?:,\d{3})*$ instead.

Results

Input

```<code>42
1,234
1,234

12,34,567
1234
</code>```

Output

Below are matches only.

```<code>42
1,234
1,234
</code>```

Explanation

^ Assert position at the start of the line

\d{1,3} Match any digit between 1 and 3 times

(?:,\d{3})* Match any number of a comma , followed by exactly 3 digits

$ Assert position at the end of the line

Title: regex ^ and $ are not working

Body:
I'm trying to  write a regex that matches a number with commas for
every three digits? It must match the following:

'42'
'1,234'
'6,368,745'

but not the following:

'12,34,567' (which has only two digits between the commas)
'1234' (which lacks commas)

so I have tried the following

((^\d{1,3})((\,\d{3})*$))
^\d{1,3}(,{3})*$
^(\d{1,3}(,{3})*)$

but it didn't match anything.
when I tried without ^ and $ then it is not matching the exact pattern.

Body:
Code

See regex in use here

^\d{1,3}(?:,\d{3})*$

Assuming you don't want to allow 0,123 you can use ^[1-9]{1,3}(?:,\d{3})*$ instead.

Results

Input

42
1,234
1,234

12,34,567
1234

Output

Below are matches only.

42
1,234
1,234

Explanation

^ Assert position at the start of the line

\d{1,3} Match any digit between 1 and 3 times

(?:,\d{3})* Match any number of a comma , followed by exactly 3 digits

$ Assert position at the end of the line


问:
Javascript match - include anything with 2 keywords, ignore anything with 1 keyword
I would like to include a string if it contains either 'jpg' or 'png' but exclude the string if it contains 'http'.

I have been trying the following but it still includes the string if it contains both http and either png or jpg:

myString.match(/(?!http)(jpg|png)/i)

An expected input would be http://s3-eu-west-1.amazonaws.com/bucket/1512491455764.png?Signature=signature

As this contains both http and png, this string would be ignored / return false from the regex

答:
You may use

```<code>/^(?!.*http).*(jpg|png)/i
</code>```

Details

^ - start of string

(?!.*http) - no http is allowed after any 0+ chars other than line break chars immediately to the right of the current location is allowed

.* -  any 0+ chars other than line break chars immediately to the right of the current location

(jpg|png) - either jpg or png.

Body:
You may use

/^(?!.*http).*(jpg|png)/i

Details

^ - start of string

(?!.*http) - no http is allowed after any 0+ chars other than line break chars immediately to the right of the current location is allowed

.* -  any 0+ chars other than line break chars immediately to the right of the current location

(jpg|png) - either jpg or png.


问:
incompatible types in assignment of 'int' to 'int [10]' in C
**i want to assign the pointers on the first element of each array but i get this message -->incompatible types in assignment of 'int' to 'int [10]' in C **    </p>

```<code>#include <stdio.h>
#include <stdlib.h>
#define ten 10
int main ()
{
  int min = 0, max = 0, *minptr, *maxptr, i;
  int arr1[ten], arr2[ten], *arr1_ptr[ten], *arr2_ptr[ten];
  arr1_ptr = &arr1[0];
  arr2_ptr = &arr2[0];
  minptr = &min;
  maxptr = &max;

  return 0;
}
</code>```

答:
arr1[0] is a single int value. Therefore &arr1[0] is a pointer to that single int. And therefore &arr1[0] has to be of type int *.

The variable arr1_ptr is an array of 10 pointers to int. If you want to make an element of that array point to an element of arr1, then you have to assign the address of an element of arr1 to an element of arr1_ptr:

```<code>arr1_ptr[0] = &arr1[0];
</code>```

If on the other hand you want a pointer to an array, then you have to do e.g.

```<code>int (*arr1_ptr)[ten] = &arr1;
</code>```

Body:
**i want to assign the pointers on the first element of each array but i get this message -->incompatible types in assignment of 'int' to 'int [10]' in C **

#include <stdio.h>
#include <stdlib.h>
#define ten 10
int main ()
{
  int min = 0, max = 0, *minptr, *maxptr, i;
  int arr1[ten], arr2[ten], *arr1_ptr[ten], *arr2_ptr[ten];
  arr1_ptr = &arr1[0];
  arr2_ptr = &arr2[0];
  minptr = &min;
  maxptr = &max;

  return 0;
}

Body:
arr1[0] is a single int value. Therefore &arr1[0] is a pointer to that single int. And therefore &arr1[0] has to be of type int *.

The variable arr1_ptr is an array of 10 pointers to int. If you want to make an element of that array point to an element of arr1, then you have to assign the address of an element of arr1 to an element of arr1_ptr:

arr1_ptr[0] = &arr1[0];

If on the other hand you want a pointer to an array, then you have to do e.g.

int (*arr1_ptr)[ten] = &arr1;


问:
Why RadioButton/CheckboxButton don't have a VALUE attribute?
Why RadioButton/CheckboxButton don't have a VALUE attribute ?

The HTML input radio have a VALUE attribute, why the RadioButton/CheckboxButton don't? That's a real error Microsoft! Why that?

Now, imagine a situation:

You need a list of cars from Database, the user need to choose only one, you put a list of radioButton with TEXT attribute with the name of the car AND the correct is to save the ID of register from Database in a VALUE attribute. The user will choose one register and i will get the value of that input and save in database.

But with Microsoft RadioButton that's is not possible by default, I'll should get the name of the car in TEXT attribute, find a register by the name of the car ( WHERE name = 'volvo' //THATS WRONG ) and get the ID of the register and then save to database.

Another way is verify if the radioButton is checked and put Manually ID of register to save in database if radioButton2 is checked.

THAT'S DEFINELY WRONG.

答: check out the RadioButtonList control which has properties for DataTextField and DataValueField</p>

ContentLicense: CC BY-SA 2.5


问:
SQL query that brings all records that doesn't includes a join with a given value
Lets suppose we have

```<code>Owners
id

Dogs
id
owner_id
trained (boolean)
</code>```

I want to get all owners who don't have any trained dog, including those who don't have a dog.

So if one owner has one trained dog, and one dog non trained, that owner should not appear, because already has a trained dog.

I tried with something like this:

```<code>SELECT * FROM owners o
LEFT JOIN dogs d on d.owner_id = o.id
WHERE
  d.trained = false OR d.trained IS NULL.
</code>```

But this query returns records including owners that have dogs trained, as long as they have a non trained dog.

I wan't to get only:

Owners who don't have a single trained dog

Owner who don't have dogs.

答:
```<code>SELECT *
FROM   Owners o,Dogs d
WHERE  o.id=d.owner_id
and  d.trained=false;
</code>```

Body:
Lets suppose we have

Owners
id

Dogs
id
owner_id
trained (boolean)

I want to get all owners who don't have any trained dog, including those who don't have a dog.

So if one owner has one trained dog, and one dog non trained, that owner should not appear, because already has a trained dog.

I tried with something like this:

SELECT * FROM owners o
LEFT JOIN dogs d on d.owner_id = o.id
WHERE
  d.trained = false OR d.trained IS NULL.

But this query returns records including owners that have dogs trained, as long as they have a non trained dog.

I wan't to get only:

Owners who don't have a single trained dog

Owner who don't have dogs.


问:
Calculating Interest Rates Python Dataframe
I Need to calculate the compund interest rate so, lets say I have a Dataframe like that:

```<code>   days
1   10
2   15
3   20
</code>```

What I want to get is (suppose the interest rate is 1% every day:

```<code>    days   interst rate
1   10     10,46%
2   15     16,10%
3   20     22,02%
</code>```

My code is as follows:

```<code>def inclusao_juros (x):
    dias = df_arrumada_4['Prazo Medio']
    return ((1.0009723)^dias)-1

df_arrumada_4['juros_acumulado'] = df_arrumada_4['Prazo Medio'].apply(inclusao_juros)
</code>```

What should I do??? Tks

Body:
I Need to calculate the compund interest rate so, lets say I have a Dataframe like that:

   days
1   10
2   15
3   20

What I want to get is (suppose the interest rate is 1% every day:

    days   interst rate
1   10     10,46%
2   15     16,10%
3   20     22,02%

My code is as follows:

def inclusao_juros (x):
    dias = df_arrumada_4['Prazo Medio']
    return ((1.0009723)^dias)-1

df_arrumada_4['juros_acumulado'] = df_arrumada_4['Prazo Medio'].apply(inclusao_juros)

What should I do??? Tks

Body:
I think you need numpy.power:

df['new'] = np.power(1.01, df['days']) - 1
print (df)
   days       new
1    10  0.104622
2    15  0.160969
3    20  0.220190


问:
Hadoop and geospatial connector
I am using Cloudera Hadoop, I want to perform Spatial Analytics and need to connect to quantum GIS(QGIS)  for geospatial purposes. I need to know how to connect both QGIS and  Hadoop. Also is there any other way to connect any other GIS systems except ARCGIS?  </p>

答:
GeoWave is a project that matches the criteria.

The goal of the project is primarily to connect the Hadoop ecosystem with popular GIS software which seems to fit well here. It enables storage/retrieval/analysis of raster/vector/point cloud data within various distributed key-value stores.

Also, the project has installers for Cloudera in addition to other vendors - the latest release with support for Cloudera 5.12.1.

Please keep in mind that I am a GeoWave core contributor.

Title: Hadoop and geospatial connector


问:
Closest Friday, with time
I am using a Date API called date.js and I want to use it for getting the closest Friday Date.today().next().friday();. It works and so on but I wanted to specify a time which I would change the next Friday and not the current so I did this Date.today().next().friday().set({hour: 19});. But it didn't work. Does anybody know how I can accomplish this with this API or plain js or any other API.

Clarification

Clearing thing up, i have a countdown I want it to countdown to the nearest Friday at 19:00, but I can't get the part with the time to work, it just ignores the time, on Friday it just looks for the net Friday and ignores that the clock haven't pased 19:00 yet.

CODE:

```<code>var d = new Date();
var dagnr = d.getDay();
var time = d.getHours();

var nextf = Date.today().next().tuesday().set({hour: 19});
var countDownDate = new Date(nextf);

//Random mening för Savar NEJ

// Romdom Mening för Svar JA
var jalist = [
      "Själklart är det de"
    , "Vad fasen skulle det annars vara?"
    , "A fram med chipsen för fan!"
    , "A men det är det ju!"
    , "Ajemän fram netflix"
    ,
];
var jarand = Math.floor(Math.random() * jalist.length);

// Update the count down every 1 second
var x = setInterval(function() {

    // Get todays date and time
    var now = new Date().getTime();
    console.log(countDownDate);
    // Find the distance between now an the count down date
    var distance = countDownDate - now;
    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // Testa vilken dag och vilken tid det är
    console.log(dagnr)
    if ((dagnr === 1 && time >= 15) || (dagnr === 6 | dagnr === 0)) {
        document.getElementById("demo").innerHTML = jalist[jarand];
    } else{
        document.getElementById("demo").innerHTML = "Nej tyvärr är det " + days + "d " + hours + "h " + minutes + "m " + seconds + "s " + "kvar";
    }

}, 1000);
</code>```

答:
You can check if today is a particular day by using Date.today().is().tuesday().  Just use that with a ternary operator and it should work just fine.

var d = new Date();
var dagnr = d.getDay();
var time = d.getHours();

var nextf =
  Date.today().is().tuesday() ?
  Date.today().set({hour: 19}) :
  Date.next().tuesday().set({hour: 19});

var countDownDate = new Date(nextf);

//Random mening för Savar NEJ

// Romdom Mening för Svar JA
var jalist = [
      "Själklart är det de"
    , "Vad fasen skulle det annars vara?"
    , "A fram med chipsen för fan!"
    , "A men det är det ju!"
    , "Ajemän fram netflix"
    ,
];
var jarand = Math.floor(Math.random() * jalist.length);

// Update the count down every 1 second
var x = setInterval(function() {

    // Get todays date and time
    var now = new Date().getTime();
    // Find the distance between now an the count down date
    var distance = countDownDate - now;
    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // Testa vilken dag och vilken tid det är
    if ((dagnr === 1 && time >= 15) || (dagnr === 6 | dagnr === 0)) {
        console.log(jarand);
    } else{
        console.log("Nej tyvärr är det " + days + "d " + hours + "h " + minutes + "m " + seconds + "s " + "kvar");
    }

}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script></code>```

Title: Closest Friday, with time

Body:
I am using a Date API called date.js and I want to use it for getting the closest Friday Date.today().next().friday();. It works and so on but I wanted to specify a time which I would change the next Friday and not the current so I did this Date.today().next().friday().set({hour: 19});. But it didn't work. Does anybody know how I can accomplish this with this API or plain js or any other API.

Clarification

Clearing thing up, i have a countdown I want it to countdown to the nearest Friday at 19:00, but I can't get the part with the time to work, it just ignores the time, on Friday it just looks for the net Friday and ignores that the clock haven't pased 19:00 yet.

CODE:

var d = new Date();
var dagnr = d.getDay();
var time = d.getHours();

var nextf = Date.today().next().tuesday().set({hour: 19});
var countDownDate = new Date(nextf);

//Random mening för Savar NEJ

// Romdom Mening för Svar JA
var jalist = [
      "Själklart är det de"
    , "Vad fasen skulle det annars vara?"
    , "A fram med chipsen för fan!"
    , "A men det är det ju!"
    , "Ajemän fram netflix"
    ,
];
var jarand = Math.floor(Math.random() * jalist.length);

// Update the count down every 1 second
var x = setInterval(function() {

    // Get todays date and time
    var now = new Date().getTime();
    console.log(countDownDate);
    // Find the distance between now an the count down date
    var distance = countDownDate - now;
    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // Testa vilken dag och vilken tid det är
    console.log(dagnr)
    if ((dagnr === 1 && time >= 15) || (dagnr === 6 | dagnr === 0)) {
        document.getElementById("demo").innerHTML = jalist[jarand];
    } else{
        document.getElementById("demo").innerHTML = "Nej tyvärr är det " + days + "d " + hours + "h " + minutes + "m " + seconds + "s " + "kvar";
    }

}, 1000);

Body:
You can check if today is a particular day by using Date.today().is().tuesday().  Just use that with a ternary operator and it should work just fine.

var d = new Date();
var dagnr = d.getDay();
var time = d.getHours();

var nextf =
  Date.today().is().tuesday() ?
  Date.today().set({hour: 19}) :
  Date.next().tuesday().set({hour: 19});

var countDownDate = new Date(nextf);

//Random mening för Savar NEJ

// Romdom Mening för Svar JA
var jalist = [
      "Själklart är det de"
    , "Vad fasen skulle det annars vara?"
    , "A fram med chipsen för fan!"
    , "A men det är det ju!"
    , "Ajemän fram netflix"
    ,
];
var jarand = Math.floor(Math.random() * jalist.length);

// Update the count down every 1 second
var x = setInterval(function() {

    // Get todays date and time
    var now = new Date().getTime();
    // Find the distance between now an the count down date
    var distance = countDownDate - now;
    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // Testa vilken dag och vilken tid det är
    if ((dagnr === 1 && time >= 15) || (dagnr === 6 | dagnr === 0)) {
        console.log(jarand);
    } else{
        console.log("Nej tyvärr är det " + days + "d " + hours + "h " + minutes + "m " + seconds + "s " + "kvar");
    }

}, 1000);

<script src="https://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script>


问:
Map SQL table rows to C++ structures
I'm trying to implement some kind of persistent storage of C++ structures into an SQLite database. It looks nice in the beginning but then it becomes complicated with all those SQL requests, data binds and manual getting field values one after another.

Ideally I'd like to have some kind of mapping from a table row in SQLite to a C++ structure, with a possibility of running SQL requests on that. On the other hand, I'd still like to keep it general enough to be able to run more complex requests with joins etc.

I even thought that an external utility that would auto-generate the corresponding C++/SQL glue code could be helpful.

What would be the right way to do this kind of mapping? I've heard people suggesting boost::serialization or Google's protocol buffers, would this be a much better option for what I want, or maybe there are some other good options?

答:
Soci is a good start. If it doesn't meet all your needs, it will help you figure out where you want to go.

I used it for a while with sqlite, and found it better than the others I could find. I did end up writing my own, though ...

Title: Map SQL table rows to C++ structures


问:
Call requestPermissions from Asynctask
I'm trying to request permissions from AsyncTask called by a android.support.v4.app.Fragment.

On doInBackground method has this piece of code

```<code>     int hasWriteContactsPermission = ContextCompat.checkSelfPermission((Context)ctx,
                Manifest.permission.SEND_SMS);

        if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
            if (!ActivityCompat.shouldShowRequestPermissionRationale((AppCompatActivity)ctx,
                    Manifest.permission.SEND_SMS)) {
                showMessageOKCancel("Necessary permissions", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                requestPermissions(new String[]{Manifest.permission.SEND_SMS},
                                        REQUEST_CODE_ASK_PERMISSIONS);
                            }
                        });
                return;
            }

           /******** PROBLEM
     requestPermissions(new String[] {Manifest.permission.SEND_SMS},
                    REQUEST_CODE_ASK_PERMISSIONS);

*************/
            return;
        }
</code>```

Calling requestPermissions through AppCompatActivity is not valid for me because i need to catch onRequestPermissionsResult in Fragment, not in Activity

The problem is that requestPermissions says this error:

```<code>Cannot resolve method requestPermissions
</code>```

How can i call requestPermissions method from Asynctask to catch the result on the caller Fragment?

答:
Actually you cannot ask for permission inside the doInBackground method, because as the name says, it is doing work in backgorund, and requesting permissions to the user needs to use UI thread. I suggest to you calling a request permission like this:</p>

```<code>    public void checkPermissions() {
    final String[] permissions = new String[]{Manifest.permission.SEND_SMS}

    if ( ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.SEND_SMS )
            != PackageManager.PERMISSION_GRANTED ) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                android.Manifest.permission.SEND_SMS )){

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Permission Needed");
            builder.setMessage("You must accept the permission.");
            builder.setPositiveButton(R.string.global_ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    ActivityCompat.requestPermissions(ConfigurarActivity.this,
                            permissions,
                            PERMISSION_REQUEST);
                }
            });
            builder.setNegativeButton(R.string.global_cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();
        } else {
            ActivityCompat.requestPermissions(this,
                    permissions,
                    PERMISSION_REQUEST);
        }
    }else{
        //doTaskThatNeedThePermission can be async
    }
}
</code>```

Title: Call requestPermissions from Asynctask

Body:
I'm trying to request permissions from AsyncTask called by a android.support.v4.app.Fragment.

On doInBackground method has this piece of code

     int hasWriteContactsPermission = ContextCompat.checkSelfPermission((Context)ctx,
                Manifest.permission.SEND_SMS);

        if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
            if (!ActivityCompat.shouldShowRequestPermissionRationale((AppCompatActivity)ctx,
                    Manifest.permission.SEND_SMS)) {
                showMessageOKCancel("Necessary permissions", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                requestPermissions(new String[]{Manifest.permission.SEND_SMS},
                                        REQUEST_CODE_ASK_PERMISSIONS);
                            }
                        });
                return;
            }

           /******** PROBLEM
     requestPermissions(new String[] {Manifest.permission.SEND_SMS},
                    REQUEST_CODE_ASK_PERMISSIONS);

*************/
            return;
        }

Calling requestPermissions through AppCompatActivity is not valid for me because i need to catch onRequestPermissionsResult in Fragment, not in Activity

The problem is that requestPermissions says this error:

Cannot resolve method requestPermissions

How can i call requestPermissions method from Asynctask to catch the result on the caller Fragment?

Body:
Actually you cannot ask for permission inside the doInBackground method, because as the name says, it is doing work in backgorund, and requesting permissions to the user needs to use UI thread. I suggest to you calling a request permission like this:

    public void checkPermissions() {
    final String[] permissions = new String[]{Manifest.permission.SEND_SMS}

    if ( ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.SEND_SMS )
            != PackageManager.PERMISSION_GRANTED ) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                android.Manifest.permission.SEND_SMS )){

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Permission Needed");
            builder.setMessage("You must accept the permission.");
            builder.setPositiveButton(R.string.global_ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    ActivityCompat.requestPermissions(ConfigurarActivity.this,
                            permissions,
                            PERMISSION_REQUEST);
                }
            });
            builder.setNegativeButton(R.string.global_cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();
        } else {
            ActivityCompat.requestPermissions(this,
                    permissions,
                    PERMISSION_REQUEST);
        }
    }else{
        //doTaskThatNeedThePermission can be async
    }
}


问:
How to authenticate a route with passport-jwt?
I'm using passport-jwt and my strategy is setup like:

```<code>  let jwtOptions = {}
  jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken()
  jwtOptions.secretOrKey = process.env.SECRET

  var strategy = new JwtStrategy(jwtOptions, function (jwt_payload, next) {
    console.log('payload received', jwt_payload);
    // usually this would be a database call:
    var user = users[_.findIndex(users, { id: jwt_payload.id })];
    if (user) {
      next(null, user);
    } else {
      next(null, false);
    }
  })
  passport.use(strategy)
</code>```

So when I POST to a /login route, I'm able to generate a token:

```<code>  var payload = { id: user.id }
  var token = jwt.sign(payload, jwtOptions.secretOrKey)
  res.json({ message: "ok", token: token })
</code>```

But then when I try to have a route that requires a token:

```<code>  app.get("/secret", passport.authenticate('jwt', { session: false }), (req, res) => {
    res.json("Success! You can not see this without a token");
  })
</code>```

My header has Authorization: JWT [token]

it continually returns a 401. What am I doing wrong?

答:
Your authorization header is incorrectly formatted.  Per the jwt-strategy docs

fromAuthHeaderAsBearerToken() creates a new extractor that looks for the JWT in the authorization header with the scheme 'bearer'

So your header should be Authorization: Bearer [token]

Body:
I'm using passport-jwt and my strategy is setup like:

  let jwtOptions = {}
  jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken()
  jwtOptions.secretOrKey = process.env.SECRET

  var strategy = new JwtStrategy(jwtOptions, function (jwt_payload, next) {
    console.log('payload received', jwt_payload);
    // usually this would be a database call:
    var user = users[_.findIndex(users, { id: jwt_payload.id })];
    if (user) {
      next(null, user);
    } else {
      next(null, false);
    }
  })
  passport.use(strategy)

So when I POST to a /login route, I'm able to generate a token:

  var payload = { id: user.id }
  var token = jwt.sign(payload, jwtOptions.secretOrKey)
  res.json({ message: "ok", token: token })

But then when I try to have a route that requires a token:

  app.get("/secret", passport.authenticate('jwt', { session: false }), (req, res) => {
    res.json("Success! You can not see this without a token");
  })

My header has Authorization: JWT [token]

it continually returns a 401. What am I doing wrong?


问:
Refresh a fragment inside a viewpager which is inside a fragment
I have an activity which consists of three fragments. In one of these fragments I have a viewpager that consists of three other fragments. I call getChildFragmentManager() inside fragment that has viewpager in it. I have searched SO and read almost every answer that are related to this topic for example: this and this and one that seemed most useful was this but could not solve my problem. I think if i can just return POSITION_NONE for getItemPosition(Object object)  in FragmentStatePagerAdapter and call notifyDataSetChanged() will solve my problem but every time I do this my app crashes with this error:

java.lang.IllegalStateException: FragmentManager is already executing
  transactions!!!

and I mentioned that I am using getChildFragmentManager() inside my fragment.
Anyone thinks of any solution to this problem?

this is the parent fragment:

```<code>public class WordDetailFragment extends Fragment {

    @BindView(R.id.word_parts_tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.word_part_view_pager)
    ViewPager mViewPager;

    private WordPagerAdapter mPagerAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_word_detail, container, false);
        ButterKnife.bind(this, view);
        mPagerAdapter = new WordPagerAdapter(getChildFragmentManager(), getActivity());
        mViewPager.setAdapter(mPagerAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
        return view;
    }

    public void notifyTranslateChanged() {
        mViewPager.getAdapter().notifyDataSetChanged();
    }
}
</code>```

this is the code for adapter

```<code>public class WordPagerAdapter extends FragmentStatePagerAdapter {
    final int PAGE_COUNT = 3;
    private String[] tabTitles = new String[]{"Definition", "Example", "Col & fam"};
    private Context context;

    public WordPagerAdapter(FragmentManager fm, Context context) {
        super(fm);
        this.context = context;
    }

    @Override
    public int getCount() {
        return PAGE_COUNT;
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment;
        switch (position) {
            case 0:
                fragment = new WordDefinitionFragment();
                break;
            case 1:
                fragment = new WordExampleFragment();
                break;
            case 2:
                fragment = new WordColFamFragment();
                break;

                default: fragment = new WordDefinitionFragment();
        }
        return fragment;
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        // Generate title based on item position
        return tabTitles[position];
    }
}
</code>```

One of the fragments in viewpager

```<code>public class WordDefinitionFragment extends Fragment {

    @BindView(R.id.show_translate_switch)
    Switch mShowTranslateSwitch;

    private List<WordInfo> mWordInfoList;
    private List<Definition> mDefinitionList;
    private boolean mShowTranslation;
    private View mView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_word_definition, container, false);
        ButterKnife.bind(this, mView);

        mShowTranslation = SharedPrefHelper.getBooleanInfo(getActivity(), getString(R.string.show_translate_key));

        mShowTranslateSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (getActivity() != null)
                    ((WordActivity) getActivity()).changeTranslateMode(b);
                showTranslation(b);
            }
        });

        return mView;
    }
}
</code>```

and my activity. U have just included the parts that i felt are needed here.

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

    @Override
    protected void onCreate(Bundle savedInstanceSate) {
        super.onCreate(savedInstanceSate);
        setContentView(R.layout.activity_word);

    }

    public void changeTranslateMode(boolean show) {
        SharedPrefHelper.setBooleanInfo(this, getString(R.string.show_translate_ke)y, show);
        ((WordDetailFragment)mWordDetailFragment).notifyTranslateChanged();
    }

}
</code>```

and my logcat error is

答:
After many searches I could figure out a way which is not very smart but for the time being has solved my problem.
First of all I used the class FixedFragmentStatePagerAdapter from this post. I also had to remove the part in which the fragment bundle is restored because it caches fragment variables and views.

```<code>public abstract class FixedFragmentStatePagerAdapter extends PagerAdapter {
    private static final String TAG = "PagerAdapter";
    private static final boolean DEBUG = false;

    private final FragmentManager mFragmentManager;
    private FragmentTransaction mCurTransaction = null;

    private ArrayList<Fragment.SavedState> mSavedState = new ArrayList<>();
    private ArrayList<String> mSavedFragmentTags = new ArrayList<>();
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private Fragment mCurrentPrimaryItem = null;

    public FixedFragmentStatePagerAdapter(FragmentManager fm) {
        mFragmentManager = fm;
    }

    /**
     * Return the Fragment associated with a specified position.
     */
    public abstract Fragment getItem(int position);

    public String getTag(int position) {
        return null;
    }

    @Override
    public void startUpdate(ViewGroup container) {
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        // If we already have this item instantiated, there is nothing
        // to do.  This can happen when we are restoring the entire pager
        // from its saved state, where the fragment manager has already
        // taken care of restoring the fragments we previously had instantiated.
        if (mFragments.size() > position) {
            Fragment f = mFragments.get(position);
            if (f != null) {
                return f;
            }
        }

        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }

        Fragment fragment = getItem(position);
        String fragmentTag = getTag(position);
        if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment + " t=" + fragmentTag);
       /* if (mSavedState.size() > position) {
            String savedTag = mSavedFragmentTags.get(position);
            if (TextUtils.equals(fragmentTag, savedTag)) {
                Fragment.SavedState fss = mSavedState.get(position);
                if (fss != null) {
                    fragment.setInitialSavedState(fss);
                }
            }
        }*/
        while (mFragments.size() <= position) {
            mFragments.add(null);
        }
        fragment.setMenuVisibility(false);
        fragment.setUserVisibleHint(false);
        mFragments.set(position, fragment);
        mCurTransaction.add(container.getId(), fragment, fragmentTag);

        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        Fragment fragment = (Fragment)object;

        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }
        if (DEBUG) Log.v(TAG, "Removing item #" + position + ": f=" + object
                + " v=" + ((Fragment)object).getView() + " t=" + fragment.getTag());
        while (mSavedState.size() <= position) {
            mSavedState.add(null);
            mSavedFragmentTags.add(null);
        }
        mSavedState.set(position, mFragmentManager.saveFragmentInstanceState(fragment));
        mSavedFragmentTags.set(position, fragment.getTag());
        mFragments.set(position, null);

        mCurTransaction.remove(fragment);
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        Fragment fragment = (Fragment)object;
        if (fragment != mCurrentPrimaryItem) {
            if (mCurrentPrimaryItem != null) {
                mCurrentPrimaryItem.setMenuVisibility(false);
                mCurrentPrimaryItem.setUserVisibleHint(false);
            }
            if (fragment != null) {
                fragment.setMenuVisibility(true);
                fragment.setUserVisibleHint(true);
            }
            mCurrentPrimaryItem = fragment;
        }
    }

    @Override
    public void finishUpdate(ViewGroup container) {
        if (mCurTransaction != null) {
            mCurTransaction.commitAllowingStateLoss();
            mCurTransaction = null;
            mFragmentManager.executePendingTransactions();
        }
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return ((Fragment)object).getView() == view;
    }

    @Override
    public Parcelable saveState() {
        Bundle state = null;
        if (mSavedState.size() > 0) {
            state = new Bundle();
            Fragment.SavedState[] fss = new Fragment.SavedState[mSavedState.size()];
            mSavedState.toArray(fss);
            state.putParcelableArray("states", fss);
            state.putStringArrayList("tags", mSavedFragmentTags);
        }
        for (int i=0; i<mFragments.size(); i++) {
            Fragment f = mFragments.get(i);
            if (f != null) {
                if (state == null) {
                    state = new Bundle();
                }
                String key = "f" + i;
                mFragmentManager.putFragment(state, key, f);
            }
        }
        return state;
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {
        if (state != null) {
            Bundle bundle = (Bundle)state;
            bundle.setClassLoader(loader);
            Parcelable[] fss = bundle.getParcelableArray("states");
            mSavedState.clear();
            mFragments.clear();

            ArrayList<String> tags = bundle.getStringArrayList("tags");
            if (tags != null) {
                mSavedFragmentTags = tags;
            } else {
                mSavedFragmentTags.clear();
            }
            if (fss != null) {
                for (int i=0; i<fss.length; i++) {
                    mSavedState.add((Fragment.SavedState)fss[i]);
                }
            }
            Iterable<String> keys = bundle.keySet();
            for (String key: keys) {
                if (key.startsWith("f")) {
                    int index = Integer.parseInt(key.substring(1));
                    Fragment f = mFragmentManager.getFragment(bundle, key);
                    if (f != null) {
                        while (mFragments.size() <= index) {
                            mFragments.add(null);
                        }
                        f.setMenuVisibility(false);
                        mFragments.set(index, f);
                    } else {
                        Log.w(TAG, "Bad fragment at key " + key);
                    }
                }
            }
        }
    }
}
</code>```

Then I implemented ViewPager.OnPageChangeListener in the fragment that contains the viewpager. And in the void onPageScrollStateChanged(int state) method I updated the view of my fragments in viewpager.

```<code>public class WordDetailFragment extends Fragment implements ViewPager.OnPageChangeListener {

    @BindView(R.id.word_parts_tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.word_part_view_pager)
    ViewPager mViewPager;

    private WordPagerAdapter mPagerAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_word_detail, container, false);
        ButterKnife.bind(this, view);
        mPagerAdapter = new WordPagerAdapter(getChildFragmentManager(), getActivity());
        mViewPager.setAdapter(mPagerAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
        mViewPager.addOnPageChangeListener(this);
        return view;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    Fragment mFragment;

    @Override
    public void onPageSelected(int position) {
        mFragment = mPagerAdapter.getItem(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        if (state == ViewPager.SCROLL_STATE_IDLE) {
            if (mFragment instanceof WordDefinitionFragment) {
                ((WordDefinitionFragment) mFragment).showTranslation();
               //Log.e("StateChanged", mFragment.getClass().getSimpleName());
            }
            if (mFragment instanceof WordExampleFragment) {
                ((WordExampleFragment) mFragment).showTranslation();
               //Log.e("StateChanged", mFragment.getClass().getSimpleName());
            }
            if (mFragment instanceof WordColFamFragment) {
                ((WordColFamFragment) mFragment).showTranslation();
                //Log.e("StateChanged", mFragment.getClass().getSimpleName());
            }
        }
    }

}
</code>```

And in my fragments, I had a callback interface which was implemented in the activity. And in void setUserVisibleHint(boolean isVisibleToUser) method I updated the UI again because neighbor fragments did not get updated.

```<code>public class WordExampleFragment extends Fragment {

    @BindView(R.id.example_field_name_id)
    TextView mExampleFieldNameTV;
    @BindView(R.id.word_tv)
    TextView mWordTv;
    @BindView(R.id.play_sound_iv)
    ImageView mPlaySoundIv;
    @BindView(R.id.show_translate_switch)
    Switch mShowTranslateSwitch;

    private TextView mExample1ContentFaTV;

    private List<WordInfo> mWordInfoList;
    private List<Example> mExampleList;
    private int mWordNumber;

    //callback interface
    private TranslateModeChangeListener mWordPartFragments;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mWordPartFragments = (TranslateModeChangeListener) context;
        } catch (ClassCastException ex) {
            throw new ClassCastException("Must implement WordPartFragments interface");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_word_example, container, false);
        ButterKnife.bind(this, view);

        mWordInfoList = WordActivity.sWordInfoList;
        mWordNumber = WordActivity.sWordNumber;
        mExampleList = mWordInfoList.get(mWordNumber).getExamples();

        showTranslation();
        mShowTranslateSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
               //this method is called from activity=> callback interface
               mWordPartFragments.changeTranslateMode(b);
                showTranslation();
            }
        });
        return view;
    }

    //this method is called when viewpager shows this fragment and it is visible to user
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {
            showTranslation();
        }
    }

    //this methoud updates my UI: shows or hides the translation
    public void showTranslation() {
        if (isAdded()) {
            boolean showTranslation = WordActivity.sTranslationShown;
            //Log.e("Ex", "added & shown = " + showTranslation);
            mShowTranslateSwitch.setChecked(showTranslation);
            mExample1ContentFaTV.setVisibility((showTranslation) ? View.VISIBLE : View.INVISIBLE);

        }
    }
}
</code>```

Body:
I have an activity which consists of three fragments. In one of these fragments I have a viewpager that consists of three other fragments. I call getChildFragmentManager() inside fragment that has viewpager in it. I have searched SO and read almost every answer that are related to this topic for example: this and this and one that seemed most useful was this but could not solve my problem. I think if i can just return POSITION_NONE for getItemPosition(Object object)  in FragmentStatePagerAdapter and call notifyDataSetChanged() will solve my problem but every time I do this my app crashes with this error:

java.lang.IllegalStateException: FragmentManager is already executing
  transactions!!!

and I mentioned that I am using getChildFragmentManager() inside my fragment.
Anyone thinks of any solution to this problem?

this is the parent fragment:

public class WordDetailFragment extends Fragment {

    @BindView(R.id.word_parts_tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.word_part_view_pager)
    ViewPager mViewPager;

    private WordPagerAdapter mPagerAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_word_detail, container, false);
        ButterKnife.bind(this, view);
        mPagerAdapter = new WordPagerAdapter(getChildFragmentManager(), getActivity());
        mViewPager.setAdapter(mPagerAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
        return view;
    }

    public void notifyTranslateChanged() {
        mViewPager.getAdapter().notifyDataSetChanged();
    }
}

this is the code for adapter

public class WordPagerAdapter extends FragmentStatePagerAdapter {
    final int PAGE_COUNT = 3;
    private String[] tabTitles = new String[]{"Definition", "Example", "Col & fam"};
    private Context context;

    public WordPagerAdapter(FragmentManager fm, Context context) {
        super(fm);
        this.context = context;
    }

    @Override
    public int getCount() {
        return PAGE_COUNT;
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment;
        switch (position) {
            case 0:
                fragment = new WordDefinitionFragment();
                break;
            case 1:
                fragment = new WordExampleFragment();
                break;
            case 2:
                fragment = new WordColFamFragment();
                break;

                default: fragment = new WordDefinitionFragment();
        }
        return fragment;
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        // Generate title based on item position
        return tabTitles[position];
    }
}

One of the fragments in viewpager

public class WordDefinitionFragment extends Fragment {

    @BindView(R.id.show_translate_switch)
    Switch mShowTranslateSwitch;

    private List<WordInfo> mWordInfoList;
    private List<Definition> mDefinitionList;
    private boolean mShowTranslation;
    private View mView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_word_definition, container, false);
        ButterKnife.bind(this, mView);

        mShowTranslation = SharedPrefHelper.getBooleanInfo(getActivity(), getString(R.string.show_translate_key));

        mShowTranslateSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (getActivity() != null)
                    ((WordActivity) getActivity()).changeTranslateMode(b);
                showTranslation(b);
            }
        });

        return mView;
    }
}

and my activity. U have just included the parts that i felt are needed here.

public class WordActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceSate) {
        super.onCreate(savedInstanceSate);
        setContentView(R.layout.activity_word);

    }

    public void changeTranslateMode(boolean show) {
        SharedPrefHelper.setBooleanInfo(this, getString(R.string.show_translate_ke)y, show);
        ((WordDetailFragment)mWordDetailFragment).notifyTranslateChanged();
    }

}

and my logcat error is

Body:
After many searches I could figure out a way which is not very smart but for the time being has solved my problem.
First of all I used the class FixedFragmentStatePagerAdapter from this post. I also had to remove the part in which the fragment bundle is restored because it caches fragment variables and views.

public abstract class FixedFragmentStatePagerAdapter extends PagerAdapter {
    private static final String TAG = "PagerAdapter";
    private static final boolean DEBUG = false;

    private final FragmentManager mFragmentManager;
    private FragmentTransaction mCurTransaction = null;

    private ArrayList<Fragment.SavedState> mSavedState = new ArrayList<>();
    private ArrayList<String> mSavedFragmentTags = new ArrayList<>();
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private Fragment mCurrentPrimaryItem = null;

    public FixedFragmentStatePagerAdapter(FragmentManager fm) {
        mFragmentManager = fm;
    }

    /**
     * Return the Fragment associated with a specified position.
     */
    public abstract Fragment getItem(int position);

    public String getTag(int position) {
        return null;
    }

    @Override
    public void startUpdate(ViewGroup container) {
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        // If we already have this item instantiated, there is nothing
        // to do.  This can happen when we are restoring the entire pager
        // from its saved state, where the fragment manager has already
        // taken care of restoring the fragments we previously had instantiated.
        if (mFragments.size() > position) {
            Fragment f = mFragments.get(position);
            if (f != null) {
                return f;
            }
        }

        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }

        Fragment fragment = getItem(position);
        String fragmentTag = getTag(position);
        if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment + " t=" + fragmentTag);
       /* if (mSavedState.size() > position) {
            String savedTag = mSavedFragmentTags.get(position);
            if (TextUtils.equals(fragmentTag, savedTag)) {
                Fragment.SavedState fss = mSavedState.get(position);
                if (fss != null) {
                    fragment.setInitialSavedState(fss);
                }
            }
        }*/
        while (mFragments.size() <= position) {
            mFragments.add(null);
        }
        fragment.setMenuVisibility(false);
        fragment.setUserVisibleHint(false);
        mFragments.set(position, fragment);
        mCurTransaction.add(container.getId(), fragment, fragmentTag);

        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        Fragment fragment = (Fragment)object;

        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }
        if (DEBUG) Log.v(TAG, "Removing item #" + position + ": f=" + object
                + " v=" + ((Fragment)object).getView() + " t=" + fragment.getTag());
        while (mSavedState.size() <= position) {
            mSavedState.add(null);
            mSavedFragmentTags.add(null);
        }
        mSavedState.set(position, mFragmentManager.saveFragmentInstanceState(fragment));
        mSavedFragmentTags.set(position, fragment.getTag());
        mFragments.set(position, null);

        mCurTransaction.remove(fragment);
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        Fragment fragment = (Fragment)object;
        if (fragment != mCurrentPrimaryItem) {
            if (mCurrentPrimaryItem != null) {
                mCurrentPrimaryItem.setMenuVisibility(false);
                mCurrentPrimaryItem.setUserVisibleHint(false);
            }
            if (fragment != null) {
                fragment.setMenuVisibility(true);
                fragment.setUserVisibleHint(true);
            }
            mCurrentPrimaryItem = fragment;
        }
    }

    @Override
    public void finishUpdate(ViewGroup container) {
        if (mCurTransaction != null) {
            mCurTransaction.commitAllowingStateLoss();
            mCurTransaction = null;
            mFragmentManager.executePendingTransactions();
        }
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return ((Fragment)object).getView() == view;
    }

    @Override
    public Parcelable saveState() {
        Bundle state = null;
        if (mSavedState.size() > 0) {
            state = new Bundle();
            Fragment.SavedState[] fss = new Fragment.SavedState[mSavedState.size()];
            mSavedState.toArray(fss);
            state.putParcelableArray("states", fss);
            state.putStringArrayList("tags", mSavedFragmentTags);
        }
        for (int i=0; i<mFragments.size(); i++) {
            Fragment f = mFragments.get(i);
            if (f != null) {
                if (state == null) {
                    state = new Bundle();
                }
                String key = "f" + i;
                mFragmentManager.putFragment(state, key, f);
            }
        }
        return state;
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {
        if (state != null) {
            Bundle bundle = (Bundle)state;
            bundle.setClassLoader(loader);
            Parcelable[] fss = bundle.getParcelableArray("states");
            mSavedState.clear();
            mFragments.clear();

            ArrayList<String> tags = bundle.getStringArrayList("tags");
            if (tags != null) {
                mSavedFragmentTags = tags;
            } else {
                mSavedFragmentTags.clear();
            }
            if (fss != null) {
                for (int i=0; i<fss.length; i++) {
                    mSavedState.add((Fragment.SavedState)fss[i]);
                }
            }
            Iterable<String> keys = bundle.keySet();
            for (String key: keys) {
                if (key.startsWith("f")) {
                    int index = Integer.parseInt(key.substring(1));
                    Fragment f = mFragmentManager.getFragment(bundle, key);
                    if (f != null) {
                        while (mFragments.size() <= index) {
                            mFragments.add(null);
                        }
                        f.setMenuVisibility(false);
                        mFragments.set(index, f);
                    } else {
                        Log.w(TAG, "Bad fragment at key " + key);
                    }
                }
            }
        }
    }
}

Then I implemented ViewPager.OnPageChangeListener in the fragment that contains the viewpager. And in the void onPageScrollStateChanged(int state) method I updated the view of my fragments in viewpager.

public class WordDetailFragment extends Fragment implements ViewPager.OnPageChangeListener {

    @BindView(R.id.word_parts_tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.word_part_view_pager)
    ViewPager mViewPager;

    private WordPagerAdapter mPagerAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_word_detail, container, false);
        ButterKnife.bind(this, view);
        mPagerAdapter = new WordPagerAdapter(getChildFragmentManager(), getActivity());
        mViewPager.setAdapter(mPagerAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
        mViewPager.addOnPageChangeListener(this);
        return view;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    Fragment mFragment;

    @Override
    public void onPageSelected(int position) {
        mFragment = mPagerAdapter.getItem(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        if (state == ViewPager.SCROLL_STATE_IDLE) {
            if (mFragment instanceof WordDefinitionFragment) {
                ((WordDefinitionFragment) mFragment).showTranslation();
               //Log.e("StateChanged", mFragment.getClass().getSimpleName());
            }
            if (mFragment instanceof WordExampleFragment) {
                ((WordExampleFragment) mFragment).showTranslation();
               //Log.e("StateChanged", mFragment.getClass().getSimpleName());
            }
            if (mFragment instanceof WordColFamFragment) {
                ((WordColFamFragment) mFragment).showTranslation();
                //Log.e("StateChanged", mFragment.getClass().getSimpleName());
            }
        }
    }

}

And in my fragments, I had a callback interface which was implemented in the activity. And in void setUserVisibleHint(boolean isVisibleToUser) method I updated the UI again because neighbor fragments did not get updated.

public class WordExampleFragment extends Fragment {

    @BindView(R.id.example_field_name_id)
    TextView mExampleFieldNameTV;
    @BindView(R.id.word_tv)
    TextView mWordTv;
    @BindView(R.id.play_sound_iv)
    ImageView mPlaySoundIv;
    @BindView(R.id.show_translate_switch)
    Switch mShowTranslateSwitch;

    private TextView mExample1ContentFaTV;

    private List<WordInfo> mWordInfoList;
    private List<Example> mExampleList;
    private int mWordNumber;

    //callback interface
    private TranslateModeChangeListener mWordPartFragments;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mWordPartFragments = (TranslateModeChangeListener) context;
        } catch (ClassCastException ex) {
            throw new ClassCastException("Must implement WordPartFragments interface");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_word_example, container, false);
        ButterKnife.bind(this, view);

        mWordInfoList = WordActivity.sWordInfoList;
        mWordNumber = WordActivity.sWordNumber;
        mExampleList = mWordInfoList.get(mWordNumber).getExamples();

        showTranslation();
        mShowTranslateSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
               //this method is called from activity=> callback interface
               mWordPartFragments.changeTranslateMode(b);
                showTranslation();
            }
        });
        return view;
    }

    //this method is called when viewpager shows this fragment and it is visible to user
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {
            showTranslation();
        }
    }

    //this methoud updates my UI: shows or hides the translation
    public void showTranslation() {
        if (isAdded()) {
            boolean showTranslation = WordActivity.sTranslationShown;
            //Log.e("Ex", "added & shown = " + showTranslation);
            mShowTranslateSwitch.setChecked(showTranslation);
            mExample1ContentFaTV.setVisibility((showTranslation) ? View.VISIBLE : View.INVISIBLE);

        }
    }
}


问:
Problem in JFileChooser

I want to use JfileChooser to choose a file and writeObject to the selected file or readObject from the selected file. I have serialize my class but I don't know how to serialize this MetalFileChooserUI? Or do I need to do it? Thank you very much.

smiliar error message to mine

Can someone help me to find a solution to it? Thank you.
My Error message:

java.io.NotSerializableException: javax.swing.plaf.metal.MetalFileChooserUI
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
      at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
      at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.writeObject(Unknown Source)
      at javax.swing.ArrayTable.writeArrayTable(Unknown Source)
      at javax.swing.ActionMap.writeObject(Unknown Source)
      at sun.reflect.GeneratedMethodAccessor11.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
      at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
      at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteObject(Unknown Source)
      at javax.swing.JComponent.writeObject(Unknown Source)
      at sun.reflect.GeneratedMethodAccessor10.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
      at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
      at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
      at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
      at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteObject(Unknown Source)
      at javax.swing.JList.writeObject(Unknown Source)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
      at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
      at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
      at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
      at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteObject(Unknown Source)
      at java.awt.Window.writeObject(Unknown Source)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
      at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
      at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.writeObject(Unknown Source)
      at java.awt.Window.writeObject(Unknown Source)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
      at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
      at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.writeObject(Unknown Source)
      at ver_2.sudoku_GUI.actionPerformed(sudoku_GUI.java:90)
      at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
      at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
      at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
      at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
      at javax.swing.AbstractButton.doClick(Unknown Source)
      at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
      at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
      at java.awt.Component.processMouseEvent(Unknown Source)
      at javax.swing.JComponent.processMouseEvent(Unknown Source)
      at java.awt.Component.processEvent(Unknown Source)
      at java.awt.Container.processEvent(Unknown Source)
      at java.awt.Component.dispatchEventImpl(Unknown Source)
      at java.awt.Container.dispatchEventImpl(Unknown Source)
      at java.awt.Component.dispatchEvent(Unknown Source)
      at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
      at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
      at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
      at java.awt.Container.dispatchEventImpl(Unknown Source)
      at java.awt.Window.dispatchEventImpl(Unknown Source)
      at java.awt.Component.dispatchEvent(Unknown Source)
      at java.awt.EventQueue.dispatchEvent(Unknown Source)
      at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
      at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
      at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
      at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
      at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
      at java.awt.EventDispatchThread.run(Unknown Source)

答: I'm not sure why you would want to serialize a file chooser as what would be the sense in this?  I think that your best bet is to not serialize the gui portion of a program but rather the data held in the model (assuming an MVC structure) -- unless you have requirements that we need to know about.</p>

Title: Problem in JFileChooser


问:
getorgchart allowed maximum node
I'm using getorgchart and i have a tree which has 86 nodes and i want to display them vertically. But it does not shown after 30. node. It must be like that:

Parent Node

1.Node

2.Node

Node

...

...

...

Node

But it seems like

Parent Node

30-31-32-....-86.node

1.Node

2.Node

3.Node

...

...

...

Node

Sorry for my english.

here is my code:

```<code> $.getJSON("/profile/getSchema/" + id, function (source) {
    $('#waiting').hide();

    var peopleElement = document.getElementById("people");
    var _layout;
    var _scale = 0.5;

    if (source.length > 1)
    {
        _layout = getOrgChart.MIXED_HIERARCHY_RIGHT_LINKS
        _scale = "auto";
    }
            var orgChart = new getOrgChart(peopleElement, {
                expandToLevel: 100,
                enableExportToImage: true,
                clickNodeEvent: clickHandler,
                enableZoomOnNodeDoubleClick: true,
                layout: _layout,
                primaryFields: ["Name", "N", "NShort", "Email"],
                photoFields: ["Image"],
                scale: _scale,
                enableEdit: false,
                enableDetailsView: true,
                dataSource: source
            });

            //$('.get-down').next().remove();
        });
</code>```

答:
You can set the maxDepth to 100 and will work

Here is an example

var orgChart = new getOrgChart(peopleElement, {
                maxDepth : 100,

Title: getorgchart allowed maximum node

Body:
I'm using getorgchart and i have a tree which has 86 nodes and i want to display them vertically. But it does not shown after 30. node. It must be like that:

Parent Node

1.Node

2.Node

Node

...

...

...

Node

But it seems like

Parent Node

30-31-32-....-86.node

1.Node

2.Node

3.Node

...

...

...

Node

Sorry for my english.

here is my code:

 $.getJSON("/profile/getSchema/" + id, function (source) {
    $('#waiting').hide();

    var peopleElement = document.getElementById("people");
    var _layout;
    var _scale = 0.5;

    if (source.length > 1)
    {
        _layout = getOrgChart.MIXED_HIERARCHY_RIGHT_LINKS
        _scale = "auto";
    }
            var orgChart = new getOrgChart(peopleElement, {
                expandToLevel: 100,
                enableExportToImage: true,
                clickNodeEvent: clickHandler,
                enableZoomOnNodeDoubleClick: true,
                layout: _layout,
                primaryFields: ["Name", "N", "NShort", "Email"],
                photoFields: ["Image"],
                scale: _scale,
                enableEdit: false,
                enableDetailsView: true,
                dataSource: source
            });

            //$('.get-down').next().remove();
        });


问:
Pandas scraped data not working in pandas
Why is when I enter data manually into an excel, pandas works.  Yet when I scrape data, put it in to a csv.  It gives me:

```<code>    zz = df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)
ValueError: operands could not be broadcast together with shapes (148,) (537,) ()
</code>```

It has not occurred for other sites.  Am I missing something obvious here?  Is the excel formatted incorrectly or the data is different here somehow?

df3

```<code>df3 = pd.DataFrame(columns=['DAT', 'G', 'TN', 'O1', 'L1', 'TN2', 'O2', 'L2', 'D', 'AJ', 'AK', 'AL'])
</code>```

df1

```<code>                                         EW    WE  \
0             Ponte Preta U20 v Cruzeiro U20  2.10
1  Fluminense RJ U20 v Defensor Sporting U20  2.00
2              Gremio RS U20 v Palmeiras U20  3.30
3                       Barcelona v Sporting  1.33

                                                  DA
0  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
1  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
2  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
3  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
</code>```

Code:

```<code>df3 = pd.DataFrame(columns=['DAT', 'G', 'TN', 'O1', 'L1', 'TN2', 'O2', 'L2', 'D', 'AJ', 'AK', 'AL'])

df3['DAT'] = df2['AA']

zz = df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)
print(zz)
</code>```

I have provided all my scripts that create the dataframe 1, 2 and the pandas code up until where it creates the error here

I keep getting

Error:

```<code>    zz = df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)
ValueError: operands could not be broadcast together with shapes (0,) (4,) ()
</code>```

Error files created from scrape and loaded as a dataframe:

In case that is not sufficient I have also loaded up the files as they are.

File 1, File 2

Working files created manually:

Working:

File 1, File 2

Any idea how this can be fixed?

答:
I think you need change:

```<code>df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)
</code>```

to

```<code>df1.WE=np.where(df1.EW.isin(df2.AL),df1.WE,np.nan)
</code>```

Problem is different length of DataFrame with real data. So need change data from df1 with another data - comapring return maks with same length as df1 and no error.

With your data:

```<code>df1 = pd.read_csv('df1.csv', names=['a','b','c'])
print (df1.head())
                                           a     b  \
0             Ponte Preta U20 v Cruzeiro U20  2.10
1  Fluminense RJ U20 v Defensor Sporting U20  2.00
2              Gremio RS U20 v Palmeiras U20  3.30
3                       Barcelona v Sporting  1.33
4                        Bayern Munich v PSG  2.40

                                                   c
0  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
1  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
2  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
3  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
4  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
</code>```

```<code>df2 = pd.read_csv('df2.csv', names=['a','b','c', 'd', 'e'])
print (df2.head())
                 a                    b                  c     d  \
0          In-Play      CSKA Moscow U19        Man Utd U19  1.14
1          In-Play  Atletico Madrid U19        Chelsea U19  1.01
2          In-Play         Juventus U19     Olympiakos U19  1.40
3  Starting in 22'       Paris St-G U19  Bayern Munich U19  2.24
4      Today 21:00         Man City U19       Shakhtar U19  2.66

                                                   e
0  https://www.betfair.com.au/exchange/plus/footb...
1  https://www.betfair.com.au/exchange/plus/footb...
2  https://www.betfair.com.au/exchange/plus/footb...
3  https://www.betfair.com.au/exchange/plus/footb...
4  https://www.betfair.com.au/exchange/plus/footb...
</code>```

comapre numeric columns, here b and d:

```<code>df1.b=np.where(df1.b.isin(df2.d),df1.b,np.nan)
#first 5 values is NaNs
print (df1.head())
                                           a   b  \
0             Ponte Preta U20 v Cruzeiro U20 NaN
1  Fluminense RJ U20 v Defensor Sporting U20 NaN
2              Gremio RS U20 v Palmeiras U20 NaN
3                       Barcelona v Sporting NaN
4                        Bayern Munich v PSG NaN
</code>```

```<code>                                                   c
0  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
1  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
2  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
3  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
4  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...

#check if some not NaNs values in b column
print (df1[df1.b.notnull()])
                                       a      b  \
23                Swindon v Forest Green   1.40
50       Sportivo Barracas v Canuelas FC  13.00
80                              FC Nitra   1.53
81                                   0-0   1.40
83       Cape Town City v Maritzburg Utd   1.53
84         Mamelodi Sundowns v Baroka FC   3.75
90  Dorking Wanderers v Tonbridge Angels   1.53
95             Coalville Town v Stamford   1.40

                                                    c
23  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
50  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
80  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
81  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
83  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
84  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
90  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
95  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
</code>```

Also problem of your test data is there are same number of rows (4), so no errors.

Body:
Why is when I enter data manually into an excel, pandas works.  Yet when I scrape data, put it in to a csv.  It gives me:

    zz = df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)
ValueError: operands could not be broadcast together with shapes (148,) (537,) ()

It has not occurred for other sites.  Am I missing something obvious here?  Is the excel formatted incorrectly or the data is different here somehow?

df3

df3 = pd.DataFrame(columns=['DAT', 'G', 'TN', 'O1', 'L1', 'TN2', 'O2', 'L2', 'D', 'AJ', 'AK', 'AL'])

df1

                                         EW    WE  \
0             Ponte Preta U20 v Cruzeiro U20  2.10
1  Fluminense RJ U20 v Defensor Sporting U20  2.00
2              Gremio RS U20 v Palmeiras U20  3.30
3                       Barcelona v Sporting  1.33

                                                  DA
0  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
1  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
2  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
3  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...

Code:

df3 = pd.DataFrame(columns=['DAT', 'G', 'TN', 'O1', 'L1', 'TN2', 'O2', 'L2', 'D', 'AJ', 'AK', 'AL'])

df3['DAT'] = df2['AA']

zz = df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)
print(zz)

I have provided all my scripts that create the dataframe 1, 2 and the pandas code up until where it creates the error here

I keep getting

Error:

    zz = df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)
ValueError: operands could not be broadcast together with shapes (0,) (4,) ()

Error files created from scrape and loaded as a dataframe:

In case that is not sufficient I have also loaded up the files as they are.

File 1, File 2

Working files created manually:

Working:

File 1, File 2

Any idea how this can be fixed?

Body:
I think you need change:

df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)

to

df1.WE=np.where(df1.EW.isin(df2.AL),df1.WE,np.nan)

Problem is different length of DataFrame with real data. So need change data from df1 with another data - comapring return maks with same length as df1 and no error.

With your data:

df1 = pd.read_csv('df1.csv', names=['a','b','c'])
print (df1.head())
                                           a     b  \
0             Ponte Preta U20 v Cruzeiro U20  2.10
1  Fluminense RJ U20 v Defensor Sporting U20  2.00
2              Gremio RS U20 v Palmeiras U20  3.30
3                       Barcelona v Sporting  1.33
4                        Bayern Munich v PSG  2.40

                                                   c
0  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
1  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
2  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
3  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
4  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...

df2 = pd.read_csv('df2.csv', names=['a','b','c', 'd', 'e'])
print (df2.head())
                 a                    b                  c     d  \
0          In-Play      CSKA Moscow U19        Man Utd U19  1.14
1          In-Play  Atletico Madrid U19        Chelsea U19  1.01
2          In-Play         Juventus U19     Olympiakos U19  1.40
3  Starting in 22'       Paris St-G U19  Bayern Munich U19  2.24
4      Today 21:00         Man City U19       Shakhtar U19  2.66

                                                   e
0  https://www.betfair.com.au/exchange/plus/footb...
1  https://www.betfair.com.au/exchange/plus/footb...
2  https://www.betfair.com.au/exchange/plus/footb...
3  https://www.betfair.com.au/exchange/plus/footb...
4  https://www.betfair.com.au/exchange/plus/footb...

comapre numeric columns, here b and d:

df1.b=np.where(df1.b.isin(df2.d),df1.b,np.nan)
#first 5 values is NaNs
print (df1.head())
                                           a   b  \
0             Ponte Preta U20 v Cruzeiro U20 NaN
1  Fluminense RJ U20 v Defensor Sporting U20 NaN
2              Gremio RS U20 v Palmeiras U20 NaN
3                       Barcelona v Sporting NaN
4                        Bayern Munich v PSG NaN

                                                   c
0  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
1  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
2  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
3  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
4  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...

#check if some not NaNs values in b column
print (df1[df1.b.notnull()])
                                       a      b  \
23                Swindon v Forest Green   1.40
50       Sportivo Barracas v Canuelas FC  13.00
80                              FC Nitra   1.53
81                                   0-0   1.40
83       Cape Town City v Maritzburg Utd   1.53
84         Mamelodi Sundowns v Baroka FC   3.75
90  Dorking Wanderers v Tonbridge Angels   1.53
95             Coalville Town v Stamford   1.40

                                                    c
23  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
50  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
80  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
81  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
83  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
84  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
90  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
95  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...

Also problem of your test data is there are same number of rows (4), so no errors.