问:
Azure Application Insights to track time spent by user on webpage
How can I use Azure Application Insights to track time spent by a user on webpage. In the javascript of the webpage, there is a chunk of code from application insights which we have to copy. I want to understand what

```<code> r=["Event","Exception","Metric","PageView","Trace","Dependency"]
</code>```

means...Are there more parameters we can add to track some other stuff. Like if I wanted to track how long a user was on a webpage, how would I track that?

答:
This functionality is built into the JavaScript SDK.

By setting autoTrackPageVisitTime: true, the time a user spends on each page is tracked. On each new PageView, the duration the user spent on the previous page is sent as a custom metric named PageVisitTime. This custom metric is viewable in the Metrics Explorer as a "log-based metric".

You can find the documentation for it here.

You pass the autoTrackPageVisitTime preference in the configuration object when creating your application insights instance.

const appInsights = new ApplicationInsights({ config: {
  connectionString: 'YOUR_CONNECTION_STRING_GOES_HERE',
  autoTrackPageVisitTime: true,
  /* ...Other Configuration Options... */
} });
```

Body:
How can I use Azure Application Insights to track time spent by a user on webpage. In the javascript of the webpage, there is a chunk of code from application insights which we have to copy. I want to understand what

 r=["Event","Exception","Metric","PageView","Trace","Dependency"]

means...Are there more parameters we can add to track some other stuff. Like if I wanted to track how long a user was on a webpage, how would I track that?


来源: stackexchange

问:
Running node apps with CodeDeploy
I am using Codeship as my CI tool, I integrate it with AWS CodeDeploy service. The procedure is perfect until my appspec.yml file calls my script to run the node app. Even though I have npm, node, bower and grunt installed I get command not found errors.

答:
Perform the below steps:

which node

sudo ln -s /home/ubuntu/.nvm/versions/node/v12.13.1/bin/node (output of above step) /usr/bin/node

which npm

sudo ln -s /home/ubuntu/.nvm/versions/node/v12.13.1/bin/npm (output of above step) /usr/bin/npm

and try to use it via /usr/bin/npm install

I hope this will help you!!

ContentLicense: CC BY-SA 3.0

Title: Running node apps with CodeDeploy

ContentLicense: CC BY-SA 4.0


问:
How to understand that file was uploaded with Selenium and Ruby?
I am writing my first automatization script with Selenium + Ruby and I need to upload a file to the web application.
The thing is that uploading takes some time (from 30sec to 3min, it depends). After the file was uploaded, I need to click "Save" button.

How could my code recognize that the uploading process was completed and it can continue to execute?

Here is the standard code, just for your reference:

```<code>driver = Selenium::WebDriver.for :chrome
driver.navigate.to 'my-website.com/upload'

driver.find_element(id: 'upload-input').send_keys('my/path/to/the/document')
driver.find_element(id: 'upload-button').click

**Now my code needs to wait till upload will be completed and then to click "Save" button**

driver.find_element(id: 'save-button').click
</code>```

Thank you!

答:
First, don't over use Capybara/Selenium, even if they are cool and can add some value to your project, they are the more brittle, capricious and slower part of any TDD suite and it never should be more than 10% of all your tests. Using it for testing the upload of a file is clearly an anti-pattern.

Use a request rspec and a javascript TDD lib (Jest/Enzyme) to test the new functionality instead. The current tread to test everything with Capybara/Selenium is insane.

Body:
I am writing my first automatization script with Selenium + Ruby and I need to upload a file to the web application.
The thing is that uploading takes some time (from 30sec to 3min, it depends). After the file was uploaded, I need to click "Save" button.

How could my code recognize that the uploading process was completed and it can continue to execute?

Here is the standard code, just for your reference:

driver = Selenium::WebDriver.for :chrome
driver.navigate.to 'my-website.com/upload'

driver.find_element(id: 'upload-input').send_keys('my/path/to/the/document')
driver.find_element(id: 'upload-button').click

**Now my code needs to wait till upload will be completed and then to click "Save" button**

driver.find_element(id: 'save-button').click

Thank you!


问:
How to optimize fine-tuned BERT's model size in TensorFlow 2.0?
After fine tuning BERT for classification the model size is ~1.3GB while the pre-trained model size was ~400MB. This happens due to additional variables related to Adam saved with the model and can be removed when saving, as explained in https://github.com/google-research/bert/issues/99 for TensorFlow 1.x.

How to do this in TensorFlow 2.x?

答: Found the solution. save() method of trained model has as an argument include_optimizer which is True by default. Setting it to False doesn't save optimizer's state and saved model file is comparable to the pre-trained file.


问:
Should I use jquery or jquery mobile or iPad web pages?
I am making a web page "app" for the iPad or ios devices.  Should I use jquery mobile or just regular jquery?  After all they're only web pages aren't they?  Is jquery proper no good for me?  Do I need mobile jquery?

Thanks.

答:
While jQuery Mobile has the 'jQuery' tag in it, it feels quite a lot different to me than 'normal' jQuery.
What jQuery Mobile helps you with is setting up pages for mobile devices easily (with html data-attributes) and handling the touch and swipe events for you. You write the mark-up, and jQuery Mobile turns it into a mobile webpage. That's something 'normal' jQuery won't do for you. You do need it if you wish to use jQuery for mobile development.

It's still in alpha and has quite some little bugs and annoyances, but I would still recommend it. It's good enough to use for production settings if you manage to work out these little annoyances.

Good luck!


问:
ReactJS app deployed to firebase hosting not updating after first deployment
hope you all are doing well and staying safe.

I have been trying to deploy my react app to the net using firebase, and all was going well until i tried updating it/redeploying it. It shows ✔  Deploy complete! in my terminal but i check the website, it shows no update. I have tried putting the following code into firebase.json:

```<code>"headers": [
      {
        "source": "/service-worker.js",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "no-cache"
          }
        ]
      }
    ]
</code>```

But that didn't change anything. My steps to release the app have been the following:

```<code>npx create-react-app firebase-test
cd firebase-test
firebase login
firebase init #I only chose hosting, chose to configure as a single-page application, wrote build as my public folder
npm run build
firebase deploy
</code>```

It shows the first deployment, but when I try to deploy again, I see no updates.

答:
Your service-worker.js is probably still cached, since you added the Cache-Control header after you first visited the site.

This means that your browser hasn't tried to request the file again, but serves it from memory. Even a standard refresh (CTRL/CMD + R) won't help.

Try a hard refresh (CTRL+Shift + R), or clear the application's cache manually in your developer tools. Your browser will re-download service-worker.js with the correct Cache-Control header, and the problem won't occur again.

And, as always, make sure you actually build your app before deploying :)

Body:
hope you all are doing well and staying safe.

I have been trying to deploy my react app to the net using firebase, and all was going well until i tried updating it/redeploying it. It shows ✔  Deploy complete! in my terminal but i check the website, it shows no update. I have tried putting the following code into firebase.json:

"headers": [
      {
        "source": "/service-worker.js",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "no-cache"
          }
        ]
      }
    ]

But that didn't change anything. My steps to release the app have been the following:

npx create-react-app firebase-test
cd firebase-test
firebase login
firebase init #I only chose hosting, chose to configure as a single-page application, wrote build as my public folder
npm run build
firebase deploy

It shows the first deployment, but when I try to deploy again, I see no updates.


问:
System.ArgumentNullException: 'Value canot be null.'
I receive the System.ArgumentNullException: 'Value cannot be null.' error when implementing search in Asp.net MVC.

```<code>public static Collection<Video> vList = VideoRepository.GetCollection();
List<Video> listofvideos = new List<Video>
public ActionResult Index(string item)
{
  foreach (Video movie in vList)
  {
    if (movie.Title.ToLower().Contains(item))
    {
     listofvideos.add(movie);
    }
  }
 return view(listofvideos);
}
</code>```

答:
it appears your listOfVideos isn't being instaniated correctly.

```<code>List<Video> listofvideos = new List<Video>
</code>```

should be

```<code>List<Video> listofvideos = new List<Video>();
</code>```

Body:
I receive the System.ArgumentNullException: 'Value cannot be null.' error when implementing search in Asp.net MVC.

public static Collection<Video> vList = VideoRepository.GetCollection();
List<Video> listofvideos = new List<Video>
public ActionResult Index(string item)
{
  foreach (Video movie in vList)
  {
    if (movie.Title.ToLower().Contains(item))
    {
     listofvideos.add(movie);
    }
  }
 return view(listofvideos);
}

Body:
it appears your listOfVideos isn't being instaniated correctly.

List<Video> listofvideos = new List<Video>

should be

List<Video> listofvideos = new List<Video>();


问:
Optimal path through a matrix with multiple costs to consider
For example given the below matrix:

```<code>[[[0, 8], [0, 3], [0, 8]],
 [[8, 0], [3, 0], [0, 5]],
 [[0, 1], [0, 6], [0, 0]]]
</code>```

where for each tuple the first number is food and the second number is water. I need to get from the bottom right to the top left and I can only move up or left.

I need to gather as much food and water as possible so I can survive as long as possible. For each day I want to survive I need 1 food and 1 water so if I could choose between a path that would result in (7,4) and one that would result in (6,6) the correct choice is (6,6) as that will allow me to live for 6 days.

How does one go about finding the best path through said matrix?

My current code is below however it does not work(it finds a very high cost path but not the highest) and I have no idea how to go about it. I have no idea how to begin implementing it, though I have been told to avoid recursion.

```<code>def maxSuppliesPath(matrix):
n = len(matrix) - 1
bestPath = matrix

# Initialize first column of bestPath array
for i in range(1, n + 1):
    if bestPath[i][0] == 0:
        bestPath[i][0] = bestPath[i - 1][0]
    else:
        bestPath[i][0] = (bestPath[i][0][0] + bestPath[i - 1][0][0], bestPath[i][0][1] + bestPath[i - 1][0][1])

# Initialize first row of bestPath array
for j in range(1, n + 1):
    if bestPath[0][j] == 0:
        bestPath[0][j] = bestPath[0][j - 1]
    else:
        bestPath[0][j] = (bestPath[0][j - 1][0] + bestPath[0][j][0], bestPath[0][j - 1][1] + bestPath[0][j][1])

# Construct rest of the bestPath array
for i in range(1, n + 1):
    for j in range(1, n + 1):
        if min(bestPath[i][j - 1][0] + bestPath[i][j][0], bestPath[i][j - 1][1] + bestPath[i][j][1]) > min(
                bestPath[i - 1][j][0] + bestPath[i][j][0], bestPath[i - 1][j][1] + bestPath[i][j][1]):
            bestPath[i][j] = (bestPath[i][j - 1][0] + bestPath[i][j][0], bestPath[i][j - 1][1] + bestPath[i][j][1])
        else:
            bestPath[i][j] = (bestPath[i - 1][j][0] + bestPath[i][j][0], bestPath[i - 1][j][1] + bestPath[i][j][1])

return min(bestPath[n][n][0], bestPath[n][n][1])
</code>```

答:
The first step in solving the problem is to understand how to traverse the matrix. The image below shows the distance from the starting point to each other point.

Notice that equidistant points are arranged on a diagonal. Given a set (call it A) that represents one diagonal, the points on the next diagonal (call it B) are found as follows:

```<code>for each point in set A
    if the x coordinate is greater than zero
        add (x-1, y) to set B
    if the y coordinate is greater than zero
        add (x, y-1) to set B
</code>```

In the example, the sets representing the diagonals should look like this:

```<code>[(2, 2)]                  // starting position
[(1, 2), (2, 1)]          // after 1 move
[(2, 0), (1, 1), (0, 2)]  // after 2 moves
[(0, 1), (1, 0)]          // after 3 moves
[(0, 0)]                  // after 4 moves
</code>```

The image below shows how many different paths can be used to reach each point in the matrix. The number of paths is the same as the numbers in Pascal's triangle. For the purposes of this question, the only thing that matters is that the numbers grow quickly, so we need to reduce the count.

To reduce the path count, we need to cull non-productive paths as we traverse the matrix. This is accomplished by comparing tuples, where each tuple consists of food and water. A tuple (F,W) dominates a tuple (f,w) iff F >= f AND W >= w.

For example, consider the center position in the matrix. We can reach that point either by moving up-then-left, or by moving left-then-up. Moving up-then-left yields (food, water) of (3,5), whereas moving left-then-up yields (3,6). (3,6) dominates (3,5), so we only need to consider (3,6). So after two moves, we have the situation shown below. Note that we only have 1 tuple in the center position, rather than the two that Pascal's triangle would predict.

After three moves, we have the situation shown below. We have two tuples for each point on the third diagonal. That's necessary because one of the tuples has more food and the other has more water, so neither dominates the other.

After four moves, we have four possible answers, and choosing the best is a simple matter of comparing min(food, water) for each of the tuples.

Body:
For example given the below matrix:

[[[0, 8], [0, 3], [0, 8]],
 [[8, 0], [3, 0], [0, 5]],
 [[0, 1], [0, 6], [0, 0]]]

where for each tuple the first number is food and the second number is water. I need to get from the bottom right to the top left and I can only move up or left.

I need to gather as much food and water as possible so I can survive as long as possible. For each day I want to survive I need 1 food and 1 water so if I could choose between a path that would result in (7,4) and one that would result in (6,6) the correct choice is (6,6) as that will allow me to live for 6 days.

How does one go about finding the best path through said matrix?

My current code is below however it does not work(it finds a very high cost path but not the highest) and I have no idea how to go about it. I have no idea how to begin implementing it, though I have been told to avoid recursion.

def maxSuppliesPath(matrix):
n = len(matrix) - 1
bestPath = matrix

# Initialize first column of bestPath array
for i in range(1, n + 1):
    if bestPath[i][0] == 0:
        bestPath[i][0] = bestPath[i - 1][0]
    else:
        bestPath[i][0] = (bestPath[i][0][0] + bestPath[i - 1][0][0], bestPath[i][0][1] + bestPath[i - 1][0][1])

# Initialize first row of bestPath array
for j in range(1, n + 1):
    if bestPath[0][j] == 0:
        bestPath[0][j] = bestPath[0][j - 1]
    else:
        bestPath[0][j] = (bestPath[0][j - 1][0] + bestPath[0][j][0], bestPath[0][j - 1][1] + bestPath[0][j][1])

# Construct rest of the bestPath array
for i in range(1, n + 1):
    for j in range(1, n + 1):
        if min(bestPath[i][j - 1][0] + bestPath[i][j][0], bestPath[i][j - 1][1] + bestPath[i][j][1]) > min(
                bestPath[i - 1][j][0] + bestPath[i][j][0], bestPath[i - 1][j][1] + bestPath[i][j][1]):
            bestPath[i][j] = (bestPath[i][j - 1][0] + bestPath[i][j][0], bestPath[i][j - 1][1] + bestPath[i][j][1])
        else:
            bestPath[i][j] = (bestPath[i - 1][j][0] + bestPath[i][j][0], bestPath[i - 1][j][1] + bestPath[i][j][1])

return min(bestPath[n][n][0], bestPath[n][n][1])

Body:
The first step in solving the problem is to understand how to traverse the matrix. The image below shows the distance from the starting point to each other point.

Notice that equidistant points are arranged on a diagonal. Given a set (call it A) that represents one diagonal, the points on the next diagonal (call it B) are found as follows:

for each point in set A
    if the x coordinate is greater than zero
        add (x-1, y) to set B
    if the y coordinate is greater than zero
        add (x, y-1) to set B

In the example, the sets representing the diagonals should look like this:

[(2, 2)]                  // starting position
[(1, 2), (2, 1)]          // after 1 move
[(2, 0), (1, 1), (0, 2)]  // after 2 moves
[(0, 1), (1, 0)]          // after 3 moves
[(0, 0)]                  // after 4 moves

The image below shows how many different paths can be used to reach each point in the matrix. The number of paths is the same as the numbers in Pascal's triangle. For the purposes of this question, the only thing that matters is that the numbers grow quickly, so we need to reduce the count.

To reduce the path count, we need to cull non-productive paths as we traverse the matrix. This is accomplished by comparing tuples, where each tuple consists of food and water. A tuple (F,W) dominates a tuple (f,w) iff F >= f AND W >= w.

For example, consider the center position in the matrix. We can reach that point either by moving up-then-left, or by moving left-then-up. Moving up-then-left yields (food, water) of (3,5), whereas moving left-then-up yields (3,6). (3,6) dominates (3,5), so we only need to consider (3,6). So after two moves, we have the situation shown below. Note that we only have 1 tuple in the center position, rather than the two that Pascal's triangle would predict.

After three moves, we have the situation shown below. We have two tuples for each point on the third diagonal. That's necessary because one of the tuples has more food and the other has more water, so neither dominates the other.

After four moves, we have four possible answers, and choosing the best is a simple matter of comparing min(food, water) for each of the tuples.


Title: How to create a list from a string

Body:
I have the following question;

Given this string:

(-9.1801505 38.7320159, -9.1800081 38.7316384, -9.1760106 38.7280334, -9.175614100000001 38.7277934, -9.174941499999999 38.7276969, -9.174286 38.7273452, -9.1739754 38.7269114, -9.173853299999999 38.7266373, -9.173908000000001 38.726382, -9.174462200000001 38.725427, -9.174693700000001 38.7252121, -9.1753494 38.7249695, -9.1772258 38.724483, -9.177979300000001 38.7241841, -9.1781305 38.7240326, -9.178122200000001 38.7237591, -9.174915199999999 38.7229978, -9.172651999999999 38.7224599, -9.1716237 38.7223014, -9.170840099999999 38.7223315, -9.1661269 38.7232445, -9.1631047 38.7238009, -9.1621644 38.7239822, -9.1611914 38.7241708, -9.161030500000001 38.7242016, -9.1606402 38.7242798, -9.1605509 38.7242976, -9.1597224 38.7244719, -9.1588452 38.7246248, -9.1574752 38.7248025, -9.1563748 38.7248708, -9.157024399999999 38.7252864, -9.160008299999999 38.7284055, -9.158204400000001 38.7296856, -9.1554751 38.7316224, -9.158455399999999 38.7338999, -9.159123599999999 38.7336254, -9.159243399999999 38.733823, -9.1590688 38.734304, -9.1587736 38.7343032, -9.1585287 38.7344595, -9.1584726 38.7346586, -9.158265099999999 38.7346166, -9.157652300000001 38.7361352, -9.1579041 38.7362527, -9.1576316 38.7366198, -9.1577363 38.7366731, -9.1574563 38.7371094, -9.1564187 38.737462, -9.157724699999999 38.7388573, -9.1598056 38.7379811, -9.1602277 38.73791, -9.165917800000001 38.738966, -9.166425500000001 38.7392131, -9.167036400000001 38.7396749, -9.168542199999999 38.7416702, -9.169788499999999 38.740959, -9.170749499999999 38.7402073, -9.171019899999999 38.7398203, -9.1712919 38.7392233, -9.1716798 38.7391685, -9.1719215 38.7391826, -9.172312700000001 38.7392701, -9.1727472 38.7394396, -9.1738649 38.7388609, -9.174271299999999 38.7365449, -9.174486099999999 38.7343981, -9.1743024 38.734297, -9.174186000000001 38.7341419, -9.1741347 38.7338797, -9.174625199999999 38.7332609, -9.1749603 38.7329354, -9.175330799999999 38.7327162, -9.1756046 38.7326312, -9.176090200000001 38.7325687, -9.1776274 38.7328163, -9.177988300000001 38.7328404, -9.178248099999999 38.7328097, -9.1799505 38.7322568, -9.1801505 38.7320159)

How can I turn it into a list of lists?

For instance this string:(-9.1801505 38.7320159, -9.1800081 38.7316384, -9.1760106 38.7280334) would become this:

[[-9.1801505, 38.7320159], [-9.1800081, 38.7316384], [-9.1760106, 38.7280334]]

Body:
You could use a regular expression to find all the pairs, then convert them into a list of lists of floats:

import re

string = '(-9.1801505 38.7320159, -9.1800081 38.7316384, -9.1760106 38.7280334)'

print([list(map(float, match)) for match in re.findall(r'(-?\d+\.\d+) (-?\d+\.\d+)', string)])

Output:

[[-9.1801505, 38.7320159], [-9.1800081, 38.7316384], [-9.1760106, 38.7280334]]


问:
how to remove index.php from codeigniter URL

Possible Duplicate:

  how to remove index.php from url in codeigniter ?

I want to remove index.php from the codeigniter url. I have created .htaccess file and placed the following code on it (as found on the CodeIgniter website. But i can not access anything on the localhost. I get the error "Not Found", if i place the code in the .htaccessfile.

```<code>RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
</code>```

My url looks like localhost/test/project/index.php

答: If you have tried everything in the user guide and had no luck it may be an issue with your local setup. If you are on a Mac there may be an issue with your Apache setup.  I would check /etc/apache2/[username].conf and make sure that you have AllowOverride set to All.

Body:
Possible Duplicate:

  how to remove index.php from url in codeigniter ?

I want to remove index.php from the codeigniter url. I have created .htaccess file and placed the following code on it (as found on the CodeIgniter website. But i can not access anything on the localhost. I get the error "Not Found", if i place the code in the .htaccessfile.

RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

My url looks like localhost/test/project/index.php


问:
Rank function in Big Query
I have below data in a big query table

```<code>col1    col2
abc 3/22/2020
abc 3/4/2020
xyz 3/22/2020
xyz 3/4/2020
</code>```

I am trying to get below output.

```<code>col1    col2
abc 3/22/2020
xyz 3/22/2020
</code>```

For this I have tried using the rank() OVER Partition clause, but no luck. Please advise.

```<code>select * from (select col1, col2 RANK() over (partition by col1, col2 order by col1, col2 desc) as r1 from table1) temp
where temp.r1 = 1
</code>```

答:
I mean, I don't know if this is a good practice but I've done this several times.</p>

```<code>select col1, MIN(PARSE_DATE('%m-%d-%Y', col2))
group by col1
</code>```

Title: Rank function in Big Query

Body:
I have below data in a big query table

col1    col2
abc 3/22/2020
abc 3/4/2020
xyz 3/22/2020
xyz 3/4/2020

I am trying to get below output.

col1    col2
abc 3/22/2020
xyz 3/22/2020

For this I have tried using the rank() OVER Partition clause, but no luck. Please advise.

select * from (select col1, col2 RANK() over (partition by col1, col2 order by col1, col2 desc) as r1 from table1) temp
where temp.r1 = 1

Body:
I mean, I don't know if this is a good practice but I've done this several times.

select col1, MIN(PARSE_DATE('%m-%d-%Y', col2))
group by col1


问:
make a record by slug
I have a model which has a slug, but when trying to register it does not allow it, generating the following error not null constraint failed: commentaries_commentarie.post_id.

this is model:

```<code>class Commentarie(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    commentarie = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
</code>```

this is urls:

```<code>urlpatterns = [
    path('<slug:slug>/', views.CommentarieCreateView.as_view(), name='add_commentarie'),
]
</code>```

this is view:

```<code>class CommentarieCreateView(CreateView):
    template_name = 'commentaries/commentarie.html'
    model = Commentarie
    form_class = CommentarieForm

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return redirect('posts:post')
</code>```

also try to create the relation, getting directly by the kwarg but it generates an error, because it turns out that it is waiting for a pk object, and it slug it is generated correctly

答:
Your post property in Commentarie cannot be null in the database. You need to either provide a value or allow it to be null.

To set the post object you can do something like this...

class CommentarieCreateView(CreateView):
    template_name = 'commentaries/commentarie.html'
    model = Commentarie
    form_class = CommentarieForm

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.post = # A Post object
        self.object.save()
        return redirect('posts:post')
```

<p>To allow it to be null change it to...</p>

<pre class="lang-py prettyprint-override"><code>class Commentarie(models.Model):
    ...
    post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True)
    ...
</code>```

Once you change it you will need to run your database migration again.

Title: make a record by slug

Body:
I have a model which has a slug, but when trying to register it does not allow it, generating the following error not null constraint failed: commentaries_commentarie.post_id.

this is model:

class Commentarie(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    commentarie = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

this is urls:

urlpatterns = [
    path('<slug:slug>/', views.CommentarieCreateView.as_view(), name='add_commentarie'),
]

this is view:

class CommentarieCreateView(CreateView):
    template_name = 'commentaries/commentarie.html'
    model = Commentarie
    form_class = CommentarieForm

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return redirect('posts:post')

also try to create the relation, getting directly by the kwarg but it generates an error, because it turns out that it is waiting for a pk object, and it slug it is generated correctly

Body:
Your post property in Commentarie cannot be null in the database. You need to either provide a value or allow it to be null.

To set the post object you can do something like this...

class CommentarieCreateView(CreateView):
    template_name = 'commentaries/commentarie.html'
    model = Commentarie
    form_class = CommentarieForm

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.post = # A Post object
        self.object.save()
        return redirect('posts:post')

To allow it to be null change it to...

class Commentarie(models.Model):
    ...
    post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True)
    ...

Once you change it you will need to run your database migration again.


问:
PHP MySQL insert values from multiple checkboxes into one column in table
I have a form that a user would fill out while creating a ticket for a bug they have found on our website.  In the form there is currently an input field where the user would enter in the designs that the bug is affecting (ex., "Design1, Design2, Design3, Design4" ...etc).  When the form is submitted the value is stored in a table column named affectedDesigns.

What i am wanting to do is create several checkboxes (one check box for each design we have) that a user would select instead of using the input field.  They would be able to select all that apply.  If possible i would still like to store all of the values into the affectedDesigns column in one record.  I'm thinking that i can gather the selected checkboxes values and create an array or some comma delimited value that contains all of the selected items and submit that to the databasein the one record in the affectedDesigns column.  How can i achieve this?

Also, how would i then pull that data and re-populate the checkboxes if they would like to go back later and edit the ticket?  Thanks for any help!

答: I would avoid to store all values within a single field. You'll have a lot of problems once you'll have to do some query because you violate normalization rules.</p>


问:
Can't control the position of .appendChild() after .cloneNode()
First things first, sorry but the code just won't run in a snippet. Neither codepan, or jsfiddle. I'm still uploading it here, but try maybe to run it locally. I'm using Angular CLI project in WebStorm.

What I want to do in my app is to create something like to-do list. When clicking on "Create a New List" a new rectangle (to-do card) should be created, right next to it. Not below it, not on top, but on it's right.

I did .cloneNode() and .appendChild(). It does the trick, but my problem is that I can't control the positioning of the result of .appenChild(). It always inserts the new to-do card below the existing one.

Please, someone bring peace to my mind!!

import { Component } from '@angular/core'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'ShoppingList'; // application name
  products = []; // array declaration
  itemToAdd;
  itemToRemove;

  /* --- adds an item in the array --- */
  addNewItem () {
    if (this.itemToAdd !== null) {
      this.products.push(this.itemToAdd)
    }
  }

  /* --- removes all items from array --- */
  removeItem () {
    const index = this.products.indexOf(this.itemToRemove)
    if (index > -1) {
      this.products.splice(index)
    }
  }

  /* --- creates new list  --- */
  createNewList () {
    const elementToClone = document.getElementById('listCard')
    const clone = elementToClone.cloneNode(true)
    document.getElementById('mainContent').appendChild(clone)
    console.log(this.products)
    console.log(clone)
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.mainContent {
  display: flex;
  flex-direction: column;
  align-items: center;
  border: 1px solid black;
}

ul {
  list-style: none none;
  margin-left: 0;
  padding-left: 0;
}

.listCard {
  width: 200px;
  height: 300px;
  border: 1px solid black;
  border-radius: 5px;
  margin: 20px;
}

.listTextAndButtons {
  display: flex;
  flex-direction: column;
  border: 1px solid black;
  padding: 5px;
  margin: 0 20px 20px 20px;
}

.textAreas {
  display: flex;
}

.addRemoveButtons {
  display: flex;
  align-items: center;
  justify-content: center;
}

.createNewListButton {
  display: flex;
  justify-content: center;
}

textarea {
  margin: 5px;
  border: 1px solid #767676;
  border-radius: 4px;
}

button {
  margin: 5px;
  width: 70%;
  height: 30px;
  border: 1px solid #767676;
  border-radius: 4px;
}</code>```

<!doctype html>

  <meta charset="utf-8">
  <title>ShoppingList</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon">

      <textarea [(ngModel)]="itemToAdd"></textarea>
      <textarea [(ngModel)]="itemToRemove"></textarea>

      <button (click)="addNewItem()">Add New Item!</button>
      <button (click)="removeItem()">Remove an Item!</button>

      <button (click)="createNewList()">Create a New List!</button>

```

答:
Here, I created a stackblitz, take a look. I removed the

```<code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</code>```

from HTML template as you are obviously on angular 2+

Regarding the flexbox I gave listCard a max-width property and set flex-wrap: wrap on .listTextArea , the direction is row by default so new items will be added to the right until they reach max-width and then wrap onto a new line. I always refer to this CSS Tricks article when it comes to flexbox

```<code>.listCard {
    max-width: 600px;
    border: 1px solid black;
    margin-bottom: 15px;
}

.listTextArea {
  display: flex;
  flex-wrap: wrap;
}
</code>```

Also, I'd recommend to follow the same pattern for lists as I did with items inside list e.g. instead of cloning and appending new node keep lists in an array and loop thru it with *ngFor

```<code><div class="listCard" *ngFor="let list of todoLists">
</code>```

Body:
First things first, sorry but the code just won't run in a snippet. Neither codepan, or jsfiddle. I'm still uploading it here, but try maybe to run it locally. I'm using Angular CLI project in WebStorm.

What I want to do in my app is to create something like to-do list. When clicking on "Create a New List" a new rectangle (to-do card) should be created, right next to it. Not below it, not on top, but on it's right.

I did .cloneNode() and .appendChild(). It does the trick, but my problem is that I can't control the positioning of the result of .appenChild(). It always inserts the new to-do card below the existing one.

Please, someone bring peace to my mind!!

import { Component } from '@angular/core'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'ShoppingList'; // application name
  products = []; // array declaration
  itemToAdd;
  itemToRemove;

  /* --- adds an item in the array --- */
  addNewItem () {
    if (this.itemToAdd !== null) {
      this.products.push(this.itemToAdd)
    }
  }

  /* --- removes all items from array --- */
  removeItem () {
    const index = this.products.indexOf(this.itemToRemove)
    if (index > -1) {
      this.products.splice(index)
    }
  }

  /* --- creates new list  --- */
  createNewList () {
    const elementToClone = document.getElementById('listCard')
    const clone = elementToClone.cloneNode(true)
    document.getElementById('mainContent').appendChild(clone)
    console.log(this.products)
    console.log(clone)
  }
}

.mainContent {
  display: flex;
  flex-direction: column;
  align-items: center;
  border: 1px solid black;
}

ul {
  list-style: none none;
  margin-left: 0;
  padding-left: 0;
}

.listCard {
  width: 200px;
  height: 300px;
  border: 1px solid black;
  border-radius: 5px;
  margin: 20px;
}

.listTextAndButtons {
  display: flex;
  flex-direction: column;
  border: 1px solid black;
  padding: 5px;
  margin: 0 20px 20px 20px;
}

.textAreas {
  display: flex;
}

.addRemoveButtons {
  display: flex;
  align-items: center;
  justify-content: center;
}

.createNewListButton {
  display: flex;
  justify-content: center;
}

textarea {
  margin: 5px;
  border: 1px solid #767676;
  border-radius: 4px;
}

button {
  margin: 5px;
  width: 70%;
  height: 30px;
  border: 1px solid #767676;
  border-radius: 4px;
}

<!doctype html>

  <meta charset="utf-8">
  <title>ShoppingList</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon">

      <textarea [(ngModel)]="itemToAdd"></textarea>
      <textarea [(ngModel)]="itemToRemove"></textarea>

      <button (click)="addNewItem()">Add New Item!</button>
      <button (click)="removeItem()">Remove an Item!</button>

      <button (click)="createNewList()">Create a New List!</button>

Body:
Here, I created a stackblitz, take a look. I removed the

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

from HTML template as you are obviously on angular 2+

Regarding the flexbox I gave listCard a max-width property and set flex-wrap: wrap on .listTextArea , the direction is row by default so new items will be added to the right until they reach max-width and then wrap onto a new line. I always refer to this CSS Tricks article when it comes to flexbox

.listCard {
    max-width: 600px;
    border: 1px solid black;
    margin-bottom: 15px;
}

.listTextArea {
  display: flex;
  flex-wrap: wrap;
}

Also, I'd recommend to follow the same pattern for lists as I did with items inside list e.g. instead of cloning and appending new node keep lists in an array and loop thru it with *ngFor

<div class="listCard" *ngFor="let list of todoLists">


问:
How to send key, value messages with the kafka console producer
I got a use case where I need to send key value messages with Kafka Console Producer. So how to achieve this through the Kafka Console Producer command?

答:
I found out the solution after some research and the solution is here.

kafka-console-producer command

```<code>kafka-console-producer.sh --broker-list localhost:9092 --topic topic-name --property "parse.key=true" --property "key.separator=:"
</code>```

After running this command you will enter in producer console and from there you can send key, value messages.

For example

```<code>key1:value1
key2:value2
key3:value3
</code>```

For more clarity, I am providing sample key-value message here, emp_info is a key and JSON object is a value.

```<code>emp_info: {"emp_id":100,"first_name":"Keshav","last_name":"Lodhi","designation":"DataEngineer"}
</code>```

Note: Simply sending lines of text will result in messages with null keys. In order to send messages with both keys and values you must set the parse.key and key.separator properties on the command line when running the producer.

Body:
I found out the solution after some research and the solution is here.

kafka-console-producer command

kafka-console-producer.sh --broker-list localhost:9092 --topic topic-name --property "parse.key=true" --property "key.separator=:"

After running this command you will enter in producer console and from there you can send key, value messages.

For example

key1:value1
key2:value2
key3:value3

For more clarity, I am providing sample key-value message here, emp_info is a key and JSON object is a value.

emp_info: {"emp_id":100,"first_name":"Keshav","last_name":"Lodhi","designation":"DataEngineer"}

Note: Simply sending lines of text will result in messages with null keys. In order to send messages with both keys and values you must set the parse.key and key.separator properties on the command line when running the producer.


问:
Using hex flag inside setiosflags function
```<code>int a=60;
cout<<setiosflags(ios::hex|ios::showbase|ios::uppercase);
cout<<a<<endl;
</code>```

The above code is not working but if I use

```<code>cout<<hex
</code>```

and then

```<code>cout<<setiosflags(ios::showbase|ios::uppercase)
</code>```

then it is working

Why? and how i do know which one can be used inside setiosflags() ?

答:
With the first version, you first have to clear std::ios::dec, otherwise it takes precedence:

```<code>std::cout << resetiosflags (std::ios::dec);
</code>```

You can do this in one hit by calling setf with the appropriate mask, e.g.:

```<code>std.cout.setf (std:ios.hex, std.ios.basefield);
</code>```

And as documented at cppreference, std::cout << hex does this for you.

Body:
int a=60;
cout<<setiosflags(ios::hex|ios::showbase|ios::uppercase);
cout<<a<<endl;

The above code is not working but if I use

cout<<hex

and then

cout<<setiosflags(ios::showbase|ios::uppercase)

then it is working

Why? and how i do know which one can be used inside setiosflags() ?

Body:
With the first version, you first have to clear std::ios::dec, otherwise it takes precedence:

std::cout << resetiosflags (std::ios::dec);

You can do this in one hit by calling setf with the appropriate mask, e.g.:

std.cout.setf (std:ios.hex, std.ios.basefield);

And as documented at cppreference, std::cout << hex does this for you.


问:
Need to use VFP code to display PDF files in VFP Windows
Users running my Foxpro 9.0 app generate a lot of PDF files. I need to show PDF files in a window.  I installed Google Chrome and set it as the default for PDFs and when double clicking on a PDF in file explorer it comes right up in Chrome.  I need to make that happen with Foxpro code.  Any ideas?</p>

答:
To expand on what Tamar said:</p>

```<code>declare long ShellExecute in "shell32.dll" ;
    long hwnd, string lpszOp, ;
    string lpszFile, string lpszParams, ;
    string lpszDir, long nShowCmd
ShellExecute(0,'Open','c:\MyFolder\MyFile.pdf','','',1)
</code>```

Body:
To expand on what Tamar said:

declare long ShellExecute in "shell32.dll" ;
    long hwnd, string lpszOp, ;
    string lpszFile, string lpszParams, ;
    string lpszDir, long nShowCmd
ShellExecute(0,'Open','c:\MyFolder\MyFile.pdf','','',1)


问:
Get all first element of tuples from list of lists of tuples in Python
```<code>Input:
orders = [[('Fries', 9)], [('Burger', 6), ('Milkshake', 2), ('Cola', 2)], [('Cola', 2), ('Nuggets', 3), ('Onion Rings', 5)], [('Fries', 9)], [('Big Burger', 7), ('Nuggets', 3)]]

Expected Output:
orders = [['Fries'], ['Burger', 'Milkshare', 'Cola'], ['Cola', 'Nuggets', 'Onion Rings'], ['Fries'], ['Big Burger', 'Nuggets']]
</code>```

My attempt:

```<code> for i, order in enumerate(orders):
        for j,item in enumerate(order):
            orders[i][j] = item[0]
</code>```

Works ok. But are there any more intuitive/one-liner/faster/cooler way to do this?

答: Or simply [[item[0] for item in order] for order in orders]

Body:
Input:
orders = [[('Fries', 9)], [('Burger', 6), ('Milkshake', 2), ('Cola', 2)], [('Cola', 2), ('Nuggets', 3), ('Onion Rings', 5)], [('Fries', 9)], [('Big Burger', 7), ('Nuggets', 3)]]

Expected Output:
orders = [['Fries'], ['Burger', 'Milkshare', 'Cola'], ['Cola', 'Nuggets', 'Onion Rings'], ['Fries'], ['Big Burger', 'Nuggets']]

My attempt:

 for i, order in enumerate(orders):
        for j,item in enumerate(order):
            orders[i][j] = item[0]

Works ok. But are there any more intuitive/one-liner/faster/cooler way to do this?


问:
If not Microsoft.Office.Interop.Excel then what?
Ok, I have a problem with the MSDN documentation for the namespace Microsoft.Office.Interop.Excel. It states in the documentation in MSDN that the code in this namespace is not intended to be used by ones application directly but it's code for supporting features in the .NET Framework.

Nowhere says what functionality this supports and what should we use to interact with Excel documents if not this. If you know what part of the .NET Framework they are implicitly talking about here, please, let me know. I've been searching for this for almost 4 months now.

Thanks in advance.

答: So I think they mean the actual implementation.  It doesn't say the same thing if you look at the _Application interface: http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel._application.aspx</p>


问:
Python scripts don't work without python -m
I'm extremely sorry for asking this question, but I'm absolutely clueless

I just migrated to a Mac, got python set up through brew, and everything works fine, except for the fact that I can't open up Jupyter notebooks, or access pip, without the

```<code>python3 -m pip
</code>```

or

```<code>python3 -m jupyterlab
</code>```

command

This has never happened to me before on Linux or on Windows, and I even double checked my path to make sure the python directories are included. Is it just that I have to create an alias, or am I missing something else here?

答:
what are the results of

```<code>echo $PATH
</code>```

are the directories where the pip and jupyterlab scripts are stored in that PATH

If

```<code>which pip
</code>```

or

```<code>which jupyterlab
</code>```

come back with empty results then that is probably the case.  If you used the --user switch to install anything with pip (or python3 -m pip) then that is almost always the reason.  On OSX I think the default user location is ~/Libraries/bin or /Library/python3.8/site-packages, on Linux it is always ~/.local/bin or ~/.local/python3.8/site-packages, so you may have to have a bit of rummage to find them.

Obviously change the python version to suit your situation.

Body:
I'm extremely sorry for asking this question, but I'm absolutely clueless

I just migrated to a Mac, got python set up through brew, and everything works fine, except for the fact that I can't open up Jupyter notebooks, or access pip, without the

python3 -m pip

or

python3 -m jupyterlab

command

This has never happened to me before on Linux or on Windows, and I even double checked my path to make sure the python directories are included. Is it just that I have to create an alias, or am I missing something else here?

Body:
what are the results of

echo $PATH

are the directories where the pip and jupyterlab scripts are stored in that PATH

If

which pip

or

which jupyterlab

come back with empty results then that is probably the case.  If you used the --user switch to install anything with pip (or python3 -m pip) then that is almost always the reason.  On OSX I think the default user location is ~/Libraries/bin or /Library/python3.8/site-packages, on Linux it is always ~/.local/bin or ~/.local/python3.8/site-packages, so you may have to have a bit of rummage to find them.

Obviously change the python version to suit your situation.


问:
In my compiled Livecode desktop app, the PC version saves files and folders as expected. The Mac compiled version is all wrong
In my desktop app, I have a very defined file and folder structure:

main_folder ---folder2 ------file1 ------file2 ---folder3 ------file1 ------file2 etc...

On PC, this writes fine.  I define the main folder and sub folders:

put "c:\folder1\folder2\file1" into someVariable

On Mac, I have:

put specialfolderpath("Documents") & "/folder1/folder2/file1" into someVariable

On PC, it writes the files to the folders as expected.  On the Mac, it seems to write a folder/file combo:

/folder1/folder2/file1

as a file.

For the software to work, I copy the folder/file structure to the Mac as it is on the PC.

The Mac app is not finding the existing files and is then writing new files underneath the existing folders/files as new files.

It's all very confusing and I just don't understand why it's not working as it should.

答:
It is not clear from your question exactly what you are trying to do and how you are writing files to your folder structure. If I were writing a file to your apps folder structure I would do it like this (assuming main_folder is where your standalone application resides):

```<code>put "some text" into tTextString
put specialFolderPath("resources") & "/folder1/folder2/myfile.txt" into tPath
put textEncode(tTextString,"utf8") into URL ("binfile:" & tPath)
# textEncode is needed if you want to preserve unicode characters
# in your file, and is more reliable for cross-platform file exchange
</code>```

SpecialFolderPath("resources") means the folder where your stack is saved in the development environment; in standalone environment, it is the folder where your standalone stack is located. Note that on a Mac this is inside the application bundle.

BTW this script should work for both Mac and Windows, assuming that you have write permissions to that folder. This is not a given for a compiled application, so instead of specialFolderPath("resources") you may want to use specialFolderPath("support") or specialFolderPath("documents"). SpecialFolderPath("resources") is a great place to store static assets your application needs, but is usually not appropriate for files written from your application.

Body:
It is not clear from your question exactly what you are trying to do and how you are writing files to your folder structure. If I were writing a file to your apps folder structure I would do it like this (assuming main_folder is where your standalone application resides):

put "some text" into tTextString
put specialFolderPath("resources") & "/folder1/folder2/myfile.txt" into tPath
put textEncode(tTextString,"utf8") into URL ("binfile:" & tPath)
# textEncode is needed if you want to preserve unicode characters
# in your file, and is more reliable for cross-platform file exchange

SpecialFolderPath("resources") means the folder where your stack is saved in the development environment; in standalone environment, it is the folder where your standalone stack is located. Note that on a Mac this is inside the application bundle.

BTW this script should work for both Mac and Windows, assuming that you have write permissions to that folder. This is not a given for a compiled application, so instead of specialFolderPath("resources") you may want to use specialFolderPath("support") or specialFolderPath("documents"). SpecialFolderPath("resources") is a great place to store static assets your application needs, but is usually not appropriate for files written from your application.


问:
How can I make my Bootstrap Date Picker work and is there an "official" Bootstrap 3 Date Picker?
I have a web app built with Bootstrap 3 and jQuery.  I want to add a Date Picker.  I checked the official Bootstrap 3 website here but there is no date picker under components (unless I'm missing it?).

I googled and found this one ...

https://uxsolutions.github.io/bootstrap-datepicker/?#sandbox

I tried adding this date picker to my app using their code sample but it didn't work ... no date picker pops up when I click on the widget

```<code><script>
    $('#sandbox-container .input-group.date').datepicker({
        autoclose: true,
        todayHighlight: true
    });
</script>

<div class="input-group date">
      <input type="text" class="form-control"><span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
</div>
</code>```

I figured I'm missing some imports so I added these link/script lines ... but it still doesn't work ...

```<code><!-- what I already had -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="/juliet/resources/juliet.css">

<!-- new for the Date Picker widget -->
<link id="bsdp-css" href="https://unpkg.com/bootstrap-datepicker@1.9.0/dist/css/bootstrap-datepicker3.min.css" rel="stylesheet">
<script src="https://unpkg.com/bootstrap-datepicker@1.9.0/dist/js/bootstrap-datepicker.min.js"></script>
</code>```

QUESTION:

What links/script imports am I missing?  And (other than asking here) how does a programmer go about determining what lines are missing when you're trying to add 3rd party widgets?

ALSO ...

I noticed there are a few different widgets that are called "bootstrap-datepicker" ... I guess it's a generic name.

Is there one place where I can find the "official" Bootstrap 3 date picker?  Or do you pretty much have to download different ones to find one that works for you?

Thanks for any advice because I could really use some advice!

UPDATED WITH SOLUTION:

Thanks to a pointer from commenter @RK_oo7 I figured out what was happening.

Here's is my fully working example code ...

```<code><!DOCTYPE html>
<title>Date Picker Test 3</title>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="/juliet/resources/juliet.css">
    <link id="bsdp-css" href="https://unpkg.com/bootstrap-datepicker@1.9.0/dist/css/bootstrap-datepicker3.min.css" rel="stylesheet">
    <script src="https://unpkg.com/bootstrap-datepicker@1.9.0/dist/js/bootstrap-datepicker.min.js"></script>
</head>

<script>
    $(document).ready(function() {

        $('#sandbox-container .input-group.date').datepicker({
            autoclose : true,
            todayHighlight : true
        });

    });
</script>

<body>

    <div id="sandbox-container">
        <div class="input-group date">
            <input type="text" class="form-control"><span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
        </div>
    </div>

</body>
</code>```

答:
please put your date picker jquery code inside document ready state</p>

```<code>$( document ).ready(function() {
// your picker initialization here
});
</code>```

Body:
I have a web app built with Bootstrap 3 and jQuery.  I want to add a Date Picker.  I checked the official Bootstrap 3 website here but there is no date picker under components (unless I'm missing it?).

I googled and found this one ...

https://uxsolutions.github.io/bootstrap-datepicker/?#sandbox

I tried adding this date picker to my app using their code sample but it didn't work ... no date picker pops up when I click on the widget

      <input type="text" class="form-control">

I figured I'm missing some imports so I added these link/script lines ... but it still doesn't work ...

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

<link rel="stylesheet" type="text/css" href="/juliet/resources/juliet.css">

<link id="bsdp-css" href="https://unpkg.com/bootstrap-datepicker@1.9.0/dist/css/bootstrap-datepicker3.min.css" rel="stylesheet">

QUESTION:

What links/script imports am I missing?  And (other than asking here) how does a programmer go about determining what lines are missing when you're trying to add 3rd party widgets?

ALSO ...

I noticed there are a few different widgets that are called "bootstrap-datepicker" ... I guess it's a generic name.

Is there one place where I can find the "official" Bootstrap 3 date picker?  Or do you pretty much have to download different ones to find one that works for you?

Thanks for any advice because I could really use some advice!

UPDATED WITH SOLUTION:

Thanks to a pointer from commenter @RK_oo7 I figured out what was happening.

Here's is my fully working example code ...

<!DOCTYPE html>
<title>Date Picker Test 3</title>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

    <link rel="stylesheet" type="text/css" href="/juliet/resources/juliet.css">
    <link id="bsdp-css" href="https://unpkg.com/bootstrap-datepicker@1.9.0/dist/css/bootstrap-datepicker3.min.css" rel="stylesheet">

            <input type="text" class="form-control">

Body:
please put your date picker jquery code inside document ready state

$( document ).ready(function() {
// your picker initialization here
});


问:
How to simulate key pressed event in Qml?
I'm implementing a customized virtual keyboard using QML. My purpose is simulating a physical key press signal of real keyboard when I click a button in virtual keyboard. I have followed the tutorial in Qt Virtual Keyboard and have successfully built and run the example code.

The problem is that the example code employs QCoreApplication::sendEvent() function in a C++ class to send key press event to focused QObject. It works well when I import QtQuick.Controls 1.3 in main.qml as the guide, but takes no effect when I change to QtQuick.Controls 2.2, which is essential in my application. Here is the core of the example code:

```<code>void KeyEmitter::emitKey(Qt::Key key)
{
    QQuickItem* receiver = qobject_cast<QQuickItem*>(QGuiApplication::focusObject());
    if(!receiver) {
        return;
    }
    QKeyEvent pressEvent = QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier, QKeySequence(key).toString());
    QKeyEvent releaseEvent = QKeyEvent(QEvent::KeyRelease, key, Qt::NoModifier);
    QCoreApplication::sendEvent(receiver, &pressEvent);
    QCoreApplication::sendEvent(receiver, &releaseEvent);
}
</code>```

So how can I send the key press event to my application?

答:
I think the focusObject is the actual clicked button, so sending an QKeyEvent to that instead of the TextField is pointless.

How about passing the actual receiver object's pointer instead of asking QGuiApplication for the focusObject.

Try this:

keyemitter.h file (header only, you don't need cpp file):

```<code>#ifndef KEYEMITTER_H
#define KEYEMITTER_H
#include <QObject>
#include <QCoreApplication>
#include <QKeyEvent>
class KeyEmitter : public QObject
{
    Q_OBJECT
public:
    KeyEmitter(QObject* parent=nullptr) : QObject(parent) {}
    Q_INVOKABLE void keyPressed(QObject* tf, Qt::Key k) {
        QKeyEvent keyPressEvent = QKeyEvent(QEvent::Type::KeyPress, k, Qt::NoModifier, QKeySequence(k).toString());
        QCoreApplication::sendEvent(tf, &keyPressEvent);
    }
};
#endif // KEYEMITTER_H

</code>```

main.cpp file:

```<code>#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include <QQmlContext>
#include "keyemitter.h"
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQuickView view;
    KeyEmitter keyEmitter;
    view.rootContext()->setContextProperty("keyEmitter", &keyEmitter);
    view.setSource(QStringLiteral("qrc:/main.qml"));
    view.show();
    return app.exec();
}

</code>```

main.qml file:

```<code>import QtQuick 2.12
import QtQuick.Controls 2.12
Rectangle {
    anchors.fill: parent
    color: "red"
    Column{
        Row {
            TextField {
                id: tf
                Component.onCompleted: { console.log(tf); }
                text: "123"
            }
        }
        Row {
            Button {
                text: "1"
                onClicked: keyEmitter.keyPressed(tf, Qt.Key_1)
            }
            Button {
                text: "2"
                onClicked: keyEmitter.keyPressed(tf, Qt.Key_2)
            }
            Button {
                text: "3"
                onClicked: keyEmitter.keyPressed(tf, Qt.Key_3)
            }
        }
        Row {
            Button {
                text: "DEL"
                onClicked: keyEmitter.keyPressed(tf, Qt.Key_Backspace)
            }
            Button {
                text: "OK"
                onClicked: keyEmitter.keyPressed(tf, Qt.Key_Enter)
            }
            Button {
                text: "ESC"
                onClicked: keyEmitter.keyPressed(tf, Qt.Key_Escape)
            }
        }
    }
}

</code>```

Body:
I'm implementing a customized virtual keyboard using QML. My purpose is simulating a physical key press signal of real keyboard when I click a button in virtual keyboard. I have followed the tutorial in Qt Virtual Keyboard and have successfully built and run the example code.

The problem is that the example code employs QCoreApplication::sendEvent() function in a C++ class to send key press event to focused QObject. It works well when I import QtQuick.Controls 1.3 in main.qml as the guide, but takes no effect when I change to QtQuick.Controls 2.2, which is essential in my application. Here is the core of the example code:

void KeyEmitter::emitKey(Qt::Key key)
{
    QQuickItem* receiver = qobject_cast<QQuickItem*>(QGuiApplication::focusObject());
    if(!receiver) {
        return;
    }
    QKeyEvent pressEvent = QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier, QKeySequence(key).toString());
    QKeyEvent releaseEvent = QKeyEvent(QEvent::KeyRelease, key, Qt::NoModifier);
    QCoreApplication::sendEvent(receiver, &pressEvent);
    QCoreApplication::sendEvent(receiver, &releaseEvent);
}

So how can I send the key press event to my application?

Body:
I think the focusObject is the actual clicked button, so sending an QKeyEvent to that instead of the TextField is pointless.

How about passing the actual receiver object's pointer instead of asking QGuiApplication for the focusObject.

Try this:

keyemitter.h file (header only, you don't need cpp file):

#ifndef KEYEMITTER_H
#define KEYEMITTER_H
#include <QObject>
#include <QCoreApplication>
#include <QKeyEvent>
class KeyEmitter : public QObject
{
    Q_OBJECT
public:
    KeyEmitter(QObject* parent=nullptr) : QObject(parent) {}
    Q_INVOKABLE void keyPressed(QObject* tf, Qt::Key k) {
        QKeyEvent keyPressEvent = QKeyEvent(QEvent::Type::KeyPress, k, Qt::NoModifier, QKeySequence(k).toString());
        QCoreApplication::sendEvent(tf, &keyPressEvent);
    }
};
#endif // KEYEMITTER_H

main.cpp file:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include <QQmlContext>
#include "keyemitter.h"
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQuickView view;
    KeyEmitter keyEmitter;
    view.rootContext()->setContextProperty("keyEmitter", &keyEmitter);
    view.setSource(QStringLiteral("qrc:/main.qml"));
    view.show();
    return app.exec();
}

main.qml file:

import QtQuick 2.12
import QtQuick.Controls 2.12
Rectangle {
    anchors.fill: parent
    color: "red"
    Column{
        Row {
            TextField {
                id: tf
                Component.onCompleted: { console.log(tf); }
                text: "123"
            }
        }
        Row {
            Button {
                text: "1"
                onClicked: keyEmitter.keyPressed(tf, Qt.Key_1)
            }
            Button {
                text: "2"
                onClicked: keyEmitter.keyPressed(tf, Qt.Key_2)
            }
            Button {
                text: "3"
                onClicked: keyEmitter.keyPressed(tf, Qt.Key_3)
            }
        }
        Row {
            Button {
                text: "DEL"
                onClicked: keyEmitter.keyPressed(tf, Qt.Key_Backspace)
            }
            Button {
                text: "OK"
                onClicked: keyEmitter.keyPressed(tf, Qt.Key_Enter)
            }
            Button {
                text: "ESC"
                onClicked: keyEmitter.keyPressed(tf, Qt.Key_Escape)
            }
        }
    }
}


问:
How to implement (char-ready?) in C
I'm currently implementing Scheme R5RS in C, and I am stuck trying to implement the (char-ready?) function.

I have the specs for the function quoted below. The function is guaranteed not to block. The standard C functions like fgetc() all block on input when called when there is no input ready.

Does anyone know if there is way to implement this in a nice simple way, without spawning a dedicated IO thread?

Edit:
My input stream type is a FILE*, which could be stdin or a file opened with fopen().

(char-ready?) procedure

(char-ready? port) procedure

Returns #t if a character is ready on the input port and returns #f otherwise. If char-ready returns #t then the next read-char operation on the given port is guaranteed not to hang. If the port is at end of file then char-ready? returns #t. Port may be omitted, in which case it defaults to the value returned by current-input-port.

Rationale:

Char-ready? exists to make it possible for a program to accept characters from interactive ports without getting stuck waiting for input. Any input editors associated with such ports must ensure that characters whose existence has been asserted by char-ready? cannot be rubbed out. If char-ready? were to return #f at end of file, a port at end of file would be indistinguishable from an interactive port that has no ready characters.

答:
Perhaps something like the code in this answer?  But note with ungetc "only one pushback is guaranteed".

As a side note, most serious scheme implementations end up doing their own buffered (possibly non-blocking) IO.

Title: How to implement (char-ready?) in C


答:
Here with one loop and one one liner:

```<code>l=[]
for order in orders:
    l.append([name[0] for order in orders for name in order])
l
</code>```

Output:

```<code>[['Fries'],
 ['Burger', 'Milkshake', 'Cola'],
 ['Cola', 'Nuggets', 'Onion Rings'],
 ['Fries'],
 ['Big Burger', 'Nuggets']]
</code>```

Title: Get all first element of tuples from list of lists of tuples in Python

Body:
Here with one loop and one one liner:

l=[]
for order in orders:
    l.append([name[0] for order in orders for name in order])
l

Output:

[['Fries'],
 ['Burger', 'Milkshake', 'Cola'],
 ['Cola', 'Nuggets', 'Onion Rings'],
 ['Fries'],
 ['Big Burger', 'Nuggets']]


问:
Navigation component , check if fragment exists in back stack
How can I check if a fragment exists in back stack when using navigation component ?

one thing I can think of is try to get the  NavBackStackEntry by using

```<code>val backStackEntry=findNavController().getBackStackEntry(R.id.courseTrackFeedbackFragment)
</code>```

In documentation it says this will throw IllegalArgumentException if the destination is not on the back stack . But this looks like a hack , is there a better way to do it ?

答:
Yes, it seems to be the only way for today</p>

```<code>try {
   getBackStackEntry(resId)
} catch (ignored: Throwable) {
}
</code>```

Body:
How can I check if a fragment exists in back stack when using navigation component ?

one thing I can think of is try to get the  NavBackStackEntry by using

val backStackEntry=findNavController().getBackStackEntry(R.id.courseTrackFeedbackFragment)

In documentation it says this will throw IllegalArgumentException if the destination is not on the back stack . But this looks like a hack , is there a better way to do it ?

Body:
Yes, it seems to be the only way for today

try {
   getBackStackEntry(resId)
} catch (ignored: Throwable) {
}


问:
How to ensure an array's values the keys of a typescript interface?
I am trying to produce an events property on Klass which contains an array of strings that exactly matches all the keys of a given interface. Like so:

```<code>interface Events {
    one: (foo: string) => void
    two: (bar: number) => void
}

class Klass {
    protected readonly events: [keyof Events] = ['one', 'two']
}
</code>```

However, the above errors out with the following:

```<code>[ts]
Type '["one", "two"]' is not assignable to type '["one" | "two"]'.
  Types of property 'length' are incompatible.
    Type '2' is not assignable to type '1'. [2322]
(property) Klass.events: ["one" | "two"]
</code>```

What is needed here to ensure that the events property returns an array that contains all of the events?

答:
You are putting the [] in the wrong place.

```<code>interface Events {
  one: (foo: string) => void
  two: (bar: number) => void
}

class Klass {
  protected readonly events: (keyof Events)[] = ['one', 'two']
}
</code>```

Notice how I change [keyof Events] to (keyof Events)[].

Check this typescript playground to verify that there are no errors.

Body:
I am trying to produce an events property on Klass which contains an array of strings that exactly matches all the keys of a given interface. Like so:

interface Events {
    one: (foo: string) => void
    two: (bar: number) => void
}

class Klass {
    protected readonly events: [keyof Events] = ['one', 'two']
}

However, the above errors out with the following:

[ts]
Type '["one", "two"]' is not assignable to type '["one" | "two"]'.
  Types of property 'length' are incompatible.
    Type '2' is not assignable to type '1'. [2322]
(property) Klass.events: ["one" | "two"]

What is needed here to ensure that the events property returns an array that contains all of the events?

Body:
You are putting the [] in the wrong place.

interface Events {
  one: (foo: string) => void
  two: (bar: number) => void
}

class Klass {
  protected readonly events: (keyof Events)[] = ['one', 'two']
}

Notice how I change [keyof Events] to (keyof Events)[].

Check this typescript playground to verify that there are no errors.


问:
How to navigate to a screen which has BottomNavigationBar and change a tab of BottomNavigationBar at the same time?
I want to navigate screen and change tab in bottomNavigationBar at the same time.

```<code>....

class _MainPageState extends State<MainPage> with TickerProviderStateMixin {
  ...

  Widget selectedAppBar(int index) {
    ...
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: selectedAppBar(_selectedIndex),
        body: SafeArea(
          child: _screenOptions.elementAt(_selectedIndex),
        ),
        bottomNavigationBar: BottomNavigation(
          onChangeScreen: _onChangeScreen,
          selectedIndex: _selectedIndex,
        ),
      );
  }

  ...
}

</code>```

other page, there is a bottom and when I click it so will be navigation to main screen and also change tab of BottomNavigationBar

```<code>....

class _ItemState extends State<ItemPage> {

  ItemScreenArguments _screenArguments;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    _screenArguments = ModalRoute.of(context).settings.arguments;
    final item = _screenArguments.item;

    return BlocBuilder<CartBloc, CartState>(
      builder: (BuildContext context, CartState state) {
        ...

        final cart = (state as LoadCartState);
        return Scaffold(
          extendBodyBehindAppBar: true,
          appBar: AppBar(
          backgroundColor: Colors.transparent,
            title: Text(item.name),
              actions: [
                Basket(
                  count: cart.count,
                  onTap: () {
                   // It should navigate main route and fourth section in bottomNavigationBar
                   Navigator.of(context).popUntil(ModalRoute.withName('/main'))
                  },
                )
              ]
            ),
            body: ItemScreen(),
            ...
        );
      }
    );
  }
</code>```

I try that do it is using Bloc or it's bad idea to use Bloc?

May be, using Router MaterialPageRoute better than Bloc or using them together? How to you do it? Can you help to choose better option?

答:
You could send the tab number you want to select by default

```<code>Navigate.of(context).pushNamed("/main",arguments:{'tab':3})
</code>```

You can retrieve this tab number using ModalRoute and set _selectedIndex accordingly

```<code>Widget build(BuildContext context) {
   final route= ModalRoute.of(context).settings.arguments as Map<String,int>;
   var _selectedIndex = route['tab']

    return Scaffold(
        appBar: selectedAppBar(_selectedIndex),
        body: SafeArea(
          child: _screenOptions.elementAt(_selectedIndex),
        ),
        bottomNavigationBar: BottomNavigation(
          onChangeScreen: _onChangeScreen,
          selectedIndex: _selectedIndex,
        ),
      );
  }
</code>```

Body:
I want to navigate screen and change tab in bottomNavigationBar at the same time.

....

class _MainPageState extends State<MainPage> with TickerProviderStateMixin {
  ...

  Widget selectedAppBar(int index) {
    ...
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: selectedAppBar(_selectedIndex),
        body: SafeArea(
          child: _screenOptions.elementAt(_selectedIndex),
        ),
        bottomNavigationBar: BottomNavigation(
          onChangeScreen: _onChangeScreen,
          selectedIndex: _selectedIndex,
        ),
      );
  }

  ...
}

other page, there is a bottom and when I click it so will be navigation to main screen and also change tab of BottomNavigationBar

....

class _ItemState extends State<ItemPage> {

  ItemScreenArguments _screenArguments;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    _screenArguments = ModalRoute.of(context).settings.arguments;
    final item = _screenArguments.item;

    return BlocBuilder<CartBloc, CartState>(
      builder: (BuildContext context, CartState state) {
        ...

        final cart = (state as LoadCartState);
        return Scaffold(
          extendBodyBehindAppBar: true,
          appBar: AppBar(
          backgroundColor: Colors.transparent,
            title: Text(item.name),
              actions: [
                Basket(
                  count: cart.count,
                  onTap: () {
                   // It should navigate main route and fourth section in bottomNavigationBar
                   Navigator.of(context).popUntil(ModalRoute.withName('/main'))
                  },
                )
              ]
            ),
            body: ItemScreen(),
            ...
        );
      }
    );
  }

I try that do it is using Bloc or it's bad idea to use Bloc?

May be, using Router MaterialPageRoute better than Bloc or using them together? How to you do it? Can you help to choose better option?

Body:
You could send the tab number you want to select by default

Navigate.of(context).pushNamed("/main",arguments:{'tab':3})

You can retrieve this tab number using ModalRoute and set _selectedIndex accordingly

Widget build(BuildContext context) {
   final route= ModalRoute.of(context).settings.arguments as Map<String,int>;
   var _selectedIndex = route['tab']

    return Scaffold(
        appBar: selectedAppBar(_selectedIndex),
        body: SafeArea(
          child: _screenOptions.elementAt(_selectedIndex),
        ),
        bottomNavigationBar: BottomNavigation(
          onChangeScreen: _onChangeScreen,
          selectedIndex: _selectedIndex,
        ),
      );
  }


问:
PHP - Display data in different time zones
Hello stackoverflow community.

I develop a web app and the concept is to display historical currency exchange rates based on time series from past.

For example a user may request exchange rates from 22 May 2020 13:00 to 26 MAY 2020 22:00. Then my backend run a loop and get the rates between those two date times each hour.

All rates in database stored in GMT time zone.

And here is the problem. Let's suppose a user make a request from a time zone offset +10:00. So if this user pick as last date time 26 MAY 2020 22:00, I guess I should grab from my database the rate in 26 MAY 2020 12:00, so to subtract 10 hours.

May this sound stupid, but I'm stuck with this.

What is my logic:

a) Get the users time zone offset via javascript in front-end

```<code>var get_timezone_offset = new Date().getTimezoneOffset();

var hrs = parseInt(-(timezone_offset / 60));

var mins = Math.abs(timezone_offset % 60);

var timezone_offset = hrs + ':' + mins;
</code>```

b) Send users time zone offset to my backend

c) Get rates from my database and convert date stored from GMT to users time zone offset via PHP's Datetime object

```<code>$date = new \DateTime('2020-05-26 22:00');

$date->modify(-10 hours);

$date->format('Y-m-d H:i:s');
</code>```

Is this right? I won't display wrong rates to my users.

Thank you in advance

答:
Please read the timezone tag wiki, especially the section titled "Time Zone != Offset".  In short, you cannot assume the offset taken now from the user is the same one that will apply at any other point in time.

A simple example is for time zones like America/New_York, which presently is UTC-4, but will switch to UTC-5 when daylight saving time ends in November.  But besides DST, many time zones have had changes in their standard time offsets.

Instead of getting the current numeric offset, get the IANA time zone identifier from the browser.

const tzid = Intl.DateTimeFormat().resolvedOptions().timeZone;
// example: "America/New_York", "Asia/Kolkata", "Europe/Athens", etc.
```

<p>Then you can use this identifier with PHP's built-in time zone support.  For example, the following converts from a local time in a given time zone to the equivalent time in UTC:</p>

<pre class="lang-php prettyprint-override"><code>$tz = new DateTimeZone("America/New_York");
$date = new DateTime('2020-05-26 22:00', $tz);
$date->setTimeZone(new DateTimeZone("UTC"));
echo $date->format('Y-m-d H:i:s');
</code>```

Body:
Hello stackoverflow community.

I develop a web app and the concept is to display historical currency exchange rates based on time series from past.

For example a user may request exchange rates from 22 May 2020 13:00 to 26 MAY 2020 22:00. Then my backend run a loop and get the rates between those two date times each hour.

All rates in database stored in GMT time zone.

And here is the problem. Let's suppose a user make a request from a time zone offset +10:00. So if this user pick as last date time 26 MAY 2020 22:00, I guess I should grab from my database the rate in 26 MAY 2020 12:00, so to subtract 10 hours.

May this sound stupid, but I'm stuck with this.

What is my logic:

a) Get the users time zone offset via javascript in front-end

var get_timezone_offset = new Date().getTimezoneOffset();

var hrs = parseInt(-(timezone_offset / 60));

var mins = Math.abs(timezone_offset % 60);

var timezone_offset = hrs + ':' + mins;

b) Send users time zone offset to my backend

c) Get rates from my database and convert date stored from GMT to users time zone offset via PHP's Datetime object

$date = new \DateTime('2020-05-26 22:00');

$date->modify(-10 hours);

$date->format('Y-m-d H:i:s');

Is this right? I won't display wrong rates to my users.

Thank you in advance

Body:
Please read the timezone tag wiki, especially the section titled "Time Zone != Offset".  In short, you cannot assume the offset taken now from the user is the same one that will apply at any other point in time.

A simple example is for time zones like America/New_York, which presently is UTC-4, but will switch to UTC-5 when daylight saving time ends in November.  But besides DST, many time zones have had changes in their standard time offsets.

Instead of getting the current numeric offset, get the IANA time zone identifier from the browser.

const tzid = Intl.DateTimeFormat().resolvedOptions().timeZone;
// example: "America/New_York", "Asia/Kolkata", "Europe/Athens", etc.

Then you can use this identifier with PHP's built-in time zone support.  For example, the following converts from a local time in a given time zone to the equivalent time in UTC:

$tz = new DateTimeZone("America/New_York");
$date = new DateTime('2020-05-26 22:00', $tz);
$date->setTimeZone(new DateTimeZone("UTC"));
echo $date->format('Y-m-d H:i:s');


答:
```<code>output = [[item[0] for item in order] for order in orders]

display(output)

[['Fries'],
['Burger', 'Milkshake', 'Cola'],
['Cola', 'Nuggets', 'Onion Rings'],
['Fries'],
['Big Burger', 'Nuggets']]
</code>```

Body:
Input:
orders = [[('Fries', 9)], [('Burger', 6), ('Milkshake', 2), ('Cola', 2)], [('Cola', 2), ('Nuggets', 3), ('Onion Rings', 5)], [('Fries', 9)], [('Big Burger', 7), ('Nuggets', 3)]]

Expected Output:
orders = [['Fries'], ['Burger', 'Milkshare', 'Cola'], ['Cola', 'Nuggets', 'Onion Rings'], ['Fries'], ['Big Burger', 'Nuggets']]

My attempt:

 for i, order in enumerate(orders):
        for j,item in enumerate(order):
            orders[i][j] = item[0]

Works ok. But are there any more intuitive/one-liner/faster/cooler way to do this?


问:
How to mock timer with Jest in React
Im unable to test my function as i have a timer in between . How can i mock timer with Jest

"await new Promise(resolve => setTimeout(resolve, 1000))"

```<code>async callAPI(user) {
   await new Promise(resolve => setTimeout(resolve, 1000));
   //Code.....
   try{
   .....
    }catch (error) {

   }
}

</code>```

答:
If you want to wait for 1 second, you can do it with jest fake timers:

jest.useFakeTimers();

it('test something after 1sec', () => {

  // Wait for 1 sec
  jest.advanceTimersByTime(1000);

  ...
});
```

Title: How to mock timer with Jest in React

Body:
Im unable to test my function as i have a timer in between . How can i mock timer with Jest

"await new Promise(resolve => setTimeout(resolve, 1000))"

async callAPI(user) {
   await new Promise(resolve => setTimeout(resolve, 1000));
   //Code.....
   try{
   .....
    }catch (error) {

   }
}


问:
how to create a Java List of two integers
Hello I am new to java and I am trying to create a list like

```<code>List<Int, Int> list = new List<Int, Int>();
</code>```

the first int is the value and the second int is the finished time. I want to be able to read from a file and save in my list, So can I later get the finished time or value list in a sorted way. I am going to ue these two list together so when the first one is sorted the second one also needs to be sorted accordingly.

If I use HashMap I cant add duplicate values, can someone help me please?
I tried with TreeMap but it also didnt work.

答:
Using java inbuilt Pair class. ArrayList or any List of pairs can be constructed. you need to import javafx.util.pair for that. Similarly for 3 values. Use java's Triplet class.

eg: Pair p=new Pair(1, 2);

ArrayList or any List of these pairs can be constructed easily now

Body:
Hello I am new to java and I am trying to create a list like

List<Int, Int> list = new List<Int, Int>();

the first int is the value and the second int is the finished time. I want to be able to read from a file and save in my list, So can I later get the finished time or value list in a sorted way. I am going to ue these two list together so when the first one is sorted the second one also needs to be sorted accordingly.

If I use HashMap I cant add duplicate values, can someone help me please?
I tried with TreeMap but it also didnt work.


问:
How to use TextBlob.correct() for a column in a dataframe
I'm trying to apply spelling correction to some tweets.

I have tried the following code:
train.text.apply(lambda x: " ".join([TextBlob(i).correct() for i in x.split()]))

However, I get an error. Could you please advise? Thanks in advance!

答:
Could you try to update this code with

train.apply(lambda x: " ".join([TextBlob(i).correct() for i in x['text'].split()]))

Hope this helps!!


问:
How do I use MyBatis BlobInputStreamTypeHandler / ClobReaderTypeHandler to stream content of select request?
I need to get BLOB content and store it somewhere (let's assume it's file). BLOB content might be big, so I want to use streams to do this. On MyBatis 'Configuration XML' page there is a list of available typehandlers. I've found there is BlobInputStreamTypeHandler which should allow me to get InputStream and that's exactly what I need. So I've specified resultType="java.io.InputStream" for my query in xml configuration. However I get java.io.IOException: Closed Connection when I try to read data from InputStream I've got after 'read from DB' method execution.
I've tried to figure it out and found that class org.apache.ibatis.executor.resultset.DefaultResultSetHandler is closing resultSet and this makes stream unreadable.

I get same exception when I try to use ClobReaderTypeHandler to get Reader from CLOB.

I'm using mybatis version 3.5.4.

How do I get Reader/InputStream from CLOB or BLOB column?
Is this a bug or am I doing something wrong?

答:
You need to read the input stream while the session is open.

Assuming your mapper method is declared as follows...

@Select("select bindata from users where id = #{id}")
InputStream selectBlob(Integer id);
```

<p>the code that gets and reads the input stream would look something like this.</p>

<pre class="lang-java prettyprint-override"><code>try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
  Mapper mapper = sqlSession.getMapper(Mapper.class);
  try (InputStream inputStream = mapper.selectBlob(1)) {
    byte[] buffer = new byte[1024];
    int read;
    while((read = inputStream.read(buffer)) > -1) {
      // use the read data
    }
  }
}
</code>```

Body:
You need to read the input stream while the session is open.

Assuming your mapper method is declared as follows...

@Select("select bindata from users where id = #{id}")
InputStream selectBlob(Integer id);

the code that gets and reads the input stream would look something like this.

try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
  Mapper mapper = sqlSession.getMapper(Mapper.class);
  try (InputStream inputStream = mapper.selectBlob(1)) {
    byte[] buffer = new byte[1024];
    int read;
    while((read = inputStream.read(buffer)) > -1) {
      // use the read data
    }
  }
}


问:
How to stop animation in android studio?
ysize.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:startOffset="0"
    android:repeatMode="reverse"
    android:fillAfter="false"
    android:shareInterpolator="@android:interpolator/linear"
    >
    <scale
        android:pivotY="50%"
        android:fromYScale="10dp"
        android:fromXScale="1"
        android:toXScale="1"
        android:toYScale="40dp"
        android:repeatCount="infinite"
        android:duration="480"
        >
    </scale>
</set>
</code>```

MainActivity.java

```<code>import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
Animation input_v1;
ImageView in_v1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        input_v1 = AnimationUtils.loadAnimation(this,R.anim.ysize);  //Animation initialization
        in_v1 = findViewById(R.id.i_v1);        //image,textview,button initialization
        in_v1.startAnimation(input_v1);        //Start animation
    }
}

</code>```

The above code work and start the Animation.

But I want to stop this animation.

and other important functions for animation

答:
//How you start

```<code>Animation rotation = AnimationUtils.loadAnimation(this, R.anim.ysize);
          rotation.setRepeatCount(Animation.INFINITE);
iv.startAnimation(rotation);
</code>```

//You do your stuff while it spins

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

//You tell it not to repeat again

```<code>rotation.setRepeatCount(0);
</code>```

Body:
ysize.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:startOffset="0"
    android:repeatMode="reverse"
    android:fillAfter="false"
    android:shareInterpolator="@android:interpolator/linear"
    >
    <scale
        android:pivotY="50%"
        android:fromYScale="10dp"
        android:fromXScale="1"
        android:toXScale="1"
        android:toYScale="40dp"
        android:repeatCount="infinite"
        android:duration="480"
        >
    </scale>
</set>

MainActivity.java

import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
Animation input_v1;
ImageView in_v1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        input_v1 = AnimationUtils.loadAnimation(this,R.anim.ysize);  //Animation initialization
        in_v1 = findViewById(R.id.i_v1);        //image,textview,button initialization
        in_v1.startAnimation(input_v1);        //Start animation
    }
}

The above code work and start the Animation.

But I want to stop this animation.

and other important functions for animation

Body:
//How you start

Animation rotation = AnimationUtils.loadAnimation(this, R.anim.ysize);
          rotation.setRepeatCount(Animation.INFINITE);
iv.startAnimation(rotation);

//You do your stuff while it spins

...

//You tell it not to repeat again

rotation.setRepeatCount(0);


问:
How to compare only one specific color of two picture using imagemagick?
magick compare will show all the diffrence of 2 picture, but how to specify magick to compare only one color in picture.

for example, only compare blue area in 2 picture

I try check the option of magick compare command, but can't find which option can be used for
https://imagemagick.org/script/compare.php

答: To process only a given color in ImageMagick compare, you need to create a mask for that color. Then use the read mask compare technique. See https://imagemagick.org/discourse-server/viewtopic.php?f=4&t=31053</p>


问:
Different filtered dataProviders for the same data?
I have several lookup tables, some of which refer to or are relationships between others.

For instance, I have membership type included inventory which has Membership ID and Inventory Type ID and is the amount of each Inventory Type that one gets when one gets a specific type of membership.

When the user is reviewing an Inventory Type, I want them to see the amounts that go with each Membership Type; when the user is reviewing a Membership Type, I want them to see what inventory that membership would get.

Can I use a only one ArrayCollection for InvetoryType instances and only one ArrayCollection for MembershipType instances and somehow create filters to get different "views" of the data?

Each "view" would need its own cursor, sorting sequence, filter, etc.

Cheers

答: You can use a single Array instance with multiple ArrayCollection instances. If you're just displaying data, or sorting and filtering using the methods/properties provided by ArrayCollection (rather than editing the Array directly), it should have no effect on the underlying shared Array.

OwnerDisplayName: Richard Haven

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: joshtynjala


问:
Use NumPy cleverly to speed up this loop
This is quite a theoretical question. It is about the for loop at the end of the code attached.

I have three compatible arrays, Z, Wt_1 and Wt_2.

I used the vectorized columns to speed up the loop, ie I code with columns as though they were scalars, and the whole process works.
But this loop still takes forever (2min+). Here, N = 5000 and a column is 100000 long.

Is there a syntax that speeds this up ?

```<code>M=100000

N=5000
t0=0.132
T=0.22
dt=T / N

Z0=8
Y0=7

ssqZ=0.04
ssqY=0.01
sigma_Z=np.sqrt(ssqZ)
sigma_Y=np.sqrt(ssqY)
rho=- 0.4

print("Genreating the Brownian Motions...")
Wt_1=rd.randn(M//2,N)
# shape is (50 000,5 000)
Wt_1=np.vstack((Wt_1,-Wt_1))
#print(np.shape(Wt_1))
Wt_2=rd.randn(M//2,N)
Wt_2=np.vstack((Wt_2,-Wt_2))
print("BM generated!\n")

Z=np.zeros((M,N+1))
# shape is (100 000, 5 001)
Y=np.zeros((M,N+1))
#in SciPy indexing starts from 0 :
Z[:,0]=Z0
Y[:,0]=Y0

for i in range(1,N+1) :
    Z[:,i]=Z[:,i-1] - 0.5*(sigma_Z**2)*dt + sigma_Z*np.sqrt(dt)*Wt_1[:,i-1]

    Y[:,i]=Y[:,i-1] + sigma_Y*np.sqrt(dt)* (rho*Wt_1[:,i-1] + np.sqrt(1 - rho**2)*Wt_2[:,i-1])
</code>```

I should add that the same routine in Matlab takes 19s, whereas this Python one takes 137s, which is counter intuitive to me

答:
Let's try to move some repeated computations out of the loop </p>

```<code>sub_1 = 0.5*(sigma_Z**2)*dt
sub_2 = sigma_Z*np.sqrt(dt)
sub_3 = np.sqrt(1 - rho**2)
sub_4 = sigma_Y*np.sqrt(dt)

for i in range(1,N+1) :
    Z[:,i]=np.add(np.subtract(Z[:,i-1] ,sub_1), np.multiply(Wt_1[:,i-1], sub_2))

    Y[:,i]=np.add(Y[:,i-1] , np.multiply(np.add(np.multiply(Wt_2[:,i-1],sub_3),np.multiply(Wt_1[:,i-1],rho)), sub_4))
</code>```

Body:
This is quite a theoretical question. It is about the for loop at the end of the code attached.

I have three compatible arrays, Z, Wt_1 and Wt_2.

I used the vectorized columns to speed up the loop, ie I code with columns as though they were scalars, and the whole process works.
But this loop still takes forever (2min+). Here, N = 5000 and a column is 100000 long.

Is there a syntax that speeds this up ?

M=100000

N=5000
t0=0.132
T=0.22
dt=T / N

Z0=8
Y0=7

ssqZ=0.04
ssqY=0.01
sigma_Z=np.sqrt(ssqZ)
sigma_Y=np.sqrt(ssqY)
rho=- 0.4

print("Genreating the Brownian Motions...")
Wt_1=rd.randn(M//2,N)
# shape is (50 000,5 000)
Wt_1=np.vstack((Wt_1,-Wt_1))
#print(np.shape(Wt_1))
Wt_2=rd.randn(M//2,N)
Wt_2=np.vstack((Wt_2,-Wt_2))
print("BM generated!\n")

Z=np.zeros((M,N+1))
# shape is (100 000, 5 001)
Y=np.zeros((M,N+1))
#in SciPy indexing starts from 0 :
Z[:,0]=Z0
Y[:,0]=Y0

for i in range(1,N+1) :
    Z[:,i]=Z[:,i-1] - 0.5*(sigma_Z**2)*dt + sigma_Z*np.sqrt(dt)*Wt_1[:,i-1]

    Y[:,i]=Y[:,i-1] + sigma_Y*np.sqrt(dt)* (rho*Wt_1[:,i-1] + np.sqrt(1 - rho**2)*Wt_2[:,i-1])

I should add that the same routine in Matlab takes 19s, whereas this Python one takes 137s, which is counter intuitive to me

Body:
Let's try to move some repeated computations out of the loop

sub_1 = 0.5*(sigma_Z**2)*dt
sub_2 = sigma_Z*np.sqrt(dt)
sub_3 = np.sqrt(1 - rho**2)
sub_4 = sigma_Y*np.sqrt(dt)

for i in range(1,N+1) :
    Z[:,i]=np.add(np.subtract(Z[:,i-1] ,sub_1), np.multiply(Wt_1[:,i-1], sub_2))

    Y[:,i]=np.add(Y[:,i-1] , np.multiply(np.add(np.multiply(Wt_2[:,i-1],sub_3),np.multiply(Wt_1[:,i-1],rho)), sub_4))


问:
Programmatically go back to previous ViewController in Swift
I send the user over to a page on a button click. This page is a UITableViewController.

Now if the user taps on a cell, I would like to push him back to the previous page.

I thought about something like self.performSegue("back").... but this seems to be a bad idea.

What is the correct way to do it?

答:
I would like to suggest another approach to this problem. Instead of using the navigation controller to pop a view controller, use unwind segues. This solution has a few, but really important, advantages:

The origin controller can go back to any other destination controller (not just the previous one) without knowing anything about the destination.

Push and pop segues are defined in storyboard, so no navigation code in your view controllers.

You can find more details in Unwind Segues Step-by-Step. The how to is better explained in the former link, including how to send data back, but here I will make a brief explanation.

1) Go to the destination (not the origin) view controller and add an unwind segue:

```<code>    @IBAction func unwindToContact(_ unwindSegue: UIStoryboardSegue) {
        //let sourceViewController = unwindSegue.source
        // Use data from the view controller which initiated the unwind segue
    }
</code>```

2) CTRL drag from the view controller itself to the exit icon in the origin view controller:

3) Select the unwind function you just created a few moments ago:

4) Select the unwind segue and give it a name:

5) Go to any place of the origin view controller and call the unwind segue:

```<code>performSegue(withIdentifier: "unwindToContact", sender: self)
</code>```

I have found this approach payoffs a lot when your navigation starts to get complicated.

I hope this helps someone.

Body:
I would like to suggest another approach to this problem. Instead of using the navigation controller to pop a view controller, use unwind segues. This solution has a few, but really important, advantages:

The origin controller can go back to any other destination controller (not just the previous one) without knowing anything about the destination.

Push and pop segues are defined in storyboard, so no navigation code in your view controllers.

You can find more details in Unwind Segues Step-by-Step. The how to is better explained in the former link, including how to send data back, but here I will make a brief explanation.

1) Go to the destination (not the origin) view controller and add an unwind segue:

    @IBAction func unwindToContact(_ unwindSegue: UIStoryboardSegue) {
        //let sourceViewController = unwindSegue.source
        // Use data from the view controller which initiated the unwind segue
    }

2) CTRL drag from the view controller itself to the exit icon in the origin view controller:

3) Select the unwind function you just created a few moments ago:

4) Select the unwind segue and give it a name:

5) Go to any place of the origin view controller and call the unwind segue:

performSegue(withIdentifier: "unwindToContact", sender: self)

I have found this approach payoffs a lot when your navigation starts to get complicated.

I hope this helps someone.


问:
Most efficient way to store normals in gltf files?
I am looking at most efficient way to store normals in gltf files, we would like to use them for webgl 1 flat and smooth shading.
Is there support for different normal precision?
We prefer to not duplicate all vertices in order to have normals because or meshes are huge.

I just found this
KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes

NORMAL  "VEC3"  5126 (FLOAT)    Normalized XYZ vertex normals

so I assume there is a  single way?

Thanks for your help

答:
Flat normals: The most efficient way to store flat normals is to omit them entirely. From the glTF specification, in the Meshes section,

"When normals are not specified, client implementations should calculate flat normals."

Smooth normals: You are correct, the core glTF specification requires that normals use 5126 / float32 precision. If you need other options, enable the KHR_mesh_quantization extension (extension spec) on your model, which allows for additional types (int16 normalized or int8 normalized). The gltfpack library can apply these optimizations automatically, or you can modify the model directly.