问:
FFmpeg - combine 2 commands
I have 2 commands as listed below.

Add intro image to a video

```<code>ffmpeg -y -loop 1 -framerate 10 -t 3 -i intro.png -i video.mp4 -filter_complex "[0:0] [1:0] concat=n=2:v=1:a=0" -c:v libx264 -crf 23 videoWithIntro.mp4
</code>```

Add watermark to video

```<code>ffmpeg -y -i video.mp4 -i watermark_color.png -filter_complex "overlay=x=(main_w-overlay_w)/2:y=(main_h-overlay_h)/2"  videoWithWatermark.mp4
</code>```

I was wondering is it possible to combine these into the 1 command?

答:
The final command to get this working correctly is as follows
ffmpeg -y -loop 1 -framerate 25 -t 3 -i 1920x1080_intro.png -i DSC_0002.MOV -i watermark_color.png -report -an -filter_complex "[1][2]overlay=x=(main_w-overlay_w)/2:y=(main_h-overlay_h)/2,setsar=1[v];[0]setsar=1[pre];[pre][v]concat=n=2:v=1:a=0" ../testing/videoWithIntroAndWatermark.mp4</p>

Title: FFmpeg - combine 2 commands

Body:
I have 2 commands as listed below.

Add intro image to a video

ffmpeg -y -loop 1 -framerate 10 -t 3 -i intro.png -i video.mp4 -filter_complex "[0:0] [1:0] concat=n=2:v=1:a=0" -c:v libx264 -crf 23 videoWithIntro.mp4

Add watermark to video

ffmpeg -y -i video.mp4 -i watermark_color.png -filter_complex "overlay=x=(main_w-overlay_w)/2:y=(main_h-overlay_h)/2"  videoWithWatermark.mp4

I was wondering is it possible to combine these into the 1 command?


来源: stackexchange

问:
@ngtools\webpack AOT doesn't work OR freezes at 95% emitting
I've been stuck trying to get AOT working with my Webpack app.
(@ngtools/webpack)

Can anyone help me at all?

It appears to work, however, compiler.js is still included in the bundle.
Also it is still looking for all of my .html files and getting 404 on all of the component templates.

So as far as I can tell it's not really doing the best parts of the AOT?

Can any shine any light here, I'm stuck!!

Thank you!!

答:
I was able to make a sample angular5 app build in AOT

https://github.com/tomalex0/angularx-aot-jit

I created a sample angular5 app which generates AOT and JIT, might not be in same structure as yours but works

https://github.com/tomalex0/angularx-aot-jit

This commit difference will give better picture of what all i changed while updating to angular5
https://github.com/tomalex0/angularx-aot-jit/commit/1435fddf1a6336f05e63f30062cb4cd2d0ba771f

tsconfig-aot.json for angular5

```<code>{
  "compilerOptions": {
    "module": "es2015",
    "moduleResolution": "node",
    "target": "es5",
    "noImplicitAny": false,
    "sourceMap": true,
    "mapRoot": "",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "es2015",
      "dom"
    ],
    "outDir": "aot",
    "skipLibCheck": true,
    "rootDir": "."
  }
}
</code>```

No longer needs "angularCompilerOptions": {"genDir": "aot" }|

in webpack config make entry as entry: './js/ng2/app/main.jit.ts'

in webpack  const { AngularCompilerPlugin } = require('@ngtools/webpack'); and in plugins as new AngularCompilerPlugin({tsConfigPath: './tsconfig-aot.json', entryModule: ...})

ContentLicense: CC BY-SA 3.0

Body:
I was able to make a sample angular5 app build in AOT

https://github.com/tomalex0/angularx-aot-jit

I created a sample angular5 app which generates AOT and JIT, might not be in same structure as yours but works

https://github.com/tomalex0/angularx-aot-jit

This commit difference will give better picture of what all i changed while updating to angular5
https://github.com/tomalex0/angularx-aot-jit/commit/1435fddf1a6336f05e63f30062cb4cd2d0ba771f

tsconfig-aot.json for angular5

{
  "compilerOptions": {
    "module": "es2015",
    "moduleResolution": "node",
    "target": "es5",
    "noImplicitAny": false,
    "sourceMap": true,
    "mapRoot": "",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "es2015",
      "dom"
    ],
    "outDir": "aot",
    "skipLibCheck": true,
    "rootDir": "."
  }
}

No longer needs "angularCompilerOptions": {"genDir": "aot" }|

in webpack config make entry as entry: './js/ng2/app/main.jit.ts'

in webpack  const { AngularCompilerPlugin } = require('@ngtools/webpack'); and in plugins as new AngularCompilerPlugin({tsConfigPath: './tsconfig-aot.json', entryModule: ...})


问:
First group of non-zero values (by neglecting single occurrence of zero)
This is what I intend to do in Python:

I have an array (freq_arr). I want to find the indices of the first group of non-zero elements. I start searching for non-zero elements from start, when I find the first non-zero element (the first element is 5, in the example below), I record its index (4, in the example shown below). I search for the next one, and record its index (which will be 5). If I encounter a single zero, I want to neglect it and continue searching for non-zero values. This way, I consider the values 5,6,0,8,9,0,1 with indices 4,5,6,7,8,9 and 10. After these values, there are five zeros and hence I stop my search. Upto a maximum of two zeros can exist in the output, and search continues. However, if I encounter 3 or more zeros, I want to stop searching.

Input:

```<code>freq_arr = np.array([0, 0, 0, 0, 5, 6, 0, 8, 9, 0, 1, 0, 0, 0, 0, 3, 6, 0])
</code>```

Output:

```<code>out_arr_indices = [4, 5, 6, 7, 8, 9, 10]
</code>```

I know to code this using for loops, but I want to avoid it since it's not efficient. Kindly let me know how this can be done.

The array will be single dimension. Each element will be in the range of 5000 to 20000.

答:
If I understand your problem right, you want to iterate through the list skipping two zeros or less in a row, and add the indices of non-zero values to an output array. Maybe something like below

```<code>freq_arr = [0, 0, 5, 6, 0, 8, 9, 0, 1, 0, 0, 0, 0, 3, 6, 0]
outputarr = []

count = 0
zerocount = 0

while count < len(freq_arr) and zerocount < 3:
    if freq_arr[count] == 0:
        zerocount += 1
    else:
        zerocount = 0
        outputarr.append(count)
    count += 1
</code>```

If you provide more details we might be able to assist better.

Body:
This is what I intend to do in Python:

I have an array (freq_arr). I want to find the indices of the first group of non-zero elements. I start searching for non-zero elements from start, when I find the first non-zero element (the first element is 5, in the example below), I record its index (4, in the example shown below). I search for the next one, and record its index (which will be 5). If I encounter a single zero, I want to neglect it and continue searching for non-zero values. This way, I consider the values 5,6,0,8,9,0,1 with indices 4,5,6,7,8,9 and 10. After these values, there are five zeros and hence I stop my search. Upto a maximum of two zeros can exist in the output, and search continues. However, if I encounter 3 or more zeros, I want to stop searching.

Input:

freq_arr = np.array([0, 0, 0, 0, 5, 6, 0, 8, 9, 0, 1, 0, 0, 0, 0, 3, 6, 0])

Output:

out_arr_indices = [4, 5, 6, 7, 8, 9, 10]

I know to code this using for loops, but I want to avoid it since it's not efficient. Kindly let me know how this can be done.

The array will be single dimension. Each element will be in the range of 5000 to 20000.

Body:
If I understand your problem right, you want to iterate through the list skipping two zeros or less in a row, and add the indices of non-zero values to an output array. Maybe something like below

freq_arr = [0, 0, 5, 6, 0, 8, 9, 0, 1, 0, 0, 0, 0, 3, 6, 0]
outputarr = []

count = 0
zerocount = 0

while count < len(freq_arr) and zerocount < 3:
    if freq_arr[count] == 0:
        zerocount += 1
    else:
        zerocount = 0
        outputarr.append(count)
    count += 1

If you provide more details we might be able to assist better.


问:
How do I pass text input from one JTextField to a variable in another class?
I am trying to create a student registration program in which the user inputs data in a JFrame in a JTextField and that data is stored into a variable in another class.
package acgregistration;

```<code>import java.util.*;
/**
*
* @author Frank
*/
public class AcgRegistration {

public static void main(String[] args) {

    memberDialogBox memberDialogBox = new memberDialogBox();

}

}

    package acgregistration;

    /**
     *
     * @author Frank
     */
    class acgMember {
 private String name;
 private int num;
 private String email;

 public acgMember(String name, int number, String email) {
    this.name = name;
    this.num = number;
    this.email = email;
 }

 public String getName() {
    return name;
 }

 public void setName(String name) {
    this.name = name;
 }

 public int getNum() {
    return num;
 }

 public void setNum(int num) {
     this.num = num;
 }

 public String getEmail() {
    return email;
 }

 public void setEmail(String email) {
    this.email = email;
 }
 }

 package acgregistration;
 import javax.swing.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;

 /**
 *
 * @author Frank
 */
 public class memberDialogBox {

 String options[] = {"Student","Faculty/Staff"};
 JComboBox choices = new JComboBox(options);
 JButton b = new JButton("Confirm");
 JLabel l = new JLabel("Select your ACG Status");

 public memberDialogBox(){
  frame();
 }

 public void frame(){

  JFrame f = new JFrame();
  f.setVisible(true);
  f.setSize(210,150);
  f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

  JPanel p = new JPanel();
  p.add(choices);
  p.add(b);
  p.add(l);

  f.add(p);

  b.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){

          String s = choices.getSelectedItem().toString();
          if ("Student".equals(choices.getSelectedItem())){

               studentDialogBox student = new studentDialogBox();
    //This code gives me an error code saying I should call
   //acgMemberModel

          }
          else{
                 facultyDialogBox faculty= new facultyDialogBox();
              }

        f.dispose();
          }

  });
  }

 }

 package acgregistration;
 import javax.swing.*;
 import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class studentDialogBox {
private JTextField nameField = new JTextField("", 20);
private JTextField emailField = new JTextField("", 20);
private JTextField numberField = new JTextField("", 20);
private JButton confirmButton = new JButton("Confirm");
private acgMemberModel model;

public studentDialogBox(acgMemberModel model) {
    this.model = model;
    frame();
}

public void frame() {
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    panel.add(nameField);
    panel.add(emailField);
    panel.add(numberField);
    panel.add(confirmButton);
    frame.add(panel);

    confirmButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String name = nameField.getText();
            String number = numberField.getText();
            String email = emailField.getText();
            acgMember member = new acgMember(name,
   Integer.valueOf(number), email);
            model.addNew(member);
        }
    });

   }
 }

class acgMemberModel {
private List<acgMember> members = new ArrayList<>();

public void addNew(acgMember member) {
    members.add(member);
}

public List<acgMember> getMembers() {
    return Collections.unmodifiableList(members);
}
}
</code>```

I'm basically trying to do this for all the text fields and then save it into an ArrayList or a Hashmap ( basically the end result). My only question is, how would i store text field inputs from one class to another?
Any help would be highly appreciated! Thank you!

答: Have you tried making the variables you want to share between classes public static?

Body:
I am trying to create a student registration program in which the user inputs data in a JFrame in a JTextField and that data is stored into a variable in another class.
package acgregistration;

import java.util.*;
/**
*
* @author Frank
*/
public class AcgRegistration {

public static void main(String[] args) {

    memberDialogBox memberDialogBox = new memberDialogBox();

}

}

    package acgregistration;

    /**
     *
     * @author Frank
     */
    class acgMember {
 private String name;
 private int num;
 private String email;

 public acgMember(String name, int number, String email) {
    this.name = name;
    this.num = number;
    this.email = email;
 }

 public String getName() {
    return name;
 }

 public void setName(String name) {
    this.name = name;
 }

 public int getNum() {
    return num;
 }

 public void setNum(int num) {
     this.num = num;
 }

 public String getEmail() {
    return email;
 }

 public void setEmail(String email) {
    this.email = email;
 }
 }

 package acgregistration;
 import javax.swing.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;

 /**
 *
 * @author Frank
 */
 public class memberDialogBox {

 String options[] = {"Student","Faculty/Staff"};
 JComboBox choices = new JComboBox(options);
 JButton b = new JButton("Confirm");
 JLabel l = new JLabel("Select your ACG Status");

 public memberDialogBox(){
  frame();
 }

 public void frame(){

  JFrame f = new JFrame();
  f.setVisible(true);
  f.setSize(210,150);
  f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

  JPanel p = new JPanel();
  p.add(choices);
  p.add(b);
  p.add(l);

  f.add(p);

  b.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){

          String s = choices.getSelectedItem().toString();
          if ("Student".equals(choices.getSelectedItem())){

               studentDialogBox student = new studentDialogBox();
    //This code gives me an error code saying I should call
   //acgMemberModel

          }
          else{
                 facultyDialogBox faculty= new facultyDialogBox();
              }

        f.dispose();
          }

  });
  }

 }

 package acgregistration;
 import javax.swing.*;
 import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class studentDialogBox {
private JTextField nameField = new JTextField("", 20);
private JTextField emailField = new JTextField("", 20);
private JTextField numberField = new JTextField("", 20);
private JButton confirmButton = new JButton("Confirm");
private acgMemberModel model;

public studentDialogBox(acgMemberModel model) {
    this.model = model;
    frame();
}

public void frame() {
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    panel.add(nameField);
    panel.add(emailField);
    panel.add(numberField);
    panel.add(confirmButton);
    frame.add(panel);

    confirmButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String name = nameField.getText();
            String number = numberField.getText();
            String email = emailField.getText();
            acgMember member = new acgMember(name,
   Integer.valueOf(number), email);
            model.addNew(member);
        }
    });

   }
 }

class acgMemberModel {
private List<acgMember> members = new ArrayList<>();

public void addNew(acgMember member) {
    members.add(member);
}

public List<acgMember> getMembers() {
    return Collections.unmodifiableList(members);
}
}

I'm basically trying to do this for all the text fields and then save it into an ArrayList or a Hashmap ( basically the end result). My only question is, how would i store text field inputs from one class to another?
Any help would be highly appreciated! Thank you!


问:
Creating Web Interface with R and Shiny to upload CSV files then download after filtering some column names,
How I can build web interface to upload CSV files then filter the column names into select option 6 "as described in shiny gallery", the result from selection creating new view then download it as another CSV file,  </p>

答:
There are examples in the Shiny docs that demonstrate almost exactly what you're looking for:

Upload a CSV file

https://shiny.rstudio.com/gallery/file-upload.html

Download a CSV file

https://shiny.rstudio.com/gallery/file-download.html


问:
Is there a way to make drawRect work right NOW?
If you are an advanced user of drawRect, you will know that of course drawRect will not actually run until "all processing is finished."

setNeedsDisplay flags a view as invalidated and the OS, and basically waits until all processing is done. This can be infuriating in the common situation where you want to have:

a view controller 1

starts some function 2

which incrementally 3

creates a more and more complicated artwork and 4

at each step, you setNeedsDisplay (wrong!) 5

until all the work is done 6

Of course, when you do the above 1-6, all that happens is that drawRect is run once only after step 6.

Your goal is for the view to be refreshed at point 5. What to do?

答:
If I understand your question correctly, there is a simple solution to this.  During your long-running routine you need to tell the current runloop to process for a single iteration (or more, of the runloop) at certain points in your own processing.  e.g, when you want to update the display.  Any views with dirty update regions will have their drawRect: methods called when you run the runloop.

To tell the current runloop to process for one iteration (and then return to you...):

```<code>[[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate: [NSDate date]];
</code>```

Here's an example of an (inefficient) long running routine with a corresponding drawRect - each in the context of a custom UIView:

```<code>- (void) longRunningRoutine:(id)sender
{
    srand( time( NULL ) );

    CGFloat x = 0;
    CGFloat y = 0;

    [_path moveToPoint: CGPointMake(0, 0)];

    for ( int j = 0 ; j < 1000 ; j++ )
    {
        x = 0;
        y = (CGFloat)(rand() % (int)self.bounds.size.height);

        [_path addLineToPoint: CGPointMake( x, y)];

        y = 0;
        x = (CGFloat)(rand() % (int)self.bounds.size.width);

        [_path addLineToPoint: CGPointMake( x, y)];

        x = self.bounds.size.width;
        y = (CGFloat)(rand() % (int)self.bounds.size.height);

        [_path addLineToPoint: CGPointMake( x, y)];

        y = self.bounds.size.height;
        x = (CGFloat)(rand() % (int)self.bounds.size.width);

        [_path addLineToPoint: CGPointMake( x, y)];

        [self setNeedsDisplay];
        [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate: [NSDate date]];
    }

    [_path removeAllPoints];
}

- (void) drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor( ctx, [UIColor blueColor].CGColor );

    CGContextFillRect( ctx,  rect);

    CGContextSetStrokeColorWithColor( ctx, [UIColor whiteColor].CGColor );

    [_path stroke];
}
</code>```

And here is a fully working sample demonstrating this technique.

With some tweaking you can probably adjust this to make the rest of the UI (i.e. user-input) responsive as well.

Update (caveat for using this technique)

I just want to say that I agree with much of the feedback from others here saying this solution (calling runMode: to force a call to drawRect:) isn't necessarily a great idea.  I've answered this question with what I feel is a factual "here's how" answer to the stated question, and I am not intending to promote this as "correct" architecture.  Also, I'm not saying there might not be other (better?) ways to achieve the same effect - certainly there may be other approaches that I wasn't aware of.

Update (response to the Joe's sample code and performance question)

The performance slowdown you're seeing is the overhead of running the runloop on each iteration of your drawing code, which includes rendering the layer to the screen as well as all of the other processing the runloop does such as input gathering and processing.

One option might be to invoke the runloop less frequently.

Another option might be to optimize your drawing code.  As it stands (and I don't know if this is your actual app, or just your sample...) there are a handful of things you could do to make it faster.  The first thing I would do is move all the UIGraphicsGet/Save/Restore code outside the loop.

From an architectural standpoint however, I would highly recommend considering some of the other approaches mentioned here.  I see no reason why you can't structure your drawing to happen on a background thread (algorithm unchanged), and use a timer or other mechanism to signal the main thread to update it's UI on some frequency until the drawing is complete.  I think most of the folks who've participated in the discussion would agree that this would be the "correct" approach.

ContentLicense: CC BY-SA 4.0

Body:
If I understand your question correctly, there is a simple solution to this.  During your long-running routine you need to tell the current runloop to process for a single iteration (or more, of the runloop) at certain points in your own processing.  e.g, when you want to update the display.  Any views with dirty update regions will have their drawRect: methods called when you run the runloop.

To tell the current runloop to process for one iteration (and then return to you...):

[[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate: [NSDate date]];

Here's an example of an (inefficient) long running routine with a corresponding drawRect - each in the context of a custom UIView:

- (void) longRunningRoutine:(id)sender
{
    srand( time( NULL ) );

    CGFloat x = 0;
    CGFloat y = 0;

    [_path moveToPoint: CGPointMake(0, 0)];

    for ( int j = 0 ; j < 1000 ; j++ )
    {
        x = 0;
        y = (CGFloat)(rand() % (int)self.bounds.size.height);

        [_path addLineToPoint: CGPointMake( x, y)];

        y = 0;
        x = (CGFloat)(rand() % (int)self.bounds.size.width);

        [_path addLineToPoint: CGPointMake( x, y)];

        x = self.bounds.size.width;
        y = (CGFloat)(rand() % (int)self.bounds.size.height);

        [_path addLineToPoint: CGPointMake( x, y)];

        y = self.bounds.size.height;
        x = (CGFloat)(rand() % (int)self.bounds.size.width);

        [_path addLineToPoint: CGPointMake( x, y)];

        [self setNeedsDisplay];
        [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate: [NSDate date]];
    }

    [_path removeAllPoints];
}

- (void) drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor( ctx, [UIColor blueColor].CGColor );

    CGContextFillRect( ctx,  rect);

    CGContextSetStrokeColorWithColor( ctx, [UIColor whiteColor].CGColor );

    [_path stroke];
}

And here is a fully working sample demonstrating this technique.

With some tweaking you can probably adjust this to make the rest of the UI (i.e. user-input) responsive as well.

Update (caveat for using this technique)

I just want to say that I agree with much of the feedback from others here saying this solution (calling runMode: to force a call to drawRect:) isn't necessarily a great idea.  I've answered this question with what I feel is a factual "here's how" answer to the stated question, and I am not intending to promote this as "correct" architecture.  Also, I'm not saying there might not be other (better?) ways to achieve the same effect - certainly there may be other approaches that I wasn't aware of.

Update (response to the Joe's sample code and performance question)

The performance slowdown you're seeing is the overhead of running the runloop on each iteration of your drawing code, which includes rendering the layer to the screen as well as all of the other processing the runloop does such as input gathering and processing.

One option might be to invoke the runloop less frequently.

Another option might be to optimize your drawing code.  As it stands (and I don't know if this is your actual app, or just your sample...) there are a handful of things you could do to make it faster.  The first thing I would do is move all the UIGraphicsGet/Save/Restore code outside the loop.

From an architectural standpoint however, I would highly recommend considering some of the other approaches mentioned here.  I see no reason why you can't structure your drawing to happen on a background thread (algorithm unchanged), and use a timer or other mechanism to signal the main thread to update it's UI on some frequency until the drawing is complete.  I think most of the folks who've participated in the discussion would agree that this would be the "correct" approach.


问:
Reverse engineering a zImage
So I have a custom kernel for an embedded arm device which I had worked on some time ago. I've revisited the project but since have reinstalled Ubuntu on my development machine. I can't compile a new zImage correctly as before. I have found an old SD which card which has the correctly compiled and working zImage.

I suspect I'm missing some build option configuration which the old zImage had. Is there a way to reverse engineer and figure out exactly how my older zImage was created?

答:
Only works if you have CONFIG_IKCONFIG enabled in the zImage.

You can extract old config using ./scripts/extract-ikconfig from the linux kernel or ./scripts/ikconfig (depending on the version of the source) if your kernel was compiled with CONFIG_IKCONFIG enabled (usually is by default)

Without CONFIG_IKCONFIG

Hope that you also have a config.gz along with your zImage on the SD card :P

Title: Reverse engineering a zImage


问:
How can I make this python code shorter and more efficient
This is my attempt at doing a higher/lower game.

```<code>import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = int(input("Please pick a number between 1 & 100: "))
if choice < number:
    print("Higher")
elif choice > number:
    print("Lower")
else:
    print("Well done!")
while choice != number:
    choice = int(input("Pick again: "))
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")
</code>```

I'm new to python and I'm just wondering is there a way of shortening the code to make it more efficient? Don't think there is a need for two 'if/elif/else' statements but can't see a way to merge them. Sorry if it's a stupid question!

Updated Code:

```<code>import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = ""
while choice != number:
    choice = int(input("Please pick a number: "))
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")
</code>```

答:
You may try something like this:

```<code>import random
print("A game of Higher or Lower")

number = random.randint(1, 100)
choice = int(input("Please pick a number between 1 & 100: "))

while choice != number:
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")

    choice = int(input("Pick again: "))

print("Well done")
</code>```

Encapsulating the code that check user input may also be a good idea.

Body:
This is my attempt at doing a higher/lower game.

import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = int(input("Please pick a number between 1 & 100: "))
if choice < number:
    print("Higher")
elif choice > number:
    print("Lower")
else:
    print("Well done!")
while choice != number:
    choice = int(input("Pick again: "))
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")

I'm new to python and I'm just wondering is there a way of shortening the code to make it more efficient? Don't think there is a need for two 'if/elif/else' statements but can't see a way to merge them. Sorry if it's a stupid question!

Updated Code:

import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = ""
while choice != number:
    choice = int(input("Please pick a number: "))
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")

Body:
You may try something like this:

import random
print("A game of Higher or Lower")

number = random.randint(1, 100)
choice = int(input("Please pick a number between 1 & 100: "))

while choice != number:
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")

    choice = int(input("Pick again: "))

print("Well done")

Encapsulating the code that check user input may also be a good idea.


问:
OcamL lazy list series generating
I've got a problem with this task:

Define lazy list lSpec (Ocaml) that contains one 1, two 2, three 3 etc. 1,2,2,3,3,3,4,4,4,4,5,...

As far I have got:

```<code>type 'a llist = LNil | LCons of 'a * (unit -> 'a llist);;

let rec lfrom k = LCons (k, function () -> lfrom (k+1));;

let rec ltake = function
(0, _) -> []
| (_, LNil) -> []
| (n, LCons(x,xf)) -> x::ltake(n-1, xf()) ;;
</code>```

This function is generating the series of integer based on input numer, eg.

```<code>ltake (5,lfrom 30);;
- : int list = [30; 31; 32; 33; 34]
</code>```

The thing that I want to do i to convert function lfrom to create not series of integers, but the series from my task. But I have no idea if there is some pattern to create such series?

Thanks for help in advance.

答:
The code you have now uses just one value k to keep track of where it is in the sequence. Fundamentally this would be enough for the new problem, but using just one number for the state would make things difficult to keep track of.

You might consider something like:

```<code>let rec lspecfrom (j, k) = . . .
</code>```

Where j is the number you're working on (1, 2, 3, 4, ...) and k is how many have been generated so far. Then the whole list would be generated by a call lspecfrom (1, 0).

Title: OcamL lazy list series generating

Body:
I've got a problem with this task:

Define lazy list lSpec (Ocaml) that contains one 1, two 2, three 3 etc. 1,2,2,3,3,3,4,4,4,4,5,...

As far I have got:

type 'a llist = LNil | LCons of 'a * (unit -> 'a llist);;

let rec lfrom k = LCons (k, function () -> lfrom (k+1));;

let rec ltake = function
(0, _) -> []
| (_, LNil) -> []
| (n, LCons(x,xf)) -> x::ltake(n-1, xf()) ;;

This function is generating the series of integer based on input numer, eg.

ltake (5,lfrom 30);;
- : int list = [30; 31; 32; 33; 34]

The thing that I want to do i to convert function lfrom to create not series of integers, but the series from my task. But I have no idea if there is some pattern to create such series?

Thanks for help in advance.

Body:
The code you have now uses just one value k to keep track of where it is in the sequence. Fundamentally this would be enough for the new problem, but using just one number for the state would make things difficult to keep track of.

You might consider something like:

let rec lspecfrom (j, k) = . . .

Where j is the number you're working on (1, 2, 3, 4, ...) and k is how many have been generated so far. Then the whole list would be generated by a call lspecfrom (1, 0).


问:
Following links in python assignment using Beautifulsoup
I have this assignment for a python class where I have to start from a specific link at a specific position, then follow that link for a specific number of times. Supposedly the first link has the position 1.
This is the link: http://python-data.dr-chuck.net/known_by_Fikret.html

traceback error picture
I have trouble with locating the link, the error "index out of range" comes out. can anyone help with figuring out how to locate the link/position? This is my code:

```<code>import urllib
from BeautifulSoup import *

url = raw_input('Enter - ')
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
count = int(raw_input('Enter count: '))+1
position = int(raw_input('Enter position: '))

tags = soup('a')
tags_lst = list()
for tag in tags:
    needed_tag = tag.get('href', None)
    tags_lst.append(needed_tag)
    for i in range(0,count):
        print 'retrieving: ',tags_lst[position]
</code>```

OK I wrote this code and it kind of works:

```<code>import urllib
from BeautifulSoup import *

url = raw_input('Enter - ')
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
count = int(raw_input('Enter count: '))+1
position = int(raw_input('Enter position: '))

tags = soup('a')
tags_lst = list()
for tag in tags:
    needed_tag = tag.get('href', None)
    tags_lst.append(needed_tag)
for i in range(0,count):
    print 'retrieving: ',tags_lst[position]
    position = position + 1
</code>```

I'm still getting other links than the ones in the example however when I print the whole list of links the positions match so I don't know. Very weird.

答:
[Edit: Cut+pasted this line from comments] Hi! I had to work in a similar exercise, and because i had some doubts i found your question. Here is my code and I think it works. I hope it will be helpful for you</p>

```<code>import urllib
from bs4 import BeautifulSoup

url = 'http://py4e-data.dr-chuck.net/known_by_Fikret.html'
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')
count = 8
position = 18
tags_lst = []

for x in xrange(count-1):
    tags = soup('a')
    my_tags = tags[position-1]
    needed_tag = my_tags.get('href', None)
    tags_lst.append(needed_tag)
    url = str(needed_tag)
    html = urllib.urlopen(url).read()
    soup = BeautifulSoup(html, 'html.parser')
</code>```

Body:
I have this assignment for a python class where I have to start from a specific link at a specific position, then follow that link for a specific number of times. Supposedly the first link has the position 1.
This is the link: http://python-data.dr-chuck.net/known_by_Fikret.html

traceback error picture
I have trouble with locating the link, the error "index out of range" comes out. can anyone help with figuring out how to locate the link/position? This is my code:

import urllib
from BeautifulSoup import *

url = raw_input('Enter - ')
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
count = int(raw_input('Enter count: '))+1
position = int(raw_input('Enter position: '))

tags = soup('a')
tags_lst = list()
for tag in tags:
    needed_tag = tag.get('href', None)
    tags_lst.append(needed_tag)
    for i in range(0,count):
        print 'retrieving: ',tags_lst[position]

OK I wrote this code and it kind of works:

import urllib
from BeautifulSoup import *

url = raw_input('Enter - ')
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
count = int(raw_input('Enter count: '))+1
position = int(raw_input('Enter position: '))

tags = soup('a')
tags_lst = list()
for tag in tags:
    needed_tag = tag.get('href', None)
    tags_lst.append(needed_tag)
for i in range(0,count):
    print 'retrieving: ',tags_lst[position]
    position = position + 1

I'm still getting other links than the ones in the example however when I print the whole list of links the positions match so I don't know. Very weird.

Body:
[Edit: Cut+pasted this line from comments] Hi! I had to work in a similar exercise, and because i had some doubts i found your question. Here is my code and I think it works. I hope it will be helpful for you

import urllib
from bs4 import BeautifulSoup

url = 'http://py4e-data.dr-chuck.net/known_by_Fikret.html'
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')
count = 8
position = 18
tags_lst = []

for x in xrange(count-1):
    tags = soup('a')
    my_tags = tags[position-1]
    needed_tag = my_tags.get('href', None)
    tags_lst.append(needed_tag)
    url = str(needed_tag)
    html = urllib.urlopen(url).read()
    soup = BeautifulSoup(html, 'html.parser')


答:
Here's one approach with slicing and argmax (to detect non-zeros and zeros) -

```<code>def start_stop_indices(freq_arr, W=3):
    nnz_mask = freq_arr!=0
    start_idx = nnz_mask.argmax()
    m0 = nnz_mask[start_idx:]
    kernel = np.ones(W,dtype=int)
    last_idx = np.convolve(m0, kernel).argmin() + start_idx - W
    return start_idx, last_idx
</code>```

Sample runs -

```<code>In [203]: freq_arr
Out[203]: array([0, 0, 0, 0, 5, 6, 0, 8, 9, 0, 1, 0, 0, 0, 0, 3, 6, 0])

In [204]: start_stop_indices(freq_arr, W=3)
Out[204]: (4, 10)

In [205]: start_stop_indices(freq_arr, W=2)
Out[205]: (4, 10)

In [206]: start_stop_indices(freq_arr, W=1)
Out[206]: (4, 5)
</code>```

Here's another for the fixed window search of length = 3, avoiding the use of convolution and making more use of slicing -

```<code>def start_stop_indices_v2(freq_arr):
    nnz_mask = freq_arr!=0
    start_idx = nnz_mask.argmax()
    m0 = nnz_mask[start_idx:]
    idx0 = (m0[:-2] | m0[1:-1] | m0[2:]).argmin()
    last_idx = idx0 + start_idx - 1
    return  start_idx, last_idx
</code>```

Title: First group of non-zero values (by neglecting single occurrence of zero)

Body:
Here's one approach with slicing and argmax (to detect non-zeros and zeros) -

def start_stop_indices(freq_arr, W=3):
    nnz_mask = freq_arr!=0
    start_idx = nnz_mask.argmax()
    m0 = nnz_mask[start_idx:]
    kernel = np.ones(W,dtype=int)
    last_idx = np.convolve(m0, kernel).argmin() + start_idx - W
    return start_idx, last_idx

Sample runs -

In [203]: freq_arr
Out[203]: array([0, 0, 0, 0, 5, 6, 0, 8, 9, 0, 1, 0, 0, 0, 0, 3, 6, 0])

In [204]: start_stop_indices(freq_arr, W=3)
Out[204]: (4, 10)

In [205]: start_stop_indices(freq_arr, W=2)
Out[205]: (4, 10)

In [206]: start_stop_indices(freq_arr, W=1)
Out[206]: (4, 5)

Here's another for the fixed window search of length = 3, avoiding the use of convolution and making more use of slicing -

def start_stop_indices_v2(freq_arr):
    nnz_mask = freq_arr!=0
    start_idx = nnz_mask.argmax()
    m0 = nnz_mask[start_idx:]
    idx0 = (m0[:-2] | m0[1:-1] | m0[2:]).argmin()
    last_idx = idx0 + start_idx - 1
    return  start_idx, last_idx


问:
Javascript Passing variable arguments to superclass constructor
What is the best/recommended way to pass variable arguments to a superclass constructor?  The background explains the problem I'm trying to solve.

Background

I'm porting some code from Java to Javascript.  One of the coding patterns that Java has is function overloading.  Java picks the best match to determine what function to call.  This becomes interesting when the function is a Class constructor method.

So code in Java might be

```<code>public class MyParser extends Parser {
    public int parse(String str) { super(str); ... }
    public int parse(String str, int base) { super(str, base); ... }
}
</code>```

In Javascript becomes:

```<code>class MyParser extends Parser {
    constructor(){
        super(arguments); // THIS DOES NOT WORK
        if (arguments.length === 1 && typeof arguments[0] === 'string'){
            constructor_1arg(arguments[0]);
        } else if (...){
            constructor_2args(arguments[0], arguments[1]);
        }
    }
}
</code>```

So I was wondering what is the best way to handle this case?

Possible solution

NOTE: I'm asking this because calling super() is a special case in a constructor and you can only call it once.  So I didn't expect this to work but it did (in NodeJS v8.2).

```<code>class MyParserTry2 extends Parser {
    constructor(){
        console.log('MyParser2 passed ' + arguments.length + ' args. ', arguments);
        if (arguments.length === 1 && typeof arguments[0] === 'string'){
            super(arguments[0]);
            this.constructor_1arg(arguments[0]);
        } else if (arguments.length === 2 && typeof arguments[0] === 'string'){
            super(arguments[0], arguments[1]);
            this.constructor_2args(arguments[0], arguments[1]);
        }
    }

    constructor_1arg(arg1){ }
    constructor_2args(arg1, arg2){ }
}
</code>```

I thought super() had to be called before other code, but this might be from another language.  Does Javascript standard support calling super() as shown in this code snippet?

Previous answers/research

I searched StackOverflow for answers and found several similar questions but not this one.  I found these questions or postings:

Passing all arguments forward to another javascript function.  Thanks to @BobStein-VisiBone who suggested that this question be re-opened because it is slightly different than the following question.  He also suggested searching on javascript pass all callers arguments to inner function

Passing an array as a function parameter

It was important to realize that arguments is not an array and can't be used to just pass along arguments to an inner function.  See Understanding what arguments object really is

Using apply() was suggested in some posts, but I didn't see anyone using super.apply(this, arguments).  If this is the best way to handle this question suggest this as the answer, but realize that my observations are that "this" is not set until after super() is called.  Interesting...

What I tried is at JSFiddle.  You'll have to open your browsers console to see log messages.  Sorry it's not easier to use.

None of the above, however, answer my question.

So... What is the best/recommended way to pass variable arguments to a superclass constructor?

答:
```<code>class SomeClass extends SomeSuperClass {
 constructor(...args){ super(...args); }
}
</code>```

Using arguments is deprecated so you could rather use rest/spread operators.

Body:
What is the best/recommended way to pass variable arguments to a superclass constructor?  The background explains the problem I'm trying to solve.

Background

I'm porting some code from Java to Javascript.  One of the coding patterns that Java has is function overloading.  Java picks the best match to determine what function to call.  This becomes interesting when the function is a Class constructor method.

So code in Java might be

public class MyParser extends Parser {
    public int parse(String str) { super(str); ... }
    public int parse(String str, int base) { super(str, base); ... }
}

In Javascript becomes:

class MyParser extends Parser {
    constructor(){
        super(arguments); // THIS DOES NOT WORK
        if (arguments.length === 1 && typeof arguments[0] === 'string'){
            constructor_1arg(arguments[0]);
        } else if (...){
            constructor_2args(arguments[0], arguments[1]);
        }
    }
}

So I was wondering what is the best way to handle this case?

Possible solution

NOTE: I'm asking this because calling super() is a special case in a constructor and you can only call it once.  So I didn't expect this to work but it did (in NodeJS v8.2).

class MyParserTry2 extends Parser {
    constructor(){
        console.log('MyParser2 passed ' + arguments.length + ' args. ', arguments);
        if (arguments.length === 1 && typeof arguments[0] === 'string'){
            super(arguments[0]);
            this.constructor_1arg(arguments[0]);
        } else if (arguments.length === 2 && typeof arguments[0] === 'string'){
            super(arguments[0], arguments[1]);
            this.constructor_2args(arguments[0], arguments[1]);
        }
    }

    constructor_1arg(arg1){ }
    constructor_2args(arg1, arg2){ }
}

I thought super() had to be called before other code, but this might be from another language.  Does Javascript standard support calling super() as shown in this code snippet?

Previous answers/research

I searched StackOverflow for answers and found several similar questions but not this one.  I found these questions or postings:

Passing all arguments forward to another javascript function.  Thanks to @BobStein-VisiBone who suggested that this question be re-opened because it is slightly different than the following question.  He also suggested searching on javascript pass all callers arguments to inner function

Passing an array as a function parameter

It was important to realize that arguments is not an array and can't be used to just pass along arguments to an inner function.  See Understanding what arguments object really is

Using apply() was suggested in some posts, but I didn't see anyone using super.apply(this, arguments).  If this is the best way to handle this question suggest this as the answer, but realize that my observations are that "this" is not set until after super() is called.  Interesting...

What I tried is at JSFiddle.  You'll have to open your browsers console to see log messages.  Sorry it's not easier to use.

None of the above, however, answer my question.

So... What is the best/recommended way to pass variable arguments to a superclass constructor?

Body:
class SomeClass extends SomeSuperClass {
 constructor(...args){ super(...args); }
}

Using arguments is deprecated so you could rather use rest/spread operators.


问:
Why passing &error instead of error in Cocoa programming?
In Cocoa programming, when dealing with NSError, why we are passing &error to a message instead of error?</p>

```<code>NSError *error;
if (![managedObject.managedObjectContext save:&error])
   //Code
</code>```

答:
NSError's fields are not settable. its interface is opaque and immutable. therefore, if you were to alloc/init an error, the client could not populate it. thus, the approach is to return a new error (if applicable), also saving you from allocs in every case.

since the return type is already specified by the method, and the error is optional, it makes sense to take this approach to returning the error in idiomatic c syntax.

iow, the client may neither mutate what you pass nor return the error using :(NSError *)outError, so the "out parameter" form :(NSError**)outError is applied.

ContentLicense: CC BY-SA 2.5

Body:
In Cocoa programming, when dealing with NSError, why we are passing &error to a message instead of error?

NSError *error;
if (![managedObject.managedObjectContext save:&error])
   //Code


问:
Mongodb get count of arrayitems over all collection items
I have a mongodb-collection like this:

```<code>{
    _id: 123,
    name: 'some name',
    category: 17,
    sizes: ['XS', 'S', 'XL']
},
{
    _id: 124,
    name: 'another name',
    category: 17,
    sizes: ['S', 'L', '2XL']
}
</code>```

I need two different approaches. First one: How many items per size are available in a specific category?

```<code>{
    17: {
        XS: 0,
        S:  19,
        M:  100
    },
    39: {
        XS: 5,
        ...
    }
}
</code>```

A solution, which just shows if an item in the size is available would also be possible:

```<code>{
    17: {
        XS: false,
        S:  true,
        M:  true,
        ...
    },
    39: {
        XS: true,
        ...
    }
}
</code>```

Second problem: I need the same, but after performing a full-text-search on a name.

I've tried to aggregate over the fields, but I'm a bit lost on how to perform that on the array.

Any help appreciated.

Update:

With help from this answer, I'm one step closer:

```<code>db.so.aggregate(
    [
        // First, filter by name or something else
        // this could also include the category
        {
            $match: {
                'name': {
                    $regex: /other.*/i
                }
            }
        },

        // explode the sizes-array into single documents
        { '$unwind': '$sizes' },

        // group and count
        { '$group': {
            '_id': '$sizes',
            'count': { '$sum': 1 }
        }}
    ]
)
</code>```

Still missing: do this by category

答:
NOTE: Projection will be added soon.

You can

unwind -> group on category and size -> group on category and push -> project

Please refer to the below query. This will give a result without any projection. I will add the projection to match your requirement soon.

```<code>var group_by_category_and_sizes = {
  "$group": {
    "_id": {
        "category": "$category",
        "size": "$sizes"
      },
      "count": {
        "$sum": 1
      }
    }
  }

var group_by_category_and_push = {
  "$group": {
    "_id": {
      "category": "$_id.category"
    },
    "combine": {
      "$push": { "size": "$_id.size", "count": "$count" }
    }
  }
}

db.clothings.aggregate([{ "$unwind": "$sizes" }, group_by_category_and_sizes, group_by_category_and_push])
</code>```

For documents

{ name: 'some name', category: 17, sizes: ['XS', 'S', 'XL'] }

{ name: 'another name', category: 17, sizes: ['S', 'L', '2XL'] }

{ name: 'another name', category: 18, sizes: ['M', 'S', 'L'] }

this will produce

```<code>{
    "_id": {
        "category": 18
    },
    "combine": [{
        "size": "L",
        "count": 1
    }, {
        "size": "S",
        "count": 1
    }, {
        "size": "M",
        "count": 1
    }]
} {
    "_id": {
        "category": 17
    },
    "combine": [{
        "size": "2XL",
        "count": 1
    }, {
        "size": "S",
        "count": 2
    }, {
        "size": "XL",
        "count": 1
    }, {
        "size": "L",
        "count": 1
    }, {
        "size": "XS",
        "count": 1
    }]
}
</code>```

Body:
I have a mongodb-collection like this:

{
    _id: 123,
    name: 'some name',
    category: 17,
    sizes: ['XS', 'S', 'XL']
},
{
    _id: 124,
    name: 'another name',
    category: 17,
    sizes: ['S', 'L', '2XL']
}

I need two different approaches. First one: How many items per size are available in a specific category?

{
    17: {
        XS: 0,
        S:  19,
        M:  100
    },
    39: {
        XS: 5,
        ...
    }
}

A solution, which just shows if an item in the size is available would also be possible:

{
    17: {
        XS: false,
        S:  true,
        M:  true,
        ...
    },
    39: {
        XS: true,
        ...
    }
}

Second problem: I need the same, but after performing a full-text-search on a name.

I've tried to aggregate over the fields, but I'm a bit lost on how to perform that on the array.

Any help appreciated.

Update:

With help from this answer, I'm one step closer:

db.so.aggregate(
    [
        // First, filter by name or something else
        // this could also include the category
        {
            $match: {
                'name': {
                    $regex: /other.*/i
                }
            }
        },

        // explode the sizes-array into single documents
        { '$unwind': '$sizes' },

        // group and count
        { '$group': {
            '_id': '$sizes',
            'count': { '$sum': 1 }
        }}
    ]
)

Still missing: do this by category

Body:
NOTE: Projection will be added soon.

You can

unwind -> group on category and size -> group on category and push -> project

Please refer to the below query. This will give a result without any projection. I will add the projection to match your requirement soon.

var group_by_category_and_sizes = {
  "$group": {
    "_id": {
        "category": "$category",
        "size": "$sizes"
      },
      "count": {
        "$sum": 1
      }
    }
  }

var group_by_category_and_push = {
  "$group": {
    "_id": {
      "category": "$_id.category"
    },
    "combine": {
      "$push": { "size": "$_id.size", "count": "$count" }
    }
  }
}

db.clothings.aggregate([{ "$unwind": "$sizes" }, group_by_category_and_sizes, group_by_category_and_push])

For documents

{ name: 'some name', category: 17, sizes: ['XS', 'S', 'XL'] }

{ name: 'another name', category: 17, sizes: ['S', 'L', '2XL'] }

{ name: 'another name', category: 18, sizes: ['M', 'S', 'L'] }

this will produce

{
    "_id": {
        "category": 18
    },
    "combine": [{
        "size": "L",
        "count": 1
    }, {
        "size": "S",
        "count": 1
    }, {
        "size": "M",
        "count": 1
    }]
} {
    "_id": {
        "category": 17
    },
    "combine": [{
        "size": "2XL",
        "count": 1
    }, {
        "size": "S",
        "count": 2
    }, {
        "size": "XL",
        "count": 1
    }, {
        "size": "L",
        "count": 1
    }, {
        "size": "XS",
        "count": 1
    }]
}


问:
Django form clean() method not raising errors when a ValidationError occurs
I am trying to create a custom validator for my form by overwriting the clean() method, and for some reason validation errors are not being raised properly. Here's my code:

forms.py

```<code>from django import forms
from django.contrib.auth import get_user_model

class EmailForm(forms.Form):
    email_field = forms.EmailField(label='E-mail address', max_length=128)

    def clean(self):
         cleaned_data = super(EmailForm, self).clean()
         email = cleaned_data.get('email')

         try:
            u = get_user_model().objects.get(email=email)
            raise forms.ValidationError("E-mail already in database.")
            print('validation error raised')
        except:
            pass
</code>```

views.py

```<code>from django.shortcuts import render
from django.contrib import messages

from .forms import EmailForm

def email_form(request):
    if request.method == 'POST':
        form = EmailForm(request.POST)

        # If the form is valid...
        if form.is_valid():
            messages.add_message(request, messages.SUCCESS, "Kaboom! Your referral e-mail was sent. Hang tight - we'll be sure to let you know when your friend makes a purchase.")
        else:
            messages.add_message(request, messages.ERROR, 'Error!')
   else:
       form = EmailForm()

   return render(request, 'template.html', {'form': form})
</code>```

template.html

```<code><form action="{% url 'form-process' %}" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
</form>
</code>```

When I submit this form with input that should raise a validation error (i.e., an e-mail address that is already associated with a user in my database), I get the 'success' message rather than an error. The strangest part about it is that 'validation error raised' is printed in my console — but for some reason the form processes and form.is_valid() passes as True.

Can anyone tell me why form.is_valid doesn't output an error in the code below when a duplicate e-mail is entered?

答:
It can't raise exception, because you catch is in except.</p>
```<code>def clean(self):
     cleaned_data = super(EmailForm, self).clean()
     email = cleaned_data.get('email')

     users = get_user_model().objects.filter(email=email)
     if users.exists():
         raise forms.ValidationError("E-mail already in database.")
</code>```

Body:
I am trying to create a custom validator for my form by overwriting the clean() method, and for some reason validation errors are not being raised properly. Here's my code:

forms.py

from django import forms
from django.contrib.auth import get_user_model

class EmailForm(forms.Form):
    email_field = forms.EmailField(label='E-mail address', max_length=128)

    def clean(self):
         cleaned_data = super(EmailForm, self).clean()
         email = cleaned_data.get('email')

         try:
            u = get_user_model().objects.get(email=email)
            raise forms.ValidationError("E-mail already in database.")
            print('validation error raised')
        except:
            pass

views.py

from django.shortcuts import render
from django.contrib import messages

from .forms import EmailForm

def email_form(request):
    if request.method == 'POST':
        form = EmailForm(request.POST)

        # If the form is valid...
        if form.is_valid():
            messages.add_message(request, messages.SUCCESS, "Kaboom! Your referral e-mail was sent. Hang tight - we'll be sure to let you know when your friend makes a purchase.")
        else:
            messages.add_message(request, messages.ERROR, 'Error!')
   else:
       form = EmailForm()

   return render(request, 'template.html', {'form': form})

template.html

<form action="{% url 'form-process' %}" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
</form>

When I submit this form with input that should raise a validation error (i.e., an e-mail address that is already associated with a user in my database), I get the 'success' message rather than an error. The strangest part about it is that 'validation error raised' is printed in my console — but for some reason the form processes and form.is_valid() passes as True.

Can anyone tell me why form.is_valid doesn't output an error in the code below when a duplicate e-mail is entered?

Body:
It can't raise exception, because you catch is in except.

def clean(self):
     cleaned_data = super(EmailForm, self).clean()
     email = cleaned_data.get('email')

     users = get_user_model().objects.filter(email=email)
     if users.exists():
         raise forms.ValidationError("E-mail already in database.")


问:
Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...
I am trying to convert a timestamp of the format 2009-09-12 20:57:19 and turn it into something like 3 minutes ago with PHP.

I found a useful script to do this, but I think it's looking for a different format to be used as the time variable. The script I'm wanting to modify to work with this format is:

```<code>function _ago($tm,$rcs = 0) {
    $cur_tm = time();
    $dif = $cur_tm-$tm;
    $pds = array('second','minute','hour','day','week','month','year','decade');
    $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);

    for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
        $no = floor($no);
        if($no <> 1)
            $pds[$v] .='s';
        $x = sprintf("%d %s ",$no,$pds[$v]);
        if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0))
            $x .= time_ago($_tm);
        return $x;
    }
</code>```

I think on those first few lines the script is trying to do something that looks like this (different date format math):

```<code>$dif = 1252809479 - 2009-09-12 20:57:19;
</code>```

How would I go about converting my timestamp into that (unix?) format?

答:
This is what I went with. Its a modified version of Abbbas khan's post:</p>

```<code><?php

  function calculate_time_span($post_time)
  {
  $seconds = time() - strtotime($post);
  $year = floor($seconds /31556926);
  $months = floor($seconds /2629743);
  $week=floor($seconds /604800);
  $day = floor($seconds /86400);
  $hours = floor($seconds / 3600);
  $mins = floor(($seconds - ($hours*3600)) / 60);
  $secs = floor($seconds % 60);
  if($seconds < 60) $time = $secs." seconds ago";
  else if($seconds < 3600 ) $time =($mins==1)?$mins."now":$mins." mins ago";
  else if($seconds < 86400) $time = ($hours==1)?$hours." hour ago":$hours." hours ago";
  else if($seconds < 604800) $time = ($day==1)?$day." day ago":$day." days ago";
  else if($seconds < 2629743) $time = ($week==1)?$week." week ago":$week." weeks ago";
  else if($seconds < 31556926) $time =($months==1)? $months." month ago":$months." months ago";
  else $time = ($year==1)? $year." year ago":$year." years ago";
  return $time;
  }

 // uses
 // $post_time="2017-12-05 02:05:12";
 // echo calculate_time_span($post_time);
</code>```

Body:
I am trying to convert a timestamp of the format 2009-09-12 20:57:19 and turn it into something like 3 minutes ago with PHP.

I found a useful script to do this, but I think it's looking for a different format to be used as the time variable. The script I'm wanting to modify to work with this format is:

function _ago($tm,$rcs = 0) {
    $cur_tm = time();
    $dif = $cur_tm-$tm;
    $pds = array('second','minute','hour','day','week','month','year','decade');
    $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);

    for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
        $no = floor($no);
        if($no <> 1)
            $pds[$v] .='s';
        $x = sprintf("%d %s ",$no,$pds[$v]);
        if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0))
            $x .= time_ago($_tm);
        return $x;
    }

I think on those first few lines the script is trying to do something that looks like this (different date format math):

$dif = 1252809479 - 2009-09-12 20:57:19;

How would I go about converting my timestamp into that (unix?) format?

Body:
This is what I went with. Its a modified version of Abbbas khan's post:

<?php

  function calculate_time_span($post_time)
  {
  $seconds = time() - strtotime($post);
  $year = floor($seconds /31556926);
  $months = floor($seconds /2629743);
  $week=floor($seconds /604800);
  $day = floor($seconds /86400);
  $hours = floor($seconds / 3600);
  $mins = floor(($seconds - ($hours*3600)) / 60);
  $secs = floor($seconds % 60);
  if($seconds < 60) $time = $secs." seconds ago";
  else if($seconds < 3600 ) $time =($mins==1)?$mins."now":$mins." mins ago";
  else if($seconds < 86400) $time = ($hours==1)?$hours." hour ago":$hours." hours ago";
  else if($seconds < 604800) $time = ($day==1)?$day." day ago":$day." days ago";
  else if($seconds < 2629743) $time = ($week==1)?$week." week ago":$week." weeks ago";
  else if($seconds < 31556926) $time =($months==1)? $months." month ago":$months." months ago";
  else $time = ($year==1)? $year." year ago":$year." years ago";
  return $time;
  }

 // uses
 // $post_time="2017-12-05 02:05:12";
 // echo calculate_time_span($post_time);


问:
C++ Searching for a word in a CSV file
I am trying to create a program that stores data from a CSV file and then searches it for key words.
I have this code, and there are no errors shown, but it wont run the program past asking for 'Enter word: '</p>

```<code>#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>

using namespace std;

int main(){

    vector<string> student(860);
    vector<string> question(860);
    vector<string> answer(860);

    int count = 0;
    string word;

    ifstream file("data2.csv");

    if (!file.is_open())
        cerr << "File not found" << endl;

    while (file.good()){

        for (int i = 0; i < 860; i++){

            getline(file, student[i], ',');
            getline(file, question[i], ',');
            getline(file, answer[i], ',');
        }
    }

    cout << "Enter word: ";
    cin >> word;

    for (int j = 0; j < 860; j++){
        if (answer[j].find(word) != std::string::npos){
            cout << student[j] << question[j] << answer[j] << endl;
            count++;
        }
    }

    cout << count;

    return 0;
}
</code>```

答:
In order to get std::cin to contain the exact string (multiple words?) that the user inputs, you can use std::getline() which will support more than one word specified by the user. It's not clear from your problem statement if this is what you want or not.  Otherwise I don't see a problem with just using std::cin if all you're looking for is a single word of input.

```<code>std::string match;
std::cout << "Enter the exact string to search for: ";
std::getline(std::cin, match);
std::cout << "\nSearching for \"" << match << "\"" << std::endl;
</code>```

Also, in your for loop for searching the answer strings, you should prefer to use the built in size of the vector you're looping through as opposed to a hard coded value.

```<code>for ( size_t j = 0; j < answer.size(); ++j )
{
    std::size_t found = answer[j].find(match);
    if (found != std::string::npos)
    {
        std::cout << "found \"" << match
            << "\" starting at character " << found << std::endl;
        count++;
    }
}
std::cout << "occurrences of match criteria: " << count << std::endl;
</code>```

Title: C++ Searching for a word in a CSV file

Body:
I am trying to create a program that stores data from a CSV file and then searches it for key words.
I have this code, and there are no errors shown, but it wont run the program past asking for 'Enter word: '

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>

using namespace std;

int main(){

    vector<string> student(860);
    vector<string> question(860);
    vector<string> answer(860);

    int count = 0;
    string word;

    ifstream file("data2.csv");

    if (!file.is_open())
        cerr << "File not found" << endl;

    while (file.good()){

        for (int i = 0; i < 860; i++){

            getline(file, student[i], ',');
            getline(file, question[i], ',');
            getline(file, answer[i], ',');
        }
    }

    cout << "Enter word: ";
    cin >> word;

    for (int j = 0; j < 860; j++){
        if (answer[j].find(word) != std::string::npos){
            cout << student[j] << question[j] << answer[j] << endl;
            count++;
        }
    }

    cout << count;

    return 0;
}

Body:
In order to get std::cin to contain the exact string (multiple words?) that the user inputs, you can use std::getline() which will support more than one word specified by the user. It's not clear from your problem statement if this is what you want or not.  Otherwise I don't see a problem with just using std::cin if all you're looking for is a single word of input.

std::string match;
std::cout << "Enter the exact string to search for: ";
std::getline(std::cin, match);
std::cout << "\nSearching for \"" << match << "\"" << std::endl;

Also, in your for loop for searching the answer strings, you should prefer to use the built in size of the vector you're looping through as opposed to a hard coded value.

for ( size_t j = 0; j < answer.size(); ++j )
{
    std::size_t found = answer[j].find(match);
    if (found != std::string::npos)
    {
        std::cout << "found \"" << match
            << "\" starting at character " << found << std::endl;
        count++;
    }
}
std::cout << "occurrences of match criteria: " << count << std::endl;


问:
How to derive the equation of a density distribution in SAS?
I am using the following procedure to get the density plot of transaction counts:

```<code>PROC SGPLOT DATA = Tran_Restaurant ;
  density Transaction_Count/ scale=density ;
  "Restaurant Transaction Count";
  XAXIS LABEL = 'Transaction_Count' GRID VALUES = (0 TO 100 BY 10);
RUN;
</code>```

Sample Data:

```<code>Customer_ID   Transaction_Count
1213x         23
2131x         14
</code>```

Customer_ID is distinct in the data set.
So, from the plot for each transaction_count we can get the number of customers.

I wanted to get the equation of the density curve? Is it possible to do that in SAS?

答:
If you know that your data is normal, you can estimate the distribution using PROC UNIVARIATE

```<code>proc univariate data=Tran_Restaurant;
    var Transaction_Count;
    histogram Transaction_Count / normal;
run;
</code>```

Scroll down to the section labeled Fitted Normal Distribution for the estimates of mu and theta.

If you have SAS/ETS and your data is not normally distributed, you can try to estimate it using PROC SEVERITY. If you have a machine with lots of cores, use PROC HPSEVERITY instead (it'll run much faster).  Out of the box, this proc can fit various predefined distributions to a set of data and estimate what their parameters are. You can optionally include your own custom distributions, which makes it extremely powerful.

I personally like to estimate how close a distribution fits using the KS statistic, but there are a variety of other ways to choose your distribution depending on the goal.

```<code>ods graphics on;

proc severity data=Tran_Restaurant
              outest=myests
              criteria=KS
              ;
    dist _ALL_;
    loss transaction_count;
run;
</code>```

It will return a set of possible predefined distributions and their closest fit.
By default, PROC SEVERITY will fit:

Burr

Exponential

Gamma

Generalized Pareto Distribution

Inverse Gaussian

Lognormal

Pareto

Scaled Tweedie

Tweedie

Weibull

Body:
I am using the following procedure to get the density plot of transaction counts:

PROC SGPLOT DATA = Tran_Restaurant ;
  density Transaction_Count/ scale=density ;
  "Restaurant Transaction Count";
  XAXIS LABEL = 'Transaction_Count' GRID VALUES = (0 TO 100 BY 10);
RUN;

Sample Data:

Customer_ID   Transaction_Count
1213x         23
2131x         14

Customer_ID is distinct in the data set.
So, from the plot for each transaction_count we can get the number of customers.

I wanted to get the equation of the density curve? Is it possible to do that in SAS?

Body:
If you know that your data is normal, you can estimate the distribution using PROC UNIVARIATE

proc univariate data=Tran_Restaurant;
    var Transaction_Count;
    histogram Transaction_Count / normal;
run;

Scroll down to the section labeled Fitted Normal Distribution for the estimates of mu and theta.

If you have SAS/ETS and your data is not normally distributed, you can try to estimate it using PROC SEVERITY. If you have a machine with lots of cores, use PROC HPSEVERITY instead (it'll run much faster).  Out of the box, this proc can fit various predefined distributions to a set of data and estimate what their parameters are. You can optionally include your own custom distributions, which makes it extremely powerful.

I personally like to estimate how close a distribution fits using the KS statistic, but there are a variety of other ways to choose your distribution depending on the goal.

ods graphics on;

proc severity data=Tran_Restaurant
              outest=myests
              criteria=KS
              ;
    dist _ALL_;
    loss transaction_count;
run;

It will return a set of possible predefined distributions and their closest fit.
By default, PROC SEVERITY will fit:

Burr

Exponential

Gamma

Generalized Pareto Distribution

Inverse Gaussian

Lognormal

Pareto

Scaled Tweedie

Tweedie

Weibull


问:
How to update report in access with bound dataset automatically?
I have a single entry output from a paradox table which is imported into Access.  Now I have created a report and done the databinding within the report to the dataset from Paradox.  When work is done in Paradox the single entry output changes...
How do I open up access and have the values from the report update automatically without having to reimport the table manually?

The objective is that when access is opened the report comes up immediately for inspection before printing.

答: Link table to Paradox file through GetData on menu.  You select the file from the route directory where your db files are and select.  Maintain a link and bind the date relationships to the dataset.  As you update using the Paradox database the tables in Access will update also.  You musn't run the db and access the same time otherwise jet engine won't work.</p>

OwnerDisplayName: CGF


问:
How are new std::map entries initialized just by key insertion?
I have one std::vector<MyString> which data is not unique. Actually, most strings are repeated. And I have to find the unique ones and their repeat number.

I use map:

```<code>std::map<MyString,unsigned short> stringsMap;
.......
if ( stringsMap.find( currentString ) == stringsMap.end() )
{
    stringsMap[ currentString ] = 0;
}

stringsMap[ currentString ]++;
........
</code>```

Do you have ideas how it could be done on fewer lines?

It could be done on one row: stringsMap[ currentString ]++; however short has indeterminate value by default.

答:
It could be done on one row: stringsMap[ currentString ]++; however short has indeterminate value by default.

This is not true, value is well defined as stated in documentation:

If an insertion is performed, the mapped value is value-initialized (default-constructed for class types, zero-initialized otherwise) and a reference to it is returned.

emphasis is mine.

So it is perfectly fine to write one liner:

```<code>stringsMap[ currentString ]++;
</code>```

and this is common practice and even given as an example in the documentation:

```<code>// count the number of occurrences of each word
// (the first call to operator[] initialized the counter with zero)
std::map<std::string, size_t>  word_map;
for (const auto &w : { "this", "sentence", "is", "not", "a", "sentence",
                       "this", "sentence", "is", "a", "hoax"}) {
    ++word_map[w];
}
</code>```

Body:
I have one std::vector<MyString> which data is not unique. Actually, most strings are repeated. And I have to find the unique ones and their repeat number.

I use map:

std::map<MyString,unsigned short> stringsMap;
.......
if ( stringsMap.find( currentString ) == stringsMap.end() )
{
    stringsMap[ currentString ] = 0;
}

stringsMap[ currentString ]++;
........

Do you have ideas how it could be done on fewer lines?

It could be done on one row: stringsMap[ currentString ]++; however short has indeterminate value by default.

Body:
It could be done on one row: stringsMap[ currentString ]++; however short has indeterminate value by default.

This is not true, value is well defined as stated in documentation:

If an insertion is performed, the mapped value is value-initialized (default-constructed for class types, zero-initialized otherwise) and a reference to it is returned.

emphasis is mine.

So it is perfectly fine to write one liner:

stringsMap[ currentString ]++;

and this is common practice and even given as an example in the documentation:

// count the number of occurrences of each word
// (the first call to operator[] initialized the counter with zero)
std::map<std::string, size_t>  word_map;
for (const auto &w : { "this", "sentence", "is", "not", "a", "sentence",
                       "this", "sentence", "is", "a", "hoax"}) {
    ++word_map[w];
}


问:
Entity Framework Core pros and cons of DBSet<MappingTable>
What are pros and cons for mapping table DbSet in the DbContext in EF Core?
Why should we do it like this or why not?

```<code>public DbSet<CategoryBooks> CategoryBooks { get; set; }
</code>```

Thanks in advance! :)

答:
The main idea behind Entity Framework is that it represents the data in the database in the form of entities which are c# variables. So for example the table would be represented as a collection of variables with each variable represents the table row and the data members of the variable represents the named columns of the table.

So instead of writing queries to insert,delete,update rows, what we do is apply these operations on the c# collection and then entity framework takes care of what to do in backend.

In the code above the collection is CategoryBooks that represent the table. Each item in this collection is lets say a book with some property. so you can do easy modifications to the books collection for example you want to modify the property of a certain book or you want to delete the book from the collection or add some new books to the collection. All you do programmatically in c#. You don't have to write queries specifically to achieve CRUD functionality. So that's an advantage.

Body:
What are pros and cons for mapping table DbSet in the DbContext in EF Core?
Why should we do it like this or why not?

public DbSet<CategoryBooks> CategoryBooks { get; set; }

Thanks in advance! :)


问:
How should implement one to many mapping in GORM as List
Domain Listini and Durate:

```<code><class name="Listino" table="listini">
    <id column="id" name="id" type="int" unsaved-value="null">
        <generator class="sequence">
            <param name="sequence">listini_seq</param>
        </generator>
    </id>
    <list cascade="all-delete-orphan" name="durate" table="durate">
        <cache usage="read-write"/>
        <key column="id_listino"/>
        <list-index column="index"/>
        <one-to-many class="Durata"/>
    </list>
</class>

<class name="Durata" table="durate">
    <id column="id" name="id" type="int" unsaved-value="null">
        <generator class="sequence">
            <param name="sequence">durate_seq</param>
        </generator>
    </id>
    <many-to-one class="Listino" column="id_listino" name="listino"/>
</class>
</code>```

I have two domain, and I was using Hibernate hbm file, but now I have to convet this mapping with GORM domain.

Please suggest me that how to implement this mapping with GORM, I need the same mapping  means, I need list index and the data must be store as a List.

答:
Here is a basic schema to start with.</p>

```<code>class Listino{

    // id is automatically handled by grails
    ...

    static hasMany = [durate : Durata]

    static mapping = {
        table "listini"
    }
}

class Durata{

    // id is automatically handled by grails
    ...

    Listino listino    // this create a belongs to relationship

    static mapping = {
        table "durate"
    }
}
</code>```

Body:
Domain Listini and Durate:

<class name="Listino" table="listini">
    <id column="id" name="id" type="int" unsaved-value="null">
        <generator class="sequence">
            <param name="sequence">listini_seq</param>
        </generator>
    </id>
    <list cascade="all-delete-orphan" name="durate" table="durate">
        <cache usage="read-write"/>
        <key column="id_listino"/>
        <list-index column="index"/>
        <one-to-many class="Durata"/>
    </list>
</class>

<class name="Durata" table="durate">
    <id column="id" name="id" type="int" unsaved-value="null">
        <generator class="sequence">
            <param name="sequence">durate_seq</param>
        </generator>
    </id>
    <many-to-one class="Listino" column="id_listino" name="listino"/>
</class>

I have two domain, and I was using Hibernate hbm file, but now I have to convet this mapping with GORM domain.

Please suggest me that how to implement this mapping with GORM, I need the same mapping  means, I need list index and the data must be store as a List.

Body:
Here is a basic schema to start with.

class Listino{

    // id is automatically handled by grails
    ...

    static hasMany = [durate : Durata]

    static mapping = {
        table "listini"
    }
}

class Durata{

    // id is automatically handled by grails
    ...

    Listino listino    // this create a belongs to relationship

    static mapping = {
        table "durate"
    }
}


问:
Chrome Dev Tools - Remembering the selected element through page reload
I am building my own type of Chrome dev tools (inspect element) which will also be in the form of a Chrome extension using JavaScript. I would like it to have some similar functionality to Chromes dev tools, one of which I'm finding hard to debunk how they have done it.

Basically, when you right click on any element and click "inspect element" it will open up the dev tools if not already open and hover over the HTML element your right click was targeting.

The bit that I want to replicate is when you refresh the page the while you still have the element selected in dev tools, it will reload all the HTML and directly go to the element you had selected in the dev tools before reloading.

Here is what I mean if it's a little unclear:

HTML:

```

If I was hovering over the div with class of "3" and refreshed the page, Chrome dev tools knows to reload with the dev tools highlighting that exact div. Even if there are multiple divs with that class or in a similar structure it will always hover the correct one.

Would anyone know if the best approach here is to have a big if statement which looks for certain traits of the element such as ideally an id but also a lot of fall-backs if the element does not have an id such as surrounding elements or unique classes/ attributes associated with that element?

I've tried searching for 'Chrome extension node selector' or similar variants but have not been able to find any information.

答:
Here is my workaround for your question.

The idea: ask a content script to pick unique selector for the inspected element, save it into the chrome.storage.local, so then you can load the selector, find element and run inspect() for it.

First of all a manifest.json file:

{
  "manifest_version": 2,
  "name": "remember element",
  "version": "1.0.0",
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content-script.js"],
      "run_at": "document_start"
    }
  ],
  "permissions": [
    "storage"
  ],
  "devtools_page": "loader.html"
}
```

<p>Then I am creating a new panel in Devtools.</p>

<p><strong>loader.html</strong></p>

<pre class="lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
<body>
  <script src="loader.js"></script>
</body>
</html>
</code>```

loader.js

chrome.devtools.panels.create('Remember element', null, 'panel.html');
```

<p><strong>panel.html</strong></p>

<pre class="lang-html prettyprint-override"><code><!doctype html>
<html>
<body>

  <button id="save">Save</button>
  <button id="get">Get</button>

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

So, the panel contains two buttons: one for saving current inspected element, and the second is to inspect the previously saved element.

Here what we need in panel.js:

document.addEventListener('DOMContentLoaded', () => {

    // Ask content-script to resolve unique selector and save it in the storage
    document.getElementById('save').addEventListener('click', () => {
        chrome
            .devtools
            .inspectedWindow
            .eval("saveUniqueSelector($0)", {
                useContentScriptContext: true // run the code in the content-script
            });
    });

    document.getElementById('get').addEventListener('click', () => {
        // Getting saved selector
        chrome.storage.local.get('prev_selected', items => {

            // Find the element by selector and run inspection for it
            chrome
                .devtools
                .inspectedWindow
                .eval(`inspect(document.querySelector("${items.prev_selected}"))`);
        });
    });
});
```

<p>and the <strong>content-script.js</strong></p>

```/**
 * Saves unique selector for the given element into chrome.storage
 *
 * The function invokes by panel.js ("chrome.devtools.inspectedWindow.eval")
 * @param el {HTMLElement}
 */
function saveUniqueSelector(el) {
    if (el) {
        const selectorGenerator = new CssSelectorGenerator();
        const selector = selectorGenerator.getSelector(el);
        if (selector) {
            console.log('Saving selector', selector);
            chrome.storage.local.set({prev_selected: selector});
        }
    }
}
```

There are many libs for getting unique selector for an element. I use here css-selector-generator

This example has big flaw: I didn't find a way to make autosave for element, when you choosing it in devtools. (except setInterval, but it isn't a great idea).

Body:
I am building my own type of Chrome dev tools (inspect element) which will also be in the form of a Chrome extension using JavaScript. I would like it to have some similar functionality to Chromes dev tools, one of which I'm finding hard to debunk how they have done it.

Basically, when you right click on any element and click "inspect element" it will open up the dev tools if not already open and hover over the HTML element your right click was targeting.

The bit that I want to replicate is when you refresh the page the while you still have the element selected in dev tools, it will reload all the HTML and directly go to the element you had selected in the dev tools before reloading.

Here is what I mean if it's a little unclear:

HTML:

If I was hovering over the div with class of "3" and refreshed the page, Chrome dev tools knows to reload with the dev tools highlighting that exact div. Even if there are multiple divs with that class or in a similar structure it will always hover the correct one.

Would anyone know if the best approach here is to have a big if statement which looks for certain traits of the element such as ideally an id but also a lot of fall-backs if the element does not have an id such as surrounding elements or unique classes/ attributes associated with that element?

I've tried searching for 'Chrome extension node selector' or similar variants but have not been able to find any information.

Body:
Here is my workaround for your question.

The idea: ask a content script to pick unique selector for the inspected element, save it into the chrome.storage.local, so then you can load the selector, find element and run inspect() for it.

First of all a manifest.json file:

{
  "manifest_version": 2,
  "name": "remember element",
  "version": "1.0.0",
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content-script.js"],
      "run_at": "document_start"
    }
  ],
  "permissions": [
    "storage"
  ],
  "devtools_page": "loader.html"
}

Then I am creating a new panel in Devtools.

loader.html

<!doctype html>
<html lang="en">
<body>
  <script src="loader.js"></script>
</body>
</html>

loader.js

chrome.devtools.panels.create('Remember element', null, 'panel.html');

panel.html

<!doctype html>
<html>
<body>

  <button id="save">Save</button>
  <button id="get">Get</button>

  <script src="panel.js"></script>
</body>
</html>

So, the panel contains two buttons: one for saving current inspected element, and the second is to inspect the previously saved element.

Here what we need in panel.js:

document.addEventListener('DOMContentLoaded', () => {

    // Ask content-script to resolve unique selector and save it in the storage
    document.getElementById('save').addEventListener('click', () => {
        chrome
            .devtools
            .inspectedWindow
            .eval("saveUniqueSelector($0)", {
                useContentScriptContext: true // run the code in the content-script
            });
    });

    document.getElementById('get').addEventListener('click', () => {
        // Getting saved selector
        chrome.storage.local.get('prev_selected', items => {

            // Find the element by selector and run inspection for it
            chrome
                .devtools
                .inspectedWindow
                .eval(`inspect(document.querySelector("${items.prev_selected}"))`);
        });
    });
});

and the content-script.js

/**
 * Saves unique selector for the given element into chrome.storage
 *
 * The function invokes by panel.js ("chrome.devtools.inspectedWindow.eval")
 * @param el {HTMLElement}
 */
function saveUniqueSelector(el) {
    if (el) {
        const selectorGenerator = new CssSelectorGenerator();
        const selector = selectorGenerator.getSelector(el);
        if (selector) {
            console.log('Saving selector', selector);
            chrome.storage.local.set({prev_selected: selector});
        }
    }
}

There are many libs for getting unique selector for an element. I use here css-selector-generator

This example has big flaw: I didn't find a way to make autosave for element, when you choosing it in devtools. (except setInterval, but it isn't a great idea).


问:
iPhone - How may I know if scrollToRowAtIndexPath will scroll something
I have some things to do at scrollViewDidEndScrollingAnimation time with a DoThis function.
But sometimes, scrollToRowAtIndexPath with animate=YES does not scroll anything.

So how can I know if the scrolling will be done to be able to force an alternative function DoThisWithNoScrollOccured call after the scrollToRowAtIndexPath call ?

答: You can check the indexPathsForVisibleRows and see if the RowAtIndexPath you are trying to scroll to is already visible.  If it is already visible, there will be no scrolling.


答:
however short has indeterminate value by default.

No. For a non existing key the map will use T() to initialize the value of the newly created entry, which effectively evaluates to 0 for unsigned short.

See the std::map::operator[] documentation (emphasis mine1):

1) Inserts value_type(key, T()) if the key does not exist. This function is equivalent to return insert(std::make_pair(key, T())).first->second;

    - key_type must meet the requirements of CopyConstructible.

    - mapped_type must meet the requirements of CopyConstructible and DefaultConstructible.

    If an insertion is performed, the mapped value is value-initialized (default-constructed for class types, zero-initialized otherwise) and a reference to it is returned.

Thus, writing just

```<code>std::map<MyString,unsigned short> stringsMap;
.......
stringsMap[ currentString ]++;
</code>```

is perfectly fine.  The entire if block is redundant and not needed.

1)That's not really true, it was @Remy Lebau's emphasis

Title: How are new std::map entries initialized just by key insertion?

Body:
however short has indeterminate value by default.

No. For a non existing key the map will use T() to initialize the value of the newly created entry, which effectively evaluates to 0 for unsigned short.

See the std::map::operator[] documentation (emphasis mine1):

1) Inserts value_type(key, T()) if the key does not exist. This function is equivalent to return insert(std::make_pair(key, T())).first->second;

    - key_type must meet the requirements of CopyConstructible.

    - mapped_type must meet the requirements of CopyConstructible and DefaultConstructible.

    If an insertion is performed, the mapped value is value-initialized (default-constructed for class types, zero-initialized otherwise) and a reference to it is returned.

Thus, writing just

std::map<MyString,unsigned short> stringsMap;
.......
stringsMap[ currentString ]++;

is perfectly fine.  The entire if block is redundant and not needed.

1)That's not really true, it was @Remy Lebau's emphasis


问:
Add empty inputs to an array with the value of 0
As a project I am building a "barebones" budgeting web-app. I have a form with a number of inputs to fill out income sources and amounts.

```<code><form>
      <div class="form-group">
        <input type="text" class="form-control" id="incomeSrc1" placeholder="Enter Source" name="incomeSrc">
        <input type="text" class="form-control" id="incomeSrc2" placeholder="Enter Source" name="incomeSrc">
        <input type="text" class="form-control" id="incomeSrc3" placeholder="Enter Source" name="incomeSrc">
        <input type="text" class="form-control" id="incomeSrc4" placeholder="Enter Source" name="incomeSrc">
      </div>
    </form>
</code>```

And

```<code><form>
      <div class="form-group">
        <input type="number" class="form-control" id="amount1" placeholder="Enter Amount" name="incAmount">
        <input type="number" class="form-control" id="amount2" placeholder="Enter Amount" name="incAmount">
        <input type="number" class="form-control" id="amount3" placeholder="Enter Amount" name="incAmount">
        <input type="number" class="form-control" id="amount4" placeholder="Enter Amount" name="incAmount">
      </div>
    </form>
</code>```

I tried to put all the inputs into a array amountArr so that I could add them together and determine the largest source of income.

This was my latest attempt :

```<code>var incAmount = document.getElementsByName("incAmount");
var amountArr = [];
//Income input function
for (var index = 0; index < incAmount.length; index++) {
    incAmount[index].addEventListener("input", add3);
    function add3() {
        for (var i = 0; i < incAmount.length; i++) {
             amountArr[i] = parseFloat(incAmount[i].value);
            if (incAmount[i].value === NaN) {
                amountArr[i] = 0;
            };
        };
    };
};
</code>```

The goal is that if an input wasn't filled then its value in the array will be 0. However all my attempts either threw errors like -

incAmount[i].value is undefined

or the array was filled with NaN's.

I also tried

```<code>if (amountArr[i].value !== NaN)
</code>```

and

```<code>if (isNaN(amountArr[i]))
</code>```

None of them returned true (executed the ensuing code)

Why doesn't amountArr or an empty incAmount reurn true when compared to NaN/null/undefined?

答:
You should use parseFloat in the condition to convert the empty value to NaN before comparison.

-Or you should use the amountArr[i] in the condition to check if that is NaN.

Also, you should use isNaN function to check for NaN value.

```<code>if (isNaN(amountArr[i])) {
   amountArr[i] = 0;
</code>```

Body:
As a project I am building a "barebones" budgeting web-app. I have a form with a number of inputs to fill out income sources and amounts.

<form>

        <input type="text" class="form-control" id="incomeSrc1" placeholder="Enter Source" name="incomeSrc">
        <input type="text" class="form-control" id="incomeSrc2" placeholder="Enter Source" name="incomeSrc">
        <input type="text" class="form-control" id="incomeSrc3" placeholder="Enter Source" name="incomeSrc">
        <input type="text" class="form-control" id="incomeSrc4" placeholder="Enter Source" name="incomeSrc">

    </form>

And

<form>

        <input type="number" class="form-control" id="amount1" placeholder="Enter Amount" name="incAmount">
        <input type="number" class="form-control" id="amount2" placeholder="Enter Amount" name="incAmount">
        <input type="number" class="form-control" id="amount3" placeholder="Enter Amount" name="incAmount">
        <input type="number" class="form-control" id="amount4" placeholder="Enter Amount" name="incAmount">

    </form>

I tried to put all the inputs into a array amountArr so that I could add them together and determine the largest source of income.

This was my latest attempt :

var incAmount = document.getElementsByName("incAmount");
var amountArr = [];
//Income input function
for (var index = 0; index < incAmount.length; index++) {
    incAmount[index].addEventListener("input", add3);
    function add3() {
        for (var i = 0; i < incAmount.length; i++) {
             amountArr[i] = parseFloat(incAmount[i].value);
            if (incAmount[i].value === NaN) {
                amountArr[i] = 0;
            };
        };
    };
};

The goal is that if an input wasn't filled then its value in the array will be 0. However all my attempts either threw errors like -

incAmount[i].value is undefined

or the array was filled with NaN's.

I also tried

if (amountArr[i].value !== NaN)

and

if (isNaN(amountArr[i]))

None of them returned true (executed the ensuing code)

Why doesn't amountArr or an empty incAmount reurn true when compared to NaN/null/undefined?

Body:
You should use parseFloat in the condition to convert the empty value to NaN before comparison.

-Or you should use the amountArr[i] in the condition to check if that is NaN.

Also, you should use isNaN function to check for NaN value.

if (isNaN(amountArr[i])) {
   amountArr[i] = 0;