问:
Command line argument in Histogram
I am writing some code which makes a histogram out of imported excel files from a directory and bins the data according to some parameter and exports new excel files accordingly, binned into their respective bins, for ex. if there is a number 5.16 then the bin count for bin (5,10] will go up by one and so on. However, I wanted to write something in which I can input a specific value that would change the bins accordingly, like if I wanted bins of 3, I would choose n=3 and the code would now bin accordingly, such that it makes bin (0,3], (3,6], etc. and the same rules as previously would apply. The original code is:

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import openpyxl
from pandas import ExcelWriter
import os

datadir = '/Users/user/Desktop/Newfolder/'

for file in os.listdir(datadir):
    if file.endswith('.xlsx'):
        data = pd.read_excel(os.path.join(datadir, file))
        counts, bins, patches = plt.hist(data.values, bins=range(0,
        int(max(data.values)+5), 5))
        df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
        plt.title('Data')
        plt.xlabel('Neuron')
        plt.ylabel('# of Spikes')
        plt.show()

        outfile = os.path.join(datadir, file.replace('.xlsx', '_bins.xlsx'))
        writer = pd.ExcelWriter(outfile)
        df.to_excel(writer)
        writer.save()
</code>```

My thought was to use argparse as a command line argument which I could us to input the change in the bins, so I wrote:

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import openpyxl
from pandas import ExcelWriter
import os
import argparse

datadir = '/Users/user/Desktop/Newfolder/'

parser = argparse.ArgumentParser(description = 'Calculating the bin width')
parser.add_argument('n', type=int, help='Changing of the width')
args = parser.parse_args()

def vary(n):
    wid = n
     return wid

if __name__ == '__main__':
    print(vary(args.n))

for file in os.listdir(datadir):
    if file.endswith('.xlsx'):
       data = pd.read_excel(os.path.join(datadir, file))
       counts, bins, patches = plt.hist(data.values, bins=range(0,
       int(max(data.values)+vary(n)), vary(n)))
       df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
       plt.title('Data')
       plt.xlabel('Neuron')
       plt.ylabel('# of Spikes')
       plt.show()

       outfile = os.path.join(datadir, file.replace('.xlsx', '_bins.xlsx'))
       writer = pd.ExcelWriter(outfile)
       df.to_excel(writer)
       writer.save()
</code>```

I apologize in advance if this looks idioitic, since I am pretty new to coding and still don't know too much about anything. Anyway, I get an error say that

```<code>Traceback (most recent call last):
File "\Users\user\Desktop\Bins.py", line 25, in <module>
        counts, bins, patches = plt.hist(data.values, bins=range(0, int(max(data.values)+vary(n)), vary(n)))
NameError: name 'n' is not defined
</code>```

Could I get some help with this, how would I go about implementing this command line argument (argparse) into the histogram so I can input the according bins everytime I need to change them. Any help would be greatly appreciated, thank you

答:
Without going too much into your code, command line arguments are easily processes using the sys module:

```<code>import sys
print sys.argv # first element is the script name, then follow the parameters as strings
</code>```

So that this script, if I name it sysArgs.pyand call it with some parameters in the console, prints

```<code>python sysArgs.py lala 5
['sysArgs.py', 'lala', '5']
</code>```

If you want to only pass one parameter n, then change it to

```<code>import sys
n = int(sys.argv[1])
# do stuff with n other than printing it
print n
</code>```

Title: Command line argument in Histogram

Body:
I am writing some code which makes a histogram out of imported excel files from a directory and bins the data according to some parameter and exports new excel files accordingly, binned into their respective bins, for ex. if there is a number 5.16 then the bin count for bin (5,10] will go up by one and so on. However, I wanted to write something in which I can input a specific value that would change the bins accordingly, like if I wanted bins of 3, I would choose n=3 and the code would now bin accordingly, such that it makes bin (0,3], (3,6], etc. and the same rules as previously would apply. The original code is:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import openpyxl
from pandas import ExcelWriter
import os

datadir = '/Users/user/Desktop/Newfolder/'

for file in os.listdir(datadir):
    if file.endswith('.xlsx'):
        data = pd.read_excel(os.path.join(datadir, file))
        counts, bins, patches = plt.hist(data.values, bins=range(0,
        int(max(data.values)+5), 5))
        df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
        plt.title('Data')
        plt.xlabel('Neuron')
        plt.ylabel('# of Spikes')
        plt.show()

        outfile = os.path.join(datadir, file.replace('.xlsx', '_bins.xlsx'))
        writer = pd.ExcelWriter(outfile)
        df.to_excel(writer)
        writer.save()

My thought was to use argparse as a command line argument which I could us to input the change in the bins, so I wrote:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import openpyxl
from pandas import ExcelWriter
import os
import argparse

datadir = '/Users/user/Desktop/Newfolder/'

parser = argparse.ArgumentParser(description = 'Calculating the bin width')
parser.add_argument('n', type=int, help='Changing of the width')
args = parser.parse_args()

def vary(n):
    wid = n
     return wid

if __name__ == '__main__':
    print(vary(args.n))

for file in os.listdir(datadir):
    if file.endswith('.xlsx'):
       data = pd.read_excel(os.path.join(datadir, file))
       counts, bins, patches = plt.hist(data.values, bins=range(0,
       int(max(data.values)+vary(n)), vary(n)))
       df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
       plt.title('Data')
       plt.xlabel('Neuron')
       plt.ylabel('# of Spikes')
       plt.show()

       outfile = os.path.join(datadir, file.replace('.xlsx', '_bins.xlsx'))
       writer = pd.ExcelWriter(outfile)
       df.to_excel(writer)
       writer.save()

I apologize in advance if this looks idioitic, since I am pretty new to coding and still don't know too much about anything. Anyway, I get an error say that

Traceback (most recent call last):
File "\Users\user\Desktop\Bins.py", line 25, in <module>
        counts, bins, patches = plt.hist(data.values, bins=range(0, int(max(data.values)+vary(n)), vary(n)))
NameError: name 'n' is not defined

Could I get some help with this, how would I go about implementing this command line argument (argparse) into the histogram so I can input the according bins everytime I need to change them. Any help would be greatly appreciated, thank you

Body:
Without going too much into your code, command line arguments are easily processes using the sys module:

import sys
print sys.argv # first element is the script name, then follow the parameters as strings

So that this script, if I name it sysArgs.pyand call it with some parameters in the console, prints

python sysArgs.py lala 5
['sysArgs.py', 'lala', '5']

If you want to only pass one parameter n, then change it to

import sys
n = int(sys.argv[1])
# do stuff with n other than printing it
print n


来源: stackexchange

问:
Is it possible to increase the max columns of an Oracle database to store huge arrays?
For reasons that are beyond my control I need to store huge arrays (10000+ entries) in database rows, and it has to be easy to access each index of the array individually, which means I'd rather avoid serialization/blobs, if at all possible.

So my first idea, and the actual question here, is can I increase max columns for Oracle in anyway?

Or is there an easy way to say store the array over a few rows and hide the implementation below the surface (I'm thinking stored procedure here).

Any other suggestions are also welcome!

答:
Not sure about increasing the max columns.
However, Why not split it across multiple tables which each table sharing the same unique ID.
This implementation will be more easier than storing it over multiple rows.</p>

OwnerDisplayName: Robert Gould

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Dheer


问:
How do I put extra number at the end of username if duplicate
Hard to explain, and let me show an example.

If username foo already exists in MySQL I want php script will allow it but to be foo1

Then if foo1 exists too, script will generate the username will be foo2

If foo2 existed then become foo3

How to make like that?

Like Col. Shrapnel said Natural increment which seems more sensible. just like "New Folder(3)" stuff in Windows

答:
```<code>  $getname   = $_POST['getname'];

  $i++;

  $q =  "SELECT username FROM User WHERE username LIKE '".$getname."%'";

  $r = mysql_query($q);

  if(mysql_num_rows($r) > 0){

    while($row = mysql_fetch_object($r)){
      if($row->username == $getname){
        $uname = $getname.$i;
      }else if($row->username == ($getname.$i)){
        $uname = $getname.$i+1;
      }
      $i++;
    }

  }
  else
  {
   $uname = "foo";
  }
</code>```

ContentLicense: CC BY-SA 3.0


问:
Mocking a helper function in django view test
I have a view function that initiates user login requests

it looks something like this:

```<code>def initiate_login(request):
    # get request parameters
    return check_user_and_send_otp(login_id)
</code>```

The request is then processed by another function

```<code>def check_user_and_send_otp(login_id):
    # check if user exits
    return send_otp_to_user(phone_number)
</code>```

And then another function

```<code>def send_otp_to_user(phone_number):
    # sends a message to user
    return response
</code>```

The problem is while testing my code, I don't want to send messages to a phone number while testing.

My login test function looks somewhat like this, is it possible to mock it without changing my code?

```<code>    def test_login_initiator(self):
    response = self.client.post(self.login_url, data=self.login_data, content_type="application/json", **self.headers)
    self.assertEqual(response.status_code, 200)
</code>```

All these functions that were called by others are located in seperate modules

答:
If you don't want to actually receive the message on a physical phone, you can use online sms receivers. Check out this blog.

Additionally, you can send messages through other free online services like Way2sms. You just have to google them up. To do this from within Python, you need to use web parsing using urllib2/requests and beautifulsoup, which is a totally new question.

Or you can skip this function by simply commenting out the message sender code or returning true from the function.

If you wanna live dangerously, think about making a config file which can help you to make switches that tell whether to execute something or not.

Body:
I have a view function that initiates user login requests

it looks something like this:

def initiate_login(request):
    # get request parameters
    return check_user_and_send_otp(login_id)

The request is then processed by another function

def check_user_and_send_otp(login_id):
    # check if user exits
    return send_otp_to_user(phone_number)

And then another function

def send_otp_to_user(phone_number):
    # sends a message to user
    return response

The problem is while testing my code, I don't want to send messages to a phone number while testing.

My login test function looks somewhat like this, is it possible to mock it without changing my code?

    def test_login_initiator(self):
    response = self.client.post(self.login_url, data=self.login_data, content_type="application/json", **self.headers)
    self.assertEqual(response.status_code, 200)

All these functions that were called by others are located in seperate modules


问:
Joining CSV fields
I need to convert

```<code>Name | Org
a    | 5
a    | 6
b    | 5
c    | 7
</code>```

into

```<code>Name | Org
a    | 5,6
b    |  5
c    |  7
</code>```

my first attempt was with this code

```<code>    while i < len(nameColumn):
    if nameColumn[i] not in resultC1:
        resultC1.append(nameColumn[i])
        while l < len(nameColumn):
            if nameColumn[l] == nameColumn[i]:
                tempdata += organizationColumn[l] + ','
            l += 1
        resultC2.append(tempdata[:-1])
        tempdata = ''
        k += 1
    i += 1
</code>```

which just ends up with the result

```<code>Name | Org
a    |
b    |
c    |
</code>```

Any help would be greatly appreciated. I havent had luck finding anything on this yet. I'm reading the data from a .CSV file into lists and working with that data and storing results into resultC1 and resultC2

答:
Assuming you're starting with the two arrays implied in your sample code, I'd go with something like this:</p>

```<code>from collections import defaultdict

nameColumn = ['a', 'a', 'b', 'c']
organizationColumn = ["5", "6", "5", "7"]

merged = defaultdict(list)
for name, org in zip(nameColumn, organizationColumn):
    merged[name].append(org)

for k, v in merged.items():
    print(f'{k} | {v}'))
</code>```

Title: Joining CSV fields

Body:
I need to convert

Name | Org
a    | 5
a    | 6
b    | 5
c    | 7

into

Name | Org
a    | 5,6
b    |  5
c    |  7

my first attempt was with this code

    while i < len(nameColumn):
    if nameColumn[i] not in resultC1:
        resultC1.append(nameColumn[i])
        while l < len(nameColumn):
            if nameColumn[l] == nameColumn[i]:
                tempdata += organizationColumn[l] + ','
            l += 1
        resultC2.append(tempdata[:-1])
        tempdata = ''
        k += 1
    i += 1

which just ends up with the result

Name | Org
a    |
b    |
c    |

Any help would be greatly appreciated. I havent had luck finding anything on this yet. I'm reading the data from a .CSV file into lists and working with that data and storing results into resultC1 and resultC2

Body:
Assuming you're starting with the two arrays implied in your sample code, I'd go with something like this:

from collections import defaultdict

nameColumn = ['a', 'a', 'b', 'c']
organizationColumn = ["5", "6", "5", "7"]

merged = defaultdict(list)
for name, org in zip(nameColumn, organizationColumn):
    merged[name].append(org)

for k, v in merged.items():
    print(f'{k} | {v}'))


问:
List item inside model always null on post - Asp.net MVC
I am trying to post model which contains List<> item looks like below:

```<code>public class AddSubscriptionPlanModel
{
    public AddSubscriptionPlanModel()
    {
        AllFeatures = new List<Feature>();
    }
    public int Id { get; set; }
    public int SubscriptionPlanId { get; set; }
    public int SubscriptionId { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }
    [Display(Name = "No Of Users")]
    public int? NoOfUsers { get; set; }
    [Display(Name = "Duration Type")]
    public DurationType DurationType { get; set; }
    public int Duration { get; set; }
    public decimal Amount { get; set; }
    public int SubscriptionPlanTrailId { get; set; }
    public int FeatureId { get; set; }
    public DateTime CreatedDateUtc { get; set; }
    public DateTime LastUpdatedUtc { get; set; }
    public int CreatedBy { get; set; }
    public int LastUpdatedBy { get; set; }
    public List<Feature> AllFeatures { get; set; }
}
</code>```

I am populating all required fields on get method and feeding List from database

```<code>public ActionResult Mapping(int id)
{
    var features = FeatureManager.GetAllFeatures();
    var model = new Ejyle.DevAccelerate.Web.App.Models.SubscriptionPlan.AddSubscriptionPlanModel();

    model.AllFeatures = features;
    model.Id = id;
    model.SubscriptionId = id;
    model.NoOfUsers = 20;
    model.SubscriptionPlanId = 1;
    model.SubscriptionPlanTrailId = 1;
    model.Amount = 1000;
    model.CreatedBy = 1;
    model.LastUpdatedBy = 1;
    model.FeatureId = 1;
    model.Duration = 20;

    return View(model);
}
</code>```

And my view code looks like below :

```<code>@using (Html.BeginForm("Mapping", "SubscriptionPlans", FormMethod.Post))
{
    @Html.HiddenFor(model => model.Id)
    @Html.HiddenFor(model => model.Amount)
    @Html.HiddenFor(model => model.Duration)
    @Html.HiddenFor(model => model.FeatureId)
    @Html.HiddenFor(model => model.CreatedBy)
    @Html.HiddenFor(model => model.LastUpdatedBy)
    @Html.HiddenFor(model => model.NoOfUsers)
    @Html.HiddenFor(model => model.SubscriptionId)
    @Html.HiddenFor(model => model.SubscriptionPlanId)
    @Html.HiddenFor(model => model.SubscriptionPlanTrailId)
    @Html.HiddenFor(model => model.AllFeatures)
    <table class="table table-striped">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.IsActive)
                </th>
            </tr>
        </thead>
        <tbody>
            @for (int i=0; i < Model.AllFeatures.Count; i++)
            {
                <tr>
                    @Html.HiddenFor(model => model.AllFeatures[i].Id)
                    @Html.HiddenFor(model => model.AllFeatures[i].Name)
                    @Html.HiddenFor(model => model.AllFeatures[i].IsActive)
                    <td>
                        @Html.TextBoxFor(model => model.AllFeatures[i].Id)
                    </td>
                    <td>
                        @Html.TextBoxFor(model => model.AllFeatures[i].Name)
                    </td>
                    <td>
                        @Html.EditorFor(model => model.AllFeatures[i].IsActive)
                    </td>
                </tr>
            }
        </tbody>
    </table>
    <input type="submit" class="btn btn-success" value="Submit" name="Submit"/>
}
</code>```

On View, the list items rendered properly and even I am able to edit those fields.

But On post, all properties have the value except AllFeatures list item property which always shows count = 0.

Edit 1: This is how my view looks like while rendering features

Edit 2:

Signature of the method posting to:

```<code>[HttpPost]
public ActionResult Mapping(AddSubscriptionPlanModel model)
{
}
</code>```

答:
I think your issue might be the nested property. You may want to review the posted form and see what it looks like.

Your markup looks correct assuming that the model binding would work for a nested property - which I am not sure it does. (Just to make sure I searched for and found this old Haack post that indicates you're doing it right: Haack Post)

As a workaround (and POC), you can try the following: Add a new parameter to your action for your features, post it like your doing now but not nested (so you can't use the Model For HTML helpers) and then in the controller, you can set it back to your main object's features property.

Body:
I am trying to post model which contains List<> item looks like below:

public class AddSubscriptionPlanModel
{
    public AddSubscriptionPlanModel()
    {
        AllFeatures = new List<Feature>();
    }
    public int Id { get; set; }
    public int SubscriptionPlanId { get; set; }
    public int SubscriptionId { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }
    [Display(Name = "No Of Users")]
    public int? NoOfUsers { get; set; }
    [Display(Name = "Duration Type")]
    public DurationType DurationType { get; set; }
    public int Duration { get; set; }
    public decimal Amount { get; set; }
    public int SubscriptionPlanTrailId { get; set; }
    public int FeatureId { get; set; }
    public DateTime CreatedDateUtc { get; set; }
    public DateTime LastUpdatedUtc { get; set; }
    public int CreatedBy { get; set; }
    public int LastUpdatedBy { get; set; }
    public List<Feature> AllFeatures { get; set; }
}

I am populating all required fields on get method and feeding List from database

public ActionResult Mapping(int id)
{
    var features = FeatureManager.GetAllFeatures();
    var model = new Ejyle.DevAccelerate.Web.App.Models.SubscriptionPlan.AddSubscriptionPlanModel();

    model.AllFeatures = features;
    model.Id = id;
    model.SubscriptionId = id;
    model.NoOfUsers = 20;
    model.SubscriptionPlanId = 1;
    model.SubscriptionPlanTrailId = 1;
    model.Amount = 1000;
    model.CreatedBy = 1;
    model.LastUpdatedBy = 1;
    model.FeatureId = 1;
    model.Duration = 20;

    return View(model);
}

And my view code looks like below :

@using (Html.BeginForm("Mapping", "SubscriptionPlans", FormMethod.Post))
{
    @Html.HiddenFor(model => model.Id)
    @Html.HiddenFor(model => model.Amount)
    @Html.HiddenFor(model => model.Duration)
    @Html.HiddenFor(model => model.FeatureId)
    @Html.HiddenFor(model => model.CreatedBy)
    @Html.HiddenFor(model => model.LastUpdatedBy)
    @Html.HiddenFor(model => model.NoOfUsers)
    @Html.HiddenFor(model => model.SubscriptionId)
    @Html.HiddenFor(model => model.SubscriptionPlanId)
    @Html.HiddenFor(model => model.SubscriptionPlanTrailId)
    @Html.HiddenFor(model => model.AllFeatures)

                    @Html.DisplayNameFor(model => model.Name)

                    @Html.DisplayNameFor(model => model.IsActive)

            @for (int i=0; i < Model.AllFeatures.Count; i++)
            {

                    @Html.HiddenFor(model => model.AllFeatures[i].Id)
                    @Html.HiddenFor(model => model.AllFeatures[i].Name)
                    @Html.HiddenFor(model => model.AllFeatures[i].IsActive)

                        @Html.TextBoxFor(model => model.AllFeatures[i].Id)

                        @Html.TextBoxFor(model => model.AllFeatures[i].Name)

                        @Html.EditorFor(model => model.AllFeatures[i].IsActive)

            }

    <input type="submit" class="btn btn-success" value="Submit" name="Submit"/>
}

On View, the list items rendered properly and even I am able to edit those fields.

But On post, all properties have the value except AllFeatures list item property which always shows count = 0.

Edit 1: This is how my view looks like while rendering features

Edit 2:

Signature of the method posting to:

[HttpPost]
public ActionResult Mapping(AddSubscriptionPlanModel model)
{
}


问:
Presenting ViewController from appDelegate
I need to show a ViewController from the appDelegate every time the app comes from the background in the applicationDidEnterBackground method.

The *securityCheck prompts the user for a passcode very much like the normal passcode in iOS. Once the passcode is validated I call dimissViewControllerAnimated inside the securityCheck and I am left with my blank UINavigationController, since the view was presented from the appDelegate I have no record of who presented the view, so I can't popToRootViewController.

My question is how can I properly dismiss the SecurityCheckViewController so that it shows the ViewController which the user was on before the app entered the background.

Here's my code:

This method is called inside AppDelegate.m

```<code>- (void)securityCheck {

   SecurityCheckViewController *securityCheck = [[SecurityCheckViewController alloc] init];
   UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:securityCheck];

   [securityCheck presentedByAppDelegate:YES];

   self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
   [self.window setRootViewController:navigationController];
   [self.window makeKeyAndVisible];
}
</code>```

Then inside the SecurityCheckViewController.m I have

```<code>- (void)unlockWasSuccessfulForPadLockScreenViewController:(ABPadLockScreenViewController *)padLockScreenViewController {

    [self.appDelegate securityCheckDone];
    [padLockScreenViewController dismissViewControllerAnimated:YES completion:nil];

     NSLog(@"Sucsessfull Unlock");I'm
}
</code>```

答:
You can call this from application:didFinishLaunchingWithOptions

NOTE: All the storyBoard "initialViewControllers" tick box on the property inspector is turned off

```<code>    UIStoryboard *storyboard =
        [UIStoryboard storyboardWithName:@"Registration" bundle:nil];

    RegisterViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"RegisterViewController"];

    //this is key else you get a black screen
    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];

    self.window.rootViewController = vc;
    [self.window makeKeyAndVisible];
</code>```

Body:
I need to show a ViewController from the appDelegate every time the app comes from the background in the applicationDidEnterBackground method.

The *securityCheck prompts the user for a passcode very much like the normal passcode in iOS. Once the passcode is validated I call dimissViewControllerAnimated inside the securityCheck and I am left with my blank UINavigationController, since the view was presented from the appDelegate I have no record of who presented the view, so I can't popToRootViewController.

My question is how can I properly dismiss the SecurityCheckViewController so that it shows the ViewController which the user was on before the app entered the background.

Here's my code:

This method is called inside AppDelegate.m

- (void)securityCheck {

   SecurityCheckViewController *securityCheck = [[SecurityCheckViewController alloc] init];
   UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:securityCheck];

   [securityCheck presentedByAppDelegate:YES];

   self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
   [self.window setRootViewController:navigationController];
   [self.window makeKeyAndVisible];
}

Then inside the SecurityCheckViewController.m I have

- (void)unlockWasSuccessfulForPadLockScreenViewController:(ABPadLockScreenViewController *)padLockScreenViewController {

    [self.appDelegate securityCheckDone];
    [padLockScreenViewController dismissViewControllerAnimated:YES completion:nil];

     NSLog(@"Sucsessfull Unlock");I'm
}

Body:
You can call this from application:didFinishLaunchingWithOptions

NOTE: All the storyBoard "initialViewControllers" tick box on the property inspector is turned off

    UIStoryboard *storyboard =
        [UIStoryboard storyboardWithName:@"Registration" bundle:nil];

    RegisterViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"RegisterViewController"];

    //this is key else you get a black screen
    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];

    self.window.rootViewController = vc;
    [self.window makeKeyAndVisible];


问:
How to get to Workbook from Window
I have a Window object and need to get corresponding Workbook because I need to know .FullName but I can't figure out how to get there. Seems like impossoible from the MSDN documentation ?</p>

答:
You can use the Parent property to return the Workbook object...

```<code>ActiveWindow.Parent
</code>```

And then you can use the FullName property to return the path and filename...

```<code>ActiveWindow.Parent.FullName
</code>```

Title: How to get to Workbook from Window

Body:
You can use the Parent property to return the Workbook object...

ActiveWindow.Parent

And then you can use the FullName property to return the path and filename...

ActiveWindow.Parent.FullName


问:
C# equivalent of C++ std::string find_first_not_of and find_last_not_of
IndexOf, IndexOfAny and LastIndexOf, LastIndexOfAny dont seem to do these (or maybe they do). I'm looking for the equialent of std::string's find_first_not_of and find_last_not_of. I'm thinking about creating an extension class but I'm not sure if C# already provides this functionality.

答:
Here's a Regex solution.</p>

```<code>string testString = "oueytestie";
var matchFirstNotOf = Regex.Match(testString, @"[^aeiouy]");
int firstNotOf = matchFirstNotOf.Success ? matchFirstNotOf.Index : -1;
var matchLastNotOf = Regex.Match(testString, @"[^aeiouy]", RegexOptions.RightToLeft);
int lastNotOf = matchLastNotOf.Success ? matchLastNotOf.Index : -1;
</code>```

Body:
Here's a Regex solution.

string testString = "oueytestie";
var matchFirstNotOf = Regex.Match(testString, @"[^aeiouy]");
int firstNotOf = matchFirstNotOf.Success ? matchFirstNotOf.Index : -1;
var matchLastNotOf = Regex.Match(testString, @"[^aeiouy]", RegexOptions.RightToLeft);
int lastNotOf = matchLastNotOf.Success ? matchLastNotOf.Index : -1;


问:
Android Room Database Nested Object Reference for array of objects
I have a class structure with

```<code>Class x {
    int a;
    int b;
    Y[] yList;
}
Class Y {
    int m;
    int n;
}
</code>```

I am using data binding, Room and Dagger. I am getting compilation error as 'cannot find class DatabindingComponent', possibly because Room doesn't allow persistent of Nested objects. To enable I used @Embedded annotation but still getting same error. But if I use @Ignore annotation indicating Room that do not process this field; compilation is happening successfully.

How to reference nested array of objects for Room Database without foreign key?

Please refer to
https://developer.android.com/topic/libraries/architecture/room.html#no-object-references
https://developer.android.com/reference/android/arch/persistence/room/Ignore.html
https://developer.android.com/reference/android/arch/persistence/room/Embedded.html.

答:
How to reference nested array of objects for Room Database without foreign key?

If you do not want Y to be an @Entity with its own table, the only option that I know of is to use @TypeConverters:

Define two static methods with @TypeConverter that convert Y[] to and from some basic type (e.g., String, by using JSON)

Register the class holding those methods using @TypeConverters somewhere (e.g., on your RoomDatabase subclass)

This works using collection classes (e.g., List, Set). I would guess that it works with Java arrays (Y[]), though I have not tried it.

Body:
I have a class structure with

Class x {
    int a;
    int b;
    Y[] yList;
}
Class Y {
    int m;
    int n;
}

I am using data binding, Room and Dagger. I am getting compilation error as 'cannot find class DatabindingComponent', possibly because Room doesn't allow persistent of Nested objects. To enable I used @Embedded annotation but still getting same error. But if I use @Ignore annotation indicating Room that do not process this field; compilation is happening successfully.

How to reference nested array of objects for Room Database without foreign key?

Please refer to
https://developer.android.com/topic/libraries/architecture/room.html#no-object-references
https://developer.android.com/reference/android/arch/persistence/room/Ignore.html
https://developer.android.com/reference/android/arch/persistence/room/Embedded.html.


问:
returning iterators to boost adaptor-transformed container
I would like to offer to users of a class the possibility to iterate over a member container, but with a transform applied to the elements. Boost adaptors seem to be a good fit for transforming a container, but I do not know how could I possibly apply it to my use case.

The function returns an IterPair template wrapping the begin and end iterators and it works without the transform. However, with the transform I am returning a pair of iterators of a local variable.
Making the transformed container a member is not possible since it does not have a default constructor.

```<code>class A
{
public:
    IterPair get_elems()
    {
          auto tr_vect =  vect_ | boost::adaptors::transformed(std::mem_fn(&std::string::c_str));
          return {std::begin(tr_vect), std::end(tr_vect)};
    }
private:
    std::vector<std::string> vect_;
}
</code>```

答:
I would just return the range and leave it up to the user to call begin/end (or use range for as in the example below) on that:

```<code>#include <boost/range/adaptor/transformed.hpp>

#include <cstring>
#include <initializer_list>
#include <iostream>
#include <string>
#include <vector>

class A {
public:
    A(std::initializer_list<std::string> xs) : vect_{std::move(xs)} {}

    // auto return type requires c++14
    auto get_elems() const {
        return vect_ |
               boost::adaptors::transformed(std::mem_fn(&std::string::c_str));
    }

private:
    std::vector<std::string> vect_;
};

int main(int argc, char** argv) {
    A a{"a", "ab", "abc"};
    auto xs = a.get_elems();
    for (const auto& x : xs) {
        std::cout << std::strlen(x) << "\n";
    }
    return 0;
}
</code>```

live example

Body:
I would like to offer to users of a class the possibility to iterate over a member container, but with a transform applied to the elements. Boost adaptors seem to be a good fit for transforming a container, but I do not know how could I possibly apply it to my use case.

The function returns an IterPair template wrapping the begin and end iterators and it works without the transform. However, with the transform I am returning a pair of iterators of a local variable.
Making the transformed container a member is not possible since it does not have a default constructor.

class A
{
public:
    IterPair get_elems()
    {
          auto tr_vect =  vect_ | boost::adaptors::transformed(std::mem_fn(&std::string::c_str));
          return {std::begin(tr_vect), std::end(tr_vect)};
    }
private:
    std::vector<std::string> vect_;
}

Body:
I would just return the range and leave it up to the user to call begin/end (or use range for as in the example below) on that:

#include <boost/range/adaptor/transformed.hpp>

#include <cstring>
#include <initializer_list>
#include <iostream>
#include <string>
#include <vector>

class A {
public:
    A(std::initializer_list<std::string> xs) : vect_{std::move(xs)} {}

    // auto return type requires c++14
    auto get_elems() const {
        return vect_ |
               boost::adaptors::transformed(std::mem_fn(&std::string::c_str));
    }

private:
    std::vector<std::string> vect_;
};

int main(int argc, char** argv) {
    A a{"a", "ab", "abc"};
    auto xs = a.get_elems();
    for (const auto& x : xs) {
        std::cout << std::strlen(x) << "\n";
    }
    return 0;
}

live example


问:
Why use double indirection? or Why use pointers to pointers?
When should a double indirection be used in C? Can anyone explain with a example?

What I know is that a double indirection is a pointer to a pointer.  Why would I need a pointer to a pointer?

答:
Simple example that you probably have seen many times before

```<code>int main(int argc, char **argv)
</code>```

In the second parameter you have it: pointer to pointer to char.

Note that the pointer notation (char* c) and the array notation (char c[]) are interchangeable in function arguments. So you could also write char *argv[]. In other words char *argv[] and char **argv are interchangeable.

What the above represents is in fact an array of character sequences (the command line arguments that are given to a program at startup).

See also this answer for more details about the above function signature.

ContentLicense: CC BY-SA 4.0

Body:
Simple example that you probably have seen many times before

int main(int argc, char **argv)

In the second parameter you have it: pointer to pointer to char.

Note that the pointer notation (char* c) and the array notation (char c[]) are interchangeable in function arguments. So you could also write char *argv[]. In other words char *argv[] and char **argv are interchangeable.

What the above represents is in fact an array of character sequences (the command line arguments that are given to a program at startup).

See also this answer for more details about the above function signature.


答:
Use OrderedDict calling setdefault with an empty list, and the csv module:

```<code>import csv
from collections import OrderedDict

organizations = OrderedDict()
with open(filename) as infile:
    for name, org in csv.reader(infile, delimiter='|'):
        organizations.setdefault(name, []).append(org)
</code>```

Then you can write the dictionary:

```<code>with open(filename, 'w') as outfile:
    writer = csv.writer(outfile, delimiter='|')
    for name, orgs in organizations.items():
        writer.writerow([name, ','.join(orgs)])
</code>```

Title: Joining CSV fields

Body:
Use OrderedDict calling setdefault with an empty list, and the csv module:

import csv
from collections import OrderedDict

organizations = OrderedDict()
with open(filename) as infile:
    for name, org in csv.reader(infile, delimiter='|'):
        organizations.setdefault(name, []).append(org)

Then you can write the dictionary:

with open(filename, 'w') as outfile:
    writer = csv.writer(outfile, delimiter='|')
    for name, orgs in organizations.items():
        writer.writerow([name, ','.join(orgs)])


问:
WPF ActualWidth is zero
I have a user control which has a Canvas of height 100 and width 1920.

At the loading of the control, I go to an external source, download a text file and add TextBlocks to the Canvas. Then I want to create a marquee scrolling effect which should work just fine, except after I add the TextBlocks to the Canvas, I need to get their width for calculation purposes but the ActualWidth property is always zero.

Here is some code:

```<code>private readonly LinkedList<TextBlock> textBlocks = new LinkedList<TextBlock>();

public LocalNewsControl()
{
    Loaded += LocalNewsControlLoaded;
}

private void LocalNewsControlLoaded(object sender, RoutedEventArgs e)
{
    LoadDataContext();
}

private void LoadDataContext()
{
    DataContext = new NewsItemsViewModel((exception) => LoadNewsItems());
}

private void LoadNewsItems()
{
    var viewModel = (NewsItemsViewModel)DataContext;

    NewsCanvas.Children.Clear();
    textBlocks.Clear();

    foreach (var newsViewModel in viewModel.NewsItems)
    {
        var tb = new TextBlock
        {
            Text = newsViewModel.Headline,
            FontSize = 28,
            FontWeight = FontWeights.Normal,
            Foreground = Brushes.Black
        };

        NewsCanvas.Children.Add(tb);

        Canvas.SetTop(tb, 20);
        Canvas.SetLeft(tb, -999);

        textBlocks.AddLast(tb);
    }

    Dispatcher.BeginInvoke(new Action(() =>
    {
        var node = textBlocks.First;

        while (node != null)
        {
            if (node.Previous != null)
            {
                //THIS IS WHERE ActualWidth is always ZERO
                var left = Canvas.GetLeft(node.Previous.Value) + node.Previous.Value.ActualWidth + Gap;
                Canvas.SetLeft(node.Value, left);
            }
            else
                Canvas.SetLeft(node.Value, NewsCanvas.Width + Gap);

            node = node.Next;
        }
    }));
}
</code>```

答:
You could always attach a delgate to the PropertyMetatdata/OnValueChanged and when ActualHeight/ActualWidth changes from 0 to something, adjust your scrolling, ActualWidth/ActualHeight will have a value once its rendered at least once:

```<code>LocalNewsControl()
{
    var descriptor = DependencyPropertyDescriptor.FromProperty(ActualWidthProperty, typeof(TextBlock));
    if (descriptor != null)
        descriptor.AddValueChanged(myTextBlock, ActualWidth_ValueChanged);
}

private void ActualWidth_ValueChanged(object a_sender, EventArgs a_e)
{
   //Modify you scroll things here
   ...
}
</code>```

Title: WPF ActualWidth is zero

Body:
I have a user control which has a Canvas of height 100 and width 1920.

At the loading of the control, I go to an external source, download a text file and add TextBlocks to the Canvas. Then I want to create a marquee scrolling effect which should work just fine, except after I add the TextBlocks to the Canvas, I need to get their width for calculation purposes but the ActualWidth property is always zero.

Here is some code:

private readonly LinkedList<TextBlock> textBlocks = new LinkedList<TextBlock>();

public LocalNewsControl()
{
    Loaded += LocalNewsControlLoaded;
}

private void LocalNewsControlLoaded(object sender, RoutedEventArgs e)
{
    LoadDataContext();
}

private void LoadDataContext()
{
    DataContext = new NewsItemsViewModel((exception) => LoadNewsItems());
}

private void LoadNewsItems()
{
    var viewModel = (NewsItemsViewModel)DataContext;

    NewsCanvas.Children.Clear();
    textBlocks.Clear();

    foreach (var newsViewModel in viewModel.NewsItems)
    {
        var tb = new TextBlock
        {
            Text = newsViewModel.Headline,
            FontSize = 28,
            FontWeight = FontWeights.Normal,
            Foreground = Brushes.Black
        };

        NewsCanvas.Children.Add(tb);

        Canvas.SetTop(tb, 20);
        Canvas.SetLeft(tb, -999);

        textBlocks.AddLast(tb);
    }

    Dispatcher.BeginInvoke(new Action(() =>
    {
        var node = textBlocks.First;

        while (node != null)
        {
            if (node.Previous != null)
            {
                //THIS IS WHERE ActualWidth is always ZERO
                var left = Canvas.GetLeft(node.Previous.Value) + node.Previous.Value.ActualWidth + Gap;
                Canvas.SetLeft(node.Value, left);
            }
            else
                Canvas.SetLeft(node.Value, NewsCanvas.Width + Gap);

            node = node.Next;
        }
    }));
}

Body:
You could always attach a delgate to the PropertyMetatdata/OnValueChanged and when ActualHeight/ActualWidth changes from 0 to something, adjust your scrolling, ActualWidth/ActualHeight will have a value once its rendered at least once:

LocalNewsControl()
{
    var descriptor = DependencyPropertyDescriptor.FromProperty(ActualWidthProperty, typeof(TextBlock));
    if (descriptor != null)
        descriptor.AddValueChanged(myTextBlock, ActualWidth_ValueChanged);
}

private void ActualWidth_ValueChanged(object a_sender, EventArgs a_e)
{
   //Modify you scroll things here
   ...
}


问:
Creating a Django sign up form with two password inputs only one of which is sent to the database
I wanted to create a sign up page with two inputs for a password, to see if they match and then input only one final password into the database.

I have seen people suggest putting in two separate password fields: a 'password1' and 'password2'. Then creating a form with these two fields and then checking if the two match one another.

However I wanted to know if there was a way I could create a model class with just one 'password' field and still create a form with two inputs that will check if both inputs match. Then return only one password to the 'password' field in the database.

I am new to Django and programming in general.
Your help would be much appreciated, thank you.

答:
The existing User model that's part of django's contrib.auth module stores passwords as a hash value.. and provides a function for setting the password:

https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#methods

They also provide a UserCreationForm class to go with the model that does exactly what you are asking.  If their form doesn't fit in with your plans, you can look at their source code and use it as a guide:

https://docs.djangoproject.com/en/1.8/_modules/django/contrib/auth/forms/

But, to answer your question directly:  Let's say you did want to store a cleartext password into your own model, and you did want to make a form for that...  In that case:

It's totally ok to add extra fields to a Modelform subclass of your own.  The form will then contain the fields generated from the model, along with any fields you added.  When the form is saved, your added fields will be ignored..  but you can still access them in form.cleaned_data and write validation methods for them.

So let's say your real model password field is called password.. you can add another field to the form called password_again and then, create a clean method on your form, something like:

```<code>def clean(self, value):
    cd = self.cleaned_data

    if self._errors:
        return cd

    cd['password'] = cd['password'].strip()
    cd['password_again'] = cd['password_again'].strip()

    if not cd['password']:
        raise ValidationError("Passwords Can't Be Blank")

    if cd['password'] != cd['password_again']:
        raise ValidationError("Passwords Don't Match")

    return cd
</code>```

All that said.. it's not usually a good idea to store cleartext passwords in the database.  Django's authentication system works.. it sometimes takes a little effort to get it to work the way you want, but it's probably easier to modify it to suit your needs (eg. writing your own forms based on their form code, or subclassing their forms to make them behave the way you want) than it is to start from zero.

Body:
The existing User model that's part of django's contrib.auth module stores passwords as a hash value.. and provides a function for setting the password:

https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#methods

They also provide a UserCreationForm class to go with the model that does exactly what you are asking.  If their form doesn't fit in with your plans, you can look at their source code and use it as a guide:

https://docs.djangoproject.com/en/1.8/_modules/django/contrib/auth/forms/

But, to answer your question directly:  Let's say you did want to store a cleartext password into your own model, and you did want to make a form for that...  In that case:

It's totally ok to add extra fields to a Modelform subclass of your own.  The form will then contain the fields generated from the model, along with any fields you added.  When the form is saved, your added fields will be ignored..  but you can still access them in form.cleaned_data and write validation methods for them.

So let's say your real model password field is called password.. you can add another field to the form called password_again and then, create a clean method on your form, something like:

def clean(self, value):
    cd = self.cleaned_data

    if self._errors:
        return cd

    cd['password'] = cd['password'].strip()
    cd['password_again'] = cd['password_again'].strip()

    if not cd['password']:
        raise ValidationError("Passwords Can't Be Blank")

    if cd['password'] != cd['password_again']:
        raise ValidationError("Passwords Don't Match")

    return cd

All that said.. it's not usually a good idea to store cleartext passwords in the database.  Django's authentication system works.. it sometimes takes a little effort to get it to work the way you want, but it's probably easier to modify it to suit your needs (eg. writing your own forms based on their form code, or subclassing their forms to make them behave the way you want) than it is to start from zero.


问:
Do I need to secure my API key when I push to GitHub?
I am trying to use the Movie Database API to populate a simple Python data structure project for a class I am taking. I am a programming beginner, and have never tried to use an API before.

I have been supplied two things:

1) API Key (V3 Auth)

2) API Read Access Token (v4 auth)

Auth Documentation | v4 Auth Documentation

First of all, what is the difference between these two? I am able to successfully query for what I need using the API key - what would #2 be used for in an actual product?

When I go to turn in my project on GitHub, do I need to worry about the API key being visible? From my understanding, in some API's the key gives total account access, but some keys can be safely displayed on the client's end without worry.

Is this correct? What about in my case - do Movie Database API keys need to be kept secure?

How would I do so assuming I have to turn in the finished project on GitHub?

答:
I took a look at the documentation, and did not see anything about API keys or v3 vs. v4.

I would try the examples using each API key (and find out where it goes!), and just use the one that works.

You are correct, that it's probably not a good idea to commit your API keys (or any secret) to Git, or store them in your code. One common pattern is to store them in the server config, or even an file on your computer that is not in the Git repo. You can add the file to .gitignore to keep it out of the repo.


问:
UPDATE on INNER JOIN throwing 'SQL command not properly ended"
```<code>UPDATE TABLE1 SET COL1 = 'UPDATED'
INNER JOIN TABLE2 ON TABLE1.ID = TABLE2.ID
WHERE COL2 = '1' AND COL3 IN('A','B') AND COL4 = 'NEW'
</code>```

The above command throwing 'SQL command not properly ended', may I know why is it happening?
NOTE: COL2 , COL2 resides in TABLE1 while COL4 In TABLE2, if that is helpful.

答:
Oracle doesn't support explicit join's in its update syntax (it does support joins when using subqueries under certain conditions).  A query like this should work:

```<code>update TABLE1
    set COL1 = 'UPDATED'
    where col2 = '1' and col3 in ('A', 'B') and col4 = 'NEW' and
          exists (select 1
                  from TABLE2
                  where TABLE1.ID = TABLE2.ID
                 );
</code>```

The conditions in the where may need to go in the subquery, if they refer to TABLE2.

Body:
UPDATE TABLE1 SET COL1 = 'UPDATED'
INNER JOIN TABLE2 ON TABLE1.ID = TABLE2.ID
WHERE COL2 = '1' AND COL3 IN('A','B') AND COL4 = 'NEW'

The above command throwing 'SQL command not properly ended', may I know why is it happening?
NOTE: COL2 , COL2 resides in TABLE1 while COL4 In TABLE2, if that is helpful.

Body:
Oracle doesn't support explicit join's in its update syntax (it does support joins when using subqueries under certain conditions).  A query like this should work:

update TABLE1
    set COL1 = 'UPDATED'
    where col2 = '1' and col3 in ('A', 'B') and col4 = 'NEW' and
          exists (select 1
                  from TABLE2
                  where TABLE1.ID = TABLE2.ID
                 );

The conditions in the where may need to go in the subquery, if they refer to TABLE2.


问:
Webpack extract text plugin unknow word export error
I'm having these errors when bundling my app and I can't figure why it's not working. I was using style-loader before and now I'm trying to implement extract-text plugin but got these errors :

The thing is all of this was actually working with style-loader, I'm just replacing style-loader with extract plugin, not changing any other loader or plugin, and I searched but didn't found any solution.

vuetify.css can be found here https://github.com/vuetifyjs/vuetify/tree/master/dist

here is my index.scss :

```<code>@import "default";
@import "list";
@import "page";
@import "toolbar";
</code>```

And here is part where I'm importing the files :

```<code>import 'vuetify/dist/vuetify.min.css';
import './sass/index.scss';
</code>```

Webpack module config :

```<code>module: {
    rules: [{
            test: /\.vue$/,
            loader: 'vue-loader',
            options: {
                loaders: {
                    scss: 'css-loader?url=false!sass-loader',
                },
                extractCSS: true,
            }
        },
        {
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
        },
        {
            test: /\.css$/,
            loader: ExtractTextPlugin.extract({
                use: 'css-loader',
                fallback: 'style-loader!css-loader'
            })
        },
        {
            test: /\.scss$/,
            loader: ExtractTextPlugin.extract({
                use: 'css-loader?url=false!sass-loader',
                fallback: 'style-loader!css-loader?url=false!sass-loader'
            })
        },
        {
            test: /\.(png|jpg|gif|svg|ttf|otf|eot|svg|woff(2)?)$/,
            loader: 'file-loader',
            options: {
                name: '[name].[ext]?[hash]'
            }
        },
    ]
}
</code>```

plugin config :

```<code>plugins: [

    new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: JSON.stringify(process.env.NODE_ENV),
        }
    }),

    new CleanWebpackPlugin([
        getPath('../cordova/www/**'),
    ], {
        root: getPath('..'),
    }),

    new CopyWebpackPlugin([{
            from: getPath('../index.html'),
            to: getPath('../cordova/www/index.html')
        },
        {
            from: getPath('../assets'),
            to: getPath('../cordova/www/assets/')
        },
    ]),

    new webpack.ProvidePlugin({
        fetch: 'imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch'
    }),

    new webpack.LoaderOptionsPlugin({
        minimize: false,
        debug: true
    }),

    new ExtractTextPlugin('styles.css')

],
</code>```

答:
Change /\.css$/ rule to this one.

```<code>  {
    test: /\.css$/,
    use: ExtractTextPlugin.extract({
      fallback: 'style-loader',
      use: 'css-loader'
    })
  }
</code>```

Body:
I'm having these errors when bundling my app and I can't figure why it's not working. I was using style-loader before and now I'm trying to implement extract-text plugin but got these errors :

The thing is all of this was actually working with style-loader, I'm just replacing style-loader with extract plugin, not changing any other loader or plugin, and I searched but didn't found any solution.

vuetify.css can be found here https://github.com/vuetifyjs/vuetify/tree/master/dist

here is my index.scss :

@import "default";
@import "list";
@import "page";
@import "toolbar";

And here is part where I'm importing the files :

import 'vuetify/dist/vuetify.min.css';
import './sass/index.scss';

Webpack module config :

module: {
    rules: [{
            test: /\.vue$/,
            loader: 'vue-loader',
            options: {
                loaders: {
                    scss: 'css-loader?url=false!sass-loader',
                },
                extractCSS: true,
            }
        },
        {
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
        },
        {
            test: /\.css$/,
            loader: ExtractTextPlugin.extract({
                use: 'css-loader',
                fallback: 'style-loader!css-loader'
            })
        },
        {
            test: /\.scss$/,
            loader: ExtractTextPlugin.extract({
                use: 'css-loader?url=false!sass-loader',
                fallback: 'style-loader!css-loader?url=false!sass-loader'
            })
        },
        {
            test: /\.(png|jpg|gif|svg|ttf|otf|eot|svg|woff(2)?)$/,
            loader: 'file-loader',
            options: {
                name: '[name].[ext]?[hash]'
            }
        },
    ]
}

plugin config :

plugins: [

    new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: JSON.stringify(process.env.NODE_ENV),
        }
    }),

    new CleanWebpackPlugin([
        getPath('../cordova/www/**'),
    ], {
        root: getPath('..'),
    }),

    new CopyWebpackPlugin([{
            from: getPath('../index.html'),
            to: getPath('../cordova/www/index.html')
        },
        {
            from: getPath('../assets'),
            to: getPath('../cordova/www/assets/')
        },
    ]),

    new webpack.ProvidePlugin({
        fetch: 'imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch'
    }),

    new webpack.LoaderOptionsPlugin({
        minimize: false,
        debug: true
    }),

    new ExtractTextPlugin('styles.css')

],

Body:
Change /\.css$/ rule to this one.

  {
    test: /\.css$/,
    use: ExtractTextPlugin.extract({
      fallback: 'style-loader',
      use: 'css-loader'
    })
  }


问:
Dealing with Exception in Overridden Interface in Java
I have a Java interface that I am implementing (EdgeProvider from JGraphT) and which is not allowed to be null. However, I'm instantiating a generic type in an overridden method and can't figure out how to deal with either InstantiationException or IllegalAccessException in a way that I can detect and cleanly break out of the execution flow.

```<code>EdgeProvider<V, E> ep = new EdgeProvider<V, E>() {
      @Override
      public E buildEdge(V from, V to, String label, Map<String, String> attributes) {
        try {
          return eClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
          return null;
        }
      }
    };
</code>```

If I rethrow I just get a warning that I have unhandled exceptions. Any suggestions?

答:
There is a way to instantiate a class without exceptions, using a constructor reference. For instance:

```<code>Supplier<SomeType> eCons = SomeType::new;
</code>```

Supplier is used for a default constructor, but you can use any functional interface type (for instance one of the ones listed here: Link) that matches the signature of the constructor you want to reference (for instance one that takes arguments).

In the case of Supplier, you can call get(), to create a new instance:

```<code>EdgeProvider<V, E> ep = new EdgeProvider<V, E>() {
    @Override
    public E buildEdge(V from, V to, String label, Map<String, String> attributes) {
        return eCons.get();
    }
};
</code>```

Body:
I have a Java interface that I am implementing (EdgeProvider from JGraphT) and which is not allowed to be null. However, I'm instantiating a generic type in an overridden method and can't figure out how to deal with either InstantiationException or IllegalAccessException in a way that I can detect and cleanly break out of the execution flow.

EdgeProvider<V, E> ep = new EdgeProvider<V, E>() {
      @Override
      public E buildEdge(V from, V to, String label, Map<String, String> attributes) {
        try {
          return eClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
          return null;
        }
      }
    };

If I rethrow I just get a warning that I have unhandled exceptions. Any suggestions?

Body:
There is a way to instantiate a class without exceptions, using a constructor reference. For instance:

Supplier<SomeType> eCons = SomeType::new;

Supplier is used for a default constructor, but you can use any functional interface type (for instance one of the ones listed here: Link) that matches the signature of the constructor you want to reference (for instance one that takes arguments).

In the case of Supplier, you can call get(), to create a new instance:

EdgeProvider<V, E> ep = new EdgeProvider<V, E>() {
    @Override
    public E buildEdge(V from, V to, String label, Map<String, String> attributes) {
        return eCons.get();
    }
};


答:
```<code>select  *
into    #input
from (
    select   1152  as clientid,        68 as releaseid , 'Yes' as status    ,  '' as ParentSignature union all
    select   1152 ,        70 , 'Yes'    , ''     union all
    select   5059 ,        68 , 'Yes'    , 'ad '  union all
    select   5410 ,        68 , 'Yes'    , '111 ' union all
    select   5410 ,        70 , 'Yes'    , '111 ' union all
    select   5410 ,        71 , 'Yes'    , ''
) x

SELECT * FROM #input x

SELECT  b.clientid
FROM    #input b
GROUP BY b.clientid
HAVING  COUNT(DISTINCT b.releaseid) = (SELECT COUNT(DISTINCT a.releaseid) FROM #input a)
</code>```

Note: If there is an UNIQUE index/constraint defined on {clientid, releaseid} then I would remove DISTINCT from  COUNT(DISTINCT b.releaseid).

Title: How to insert dummy rows for distinct ids in a result set

Body:
I have a result set as follows:

+---------+-----------+--------+-----------------+
| ChildID | ReleaseID | Status | ParentSignature |
+---------+-----------+--------+-----------------+
|    1152 |        68 | Yes    |                 |
|    1152 |        70 | Yes    |                 |
|    5059 |        68 | Yes    | ad              |
|    5410 |        68 | Yes    | 111             |
|    5410 |        70 | Yes    | 111             |
|    5410 |        71 | Yes    |                 |
+---------+-----------+--------+-----------------+

In the above result set, there are 3 distinct values in ReleaseID column such as 68, 70 and 71.
Only one child id  (5410) has records corresponding to all the releaseids.

My requirement is to get an output result set in which there are records for each child for each release id with blank values for remaining columns.
The number of maximum distinct releaseids can vary. In this example, there are 3 releaseids.

Expected output:-

+---------+-----------+--------+-----------------+
| ChildID | ReleaseID | Status | ParentSignature |
+---------+-----------+--------+-----------------+
|    1152 |        68 | Yes    |                 |
|    1152 |        70 | Yes    |                 |
|    1152 |        71 |        |                 |
|    5059 |        68 | Yes    | ad              |
|    5059 |        70 |        |                 |
|    5059 |        71 |        |                 |
|    5410 |        68 | Yes    | 111             |
|    5410 |        70 | Yes    | 111             |
|    5410 |        71 | Yes    |                 |
+---------+-----------+--------+-----------------+

Body:
select  *
into    #input
from (
    select   1152  as clientid,        68 as releaseid , 'Yes' as status    ,  '' as ParentSignature union all
    select   1152 ,        70 , 'Yes'    , ''     union all
    select   5059 ,        68 , 'Yes'    , 'ad '  union all
    select   5410 ,        68 , 'Yes'    , '111 ' union all
    select   5410 ,        70 , 'Yes'    , '111 ' union all
    select   5410 ,        71 , 'Yes'    , ''
) x

SELECT * FROM #input x

SELECT  b.clientid
FROM    #input b
GROUP BY b.clientid
HAVING  COUNT(DISTINCT b.releaseid) = (SELECT COUNT(DISTINCT a.releaseid) FROM #input a)

Note: If there is an UNIQUE index/constraint defined on {clientid, releaseid} then I would remove DISTINCT from  COUNT(DISTINCT b.releaseid).


问:
Inserting multiple values in a table, in C#
I have 98 columns in a table named 'molasses_analysis' and I need to insert records using my c# desktop application.

Sample of my code is as below.

```<code>    string insert_sql = @"insert into molasses_analysis(mo_entry_date, mo_entry_time, mo_code, mo_brix, mo_pol, mo_purity, mo_crtd_by) " +
    " values(@entry_date, @entry_time, @mol_code, @brix, @pol, @purity, @crtd_by)";
    try
        {
         List<SqlParameter> param = new List<SqlParameter>();
         param.Add(new SqlParameter("@entry_date", entry_date));
         param.Add(new SqlParameter("@entry_time", entry_time));
         param.Add(new SqlParameter("@mol_code", mol_code));
         param.Add(new SqlParameter("@brix", brix));
         param.Add(new SqlParameter("@pol", pol));
         param.Add(new SqlParameter("@purity", purity));
         param.Add(new SqlParameter("@crtd_by", crtd_by));
        int inserted_rows = SqlHelper.ExecuteNonQuery(dbConn.sqlConn(),CommandType.Text, insert_sql, param.ToArray());
        }
catch (Exception ex)
      {
        MessageBox.Show("Data not saved!\nError message - "+ex.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
</code>```

Here I just used seven fields/columns only but it will be quite hectic and painful to write such code for 98 columns and assign Sql Parameter for each column.
My question is, is there any cleaner and good code to insert multiple columns using c# code?

答:
If your property names and columns names are same this answer will help you.
First, get your column names with SQL code which is given below

```<code>SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'molasses_analysis';
//this returns column names and column types
</code>```

Then assign table to list which contains column names

```<code>List<string> listColNames = new List<string>();
</code>```

Then create your sqlInsert string with loop

```<code>foreach (string item in listColNames) {
    params.Add(new SqlParameter("@" + item, item));
}
</code>```

Body:
I have 98 columns in a table named 'molasses_analysis' and I need to insert records using my c# desktop application.

Sample of my code is as below.

    string insert_sql = @"insert into molasses_analysis(mo_entry_date, mo_entry_time, mo_code, mo_brix, mo_pol, mo_purity, mo_crtd_by) " +
    " values(@entry_date, @entry_time, @mol_code, @brix, @pol, @purity, @crtd_by)";
    try
        {
         List<SqlParameter> param = new List<SqlParameter>();
         param.Add(new SqlParameter("@entry_date", entry_date));
         param.Add(new SqlParameter("@entry_time", entry_time));
         param.Add(new SqlParameter("@mol_code", mol_code));
         param.Add(new SqlParameter("@brix", brix));
         param.Add(new SqlParameter("@pol", pol));
         param.Add(new SqlParameter("@purity", purity));
         param.Add(new SqlParameter("@crtd_by", crtd_by));
        int inserted_rows = SqlHelper.ExecuteNonQuery(dbConn.sqlConn(),CommandType.Text, insert_sql, param.ToArray());
        }
catch (Exception ex)
      {
        MessageBox.Show("Data not saved!\nError message - "+ex.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }

Here I just used seven fields/columns only but it will be quite hectic and painful to write such code for 98 columns and assign Sql Parameter for each column.
My question is, is there any cleaner and good code to insert multiple columns using c# code?

Body:
If your property names and columns names are same this answer will help you.
First, get your column names with SQL code which is given below

SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'molasses_analysis';
//this returns column names and column types

Then assign table to list which contains column names

List<string> listColNames = new List<string>();

Then create your sqlInsert string with loop

foreach (string item in listColNames) {
    params.Add(new SqlParameter("@" + item, item));
}


问:
Write firebase function and schedule time to send notification android
I have a function that triggers the date to the firebase database node and sending notification when user inputs data to the android device. I want to to schedule timer to send this notification using an external cron job.I have the code below that successfully sends notification as soon as the user enters the date. Can any one help me please as I'm finding really hard to understand it.What do I have to modify to make it work?

This is the index.js

```<code>    var functions = require('firebase-functions');
var admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/Users/{userId}/description/{descId}')
        .onWrite(event => {

        // Grab the current value of what was written to the Realtime Database.
        var eventSnapshot = event.data;
        var str1 = "Your profile title is ";
        var str2 = "Date is ";
        var strProfile = str1.concat(eventSnapshot.child("title").val());
        var strStatus = str2.concat(eventSnapshot.child("date").val());
        console.log(strProfile);
        console.log(strStatus)

        var topic = "android";
        var payload = {
            data: {
                title: eventSnapshot.child("title").val(),
                date: eventSnapshot.child("date").val()
            }
        };

        // Send a message to devices subscribed to the provided topic.
        return admin.messaging().sendToTopic(topic, payload)
            .then(function (response) {
                // See the MessagingTopicResponse reference documentation for the
                // contents of response.
                console.log("Successfully sent message:", response);
            })
            .catch(function (error) {
                console.log("Error sending message:", error);
            });
        });
</code>```

MyFirebaseMessagingService Activity

```<code>    public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            showNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("date"));
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {

        }
    }

    private void showNotification(String title, String date) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setContentTitle("title  is " + title)
                .setSmallIcon(R.drawable.alex)
                .setContentText("your deadline date is " + date)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }

}
</code>```

答:
You can easily achieve this with the help of AlarmManager. When user inputs a date, get that date and set an Alarm for that specific date and time like this:

```<code>Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar

Calendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 32);
cal.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));
cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));
Intent intent = new Intent(ProfileList.this,
IntentBroadcastedReceiver.class);
PendingIntent pintent = PendingIntent.getService(ProfileList.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pintent);
</code>```

Then you have to set up a Broadcast Receiver to handle the event. In onReceive() method of your Broadcast Receiver, you will call your web-service to send the request to your server.

```<code>public class MyBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {

    // Call your web-service here.

}
}
</code>```

Don't forget to define receiver in manifest:

```<code><receiver android:name=".MyBroadcastReceiver" >
</code>```

Body:
I have a function that triggers the date to the firebase database node and sending notification when user inputs data to the android device. I want to to schedule timer to send this notification using an external cron job.I have the code below that successfully sends notification as soon as the user enters the date. Can any one help me please as I'm finding really hard to understand it.What do I have to modify to make it work?

This is the index.js

    var functions = require('firebase-functions');
var admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/Users/{userId}/description/{descId}')
        .onWrite(event => {

        // Grab the current value of what was written to the Realtime Database.
        var eventSnapshot = event.data;
        var str1 = "Your profile title is ";
        var str2 = "Date is ";
        var strProfile = str1.concat(eventSnapshot.child("title").val());
        var strStatus = str2.concat(eventSnapshot.child("date").val());
        console.log(strProfile);
        console.log(strStatus)

        var topic = "android";
        var payload = {
            data: {
                title: eventSnapshot.child("title").val(),
                date: eventSnapshot.child("date").val()
            }
        };

        // Send a message to devices subscribed to the provided topic.
        return admin.messaging().sendToTopic(topic, payload)
            .then(function (response) {
                // See the MessagingTopicResponse reference documentation for the
                // contents of response.
                console.log("Successfully sent message:", response);
            })
            .catch(function (error) {
                console.log("Error sending message:", error);
            });
        });

MyFirebaseMessagingService Activity

    public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            showNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("date"));
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {

        }
    }

    private void showNotification(String title, String date) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setContentTitle("title  is " + title)
                .setSmallIcon(R.drawable.alex)
                .setContentText("your deadline date is " + date)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }

}

Body:
You can easily achieve this with the help of AlarmManager. When user inputs a date, get that date and set an Alarm for that specific date and time like this:

Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar

Calendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 32);
cal.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));
cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));
Intent intent = new Intent(ProfileList.this,
IntentBroadcastedReceiver.class);
PendingIntent pintent = PendingIntent.getService(ProfileList.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pintent);

Then you have to set up a Broadcast Receiver to handle the event. In onReceive() method of your Broadcast Receiver, you will call your web-service to send the request to your server.

public class MyBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {

    // Call your web-service here.

}
}

Don't forget to define receiver in manifest:

<receiver android:name=".MyBroadcastReceiver" >


问:
App crashes when putSerializable() in onSaveInstanceState is used in fragment code
Im using this library https://github.com/stepstone-tech/android-material-stepper
for accomodating multiple fragments in a single activity. In one of the fragments, I was trying to save the item objects in the fragments recyclerview in onSaveInstanceState() method,it works quite alright but when the app loses focus(such as pressing home button),the app crashes(it works well when i exit the app by pressing the back button).
Here is the fragment

```<code> public class StylesFragment extends Fragment implements Step {
        private static final String STATE_ITEMS = "items";
        RecyclerView recyclerView;
        private TAASService mService;
        public ArrayList<CustomStyles> styles;
        public StylesFragment() {
            // Required empty public constructor
        }

        @Override
        public void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);

        }

        @SuppressWarnings("unchecked")
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment

            final View v=inflater.inflate(R.layout.fragment_styles, container, false);
            recyclerView=(RecyclerView) v.findViewById(R.id.recycler);
            //recyclerView.setAdapter(adapter);
            mService = ApiUtils.getTAASService();
            if (savedInstanceState==null) {
                loadCustomStyles();
            }else{
                    styles = (ArrayList<CustomStyles>) savedInstanceState.getSerializable(STATE_ITEMS);
                    StylesListAdapter adapter = new StylesListAdapter(styles);
                    //do more things

            }
            return v;
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putSerializable(STATE_ITEMS,styles);
        }

        public void loadCustomStyles() {

          //load from network
        }
</code>```

So I noticed on removing outState.putSerializable(); .It does not crash the app when the app loses focus,anyone know what is happening here and how i can correct it?Thank you

PS:The laptop I use for coding android is of low quality,so I cant make use of the logcat.Have to assemble,install on my phone,to see how it works.

UPDATE

```<code>public class CustomStyles implements Serializable{

    @SerializedName("pk")
    @Expose
    private Integer pk;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("gender")
    @Expose
    private String gender;
    @SerializedName("photo1")
    @Expose
    private String photo1;
    @SerializedName("custom_price")
    @Expose
    private Integer customPrice;
    @SerializedName("designer")
    @Expose
    private Designer designer;

    public Integer getPk() {
        return pk;
    }

    public void setPk(Integer pk) {
        this.pk = pk;
    }

    public String getName() {
        return name;
    }
    @Override
    public String toString() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getPhoto1() {
        return photo1;
    }

    public void setPhoto1(String photo1) {
        this.photo1 = photo1;
    }

    public Integer getCustomPrice() {
        return customPrice;
    }

    public void setCustomPrice(Integer customPrice) {
        this.customPrice = customPrice;
    }

    public Designer getDesigner()  {
        return designer;
    }

    public void setDesigner(Designer designer) {
        this.designer = designer;
    }

}
</code>```

答:
Your CustomStyles class is not serializable

Implement serializable in you class CustomStyles (and also in all custom classes you are using inside CustomStyles class)

```<code>public class CustomStyles implements Serializable {

    .
    .
    .
    .
}
</code>```

Body:
Im using this library https://github.com/stepstone-tech/android-material-stepper
for accomodating multiple fragments in a single activity. In one of the fragments, I was trying to save the item objects in the fragments recyclerview in onSaveInstanceState() method,it works quite alright but when the app loses focus(such as pressing home button),the app crashes(it works well when i exit the app by pressing the back button).
Here is the fragment

 public class StylesFragment extends Fragment implements Step {
        private static final String STATE_ITEMS = "items";
        RecyclerView recyclerView;
        private TAASService mService;
        public ArrayList<CustomStyles> styles;
        public StylesFragment() {
            // Required empty public constructor
        }

        @Override
        public void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);

        }

        @SuppressWarnings("unchecked")
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment

            final View v=inflater.inflate(R.layout.fragment_styles, container, false);
            recyclerView=(RecyclerView) v.findViewById(R.id.recycler);
            //recyclerView.setAdapter(adapter);
            mService = ApiUtils.getTAASService();
            if (savedInstanceState==null) {
                loadCustomStyles();
            }else{
                    styles = (ArrayList<CustomStyles>) savedInstanceState.getSerializable(STATE_ITEMS);
                    StylesListAdapter adapter = new StylesListAdapter(styles);
                    //do more things

            }
            return v;
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putSerializable(STATE_ITEMS,styles);
        }

        public void loadCustomStyles() {

          //load from network
        }

So I noticed on removing outState.putSerializable(); .It does not crash the app when the app loses focus,anyone know what is happening here and how i can correct it?Thank you

PS:The laptop I use for coding android is of low quality,so I cant make use of the logcat.Have to assemble,install on my phone,to see how it works.

UPDATE

public class CustomStyles implements Serializable{

    @SerializedName("pk")
    @Expose
    private Integer pk;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("gender")
    @Expose
    private String gender;
    @SerializedName("photo1")
    @Expose
    private String photo1;
    @SerializedName("custom_price")
    @Expose
    private Integer customPrice;
    @SerializedName("designer")
    @Expose
    private Designer designer;

    public Integer getPk() {
        return pk;
    }

    public void setPk(Integer pk) {
        this.pk = pk;
    }

    public String getName() {
        return name;
    }
    @Override
    public String toString() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getPhoto1() {
        return photo1;
    }

    public void setPhoto1(String photo1) {
        this.photo1 = photo1;
    }

    public Integer getCustomPrice() {
        return customPrice;
    }

    public void setCustomPrice(Integer customPrice) {
        this.customPrice = customPrice;
    }

    public Designer getDesigner()  {
        return designer;
    }

    public void setDesigner(Designer designer) {
        this.designer = designer;
    }

}

Body:
Your CustomStyles class is not serializable

Implement serializable in you class CustomStyles (and also in all custom classes you are using inside CustomStyles class)

public class CustomStyles implements Serializable {

    .
    .
    .
    .
}


答:
I think you may be approaching this incorrectly... instead of doing what you wrote, I would offer the following approach, which is really too much code to flesh-out in a quick post:

```<code>template <typename CONTAINER, // your underlying container
          typename TRANSFORM> // functor for your transform
class transform_adaptor
{
    template <typename IT = typename CONTAINER::iterator>
    class proxy_iterator : private TRANSFORM {
        // standard iterator typedefs, sourced from CONTAINER::iterator

        typedef IT underlying_iterator;
        underlying_iterator i;
     public:
        auto operator * () const -> decltype(TRANSFORM{}(*i))
        {
            return this->operator () (*i);
        }
        // Other proxy functions for the underlying iterator,
        // i.e. operator++, etc
    }

    CONTAINER * cptr;
 public:
    typedef proxy_iterator iterator;
    typedef proxy_iterator const_iterator;
    // necessary value_type, iterator, allocator, etc adaptors here

    iterator begin() { return proxy_iterator(cptr->begin()); }
    iterator end() { return proxy_iterator(cptr->end()); }
};
</code>```

I'm sorry for barely sketching out the bones of this, but it turns out to be considerably more code than I wish to compile and test right now...

The idea being that you create a wrapper container class that contains an iterator proxy to the underlying container as well as a reference (pointer) to the underlying container. When the proxy iterator is dereferenced, using it's operator*, it applies a transform to the underlying container element and returns its result.

Where this falls short, is that it breaks the STL's API for certain operations, just as std::vector<bool> breaks things - you can't assign elements back into the container from a proxy_iterator handle without some more hackery and a guarantee that you can reverse-map the result-type of your transfer back into your original data domain (i.e. your transform is 1 to 1, or bijective). As a result of this, certain operations, like std::sort will fail on your proxy container, but it certainly is a good option for data transform if you need to have a const container to move data between two different api's.

Title: returning iterators to boost adaptor-transformed container

Body:
I would like to offer to users of a class the possibility to iterate over a member container, but with a transform applied to the elements. Boost adaptors seem to be a good fit for transforming a container, but I do not know how could I possibly apply it to my use case.

The function returns an IterPair template wrapping the begin and end iterators and it works without the transform. However, with the transform I am returning a pair of iterators of a local variable.
Making the transformed container a member is not possible since it does not have a default constructor.

class A
{
public:
    IterPair get_elems()
    {
          auto tr_vect =  vect_ | boost::adaptors::transformed(std::mem_fn(&std::string::c_str));
          return {std::begin(tr_vect), std::end(tr_vect)};
    }
private:
    std::vector<std::string> vect_;
}

Body:
I think you may be approaching this incorrectly... instead of doing what you wrote, I would offer the following approach, which is really too much code to flesh-out in a quick post:

template <typename CONTAINER, // your underlying container
          typename TRANSFORM> // functor for your transform
class transform_adaptor
{
    template <typename IT = typename CONTAINER::iterator>
    class proxy_iterator : private TRANSFORM {
        // standard iterator typedefs, sourced from CONTAINER::iterator

        typedef IT underlying_iterator;
        underlying_iterator i;
     public:
        auto operator * () const -> decltype(TRANSFORM{}(*i))
        {
            return this->operator () (*i);
        }
        // Other proxy functions for the underlying iterator,
        // i.e. operator++, etc
    }

    CONTAINER * cptr;
 public:
    typedef proxy_iterator iterator;
    typedef proxy_iterator const_iterator;
    // necessary value_type, iterator, allocator, etc adaptors here

    iterator begin() { return proxy_iterator(cptr->begin()); }
    iterator end() { return proxy_iterator(cptr->end()); }
};

I'm sorry for barely sketching out the bones of this, but it turns out to be considerably more code than I wish to compile and test right now...

The idea being that you create a wrapper container class that contains an iterator proxy to the underlying container as well as a reference (pointer) to the underlying container. When the proxy iterator is dereferenced, using it's operator*, it applies a transform to the underlying container element and returns its result.

Where this falls short, is that it breaks the STL's API for certain operations, just as std::vector<bool> breaks things - you can't assign elements back into the container from a proxy_iterator handle without some more hackery and a guarantee that you can reverse-map the result-type of your transfer back into your original data domain (i.e. your transform is 1 to 1, or bijective). As a result of this, certain operations, like std::sort will fail on your proxy container, but it certainly is a good option for data transform if you need to have a const container to move data between two different api's.


问:
In Selenium, how to handle InvalidSelectorException while log in website
I'm trying to log in website with selenium. This is the code that I made.

```<code>from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://abcde.com")

assert "xxx" in driver.title
user = driver.find_element_by_css_selector("#ctl00_MasterHeaderPlaceHolder_ctl00_userNameTextbox")
user.clear()
user.send_keys("username")

pwd = driver.find_element_by_css_selector("#ctl00$MasterHeaderPlaceHolder$ctl00$passwordTextbox")
pwd.clear()
pwd.send_keys("mypassword")
pwd.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
driver.close()
</code>```

When I run this code, InvalidSelectorException has occurred.

raise exception_class(message, screen, stacktrace)
  selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified
    (Session info: chrome=59.0.3071.115)
    (Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 4.4.0-83-generic x86_64)

I've attached png file for your convenience.

This is the page source in the website.

```<code><input name="ctl00$MasterHeaderPlaceHolder$ctl00$userNameTextbox" type="text" value="Username" id="ctl00_MasterHeaderPlaceHolder_ctl00_userNameTextbox" OnClick="UsernameBehaviour("click", "ctl00_MasterHeaderPlaceHolder_ctl00_userNameTextbox", "Username");" OnFocus="UsernameBehaviour("focus", "ctl00_MasterHeaderPlaceHolder_ctl00_userNameTextbox", "Username");" OnBlur="UsernameBehaviour("blur", "ctl00_MasterHeaderPlaceHolder_ctl00_userNameTextbox", "Username");" />
<input name="ctl00$MasterHeaderPlaceHolder$ctl00$passwordTextbox" type="password" id="ctl00_MasterHeaderPlaceHolder_ctl00_passwordTextbox" OnBlur="PasswordBehaviour("ctl00_MasterHeaderPlaceHolder_ctl00_passwordTextbox", "ctl00_MasterHeaderPlaceHolder_ctl00_tempPasswordTextbox", 1);" style="display:none" />
<input name="ctl00$MasterHeaderPlaceHolder$ctl00$tempPasswordTextbox" type="text" value="Password" id="ctl00_MasterHeaderPlaceHolder_ctl00_tempPasswordTextbox" OnClick="PasswordBehaviour("ctl00_MasterHeaderPlaceHolder_ctl00_passwordTextbox", "ctl00_MasterHeaderPlaceHolder_ctl00_tempPasswordTextbox", 2);" OnFocus="PasswordBehaviour("ctl00_MasterHeaderPlaceHolder_ctl00_passwordTextbox", "ctl00_MasterHeaderPlaceHolder_ctl00_tempPasswordTextbox", 2);" />
</code>```

I have attached png file for the convenience.

As you can see, there are two input box related password. When I click password input tag, javascript seems to do something. But I'm not sure.

I would like to know the reason and solution.

Thanks for your time.

Please help me.

答:
You are using CSS selector incorrectly. It needs to have an element tied to it, but you are trying to find using an attribute value.

In order for it to work you need to change your CSS selector to this.

Solution 1.

```<code>driver.find_element_by_css_selector("input[id='ctl00_MasterHeaderPlaceHolder_ctl00_tempPasswordTextbox']")
</code>```

Solution 2

As the elements have name attribute, you can use  "find_element_by_name".

```<code>driver.find_element_by_name("ctl00$MasterHeaderPlaceHolder$ctl00$tempPasswordTextbox")
</code>```

Body:
I'm trying to log in website with selenium. This is the code that I made.

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://abcde.com")

assert "xxx" in driver.title
user = driver.find_element_by_css_selector("#ctl00_MasterHeaderPlaceHolder_ctl00_userNameTextbox")
user.clear()
user.send_keys("username")

pwd = driver.find_element_by_css_selector("#ctl00$MasterHeaderPlaceHolder$ctl00$passwordTextbox")
pwd.clear()
pwd.send_keys("mypassword")
pwd.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
driver.close()

When I run this code, InvalidSelectorException has occurred.

raise exception_class(message, screen, stacktrace)
  selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified
    (Session info: chrome=59.0.3071.115)
    (Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 4.4.0-83-generic x86_64)

I've attached png file for your convenience.

This is the page source in the website.

<input name="ctl00$MasterHeaderPlaceHolder$ctl00$userNameTextbox" type="text" value="Username" id="ctl00_MasterHeaderPlaceHolder_ctl00_userNameTextbox" OnClick="UsernameBehaviour("click", "ctl00_MasterHeaderPlaceHolder_ctl00_userNameTextbox", "Username");" OnFocus="UsernameBehaviour("focus", "ctl00_MasterHeaderPlaceHolder_ctl00_userNameTextbox", "Username");" OnBlur="UsernameBehaviour("blur", "ctl00_MasterHeaderPlaceHolder_ctl00_userNameTextbox", "Username");" />
<input name="ctl00$MasterHeaderPlaceHolder$ctl00$passwordTextbox" type="password" id="ctl00_MasterHeaderPlaceHolder_ctl00_passwordTextbox" OnBlur="PasswordBehaviour("ctl00_MasterHeaderPlaceHolder_ctl00_passwordTextbox", "ctl00_MasterHeaderPlaceHolder_ctl00_tempPasswordTextbox", 1);" style="display:none" />
<input name="ctl00$MasterHeaderPlaceHolder$ctl00$tempPasswordTextbox" type="text" value="Password" id="ctl00_MasterHeaderPlaceHolder_ctl00_tempPasswordTextbox" OnClick="PasswordBehaviour("ctl00_MasterHeaderPlaceHolder_ctl00_passwordTextbox", "ctl00_MasterHeaderPlaceHolder_ctl00_tempPasswordTextbox", 2);" OnFocus="PasswordBehaviour("ctl00_MasterHeaderPlaceHolder_ctl00_passwordTextbox", "ctl00_MasterHeaderPlaceHolder_ctl00_tempPasswordTextbox", 2);" />

I have attached png file for the convenience.

As you can see, there are two input box related password. When I click password input tag, javascript seems to do something. But I'm not sure.

I would like to know the reason and solution.

Thanks for your time.

Please help me.

Body:
You are using CSS selector incorrectly. It needs to have an element tied to it, but you are trying to find using an attribute value.

In order for it to work you need to change your CSS selector to this.

Solution 1.

driver.find_element_by_css_selector("input[id='ctl00_MasterHeaderPlaceHolder_ctl00_tempPasswordTextbox']")

Solution 2

As the elements have name attribute, you can use  "find_element_by_name".

driver.find_element_by_name("ctl00$MasterHeaderPlaceHolder$ctl00$tempPasswordTextbox")


问:
Why 'await' requires 'async' in function definition
I'm currently learning Dart, but this is also applicable to what's going on in the JavaScript world right now, and it seems like C# also uses the same pattern.

In Dart, any function that uses await must itself be labeled asynchronous through async as follows:

```<code>import "dart:html";

main() async {
  var context = querySelector("canvas").context2D;
  var running = true;

  while (running) {
    var time = await window.animationFrame;
    ...
  }
}
</code>```

This does not make sense to me. If a function is waiting on an asynchronous function to complete, is it not then considered blocking? Why do JS and Dart require it to be labeled asynchronous? Would it not be the opposite?

To me it would make far more sense if the calling function must use the async keyword if it calls any function that also includes it in its definition. In this pattern, await would be used to convert asynchronous functions to synchronous ones.

This way would also avoid duplicate functions, since right now, libraries seem to always have func() and funcSync() or funcAsync().

答:
In Dart async indicates that the code containing await needs to be rewritten.
async/await is just syntactic sugar for the Future.then() base API, and the code is rewritten to this canonical Future based form, before it is compiled and executed.

Therefore await doesn't make code blocking.

There are also other supported markers like *sync and *async for generators.

See also
- Dart async/await internals
- https://www.dartlang.org/articles/language/await-async

Body:
I'm currently learning Dart, but this is also applicable to what's going on in the JavaScript world right now, and it seems like C# also uses the same pattern.

In Dart, any function that uses await must itself be labeled asynchronous through async as follows:

import "dart:html";

main() async {
  var context = querySelector("canvas").context2D;
  var running = true;

  while (running) {
    var time = await window.animationFrame;
    ...
  }
}

This does not make sense to me. If a function is waiting on an asynchronous function to complete, is it not then considered blocking? Why do JS and Dart require it to be labeled asynchronous? Would it not be the opposite?

To me it would make far more sense if the calling function must use the async keyword if it calls any function that also includes it in its definition. In this pattern, await would be used to convert asynchronous functions to synchronous ones.

This way would also avoid duplicate functions, since right now, libraries seem to always have func() and funcSync() or funcAsync().