问:
Removing n columns from all the files from directory in Unix
I have around 2000+ files which has random number of columns in each file.
I wanted to remove last 4 columns from each of the file.

I tried to use below command, but it is not an inline command. Delimiter of the file is #

awk -F"#" '{NF-=4;OFS="#";print}' test > testing.csv

I wanted to save the file with the same name.(e.g. filename test with test only)

How to remove last 4 columns and save the file with same name?
Can someone please help?

答:
In case you have GNU awk's latest version could you please try following.

```<code>gawk -i inplace -v INPLACE_SUFFIX=.bak 'BEGIN{FS=OFS=","} {NF-=4} 1' *.csv
</code>```

This will take backup also for each csv Input_file.

Above is safe option which has your Input_file's backup too, in case you are happy with above command and DO NOT want backup files then you could simply run following.

```<code>gawk -i inplace 'BEGIN{FS=OFS=","} {NF-=4} 1' *.csv
</code>```

NOTE: In case anyone using GNU awk version 5+ then we could use inplace::suffix='.bak' s per @Sundeep sir's comment here.

Body:
In case you have GNU awk's latest version could you please try following.

gawk -i inplace -v INPLACE_SUFFIX=.bak 'BEGIN{FS=OFS=","} {NF-=4} 1' *.csv

This will take backup also for each csv Input_file.

Above is safe option which has your Input_file's backup too, in case you are happy with above command and DO NOT want backup files then you could simply run following.

gawk -i inplace 'BEGIN{FS=OFS=","} {NF-=4} 1' *.csv

NOTE: In case anyone using GNU awk version 5+ then we could use inplace::suffix='.bak' s per @Sundeep sir's comment here.


来源: stackexchange

问:
Angular: Replacing environment.ts with configuration specific files with ng serve
I have an Angular app which uses environment.ts file to set stuff like urls of servers.

I know that I can use build configurations specified in angular.json to replace files at build time, e.g. replace environment.ts with environment.prod.ts.

I would like something similar with ng serve, e.g. launching

```<code>ng serve --configuration=production
</code>```

and having environment.prod.ts replacing environment.ts.

I this possible? Are there better ways to drive with command lines parameters which settings are used in ng serve?

答:
The one you say, ng serve --configuration=production actually replaces environment.ts with environment.prod.ts. It is already defined in Angular.

In case you want to have another replacements (i.e., more files replaced) depending on configuration, go to you angular.json and follow the structure:

Create a new configuration name under build:configurations

Fill in the fileReplacements array with your files to be replaced

Under serve:configurations create a new tag, and reference to the one you just created.

Launch serve, like: ng serve --c=configuration-name (note that --c is the same as --configuration)

Example:

{
  . . .
  "projects": {
    "your-project-name": {
      . . .
      "architect": {
        "build": {
          . . .
          "options": { . . . },
          "configurations": {
            "production": { . . .  },
            "configuration-you-want-to-create": {
              "fileReplacements": [
                {
                  "replace": "src/path-to-file.original",
                  "with": "src/path-to-file.tobereplaced"
                },
                {
                  "replace": "src/other-path-to-file.original",
                  "with": "src/other-path-to-file.tobereplaced"
                }
              ]
            }
          }
        },
        "serve": {
          . . .
          "options": {. . .},
          "configurations": {
            "production": { . . .},
            "configuration-you-want-to-create": {
              "browserTarget": "your-project-name:build:configuration-you-want-to-create"
            }
          }
        },
        . . .
      }
    }},
  . . .
}
```

ContentLicense: CC BY-SA 4.0

Body:
I have an Angular app which uses environment.ts file to set stuff like urls of servers.

I know that I can use build configurations specified in angular.json to replace files at build time, e.g. replace environment.ts with environment.prod.ts.

I would like something similar with ng serve, e.g. launching

ng serve --configuration=production

and having environment.prod.ts replacing environment.ts.

I this possible? Are there better ways to drive with command lines parameters which settings are used in ng serve?


问:
JavaScript Password Generator Numerical Problem
i've just start a coding boot camp and for our third assignment we had to code a Random Password Generator with a few user preferences. i wrote my code and everything work apart from one bit. When the user only chooses to have numerical values an error is given where my selection pool of characters tells me that "pSelection.charAt is not a function at generatePWD".

It makes no sense to me at all considering that function works perfectly in every other situation. I've tried making a separate array for the specific (else if) Statement that is failing. I've tried swapping variable names in case of a clash of "Char".

If someone could have a look and tell me what I've done wrong i'd appreciate the help because i thought i understood what was going on but apparently not..

Here's the JavaScript - Below is the HTML

```<code>// Add event listener to the generate button
document.getElementById("generate").addEventListener("click", function(){

// Setting up the possible Characters
  var lowercaseAlphabetChar = ("abcdefghijklmnopqrstuvwxyz");
  var uppercaseAlphabetChar = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
  var numericChar = (1234567890);
  var specialChar = ("!@#$%^&*()?~/|:'><");
  var password = "";
  var pSelection = "";

// User Prompts
  var length = prompt("How long is your Password? Choose between 8 and 128 Characters");

// Making sure User Chooses between 8 and 128 Characters
  if (length < 8 || length > 128){
    alert("Length has to be Between 8 and 128. Please Try Again")
    return
  }

  var wantsLower = confirm("Do you want Lowercase Characters?")
  var wantsUpper = confirm("Do you want Uppercase Characters?")
  var wantsNumbers = confirm("Do you want Numerical Characters?")
  var wantsSpecial = confirm("Do you want Special Characters?")

//Verification Points System - I allocate a point when an option is confirmed. if no points are allocated, user has not selected anything
  var verify = 0;

  if (wantsLower == true || wantsUpper == true || wantsNumbers == true || wantsSpecial == true) {
    verify += 1;
  }

  if (verify == 0) {
    alert("You have not selected a character Type, Please Try again.")
    return
  }

// Script will exit if not verified, if verified we Proceed to Grouping Password to User Needs.
  function generatePWD() {
    for (var i = 0; i <= length; i++) {
      password = password + pSelection.charAt(Math.floor(Math.random() * Math.floor(pSelection.length - 1)));
    }
  }

// IF STATEMENTS for User PreferenceLowerCase
  if (wantsLower && !wantsUpper && !wantsNumbers && !wantsSpecial) {
    pSelection = lowercaseAlphabetChar;
    generatePWD();
  }
// LowerCase and UpperCase
  else if (wantsLower && wantsUpper && !wantsNumbers && !wantsSpecial) {
    pSelection = lowercaseAlphabetChar + uppercaseAlphabetChar;
    generatePWD();
  }

//LowerCase and UpperCase and Numbers
  else if (wantsLower && wantsUpper && wantsNumbers && !wantsSpecial) {
    pSelection = lowercaseAlphabetChar + uppercaseAlphabetChar + numericChar;
    generatePWD();
  }
// Everything
  else if (wantsLower && wantsUpper && wantsNumbers && wantsSpecial) {
    pSelection = lowercaseAlphabetChar + uppercaseAlphabetChar + numericChar + specialChar;
    generatePWD();
  }
//Lowercase and Numbers
  else if (wantsLower && !wantsUpper && wantsNumbers && !wantsSpecial) {
    pSelection = lowercaseAlphabetChar + numericChar;
    generatePWD();
  }
//Lowercase and Numbers and Special
  else if (wantsLower && !wantsUpper && wantsNumbers && wantsSpecial) {
    pSelection = lowercaseAlphabetChar + numericChar + specialChar;
    generatePWD();
  }
// Lowercase and Special
  else if (wantsLower && !wantsUpper && !wantsNumbers && wantsSpecial) {
    pSelection = lowercaseAlphabetChar + specialChar;
    generatePWD();
  }
// Uppercase
  else if (!wantsLower && wantsUpper && !wantsNumbers && !wantsSpecial) {
    pSelection = uppercaseAlphabetChar;
    generatePWD();
  }
// UpperCase and Numbers
  else if (!wantsLower && wantsUpper && wantsNumbers && !wantsSpecial) {
    pSelection = uppercaseAlphabetChar + numericChar;
    generatePWD();
  }

// Uppercase and Numbers and Special
  else if (!wantsLower && wantsUpper && wantsNumbers && wantsSpecial) {
    pSelection = uppercaseAlphabetChar + numericChar + specialChar;
    generatePWD();
  }
// Uppercase and Special
  else if (!wantsLower && wantsUpper && !wantsNumbers && wantsSpecial) {
    pSelection = uppercaseAlphabetChar + specialChar;
    generatePWD();
  }
// Numbers
  else if (!wantsLower && !wantsUpper && wantsNumbers && !wantsSpecial) {
    pSelection = numericChar;
    generatePWD();
  }
// Numbers and Special
  else if (!wantsLower && !wantsUpper && wantsNumbers && wantsSpecial) {
    pSelection = numericChar + specialChar;
    generatePWD();
  }
// Special
  else if (!wantsLower && !wantsUpper && !wantsNumbers && wantsSpecial) {
    pSelection = specialChar;
    generatePWD();
  }
  document.getElementById("password").innerHTML = password;
  console.log(password);

});
</code>```

HTML

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Password Generator</title>
    <link rel="stylesheet" href="assets/style.css" />
  </head>
  <body>
    <div class="wrapper">
      <header>
        <h1>Password Generator</h1>
      </header>
      <div class="card">
        <div class="card-header">
          <h2>Generate a Password</h2>
        </div>
        <div class="card-body">
          <textarea
            readonly
            id="password"
            placeholder="Your Secure Password"
            aria-label="Generated Password"
          ></textarea>
        </div>
        <div class="card-footer">
          <button id="generate" class="btn">Generate Password</button>
        </div>
      </div>
    </div>

    <script src="assets/script.js"></script>
  </body>
</html>
</code>```

答:
numericChar needs to be a string i.e. "1234567890" - as it is, you've got it initialised with a number.

If you change the declaration of the variable to

var numericChar = "1234567890";

Then it should work :)

Body:
i've just start a coding boot camp and for our third assignment we had to code a Random Password Generator with a few user preferences. i wrote my code and everything work apart from one bit. When the user only chooses to have numerical values an error is given where my selection pool of characters tells me that "pSelection.charAt is not a function at generatePWD".

It makes no sense to me at all considering that function works perfectly in every other situation. I've tried making a separate array for the specific (else if) Statement that is failing. I've tried swapping variable names in case of a clash of "Char".

If someone could have a look and tell me what I've done wrong i'd appreciate the help because i thought i understood what was going on but apparently not..

Here's the JavaScript - Below is the HTML

// Add event listener to the generate button
document.getElementById("generate").addEventListener("click", function(){

// Setting up the possible Characters
  var lowercaseAlphabetChar = ("abcdefghijklmnopqrstuvwxyz");
  var uppercaseAlphabetChar = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
  var numericChar = (1234567890);
  var specialChar = ("!@#$%^&*()?~/|:'><");
  var password = "";
  var pSelection = "";

// User Prompts
  var length = prompt("How long is your Password? Choose between 8 and 128 Characters");

// Making sure User Chooses between 8 and 128 Characters
  if (length < 8 || length > 128){
    alert("Length has to be Between 8 and 128. Please Try Again")
    return
  }

  var wantsLower = confirm("Do you want Lowercase Characters?")
  var wantsUpper = confirm("Do you want Uppercase Characters?")
  var wantsNumbers = confirm("Do you want Numerical Characters?")
  var wantsSpecial = confirm("Do you want Special Characters?")

//Verification Points System - I allocate a point when an option is confirmed. if no points are allocated, user has not selected anything
  var verify = 0;

  if (wantsLower == true || wantsUpper == true || wantsNumbers == true || wantsSpecial == true) {
    verify += 1;
  }

  if (verify == 0) {
    alert("You have not selected a character Type, Please Try again.")
    return
  }

// Script will exit if not verified, if verified we Proceed to Grouping Password to User Needs.
  function generatePWD() {
    for (var i = 0; i <= length; i++) {
      password = password + pSelection.charAt(Math.floor(Math.random() * Math.floor(pSelection.length - 1)));
    }
  }

// IF STATEMENTS for User PreferenceLowerCase
  if (wantsLower && !wantsUpper && !wantsNumbers && !wantsSpecial) {
    pSelection = lowercaseAlphabetChar;
    generatePWD();
  }
// LowerCase and UpperCase
  else if (wantsLower && wantsUpper && !wantsNumbers && !wantsSpecial) {
    pSelection = lowercaseAlphabetChar + uppercaseAlphabetChar;
    generatePWD();
  }

//LowerCase and UpperCase and Numbers
  else if (wantsLower && wantsUpper && wantsNumbers && !wantsSpecial) {
    pSelection = lowercaseAlphabetChar + uppercaseAlphabetChar + numericChar;
    generatePWD();
  }
// Everything
  else if (wantsLower && wantsUpper && wantsNumbers && wantsSpecial) {
    pSelection = lowercaseAlphabetChar + uppercaseAlphabetChar + numericChar + specialChar;
    generatePWD();
  }
//Lowercase and Numbers
  else if (wantsLower && !wantsUpper && wantsNumbers && !wantsSpecial) {
    pSelection = lowercaseAlphabetChar + numericChar;
    generatePWD();
  }
//Lowercase and Numbers and Special
  else if (wantsLower && !wantsUpper && wantsNumbers && wantsSpecial) {
    pSelection = lowercaseAlphabetChar + numericChar + specialChar;
    generatePWD();
  }
// Lowercase and Special
  else if (wantsLower && !wantsUpper && !wantsNumbers && wantsSpecial) {
    pSelection = lowercaseAlphabetChar + specialChar;
    generatePWD();
  }
// Uppercase
  else if (!wantsLower && wantsUpper && !wantsNumbers && !wantsSpecial) {
    pSelection = uppercaseAlphabetChar;
    generatePWD();
  }
// UpperCase and Numbers
  else if (!wantsLower && wantsUpper && wantsNumbers && !wantsSpecial) {
    pSelection = uppercaseAlphabetChar + numericChar;
    generatePWD();
  }

// Uppercase and Numbers and Special
  else if (!wantsLower && wantsUpper && wantsNumbers && wantsSpecial) {
    pSelection = uppercaseAlphabetChar + numericChar + specialChar;
    generatePWD();
  }
// Uppercase and Special
  else if (!wantsLower && wantsUpper && !wantsNumbers && wantsSpecial) {
    pSelection = uppercaseAlphabetChar + specialChar;
    generatePWD();
  }
// Numbers
  else if (!wantsLower && !wantsUpper && wantsNumbers && !wantsSpecial) {
    pSelection = numericChar;
    generatePWD();
  }
// Numbers and Special
  else if (!wantsLower && !wantsUpper && wantsNumbers && wantsSpecial) {
    pSelection = numericChar + specialChar;
    generatePWD();
  }
// Special
  else if (!wantsLower && !wantsUpper && !wantsNumbers && wantsSpecial) {
    pSelection = specialChar;
    generatePWD();
  }
  document.getElementById("password").innerHTML = password;
  console.log(password);

});

HTML

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Password Generator</title>
    <link rel="stylesheet" href="assets/style.css" />

Password Generator

Generate a Password

          <textarea
            readonly
            id="password"
            placeholder="Your Secure Password"
            aria-label="Generated Password"
          ></textarea>

          <button id="generate" class="btn">Generate Password</button>


问:
Add items to an existing list mvc5
(I am a new developer)I have a list that I put in a viewBag to make a dropwdown in my view and I would like to add 3 elements to this list so that we can see them at the end of my dropdown. I make a timesheet for the employees and I have a dropdown of the projects that the person worked during the week and I would like to add at the end of the dropdown the 3 options "Vacancy", "Unplanned Absence", "Planned Absence" if the person has been on leave instead of working.

This is my request for the projects :

```<code>var projectAssignment = (from pa in db.ProjectAssignment
                                     join p in db.Projects on pa.ProjectId equals p.ID
                                     where pa.EmployeeId == EmployeeId && pa.StartDate !=null && (pa.EndDate == null || pa.EndDate >= DateTime.Now)
                                     select new ProjectTimesheetList
                                     {
                                         ProjectName = p.ProjectName,
                                         ProjectId = pa.ProjectId
                                     });
ViewBag.ProjectTimeSHeet = projectAssignment;
</code>```

This is a the modal to add my timehseet and i want to put the 3 daysoff type at the end of dropdown, so in this case after "NatureBooker"

And this is my code of my dropdown:

```<code><select name="' + row + '_' + col + '" class="custom-select" id="tsCell_' + row + '_' + col + '" data-row="' + row + '" data-col="' + col + '">' +
                    '<option value="">----Select----</option>@Html.Raw(projsStr)</select>';
</code>```

SOLUTION:

```<code>var projectAssignment = (from pa in db.ProjectAssignment
                                     join p in db.Projects on pa.ProjectId equals p.ID
                                     where pa.EmployeeId == EmployeeId && pa.StartDate !=null && (pa.EndDate == null || pa.EndDate >= DateTime.Now)
                                     select new ProjectTimesheetList
                                     {
                                         ProjectName = p.ProjectName,
                                         ProjectId = pa.ProjectId
                                     });

            List<ProjectTimesheetList> projectAssignments = projectAssignment.ToList();

            projectAssignments.Add(new ProjectTimesheetList
            {
                ProjectName = "Vacancy",
                ProjectId = -1,
            });

            projectAssignments.Add(new ProjectTimesheetList
            {
                ProjectName = "Unplanned Absence",
                ProjectId = -2,
            });

            projectAssignments.Add(new ProjectTimesheetList
            {
                ProjectName = "Planned Absence",
                ProjectId = -3,
            });

            ViewBag.ProjectTimeSHeet = projectAssignments;
</code>```

And the result:

答:
Still not clear what exactly you want, but if my guess is right you probably want to add "fake" projects to the enumerable you're binding to (not a list, by the way).

As long as you understand that this is absolutely wrong and grounds for being fired on the spot, here you go:

```<code>ViewBag.ProjectTimeSHeet = projectAssignment
    .Concat(new[]
        {
            new ProjectTimesheetList
            {
                ProjectName = "Vacancy",
                ProjectId = -1,
            },
            new ProjectTimesheetList
            {
                ProjectName = "Unplanned Absence",
                ProjectId = -2,
            },
            new ProjectTimesheetList
            {
                ProjectName = "Planned Absence",
                ProjectId = -3,
            },
        });
</code>```

Title: Add items to an existing list mvc5

Body:
(I am a new developer)I have a list that I put in a viewBag to make a dropwdown in my view and I would like to add 3 elements to this list so that we can see them at the end of my dropdown. I make a timesheet for the employees and I have a dropdown of the projects that the person worked during the week and I would like to add at the end of the dropdown the 3 options "Vacancy", "Unplanned Absence", "Planned Absence" if the person has been on leave instead of working.

This is my request for the projects :

var projectAssignment = (from pa in db.ProjectAssignment
                                     join p in db.Projects on pa.ProjectId equals p.ID
                                     where pa.EmployeeId == EmployeeId && pa.StartDate !=null && (pa.EndDate == null || pa.EndDate >= DateTime.Now)
                                     select new ProjectTimesheetList
                                     {
                                         ProjectName = p.ProjectName,
                                         ProjectId = pa.ProjectId
                                     });
ViewBag.ProjectTimeSHeet = projectAssignment;

This is a the modal to add my timehseet and i want to put the 3 daysoff type at the end of dropdown, so in this case after "NatureBooker"

And this is my code of my dropdown:

<select name="' + row + '_' + col + '" class="custom-select" id="tsCell_' + row + '_' + col + '" data-row="' + row + '" data-col="' + col + '">' +
                    '<option value="">----Select----</option>@Html.Raw(projsStr)</select>';

SOLUTION:

var projectAssignment = (from pa in db.ProjectAssignment
                                     join p in db.Projects on pa.ProjectId equals p.ID
                                     where pa.EmployeeId == EmployeeId && pa.StartDate !=null && (pa.EndDate == null || pa.EndDate >= DateTime.Now)
                                     select new ProjectTimesheetList
                                     {
                                         ProjectName = p.ProjectName,
                                         ProjectId = pa.ProjectId
                                     });

            List<ProjectTimesheetList> projectAssignments = projectAssignment.ToList();

            projectAssignments.Add(new ProjectTimesheetList
            {
                ProjectName = "Vacancy",
                ProjectId = -1,
            });

            projectAssignments.Add(new ProjectTimesheetList
            {
                ProjectName = "Unplanned Absence",
                ProjectId = -2,
            });

            projectAssignments.Add(new ProjectTimesheetList
            {
                ProjectName = "Planned Absence",
                ProjectId = -3,
            });

            ViewBag.ProjectTimeSHeet = projectAssignments;

And the result:

Body:
Still not clear what exactly you want, but if my guess is right you probably want to add "fake" projects to the enumerable you're binding to (not a list, by the way).

As long as you understand that this is absolutely wrong and grounds for being fired on the spot, here you go:

ViewBag.ProjectTimeSHeet = projectAssignment
    .Concat(new[]
        {
            new ProjectTimesheetList
            {
                ProjectName = "Vacancy",
                ProjectId = -1,
            },
            new ProjectTimesheetList
            {
                ProjectName = "Unplanned Absence",
                ProjectId = -2,
            },
            new ProjectTimesheetList
            {
                ProjectName = "Planned Absence",
                ProjectId = -3,
            },
        });


问:
NSURLConnection download large file (>40MB)
I need to download large file (i.e. > 40MB) to my application from server, this file will be ZIP or PDF. I achieved it using NSURLConnection, that works well if the file is smaller other wise it download a part of the fill and the execution has stopped. for example I  tried to download 36MB PDF file, but but 16MB only downloaded. pls help me to know the reason? how to fix it?

FYI:
Implementation File

```<code>#import "ZipHandlerV1ViewController.h"
@implementation ZipHandlerV1ViewController
- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
 - (void)viewDidLoad
 {
     UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 400, 400)];
     [mainView setBackgroundColor:[UIColor darkGrayColor]];

     UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
     [downloadButton setFrame:CGRectMake(50, 50, 150, 50)];
     [downloadButton setTitle:@"Download File" forState:UIControlStateNormal];
     [downloadButton addTarget:self action:@selector(downloadFileFromURL:) forControlEvents:UIControlEventTouchUpInside];
     [mainView addSubview:downloadButton];

     [self setRequestURL:@"http://www.mobileveda.com/r_d/mcps/optimized_av_allpdf.pdf"];
     [self.view addSubview:mainView];

     [super viewDidLoad];
 }

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void) setRequestURL:(NSString*) requestURL {
    url = requestURL;
}

-(void) downloadFileFromURL:(id) sender {
    NSURL *reqURL =  [NSURL URLWithString:url];

    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:reqURL];
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection) {
       webData = [[NSMutableData data] retain];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error !" message:@"Error has occured, please verify internet connection"  delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];

        [alert show];
        [alert release];
    }
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [webData setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [webData appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
   NSString *fileName = [[[NSURL URLWithString:url] path] lastPathComponent];
    NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *folder = [pathArr objectAtIndex:0];

    NSString *filePath = [folder stringByAppendingPathComponent:fileName];
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    NSError *writeError = nil;

    [webData writeToURL: fileURL options:0 error:&writeError];
    if( writeError) {
        NSLog(@" Error in writing file %@' : \n %@ ", filePath , writeError );
        return;
    }
    NSLog(@"%@",fileURL);
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error !" message:@"Error has occured, please verify internet connection.."  delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];

    [alert show];
    [alert release];

}

@end
</code>```

Header File:

```<code>#import <UIKit/UIKit.h>
@interface ZipHandlerV1ViewController : UIViewController {
    NSMutableData *webData;
    NSString *url;
}
-(void) setRequestURL:(NSString*) requestURL;
@end
</code>```

Thank you,

Updated:
This happens because of my downloadable file was in shared hosting which having the download limitations. After I moved that file to dedicated server that working fine. and also I tried to download some other files like videos from some other sites, that also working fine.
So, if you having problem like partial download, don't only stick with the code, check the server too

答:
You are currently keeping all downloaded data in a NSMutableData object which is kept within the RAM of your device. That will, depending on the device and the available memory, at some point trigger a memory warning or even a crash.

To get such large downloads to work, you will have to write all downloaded data directly to the filesystem.

```<code>-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
   //try to access that local file for writing to it...
   NSFileHandle *hFile = [NSFileHandle fileHandleForWritingAtPath:self.localPath];
   //did we succeed in opening the existing file?
   if (!hFile)
   {   //nope->create that file!
       [[NSFileManager defaultManager] createFileAtPath:self.localPath contents:nil attributes:nil];
       //try to open it again...
       hFile = [NSFileHandle fileHandleForWritingAtPath:self.localPath];
   }
   //did we finally get an accessable file?
   if (!hFile)
   {   //nope->bomb out!
       NSLog("could not write to file %@", self.localPath);
       return;
   }
   //we never know - hence we better catch possible exceptions!
   @try
   {
       //seek to the end of the file
       [hFile seekToEndOfFile];
       //finally write our data to it
       [hFile writeData:data];
   }
   @catch (NSException * e)
   {
       NSLog("exception when writing to file %@", self.localPath);
       result = NO;
   }
   [hFile closeFile];
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to download large file (i.e. > 40MB) to my application from server, this file will be ZIP or PDF. I achieved it using NSURLConnection, that works well if the file is smaller other wise it download a part of the fill and the execution has stopped. for example I  tried to download 36MB PDF file, but but 16MB only downloaded. pls help me to know the reason? how to fix it?

FYI:
Implementation File

#import "ZipHandlerV1ViewController.h"
@implementation ZipHandlerV1ViewController
- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
 - (void)viewDidLoad
 {
     UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 400, 400)];
     [mainView setBackgroundColor:[UIColor darkGrayColor]];

     UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
     [downloadButton setFrame:CGRectMake(50, 50, 150, 50)];
     [downloadButton setTitle:@"Download File" forState:UIControlStateNormal];
     [downloadButton addTarget:self action:@selector(downloadFileFromURL:) forControlEvents:UIControlEventTouchUpInside];
     [mainView addSubview:downloadButton];

     [self setRequestURL:@"http://www.mobileveda.com/r_d/mcps/optimized_av_allpdf.pdf"];
     [self.view addSubview:mainView];

     [super viewDidLoad];
 }

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void) setRequestURL:(NSString*) requestURL {
    url = requestURL;
}

-(void) downloadFileFromURL:(id) sender {
    NSURL *reqURL =  [NSURL URLWithString:url];

    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:reqURL];
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection) {
       webData = [[NSMutableData data] retain];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error !" message:@"Error has occured, please verify internet connection"  delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];

        [alert show];
        [alert release];
    }
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [webData setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [webData appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
   NSString *fileName = [[[NSURL URLWithString:url] path] lastPathComponent];
    NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *folder = [pathArr objectAtIndex:0];

    NSString *filePath = [folder stringByAppendingPathComponent:fileName];
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    NSError *writeError = nil;

    [webData writeToURL: fileURL options:0 error:&writeError];
    if( writeError) {
        NSLog(@" Error in writing file %@' : \n %@ ", filePath , writeError );
        return;
    }
    NSLog(@"%@",fileURL);
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error !" message:@"Error has occured, please verify internet connection.."  delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];

    [alert show];
    [alert release];

}

@end

Header File:

#import <UIKit/UIKit.h>
@interface ZipHandlerV1ViewController : UIViewController {
    NSMutableData *webData;
    NSString *url;
}
-(void) setRequestURL:(NSString*) requestURL;
@end

Thank you,

Updated:
This happens because of my downloadable file was in shared hosting which having the download limitations. After I moved that file to dedicated server that working fine. and also I tried to download some other files like videos from some other sites, that also working fine.
So, if you having problem like partial download, don't only stick with the code, check the server too

Body:
You are currently keeping all downloaded data in a NSMutableData object which is kept within the RAM of your device. That will, depending on the device and the available memory, at some point trigger a memory warning or even a crash.

To get such large downloads to work, you will have to write all downloaded data directly to the filesystem.

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
   //try to access that local file for writing to it...
   NSFileHandle *hFile = [NSFileHandle fileHandleForWritingAtPath:self.localPath];
   //did we succeed in opening the existing file?
   if (!hFile)
   {   //nope->create that file!
       [[NSFileManager defaultManager] createFileAtPath:self.localPath contents:nil attributes:nil];
       //try to open it again...
       hFile = [NSFileHandle fileHandleForWritingAtPath:self.localPath];
   }
   //did we finally get an accessable file?
   if (!hFile)
   {   //nope->bomb out!
       NSLog("could not write to file %@", self.localPath);
       return;
   }
   //we never know - hence we better catch possible exceptions!
   @try
   {
       //seek to the end of the file
       [hFile seekToEndOfFile];
       //finally write our data to it
       [hFile writeData:data];
   }
   @catch (NSException * e)
   {
       NSLog("exception when writing to file %@", self.localPath);
       result = NO;
   }
   [hFile closeFile];
}


问:
Display List entries that match user input value
I am a newbie to python 3 and am creating a collection programme and it consists of different types of items. I am having trouble at constructing lines of code to show items by category and deleting an entry. I'm currently trying to create an option where the user can input a type (for example Phone) and the list will show all list entries that have been added and stored as phone in the item_type.

I wrote this code, and the Show category & Delete item sections do not work. Can someone help me understand what is wrong with the code formulation:

```<code>def show_items():
    print("{0:3}\t{1:10}\t{2:10}\t{3:10}".format("ID", "Item", "Date added", 'Date manufactured'))
    for i in Item.py_collection_list:
        print("{0:03d}\t{1:10}\t{2:10}\t{3:10}".format(i.get_id(), i.item_name, i.date_add, i.dom))
    response = input('Press [x] to go back to main menu or press [c] to view items by type ')
    if response == 'c':
        show_category()

def show_category():
    item_types = {"Computer": [], "Camera": [], "Phone": [], "Video Player": []}
    print()
    print('View items by type \nComputer | Camera | Phone | Video Player > ')
    response = input('Type> ')
    if response in item_types:
        print(item_types[response])
</code>```

答:
I am not sure what you are trying to obtain with Item.py_collection_list.
A far easier way to solve this problem would be to use a dictionary.
Something like:

```<code>def show_category():
    all_items = {"Phone":["iPhone","OtherBrand0","OtherBrand1"], "Computer":["Asus","MSI","OtherBrand"]} # add {type: [list of products]}
    print()
    print('View items by type \nComputer | Camera | Phone | Video Player > ')
    response = input('Type> ')
    if response in all_items.keys():
        print(all_items[response]) # or whatever
</code>```

Body:
I am a newbie to python 3 and am creating a collection programme and it consists of different types of items. I am having trouble at constructing lines of code to show items by category and deleting an entry. I'm currently trying to create an option where the user can input a type (for example Phone) and the list will show all list entries that have been added and stored as phone in the item_type.

I wrote this code, and the Show category & Delete item sections do not work. Can someone help me understand what is wrong with the code formulation:

def show_items():
    print("{0:3}\t{1:10}\t{2:10}\t{3:10}".format("ID", "Item", "Date added", 'Date manufactured'))
    for i in Item.py_collection_list:
        print("{0:03d}\t{1:10}\t{2:10}\t{3:10}".format(i.get_id(), i.item_name, i.date_add, i.dom))
    response = input('Press [x] to go back to main menu or press [c] to view items by type ')
    if response == 'c':
        show_category()

def show_category():
    item_types = {"Computer": [], "Camera": [], "Phone": [], "Video Player": []}
    print()
    print('View items by type \nComputer | Camera | Phone | Video Player > ')
    response = input('Type> ')
    if response in item_types:
        print(item_types[response])

Body:
I am not sure what you are trying to obtain with Item.py_collection_list.
A far easier way to solve this problem would be to use a dictionary.
Something like:

def show_category():
    all_items = {"Phone":["iPhone","OtherBrand0","OtherBrand1"], "Computer":["Asus","MSI","OtherBrand"]} # add {type: [list of products]}
    print()
    print('View items by type \nComputer | Camera | Phone | Video Player > ')
    response = input('Type> ')
    if response in all_items.keys():
        print(all_items[response]) # or whatever


问:
Why console.log shows correct array but the state is wrong (ReactJS)
I have a component which is address of company. Each address is an object which is consists of two fields address and metro. (I get rid of some code with declaring Props and State because it doesn't matter)

```<code>class CompanyAddress extends React.Component<Props, State> {
    constructor(props:Props) {
        super(props);
        this.state = {address:''}
    }

    changeAddress = (text:string) => {
        this.setState({address: text});
        this.props.changeAddress(this.props.index, text, this.state.metro);
    }

    changeMetro = (metro:{id: Number, name: string}) => {
        this.setState({metro:metro});
        this.props.changeAddress(this.props.index, this.state.address, metro.id);
    }

    render() {
        return (
            <View style={styles.container}>
                <TextInput
                    autoCompleteType="name"
                    placeholder={("address " + (this.props.num))}
                    maxLength={50}
                    style={[styles.address, {marginTop: 5}]}
                    onChangeText={(text) => { this.changeAddress(text)}}
                />

                <TouchableOpacity
                    style={styles.address}
                    onPress={() => this.props.navigation.navigate('MetroList', {changeMetro: this.changeMetro})}
                >
                    {this.state.metro ? (
                        <Text style={[styles.metroText, {color: 'black'}]}>
                            {this.state.metro.name}
                        </Text>
                    ) : (
                        <Text style={styles.metroText}>
                            Nearest metro
                        </Text>
                    )}
                </TouchableOpacity>

                {this.props.num != 1 ? (
                    <AntDesign
                        onPress={() => {this.props.removeAddress(this.props.index)}}
                        style={styles.minus}
                        name="minus"
                        size={24}
                        color="black"
                    />
                ) : null}
            </View>
        );
    }
}
</code>```

I also have parrent component with array of addreses and 3 methods addAddress, changeAddress and removeAddress.

```<code>class CompanyAddresses extends React.Component<Props, State> {
    constructor(props:Props) {
        super(props);

        this.state = {
            addresses: [{address: ''}]
        }
    }

    addAddress = () => {
        this.setState({addresses: [...this.state.addresses, {address: ''}]});
    }

    changeAddress = (elemIndex:number, address:string, metro:number) => {
        let addresses = this.state.addresses;

        addresses[elemIndex] = {address: address, metro: metro};
        this.setState({addresses:addresses});
    }

    removeAddress = (elemIndex:number) => {
        const filtered = this.state.addresses.filter((value, index) => {
           return index != elemIndex;
        });

        console.log(filtered);

        this.setState({addresses: filtered})
    }

    render() {
        return (
            <View style={styles.container}>
                {this.state.addresses.map((address:any, index) =>
                    <CompanyAddress
                        changeAddress={this.changeAddress}
                        removeAddress={this.removeAddress}
                        navigation={this.props.navigation}
                        key={index}
                        index={index}
                        num={index + 1}
                    />
                )}
                {this.state.addresses.length < 5 ? (
                    <Button title="add address" onPress={this.addAddress} />
                ) : null}
            </View>
        );
    }
}
</code>```

addAdress and changeAddress work well but removeAddress does not. This method doest not render right addresses after render.

For example, I added 3 addresses with name "one", "two" and "three". Then I removed address with name "two" but I see two adresses with name "one" and "two".

The most ineteresting thing is the fact that I see correct array with addresses "one" and "three" in console just before setState method.

答:
The state is almost certainly being updated correctly. The issue you're seeing is due to the fact that your key inside the map is the index of the array. You can see in the docs that using the index as the key is not recommended, and this is a major reason.

We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state.

You've modified the array so that what was at index 2 is now at index 1. This causes react to think that only the third item should be removed, and nothing else needs to change.

Body:
I have a component which is address of company. Each address is an object which is consists of two fields address and metro. (I get rid of some code with declaring Props and State because it doesn't matter)

class CompanyAddress extends React.Component<Props, State> {
    constructor(props:Props) {
        super(props);
        this.state = {address:''}
    }

    changeAddress = (text:string) => {
        this.setState({address: text});
        this.props.changeAddress(this.props.index, text, this.state.metro);
    }

    changeMetro = (metro:{id: Number, name: string}) => {
        this.setState({metro:metro});
        this.props.changeAddress(this.props.index, this.state.address, metro.id);
    }

    render() {
        return (
            <View style={styles.container}>
                <TextInput
                    autoCompleteType="name"
                    placeholder={("address " + (this.props.num))}
                    maxLength={50}
                    style={[styles.address, {marginTop: 5}]}
                    onChangeText={(text) => { this.changeAddress(text)}}
                />

                <TouchableOpacity
                    style={styles.address}
                    onPress={() => this.props.navigation.navigate('MetroList', {changeMetro: this.changeMetro})}
                >
                    {this.state.metro ? (
                        <Text style={[styles.metroText, {color: 'black'}]}>
                            {this.state.metro.name}
                        </Text>
                    ) : (
                        <Text style={styles.metroText}>
                            Nearest metro
                        </Text>
                    )}
                </TouchableOpacity>

                {this.props.num != 1 ? (
                    <AntDesign
                        onPress={() => {this.props.removeAddress(this.props.index)}}
                        style={styles.minus}
                        name="minus"
                        size={24}
                        color="black"
                    />
                ) : null}
            </View>
        );
    }
}

I also have parrent component with array of addreses and 3 methods addAddress, changeAddress and removeAddress.

class CompanyAddresses extends React.Component<Props, State> {
    constructor(props:Props) {
        super(props);

        this.state = {
            addresses: [{address: ''}]
        }
    }

    addAddress = () => {
        this.setState({addresses: [...this.state.addresses, {address: ''}]});
    }

    changeAddress = (elemIndex:number, address:string, metro:number) => {
        let addresses = this.state.addresses;

        addresses[elemIndex] = {address: address, metro: metro};
        this.setState({addresses:addresses});
    }

    removeAddress = (elemIndex:number) => {
        const filtered = this.state.addresses.filter((value, index) => {
           return index != elemIndex;
        });

        console.log(filtered);

        this.setState({addresses: filtered})
    }

    render() {
        return (
            <View style={styles.container}>
                {this.state.addresses.map((address:any, index) =>
                    <CompanyAddress
                        changeAddress={this.changeAddress}
                        removeAddress={this.removeAddress}
                        navigation={this.props.navigation}
                        key={index}
                        index={index}
                        num={index + 1}
                    />
                )}
                {this.state.addresses.length < 5 ? (
                    <Button title="add address" onPress={this.addAddress} />
                ) : null}
            </View>
        );
    }
}

addAdress and changeAddress work well but removeAddress does not. This method doest not render right addresses after render.

For example, I added 3 addresses with name "one", "two" and "three". Then I removed address with name "two" but I see two adresses with name "one" and "two".

The most ineteresting thing is the fact that I see correct array with addresses "one" and "three" in console just before setState method.


答:
Assuming that you have a list of all entries as a dictionary with one of the keys being "item_type", a simple list comprehension can do the job.

```<code>entries = [entry for entry in allEntries if entry["item_type"]==response]
</code>```

This is equivalent to writing the following

```<code>entries = []
for entry in allEntries:
  if entry["item_type"] == response:
    matches.append(c)
</code>```

Title: Display List entries that match user input value

Body:
Assuming that you have a list of all entries as a dictionary with one of the keys being "item_type", a simple list comprehension can do the job.

entries = [entry for entry in allEntries if entry["item_type"]==response]

This is equivalent to writing the following

entries = []
for entry in allEntries:
  if entry["item_type"] == response:
    matches.append(c)


问:
Achieve Truncate and Copy in single transaction using Python + Redshift
I do realize that Redshift commits the transaction in which it is run.

But I wanted to achieve something like:

```<code>BEGIN TX;
TRUNCATE TABLE t1;
COPY FROM S3;
rollback;
</code>```

But I was wondering if there is a way to achieve a similar behavior.

答:
In Redshift TRUNCATE performs an implicit commit and therefore cannot be run inside an explicit BEGIN..END transaction.

You can consider using either of the following inside your transaction as an alternative:

DELETE FROM t1;

CREATE TABLE t2 (LIKE t1); DROP TABLE t1; ALTER TABLE t2 RENAME TO t1;

Body:
I do realize that Redshift commits the transaction in which it is run.

But I wanted to achieve something like:

BEGIN TX;
TRUNCATE TABLE t1;
COPY FROM S3;
rollback;

But I was wondering if there is a way to achieve a similar behavior.


问:
Caching - .NET Core equivalents of .NET Framework classes
Looking to understand some of the changes in .NET Core vs .NET Framework and the area I'm looking at is caching. In Framework - in the System.Runtime.Caching namespace - there are the CacheItem(which represented an individual cache entry in the cache) and CacheItemPolicy(representing a set of eviction and expiration details for a specific cache entry) classes.

From my initial look at this these two classes appear not to have made it across to Core, but are there some (differently named) equivalents to them that I'm just not finding?

答: CacheItem and CacheItemPolicy are there in all versions - you may need the package from NuGet: https://www.nuget.org/packages/System.Runtime.Caching/4.7.0


问:
How to convert HQL to SQL Query programmatically (without logging)
I am executing the following HQL and it is executing properly

```<code>String hql = "FROM Employee";
Query query = session.createQuery(hql);
List results = query.list();
</code>```

Now, I also want to log the sql generated at the backend in logs for support users.

I want to make use of QueryTranslator please advise how can I generate the sql for the corresponding HQL please advise how to achieve this.

答:
Hibernate Types

Starting with the 2.9.11 version, the Hibernate Types open-source project offers the SQLExtractor utility that allows you to get the SQL query from any JPQL or Criteria API query, no matter you are using Hibernate 5.4, 5.3, 5.2, 5.1, 5.0, 4.3, 4.2, or 4.1.

Get the SQL statement from a JPQL (HQL) Query

Let's assume we have the following JPQL (HQL) query:

```<code>Query jpql = entityManager.createQuery("""
    select
       YEAR(p.createdOn) as year,
       count(p) as postCount
    from
       Post p
    group by
       YEAR(p.createdOn)
    """, Tuple.class
);
</code>```

With Hibernate Types, extracting the Hibernate-generated SQL query is as simple as that:

```<code>String sql = SQLExtractor.from(jpql);
</code>```

And, if we log the extracted SQL query:

```<code>LOGGER.info("""
    The JPQL query: [
        {}
    ]
    generates the following SQL query: [
        {}
    ]
    """,
    jpql.unwrap(org.hibernate.query.Query.class).getQueryString(),
    sql
);
</code>```

We get the following output:

```<code>- The JPQL query: [
    select
        YEAR(p.createdOn) as year,
        count(p) as postCount
    from
        Post p
    group by
        YEAR(p.createdOn)
]
generates the following SQL query: [
    SELECT
        extract(YEAR FROM sqlextract0_.created_on) AS col_0_0_,
        count(sqlextract0_.id) AS col_1_0_
    FROM
        post p
    GROUP BY
        extract(YEAR FROM p.created_on)
]
</code>```

Notice that we unwrapped the JPQL (HQL) Query to the Hibernate org.hibernate.query.Query interface which provided the getQueryString method we can use to log the associated JPQL query string.

Body:
I am executing the following HQL and it is executing properly

String hql = "FROM Employee";
Query query = session.createQuery(hql);
List results = query.list();

Now, I also want to log the sql generated at the backend in logs for support users.

I want to make use of QueryTranslator please advise how can I generate the sql for the corresponding HQL please advise how to achieve this.

Body:
Hibernate Types

Starting with the 2.9.11 version, the Hibernate Types open-source project offers the SQLExtractor utility that allows you to get the SQL query from any JPQL or Criteria API query, no matter you are using Hibernate 5.4, 5.3, 5.2, 5.1, 5.0, 4.3, 4.2, or 4.1.

Get the SQL statement from a JPQL (HQL) Query

Let's assume we have the following JPQL (HQL) query:

Query jpql = entityManager.createQuery("""
    select
       YEAR(p.createdOn) as year,
       count(p) as postCount
    from
       Post p
    group by
       YEAR(p.createdOn)
    """, Tuple.class
);

With Hibernate Types, extracting the Hibernate-generated SQL query is as simple as that:

String sql = SQLExtractor.from(jpql);

And, if we log the extracted SQL query:

LOGGER.info("""
    The JPQL query: [
        {}
    ]
    generates the following SQL query: [
        {}
    ]
    """,
    jpql.unwrap(org.hibernate.query.Query.class).getQueryString(),
    sql
);

We get the following output:

- The JPQL query: [
    select
        YEAR(p.createdOn) as year,
        count(p) as postCount
    from
        Post p
    group by
        YEAR(p.createdOn)
]
generates the following SQL query: [
    SELECT
        extract(YEAR FROM sqlextract0_.created_on) AS col_0_0_,
        count(sqlextract0_.id) AS col_1_0_
    FROM
        post p
    GROUP BY
        extract(YEAR FROM p.created_on)
]

Notice that we unwrapped the JPQL (HQL) Query to the Hibernate org.hibernate.query.Query interface which provided the getQueryString method we can use to log the associated JPQL query string.


问:
How to filter the category in Django properly?

I have a category function named 'person' in my Django Blog.

In my blog, Each post(article) has 1 ~ multiple categories and when I click 1 of those categories, it shows all the posts under that category.

However, for some categories especially which have only English Alphabets like 'Steve', show the same post multiple times.

I think using objects.filter has some problem with filtering it but am not sure what exactly the problem is.

Do you have any solution for this issue?

the below are my codes.

models.py

```<code>class Category(models.Model):
    person = models.CharField(max_length=20)
    description = models.TextField()
    slug = models.SlugField()
    def __str__(self):
        return self.person

class Post(models.Model):
        book_title = models.CharField(max_length=255)
        author = models.CharField(max_length=255)
        book_link = models.CharField(max_length=255)
        source = models.TextField()
        source_link = models.CharField(max_length=255)
        created_on = models.DateTimeField(auto_now_add=True)
        last_modified = models.DateTimeField(auto_now=True)
        categories = models.ManyToManyField("Category", related_name="posts")
</code>```

views.py

```<code>def blog_category(request, category):
    posts = Post.objects.filter(categories__person__contains=category).order_by(
    "-created_on"
    )

    context = {"category": category, "posts": posts}
    return render(request, "blog_category.html", context)
</code>```

答:
It is possible that the same Post is returned multiple times, if multiple Categorys to which it belong match (so contain the query). You can use .distinct() [Django-doc] to retrieve each post only once:

```<code>def blog_category(request, category):
    posts = Post.objects.filter(
        categories__person__contains=category
    ).order_by('-created_on')<b>.distinct()</b>

    context = {'category': category, 'posts': posts}
    return render(request, 'blog_category.html', context)</code>```

Body:
I have a category function named 'person' in my Django Blog.

In my blog, Each post(article) has 1 ~ multiple categories and when I click 1 of those categories, it shows all the posts under that category.

However, for some categories especially which have only English Alphabets like 'Steve', show the same post multiple times.

I think using objects.filter has some problem with filtering it but am not sure what exactly the problem is.

Do you have any solution for this issue?

the below are my codes.

models.py

class Category(models.Model):
    person = models.CharField(max_length=20)
    description = models.TextField()
    slug = models.SlugField()
    def __str__(self):
        return self.person

class Post(models.Model):
        book_title = models.CharField(max_length=255)
        author = models.CharField(max_length=255)
        book_link = models.CharField(max_length=255)
        source = models.TextField()
        source_link = models.CharField(max_length=255)
        created_on = models.DateTimeField(auto_now_add=True)
        last_modified = models.DateTimeField(auto_now=True)
        categories = models.ManyToManyField("Category", related_name="posts")

views.py

def blog_category(request, category):
    posts = Post.objects.filter(categories__person__contains=category).order_by(
    "-created_on"
    )

    context = {"category": category, "posts": posts}
    return render(request, "blog_category.html", context)

Body:
It is possible that the same Post is returned multiple times, if multiple Categorys to which it belong match (so contain the query). You can use .distinct() [Django-doc] to retrieve each post only once:

def blog_category(request, category):
    posts = Post.objects.filter(
        categories__person__contains=category
    ).order_by('-created_on').distinct()

    context = {'category': category, 'posts': posts}
    return render(request, 'blog_category.html', context)


问:
.NET Core 3.1, Vue, Axios and [ValidateAntiForgeryToken]
I've been playing with this all day and reading as much as I can and I've utterly failed to get this working.

I've compared my implementation to the MS documentation and other answers around SO and none of the approaches seem to work.

The root of the problem is the switch from an anonymous user and a logged in user.

I've been following the MS advice here. And various answers here and here

For testing I have one contact form with an endpoint decorated with [ValidateAntiForgeryToken].

The flow is:

Visit the site, post this form and everything works fine.
Login
Visit the form, post - BOOM - The provided antiforgery token was meant for a different claims-based user than the current user.

In my public void Configure( method, I have:

```<code>app.Use(async (context, next) =>
{
        var tokens = antiforgery.GetAndStoreTokens(context);
        context.Response.Cookies.Append("CSRF-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false });

    await next();
});
</code>```

In my public void ConfigureServices( method I have:

```<code>services.AddAntiforgery(options => options.HeaderName = "X-CSRF-TOKEN");
</code>```

In my Vue Router I have added a call to a method on my axios API like this:

```<code>router.afterEach((to, from) => {
    api.readCsrfCookieAndSetHeader();
});
</code>```

This method just reads the cookie and updates the header:

```<code>public readCsrfCookieAndSetHeader() {
    console.info('READING CSRF-TOKEN');
    if (document.cookie.indexOf('CSRF-TOKEN') > -1) {
        const v = document.cookie.match('(^|;) ?' + 'CSRF-TOKEN' + '=([^;]*)(;|$)');
        const r = v ? v[2] : '';
        // console.log(r);
        this.csrfToken = r;
        axios.defaults.headers.common['X-CSRF-TOKEN'] = this.csrfToken;
        console.log(axios.defaults.headers.common['X-CSRF-TOKEN']);
    } else {
        this.csrfToken = '';
    }
}
</code>```

I can see this value changing page by page.  One suggestion that seem to have worked for some is to rerun GetAndStoreTokens at the point where the user is signed in, such as:

```<code>var user = await _userManager.FindByEmailAsync(userName);
var result = await _signInManager.PasswordSignInAsync(user, password, true, false);
_httpContextAccessor.HttpContext.User = await _signInManager.CreateUserPrincipalAsync(user);
if (result.Succeeded)
{
    // get, store and send the anti forgery token
    AntiforgeryTokenSet tokens = _antiforgery.GetAndStoreTokens(_httpContextAccessor.HttpContext);
    _httpContextAccessor.HttpContext.Response.Cookies.Append("CSRF-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false });
}

return result;
</code>```

But this hasn't worked for me either.

I've also tried updating the value with an axios interceptor, like this:

```<code>axios.interceptors.response.use(
    (response) => {
        // this.readCsrfCookieAndSetHeader();
        return response;
    },
    (error) => {
</code>```

But that's really just really another way in to get the value updated that I'm sure is already being updated.

I've run out of ideas and, it seems, things to try. Hence this Q.

Have I missed anything obvious? It seems like I've replicated the MS Angular example nearly verbatim so I'm at a loss as to what I've done wrong.

Any pointers would be very much appreciated.

答: Where is definition of HttpContextSessionValues.SessionStrings.Timezone ? </p>

Body:
I've been playing with this all day and reading as much as I can and I've utterly failed to get this working.

I've compared my implementation to the MS documentation and other answers around SO and none of the approaches seem to work.

The root of the problem is the switch from an anonymous user and a logged in user.

I've been following the MS advice here. And various answers here and here

For testing I have one contact form with an endpoint decorated with [ValidateAntiForgeryToken].

The flow is:

Visit the site, post this form and everything works fine.
Login
Visit the form, post - BOOM - The provided antiforgery token was meant for a different claims-based user than the current user.

In my public void Configure( method, I have:

app.Use(async (context, next) =>
{
        var tokens = antiforgery.GetAndStoreTokens(context);
        context.Response.Cookies.Append("CSRF-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false });

    await next();
});

In my public void ConfigureServices( method I have:

services.AddAntiforgery(options => options.HeaderName = "X-CSRF-TOKEN");

In my Vue Router I have added a call to a method on my axios API like this:

router.afterEach((to, from) => {
    api.readCsrfCookieAndSetHeader();
});

This method just reads the cookie and updates the header:

public readCsrfCookieAndSetHeader() {
    console.info('READING CSRF-TOKEN');
    if (document.cookie.indexOf('CSRF-TOKEN') > -1) {
        const v = document.cookie.match('(^|;) ?' + 'CSRF-TOKEN' + '=([^;]*)(;|$)');
        const r = v ? v[2] : '';
        // console.log(r);
        this.csrfToken = r;
        axios.defaults.headers.common['X-CSRF-TOKEN'] = this.csrfToken;
        console.log(axios.defaults.headers.common['X-CSRF-TOKEN']);
    } else {
        this.csrfToken = '';
    }
}

I can see this value changing page by page.  One suggestion that seem to have worked for some is to rerun GetAndStoreTokens at the point where the user is signed in, such as:

var user = await _userManager.FindByEmailAsync(userName);
var result = await _signInManager.PasswordSignInAsync(user, password, true, false);
_httpContextAccessor.HttpContext.User = await _signInManager.CreateUserPrincipalAsync(user);
if (result.Succeeded)
{
    // get, store and send the anti forgery token
    AntiforgeryTokenSet tokens = _antiforgery.GetAndStoreTokens(_httpContextAccessor.HttpContext);
    _httpContextAccessor.HttpContext.Response.Cookies.Append("CSRF-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false });
}

return result;

But this hasn't worked for me either.

I've also tried updating the value with an axios interceptor, like this:

axios.interceptors.response.use(
    (response) => {
        // this.readCsrfCookieAndSetHeader();
        return response;
    },
    (error) => {

But that's really just really another way in to get the value updated that I'm sure is already being updated.

I've run out of ideas and, it seems, things to try. Hence this Q.

Have I missed anything obvious? It seems like I've replicated the MS Angular example nearly verbatim so I'm at a loss as to what I've done wrong.

Any pointers would be very much appreciated.


问:
Connection refused when connecting to host mysql db from docker container
I am trying to connect to mysql server running on host machine (localhost) from a spring app running inside a docker container

this is my Dockerfile

```<code>FROM openjdk:11
ADD build/libs/demo-0.0.1-SNAPSHOT.jar demo.jar
EXPOSE 8000
RUN mkdir -p tmp/scripts
RUN mkdir -p tmp/logs
ENTRYPOINT ["java","-jar","/demo.jar"]
</code>```

I am using Docker desktop for mac v2.3.0.3 with engine version 19.03.8

This is may hikariCP datasource connection properties

```<code>spring.datasource.jdbcUrl=jdbc:mysql://**host.docker.internal:3306**/freshid
spring.datasource.username=sa
spring.datasource.password=test
</code>```

When I build docker build -f Dockerfile -t demo . and run the image as docker run -p 8000:8000 demo

I get the following error on application start up

```<code>The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:835)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:455)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138)
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:354)
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:202)
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:473)
    at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:554)
    ... 64 common frames omitted
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151)
    at com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:167)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:91)
    at com.mysql.cj.NativeSession.connect(NativeSession.java:152)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:955)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825)
    ... 72 common frames omitted
Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399)
    at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242)
    at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:403)
    at java.base/java.net.Socket.connect(Socket.java:609)
    at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:155)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:65)
    ... 75 common frames omitted
</code>```

答:
I would suggest a simple solution.

Step 1: Turboshooting: Try to run springboot appliction in you machine, outside container. If works fine, then there is no issue your application. (Make sure while testing locally you change your DB connection string from host.docker.internal to localhost)

Step 2: Please expose your DB port, that is 3306 by default in case of mysql when you run Docker Container with imperitive command

docker run -p 8000:8000 -p 3306:3306 demo

This should resolve your issue

Body:
I am trying to connect to mysql server running on host machine (localhost) from a spring app running inside a docker container

this is my Dockerfile

FROM openjdk:11
ADD build/libs/demo-0.0.1-SNAPSHOT.jar demo.jar
EXPOSE 8000
RUN mkdir -p tmp/scripts
RUN mkdir -p tmp/logs
ENTRYPOINT ["java","-jar","/demo.jar"]

I am using Docker desktop for mac v2.3.0.3 with engine version 19.03.8

This is may hikariCP datasource connection properties

spring.datasource.jdbcUrl=jdbc:mysql://**host.docker.internal:3306**/freshid
spring.datasource.username=sa
spring.datasource.password=test

When I build docker build -f Dockerfile -t demo . and run the image as docker run -p 8000:8000 demo

I get the following error on application start up

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:835)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:455)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199)
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138)
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:354)
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:202)
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:473)
    at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:554)
    ... 64 common frames omitted
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151)
    at com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:167)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:91)
    at com.mysql.cj.NativeSession.connect(NativeSession.java:152)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:955)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825)
    ... 72 common frames omitted
Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399)
    at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242)
    at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:403)
    at java.base/java.net.Socket.connect(Socket.java:609)
    at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:155)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:65)
    ... 75 common frames omitted


问:
How to change referenced numpy arrays to a slice of itself?
Consider the following operation and slicing applied to two numpy arrays:

```<code>In [1]: import numpy as np

In [2]: a = np.array([1,2,3,4])

In [3]: b = np.array([5,6,7,8])

In [4]: a[2:] = 0

In [5]: a = a[::2]

In [6]: b[2:] = 0

In [7]: b = b[::2]

In [8]: a
Out[8]: array([1, 0])

In [9]: b
Out[9]: array([5, 0])
</code>```

I do not want to repeat the slicing code, for example, instead of lines [4]-[7] above, I wish to use something like

```<code>In [4]: for data in [a,b] :
   ...:     data[2:] = 0
   ...:     data = data[::2]
</code>```

I understand that it does not work because the effect of data = data[::2] is to make data to point a new object, not to change the original objects. So the values of a and b are not sliced:

```<code>In [5]: a
Out[5]: array([1, 2, 0, 0])

In [6]: b
Out[6]: array([5, 6, 0, 0])
</code>```

My question is:

How to slice a numpy array referenced by a variable?

In my real application, I an doing several operations in each array, and want to have them all in the same block inside the for.

答:
You could use a list comprehension:</p>

```<code>a,b = [arr[::2] for arr in [a,b]]
</code>```

Body:
Consider the following operation and slicing applied to two numpy arrays:

In [1]: import numpy as np

In [2]: a = np.array([1,2,3,4])

In [3]: b = np.array([5,6,7,8])

In [4]: a[2:] = 0

In [5]: a = a[::2]

In [6]: b[2:] = 0

In [7]: b = b[::2]

In [8]: a
Out[8]: array([1, 0])

In [9]: b
Out[9]: array([5, 0])

I do not want to repeat the slicing code, for example, instead of lines [4]-[7] above, I wish to use something like

In [4]: for data in [a,b] :
   ...:     data[2:] = 0
   ...:     data = data[::2]

I understand that it does not work because the effect of data = data[::2] is to make data to point a new object, not to change the original objects. So the values of a and b are not sliced:

In [5]: a
Out[5]: array([1, 2, 0, 0])

In [6]: b
Out[6]: array([5, 6, 0, 0])

My question is:

How to slice a numpy array referenced by a variable?

In my real application, I an doing several operations in each array, and want to have them all in the same block inside the for.

Body:
You could use a list comprehension:

a,b = [arr[::2] for arr in [a,b]]


问:
apt-get update show: CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none
sudo apt-get update

W: Failed to fetch https://get.docker.com/ubuntu/dists/docker/main/binary-amd64/Packages  server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

openssl s_client -connect get.docker.com:443 -tls1 -debug => http://paste.ubuntu.com/10687412

my machine is Ubuntu 14.10

any ideas?

答:
Scratched my head for couple of days, eventually this worked

```<code>USER root
RUN rm -rf /var/lib/apt/lists/*
RUN rm -rf /etc/apt/sources.list.d/*
</code>```

RUN apt-get update

Body:
Scratched my head for couple of days, eventually this worked

USER root
RUN rm -rf /var/lib/apt/lists/*
RUN rm -rf /etc/apt/sources.list.d/*

RUN apt-get update


问:
how to output the difference of two floats as an interger in python
is there any way to output the difference between two float numbers as an integer </p>

<p>below is three examples of the float values provided for script, my goal is to output the difference between these values as an integer , in the first example i should get 2 where num_two - num_one equals 0.000002 but i don't want the zeros as they don't matter i can do it with string format but i have no way of telling how big the number is or how many zeros it has </p>

```<code>## example 1
num_one = 0.000012
num_two = 0.000014

## example 2
num_0ne = 0.0123
num_tw0 = 0.013

## example 3
num_1 = 23.32
num_2 = 23.234

print (float(num_2) - float(num_1))

## this should output 86 as an integer
</code>```

答:
Beware of floats (see https://en.wikipedia.org/wiki/IEEE_754):

```<code>>>> 23.32 - 23.234
0.08599999999999852
</code>```

You need exact precision. Use the decimal module:

```<code>>>> from decimal import Decimal
>>> n1 = Decimal("23.32")
>>> n2 = Decimal("23.234")
>>> n1, n2
(Decimal('23.32'), Decimal('23.234'))
>>> d = abs(n1-n2)
>>> d
Decimal('0.086')
</code>```

Now, just shift the decimal point right (that is * 10) until there is no fractional part left (d % 1 == 0):

```<code>>>> while d % 1:
...     d *= 10
</code>```

(Don't be afraid, the loop will stop because you can't have more decimal levels than decimal.getcontext().prec at the beginning and the decimal level decrease on each iteration).

You get the expected result:

```<code>>>> d
Decimal('86.000')
>>> int(d)
86
</code>```

Body:
is there any way to output the difference between two float numbers as an integer

below is three examples of the float values provided for script, my goal is to output the difference between these values as an integer , in the first example i should get 2 where num_two - num_one equals 0.000002 but i don't want the zeros as they don't matter i can do it with string format but i have no way of telling how big the number is or how many zeros it has

## example 1
num_one = 0.000012
num_two = 0.000014

## example 2
num_0ne = 0.0123
num_tw0 = 0.013

## example 3
num_1 = 23.32
num_2 = 23.234

print (float(num_2) - float(num_1))

## this should output 86 as an integer

Body:
Beware of floats (see https://en.wikipedia.org/wiki/IEEE_754):

>>> 23.32 - 23.234
0.08599999999999852

You need exact precision. Use the decimal module:

>>> from decimal import Decimal
>>> n1 = Decimal("23.32")
>>> n2 = Decimal("23.234")
>>> n1, n2
(Decimal('23.32'), Decimal('23.234'))
>>> d = abs(n1-n2)
>>> d
Decimal('0.086')

Now, just shift the decimal point right (that is * 10) until there is no fractional part left (d % 1 == 0):

>>> while d % 1:
...     d *= 10

(Don't be afraid, the loop will stop because you can't have more decimal levels than decimal.getcontext().prec at the beginning and the decimal level decrease on each iteration).

You get the expected result:

>>> d
Decimal('86.000')
>>> int(d)
86


问:
How do I use NLTK's default tokenizer to get spans instead of strings?
NLTK's default tokenizer, nltk.word_tokenizer, chains two tokenizers, a sentence tokenizer and then a word tokenizer that operates on sentences. It does a pretty good job out of the box.

```<code>>>> nltk.word_tokenize("(Dr. Edwards is my friend.)")
['(', 'Dr.', 'Edwards', 'is', 'my', 'friend', '.', ')']
</code>```

I'd like to use this same algorithm except to have it return tuples of offsets into the original string instead of string tokens.

By offset I mean 2-ples that can serve as indexes into the original string. For example here I'd have

```<code>>>> s = "(Dr. Edwards is my friend.)"
>>> s.token_spans()
[(0,1), (1,4), (5,12), (13,15), (16,18), (19,25), (25,26), (26,27)]
</code>```

because s[0:1] is "(", s[1:4] is "Dr." and so forth.

Is there a single NLTK call that does this, or do I have to write my own offset arithmetic?

答:
pytokenizations have a useful function get_original_spans to get the spans:

# $ pip install pytokenizations
import tokenizations
text = "(Dr. Edwards is my friend.)"
tokens = nltk.word_tokenize(text)
tokenizations.get_original_spans(tokens, text)
>>> [(0,1), (1,4), (5,12), (13,15), (16,18), (19,25), (25,26), (26,27)]
```

See the documentation for other useful functions.

Body:
NLTK's default tokenizer, nltk.word_tokenizer, chains two tokenizers, a sentence tokenizer and then a word tokenizer that operates on sentences. It does a pretty good job out of the box.

>>> nltk.word_tokenize("(Dr. Edwards is my friend.)")
['(', 'Dr.', 'Edwards', 'is', 'my', 'friend', '.', ')']

I'd like to use this same algorithm except to have it return tuples of offsets into the original string instead of string tokens.

By offset I mean 2-ples that can serve as indexes into the original string. For example here I'd have

>>> s = "(Dr. Edwards is my friend.)"
>>> s.token_spans()
[(0,1), (1,4), (5,12), (13,15), (16,18), (19,25), (25,26), (26,27)]

because s[0:1] is "(", s[1:4] is "Dr." and so forth.

Is there a single NLTK call that does this, or do I have to write my own offset arithmetic?

Body:
pytokenizations have a useful function get_original_spans to get the spans:

# $ pip install pytokenizations
import tokenizations
text = "(Dr. Edwards is my friend.)"
tokens = nltk.word_tokenize(text)
tokenizations.get_original_spans(tokens, text)
>>> [(0,1), (1,4), (5,12), (13,15), (16,18), (19,25), (25,26), (26,27)]

See the documentation for other useful functions.


问:
plotly plots in jupyter notebooks: Validation fails when saving
I'am new to plotly and I'am having a problem with my plots when generating them inside jupyter notebooks.

Whenever I generate a plot, evrything works fine, but when I try to save the notebook I get an error message telling me that the notebook validation failed because it's not valid under any of the given schemas (example taken straight from the plot.ly webiste).

Here is an example:

```<code>import plotly.plotly as py
iplot([{"x": [1, 2, 3], "y": [3, 1, 6]}])
</code>```

I get the following message when I try to save the notebook:
Notebook Validation failed: {u'data': [{u'y': [3, 1, 6], u'x': [1, 2, 3]}], u'layout': {}} is not valid under any of the given schemas:

```<code>{
 "data": [
  {
   "y": [
    3,
    1,
    6
   ],
   "x": [
    1,
    2,
    3
   ]
  }
 ],
 "layout": {}
}
</code>```

Thank you!

答: As in gerard's answer pip install --upgrade nbformat solved the issue, however conda (which I tried before pip) didn't solve the issue.

Body:
I'am new to plotly and I'am having a problem with my plots when generating them inside jupyter notebooks.

Whenever I generate a plot, evrything works fine, but when I try to save the notebook I get an error message telling me that the notebook validation failed because it's not valid under any of the given schemas (example taken straight from the plot.ly webiste).

Here is an example:

import plotly.plotly as py
iplot([{"x": [1, 2, 3], "y": [3, 1, 6]}])

I get the following message when I try to save the notebook:
Notebook Validation failed: {u'data': [{u'y': [3, 1, 6], u'x': [1, 2, 3]}], u'layout': {}} is not valid under any of the given schemas:

{
 "data": [
  {
   "y": [
    3,
    1,
    6
   ],
   "x": [
    1,
    2,
    3
   ]
  }
 ],
 "layout": {}
}

Thank you!


问:
How to avoid parallel class hierarchy in python
I've been running into a weird little smell in my python code lately and I think it has something to do with parallel inheritance. Here is a small example I concocted:

```<code>class DogHabits:
    def __init__(self):
        self.habits = ['lick butt']

class GermanShepherdHabits(DogHabits):
    def __init__(self):
        super().__init__()
        self.habits.extend(['herd sheep'])

class LabradorHabits(DogHabits):
    def __init__(self):
        super().__init__()
        self.habits.extend(['hunt', 'pee on owner'])

class Dog:
    def __init__(self):
        self.type = 'generic_dog'
        self.my_habits = DogHabits()

    def do_stuff(self):
        for habit in self.my_habits.habits:
            print(habit)

class GermanShepherd(Dog):
    def __init__(self):
        self.type = 'german shepherd'
        self.my_habits = GermanShepherdHabits()

class Labrador(Dog):
    def __init__(self):
        self.type = 'labrador'
        self.my_habits = LabradorHabits()

if __name__ == "__main__":
    german_shepherd = GermanShepherd()
    print('\n{}'.format(german_shepherd.type))
    german_shepherd.do_stuff()

    labrador = Labrador()
    print('\n{}'.format(labrador.type))
    labrador.do_stuff()
</code>```

I have a generic dog class from which concrete dog implementations inherit. Every dog class (including the generic/abstract one) has a set of habits, itself represented by another class hierarchy for the habits.

I am annoyed by the fact that I have to have both hierarchies exactly the same at all times. Furthermore the inheritance between the DogHabits is useful within the habits hierarchy, but it is not useful within the dogs hierarchy, as I need to instantiate a separate habits object for each class in the dog hierarchy.

What is the antidote to this? I may want to add many implementations of the dog class, and updating the corresponding habits hierarchy sounds tedious and smells bad...

答:
This answer assumes that the DogHabits is much more complex than a mere list and is really worth a dedicated class with its own inheritance.

On a design point of view, I can see a first question on whether habits and type should be class or instance members. Here again, this answer assumes that there are reasons to make them instance members.

I would make Habits an inner class of Dogs and state in the class documentation that is can be customized by building a subclass of it in a subclass of Dogs:

```<code> class Dog:
    class Habits:
        """Represents the habits of a Dog.

        It can be customized in a child class by creating in the subclass an
        inner class named Habits that would be a subclass of Dog.Habits
        """

        def __init__(self):
            self.habits = ['lick butt']

    def __init__(self, typ='generic_dog'):
        self.type = typ
        self.my_habits = self.__class__.Habits()

    def do_stuff(self):
        for habit in self.my_habits.habits:
            print(habit)

class GermanShepherd(Dog):

    class Habits(Dog.Habits):

        def __init__(self):
            super().__init__()
            self.habits.extend(['herd sheep'])

    def __init__(self):
        super().__init__('german shepherd')

class Labrador(Dog):

    class Habits(Dog.Habits):
        def __init__(self):
            super().__init__()
            self.habits.extend(['hunt', 'pee on owner'])

    def __init__(self):
        super().__init__('labrador')
</code>```

Body:
I've been running into a weird little smell in my python code lately and I think it has something to do with parallel inheritance. Here is a small example I concocted:

class DogHabits:
    def __init__(self):
        self.habits = ['lick butt']

class GermanShepherdHabits(DogHabits):
    def __init__(self):
        super().__init__()
        self.habits.extend(['herd sheep'])

class LabradorHabits(DogHabits):
    def __init__(self):
        super().__init__()
        self.habits.extend(['hunt', 'pee on owner'])

class Dog:
    def __init__(self):
        self.type = 'generic_dog'
        self.my_habits = DogHabits()

    def do_stuff(self):
        for habit in self.my_habits.habits:
            print(habit)

class GermanShepherd(Dog):
    def __init__(self):
        self.type = 'german shepherd'
        self.my_habits = GermanShepherdHabits()

class Labrador(Dog):
    def __init__(self):
        self.type = 'labrador'
        self.my_habits = LabradorHabits()

if __name__ == "__main__":
    german_shepherd = GermanShepherd()
    print('\n{}'.format(german_shepherd.type))
    german_shepherd.do_stuff()

    labrador = Labrador()
    print('\n{}'.format(labrador.type))
    labrador.do_stuff()

I have a generic dog class from which concrete dog implementations inherit. Every dog class (including the generic/abstract one) has a set of habits, itself represented by another class hierarchy for the habits.

I am annoyed by the fact that I have to have both hierarchies exactly the same at all times. Furthermore the inheritance between the DogHabits is useful within the habits hierarchy, but it is not useful within the dogs hierarchy, as I need to instantiate a separate habits object for each class in the dog hierarchy.

What is the antidote to this? I may want to add many implementations of the dog class, and updating the corresponding habits hierarchy sounds tedious and smells bad...

Body:
This answer assumes that the DogHabits is much more complex than a mere list and is really worth a dedicated class with its own inheritance.

On a design point of view, I can see a first question on whether habits and type should be class or instance members. Here again, this answer assumes that there are reasons to make them instance members.

I would make Habits an inner class of Dogs and state in the class documentation that is can be customized by building a subclass of it in a subclass of Dogs:

 class Dog:
    class Habits:
        """Represents the habits of a Dog.

        It can be customized in a child class by creating in the subclass an
        inner class named Habits that would be a subclass of Dog.Habits
        """

        def __init__(self):
            self.habits = ['lick butt']

    def __init__(self, typ='generic_dog'):
        self.type = typ
        self.my_habits = self.__class__.Habits()

    def do_stuff(self):
        for habit in self.my_habits.habits:
            print(habit)

class GermanShepherd(Dog):

    class Habits(Dog.Habits):

        def __init__(self):
            super().__init__()
            self.habits.extend(['herd sheep'])

    def __init__(self):
        super().__init__('german shepherd')

class Labrador(Dog):

    class Habits(Dog.Habits):
        def __init__(self):
            super().__init__()
            self.habits.extend(['hunt', 'pee on owner'])

    def __init__(self):
        super().__init__('labrador')


问:
Will Python open a file before it's finished writing?
I am writing a script that will be polling a directory looking for new files.

In this scenario, is it necessary to do some sort of error checking to make sure the files are completely written prior to accessing them?

I don't want to work with a file before it has been written completely to disk, but because the info I want from the file is near the beginning, it seems like it could be possible to pull the data I need without realizing the file isn't done being written.

Is that something I should worry about, or will the file be locked because the OS is writing to the hard drive?

This is on a Linux system.

答:
If you have some control over the writing program, have it write the file somewhere else (like the /tmp directory) and then when it's done move it to the directory being watched. </p>

<p>If you don't have control of the program doing the writing (and by 'control' I mean 'edit the source code'), you probably won't be able to make it do file locking either, so that's probably out. In which case you'll likely need to know something about the file format to know when the writer is done. For instance, if the writer always writes "DONE" as the last four characters in the file, you could open the file, seek to the end, and read the last four characters. </p>

Body:
If you have some control over the writing program, have it write the file somewhere else (like the /tmp directory) and then when it's done move it to the directory being watched.

If you don't have control of the program doing the writing (and by 'control' I mean 'edit the source code'), you probably won't be able to make it do file locking either, so that's probably out. In which case you'll likely need to know something about the file format to know when the writer is done. For instance, if the writer always writes "DONE" as the last four characters in the file, you could open the file, seek to the end, and read the last four characters.


问:
Type '{ text: string; }' is not assignable to type 'TitleObject'. in highcharts
When I use HighCharts angular so I get this error,
Type '{ text: string; }' is not assignable to type 'TitleObject'.

```<code>const sampleData: Highcharts.Chart = {
      chart: {
        type: 'column',
      },
      title: { text: 'Total Predected Revenue Vs Actual Revenue' },
      xAxis: {
        categories: [
          '2010',
          '2011',
          '2012',
          '2013',
          '2014',
          '2015',
          '2016',
          '2017',
        ],
        crosshair: true,
      },
      yAxis: {
        min: 0,
      },
      series: [
        {
          name: 'Predected',
          data: [14, 17, 9, 10, 6, 19, 6, 8] ,
        } ,
        {
          name: 'Actual',
          data: [65, 74, 44, 66, 9, 23, 36, 51],
        },
      ],
    };
</code>```

for Title, categories,yaxis, and for data i get the error Type '{  }' is not assignable to type ' '. in highcharts

答:
I just Checked the source code of highcharts at https://github.com/highcharts/highcharts.

I notice TitleObject is subClass of SVGElement.
So dive deeper in SVGElement class definition

```<code>class SVGElement {
    public constructor();
    [key: string]: any;
    public element: (HTMLDOMElement|SVGDOMElement);
    public hasBoxWidthChanged: boolean;
    public parentGroup?: SVGElement;
    public pathArray?: SVGPath;
    public r?: number;
    public renderer: SVGRenderer;
    public rotation?: number;
    public shadows?: Array<(HTMLDOMElement|SVGDOMElement)>;
    public oldShadowOptions?: Highcharts.ShadowOptionsObject;
    public styles?: CSSObject;
    public textStr?: string;
    public x?: number;
    public y?: number;
    public add(parent?: SVGElement): SVGElement;
    public addClass(className: string, replace?: boolean): SVGElement;
    public afterSetters(): void;
}
</code>```

at here https://github.com/highcharts/highcharts/blob/d1be8b45541bc903e7c3c3cacd010956a3a5db01/ts/parts/SVGElement.ts
you will notice there is no 'text' property.I suppose HighCharts update 'text' to 'textStr'.

Body:
When I use HighCharts angular so I get this error,
Type '{ text: string; }' is not assignable to type 'TitleObject'.

const sampleData: Highcharts.Chart = {
      chart: {
        type: 'column',
      },
      title: { text: 'Total Predected Revenue Vs Actual Revenue' },
      xAxis: {
        categories: [
          '2010',
          '2011',
          '2012',
          '2013',
          '2014',
          '2015',
          '2016',
          '2017',
        ],
        crosshair: true,
      },
      yAxis: {
        min: 0,
      },
      series: [
        {
          name: 'Predected',
          data: [14, 17, 9, 10, 6, 19, 6, 8] ,
        } ,
        {
          name: 'Actual',
          data: [65, 74, 44, 66, 9, 23, 36, 51],
        },
      ],
    };

for Title, categories,yaxis, and for data i get the error Type '{  }' is not assignable to type ' '. in highcharts

Body:
I just Checked the source code of highcharts at https://github.com/highcharts/highcharts.

I notice TitleObject is subClass of SVGElement.
So dive deeper in SVGElement class definition

class SVGElement {
    public constructor();
    [key: string]: any;
    public element: (HTMLDOMElement|SVGDOMElement);
    public hasBoxWidthChanged: boolean;
    public parentGroup?: SVGElement;
    public pathArray?: SVGPath;
    public r?: number;
    public renderer: SVGRenderer;
    public rotation?: number;
    public shadows?: Array<(HTMLDOMElement|SVGDOMElement)>;
    public oldShadowOptions?: Highcharts.ShadowOptionsObject;
    public styles?: CSSObject;
    public textStr?: string;
    public x?: number;
    public y?: number;
    public add(parent?: SVGElement): SVGElement;
    public addClass(className: string, replace?: boolean): SVGElement;
    public afterSetters(): void;
}

at here https://github.com/highcharts/highcharts/blob/d1be8b45541bc903e7c3c3cacd010956a3a5db01/ts/parts/SVGElement.ts
you will notice there is no 'text' property.I suppose HighCharts update 'text' to 'textStr'.