问:
Looking for an appropriate synchronization mechanism
Presume I have the following (pseudo) code:

class Cache {
    Entry addIfMissing(String data) {
        // omitted for brevity
    }
    void evictOldEntries() {
        // omitted for brevity
    }
}
```

<pre class="lang-java prettyprint-override"><code>class Program {
    private Cache cache = new Cache();

    doWork() { // called from multiple threads
        var entry = cache.addIfMissing("omitted for brevity");
        // work with entry
    }

    static {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            cache.evictOldEntries();
        }, 10, 10, TimeUnit.MINUTES);
    }
}
</code>```

I want to make sure while the evictOldEntries method is running all the other threads in the program have to wait for it to be done.

Which synchronization mechanism would be appropriate in such a scenario?

答:
What you need is something like this:</p>

```<code>class Cache {

    final ReentrantLock lock;

    public Cache { lock = new ReentrantLock(); }

    Entry addIfMissing(String data) {
        lock.lock();
        try {
            // Add data here
        }
        finally {
            lock.unlock();
        }
    }

    void evictOldEntries() {
        if (lock.tryLock()) {
           try {
              // Evict old entries
           }
           finally {
              lock.unlock();
           }
        }
    }
}
</code>```

Body:
Presume I have the following (pseudo) code:

class Cache {
    Entry addIfMissing(String data) {
        // omitted for brevity
    }
    void evictOldEntries() {
        // omitted for brevity
    }
}

class Program {
    private Cache cache = new Cache();

    doWork() { // called from multiple threads
        var entry = cache.addIfMissing("omitted for brevity");
        // work with entry
    }

    static {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            cache.evictOldEntries();
        }, 10, 10, TimeUnit.MINUTES);
    }
}

I want to make sure while the evictOldEntries method is running all the other threads in the program have to wait for it to be done.

Which synchronization mechanism would be appropriate in such a scenario?

Body:
What you need is something like this:

class Cache {

    final ReentrantLock lock;

    public Cache { lock = new ReentrantLock(); }

    Entry addIfMissing(String data) {
        lock.lock();
        try {
            // Add data here
        }
        finally {
            lock.unlock();
        }
    }

    void evictOldEntries() {
        if (lock.tryLock()) {
           try {
              // Evict old entries
           }
           finally {
              lock.unlock();
           }
        }
    }
}


来源: stackexchange

问:
How can I take multiple values from object without calling object's name everytime?
I have class Weekdays which has 7 parameters. I have also entity object which contains all required arguments to satisfy Weekdays class.
Normally I would write something like this to init this class:

```<code>   Weekdays(entity.isMonday,
            entity.isTuesday,
            entity.isWednesday,
            entity.isThursday,
            entity.isFriday,
            entity.isSaturday,
            entity.isSunday)
</code>```

But everytime I need to call entity object to get value from this. Is there any keyword that would allow me not to call entity every time I want to get value from it?

答:
Depending on your requirements, you could add a secondary constructor to your Weekdays class, which calls the primary constructor in the way shown.

Or you could add a factory method to its companion object, which can use with to simplify a little, e.g.:

```<code>class Weekdays(/*...*/) {
    /*
    ...
    */
    companion object {
        fun Weekdays(entity: Entity) = with(entity) {
            Weekdays(isMonday, isTuesday, isWednesday, isThursday, isFriday, isSaturday, isSunday)
        }
    }
}
</code>```

Or you could restructure Weekdays so that it has an array or other structure, instead of named fields.

ContentLicense: CC BY-SA 4.0

Body:
I have class Weekdays which has 7 parameters. I have also entity object which contains all required arguments to satisfy Weekdays class.
Normally I would write something like this to init this class:

   Weekdays(entity.isMonday,
            entity.isTuesday,
            entity.isWednesday,
            entity.isThursday,
            entity.isFriday,
            entity.isSaturday,
            entity.isSunday)

But everytime I need to call entity object to get value from this. Is there any keyword that would allow me not to call entity every time I want to get value from it?

Body:
Depending on your requirements, you could add a secondary constructor to your Weekdays class, which calls the primary constructor in the way shown.

Or you could add a factory method to its companion object, which can use with to simplify a little, e.g.:

class Weekdays(/*...*/) {
    /*
    ...
    */
    companion object {
        fun Weekdays(entity: Entity) = with(entity) {
            Weekdays(isMonday, isTuesday, isWednesday, isThursday, isFriday, isSaturday, isSunday)
        }
    }
}

Or you could restructure Weekdays so that it has an array or other structure, instead of named fields.


问:
How to know what column has been resized when using TableColumnModelListener
I'm using TableColumnModelListener on a JTable to know when a Column is resized.

I took a look at the ChangeEvent object inside the columnMarginChanged(ChangeEvent e) method, but I didn't found a way to know what column has been resized.

Is there a way?

答:
Instead of a TableColumnModelListener, you can add a property listener to each individual TableColumn whose size interests you:</p>

```<code>columnModel.getColumn(0).addPropertyChangeListener(
    new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent event) {
            if (event.getPropertyName().equals("width")) {
                int oldWidth = (Integer) e.getOldValue();
                int newWidth = (Integer) e.getNewValue();
                // etc.
            }
        }
    });
</code>```

Body:
Instead of a TableColumnModelListener, you can add a property listener to each individual TableColumn whose size interests you:

columnModel.getColumn(0).addPropertyChangeListener(
    new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent event) {
            if (event.getPropertyName().equals("width")) {
                int oldWidth = (Integer) e.getOldValue();
                int newWidth = (Integer) e.getNewValue();
                // etc.
            }
        }
    });


问:
Maven : Is there a way to check if a particular version of child dependency is compatible with parent?

I have a janusgraph-cassandra dependency in my project which brings cassandra-all transitive dependency with it.

Now I am trying to upgrade cassandra-all dependency from 2.1.20 to 3.11.4 but it does not seem to be compatible with parent janusgraph-cassandra 0.3.1.

Is there a way to check the version compatibility between parent and transitive dependencies?
Or should it be taken as a rule of thumb that only the versions that a maven artifact brings on it's own are compatible?

答:
The maven dependency:tree goal is a means to identify where you may have conflicting dependencies, but establishing compatibility is a more complex question that can't be solved by maven on its own.

Establishing whether there is compatibility between versions is sometimes quite difficult.  The primary reason is that there is no enforced rules about what dictates when a library has breaking changes.

A popular way of communicating compatibility is using a predictable versioning strategy.  Semantic Versioning is one such popular strategy that mandates:

Given a version number MAJOR.MINOR.PATCH, increment the:

MAJOR version when you make incompatible API changes,

MINOR version when you add functionality in a backwards-compatible manner, and

PATCH version when you make backwards-compatible bug fixes.

That being said, cassandra-all does not claim to follow this.  Cassandra is a database, and not so much a library.  Between minor versions there are known to be breaking API changes, and I bet it has been known to happen between patch versions.

If you are using janusgraph, I would suggest binding yourself to the version of cassandra that it claims to depend on.

However if you are running janusgraph with cassandra using Remote Server Mode, I would anticipate that you could upgrade the Cassandra cluster to 3.11.4 and things should continue to work.

It's likely that only when using Embedded Mode that cassandra-all is used.


问:
Find SAP modifications of function groups includes
(access key for SAP standard modifications needed for test data of this question)

Introduction:
I want to find a certain type of modification to a certain SAP standard repository object (IDES test dataset).
The modification is located in the include of a function group (it is listed under System-defined Include-files in the functionpool of the function group).

So far, I found the table SMODILOG as a central list of modifications (Log of Customer Modifications to Dev. Env. Objects).

Test Data:
My test data is function group V07A, that has e.g. the include LV07A014 (Part of the LV07ANNN include). This was modified by inserting stuff in its source code (one needs an access key in order to be allowed to do this) such as:

```<code>*{   INSERT         IDSEXAMPLE                                        1
* this is a comment, which was added
*}   INSERT
</code>```

Goal:
Subsequently I want to find a table where all modifications like this are listed. I want to find the place of modification, i.e. the object type and program id of the object that was modified.

2 Questions:
I realize that the SAP standard include of a function group has a different object type and program ID than the top-include and uxx-includes.
Whereas the latter are of type PROG and prgmid R3TR (found in object catalog entry), the LV07A014 has an object catalog entry identical to the function group that it belongs to, namely R3TR FUGR. This is already peculiar to me. This seems to me as if the resolution to the sub-level (include level) is missing.

In addition, the modification to LV07A014 is listed in table SMODILOG as having the object type (field sub_type) REPS (the pgmid is not included in SMODILOG). I would expect PROG, as for the other inclueds (LTOP, LUXX).

-> Why is there a difference of object types, programids between L_TOP, L_UXX on the one hand and L_NNN Inclues on the other? (Or am I mistaken?)

-> Where can I find information of all SAP standard modifications in my system and the true object type,pgmid belonging to these modified objects (and not the function group that the modified object belongs to, this resolution does not suffice)?

答:
Why do you need a table? For what? Is it purely academic question or connected with real life tasks?

Have you ever tried SE95 transaction? It lists all modifications that were done in system disregard of object type and name. Yes, and function groups too. They are easily searchable by hierarchy

If it is FUGR include that was modified, then it will be listed in the node Outside of modularization units

Finally RTFM, bro...

Body:
(access key for SAP standard modifications needed for test data of this question)

Introduction:
I want to find a certain type of modification to a certain SAP standard repository object (IDES test dataset).
The modification is located in the include of a function group (it is listed under System-defined Include-files in the functionpool of the function group).

So far, I found the table SMODILOG as a central list of modifications (Log of Customer Modifications to Dev. Env. Objects).

Test Data:
My test data is function group V07A, that has e.g. the include LV07A014 (Part of the LV07ANNN include). This was modified by inserting stuff in its source code (one needs an access key in order to be allowed to do this) such as:

*{   INSERT         IDSEXAMPLE                                        1
* this is a comment, which was added
*}   INSERT

Goal:
Subsequently I want to find a table where all modifications like this are listed. I want to find the place of modification, i.e. the object type and program id of the object that was modified.

2 Questions:
I realize that the SAP standard include of a function group has a different object type and program ID than the top-include and uxx-includes.
Whereas the latter are of type PROG and prgmid R3TR (found in object catalog entry), the LV07A014 has an object catalog entry identical to the function group that it belongs to, namely R3TR FUGR. This is already peculiar to me. This seems to me as if the resolution to the sub-level (include level) is missing.

In addition, the modification to LV07A014 is listed in table SMODILOG as having the object type (field sub_type) REPS (the pgmid is not included in SMODILOG). I would expect PROG, as for the other inclueds (LTOP, LUXX).

-> Why is there a difference of object types, programids between L_TOP, L_UXX on the one hand and L_NNN Inclues on the other? (Or am I mistaken?)

-> Where can I find information of all SAP standard modifications in my system and the true object type,pgmid belonging to these modified objects (and not the function group that the modified object belongs to, this resolution does not suffice)?


问:
Progress bar in Swing (Java) for command tools
I have several C/C++ command line tools that I'm wrapping with Java.Swing as GUI. The command line tools can take minutes to hours. Progress bar seems like a good idea to keep users sane. I'm also thinking it might be nice to wrap a GUI for the progress bar, instead of just using system out.  But how?

I'm thinking the command line tools can write percents to stderr and I can somehow read it in java. Not exactly sure what the mechanics for this would be.  I'm also not clear on asynchronous display (learned a bit about invokeLater() ).  New to Java, and would appreciate general suggestions as well.  Thanks.

--- update ---

Thanks everyone for your suggestions.  Here's the resulting code.

```<code>private void redirectSystemStreams() {
    OutputStream out_stderr = new OutputStream() {
      @Override
      public void write(final int b) throws IOException {
        update(String.valueOf((char) b));
      }
      @Override
      public void write(byte[] b, int off, int len) throws IOException {
        update(new String(b, off, len));
      }
      @Override
      public void write(byte[] b) throws IOException {
        write(b, 0, b.length);
      }
    };
    System.setErr(new PrintStream(out_stderr, true));
}

private void update(final String inputText) {
    int value = 20; //parse inputText; make sure your executable calls fflush(stderr) after each fprintf().
    jProgressBar.setValue(value);

    /* Also one can redirect to a textpane
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        //update jTextPane with inputText
      }
    });
    */
}
</code>```

答:
For the progress bar part of your problem you can do something like the following. Note that this is just an example to illustrate the point.

Basically, a thread is created to do the work. Presumably this Runner thread will be interacting with your C/C++ code to get its progress. It then calls update on the Progress Bars Dialog class.

```<code>   import java.awt.BorderLayout;
   import java.awt.Dimension;
   import javax.swing.JDialog;
   import javax.swing.JFrame;
   import javax.swing.JLabel;
   import javax.swing.JPanel;
   import javax.swing.JProgressBar;

  public class Main {

   private int value;
   private Progress pbar;

   public static void main(String args[]) {
      new Main();
   }

   public Main() {

     pbar = new Progress();
     Thread t = new Thread(new Runner());
     t.start();

  }

  class Progress extends JDialog {

    JProgressBar pb;
    JLabel label;

    public Progress() {
        super((JFrame) null, "Task In Progress");
        pb = new JProgressBar(0, 100);
        pb.setPreferredSize(new Dimension(175, 20));
        pb.setString("Working");
        pb.setStringPainted(true);
        pb.setValue(0);

        label = new JLabel("Progress: ");

        JPanel panel = new JPanel();
        panel.add(label);
        panel.add(pb);
        add(panel, BorderLayout.CENTER);
        pack();
        setVisible(true);
    }

    public void update(){
        pb.setValue(value);

        if(value >= 100){
            this.setVisible(false);
            this.dispose();
        }
    }
}

class Runner implements Runnable {

    public void run() {
        for (int i = 0; i <= 100; i++) {
            value++;
            pbar.update();
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
            }
        }
     }
   }
 }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have several C/C++ command line tools that I'm wrapping with Java.Swing as GUI. The command line tools can take minutes to hours. Progress bar seems like a good idea to keep users sane. I'm also thinking it might be nice to wrap a GUI for the progress bar, instead of just using system out.  But how?

I'm thinking the command line tools can write percents to stderr and I can somehow read it in java. Not exactly sure what the mechanics for this would be.  I'm also not clear on asynchronous display (learned a bit about invokeLater() ).  New to Java, and would appreciate general suggestions as well.  Thanks.

--- update ---

Thanks everyone for your suggestions.  Here's the resulting code.

private void redirectSystemStreams() {
    OutputStream out_stderr = new OutputStream() {
      @Override
      public void write(final int b) throws IOException {
        update(String.valueOf((char) b));
      }
      @Override
      public void write(byte[] b, int off, int len) throws IOException {
        update(new String(b, off, len));
      }
      @Override
      public void write(byte[] b) throws IOException {
        write(b, 0, b.length);
      }
    };
    System.setErr(new PrintStream(out_stderr, true));
}

private void update(final String inputText) {
    int value = 20; //parse inputText; make sure your executable calls fflush(stderr) after each fprintf().
    jProgressBar.setValue(value);

    /* Also one can redirect to a textpane
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        //update jTextPane with inputText
      }
    });
    */
}

Body:
For the progress bar part of your problem you can do something like the following. Note that this is just an example to illustrate the point.

Basically, a thread is created to do the work. Presumably this Runner thread will be interacting with your C/C++ code to get its progress. It then calls update on the Progress Bars Dialog class.

   import java.awt.BorderLayout;
   import java.awt.Dimension;
   import javax.swing.JDialog;
   import javax.swing.JFrame;
   import javax.swing.JLabel;
   import javax.swing.JPanel;
   import javax.swing.JProgressBar;

  public class Main {

   private int value;
   private Progress pbar;

   public static void main(String args[]) {
      new Main();
   }

   public Main() {

     pbar = new Progress();
     Thread t = new Thread(new Runner());
     t.start();

  }

  class Progress extends JDialog {

    JProgressBar pb;
    JLabel label;

    public Progress() {
        super((JFrame) null, "Task In Progress");
        pb = new JProgressBar(0, 100);
        pb.setPreferredSize(new Dimension(175, 20));
        pb.setString("Working");
        pb.setStringPainted(true);
        pb.setValue(0);

        label = new JLabel("Progress: ");

        JPanel panel = new JPanel();
        panel.add(label);
        panel.add(pb);
        add(panel, BorderLayout.CENTER);
        pack();
        setVisible(true);
    }

    public void update(){
        pb.setValue(value);

        if(value >= 100){
            this.setVisible(false);
            this.dispose();
        }
    }
}

class Runner implements Runnable {

    public void run() {
        for (int i = 0; i <= 100; i++) {
            value++;
            pbar.update();
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
            }
        }
     }
   }
 }


问:
How Can I get two diffrents event with onclick?
Hello I have this problem. When I click the first element p, the color change in red, and if I click the second element p after the first elment p the color will be green, but I want red. I would like have this efect: if i click the first elment p, it will be red, and after if I click the second element p, it will be red. I think my JavaScript code is wrong, what can I do for get this effect?
Thank you all for your help

var clicked = true;

function change(abba) {
  if (clicked) {
    abba.style.color = "red";
  } else {
    abba.style.color = "green";
  }
  clicked = !clicked;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p onclick="change(this)">HELLO WORLD</p>
<p onclick="change(this)">HELLO WORLD</p>
<p onclick="change(this)">HELLO WORLD</p>
<p onclick="change(this)">HELLO WORLD</p></code>```

答:
If you want to toggle text color, you can check if current color is red, if it is, assign the color to green, set to red otherwise.

function change(abba) {
  abba.style.color = abba.style.color === "red" ? "green" : "red";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p onclick="change(this)">HELLO WORLD</p>
<p onclick="change(this)">HELLO WORLD</p>
<p onclick="change(this)">HELLO WORLD</p>
<p onclick="change(this)">HELLO WORLD</p></code>```

Body:
Hello I have this problem. When I click the first element p, the color change in red, and if I click the second element p after the first elment p the color will be green, but I want red. I would like have this efect: if i click the first elment p, it will be red, and after if I click the second element p, it will be red. I think my JavaScript code is wrong, what can I do for get this effect?
Thank you all for your help

var clicked = true;

function change(abba) {
  if (clicked) {
    abba.style.color = "red";
  } else {
    abba.style.color = "green";
  }
  clicked = !clicked;
}

HELLO WORLD

HELLO WORLD

HELLO WORLD

HELLO WORLD

Body:
If you want to toggle text color, you can check if current color is red, if it is, assign the color to green, set to red otherwise.

function change(abba) {
  abba.style.color = abba.style.color === "red" ? "green" : "red";
}

<p onclick="change(this)">HELLO WORLD</p>
<p onclick="change(this)">HELLO WORLD</p>
<p onclick="change(this)">HELLO WORLD</p>
<p onclick="change(this)">HELLO WORLD</p>


问:
How can I implement firebase only once and use it in other scripts instead of initializing in every script I need it in javscript?
So I'm looking for a way to initialize Firebase in only one JavaScript file and then access firebase in other scripts to use it in there. Right now, in every script I use firebase in I have to initialize it which means I'm calling     firebase.initializeApp(firebaseConfig); in every script and I'm hoping I could maybe define it once and get it in every script that I need it in.

答:
```<code>import firebase from 'firebase/app'

require('firebase/firestore')
var config = {
  apiKey: process.env['FIREBASE_API_KEY'],
  authDomain: process.env['FIREBASE_AUTH_DOMAIN'],
  databaseURL: process.env['FIREBASE_DATABASE_URL'],
  projectId: process.env['FIREBASE_PROJECT'],
  storageBucket: process.env['FIREBASE_STORAGE'],
  messagingSenderId: process.env['FIREBASE_MESSAGE_ID'],
  appId: process.env['FIREBASE_APP_ID'],
}

firebase.initializeApp(config)

export default firebase
</code>```

On your index.js you require this file, then you import firebase on any file.. not need to init your app again

Body:
import firebase from 'firebase/app'

require('firebase/firestore')
var config = {
  apiKey: process.env['FIREBASE_API_KEY'],
  authDomain: process.env['FIREBASE_AUTH_DOMAIN'],
  databaseURL: process.env['FIREBASE_DATABASE_URL'],
  projectId: process.env['FIREBASE_PROJECT'],
  storageBucket: process.env['FIREBASE_STORAGE'],
  messagingSenderId: process.env['FIREBASE_MESSAGE_ID'],
  appId: process.env['FIREBASE_APP_ID'],
}

firebase.initializeApp(config)

export default firebase

On your index.js you require this file, then you import firebase on any file.. not need to init your app again


问:
Router link changes the path but Router view doesn’t change
So i have a side navbar and some link in it. The entry point is the homepage. The problem is, when i'm trying to change router-view using router-link in my side navbar, the router-view doesn't change, but the path has change.

So here's my route path on my router.js:

```<code>        {
        path: '/',
        component: Home,
        children: [
                {
                    path: ':name',
                    name: 'theTask',
                    props: true,
                    component: TodoList
                }
            ]
        },
    ],
</code>```

And here's my App.vue

```<code><div class="container">
            <div class="main__content">
                <div class="sidenav">
                    <aside class="menu">
                        <ul class="menu-list">
                            <li><router-link :to="{ name: 'theTask', params: {name: 'today'} }">Today</router-link></li>
                            <li><router-link :to="{ name: 'home' }">Next 7 Days</router-link></li>
                        </ul>
                    </aside>
                </div>
                <div class="content">
                    <router-view></router-view>
                </div>
            </div>
     </div>
</code>```

It rendered the homepage, but when i'm clicking router-link to the child route, it doesn't change the router-view, only the router link.

答:
I am not sure about the use case but most likely you don't need to use children in your routes. That is meant for components that live ON the original page as their parent. If you just want a different component on a different page, you should define them as individual routes:

```<code>{
  path: '/',
  name: 'Home',
  component: Home
},
{
  path: '/:name',
  name: 'theTask', // although IMO this should be called something like "TodoList"
  component: TodoList
}
</code>```

You can then use the Vue Developer Tools (for Chrome) to inspect and see which route is currently being rendered on your page.

Body:
So i have a side navbar and some link in it. The entry point is the homepage. The problem is, when i'm trying to change router-view using router-link in my side navbar, the router-view doesn't change, but the path has change.

So here's my route path on my router.js:

        {
        path: '/',
        component: Home,
        children: [
                {
                    path: ':name',
                    name: 'theTask',
                    props: true,
                    component: TodoList
                }
            ]
        },
    ],

And here's my App.vue

<router-link :to="{ name: 'theTask', params: {name: 'today'} }">Today</router-link>

<router-link :to="{ name: 'home' }">Next 7 Days</router-link>

                    <router-view></router-view>

It rendered the homepage, but when i'm clicking router-link to the child route, it doesn't change the router-view, only the router link.

Body:
I am not sure about the use case but most likely you don't need to use children in your routes. That is meant for components that live ON the original page as their parent. If you just want a different component on a different page, you should define them as individual routes:

{
  path: '/',
  name: 'Home',
  component: Home
},
{
  path: '/:name',
  name: 'theTask', // although IMO this should be called something like "TodoList"
  component: TodoList
}

You can then use the Vue Developer Tools (for Chrome) to inspect and see which route is currently being rendered on your page.


问:
How to run a specific test with Create React App
In an app create with CRA v.1 I need to run a specific test file. How do I go about it? There is the --testPathIgnorePatterns flag to add to the npm test script to ignore a file or path but how do I run a particular test file with CRA from the command line?

答:
You can use the name of the file in the command, and it will run only it.

For example:

```<code>npm test src/App.test.js
</code>```

Body:
You can use the name of the file in the command, and it will run only it.

For example:

npm test src/App.test.js


问:
How to fix typerror dealing with '<='
what the codes is supposed to is take the users input and then movie the rectangle around and when I run the code i get a Typeerror:<=' not supported between instances of 'str' and 'int'

these were some of the comments made on my code

For both Point and Rectangle class constructors, you are providing default values for the parameters. You should not since the assignment states, you should make them required arguments. (-4)

rectangleCount static attribute of the Rectangle class not kept up to date (should be incremented in the constructor to keep track of count of Rectangle objects created so far) (-2)

Rectangle's constructor doesn't check if width and height is negative, and if so print error message. (-2)

Calculations in the bottomRight property is incorrect. (-2) It should be

```<code>    @property
    def bottomRight(self):
        return Point(self.topLeft.x + self.width, self.topLeft.y + self.height)
</code>```

Calculations in the perimeter proper

```<code>    # Prog 120
    # Rectangle & Point Classes

    class Point:
        def __init__(self, x, y): # makes the value required
            self.__x = x
            self.__y = y

        @property  # read only property for x
        def x(self):
            return self.__x

        @property  # read only property for y
        def y(self):
            return self.__y

        def translate(self, dx, dy):  # moves x coordinate by 'dx' amount of time  and move dy
            self.__x += dx
            self.__y += dy

    class Rectangle:
        DEFAULT_WIDTH = 1 # static attributes
        DEFAULT_HEIGHT = 1
        rectangleCount = 0

        def __init__(self, topLeft, width, height):
            self.__topLeft = topLeft

            # check width argument
            if (width <= 0):
                print("Invalid width")
                self.__width = Rectangle.DEFAULT_WIDTH
            else:
                self.__width = width

             # check height argument
            if (height <= 0):
                 print("Invalid Height")
                 self.__height = Rectangle.DEFAULT_HEIGHT
            else:
                self.__height = height

            Rectangle.rectangleCount +=1 #updates the count of rectangels created

        @property
        def topLeft(self):
            return self.__topLeft

        @topLeft.setter
        def topLeft(self, newTopLeft):
            self.__topLeft = newTopLeft

        @property
        def width(self):
            return self.__width

        @width.setter
        def width(self, newWidth):
            if (newWidth <= 0):
                print("Width cannot be less than '0'. ")
            else:
                self.__width = newWidth

        @property
        def height(self):
            return self.__height

        @height.setter
        def height(self, newHeight):
            if (newHeight <= 0):
                print("Height cannot be less than '0'. ")
            else:
                self.__height = newHeight

        @property
        def bottomRight(self):
            return Point(self.topLeft.x + self.topLeft.y + self.height)

        @property
        def area(self):
            return self.__width * self.__height

        @property
        def perimeter(self):
            return self.__width *2 + self.__height *2

        def translate(self, dx, dy):  # moves x coordinate by 'dx' amount of time and move y
            self.__topLeft.translare(dx,dy)

    def main():
        bill = Point(x="", y="")
        will = Rectangle(topLeft="", width="", height="")
        if will.width and will.height < 0:
            print("Width and Height cannot be less than 0.")
            will.width = will.DEFAULT_WIDTH
            will.height = will.DEFAULT_HEIGHT
        will.rectangleCount += 1

    if __name__ == "__main__":
        main()

</code>```

答:
```<code>bill = Point(x="", y="")
will = Rectangle(topLeft="", width="", height="")
</code>```

Here you are setting the attributes in Rectangle to the empty string.

And here:

```<code> def __init__(self, topLeft, width, height):
            self.__topLeft = topLeft

            # check width argument
            if (width <= 0):
                print("Invalid width")
                self.__width = Rectangle.DEFAULT_WIDTH
</code>```

You are comparing that string to 0 - an int. Obviously you can't compare "" with 0. That doesn't make any sense. That's what python is telling you with that error message.

Maybe try passing integers to the constructors. Like this:

```<code>bill = Point(x=5, y=9)
will = Rectangle(topLeft=2, width=4, height=1)
</code>```

Title: How to fix typerror dealing with '<='

Body:
what the codes is supposed to is take the users input and then movie the rectangle around and when I run the code i get a Typeerror:<=' not supported between instances of 'str' and 'int'

these were some of the comments made on my code

For both Point and Rectangle class constructors, you are providing default values for the parameters. You should not since the assignment states, you should make them required arguments. (-4)

rectangleCount static attribute of the Rectangle class not kept up to date (should be incremented in the constructor to keep track of count of Rectangle objects created so far) (-2)

Rectangle's constructor doesn't check if width and height is negative, and if so print error message. (-2)

Calculations in the bottomRight property is incorrect. (-2) It should be

    @property
    def bottomRight(self):
        return Point(self.topLeft.x + self.width, self.topLeft.y + self.height)

Calculations in the perimeter proper

    # Prog 120
    # Rectangle & Point Classes

    class Point:
        def __init__(self, x, y): # makes the value required
            self.__x = x
            self.__y = y

        @property  # read only property for x
        def x(self):
            return self.__x

        @property  # read only property for y
        def y(self):
            return self.__y

        def translate(self, dx, dy):  # moves x coordinate by 'dx' amount of time  and move dy
            self.__x += dx
            self.__y += dy

    class Rectangle:
        DEFAULT_WIDTH = 1 # static attributes
        DEFAULT_HEIGHT = 1
        rectangleCount = 0

        def __init__(self, topLeft, width, height):
            self.__topLeft = topLeft

            # check width argument
            if (width <= 0):
                print("Invalid width")
                self.__width = Rectangle.DEFAULT_WIDTH
            else:
                self.__width = width

             # check height argument
            if (height <= 0):
                 print("Invalid Height")
                 self.__height = Rectangle.DEFAULT_HEIGHT
            else:
                self.__height = height

            Rectangle.rectangleCount +=1 #updates the count of rectangels created

        @property
        def topLeft(self):
            return self.__topLeft

        @topLeft.setter
        def topLeft(self, newTopLeft):
            self.__topLeft = newTopLeft

        @property
        def width(self):
            return self.__width

        @width.setter
        def width(self, newWidth):
            if (newWidth <= 0):
                print("Width cannot be less than '0'. ")
            else:
                self.__width = newWidth

        @property
        def height(self):
            return self.__height

        @height.setter
        def height(self, newHeight):
            if (newHeight <= 0):
                print("Height cannot be less than '0'. ")
            else:
                self.__height = newHeight

        @property
        def bottomRight(self):
            return Point(self.topLeft.x + self.topLeft.y + self.height)

        @property
        def area(self):
            return self.__width * self.__height

        @property
        def perimeter(self):
            return self.__width *2 + self.__height *2

        def translate(self, dx, dy):  # moves x coordinate by 'dx' amount of time and move y
            self.__topLeft.translare(dx,dy)

    def main():
        bill = Point(x="", y="")
        will = Rectangle(topLeft="", width="", height="")
        if will.width and will.height < 0:
            print("Width and Height cannot be less than 0.")
            will.width = will.DEFAULT_WIDTH
            will.height = will.DEFAULT_HEIGHT
        will.rectangleCount += 1

    if __name__ == "__main__":
        main()

Body:
bill = Point(x="", y="")
will = Rectangle(topLeft="", width="", height="")

Here you are setting the attributes in Rectangle to the empty string.

And here:

 def __init__(self, topLeft, width, height):
            self.__topLeft = topLeft

            # check width argument
            if (width <= 0):
                print("Invalid width")
                self.__width = Rectangle.DEFAULT_WIDTH

You are comparing that string to 0 - an int. Obviously you can't compare "" with 0. That doesn't make any sense. That's what python is telling you with that error message.

Maybe try passing integers to the constructors. Like this:

bill = Point(x=5, y=9)
will = Rectangle(topLeft=2, width=4, height=1)


问:
Mercurial - which head is active in your working directory?
hg head lists multiple heads.  How do you know which head is active in your working directory?

答: hg id gives you the revision of the working directory. hg sum provides the same information and some more. You might also want to check the compass extension which provides detailed information about the "location" of your working copy within the whole repository.


问:
How to fix error "ValueError: <Follower: Follower object (None)> instance is not saved." Use bulk = False or save the object first. "
I wanted to create a follower system, and I get a "ValueError:  instance is not saved." Use bulk = False or save the object first. " .Please how to solve this problem, sorry for my bad writing!!

```<code>#my models.py

from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()

class Follower(models.Model):
    follower = models.ForeignKey(User, related_name='following', on_delete=None)
    following = models.ForeignKey(User, related_name='followers', on_delete=None)

    class Meta:
        unique_together = ('follower', 'following')

    def __unicode__(self):
        return u'%s follows %s' % (self.follower, self.following)

#in the interpreter
>>> from followers.models import *

>>> john = User.objects.create_user('john', 'lennon@thebeatles.com', 'password')
>>> paul = User.objects.create_user('paul', 'mccartney@thebeatles.com', 'password')
>>> george = User.objects.create_user('george', 'harrison@thebeatles.com', 'password')
>>> ringo = User.objects.create_user('ringo', 'starr@thebeatles.com', 'password')

#the mistake comes from here
>>> john.following.add(Follower(following=paul))
</code>```

and I get

in add "the object first." % obj
ValueError:  instance isn't saved. Use bulk=False or save the object first.`

答:
You should create a Follower object like:

```<code>Follower.objects.create(<b>follower=john, following=paul</b>)</code>```

You can not add unsaved objects to a one-to-many or many-to-many relation, since at that moment they do not have a primary key yet. Since here your ForeignKeys are non-nullable, you can not first save the Follower object with one of the two relations filled in, and then use .add(..) to add the other end, but that would be more expensive anyway, since it results in two queries.

You can also make Follower objects in bulk like:

```<code>Follower.objects.<b>bulk_create</b>([
    Follower(follower=john, following=paul),
    Follower(follower=john, following=ringo),
    Follower(follower=ringo, following=paul),
    Follower(follower=george, following=ringo)
])</code>```

Body:
I wanted to create a follower system, and I get a "ValueError:  instance is not saved." Use bulk = False or save the object first. " .Please how to solve this problem, sorry for my bad writing!!

#my models.py

from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()

class Follower(models.Model):
    follower = models.ForeignKey(User, related_name='following', on_delete=None)
    following = models.ForeignKey(User, related_name='followers', on_delete=None)

    class Meta:
        unique_together = ('follower', 'following')

    def __unicode__(self):
        return u'%s follows %s' % (self.follower, self.following)

#in the interpreter
>>> from followers.models import *

>>> john = User.objects.create_user('john', 'lennon@thebeatles.com', 'password')
>>> paul = User.objects.create_user('paul', 'mccartney@thebeatles.com', 'password')
>>> george = User.objects.create_user('george', 'harrison@thebeatles.com', 'password')
>>> ringo = User.objects.create_user('ringo', 'starr@thebeatles.com', 'password')

#the mistake comes from here
>>> john.following.add(Follower(following=paul))

and I get

in add "the object first." % obj
ValueError:  instance isn't saved. Use bulk=False or save the object first.`

Body:
You should create a Follower object like:

Follower.objects.create(follower=john, following=paul)

You can not add unsaved objects to a one-to-many or many-to-many relation, since at that moment they do not have a primary key yet. Since here your ForeignKeys are non-nullable, you can not first save the Follower object with one of the two relations filled in, and then use .add(..) to add the other end, but that would be more expensive anyway, since it results in two queries.

You can also make Follower objects in bulk like:

Follower.objects.bulk_create([
    Follower(follower=john, following=paul),
    Follower(follower=john, following=ringo),
    Follower(follower=ringo, following=paul),
    Follower(follower=george, following=ringo)
])


问:
Byte-buddy and cglib not available in Spock test
I started playing around with Spock testing framework and my build.gradle dependencies section looks like this:

```<code>dependencies {
    testCompile "org.spockframework:spock-core:1.3-groovy-2.5"
}
</code>```

I have a (useless) Spock test that requires creation of a stub:

```<code>def 'A test that will fail'() {
    given: ''
    def random = Stub(Random)
}
</code>```

When launched, the test fails with the given error:

CannotCreateMockException: Cannot create mock for class java.util.Random. Mocking of non-interface types requires a code generation library. Please put an up-to-date version of byte-buddy or cglib-nodep on the class path.

This error is mentioned in Spock documentation and it's caused by cglib or byte-buddy not being available at runtime.

Considering that spock-core's pom lists both byte-buddy and cglib as compile dependencies, why are they not retained at runtime? In other words, why do we need to explicitly add the following runtime dependency to our build.gradle file?

```<code>testRuntime "net.bytebuddy:byte-buddy:1.9.3"
</code>```

答:
Because both (byte-buddy and cglib-nodep) are marked as <optional>true</optional>, where from Gradle point of view they are as compileOnly dependencies - see: https://blog.gradle.org/introducing-compile-only-dependencies

Compile-only dependencies are distinctly different than regular
  compile dependencies. They are not included on the runtime classpath
  and they are non-transitive, meaning they are not included in
  dependent projects.

Body:
I started playing around with Spock testing framework and my build.gradle dependencies section looks like this:

dependencies {
    testCompile "org.spockframework:spock-core:1.3-groovy-2.5"
}

I have a (useless) Spock test that requires creation of a stub:

def 'A test that will fail'() {
    given: ''
    def random = Stub(Random)
}

When launched, the test fails with the given error:

CannotCreateMockException: Cannot create mock for class java.util.Random. Mocking of non-interface types requires a code generation library. Please put an up-to-date version of byte-buddy or cglib-nodep on the class path.

This error is mentioned in Spock documentation and it's caused by cglib or byte-buddy not being available at runtime.

Considering that spock-core's pom lists both byte-buddy and cglib as compile dependencies, why are they not retained at runtime? In other words, why do we need to explicitly add the following runtime dependency to our build.gradle file?

testRuntime "net.bytebuddy:byte-buddy:1.9.3"


答:
In your code clicked is a public variable, meaning it's the same for every element.
The easiest way of doing it would be checking the current color of the element

function change(abba) {
  if (abba.style.color !== "red") {
    abba.style.color = "red";
  } else {
    abba.style.color = "green";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p onclick="change(this)">HELLO WORLD</p>
<p onclick="change(this)">HELLO WORLD</p>
<p onclick="change(this)">HELLO WORLD</p>
<p onclick="change(this)">HELLO WORLD</p></code>```

Title: How Can I get two diffrents event with onclick?

Body:
In your code clicked is a public variable, meaning it's the same for every element.
The easiest way of doing it would be checking the current color of the element

function change(abba) {
  if (abba.style.color !== "red") {
    abba.style.color = "red";
  } else {
    abba.style.color = "green";
  }
}

<p onclick="change(this)">HELLO WORLD</p>
<p onclick="change(this)">HELLO WORLD</p>
<p onclick="change(this)">HELLO WORLD</p>
<p onclick="change(this)">HELLO WORLD</p>


问:
Refresh page when localStorage is deleted
I am building an app in reactjs.

I use JWT in localStorage in order to authenticate the user in every request in the backend.

What I want to do is to logout the user automatically when the localStorage is deleted via cookies from the user OR JWT token expires.

Is it possible to add a listener which is fired when localStorage is deleted?

For now I am doing something like

```<code>if(!!localStorage.getItem('id_token') && !this.isTokenExpired(token)) {
  // eslint-disable-next-line
  location.reload(true);
}
</code>```

It works but its not efficient to add these lines of code in every button functions.

So I want a listener which when the localStorage is deleted or expires to fire the above code.

Any advice? Thank you in advance

答:
Finally I solve it by adding an event listener and index.js

```<code>window.addEventListener('storage', function(e) {
  if(!Auth.loggedIn()) {
    // eslint-disable-next-line
    location.reload(true);
  }
});
</code>```

So when the storage changes I check if the user is logged in and reload the page. When the page is reloaded I logout the user .

Body:
I am building an app in reactjs.

I use JWT in localStorage in order to authenticate the user in every request in the backend.

What I want to do is to logout the user automatically when the localStorage is deleted via cookies from the user OR JWT token expires.

Is it possible to add a listener which is fired when localStorage is deleted?

For now I am doing something like

if(!!localStorage.getItem('id_token') && !this.isTokenExpired(token)) {
  // eslint-disable-next-line
  location.reload(true);
}

It works but its not efficient to add these lines of code in every button functions.

So I want a listener which when the localStorage is deleted or expires to fire the above code.

Any advice? Thank you in advance

Body:
Finally I solve it by adding an event listener and index.js

window.addEventListener('storage', function(e) {
  if(!Auth.loggedIn()) {
    // eslint-disable-next-line
    location.reload(true);
  }
});

So when the storage changes I check if the user is logged in and reload the page. When the page is reloaded I logout the user .


问:
Send SMS programmatically on Oppo phones
My android app sends SMS programmatically (usually triggered by a push message), and works as expected on numerous Android versions and devices. However on a new Oppo phone model CPH1851 I see a notification pop-up saying:

"[app name] will send SMS to [phone number]"

(where [app name] is the name of my app, and [phone number] is the number to which the app is sending an SMS to

The notification has a "Send" button and a "Cancel" button (latter with a decrementing timer)

Clearly this seems like another misguided attempt at Android security, without any thought to fragmentation and user-experience, but just looking to solve it.

Thanks for the help

答:
Oppo's customized version of Android (called ColorOS) is the reason behind this trouble.

Settings/Security/Permissions/Send SMS shows you whether the app is "Allow"-ed to send SMS ("Ask" & "Forbid" are the other options). Setting this to "Allow" made the problem go away on one Oppo model. But not on another.

So the other option is to enable Developer Options, and turn on "Disable Permission Monitoring", at the very bottom of the list (this seems to turn off all of the ColorOS permission monitoring, but doesn't affect the basic Android permissioning).


问:
How to remove duplicate elements from an array in Swift 5?
I have an array of custom objects, a.k.a users, and some of them are duplicates.

How can I make sure there is only one of each element? No duplicates.

Also, what's the most efficient way?

```<code>var users: UserModel = [UserModel]()
</code>```

答: Maybe instead of using an array you want to use a set? https://developer.apple.com/documentation/swift/set</p>

Body:
I have an array of custom objects, a.k.a users, and some of them are duplicates.

How can I make sure there is only one of each element? No duplicates.

Also, what's the most efficient way?

var users: UserModel = [UserModel]()


问:
Correct name for non-COM, non-.NET DLL?
In the Windows world, what is the correct name for a good. old-fashioned C++ DLL with exported functions? Not a COM DLL, not a .NET DLL. The kind of DLL that we used to invoke by calling LoadLibrary() and GetProcAddress()?

I've always called them "flat DLLs" because the caller cannot instantiate objects from the DLL, but what is the correct name?

EDIT

Thanks for the answers.

Just "DLL" may be technically correct, but where I work everyone assumes that "DLL" means COM, or maybe at a push .NET, so I need a term that distinguishes exactly what I mean.

答: I always just called them DLLs, but I didn't stay in th C++/VB6 world for too long.</p>

OwnerDisplayName: Peter May

ContentLicense: CC BY-SA 2.5

Title: Correct name for non-COM, non-.NET DLL?

LastEditorDisplayName: Peter May

OwnerDisplayName: Charles Graham


问:
What does the red exclamation point icon in Eclipse mean?
What does the red exclamation point icon in Eclipse mean? There are lots of different search results on the Internet about "red exclamation point icons" and "red exclamation mark decorators" and "red bang icons," no doubt because lots of plugins and programming-related tools use red exclamation point icons. So, to be clear, this is the one I mean:

It appears as a decorator on projects in the Package Explorer view.

In my case, the icon went away when a missing build path variable was filled in. I'm using MyEclipse 9.0, but I don't think this is MyEclipse-specific. Other people on the Internet have reported that it has to do with other issues, including Subclipse, the .svn folder and moving files between working copies.

答:
According to the documentation:

Decorates Java projects and working
  sets that contain build path errors

In practice, I've found that a "build path error" may be caused by any number of reasons, depending on what plugins are active.  Check the "Problems" view for more information.


问:
download pdf with guzzle
I want to download a pdf file with guzzle. Is this possible?

I tried this code:

$response  = $this->client->post(self::API_BASE_URL.self::API_LABEL_URL,
                    [
                            'future' => true,
                            'json' => [$this->json],
                            'headers' => ['Content-Type' => 'application/json', 'Accept' => 'application/pdf'],
                            'query' => [
                                        'return-type' => 'pdf',
                                        'x-api-key'   => $this->apiKey
                            ],
                     ]);
```

<p>and I get</p>

```[body] => GuzzleHttp\Stream\Stream Object(
[stream:GuzzleHttp\Stream\Stream:private] => Resource id #120
[size:GuzzleHttp\Stream\Stream:private] => 649
[seekable:GuzzleHttp\Stream\Stream:private] => 1
[readable:GuzzleHttp\Stream\Stream:private] => 1
[writable:GuzzleHttp\Stream\Stream:private] => 1
[uri:GuzzleHttp\Stream\Stream:private] => php://temp
[customMetadata:GuzzleHttp\Stream\Stream:private] => Array
```

But I don't have an idea how I can handle this Resource id to save the pdf file.
I use guzzle 5.3 and PHP 5.4 with no options to update the php version.

答:
You can use Guzzle sink option to download file - http://docs.guzzlephp.org/en/stable/request-options.html#sink

```<code>$pdfFilePath = __DIR__ . '/resource/file.pdf'; // specify your path
$pdfFileResource = fopen($pdfFilePath, 'w+');

$this->client->post(
    self::API_BASE_URL . self::API_LABEL_URL,
    [
        'future' => true,
        'json' => [$this->json],
        'headers' => [
            'Content-Type' => 'application/json',
            'Accept' => 'application/pdf'
        ],
        'query' => [
            'return-type' => 'pdf',
            'x-api-key'   => $this->apiKey
        ],
        'sink' => $pdfFileResource
    ]
);
</code>```

More examples - https://github.com/andriichuk/php-curl-cookbook#download-file

Title: download pdf with guzzle

Body:
I want to download a pdf file with guzzle. Is this possible?

I tried this code:

$response  = $this->client->post(self::API_BASE_URL.self::API_LABEL_URL,
                    [
                            'future' => true,
                            'json' => [$this->json],
                            'headers' => ['Content-Type' => 'application/json', 'Accept' => 'application/pdf'],
                            'query' => [
                                        'return-type' => 'pdf',
                                        'x-api-key'   => $this->apiKey
                            ],
                     ]);

and I get

[body] => GuzzleHttp\Stream\Stream Object(
[stream:GuzzleHttp\Stream\Stream:private] => Resource id #120
[size:GuzzleHttp\Stream\Stream:private] => 649
[seekable:GuzzleHttp\Stream\Stream:private] => 1
[readable:GuzzleHttp\Stream\Stream:private] => 1
[writable:GuzzleHttp\Stream\Stream:private] => 1
[uri:GuzzleHttp\Stream\Stream:private] => php://temp
[customMetadata:GuzzleHttp\Stream\Stream:private] => Array

But I don't have an idea how I can handle this Resource id to save the pdf file.
I use guzzle 5.3 and PHP 5.4 with no options to update the php version.

Body:
You can use Guzzle sink option to download file - http://docs.guzzlephp.org/en/stable/request-options.html#sink

$pdfFilePath = __DIR__ . '/resource/file.pdf'; // specify your path
$pdfFileResource = fopen($pdfFilePath, 'w+');

$this->client->post(
    self::API_BASE_URL . self::API_LABEL_URL,
    [
        'future' => true,
        'json' => [$this->json],
        'headers' => [
            'Content-Type' => 'application/json',
            'Accept' => 'application/pdf'
        ],
        'query' => [
            'return-type' => 'pdf',
            'x-api-key'   => $this->apiKey
        ],
        'sink' => $pdfFileResource
    ]
);

More examples - https://github.com/andriichuk/php-curl-cookbook#download-file


问:
Recording the total time taken for running a spider in scrapy
I am using scrapy to scrap a site

I had written a spider and fetched all the items from the page and saved to a csv file,
and now i want to save the total execution time taken by scrapy to run the spider file,
actually after spider execution is completed and when we have at at terminal it will display some results
like starttime, endtime and so on .... so now in my program i need to calculate the total time taken by scrapy to run the spider and storing the total time some where....

Can anyone let me now how to do this through an example........

Thanks in advance...........

答:
I'm quite a beginner but I did it in a bit simpler method and I hope it makes sense.

```<code>import datetime
</code>```

then declare two global variables i.e
self.starting_time and self.ending_time.

Inside the constructor of the spider class, set the starting time as

```<code>def __init__(self, name=None, **kwargs):
        self.start_time = datetime.datetime.now()
</code>```

After that, use the closed method to find the difference between the ending and the starting.
i.e

```<code>def closed(self, response):
   self.ending_time = datetime.datetime.now()
   duration = self.ending_time - self.starting_time
   print(duration)
</code>```

That's pretty much of it. The closed method is called soon after the spider has ended the process. See the documentation here.

Body:
I'm quite a beginner but I did it in a bit simpler method and I hope it makes sense.

import datetime

then declare two global variables i.e
self.starting_time and self.ending_time.

Inside the constructor of the spider class, set the starting time as

def __init__(self, name=None, **kwargs):
        self.start_time = datetime.datetime.now()

After that, use the closed method to find the difference between the ending and the starting.
i.e

def closed(self, response):
   self.ending_time = datetime.datetime.now()
   duration = self.ending_time - self.starting_time
   print(duration)

That's pretty much of it. The closed method is called soon after the spider has ended the process. See the documentation here.


问:
Image in flex container not centering after defining width and height
I'm doing some personal portfolio using css flex box. what I'm trying to do is to center the image horizontally, It did center but the problem is after I defined width and height to img the image is at the start or left now not in the center.

This is what it looks like when centered and not defining the width and height

.center-img{
  border-radius: 50%;
  display:flex;
  flex-direction:column;
  justify-content:center;
  text-align:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="center-img">
  <img src="https://png2.kisspng.com/sh/06560124247439e98f5534b17467b691/L0KzQYm3VcA5N5DBiZH0aYP2gLBuTgV0baMye9H2cIX3dcO0ifNwdqQyiAt8dHXwPbTvif5me5Yyj9t3ZD33ecXzhb1kd516hdC2NXHpQYW5VBZlO5JnTKo3M0e7RIa8VccyPWM6T6g5NkO8SIeATwBvbz==/kisspng-user-computer-icons-system-chinese-wind-title-column-5af1427fd3ab48.378455571525760639867.png" alt="user">
  <h1>User</h1>
</div></code>```

And this is what it look liked after defining width and height

.center-img{
  width:100px;
  height:100px;
  border-radius: 50%;
  display:flex;
  flex-direction:column;
  justify-content:center;
  text-align:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="center-img">
  <img src="https://png2.kisspng.com/sh/06560124247439e98f5534b17467b691/L0KzQYm3VcA5N5DBiZH0aYP2gLBuTgV0baMye9H2cIX3dcO0ifNwdqQyiAt8dHXwPbTvif5me5Yyj9t3ZD33ecXzhb1kd516hdC2NXHpQYW5VBZlO5JnTKo3M0e7RIa8VccyPWM6T6g5NkO8SIeATwBvbz==/kisspng-user-computer-icons-system-chinese-wind-title-column-5af1427fd3ab48.378455571525760639867.png" alt="user">
  <h1>User</h1>
</div></code>```

I expect that after defining the width and height of the image it would not affect the position of the image. so it should be in the center.
thank you!

答:
Apply the height and width to the img only and add align-items: center like this:

```<code>.center-img {
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

img {
 width: 100px;
 height: 100px;
}
</code>```

```<code><div class="center-img">
  <img src="https://png2.kisspng.com/sh/06560124247439e98f5534b17467b691/L0KzQYm3VcA5N5DBiZH0aYP2gLBuTgV0baMye9H2cIX3dcO0ifNwdqQyiAt8dHXwPbTvif5me5Yyj9t3ZD33ecXzhb1kd516hdC2NXHpQYW5VBZlO5JnTKo3M0e7RIa8VccyPWM6T6g5NkO8SIeATwBvbz==/kisspng-user-computer-icons-system-chinese-wind-title-column-5af1427fd3ab48.378455571525760639867.png"
            alt="user">
 <h1>User</h1>
</div>
</code>```

Body:
I'm doing some personal portfolio using css flex box. what I'm trying to do is to center the image horizontally, It did center but the problem is after I defined width and height to img the image is at the start or left now not in the center.

This is what it looks like when centered and not defining the width and height

.center-img{
  border-radius: 50%;
  display:flex;
  flex-direction:column;
  justify-content:center;
  text-align:center;
}

User

And this is what it look liked after defining width and height

.center-img{
  width:100px;
  height:100px;
  border-radius: 50%;
  display:flex;
  flex-direction:column;
  justify-content:center;
  text-align:center;
}

User

I expect that after defining the width and height of the image it would not affect the position of the image. so it should be in the center.
thank you!

Body:
Apply the height and width to the img only and add align-items: center like this:

.center-img {
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

img {
 width: 100px;
 height: 100px;
}

<div class="center-img">
  <img src="https://png2.kisspng.com/sh/06560124247439e98f5534b17467b691/L0KzQYm3VcA5N5DBiZH0aYP2gLBuTgV0baMye9H2cIX3dcO0ifNwdqQyiAt8dHXwPbTvif5me5Yyj9t3ZD33ecXzhb1kd516hdC2NXHpQYW5VBZlO5JnTKo3M0e7RIa8VccyPWM6T6g5NkO8SIeATwBvbz==/kisspng-user-computer-icons-system-chinese-wind-title-column-5af1427fd3ab48.378455571525760639867.png"
            alt="user">
 <h1>User</h1>
</div>


问:
How do I attach the image result from my API call as the background image to my app?
So background on what I'm trying to do.. User inputs city and the background changes to an image of that city, an image that is acquired from an API call to the Pixabay API. I have held the result as the variable "background" but I can't figure out how to append it to the background of the page. The "const background" variable itself renders an image URL. Meaning that when I console.log(background) I get the URL for the background image that I want to apply to the entire page.

```<code>import React, { Component } from "react";
import Title from "./Title.js";
import Form from "./Form.js";
import Weather from "./Weather.js";
import axios from "axios";

// import logo from "./logo.svg";
import "./App.css";

const API_KEY = "b6907d289e10d714a6e88b30761fae22";
// const API_ID = "12653279-f2ae53f8bfb342d39b6cbf92b";

class App extends Component {
  // the initial state of the application is set below, will change upon submit of button
  state = {
    temperature: undefined,
    city: undefined,
    description: undefined,
    error: undefined,
    searchText: "",
    apiUrl: "https://pixabay.com/api",
    apiKey: "12653279-f2ae53f8bfb342d39b6cbf92b",
    images: []
  };
  getweatherData = async e => {
    // arrow function used as an alternative to constructor to bind data and use "this" to still be bound to component
    // async returns a promsise to be settled
    e.preventDefault();
    // e argument passed in the async function is now used to prevent refresh default action
    const city = e.target.elements.city.value;
    // a way that we can make the city value dynamic within the api url in the api call
    const api_call = await fetch(
      // await key word pauses the function until data is recieved from api call
      `https://openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}`
    );
    const data = await api_call.json();
    // above, the data recieved from the API is converted to json readable format
    console.log(data);
    if (data.cod === 404) {
      throw Error(data.message);
    } else {
      this.setState({
        temperature: data.main.temp.toFixed(0),
        city: data.sys.city,
        country: data.sys.country,
        description: data.weather[0].description,
        error: "undefined"
      });
    }
    axios
      .get(
        `${this.state.apiUrl}/?key=${
          this.state.apiKey
        }&q=${city}&image_type=photo&per_page="1"
        }&safesearch=true&editorschoice= true`
      )
      .then(res => {
        this.setState({ images: res.data.hits });
        const background = res.data.hits[1];
        console.log(background);
      });
  };

  render() {
    return (
      <div className="container">
        <Title />
        {/* setting up a prop to the getweatherData value so we can have access to it in the form.js */}
        <Form getweatherData={this.getweatherData} />
        {/* defining props so they can be accessed in the weather.js */}
        <Weather
          temperature={this.state.temperature}
          city={this.state.city}
          country={this.state.country}
          description={this.state.description}
          error={this.state.error}
        />
      </div>
    );
  }
}

export default App;

</code>```

Form. js

```<code>import React, { Component } from "react";

class Form extends Component {
  render() {
    return (
      // a react attribute onSubmit to call in our prop
      <form onSubmit={this.props.getweatherData}>
        <input type="text" name="city" placeholder="City..." />
        {/* <input type="text" name="country" placeholder="Country..." /> */}
        <button>Get Weather</button>
      </form>
    );
  }
}

export default Form;
</code>```

答:
Set the background image in state, and then use inline style on your whatever element you want it to be displayed in. Something like this.</p>

```<code>...
const background = res.data.hits[1];
this.setState({ background })
...
return (
    <div className="container" style={{ this.state.background ? { background: this.state.background } : {} }}>
...
</code>```

Body:
So background on what I'm trying to do.. User inputs city and the background changes to an image of that city, an image that is acquired from an API call to the Pixabay API. I have held the result as the variable "background" but I can't figure out how to append it to the background of the page. The "const background" variable itself renders an image URL. Meaning that when I console.log(background) I get the URL for the background image that I want to apply to the entire page.

import React, { Component } from "react";
import Title from "./Title.js";
import Form from "./Form.js";
import Weather from "./Weather.js";
import axios from "axios";

// import logo from "./logo.svg";
import "./App.css";

const API_KEY = "b6907d289e10d714a6e88b30761fae22";
// const API_ID = "12653279-f2ae53f8bfb342d39b6cbf92b";

class App extends Component {
  // the initial state of the application is set below, will change upon submit of button
  state = {
    temperature: undefined,
    city: undefined,
    description: undefined,
    error: undefined,
    searchText: "",
    apiUrl: "https://pixabay.com/api",
    apiKey: "12653279-f2ae53f8bfb342d39b6cbf92b",
    images: []
  };
  getweatherData = async e => {
    // arrow function used as an alternative to constructor to bind data and use "this" to still be bound to component
    // async returns a promsise to be settled
    e.preventDefault();
    // e argument passed in the async function is now used to prevent refresh default action
    const city = e.target.elements.city.value;
    // a way that we can make the city value dynamic within the api url in the api call
    const api_call = await fetch(
      // await key word pauses the function until data is recieved from api call
      `https://openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}`
    );
    const data = await api_call.json();
    // above, the data recieved from the API is converted to json readable format
    console.log(data);
    if (data.cod === 404) {
      throw Error(data.message);
    } else {
      this.setState({
        temperature: data.main.temp.toFixed(0),
        city: data.sys.city,
        country: data.sys.country,
        description: data.weather[0].description,
        error: "undefined"
      });
    }
    axios
      .get(
        `${this.state.apiUrl}/?key=${
          this.state.apiKey
        }&q=${city}&image_type=photo&per_page="1"
        }&safesearch=true&editorschoice= true`
      )
      .then(res => {
        this.setState({ images: res.data.hits });
        const background = res.data.hits[1];
        console.log(background);
      });
  };

  render() {
    return (

        <Title />
        {/* setting up a prop to the getweatherData value so we can have access to it in the form.js */}
        <Form getweatherData={this.getweatherData} />
        {/* defining props so they can be accessed in the weather.js */}
        <Weather
          temperature={this.state.temperature}
          city={this.state.city}
          country={this.state.country}
          description={this.state.description}
          error={this.state.error}
        />

    );
  }
}

export default App;

Form. js

import React, { Component } from "react";

class Form extends Component {
  render() {
    return (
      // a react attribute onSubmit to call in our prop
      <form onSubmit={this.props.getweatherData}>
        <input type="text" name="city" placeholder="City..." />
        {/* <input type="text" name="country" placeholder="Country..." /> */}
        <button>Get Weather</button>
      </form>
    );
  }
}

export default Form;

Body:
Set the background image in state, and then use inline style on your whatever element you want it to be displayed in. Something like this.

...
const background = res.data.hits[1];
this.setState({ background })
...
return (
    <div className="container" style={{ this.state.background ? { background: this.state.background } : {} }}>
...


问:
Progress bar in Swing (Java) for command tools
I have several C/C++ command line tools that I'm wrapping with Java.Swing as GUI. The command line tools can take minutes to hours. Progress bar seems like a good idea to keep users sane. I'm also thinking it might be nice to wrap a GUI for the progress bar, instead of just using system out.  But how?

I'm thinking the command line tools can write percents to stderr and I can somehow read it in java. Not exactly sure what the mechanics for this would be.  I'm also not clear on asynchronous display (learned a bit about invokeLater() ).  New to Java, and would appreciate general suggestions as well.  Thanks.

--- update ---

Thanks everyone for your suggestions.  Here's the resulting code.

```<code>private void redirectSystemStreams() {
    OutputStream out_stderr = new OutputStream() {
      @Override
      public void write(final int b) throws IOException {
        update(String.valueOf((char) b));
      }
      @Override
      public void write(byte[] b, int off, int len) throws IOException {
        update(new String(b, off, len));
      }
      @Override
      public void write(byte[] b) throws IOException {
        write(b, 0, b.length);
      }
    };
    System.setErr(new PrintStream(out_stderr, true));
}

private void update(final String inputText) {
    int value = 20; //parse inputText; make sure your executable calls fflush(stderr) after each fprintf().
    jProgressBar.setValue(value);

    /* Also one can redirect to a textpane
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        //update jTextPane with inputText
      }
    });
    */
}
</code>```

答:
```<code>// Create a window
JFrame frame = new JFrame("Progress");
// Creates a progress bar and add it to the window
JProgressBar prog = new JProgressBar();
frame.add(prog);
// Run C/C++ application
try {
   Process p = Runtime.getRuntime().exec(new String[]{"filename","arg1","arg2","..."});
   // Get InputStream
   BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
   // Update the progress when recieving output from C/C++
   new java.util.Timer().schedule(new TimerTask(){
       public void run(){
          String str = "";
          while ((str=br.readLine()!=null) {
             prog.setValue(new Integer(str)); // Set Value of Progress Bar
             prog.setString(str+"%"); // Set Value to display (in text) on Progress Bar
          }
       }
   },0,100); // Check every 100 milliseconds
   // Fit the window to its contents and display it
   frame.pack();
   frame.setVisible(true);
 } catch (Exception e) {
    System.out.println("Failed To Launch Program or Failed To Get Input Stream");
 }
</code>```

Body:
I have several C/C++ command line tools that I'm wrapping with Java.Swing as GUI. The command line tools can take minutes to hours. Progress bar seems like a good idea to keep users sane. I'm also thinking it might be nice to wrap a GUI for the progress bar, instead of just using system out.  But how?

I'm thinking the command line tools can write percents to stderr and I can somehow read it in java. Not exactly sure what the mechanics for this would be.  I'm also not clear on asynchronous display (learned a bit about invokeLater() ).  New to Java, and would appreciate general suggestions as well.  Thanks.

--- update ---

Thanks everyone for your suggestions.  Here's the resulting code.

private void redirectSystemStreams() {
    OutputStream out_stderr = new OutputStream() {
      @Override
      public void write(final int b) throws IOException {
        update(String.valueOf((char) b));
      }
      @Override
      public void write(byte[] b, int off, int len) throws IOException {
        update(new String(b, off, len));
      }
      @Override
      public void write(byte[] b) throws IOException {
        write(b, 0, b.length);
      }
    };
    System.setErr(new PrintStream(out_stderr, true));
}

private void update(final String inputText) {
    int value = 20; //parse inputText; make sure your executable calls fflush(stderr) after each fprintf().
    jProgressBar.setValue(value);

    /* Also one can redirect to a textpane
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        //update jTextPane with inputText
      }
    });
    */
}


问:
what is the meaning of hashable in dict
why I cannot write this {names: heroes} inside the dictionary .when I did this
{{names: heroes} for names, heroes in zip(names, heroes)} an error occurred which is a type error saying unhashable dict. What does that mean?

```<code>nums={{names:heroes} for names, heroes in zip(names,heroes)}
print(nums)
</code>```

```<code>Traceback (most recent call last):
  File "C:/Users/ahmod/AppData/Local/Programs/Python/Python37-32/mim.py", line 7, in <module>
    nums={{names:heroes} for names, heroes in zip(names,heroes)}
  File "C:/Users/ahmod/AppData/Local/Programs/Python/Python37-32/mim.py", line 7, in <setcomp>
    nums={{names:heroes} for names, heroes in zip(names,heroes)}
TypeError: unhashable type: 'dict'
</code>```

答:
```<code>{{names: heroes} for names, heroes in zip(names, heroes)}
</code>```

This is a set comprehension -because you are using the {} curly braces. In a set, each element must be hashable. you are setting each elements in the set to {names: heroes} - which is a dict. So you are trying to make a set of dict.

But unfortunately, in python, dict is not hashable - since it's a mutable type.

So you can't do that.

Instead you can try to create a dictionary directly:

```<code>{name: heroe for name, heroe in zip(names, heroes)}
</code>```

By just removing the extra curly braces.

Title: what is the meaning of hashable in dict

Body:
why I cannot write this {names: heroes} inside the dictionary .when I did this
{{names: heroes} for names, heroes in zip(names, heroes)} an error occurred which is a type error saying unhashable dict. What does that mean?

nums={{names:heroes} for names, heroes in zip(names,heroes)}
print(nums)

Traceback (most recent call last):
  File "C:/Users/ahmod/AppData/Local/Programs/Python/Python37-32/mim.py", line 7, in <module>
    nums={{names:heroes} for names, heroes in zip(names,heroes)}
  File "C:/Users/ahmod/AppData/Local/Programs/Python/Python37-32/mim.py", line 7, in <setcomp>
    nums={{names:heroes} for names, heroes in zip(names,heroes)}
TypeError: unhashable type: 'dict'

Body:
{{names: heroes} for names, heroes in zip(names, heroes)}

This is a set comprehension -because you are using the {} curly braces. In a set, each element must be hashable. you are setting each elements in the set to {names: heroes} - which is a dict. So you are trying to make a set of dict.

But unfortunately, in python, dict is not hashable - since it's a mutable type.

So you can't do that.

Instead you can try to create a dictionary directly:

{name: heroe for name, heroe in zip(names, heroes)}

By just removing the extra curly braces.


问:
How do I move a Python 3.6 installation a different directory?
I have installed Python 3.6.2  Windows in

c:\users\username\AppData\Local\programs\Python\Python36

(because that is the (totally stupid) default.

I have manually moved that into c:\

But the update to Python 3.6.3 still installs to the original target.

How do I change this (without uninstalling (which would also uninstall all packages))?

答:
I had faced similar problem. For some reason I wanted to change the PC admin but my Python was installed on the old user directory.
All updates and repairs I had to do on the same directory.

Then I deleted the python path from registry (Since I wanted to have fresh install later):
Computer\HKEY_CURRENT_USER\SOFTWARE\Python
and then reinstalled python.

PS: While installing on your home PC its better to install across users. My python is installed at below location:
C:\Program Files\Python37


问:
ModuleNotFoundError: No module named 'tensorflow_docs' when creating TensorFlow docs
I'm trying to follow the contribution guide for documentation. The required steps are:

```<code>git clone https://github.com/tensorflow/tensorflow tensorflow
cd tensorflow/tensorflow/tools/docs
pip install tensorflow==2.0.0-alpha0
python generate2.py --output_dir=/tmp/out
</code>```

But the last command gives me:

Traceback (most recent call last):   File "generate2.py", line 36, in

      from tensorflow_docs.api_generator import doc_controls ModuleNotFoundError: No module named 'tensorflow_docs'

This is in line 36 of generate2.py:

```<code>from tensorflow_docs.api_generator import doc_controls
</code>```

I haven't found a pip package containing tensorflow_docs. Any ideas?

答:
First install tensorflow_docs using this command:

pip install git+https://github.com/tensorflow/docs

Body:
I'm trying to follow the contribution guide for documentation. The required steps are:

git clone https://github.com/tensorflow/tensorflow tensorflow
cd tensorflow/tensorflow/tools/docs
pip install tensorflow==2.0.0-alpha0
python generate2.py --output_dir=/tmp/out

But the last command gives me:

Traceback (most recent call last):   File "generate2.py", line 36, in

      from tensorflow_docs.api_generator import doc_controls ModuleNotFoundError: No module named 'tensorflow_docs'

This is in line 36 of generate2.py:

from tensorflow_docs.api_generator import doc_controls

I haven't found a pip package containing tensorflow_docs. Any ideas?


问:
comment system switching to ajax, so not going to a different page
I was able to write comment system in python, django. but to make a comment the user has to move to different url. I don't want the users to move to a different page to write,edit,delete comment. I googled and it seems like I have to use ajax but I'm not sure. can someone guide me how to do it?

```<code>views.py

@login_required
def comment_new(request, post_pk):
    post = get_object_or_404(Post, pk=post_pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.author = request.user
            comment.save()
            return redirect('home')
    else:
        form = CommentForm()
    return render(request, 'community/comment_form.html', {
        'form':form,
        })

@login_required
def comment_edit(request, post_pk, pk):
    #post = get_object_or_404(Post, pk=post_pk)
    comment = get_object_or_404(Comment, pk=pk)
    if comment.author != request.user:
        return redirect(comment.post)
    if request.method == 'POST':
        form = CommentForm(request.POST, instance=comment)
        if form.is_valid():
            comment = form.save()
            return redirect(comment.post)
    else:
        form = CommentForm(instance=comment)
    return render(request, 'community/comment_form.html', {
        'form':form,
        })

@login_required
def comment_delete(request, post_pk, pk):
    comment = get_object_or_404(Comment, pk=pk)
    if comment.author != request.user:
        return redirect(comment.post)
    if request.method == 'POST':
        comment.delete()
        return redirect(comment.post)
    return render(request, 'community/comment_confirm_delete.html', {
        'comment':comment,
        })
</code>```

models.py

```<code>class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    author = models.ForeignKey(settings.AUTH_USER_MODEL,  on_delete=models.CASCADE)
    message = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-id']

    def get_edit_url(self):
        return reverse('comment_edit', args=[self.post.pk, self.pk])

    def get_delete_url(self):
        return reverse('comment_delete', args=[self.post.pk, self.pk])
</code>```

urls.py

```<code>urlpatterns = [
    path('', PostListView.as_view(), name='community-home'),
    path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
    path('post/<int:post_pk>/comment/new',views.comment_new, name='comment_new'),
    path('post/<int:post_pk>/comment/<int:pk>/edit',views.comment_edit, name='comment_edit'),
    path('post/<int:post_pk>/comment/<int:pk>/delete',views.comment_delete, name='comment_delete'),
</code>```

my html

```<code><a href="{% url 'comment_new' post.id %}">hello</a>

  <ul>
    {% for comment in post.comment_set.all %}
    <li>
      {{comment.message}} by {{comment.author}} at {{comment.created_at}}
      {% if comment.author == request.user %}
      <a href="{{ comment.get_edit_url }} ">
        edit
      </a>
      <a href="{{comment.get_delete_url}}">delete</a>
      {% endif %}
    </li>
    {% endfor %}
  </ul>
</code>```

forms.py

```<code>from django import forms
from .models import Comment

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['message']
</code>```

答:
You have to show the html. I'll do the ajax code for you if you do.

First you need to make sure you have jquery in your script. Put this after the head and before the body

```<code>  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</code>```

Next you have to call a javascript function via onclick for the AJAX request.

```<code>   {% for comment in post.comment_set.all %}

      <a href=onclick="get_delete({{comment.id}})">delete</a>

    {% endfor %}
</code>```

Here is the javascript function you call:

```<code>function get_delete(n){

var patch = '{% url "comment_delete" %}'
var post_data = {
  'csrfmiddlewaretoken':"{{ csrf_token }}",
 'iddy':n,}

$.ajax({
  type: "POST",
  url: patch,
  data:post_data,
  datatype:'json',
success: function(data){
console.log(data)
return
}

})}
</code>```

change your url path to.

```<code>path('post/commentdelete',views.comment_delete, name='comment_delete')
</code>```

finally, in views

```<code>def comment_delete(request):
    if request.POST:
        response_json = request.POST
        response_json = json.dumps(response_json)
        data = json.loads(response_json)
        comment = get_object_or_404(Comment, id=data['iddy'])
        if comment.author != request.user:
            msg = "you didnt write this comment"
            data = {'msg':msg}
        else:
             comment.delete()
             msg = "deleted"
             data = {'msg':msg}
   return JsonResponse(data, safe=False)
</code>```

Body:
I was able to write comment system in python, django. but to make a comment the user has to move to different url. I don't want the users to move to a different page to write,edit,delete comment. I googled and it seems like I have to use ajax but I'm not sure. can someone guide me how to do it?

views.py

@login_required
def comment_new(request, post_pk):
    post = get_object_or_404(Post, pk=post_pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.author = request.user
            comment.save()
            return redirect('home')
    else:
        form = CommentForm()
    return render(request, 'community/comment_form.html', {
        'form':form,
        })

@login_required
def comment_edit(request, post_pk, pk):
    #post = get_object_or_404(Post, pk=post_pk)
    comment = get_object_or_404(Comment, pk=pk)
    if comment.author != request.user:
        return redirect(comment.post)
    if request.method == 'POST':
        form = CommentForm(request.POST, instance=comment)
        if form.is_valid():
            comment = form.save()
            return redirect(comment.post)
    else:
        form = CommentForm(instance=comment)
    return render(request, 'community/comment_form.html', {
        'form':form,
        })

@login_required
def comment_delete(request, post_pk, pk):
    comment = get_object_or_404(Comment, pk=pk)
    if comment.author != request.user:
        return redirect(comment.post)
    if request.method == 'POST':
        comment.delete()
        return redirect(comment.post)
    return render(request, 'community/comment_confirm_delete.html', {
        'comment':comment,
        })

models.py

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    author = models.ForeignKey(settings.AUTH_USER_MODEL,  on_delete=models.CASCADE)
    message = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-id']

    def get_edit_url(self):
        return reverse('comment_edit', args=[self.post.pk, self.pk])

    def get_delete_url(self):
        return reverse('comment_delete', args=[self.post.pk, self.pk])

urls.py

urlpatterns = [
    path('', PostListView.as_view(), name='community-home'),
    path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
    path('post/<int:post_pk>/comment/new',views.comment_new, name='comment_new'),
    path('post/<int:post_pk>/comment/<int:pk>/edit',views.comment_edit, name='comment_edit'),
    path('post/<int:post_pk>/comment/<int:pk>/delete',views.comment_delete, name='comment_delete'),

my html

hello

    {% for comment in post.comment_set.all %}

      {{comment.message}} by {{comment.author}} at {{comment.created_at}}
      {% if comment.author == request.user %}

        edit

      delete
      {% endif %}

    {% endfor %}

forms.py

from django import forms
from .models import Comment

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['message']

Body:
You have to show the html. I'll do the ajax code for you if you do.

First you need to make sure you have jquery in your script. Put this after the head and before the body

  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

Next you have to call a javascript function via onclick for the AJAX request.

   {% for comment in post.comment_set.all %}

      <a href=onclick="get_delete({{comment.id}})">delete</a>

    {% endfor %}

Here is the javascript function you call:

function get_delete(n){

var patch = '{% url "comment_delete" %}'
var post_data = {
  'csrfmiddlewaretoken':"{{ csrf_token }}",
 'iddy':n,}

$.ajax({
  type: "POST",
  url: patch,
  data:post_data,
  datatype:'json',
success: function(data){
console.log(data)
return
}

})}

change your url path to.

path('post/commentdelete',views.comment_delete, name='comment_delete')

finally, in views

def comment_delete(request):
    if request.POST:
        response_json = request.POST
        response_json = json.dumps(response_json)
        data = json.loads(response_json)
        comment = get_object_or_404(Comment, id=data['iddy'])
        if comment.author != request.user:
            msg = "you didnt write this comment"
            data = {'msg':msg}
        else:
             comment.delete()
             msg = "deleted"
             data = {'msg':msg}
   return JsonResponse(data, safe=False)


问:
Changing application language
I'm trying to change my application language in runtime. I have checked several posts and my code now looks like:

```<code>if(position == 0){//Position 0 of an array to select the language
  val locale = Locale("es_ES")
  val config = applicationContext.resources.configuration
  config.setLocale(locale)
  applicationContext.createConfigurationContext(config)
}
</code>```

I have a values-es directory where I have my own strings.xml file with strings translated. Anyway, it seems like it doesn't change anything.

I repeat I tried and checked a lot of posts in Stack Overflow but I don't know where I'm failing.
Thanks in advance, I'm open to any question due to my bad english.

Second try:

I've been tryng and now my code looks like this:

```<code>val locale = Locale("es")
Locale.setDefault(locale)
val config = applicationContext.resources.configuration
config.setLocale(locale)
applicationContext.resources.configuration.setTo(config)
Log.d("Configuration",config.toString())
Log.d("Language",config.locales.toLanguageTags())
</code>```

And the debug messages are :

```<code>D/Configuration: {1.0 310mcc260mnc [es] ldltr sw411dp w683dp h387dp 420dpi nrml land finger qwerty/v/v -nav/h winConfig={ mBounds=Rect(0, 0 - 1794, 1080) mAppBounds=Rect(0, 0 - 1794, 1080) mWindowingMode=fullscreen mActivityType=undefined} s.40}

D/Language: es
</code>```

But my strings doesn't change and my app keeps using the strings(en) file.

答:
Please try this code</p>

```<code>String languageToLoad = "es"; // your language
                Locale locale = new Locale(languageToLoad);
                Locale.setDefault(locale);
                Configuration config = new Configuration();
                config.locale = locale;
                getBaseContext().getResources().updateConfiguration(config,
                        getBaseContext().getResources().getDisplayMetrics());

                Intent refresh = new Intent(DashboardActivity.this, DashboardActivity.class);
                startActivity(refresh);
                finish();
</code>```

Title: Changing application language

Body:
I'm trying to change my application language in runtime. I have checked several posts and my code now looks like:

if(position == 0){//Position 0 of an array to select the language
  val locale = Locale("es_ES")
  val config = applicationContext.resources.configuration
  config.setLocale(locale)
  applicationContext.createConfigurationContext(config)
}

I have a values-es directory where I have my own strings.xml file with strings translated. Anyway, it seems like it doesn't change anything.

I repeat I tried and checked a lot of posts in Stack Overflow but I don't know where I'm failing.
Thanks in advance, I'm open to any question due to my bad english.

Second try:

I've been tryng and now my code looks like this:

val locale = Locale("es")
Locale.setDefault(locale)
val config = applicationContext.resources.configuration
config.setLocale(locale)
applicationContext.resources.configuration.setTo(config)
Log.d("Configuration",config.toString())
Log.d("Language",config.locales.toLanguageTags())

And the debug messages are :

D/Configuration: {1.0 310mcc260mnc [es] ldltr sw411dp w683dp h387dp 420dpi nrml land finger qwerty/v/v -nav/h winConfig={ mBounds=Rect(0, 0 - 1794, 1080) mAppBounds=Rect(0, 0 - 1794, 1080) mWindowingMode=fullscreen mActivityType=undefined} s.40}

D/Language: es

But my strings doesn't change and my app keeps using the strings(en) file.

Body:
Please try this code

String languageToLoad = "es"; // your language
                Locale locale = new Locale(languageToLoad);
                Locale.setDefault(locale);
                Configuration config = new Configuration();
                config.locale = locale;
                getBaseContext().getResources().updateConfiguration(config,
                        getBaseContext().getResources().getDisplayMetrics());

                Intent refresh = new Intent(DashboardActivity.this, DashboardActivity.class);
                startActivity(refresh);
                finish();