问:
CoreLocationManager never pauses?
Trying to get my app to use less power, it's tracking location always in the background but I'd like for it automatically pause so I can turn on region watching and use that to resume precise location monitoring once the user moves around a bit.

I've had the app on for half an hour now and the location service is not pausing.  I think this has been the case since Apple changed location stuff in iOS 13? I'm not really sure.  All the documentation I can find online seems extremely outdated.

Any advice is greatly appreciated, relevant code follows:

```<code>init() {
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = 10
        locationManager.activityType = .fitness
        locationManager.requestAlwaysAuthorization()
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.pausesLocationUpdatesAutomatically = true
        locationManager.showsBackgroundLocationIndicator = true
        locationManager.startUpdatingLocation()
    }
    func locationManagerDidPauseLocationUpdates(_ manager: CLLocationManager) {
        delegate?.paused(tracker: self)
        print("MT | LOCATION SERVICES PAUSED!") <---- NEVER GETTING CALLED (been running for 40 minutes now, no location updates, still going though?)
        // if not already, start region monitoring

    }
 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // Collect data
        for location in locations {
           print("MT | New Location: \(location)")
        }
    }
</code>```

答:
The issue is caused by your desired accuracy.

You are setting the accuracy to the best, which will make your application run continuously, so it will never pause in any iOS versions.

Furthermore, in a practical test whether it is pausing or not, change the accuracy to kCLLocationAccuracyHundredMeters. It will definitely pause. You can change the filter accuracy as you need for the next update.

Title: CoreLocationManager never pauses?

Body:
Trying to get my app to use less power, it's tracking location always in the background but I'd like for it automatically pause so I can turn on region watching and use that to resume precise location monitoring once the user moves around a bit.

I've had the app on for half an hour now and the location service is not pausing.  I think this has been the case since Apple changed location stuff in iOS 13? I'm not really sure.  All the documentation I can find online seems extremely outdated.

Any advice is greatly appreciated, relevant code follows:

init() {
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = 10
        locationManager.activityType = .fitness
        locationManager.requestAlwaysAuthorization()
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.pausesLocationUpdatesAutomatically = true
        locationManager.showsBackgroundLocationIndicator = true
        locationManager.startUpdatingLocation()
    }
    func locationManagerDidPauseLocationUpdates(_ manager: CLLocationManager) {
        delegate?.paused(tracker: self)
        print("MT | LOCATION SERVICES PAUSED!") <---- NEVER GETTING CALLED (been running for 40 minutes now, no location updates, still going though?)
        // if not already, start region monitoring

    }
 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // Collect data
        for location in locations {
           print("MT | New Location: \(location)")
        }
    }


来源: stackexchange

问:
How to Multi-threading this scenario of problem?
I would like to make a simulation of a distributed system, in which, I should make a research for information(supplies) in a distributed (parallel if I could!!) way, for example I have the following class:

```<code>public class Group{
public int identifier;
public int[] members;
public String name;
public String[] supplies;
public int[] neighbors;}
</code>```

There are many groups, each one has a name and consists of a list of members, neighbors and supplies, each member has some information and list to other groups that may contain pertinent information and supplies, and so on.

1- I want to make a research for supplies, First: inside one group, if I do not find the required supply, I should make a search inside all groups which are neighbors to the this group, I think to make this using Multi-threading, I mean, if the search was failed I should make a search inside all the other neighbors at the same time using multiple threads, each one take in consideration one neighbor, If I have 10 neighbors then 10 threads should be created....

2- Now, if I want  to begin the re-search at the first time with several groups, I mean to begin with 3 or 4 groups or more, each one look for a different supply, or the same....
 + one group which invoke the search could be a neighbor for another group...

So, my question is How to achieve this scenario using threads ?

PS.I have a machine with a single processor with one core, and I do not care about a time of execution (the overhead), all I want is to simulate this problem...

Thanks for every response, and best regards.

答:
I don't see any performance advantage to multi-threading this on a single CPU machine.  This is because only 1 thread will be able to run at a time and there will be switching time between threads, thus it will probably actually take more time to find a group with the desired resource.

Personally, I'd just iterate through the first group's neighbors and check them for resources.   Then, if the resources were not found, I'd call the search on each of the sub-groups, passing in the list of groups that were already checked, so it can skip groups that have already been checked.  Something like:

```<code>public Group searchForGroupWithResource(Resource resource){
    List<Group> groupsToCheck = new ArrayList<Group>();
    groupsToCheck.add(this);
    int currentIndex = 0;
    while(currentIndex < groupsToCheck.size()){
        Group currentGroup = groupsToCheck.get(currentIndex);
        if(currentGroup.hasResource(resource)){
            return currentGroup;
        }
        groupsToCheck.addAll(currentGroup.getNeighbors(groupsToCheck));
        currentIndex++;
    }
    return null;
}

public List<Group> getNeighbors(List<Group> excludeGroups){
    //Get non-excluded neighbors
    List<Group> returnNeighbors = new ArrayList<Group>();
    for(Group neighbor : neighbors){
        boolean includeGroup = true;
        for(Group excludeGroup : excludeGroups){
            if(excludeGroup.equals(neighbor)){
                includeGroup = false;
                break;
            }
        }
        if(includeGroup){
            returnNeighbors.add(neighbor);
        }
    }
    return returnNeighbors;
}
</code>```

Note:  If you still decide to go for the multi-threading, I would suggest a common object that stores information about the search that is accessible to all threads.  This would specify the Groups that were checked (so you don't check the same group twice) and whether the required supplies were found (so you can stop checking resources).

ContentLicense: CC BY-SA 3.0

Body:
I would like to make a simulation of a distributed system, in which, I should make a research for information(supplies) in a distributed (parallel if I could!!) way, for example I have the following class:

public class Group{
public int identifier;
public int[] members;
public String name;
public String[] supplies;
public int[] neighbors;}

There are many groups, each one has a name and consists of a list of members, neighbors and supplies, each member has some information and list to other groups that may contain pertinent information and supplies, and so on.

1- I want to make a research for supplies, First: inside one group, if I do not find the required supply, I should make a search inside all groups which are neighbors to the this group, I think to make this using Multi-threading, I mean, if the search was failed I should make a search inside all the other neighbors at the same time using multiple threads, each one take in consideration one neighbor, If I have 10 neighbors then 10 threads should be created....

2- Now, if I want  to begin the re-search at the first time with several groups, I mean to begin with 3 or 4 groups or more, each one look for a different supply, or the same....
 + one group which invoke the search could be a neighbor for another group...

So, my question is How to achieve this scenario using threads ?

PS.I have a machine with a single processor with one core, and I do not care about a time of execution (the overhead), all I want is to simulate this problem...

Thanks for every response, and best regards.

Body:
I don't see any performance advantage to multi-threading this on a single CPU machine.  This is because only 1 thread will be able to run at a time and there will be switching time between threads, thus it will probably actually take more time to find a group with the desired resource.

Personally, I'd just iterate through the first group's neighbors and check them for resources.   Then, if the resources were not found, I'd call the search on each of the sub-groups, passing in the list of groups that were already checked, so it can skip groups that have already been checked.  Something like:

public Group searchForGroupWithResource(Resource resource){
    List<Group> groupsToCheck = new ArrayList<Group>();
    groupsToCheck.add(this);
    int currentIndex = 0;
    while(currentIndex < groupsToCheck.size()){
        Group currentGroup = groupsToCheck.get(currentIndex);
        if(currentGroup.hasResource(resource)){
            return currentGroup;
        }
        groupsToCheck.addAll(currentGroup.getNeighbors(groupsToCheck));
        currentIndex++;
    }
    return null;
}

public List<Group> getNeighbors(List<Group> excludeGroups){
    //Get non-excluded neighbors
    List<Group> returnNeighbors = new ArrayList<Group>();
    for(Group neighbor : neighbors){
        boolean includeGroup = true;
        for(Group excludeGroup : excludeGroups){
            if(excludeGroup.equals(neighbor)){
                includeGroup = false;
                break;
            }
        }
        if(includeGroup){
            returnNeighbors.add(neighbor);
        }
    }
    return returnNeighbors;
}

Note:  If you still decide to go for the multi-threading, I would suggest a common object that stores information about the search that is accessible to all threads.  This would specify the Groups that were checked (so you don't check the same group twice) and whether the required supplies were found (so you can stop checking resources).


问:
Xamarin Forms - Custom Control Binding Issue
There's a good chance I haven't had enough coffee today, but I've got an issue I've been going around in circles with for the last few hours.

I've created a CustomEntry class which is just a ContentView containing an Entry and a few other bits and I have added a new BindableProperty to this class which should set it's "Test" property.

The plan is to pass a string value from my ViewModel via this bindableproperty but rather than just hardcode the value (eg. ) I want to pass a value from my ViewModel using a binding (eg. Test="{Binding AStringFromMyViewModel}") - For some reason, when I try using a binding, the bindableproperty is never set.

Note that if I do hard-code the value, eg Test="123", then it works fine but doesn't work if I do Test="{Binding AStringFromMyViewModel}" as I have done below.

Here's what I have:

Page XML

```<code><?xml version="1.0" encoding="UTF-8"?>
<pages:BasePage xmlns:pages="clr-namespace:ShoppingListNEW.Pages" NavigationPage.HasNavigationBar="True" xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:helpers="clr-namespace:ShoppingListNEW.MarkupExtensions" xmlns:views="clr-namespace:ShoppingListNEW.Views" xmlns:yummy="clr-namespace:Xamarin.Forms.PancakeView;assembly=Xamarin.Forms.PancakeView" x:Class="ShoppingListNEW.Pages.SignUp">
    <StackLayout>
        <Label Margin="15,15,0,0" TextColor="#2b2c2e" Text="{helpers:TranslateExtension FirstName}"></Label>
        <views:CustomEntry Test="{Binding AStringFromMyViewModel, Mode=TwoWay}" BorderColor="Gray" HeightRequest="50" PlaceholderColor="Gray" Margin="15,0,15,0" BackgroundColor="Transparent" Text="{Binding FirstName}" TextColor="#232324" Placeholder="{helpers:TranslateExtension PleaseEnterYourFirstName}" AutomationId="txtFirstName" />
    </StackLayout>
</pages:BasePage>
</code>```

Page Backing

```<code>public partial class SignUp : BasePage
{
    public SignUp()
    {
        InitializeComponent();

        //Bind our UI to our ViewModel
        BindingContext = App.Locator.SignUpViewModel;
    }
}
</code>```

View Model

```<code>public class SignUpViewModel : ViewModelBase
{
    //I expect this value of "123" to be passed to my BindableProperty but it's not
    public string AStringFromMyViewModel {get; set; } = "123";

    public SignUpViewModel()
    {
    }
}
</code>```

And finally my new CustomEntry control - I don't think you need the XML, as it's just the BindableProperty that isn't working.

```<code>public partial class CustomEntry : ContentView, INotifyPropertyChanged
{
    public static readonly BindableProperty TestProperty =
        BindableProperty.Create("Test", typeof(string), typeof(CustomEntry), null, BindingMode.OneWay, null);

    public string Test
    {
        get
        {
            return (string)GetValue(TestProperty);
        }
        set
        {
    //This is never called
            SetValue(TestProperty, value);
        }
    }

    public CustomEntry()
    {
        InitializeComponent();
        BindingContext = this;
    }

}
</code>```

Thanks in advance.

答:
Modify your ViewModel to implement INotifyPropertyChanged
and change your AStringFromMyViewModel {get; set; } become

```<code>private string _aString;
public string AStringFromMyViewModel {
    get => _aString;
    set {
        _aString = value;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(AStringFromMyViewModel)))
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There's a good chance I haven't had enough coffee today, but I've got an issue I've been going around in circles with for the last few hours.

I've created a CustomEntry class which is just a ContentView containing an Entry and a few other bits and I have added a new BindableProperty to this class which should set it's "Test" property.

The plan is to pass a string value from my ViewModel via this bindableproperty but rather than just hardcode the value (eg. ) I want to pass a value from my ViewModel using a binding (eg. Test="{Binding AStringFromMyViewModel}") - For some reason, when I try using a binding, the bindableproperty is never set.

Note that if I do hard-code the value, eg Test="123", then it works fine but doesn't work if I do Test="{Binding AStringFromMyViewModel}" as I have done below.

Here's what I have:

Page XML

<?xml version="1.0" encoding="UTF-8"?>
<pages:BasePage xmlns:pages="clr-namespace:ShoppingListNEW.Pages" NavigationPage.HasNavigationBar="True" xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:helpers="clr-namespace:ShoppingListNEW.MarkupExtensions" xmlns:views="clr-namespace:ShoppingListNEW.Views" xmlns:yummy="clr-namespace:Xamarin.Forms.PancakeView;assembly=Xamarin.Forms.PancakeView" x:Class="ShoppingListNEW.Pages.SignUp">
    <StackLayout>

        <views:CustomEntry Test="{Binding AStringFromMyViewModel, Mode=TwoWay}" BorderColor="Gray" HeightRequest="50" PlaceholderColor="Gray" Margin="15,0,15,0" BackgroundColor="Transparent" Text="{Binding FirstName}" TextColor="#232324" Placeholder="{helpers:TranslateExtension PleaseEnterYourFirstName}" AutomationId="txtFirstName" />
    </StackLayout>
</pages:BasePage>

Page Backing

public partial class SignUp : BasePage
{
    public SignUp()
    {
        InitializeComponent();

        //Bind our UI to our ViewModel
        BindingContext = App.Locator.SignUpViewModel;
    }
}

View Model

public class SignUpViewModel : ViewModelBase
{
    //I expect this value of "123" to be passed to my BindableProperty but it's not
    public string AStringFromMyViewModel {get; set; } = "123";

    public SignUpViewModel()
    {
    }
}

And finally my new CustomEntry control - I don't think you need the XML, as it's just the BindableProperty that isn't working.

public partial class CustomEntry : ContentView, INotifyPropertyChanged
{
    public static readonly BindableProperty TestProperty =
        BindableProperty.Create("Test", typeof(string), typeof(CustomEntry), null, BindingMode.OneWay, null);

    public string Test
    {
        get
        {
            return (string)GetValue(TestProperty);
        }
        set
        {
    //This is never called
            SetValue(TestProperty, value);
        }
    }

    public CustomEntry()
    {
        InitializeComponent();
        BindingContext = this;
    }

}

Thanks in advance.

Body:
Modify your ViewModel to implement INotifyPropertyChanged
and change your AStringFromMyViewModel {get; set; } become

private string _aString;
public string AStringFromMyViewModel {
    get => _aString;
    set {
        _aString = value;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(AStringFromMyViewModel)))
    }
}


问:
Unable to apply animation for PNotify in Angular app
I am using PNotify for alert message in angular app. I have applied animation, but animation is not working.

Below is the code that which I am using.

```<code>PNotify.notice({
          title: 'Animate.css Effect',
          text: 'Part Quantity is greater.',
          modules: {
            Animate: {
              animate: true,
              inClass: 'rotateInDownLeft',
              outClass: 'rotateOutUpRight'
            }
          }
        });
</code>```

答:
If you are using different modules apart fromapp.module.ts, include BrowserAnimationsModule in those modules also.
hope it will solve.

Body:
I am using PNotify for alert message in angular app. I have applied animation, but animation is not working.

Below is the code that which I am using.

PNotify.notice({
          title: 'Animate.css Effect',
          text: 'Part Quantity is greater.',
          modules: {
            Animate: {
              animate: true,
              inClass: 'rotateInDownLeft',
              outClass: 'rotateOutUpRight'
            }
          }
        });


问:
Reducing the size of UISwitch in Xamarin Forms does not work
In Xamarin Forms, I created a custom renderer for Switch. On iOS, I updated the scale transform to make it smaller than its default size:

```<code>Control.Transform = CGAffineTransform.MakeScale((float)0.75, (float)0.75);
</code>```

While this successfully resizes the Switch, it doesn't resize its bounding box. How can I resize it as well?

Here the background color of the Switch is set to red in XAML. It looks like the original bounds are still being maintained even though the thumb is smaller.

答:
You can use the Scale property of Switch in Xamarin.Forms:

```<code>   <Switch OnColor="Orange" Scale="0.75" BackgroundColor="Red"
    ThumbColor="Green" />
</code>```

Body:
In Xamarin Forms, I created a custom renderer for Switch. On iOS, I updated the scale transform to make it smaller than its default size:

Control.Transform = CGAffineTransform.MakeScale((float)0.75, (float)0.75);

While this successfully resizes the Switch, it doesn't resize its bounding box. How can I resize it as well?

Here the background color of the Switch is set to red in XAML. It looks like the original bounds are still being maintained even though the thumb is smaller.

Body:
You can use the Scale property of Switch in Xamarin.Forms:

   <Switch OnColor="Orange" Scale="0.75" BackgroundColor="Red"
    ThumbColor="Green" />


问:
Some labels and UITextfiled and it's text becoming black automatically when selecting Dark Dode
I am migrated my all code to swift 5 and Xcode 11 recently,
My app works fine for iOS versions below 13.0 but when I chose Dark Mode, the labels are going black, some textfields and it's text automatically shown black, all of has white background and app theme is in white background and it is very hard to reset it from storyboard.

Anyone has any trick to do it in app delegate or in viewdidload to turn off the dark mode for this particular app? I don't want to take the facility of dark mode right now.

答:
Yes you can do it in one line of code to eliminate the dark mode entirely by setting the UserInterfaceStyle on main window:

```<code>window!.overrideUserInterfaceStyle = .light
</code>```

or you can do it in

```<code>if #available(iOS 13.0, *) {
    window!.overrideUserInterfaceStyle = .light
}
</code>```

Body:
Yes you can do it in one line of code to eliminate the dark mode entirely by setting the UserInterfaceStyle on main window:

window!.overrideUserInterfaceStyle = .light

or you can do it in

if #available(iOS 13.0, *) {
    window!.overrideUserInterfaceStyle = .light
}


问:
Want to show/hide div based on dropdown box selection
I want to have jQuery show div id='business' only if 'business use' is selected in the dropdown box.

This is my code:

```<code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$('#purpose').on('change', function() {
  if ( this.value == '1');
  {
    $("#business").show();
  }
  else
  {
    $("#business").hide();
  }
});
});
</script>
<body>
<select id='purpose'>
<option value="0">Personal use</option>
<option value="1">Business use</option>
<option value="2">Passing on to a client</option>
</select>
<div style='display:none;' id='business'>Business Name<br/>
<br/>
    <input type='text' class='text' name='business' value size='20' />
    <br/>
</div>
</body>
</code>```

and the JSFiddle: http://jsfiddle.net/2kGzZ/1/

答:
https://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-show-hide-div-using-select-box
It's working well in my case

$(document).ready(function(){
    $("select").change(function(){
        $(this).find("option:selected").each(function(){
            var optionValue = $(this).attr("value");
            if(optionValue){
                $(".box").not("." + optionValue).hide();
                $("." + optionValue).show();
            } else{
                $(".box").hide();
            }
        });
    }).change();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Show Hide Elements Using Select Box</title>
<style>
    .box{
        color: #fff;
        padding: 50px;
        display: none;
        margin-top: 10px;
    }
    .red{ background: #ff0000; }
    .green{ background: #228B22; }
    .blue{ background: #0000ff; }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

</head>
<body>
    <div>
        <select>
            <option>Choose Color</option>
            <option value="red">Red</option>
            <option value="green">Green</option>
            <option value="blue">Blue</option>
        </select>
    </div>
    <div class="red box">You have selected <strong>red option</strong> so i am here</div>
    <div class="green box">You have selected <strong>green option</strong> so i am here</div>
    <div class="blue box">You have selected <strong>blue option</strong> so i am here</div>
</body>
</html></code>```

Body:
I want to have jQuery show div id='business' only if 'business use' is selected in the dropdown box.

This is my code:

<select id='purpose'>
<option value="0">Personal use</option>
<option value="1">Business use</option>
<option value="2">Passing on to a client</option>
</select>

Business Name

    <input type='text' class='text' name='business' value size='20' />

and the JSFiddle: http://jsfiddle.net/2kGzZ/1/

Body:
https://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-show-hide-div-using-select-box
It's working well in my case

$(document).ready(function(){
    $("select").change(function(){
        $(this).find("option:selected").each(function(){
            var optionValue = $(this).attr("value");
            if(optionValue){
                $(".box").not("." + optionValue).hide();
                $("." + optionValue).show();
            } else{
                $(".box").hide();
            }
        });
    }).change();
});

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Show Hide Elements Using Select Box</title>
<style>
    .box{
        color: #fff;
        padding: 50px;
        display: none;
        margin-top: 10px;
    }
    .red{ background: #ff0000; }
    .green{ background: #228B22; }
    .blue{ background: #0000ff; }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

</head>
<body>
    <div>
        <select>
            <option>Choose Color</option>
            <option value="red">Red</option>
            <option value="green">Green</option>
            <option value="blue">Blue</option>
        </select>
    </div>
    <div class="red box">You have selected <strong>red option</strong> so i am here</div>
    <div class="green box">You have selected <strong>green option</strong> so i am here</div>
    <div class="blue box">You have selected <strong>blue option</strong> so i am here</div>
</body>
</html>


问:
Inheriting From MembershipUser - Asp.net/C#
I have a customer class that inherits from MembershipUser.

When i load a Customer object i want to be able to set all the values in the base class easily.

I try to declare properties of Customer that hide readonly MembershipUser properties such as ProviderUserKey and then set those properties, however the base class properties are null when i need them to be set.

here is my class Customer.cs

```<code>using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Web;
using System.Web.Security;
using _FusioLibrary.Utilities;

namespace _CutMyCostsLibrary.BusinessObjects
{
   public class Customer : MembershipUser
   {
    #region Properties

    private Boolean active;
    public Boolean Active
    {
        get { return active; }
        set { active = value; }
    }

    private String address1;
    public String Address1
    {
        get { return address1; }
        set { address1 = value; }
    }

    private String address2;
    public String Address2
    {
        get { return address2; }
        set { address2 = value; }
    }

    private String companyName;
    public String CompanyName
    {
        get { return companyName; }
        set { companyName = value; }
    }

    private String county;
    public String County
    {
        get { return county; }
        set { county = value; }
    }

    private DateTime createDate;
    public DateTime CreateDate
    {
        get { return createDate; }
        set { createDate = value; }
    }

    private Int32 customerId;
    public Int32 CustomerId
    {
        get { return customerId; }
        set { customerId = value; }
    }

    private Boolean deleted;
    public Boolean Deleted
    {
        get { return deleted; }
        set { deleted = value; }
    }

    private String firstName;
    public String FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }

    private String lastName;
    public String LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }

    private String mobile;
    public String Mobile
    {
        get { return mobile; }
        set { mobile = value; }
    }

    private DateTime modifyDate;
    public DateTime ModifyDate
    {
        get { return modifyDate; }
        set { modifyDate = value; }
    }

    private String phone;
    public String Phone
    {
        get { return phone; }
        set { phone = value; }
    }

    private DateTime reminderEmailSentDate;
    public DateTime ReminderEmailSentDate
    {
        get { return reminderEmailSentDate; }
        set { reminderEmailSentDate = value; }
    }

    private String town;
    public String Town
    {
        get { return town; }
        set { town = value; }
    }

    private String userIdAspNet;
    public String UserIdAspNet
    {
        get { return userIdAspNet; }
        set { userIdAspNet = value; }
    }

    #endregion

    #region MembershipUser Properties Hiding

    read only properties need to be writeable

    private DateTime creationDate;
    public DateTime CreationDate
    {
        get { return creationDate; }
        set { creationDate = value; }
    }

    private bool isLockedOut;
    public bool IsLockedOut
    {
        get { return isLockedOut; }
        set { isLockedOut = value; }
    }

    private bool isOnline;
    public bool IsOnline
    {
        get { return isOnline; }
        set { isOnline = value; }
    }

    private DateTime lastLockoutDate;
    public DateTime LastLockoutDate
    {
        get { return lastLockoutDate; }
        set { lastLockoutDate = value; }
    }

    private DateTime lastPasswordChangedDate;
    public DateTime LastPasswordChangedDate
    {
        get { return lastPasswordChangedDate; }
        set { lastPasswordChangedDate = value; }
    }

    private string passwordQuestion;
    public string PasswordQuestion
    {
        get { return passwordQuestion; }
        set { passwordQuestion = value; }
    }
    private string providerName;
    public string ProviderName
    {
        get { return providerName; }
        set { providerName = value; }
    }

    private object providerUserKey;
    public object ProviderUserKey
    {
        get { return providerUserKey; }
        set { providerUserKey = value; }
    }

    private string userName;
    public string UserName
    {
        get { return userName; }
        set { userName = value; }
    }

    #endregion

    #region Load

    public static Customer Load(IDataReader iDataReader)
    {
        Customer oCustomer = new Customer();

        //populate the customer properties
        oCustomer.Active = DataReaderUtility.GetBool(iDataReader["Active"]);
        oCustomer.Address1 = DataReaderUtility.GetString(iDataReader["Address1"]);
        oCustomer.Address2 = DataReaderUtility.GetString(iDataReader["Address2"]);
        oCustomer.CompanyName = DataReaderUtility.GetString(iDataReader["CompanyName"]);
        oCustomer.County = DataReaderUtility.GetString(iDataReader["County"]);
        oCustomer.CreateDate = DataReaderUtility.GetDateTime(iDataReader["CreateDate"]);
        oCustomer.CustomerId = DataReaderUtility.GetInt(iDataReader["CustomerId"]);
        oCustomer.Deleted = DataReaderUtility.GetBool(iDataReader["Deleted"]);
        oCustomer.FirstName = DataReaderUtility.GetString(iDataReader["FirstName"]);
        oCustomer.LastName = DataReaderUtility.GetString(iDataReader["LastName"]);
        oCustomer.Mobile = DataReaderUtility.GetString(iDataReader["Mobile"]);
        oCustomer.ModifyDate = DataReaderUtility.GetDateTime(iDataReader["ModifyDate"]);
        oCustomer.Phone = DataReaderUtility.GetString(iDataReader["Phone"]);
        oCustomer.ReminderEmailSentDate = DataReaderUtility.GetDateTime(iDataReader["ReminderEmailSentDate"]);
        oCustomer.Town = DataReaderUtility.GetString(iDataReader["Town"]);
        oCustomer.UserIdAspNet = DataReaderUtility.GetString(iDataReader["UserIdAspNet"]);

        //populate the MembershipUser properties
        if(!string.IsNullOrEmpty(oCustomer.UserIdAspNet))
        {
           MembershipUser oMembershipUser  = Membership.GetUser(Guid.Parse(oCustomer.UserIdAspNet));

           oCustomer.Comment = oMembershipUser.Comment;
           oCustomer.CreationDate = oMembershipUser.CreationDate;
           oCustomer.Email = oMembershipUser.Email;
           oCustomer.IsApproved = oMembershipUser.IsApproved;
           oCustomer.IsLockedOut = oMembershipUser.IsLockedOut;
           oCustomer.IsOnline = oMembershipUser.IsOnline;
           oCustomer.LastActivityDate = oMembershipUser.LastActivityDate;
           oCustomer.LastLockoutDate = oMembershipUser.LastLockoutDate;
           oCustomer.LastLoginDate = oMembershipUser.LastLoginDate;
           oCustomer.LastPasswordChangedDate = oMembershipUser.LastPasswordChangedDate;
           oCustomer.PasswordQuestion = oMembershipUser.PasswordQuestion;
           oCustomer.ProviderName = oMembershipUser.ProviderName;
           oCustomer.ProviderUserKey = oMembershipUser.ProviderUserKey;
           oCustomer.UserName = oMembershipUser.UserName;

        }

        return oCustomer;

    }

    #endregion
 }
}
</code>```

Now when i try to execute the following code i get an error because the base class ProviderUserKey is null.

```<code>                    Customer oCustomer = CustomerManager.GetCustomer(UrlUtility.GetStringValue("UserId"));

                    //first we need to update the username
                    CustomerManager.UpdateCustomerUserName(oCustomer.UserIdAspNet, this.txtEmail.Text);

                    //Insert the modified data into the object

                    oCustomer.Active = this.cbActive.Checked;
                    oCustomer.Address1 = this.txtAddress1.Text;
                    oCustomer.Address2 = this.txtAddress2.Text;
                    oCustomer.CompanyName = this.txtCompanyName.Text;
                    oCustomer.County = this.txtCounty.Text;
                    oCustomer.FirstName = this.txtFirstName.Text;
                    oCustomer.LastName = this.txtLastName.Text;
                    oCustomer.Mobile = this.txtMobile.Text;
                    oCustomer.ModifyDate = DateTime.Now;
                    oCustomer.Phone = this.txtPhone.Text;
                    oCustomer.Town = this.txtTown.Text;
                    oCustomer.Email = this.txtEmail.Text;

                    //Update The Customer table
                    CustomerManager.UpdateCustomer(oCustomer);

                    //update the membership tables
                    Membership.UpdateUser(oCustomer);
</code>```

it errors on the last line Membership.UpdateUser(oCustomer) because ProviderUserKey in the base class is null.

Any Ideas how to populate the base class, bearing in mind ProviderUserKey is readonly?

Code samples (my code modified) would be really helpful and appreciated.

答:
You can't. Readonly means you can't set it, you can only read its value.

The only way to get a properly populated MembershipUser that you can update is through Membership.GetUser, which is going to return an instance of the default MembershipUser class, not an instance of your custom class. To do what you're trying to do, you would need to create a custom MembershipProvider that returns a Customer instead of a MemberhipUser, but that's probably more trouble than it's worth. What I've found works much better is to make Customer "wrap" MembershipUser instead of extending it. I've done it both ways (creating a custom MembershipProvider and creating a wrapper around MembershipUser), and using a wrapper is definitely the easier approach:

```<code>public class Customer : MembershipUser
{
    #region Properties

    private MembershipUser _user;

    ....

    #region Load

    public static Customer Load(IDataReader iDataReader)
    {
        Customer oCustomer = new Customer();
        ...

        if(!string.IsNullOrEmpty(oCustomer.UserIdAspNet))
        {
            oCustomer._user = Membership.GetUser(Guid.Parse(oCustomer.UserIdAspNet));
        }

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

Then instead of hiding the readonly properties, actually do something with them. Changing Customer.IsLockedOut from true to false means something needs to happen, so in your Customer.IsLockedOut property, instead of just storing a value that doesn't mean anything, call MembershipUser.UnlockUser():

```<code>public bool IsLockedOut
{
    get
    {
        return _user.IsLockedOut;
    }
    set
    {
        if(value != _user.IsLockedOut)
        {
            if(value)
            {
                // There's no way to programatically lock out a user, so either throw an InvalidOperationException or ignore it
            }
            else
            {
                _user.UnlockUser();
            }
        }
    }
}
</code>```

If you don't want that to run when you set the property, then you would need to track whether the value changed, and call UnlockUser() from your CustomerManager.UpdateCustomer method.

Body:
I have a customer class that inherits from MembershipUser.

When i load a Customer object i want to be able to set all the values in the base class easily.

I try to declare properties of Customer that hide readonly MembershipUser properties such as ProviderUserKey and then set those properties, however the base class properties are null when i need them to be set.

here is my class Customer.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Web;
using System.Web.Security;
using _FusioLibrary.Utilities;

namespace _CutMyCostsLibrary.BusinessObjects
{
   public class Customer : MembershipUser
   {
    #region Properties

    private Boolean active;
    public Boolean Active
    {
        get { return active; }
        set { active = value; }
    }

    private String address1;
    public String Address1
    {
        get { return address1; }
        set { address1 = value; }
    }

    private String address2;
    public String Address2
    {
        get { return address2; }
        set { address2 = value; }
    }

    private String companyName;
    public String CompanyName
    {
        get { return companyName; }
        set { companyName = value; }
    }

    private String county;
    public String County
    {
        get { return county; }
        set { county = value; }
    }

    private DateTime createDate;
    public DateTime CreateDate
    {
        get { return createDate; }
        set { createDate = value; }
    }

    private Int32 customerId;
    public Int32 CustomerId
    {
        get { return customerId; }
        set { customerId = value; }
    }

    private Boolean deleted;
    public Boolean Deleted
    {
        get { return deleted; }
        set { deleted = value; }
    }

    private String firstName;
    public String FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }

    private String lastName;
    public String LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }

    private String mobile;
    public String Mobile
    {
        get { return mobile; }
        set { mobile = value; }
    }

    private DateTime modifyDate;
    public DateTime ModifyDate
    {
        get { return modifyDate; }
        set { modifyDate = value; }
    }

    private String phone;
    public String Phone
    {
        get { return phone; }
        set { phone = value; }
    }

    private DateTime reminderEmailSentDate;
    public DateTime ReminderEmailSentDate
    {
        get { return reminderEmailSentDate; }
        set { reminderEmailSentDate = value; }
    }

    private String town;
    public String Town
    {
        get { return town; }
        set { town = value; }
    }

    private String userIdAspNet;
    public String UserIdAspNet
    {
        get { return userIdAspNet; }
        set { userIdAspNet = value; }
    }

    #endregion

    #region MembershipUser Properties Hiding

    read only properties need to be writeable

    private DateTime creationDate;
    public DateTime CreationDate
    {
        get { return creationDate; }
        set { creationDate = value; }
    }

    private bool isLockedOut;
    public bool IsLockedOut
    {
        get { return isLockedOut; }
        set { isLockedOut = value; }
    }

    private bool isOnline;
    public bool IsOnline
    {
        get { return isOnline; }
        set { isOnline = value; }
    }

    private DateTime lastLockoutDate;
    public DateTime LastLockoutDate
    {
        get { return lastLockoutDate; }
        set { lastLockoutDate = value; }
    }

    private DateTime lastPasswordChangedDate;
    public DateTime LastPasswordChangedDate
    {
        get { return lastPasswordChangedDate; }
        set { lastPasswordChangedDate = value; }
    }

    private string passwordQuestion;
    public string PasswordQuestion
    {
        get { return passwordQuestion; }
        set { passwordQuestion = value; }
    }
    private string providerName;
    public string ProviderName
    {
        get { return providerName; }
        set { providerName = value; }
    }

    private object providerUserKey;
    public object ProviderUserKey
    {
        get { return providerUserKey; }
        set { providerUserKey = value; }
    }

    private string userName;
    public string UserName
    {
        get { return userName; }
        set { userName = value; }
    }

    #endregion

    #region Load

    public static Customer Load(IDataReader iDataReader)
    {
        Customer oCustomer = new Customer();

        //populate the customer properties
        oCustomer.Active = DataReaderUtility.GetBool(iDataReader["Active"]);
        oCustomer.Address1 = DataReaderUtility.GetString(iDataReader["Address1"]);
        oCustomer.Address2 = DataReaderUtility.GetString(iDataReader["Address2"]);
        oCustomer.CompanyName = DataReaderUtility.GetString(iDataReader["CompanyName"]);
        oCustomer.County = DataReaderUtility.GetString(iDataReader["County"]);
        oCustomer.CreateDate = DataReaderUtility.GetDateTime(iDataReader["CreateDate"]);
        oCustomer.CustomerId = DataReaderUtility.GetInt(iDataReader["CustomerId"]);
        oCustomer.Deleted = DataReaderUtility.GetBool(iDataReader["Deleted"]);
        oCustomer.FirstName = DataReaderUtility.GetString(iDataReader["FirstName"]);
        oCustomer.LastName = DataReaderUtility.GetString(iDataReader["LastName"]);
        oCustomer.Mobile = DataReaderUtility.GetString(iDataReader["Mobile"]);
        oCustomer.ModifyDate = DataReaderUtility.GetDateTime(iDataReader["ModifyDate"]);
        oCustomer.Phone = DataReaderUtility.GetString(iDataReader["Phone"]);
        oCustomer.ReminderEmailSentDate = DataReaderUtility.GetDateTime(iDataReader["ReminderEmailSentDate"]);
        oCustomer.Town = DataReaderUtility.GetString(iDataReader["Town"]);
        oCustomer.UserIdAspNet = DataReaderUtility.GetString(iDataReader["UserIdAspNet"]);

        //populate the MembershipUser properties
        if(!string.IsNullOrEmpty(oCustomer.UserIdAspNet))
        {
           MembershipUser oMembershipUser  = Membership.GetUser(Guid.Parse(oCustomer.UserIdAspNet));

           oCustomer.Comment = oMembershipUser.Comment;
           oCustomer.CreationDate = oMembershipUser.CreationDate;
           oCustomer.Email = oMembershipUser.Email;
           oCustomer.IsApproved = oMembershipUser.IsApproved;
           oCustomer.IsLockedOut = oMembershipUser.IsLockedOut;
           oCustomer.IsOnline = oMembershipUser.IsOnline;
           oCustomer.LastActivityDate = oMembershipUser.LastActivityDate;
           oCustomer.LastLockoutDate = oMembershipUser.LastLockoutDate;
           oCustomer.LastLoginDate = oMembershipUser.LastLoginDate;
           oCustomer.LastPasswordChangedDate = oMembershipUser.LastPasswordChangedDate;
           oCustomer.PasswordQuestion = oMembershipUser.PasswordQuestion;
           oCustomer.ProviderName = oMembershipUser.ProviderName;
           oCustomer.ProviderUserKey = oMembershipUser.ProviderUserKey;
           oCustomer.UserName = oMembershipUser.UserName;

        }

        return oCustomer;

    }

    #endregion
 }
}

Now when i try to execute the following code i get an error because the base class ProviderUserKey is null.

                    Customer oCustomer = CustomerManager.GetCustomer(UrlUtility.GetStringValue("UserId"));

                    //first we need to update the username
                    CustomerManager.UpdateCustomerUserName(oCustomer.UserIdAspNet, this.txtEmail.Text);

                    //Insert the modified data into the object

                    oCustomer.Active = this.cbActive.Checked;
                    oCustomer.Address1 = this.txtAddress1.Text;
                    oCustomer.Address2 = this.txtAddress2.Text;
                    oCustomer.CompanyName = this.txtCompanyName.Text;
                    oCustomer.County = this.txtCounty.Text;
                    oCustomer.FirstName = this.txtFirstName.Text;
                    oCustomer.LastName = this.txtLastName.Text;
                    oCustomer.Mobile = this.txtMobile.Text;
                    oCustomer.ModifyDate = DateTime.Now;
                    oCustomer.Phone = this.txtPhone.Text;
                    oCustomer.Town = this.txtTown.Text;
                    oCustomer.Email = this.txtEmail.Text;

                    //Update The Customer table
                    CustomerManager.UpdateCustomer(oCustomer);

                    //update the membership tables
                    Membership.UpdateUser(oCustomer);

it errors on the last line Membership.UpdateUser(oCustomer) because ProviderUserKey in the base class is null.

Any Ideas how to populate the base class, bearing in mind ProviderUserKey is readonly?

Code samples (my code modified) would be really helpful and appreciated.

Body:
You can't. Readonly means you can't set it, you can only read its value.

The only way to get a properly populated MembershipUser that you can update is through Membership.GetUser, which is going to return an instance of the default MembershipUser class, not an instance of your custom class. To do what you're trying to do, you would need to create a custom MembershipProvider that returns a Customer instead of a MemberhipUser, but that's probably more trouble than it's worth. What I've found works much better is to make Customer "wrap" MembershipUser instead of extending it. I've done it both ways (creating a custom MembershipProvider and creating a wrapper around MembershipUser), and using a wrapper is definitely the easier approach:

public class Customer : MembershipUser
{
    #region Properties

    private MembershipUser _user;

    ....

    #region Load

    public static Customer Load(IDataReader iDataReader)
    {
        Customer oCustomer = new Customer();
        ...

        if(!string.IsNullOrEmpty(oCustomer.UserIdAspNet))
        {
            oCustomer._user = Membership.GetUser(Guid.Parse(oCustomer.UserIdAspNet));
        }

        return oCustomer;
    }
}

Then instead of hiding the readonly properties, actually do something with them. Changing Customer.IsLockedOut from true to false means something needs to happen, so in your Customer.IsLockedOut property, instead of just storing a value that doesn't mean anything, call MembershipUser.UnlockUser():

public bool IsLockedOut
{
    get
    {
        return _user.IsLockedOut;
    }
    set
    {
        if(value != _user.IsLockedOut)
        {
            if(value)
            {
                // There's no way to programatically lock out a user, so either throw an InvalidOperationException or ignore it
            }
            else
            {
                _user.UnlockUser();
            }
        }
    }
}

If you don't want that to run when you set the property, then you would need to track whether the value changed, and call UnlockUser() from your CustomerManager.UpdateCustomer method.


问:
How to generate java entity by Graphql schema
I'm a newcomer for graphql java client development. Recently I meet a problem that how to generate a java entity through the graphql schema definition. Since in my side, the schema is always changing by another side, so I want a method to generate the java entity class automatically instead of reading the schema manually then change the code. If there are any practices on such a requirement? Thanks.</p>

答:
You could look into the following maven plugin. It would help you generate Java classes from your .graphqls files.

Assuming you have only one file defining your GraphQL model, named myGraphqls, I would use this plugin as follow:

<build>
    <plugins>
        <plugin>
            <groupId>io.github.kobylynskyi</groupId>
            <artifactId>graphql-codegen-maven-plugin</artifactId>
            <version>1.2.3</version>
            <executions>
                <execution>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <graphqlSchemaPaths>
                            <graphqlSchemaPath>${project.basedir}/src/main/resources/graphql/myGraphqls.graphqls</graphqlSchemaPath>
                        </graphqlSchemaPaths>
                        <outputDir>${project.build.directory}/generated-sources/graphql</outputDir>
                        <packageName>com.graphql.model</packageName>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
```

After running maven, you would be able to find in the generated-sources folder, a folder named graphql with the classes generated under the package com.graphql.model.

Body:
You could look into the following maven plugin. It would help you generate Java classes from your .graphqls files.

Assuming you have only one file defining your GraphQL model, named myGraphqls, I would use this plugin as follow:

<build>
    <plugins>
        <plugin>
            <groupId>io.github.kobylynskyi</groupId>
            <artifactId>graphql-codegen-maven-plugin</artifactId>
            <version>1.2.3</version>
            <executions>
                <execution>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <graphqlSchemaPaths>
                            <graphqlSchemaPath>${project.basedir}/src/main/resources/graphql/myGraphqls.graphqls</graphqlSchemaPath>
                        </graphqlSchemaPaths>
                        <outputDir>${project.build.directory}/generated-sources/graphql</outputDir>
                        <packageName>com.graphql.model</packageName>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

After running maven, you would be able to find in the generated-sources folder, a folder named graphql with the classes generated under the package com.graphql.model.


问:
How can I overlay Sentinal 2 data with shapefiles in R?
I need to extract Sentinal 2 data for NDVI for specific study sites. I used RGIS tools and followed the reference manual https://cran.r-project.org/web/packages/RGISTools/RGISTools.pdf . I was able to obtain and plot the time series for NDVI.

Now I have to do the same procedure for my study area. I have a shapefile for my area which is accessible here, https://gis.utah.gov/data/boundaries/zip-codes/. It looks like that the shapefile needs to be converted into raster or sf type object before using it. I used st_as_sf to convert shapefile to sf but I receive the following error in senSearch function,

Error in if (as.integer(json$feed$opensearch:totalResults) > 0) { :
  argument is of length zero

It is my first time working with such data, any help is appreciated.

答:
It looks like you try to search using the extent argument. This argument only accepts spatial objects projected as lonlat projections. You can use the region argument with any spatial obj (sp, sf, or raster).

Here you have an example with your region:

```<code>library(RGISTools)
library(rgdal)
shp<-readOGR("ZipCodes_shp/ZipCodes")
plot(shp)

senres<-senSearch(startDate = as.Date("2018210", "%Y%j"),
                  endDate = as.Date("2018215", "%Y%j"),
                  platform = "Sentinel-2",
                  region = shp,
                  product = "S2MSI1C",
                  username="user",
                  password="pass")
</code>```

Body:
It looks like you try to search using the extent argument. This argument only accepts spatial objects projected as lonlat projections. You can use the region argument with any spatial obj (sp, sf, or raster).

Here you have an example with your region:

library(RGISTools)
library(rgdal)
shp<-readOGR("ZipCodes_shp/ZipCodes")
plot(shp)

senres<-senSearch(startDate = as.Date("2018210", "%Y%j"),
                  endDate = as.Date("2018215", "%Y%j"),
                  platform = "Sentinel-2",
                  region = shp,
                  product = "S2MSI1C",
                  username="user",
                  password="pass")


问:
parallelising tf.data.Dataset.from_generator with TF2.1
They are already 2 posts about this topics, but they have not been updated for the recent TF2.1 release...

In brief, I've got a lot of tif images to read and parse with a specific pipeline.

import tensorflow as tf
import numpy as np

files = # a list of str
labels = # a list of int
n_unique_label = len(np.unique(labels))

gen = functools.partial(generator, file_list=files, label_list=labels, param1=x1, param2=x2)
dataset = tf.data.Dataset.from_generator(gen, output_types=(tf.float32, tf.int32))
dataset = dataset.map(lambda b, c: (b, tf.one_hot(c, depth=n_unique_label)))
```

<p>This processing works well. Nevertheless, I need to parallelize the file parsing part, trying the following solution:</p>

<pre class="lang-py prettyprint-override"><code>files = # a list of str
files = tensorflow.data.Dataset.from_tensor_slices(files)

def wrapper(file_path):
    parser = partial(tif_parser, param1=x1, param2=x2)
    return tf.py_function(parser, inp=[file_path], Tout=[tf.float32])

dataset = files.map(wrapper, num_parallel_calls=2)
</code>```

The difference is that I parse one file at a time here with the parser function. However, but it does not work:

  File "loader.py", line 643, in tif_parser
    image = numpy.array(Image.open(file_path)).astype(float)

  File "python3.7/site-packages/PIL/Image.py", line 2815, in open
    fp = io.BytesIO(fp.read())

AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'read'

     [[{{node EagerPyFunc}}]] [Op:IteratorGetNextSync]
```

<p>As far as I understand, the <code>tif_parser</code> function does not receive a string but an (unevaluated) tensor. At now, this function is fairly simple:</p>

<pre class="lang-py prettyprint-override"><code>def tif_parser(file_path, param1=1, param2=2):
    image = numpy.array(Image.open(file_path)).astype(float)
    image /= 255.0

    return image
</code>```

答:
Here is how I have proceeded

dataset = tf.data.Dataset.from_tensor_slices((files, labels))

def wrapper(file_path, label):
    import functools
    parser = functools.partial(tif_parser,  param1=x1, param2=x2)
    return tf.data.Dataset.from_generator(parser, (tf.float32, tf.int32), args=(file_path, label))

dataset = dataset.interleave(wrapper, cycle_length=tf.data.experimental.AUTOTUNE)

# The labels are converted to 1-hot vectors, could be integrated in tif_parser
dataset = dataset.map(lambda i, l: (i, tf.one_hot(l, depth=unique_label_count)))

dataset = dataset.shuffle(buffer_size=file_count, reshuffle_each_iteration=True)
dataset = dataset.batch(batch_size=batch_size, drop_remainder=False)
dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE)
```

Concretely, I generate a data set every time the parser is called. The parser is run cycle_length time at each call, meaning that cycle_length images are read at once. This is suited to my specific case, because I cannot load all the images in memory. I am unsure whether the prefetch is used correctly or not here.

Body:
They are already 2 posts about this topics, but they have not been updated for the recent TF2.1 release...

In brief, I've got a lot of tif images to read and parse with a specific pipeline.

import tensorflow as tf
import numpy as np

files = # a list of str
labels = # a list of int
n_unique_label = len(np.unique(labels))

gen = functools.partial(generator, file_list=files, label_list=labels, param1=x1, param2=x2)
dataset = tf.data.Dataset.from_generator(gen, output_types=(tf.float32, tf.int32))
dataset = dataset.map(lambda b, c: (b, tf.one_hot(c, depth=n_unique_label)))

This processing works well. Nevertheless, I need to parallelize the file parsing part, trying the following solution:

files = # a list of str
files = tensorflow.data.Dataset.from_tensor_slices(files)

def wrapper(file_path):
    parser = partial(tif_parser, param1=x1, param2=x2)
    return tf.py_function(parser, inp=[file_path], Tout=[tf.float32])

dataset = files.map(wrapper, num_parallel_calls=2)

The difference is that I parse one file at a time here with the parser function. However, but it does not work:

  File "loader.py", line 643, in tif_parser
    image = numpy.array(Image.open(file_path)).astype(float)

  File "python3.7/site-packages/PIL/Image.py", line 2815, in open
    fp = io.BytesIO(fp.read())

AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'read'

     [[{{node EagerPyFunc}}]] [Op:IteratorGetNextSync]

As far as I understand, the tif_parser function does not receive a string but an (unevaluated) tensor. At now, this function is fairly simple:

def tif_parser(file_path, param1=1, param2=2):
    image = numpy.array(Image.open(file_path)).astype(float)
    image /= 255.0

    return image

Body:
Here is how I have proceeded

dataset = tf.data.Dataset.from_tensor_slices((files, labels))

def wrapper(file_path, label):
    import functools
    parser = functools.partial(tif_parser,  param1=x1, param2=x2)
    return tf.data.Dataset.from_generator(parser, (tf.float32, tf.int32), args=(file_path, label))

dataset = dataset.interleave(wrapper, cycle_length=tf.data.experimental.AUTOTUNE)

# The labels are converted to 1-hot vectors, could be integrated in tif_parser
dataset = dataset.map(lambda i, l: (i, tf.one_hot(l, depth=unique_label_count)))

dataset = dataset.shuffle(buffer_size=file_count, reshuffle_each_iteration=True)
dataset = dataset.batch(batch_size=batch_size, drop_remainder=False)
dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE)

Concretely, I generate a data set every time the parser is called. The parser is run cycle_length time at each call, meaning that cycle_length images are read at once. This is suited to my specific case, because I cannot load all the images in memory. I am unsure whether the prefetch is used correctly or not here.


问:
Sequences in SAS Tables
I'm looking to add a sequence column to my sas dataset, but according to ids and transaction dates. To illustrate, below is the table I'm referring to:

```<code>ID   |   TXN_DT    |
01   |  01JAN2020  |
01   |  01JAN2020  |
01   |  02JAN2020  |
01   |  03JAN2020  |
02   |  01JAN2020  |
02   |  02JAN2020  |
02   |  02JAN2020  |
02   |  03JAN2020  |
02   |  03JAN2020  |
</code>```

and I want to add a sequence like so:

```<code>ID   |   TXN_DT    |   SEQ  |
01   |  01JAN2020  |    1   |
01   |  01JAN2020  |    1   |
01   |  02JAN2020  |    2   |
01   |  03JAN2020  |    3   |
02   |  01JAN2020  |    1   |
02   |  02JAN2020  |    2   |
02   |  02JAN2020  |    2   |
02   |  03JAN2020  |    3   |
02   |  03JAN2020  |    3   |
</code>```

I'm trying to run the following code, but it seems to jump a row up and not copying the previous' row's value, and instead skips to 2 rows above.

```<code>data want;
set have;
by id;
if first.id then seq=1;
else seq+1;
if txn_dt=lag(txn_dt) then seq = lag(seq);
keep id seq txn_dt;
run;
</code>```

any help? Thanks in advance!

Title: Sequences in SAS Tables

Body:
I'm looking to add a sequence column to my sas dataset, but according to ids and transaction dates. To illustrate, below is the table I'm referring to:

ID   |   TXN_DT    |
01   |  01JAN2020  |
01   |  01JAN2020  |
01   |  02JAN2020  |
01   |  03JAN2020  |
02   |  01JAN2020  |
02   |  02JAN2020  |
02   |  02JAN2020  |
02   |  03JAN2020  |
02   |  03JAN2020  |

and I want to add a sequence like so:

ID   |   TXN_DT    |   SEQ  |
01   |  01JAN2020  |    1   |
01   |  01JAN2020  |    1   |
01   |  02JAN2020  |    2   |
01   |  03JAN2020  |    3   |
02   |  01JAN2020  |    1   |
02   |  02JAN2020  |    2   |
02   |  02JAN2020  |    2   |
02   |  03JAN2020  |    3   |
02   |  03JAN2020  |    3   |

I'm trying to run the following code, but it seems to jump a row up and not copying the previous' row's value, and instead skips to 2 rows above.

data want;
set have;
by id;
if first.id then seq=1;
else seq+1;
if txn_dt=lag(txn_dt) then seq = lag(seq);
keep id seq txn_dt;
run;

any help? Thanks in advance!

Body:
Try to use retain and first.

data want(drop=txn_dt_group);
    set have;
    by id txn_dt;
    retain txn_dt_group seq;
    if first.id then do;
        txn_dt_group=txn_dt;
        seq=1;
    end;
    if txn_dt ne txn_dt_group then do;
        seq=seq+1;
        txn_dt_group=txn_dt;
    end;
run;

Output:

+-----------+----+-----+
|  txn_dt   | ID | seq |
+-----------+----+-----+
| 01JAN2020 |  1 |   1 |
| 01JAN2020 |  1 |   1 |
| 02JAN2020 |  1 |   2 |
| 03JAN2020 |  1 |   3 |
| 01JAN2020 |  2 |   1 |
| 02JAN2020 |  2 |   2 |
| 02JAN2020 |  2 |   2 |
| 03JAN2020 |  2 |   3 |
| 03JAN2020 |  2 |   3 |
+-----------+----+-----+


问:
Pass function as template argument to a class
I want to pass functions as template arguments but somehow I can't get it to work. I've written a lot of template classes in the past but only using "normal" types as arguments. I've already searched for that issue but nothing seems to fit here. So I'm stuck.

Here is what I want to achieve:
I have a couple of type specific library functions which I want to encapsulate. I know that there are other ways of doing it as well (e.g. inheritance) but since I also want to learn a little bit here, I want to get it done with the template approach.

What I want to achieve:

```<code>MyType<int> myIntObject(...);
...
int writeVal = 10;
myIntObject.Write(writeVal);
...
int readVal;
myIntObject.Read(&readVal);
</code>```

Maybe also using typedefs:

```<code>typedef MyType<int> MyIntType;
</code>```

What I did so far:

```<code>template<typename T>
struct SetFunction
{
  inline ret_code operator()(someArgs, T value) const {return E_Fail;}
}

template<typename T>
struct GetFunction
{
  inline ret_code operator()(someArgs, T& value) const {return E_Fail;}
}

//template specialization:
template<>
struct SetFunction<int>
{
  inline ret_code operator()(someArgs, T value) const
  {
    //some other code
    return libraryFunctionWriteInt(someArgs, value);
  }
}

template<>
struct GetFunction<int>
{
  inline ret_code operator()(someArgs, T& value) const
  {
    //some other code
    return libraryFunctionReadInt(someArgs, &value);
  }
}
//do the specialization for all other types as well

template<class T, typename T_get_function = GetFunction<T>(), typename T_set_function = SetFunction<T>()>
MyType
{
public:
  MyType(someArgs)
  {
    if(T_get_function(someArgs, &_value) == E_Fail)
    {
      throw someting;
    }
  }

  bool SetValue(T value)
  {
    _value = value;
    //maybe some other code
    return T_set_function(someArgs, _value) == E_Success;
  }

  bool GetValue(T &value)
  {
    //maybe some other code
    return T_get_function(someArgs, &_value) == E_Success;
  }

private:
  T _value;
}

//and then eventually using it (maybe using some typedefs as well)
MyType<int> myIntObject(someArgs);
...
int writeVal = 10;
myIntObject.SetValue(writeValue);
...
int readVal;
myIntObject.GetValue(&readValue);
</code>```

Now I get compile errors: expression list treated as compound expression in functional cast on those two lines where I call the T_set_function / T_get_function. I also tried passing the library functions directly as template arguments and don't set any default functions but I couldn't get it to work that way as well.

Almost all of the books, articles and examples I read so far are only dealing with passing "normal" types as template arguments but since stl makes use of passing functions as well I really want to know how to do this.

答:
I don't know if I catch your question, but from the headline I read you want to pass a function as template parameter. That is quite easy, even if you want with function parms or not and with or without return value.

Example:

```<code>template < auto func >
struct X
{
    template < typename ... PARMS >
    static auto call(PARMS&& ... parms)
    {
        return func(parms...);
    }
};

void func1()           { std::cout << "1" << std::endl; }
void func2(int value ) { std::cout << "2 with " << value << std::endl; }
int  func3()           { std::cout << "With retval" << std::endl; return 987; }

int main()
{
    X<func1>::call( );
    X<func2>::call( 123 );
    std::cout << "Get retval" << X<func3>::call() << std::endl;
}
</code>```

Body:
I want to pass functions as template arguments but somehow I can't get it to work. I've written a lot of template classes in the past but only using "normal" types as arguments. I've already searched for that issue but nothing seems to fit here. So I'm stuck.

Here is what I want to achieve:
I have a couple of type specific library functions which I want to encapsulate. I know that there are other ways of doing it as well (e.g. inheritance) but since I also want to learn a little bit here, I want to get it done with the template approach.

What I want to achieve:

MyType<int> myIntObject(...);
...
int writeVal = 10;
myIntObject.Write(writeVal);
...
int readVal;
myIntObject.Read(&readVal);

Maybe also using typedefs:

typedef MyType<int> MyIntType;

What I did so far:

template<typename T>
struct SetFunction
{
  inline ret_code operator()(someArgs, T value) const {return E_Fail;}
}

template<typename T>
struct GetFunction
{
  inline ret_code operator()(someArgs, T& value) const {return E_Fail;}
}

//template specialization:
template<>
struct SetFunction<int>
{
  inline ret_code operator()(someArgs, T value) const
  {
    //some other code
    return libraryFunctionWriteInt(someArgs, value);
  }
}

template<>
struct GetFunction<int>
{
  inline ret_code operator()(someArgs, T& value) const
  {
    //some other code
    return libraryFunctionReadInt(someArgs, &value);
  }
}
//do the specialization for all other types as well

template<class T, typename T_get_function = GetFunction<T>(), typename T_set_function = SetFunction<T>()>
MyType
{
public:
  MyType(someArgs)
  {
    if(T_get_function(someArgs, &_value) == E_Fail)
    {
      throw someting;
    }
  }

  bool SetValue(T value)
  {
    _value = value;
    //maybe some other code
    return T_set_function(someArgs, _value) == E_Success;
  }

  bool GetValue(T &value)
  {
    //maybe some other code
    return T_get_function(someArgs, &_value) == E_Success;
  }

private:
  T _value;
}

//and then eventually using it (maybe using some typedefs as well)
MyType<int> myIntObject(someArgs);
...
int writeVal = 10;
myIntObject.SetValue(writeValue);
...
int readVal;
myIntObject.GetValue(&readValue);

Now I get compile errors: expression list treated as compound expression in functional cast on those two lines where I call the T_set_function / T_get_function. I also tried passing the library functions directly as template arguments and don't set any default functions but I couldn't get it to work that way as well.

Almost all of the books, articles and examples I read so far are only dealing with passing "normal" types as template arguments but since stl makes use of passing functions as well I really want to know how to do this.

Body:
I don't know if I catch your question, but from the headline I read you want to pass a function as template parameter. That is quite easy, even if you want with function parms or not and with or without return value.

Example:

template < auto func >
struct X
{
    template < typename ... PARMS >
    static auto call(PARMS&& ... parms)
    {
        return func(parms...);
    }
};

void func1()           { std::cout << "1" << std::endl; }
void func2(int value ) { std::cout << "2 with " << value << std::endl; }
int  func3()           { std::cout << "With retval" << std::endl; return 987; }

int main()
{
    X<func1>::call( );
    X<func2>::call( 123 );
    std::cout << "Get retval" << X<func3>::call() << std::endl;
}


问:
Determining the Orientation of the screen rather than the orientation of the device
The [[UIDevice currentDevice] orientation] method returns a number of orientations beyond the portrait and landscape orientation.  I am well aware of checking to see if the orientation returned is "valid", unfortunately if the orientation returned is NOT "valid" when my app requires a specific orientation to determine which methods to run, I have no way of knowing which method is appropriate.

I have attempted a number of solutions to this, but for now the only thing I have been able to work out is to check to see if the orientation is LandscapeLeft or LandscapeRight and if it isn't I assume the screen is in portrait orientation.  Unfortunately this isn't true when the device is face up and the screen is in landscape orientation.

I attempted to use the parent view controller's orientation:

```<code>parentController.interfaceOrientation;
</code>```

Unfortunately it returned UIDeviceOrientationUnknown.  I search SO and Google for someone else who has faced this problem.  It seems silly to me that Apple would have anything but LandscapeLeft/Right and PortraitUp/Down for their orientations.

What I really need is the APPS orientation not the devices, since these are sometimes at odds.  Any advice?

答:
Have you tried using UIInterfaceOrientationPortrait/UIInterfaceOrientationLandscape?  I usually have pretty good results using these methods:

```<code>if(UIInterfaceOrientationIsPortrait(viewController.interfaceOrientation)) {
    //do portrait work
} else if(UIInterfaceOrientationIsLandscape(viewController.interfaceOrientation)){
    //do landscape work
}
</code>```

You might also try UIDeviceOrientationIsValidInterfaceOrientation.

These will only return the app's orientation, which may not be the same as the device's orientation.

If those don't work, you can also try:

```<code>[[UIApplication sharedApplication] statusBarOrientation]
</code>```

Body:
The [[UIDevice currentDevice] orientation] method returns a number of orientations beyond the portrait and landscape orientation.  I am well aware of checking to see if the orientation returned is "valid", unfortunately if the orientation returned is NOT "valid" when my app requires a specific orientation to determine which methods to run, I have no way of knowing which method is appropriate.

I have attempted a number of solutions to this, but for now the only thing I have been able to work out is to check to see if the orientation is LandscapeLeft or LandscapeRight and if it isn't I assume the screen is in portrait orientation.  Unfortunately this isn't true when the device is face up and the screen is in landscape orientation.

I attempted to use the parent view controller's orientation:

parentController.interfaceOrientation;

Unfortunately it returned UIDeviceOrientationUnknown.  I search SO and Google for someone else who has faced this problem.  It seems silly to me that Apple would have anything but LandscapeLeft/Right and PortraitUp/Down for their orientations.

What I really need is the APPS orientation not the devices, since these are sometimes at odds.  Any advice?

Body:
Have you tried using UIInterfaceOrientationPortrait/UIInterfaceOrientationLandscape?  I usually have pretty good results using these methods:

if(UIInterfaceOrientationIsPortrait(viewController.interfaceOrientation)) {
    //do portrait work
} else if(UIInterfaceOrientationIsLandscape(viewController.interfaceOrientation)){
    //do landscape work
}

You might also try UIDeviceOrientationIsValidInterfaceOrientation.

These will only return the app's orientation, which may not be the same as the device's orientation.

If those don't work, you can also try:

[[UIApplication sharedApplication] statusBarOrientation]


问:
React router with Gatsby
I currently have an application built with CRA which uses React Router. I'm now trying to have a part of my application be rendered via Gatsby so that non technical users can control the content of this part of the application via a CMS.

What I have currently works in the dev server, but dies when I try and build.

This is my gatsby-node

```<code>exports.onCreatePage = async ({ actions, page }) => {
  const { createPage } = actions;

  return new Promise((resolve, reject) => {
    if (page.path === "/") {
      createPage({
        ...page,
        matchPath: "/*"
      });
    }
    resolve();
  });
};
</code>```

I have a static page that is being rendered at pages/study/index.js. It's quite large, so assume it looks like this

```<code>export default function Home({ data }) {
  if (!data) return null;

  const { mdx } = data;
  const { frontmatter: cmsData } = mdx;

  return (
    <StaticRouter location="/study">
      <Provider>
        <HomeTemplateWithRouter cmsData={cmsData} data={data} />
      </Provider>
    </StaticRouter>
  );
}
</code>```

I also have an index.js which looks like this

```<code>import React from "react";
import { Provider } from "components/general/Provider";
import { BrowserRouter } from "react-router-dom";
import AppContainer from "containers/AppContainer";
import { StaticRouter } from "react-router";

const Application = () => {
  return (
    <BrowserRouter>
      <Provider>
        <AppContainer />
      </Provider>
    </BrowserRouter>
  );
};

export default Application;
</code>```

Everything works when I use the development server. However when I build I get this error

```<code>Building static HTML failed for path "/"

See our docs page for more info on this error: https://gatsby.dev/debug-html

   7 |
   8 |   if (isProduction) {
>  9 |     throw new Error(prefix);
     | ^
  10 |   } else {
  11 |     throw new Error(prefix + ": " + (message || ''));
  12 |   }

  WebpackError: Invariant failed

  - tiny-invariant.esm.js:9 invariant
    node_modules/tiny-invariant/dist/tiny-invariant.esm.js:9:1

  - history.js:250 createBrowserHistory
    node_modules/history/esm/history.js:250:115

  - BrowserRouter.js:29 new BrowserRouter
    node_modules/react-router-dom/es/BrowserRouter.js:29:176
</code>```

Why is this happening only when I build a production version of the website?

Why is this happening given that I've defined a client side route and the code here should only be rendered client side?

What is the way around this without changing my dependency on react-router?

Thanks!

答: I have the same problem. I search on the Internet and find only one solution is to avoid react-router-dom.

Title: React router with Gatsby

Body:
I currently have an application built with CRA which uses React Router. I'm now trying to have a part of my application be rendered via Gatsby so that non technical users can control the content of this part of the application via a CMS.

What I have currently works in the dev server, but dies when I try and build.

This is my gatsby-node

exports.onCreatePage = async ({ actions, page }) => {
  const { createPage } = actions;

  return new Promise((resolve, reject) => {
    if (page.path === "/") {
      createPage({
        ...page,
        matchPath: "/*"
      });
    }
    resolve();
  });
};

I have a static page that is being rendered at pages/study/index.js. It's quite large, so assume it looks like this

export default function Home({ data }) {
  if (!data) return null;

  const { mdx } = data;
  const { frontmatter: cmsData } = mdx;

  return (
    <StaticRouter location="/study">
      <Provider>
        <HomeTemplateWithRouter cmsData={cmsData} data={data} />
      </Provider>
    </StaticRouter>
  );
}

I also have an index.js which looks like this

import React from "react";
import { Provider } from "components/general/Provider";
import { BrowserRouter } from "react-router-dom";
import AppContainer from "containers/AppContainer";
import { StaticRouter } from "react-router";

const Application = () => {
  return (
    <BrowserRouter>
      <Provider>
        <AppContainer />
      </Provider>
    </BrowserRouter>
  );
};

export default Application;

Everything works when I use the development server. However when I build I get this error

Building static HTML failed for path "/"

See our docs page for more info on this error: https://gatsby.dev/debug-html

   7 |
   8 |   if (isProduction) {
>  9 |     throw new Error(prefix);
     | ^
  10 |   } else {
  11 |     throw new Error(prefix + ": " + (message || ''));
  12 |   }

  WebpackError: Invariant failed

  - tiny-invariant.esm.js:9 invariant
    node_modules/tiny-invariant/dist/tiny-invariant.esm.js:9:1

  - history.js:250 createBrowserHistory
    node_modules/history/esm/history.js:250:115

  - BrowserRouter.js:29 new BrowserRouter
    node_modules/react-router-dom/es/BrowserRouter.js:29:176

Why is this happening only when I build a production version of the website?

Why is this happening given that I've defined a client side route and the code here should only be rendered client side?

What is the way around this without changing my dependency on react-router?

Thanks!


问:
Pandas lambda function won't recognize NaN
I'm trying to evaluate a new column in a DF by values from two others, but if a value is missing I try to pass another expression.

```<code>df_merge["3"] = df_merge.apply(lambda row: row["1"] + row["2"]
    if pd.isnull(row["1"]) or pd.isnull(row["2"])
    else (row["1"] + row["2"])/2,
    axis=1)

                         loc              1               2               3
    0                   135200           0.391           0.224          0.3075
    1                   135210           0.400           0.220          0.3100
    95                  136150             NaN           0.505             NaN
    96                  136160             NaN           0.527             NaN
</code>```

This is what I got. So if 1 or 2 is null I want to use the first expression, else the last one.
However, the first expression never gets passed. If I try to test for example:

```<code>pd.isnull(df_merge.iloc[96,3])
</code>```

It evaluates to True, so why isn't the first expression passed in that instance??

I also tried:

```<code>df_merge["3"].fillna(value=df_merge["1"] + df_merge["2"],inplace=True)
</code>```

Which did exactly nothing.

Sincerely,
Fredrik

答:
The simpliest here is use mean per rows, because mean by default in pandas omit NaNs (if not both NaNs like row 2):

```<code>df_merge = pd.DataFrame({'1':[np.nan, np.nan, 1, 2],
                   '2':[5, np.nan, np.nan, 4]})

df_merge["3"] = df_merge[["1",'2']].mean(axis=1)
print (df_merge)
     1    2    3
0  NaN  5.0  5.0
1  NaN  NaN  NaN
2  1.0  NaN  1.0
3  2.0  4.0  3.0
</code>```

Body:
I'm trying to evaluate a new column in a DF by values from two others, but if a value is missing I try to pass another expression.

df_merge["3"] = df_merge.apply(lambda row: row["1"] + row["2"]
    if pd.isnull(row["1"]) or pd.isnull(row["2"])
    else (row["1"] + row["2"])/2,
    axis=1)

                         loc              1               2               3
    0                   135200           0.391           0.224          0.3075
    1                   135210           0.400           0.220          0.3100
    95                  136150             NaN           0.505             NaN
    96                  136160             NaN           0.527             NaN

This is what I got. So if 1 or 2 is null I want to use the first expression, else the last one.
However, the first expression never gets passed. If I try to test for example:

pd.isnull(df_merge.iloc[96,3])

It evaluates to True, so why isn't the first expression passed in that instance??

I also tried:

df_merge["3"].fillna(value=df_merge["1"] + df_merge["2"],inplace=True)

Which did exactly nothing.

Sincerely,
Fredrik

Body:
The simpliest here is use mean per rows, because mean by default in pandas omit NaNs (if not both NaNs like row 2):

df_merge = pd.DataFrame({'1':[np.nan, np.nan, 1, 2],
                   '2':[5, np.nan, np.nan, 4]})

df_merge["3"] = df_merge[["1",'2']].mean(axis=1)
print (df_merge)
     1    2    3
0  NaN  5.0  5.0
1  NaN  NaN  NaN
2  1.0  NaN  1.0
3  2.0  4.0  3.0


问:
Save model without training in Tensorflow 2.0 with Keras
I use Tensorflow 2.0 and the Keras sequential API to build a model. I would like to save an untrained model for baseline comparison. How do I do that? I tried to set epochs=0 and period=0 which did not work.

Here is my code:

```<code>network = NeuralNetwork() # sequential neural network
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath='./models/', save_weights_only=False, period=0)
network.fit(x_train, y_train, epochs=0, callbacks=[cp_callback])
</code>```

How can I save an untrained model?

答:
You simply have to call model.save after instanciation of your model :

```<code>network = NeuralNetwork() # sequential neural network
network.save("/your/path/.h5")
</code>```

ModelCheckpoint can only be called as a callback, so during the training.

Body:
I use Tensorflow 2.0 and the Keras sequential API to build a model. I would like to save an untrained model for baseline comparison. How do I do that? I tried to set epochs=0 and period=0 which did not work.

Here is my code:

network = NeuralNetwork() # sequential neural network
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath='./models/', save_weights_only=False, period=0)
network.fit(x_train, y_train, epochs=0, callbacks=[cp_callback])

How can I save an untrained model?

Body:
You simply have to call model.save after instanciation of your model :

network = NeuralNetwork() # sequential neural network
network.save("/your/path/.h5")

ModelCheckpoint can only be called as a callback, so during the training.


问:
webcrawler analyse of the found pages
i wrote a simle webcrawler. i fetched all the websites and but them on my hdd.
now i want to analyse them, so i could write a simple interface like www.google.de and search for information in my fetched pages.

the problem is how to find out the important informations in a "fast" way. so the calculation is important. it could be realtime or after the fetch. my idea is to write a dictonary with a list of english words and count the entrys... or what to do ? i need lecture how to extract information and compress them. but i dont know where to look.

the crawler is based on c++ with mysql where the links stored.

i hope my question is clearly. :D

btw sry for my bad english but there istn a board like this in german :P

答:
The science of Information Retrieval (IR) is a complicated one.

Have you looked at any of the standard texts? Like:

Introduction to Information Retrieval by Christopher D. Manning, Prabhakar Raghavan and Hinrich Schütze (Jul 7, 2008) - http://www.amazon.com/Introduction-Information-Retrieval-Christopher-Manning/dp/0521865719/ref=sr_1_1?s=books&ie=UTF8&qid=1305573574&sr=1-1

Information Retrieval: Implementing and Evaluating Search Engines by Stefan Büttcher, Charles L. A. Clarke and Gordon V. Cormack (Jul 23, 2010) - http://www.amazon.com/Information-Retrieval-Implementing-Evaluating-Engines/dp/0262026511/ref=sr_1_3?s=books&ie=UTF8&qid=1305573574&sr=1-3

Search for 'information retrieval' on Amazon for more.

You might also take a look at my answer to Design Question for Notification System which outlines a general architecture for spidering websites for search.

Title: webcrawler analyse of the found pages


问:
warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
I'm trying to compile the below code using GCC compiler

```<code>class Class
{
public:

uInt16    temp;
const uInt32 function() const;

}

inline const uInt32 class::function() const
{
   return temp;
}
</code>```

And I'm getting the following compiler warning

warning: type qualifiers ignored on function return type [-Wignored-qualifiers]

Any ideas how I can fix this warning?

答:
Use simply:

```<code>uInt32 function() const;
</code>```

Returning const primitive type is useless, as you cannot do c.function()++ even without const.

Returning const Object was used to mimic primitives and forbid code similar to above,
but now (since C++11), we can forbid that cleanly, if required:

```<code>struct S
{
    S& operator ++() &;
    S& operator ++() && = delete;
};

S f(); // Sufficient, no need of const S f() which forbids move
</code>```

Body:
I'm trying to compile the below code using GCC compiler

class Class
{
public:

uInt16    temp;
const uInt32 function() const;

}

inline const uInt32 class::function() const
{
   return temp;
}

And I'm getting the following compiler warning

warning: type qualifiers ignored on function return type [-Wignored-qualifiers]

Any ideas how I can fix this warning?

Body:
Use simply:

uInt32 function() const;

Returning const primitive type is useless, as you cannot do c.function()++ even without const.

Returning const Object was used to mimic primitives and forbid code similar to above,
but now (since C++11), we can forbid that cleanly, if required:

struct S
{
    S& operator ++() &;
    S& operator ++() && = delete;
};

S f(); // Sufficient, no need of const S f() which forbids move


问:
How to manage containerized applications settings?
I have a bunch of containerized java applications on OpenShift server. Each has an applications.properties file where described the url's to databases and http servers.

So if I want to change one of that urls, I have to change 20+ application.properties files and redeploy 20+ applications.

How to sipmlify app properties management?

答:
I suggest to integrate applications with config server, e.g. it can be zookeeper. In case of spring cloud applications see spring-cloud-zookeeper-config, so it provide abilities to configure application settings individually or with common settings.
In addition, it provide multitenancy capabilities via different namespaces:</p>

```<code>spring:
  cloud:
    zookeeper:
      config:
        enabled: true
        root: config/${spring.application.namespace}
</code>```

Body:
I suggest to integrate applications with config server, e.g. it can be zookeeper. In case of spring cloud applications see spring-cloud-zookeeper-config, so it provide abilities to configure application settings individually or with common settings.
In addition, it provide multitenancy capabilities via different namespaces:

spring:
  cloud:
    zookeeper:
      config:
        enabled: true
        root: config/${spring.application.namespace}


问:
Flask Jinja2 template syntax conflicts with AngularJS (jinja2.exceptions.UndefinedError:)

How to access a $scope.list in html from angularjs?

jinja2.exceptions.UndefinedError: 'car' is undefined

main.js

```<code>(function ()
{
    'use strict';

    angular.module('WordcountApp', [])

    .controller('WordcountController', ['$scope',
                                        function($scope)
                                        {
                                            $scope.some = 'jjj'

                                            console.log( "in WordcountController " , $scope.some)

                                            $scope.cars = [
                                                            {make: 'Mazda', model: 'Miata', year: 2001},
                                                            {make: 'Toyota', model: 'Prius', year: 2013},
                                                            {make: 'Tesla', model: 'S', year: 2015},
                                                            {make: 'BMW', model: '325i', year: 2012}
                                                          ]
                                        }
                                       ]
                );
}()
);
</code>```

index.html

```<code><!DOCTYPE html>
<html ng-app = "WordcountApp" >

    <head>
        <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"> </script>
        <script src = "static/main.js" > </script>
    </head>

    <body ng-controller = "WordcountController">
        <ul ng-repeat = "car in cars" >
            <p> {{ car.make }} </p>
        </ul>
    </body>
</html>
</code>```

app.py

```<code>from flask import Flask
from flask import render_template
from flask import request

app = Flask( __name__ )
displayText = 'Default text from Python'

@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template('index.html')

@app.route("/writeOutput", methods=['POST'])
def writeOutput():
    global displayText

    print("request.get_json():- ", request.get_json())

    displayText = request.get_json()['myOutput']['myText']

    print ("from POST " , displayText)
    return displayText

@app.route("/displayPreviousText", methods=['GET'])
def displayPreviousText():
    global displayText
    return displayText

if __name__ == "__main__":
    app.run()
</code>```

I run this application as python app.py

Error: jinja2.exceptions.UndefinedError: 'car' is undefined

What is the way to access the list in html from angular?

答:
You error Error: jinja2.exceptions.UndefinedError: 'car' is undefined is not related to JavaScript. The problem seems to be as follows -  Jinja2 template renderer also relies on double curly braces same as AngularJS {{ your expression here }}.

There are several solutions that could be used to solve this

You may change the interpolate notation for Angular i.e.

```<code>angular.module('WordcountApp', [])
   .config(['$interpolateProvider', function($interpolateProvider) {
      $interpolateProvider.startSymbol('[[');
      $interpolateProvider.endSymbol(']]');
   }]);
</code>```

So your javascript/html code should look as follows

(function ()
{
  'use strict';

  angular.module('WordcountApp', [])

  // Setting up new interpolation delimiter which does not conflict with Jinja2
  .config(['$interpolateProvider', function($interpolateProvider) {
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');
  }])

  .controller('WordcountController', ['$scope',  function($scope) {
        $scope.some = 'jjj'

        console.log( "in WordcountController " , $scope.some)

        $scope.cars = [
            {make: 'Mazda', model: 'Miata', year: 2001},
            {make: 'Toyota', model: 'Prius', year: 2013},
            {make: 'Tesla', model: 'S', year: 2015},
            {make: 'BMW', model: '325i', year: 2012}
        ]
  }])

}()
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app = "WordcountApp" >

    <head>
        <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"> </script>
        <script src = "static/main.js" > </script>
    </head>

    <body ng-controller = "WordcountController">
        <ul ng-repeat = "car in cars" >
            <!-- Utilizing new interpolation delimiter -->
            <p> [[ car.make ]] </p>
        </ul>
    </body>
</html>

 </code>```

Also, I believe that a more simple way should work like

```<code><ul ng-repeat = "car in cars" >
    <p> {{ '{{ car.make }}' }} </p>
</ul>
</code>```

which will use Jinja2 templater first and the output for the raw HTML would be correct AngularJS syntax. But I'm not 100% sure about this way and cannot check it right now.

Also while researching your problem I've found one more solution which could be used for solving your problem. Flask-Triangle provides a filter angular to tell Jinja if the evaluation of an expression must be rendered as an Angular expression. The undefined variables are rendered as-is in the HTML output.

In this case your html part code should look as follows

```<code><body ng-controller = "WordcountController">
    <ul ng-repeat = "car in cars" >
        <p> {{car.make|angular}} </p>
    </ul>
</body>
</code>```

You can read more about this solution

Flash Triangle In-depth Tutorial -- AngularJS Templating in Jinja

Body:
How to access a $scope.list in html from angularjs?

jinja2.exceptions.UndefinedError: 'car' is undefined

main.js

(function ()
{
    'use strict';

    angular.module('WordcountApp', [])

    .controller('WordcountController', ['$scope',
                                        function($scope)
                                        {
                                            $scope.some = 'jjj'

                                            console.log( "in WordcountController " , $scope.some)

                                            $scope.cars = [
                                                            {make: 'Mazda', model: 'Miata', year: 2001},
                                                            {make: 'Toyota', model: 'Prius', year: 2013},
                                                            {make: 'Tesla', model: 'S', year: 2015},
                                                            {make: 'BMW', model: '325i', year: 2012}
                                                          ]
                                        }
                                       ]
                );
}()
);

index.html

<!DOCTYPE html>

 {{ car.make }}

app.py

from flask import Flask
from flask import render_template
from flask import request

app = Flask( __name__ )
displayText = 'Default text from Python'

@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template('index.html')

@app.route("/writeOutput", methods=['POST'])
def writeOutput():
    global displayText

    print("request.get_json():- ", request.get_json())

    displayText = request.get_json()['myOutput']['myText']

    print ("from POST " , displayText)
    return displayText

@app.route("/displayPreviousText", methods=['GET'])
def displayPreviousText():
    global displayText
    return displayText

if __name__ == "__main__":
    app.run()

I run this application as python app.py

Error: jinja2.exceptions.UndefinedError: 'car' is undefined

What is the way to access the list in html from angular?

Body:
You error Error: jinja2.exceptions.UndefinedError: 'car' is undefined is not related to JavaScript. The problem seems to be as follows -  Jinja2 template renderer also relies on double curly braces same as AngularJS {{ your expression here }}.

There are several solutions that could be used to solve this

You may change the interpolate notation for Angular i.e.

angular.module('WordcountApp', [])
   .config(['$interpolateProvider', function($interpolateProvider) {
      $interpolateProvider.startSymbol('[[');
      $interpolateProvider.endSymbol(']]');
   }]);

So your javascript/html code should look as follows

(function ()
{
  'use strict';

  angular.module('WordcountApp', [])

  // Setting up new interpolation delimiter which does not conflict with Jinja2
  .config(['$interpolateProvider', function($interpolateProvider) {
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');
  }])

  .controller('WordcountController', ['$scope',  function($scope) {
        $scope.some = 'jjj'

        console.log( "in WordcountController " , $scope.some)

        $scope.cars = [
            {make: 'Mazda', model: 'Miata', year: 2001},
            {make: 'Toyota', model: 'Prius', year: 2013},
            {make: 'Tesla', model: 'S', year: 2015},
            {make: 'BMW', model: '325i', year: 2012}
        ]
  }])

}()
);

<!DOCTYPE html>
<html ng-app = "WordcountApp" >

    <head>
        <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"> </script>
        <script src = "static/main.js" > </script>
    </head>

    <body ng-controller = "WordcountController">
        <ul ng-repeat = "car in cars" >
            <!-- Utilizing new interpolation delimiter -->
            <p> [[ car.make ]] </p>
        </ul>
    </body>
</html>

Also, I believe that a more simple way should work like

<ul ng-repeat = "car in cars" >
    <p> {{ '{{ car.make }}' }} </p>
</ul>

which will use Jinja2 templater first and the output for the raw HTML would be correct AngularJS syntax. But I'm not 100% sure about this way and cannot check it right now.

Also while researching your problem I've found one more solution which could be used for solving your problem. Flask-Triangle provides a filter angular to tell Jinja if the evaluation of an expression must be rendered as an Angular expression. The undefined variables are rendered as-is in the HTML output.

In this case your html part code should look as follows

<body ng-controller = "WordcountController">
    <ul ng-repeat = "car in cars" >
        <p> {{car.make|angular}} </p>
    </ul>
</body>

You can read more about this solution

Flash Triangle In-depth Tutorial -- AngularJS Templating in Jinja


问:
Elasticsearch - How to index a calculated field?
Is it possible to put a calculation with a "Today" comparison in the index, that I can search and filter the calculated field?

For example:

Name: John

Surname: Smith

Full_Name: Name + Surname = John Smith

Birthday: 22.01.1992

Age: Today - Birthday = 28

or something like that:

company_name: John Smiths Company

certification_date: 05.01.2015

new_certification_needed: (Today - certification_date) > 495 ? Yes : No

There are  multiple indices and they are user specific. A user can create their own raws and calculation and the only problem is with a "Today" calculation like "Age" or "new_certification_needed". Something like the "Full_Name" is always up to date when saved.

答: The closest thing that comes to mind is using a scripted field in your query, see here. There are some complications to getting the current date in scripts, so you'd have to pass the current time as a parameter with the search query.</p>