问:
Looking for a database of n-grams taken from wikipedia
I am effectively trying to solve the same problem as this question:

Finding related words (specifically physical objects) to a specific word

minus the requirement that words represent physical objects.  The answers and edited question seem to indicate that a good start is building a list of frequency of n-grams using wikipedia text as a corpus.  Before I start downloading the mammoth wikipedia dump, does anyone know if such a list already exists?

PS if the original poster of the previous question sees this, I would love to know how you went about solving the problem, as your results seem excellent :-)

答:
You can find the June 2008 Wikipedia n-grams here. In addition it also has headwords and tagged sentences. I tried to create my own n-grams, but ran out of memory (32Gb) on the bigrams (the current English Wikipedia is massive). It also took about 8 hours to extract the xml, 5 hours for unigrams and 8 hours for bigrams.

The linked n-grams also has the benefit of having been cleaned somewhat since mediawiki and Wikipedia has a lot of junk in between the text.

Here's my Python code:

```<code>from nltk.tokenize import sent_tokenize
from nltk.tokenize import word_tokenize
from nltk.tokenize import wordpunct_tokenize
from datetime import datetime
from collections import deque
from collections import defaultdict
from collections import OrderedDict
import operator
import os

# Loop through all the English Wikipedia Article files and store their path and filename in a list. 4 minutes.
dir = r'D:\Downloads\Wikipedia\articles'
l = [os.path.join(root, name) for root, _, files in os.walk(dir) for name in files]

t1 = datetime.now()

# For each article (file) loop through all the words and generate unigrams. 1175MB memory use spotted.
# 12 minutes to first output. 4200000: 4:37:24.586706 was last output.
c = 1
d1s = defaultdict(int)
for file in l:
    try:
        with open(file, encoding="utf8") as f_in:
            content = f_in.read()
    except:
        with open(file, encoding="latin-1") as f_in:
            content = f_in.read()
    words = wordpunct_tokenize(content)    # word_tokenize handles 'n ʼn and ŉ as a single word. wordpunct_tokenize does not.
    # Take all the words from the sentence and count them.
    for i, word in enumerate(words):
        d1s[word] = d1s[word] + 1
    c = c + 1
    if c % 200000 == 0:
        t2 = datetime.now()
        print(str(c) + ': ' + str(t2 - t1))

t2 = datetime.now()
print('After unigram: ' + str(t2 - t1))

t1 = datetime.now()
# Sort the defaultdict in descending order and write the unigrams to a file.
# 0:00:27.740082 was output. 3285Mb memory. 165Mb output file.
d1ss = OrderedDict(sorted(d1s.items(), key=operator.itemgetter(1), reverse=True))
with open("D:\\Downloads\\Wikipedia\\en_ngram1.txt", mode="w", encoding="utf-8") as f_out:
    for k, v in d1ss.items():
        f_out.write(k + '┼' + str(v) + "\n")
t2 = datetime.now()
print('After unigram write: ' + str(t2 - t1))

# Determine the lowest 1gram count we are interested in.
low_count = 20 - 1
d1s = {}
# Get all the 1gram counts as a dict.
for word, count in d1ss.items():
    # Stop adding 1gram counts when we reach the lowest 1gram count.
    if count == low_count:
        break
    # Add the count to the dict.
    d1s[word] = count

t1 = datetime.now()

# For each article (file) loop through all the sentences and generate 2grams. 13GB memory use spotted.
# 17 minutes to first output. 4200000: 4:37:24.586706 was last output.
c = 1
d2s = defaultdict(int)
for file in l:
    try:
        with open(file, encoding="utf8") as f_in:
            content = f_in.read()
    except:
        with open(file, encoding="latin-1") as f_in:
            content = f_in.read()
    # Extract the sentences in the file content.
    sentences = deque()
    sentences.extend(sent_tokenize(content))
    # Get all the words for one sentence.
    for sentence in sentences:
        words = wordpunct_tokenize(sentence)    # word_tokenize handles 'n ʼn and ŉ as a single word. wordpunct_tokenize does not.
        # Take all the words from the sentence with high 1gram count that are next to each other and count them.
        for i, word in enumerate(words):
            if word in d1s:
                try:
                    word2 = words[i+1]
                    if word2 in d1s:
                        gram2 = word + ' ' + word2
                        d2s[gram2] = d2s[gram2] + 1
                except:
                    pass
    c = c + 1
    if c % 200000 == 0:
        t2 = datetime.now()
        print(str(c) + ': ' + str(t2 - t1))

t2 = datetime.now()
print('After bigram: ' + str(t2 - t1))
</code>```

Body:
You can find the June 2008 Wikipedia n-grams here. In addition it also has headwords and tagged sentences. I tried to create my own n-grams, but ran out of memory (32Gb) on the bigrams (the current English Wikipedia is massive). It also took about 8 hours to extract the xml, 5 hours for unigrams and 8 hours for bigrams.

The linked n-grams also has the benefit of having been cleaned somewhat since mediawiki and Wikipedia has a lot of junk in between the text.

Here's my Python code:

from nltk.tokenize import sent_tokenize
from nltk.tokenize import word_tokenize
from nltk.tokenize import wordpunct_tokenize
from datetime import datetime
from collections import deque
from collections import defaultdict
from collections import OrderedDict
import operator
import os

# Loop through all the English Wikipedia Article files and store their path and filename in a list. 4 minutes.
dir = r'D:\Downloads\Wikipedia\articles'
l = [os.path.join(root, name) for root, _, files in os.walk(dir) for name in files]

t1 = datetime.now()

# For each article (file) loop through all the words and generate unigrams. 1175MB memory use spotted.
# 12 minutes to first output. 4200000: 4:37:24.586706 was last output.
c = 1
d1s = defaultdict(int)
for file in l:
    try:
        with open(file, encoding="utf8") as f_in:
            content = f_in.read()
    except:
        with open(file, encoding="latin-1") as f_in:
            content = f_in.read()
    words = wordpunct_tokenize(content)    # word_tokenize handles 'n ʼn and ŉ as a single word. wordpunct_tokenize does not.
    # Take all the words from the sentence and count them.
    for i, word in enumerate(words):
        d1s[word] = d1s[word] + 1
    c = c + 1
    if c % 200000 == 0:
        t2 = datetime.now()
        print(str(c) + ': ' + str(t2 - t1))

t2 = datetime.now()
print('After unigram: ' + str(t2 - t1))

t1 = datetime.now()
# Sort the defaultdict in descending order and write the unigrams to a file.
# 0:00:27.740082 was output. 3285Mb memory. 165Mb output file.
d1ss = OrderedDict(sorted(d1s.items(), key=operator.itemgetter(1), reverse=True))
with open("D:\\Downloads\\Wikipedia\\en_ngram1.txt", mode="w", encoding="utf-8") as f_out:
    for k, v in d1ss.items():
        f_out.write(k + '┼' + str(v) + "\n")
t2 = datetime.now()
print('After unigram write: ' + str(t2 - t1))

# Determine the lowest 1gram count we are interested in.
low_count = 20 - 1
d1s = {}
# Get all the 1gram counts as a dict.
for word, count in d1ss.items():
    # Stop adding 1gram counts when we reach the lowest 1gram count.
    if count == low_count:
        break
    # Add the count to the dict.
    d1s[word] = count

t1 = datetime.now()

# For each article (file) loop through all the sentences and generate 2grams. 13GB memory use spotted.
# 17 minutes to first output. 4200000: 4:37:24.586706 was last output.
c = 1
d2s = defaultdict(int)
for file in l:
    try:
        with open(file, encoding="utf8") as f_in:
            content = f_in.read()
    except:
        with open(file, encoding="latin-1") as f_in:
            content = f_in.read()
    # Extract the sentences in the file content.
    sentences = deque()
    sentences.extend(sent_tokenize(content))
    # Get all the words for one sentence.
    for sentence in sentences:
        words = wordpunct_tokenize(sentence)    # word_tokenize handles 'n ʼn and ŉ as a single word. wordpunct_tokenize does not.
        # Take all the words from the sentence with high 1gram count that are next to each other and count them.
        for i, word in enumerate(words):
            if word in d1s:
                try:
                    word2 = words[i+1]
                    if word2 in d1s:
                        gram2 = word + ' ' + word2
                        d2s[gram2] = d2s[gram2] + 1
                except:
                    pass
    c = c + 1
    if c % 200000 == 0:
        t2 = datetime.now()
        print(str(c) + ': ' + str(t2 - t1))

t2 = datetime.now()
print('After bigram: ' + str(t2 - t1))


来源: stackexchange

问:
How do I get Cargo to save the name/version of a package to the "[dependencies]" section of my "Cargo.toml" file?
Today I spent more time than I should have trying to figure out why my project wasn't building, only to find out that I forgot to include the following crate:

```<code>[dependencies]
glob = "~0.3.0"
</code>```

I'd like to avoid making this mistake again by having Cargo add the name/version of a package to the [dependencies] section of my Cargo.toml file when I install the package.

To give you a better example of what I mean, in NPM if you run:

```<code>npm install --save-dev glob
</code>```

It'd save the name/version of the glob package to dependencies section of the package.json file.

How do I do this in Cargo?

答:
There's a crate called cargo-edit which expands cargo with subcommands add, rm and upgrade to act similarly to how npm install (and other package managers) do:

```<code># install cargo-edit
cargo install cargo-edit

# add crate "glob"
cargo add glob
</code>```

The resulting Cargo.toml file would look like this:

```<code>[dependencies]
glob = "0.3.0"
</code>```

The crate will be downloaded and built the next time you run a regular Cargo command (e.g. cargo build, cargo run, cargo test).

ContentLicense: CC BY-SA 4.0

Body:
Today I spent more time than I should have trying to figure out why my project wasn't building, only to find out that I forgot to include the following crate:

[dependencies]
glob = "~0.3.0"

I'd like to avoid making this mistake again by having Cargo add the name/version of a package to the [dependencies] section of my Cargo.toml file when I install the package.

To give you a better example of what I mean, in NPM if you run:

npm install --save-dev glob

It'd save the name/version of the glob package to dependencies section of the package.json file.

How do I do this in Cargo?

Body:
There's a crate called cargo-edit which expands cargo with subcommands add, rm and upgrade to act similarly to how npm install (and other package managers) do:

# install cargo-edit
cargo install cargo-edit

# add crate "glob"
cargo add glob

The resulting Cargo.toml file would look like this:

[dependencies]
glob = "0.3.0"

The crate will be downloaded and built the next time you run a regular Cargo command (e.g. cargo build, cargo run, cargo test).


问:
Loading audio via a Blob URL fails in Safari
Following code works in Chrome (22.0) but not in Safari (6.0)

<!DOCTYPE html>

  <input type="file" id="file" name="file" />
  <input type="submit" id="go" onclick="onGo()" value="Go" />

```

In Safari, neither callback (loadeddata nor error) is called.
The content used is an mp3 file, which is normally played back with audio tag.
Is there any special care needed for Safari?

答:
Many years later, I believe the example in the OP should work just fine. As long as you somehow set the mime type when creating the blob, like the OP does above with the type property of the options passed in:

```<code>new Blob([data], {type: 'audio/mpeg'});
</code>```

You could also use a <source> element inside of an audio element and set the type attribute of the <source> element. I have an example of this here:

https://lastmjs.github.io/safari-object-url-test

And here is the code:

```<code>const response = await window.fetch('https://upload.wikimedia.org/wikipedia/commons/transcoded/a/ab/Alexander_Graham_Bell%27s_Voice.ogg/Alexander_Graham_Bell%27s_Voice.ogg.mp3');

const audioArrayBuffer = await response.arrayBuffer();
const audioBlob = new Blob([audioArrayBuffer]);
const audioObjectURL = window.URL.createObjectURL(audioBlob);

const audioElement = document.createElement('audio');

audioElement.setAttribute('controls', true);
document.body.appendChild(audioElement);

const sourceElement = document.createElement('source');

audioElement.appendChild(sourceElement);

sourceElement.src = audioObjectURL;
sourceElement.type = 'audio/mp3';
</code>```

I prefer just setting the mime type of the blob when creating it. The <source> element src attribute/property cannot be updated dynamically.

ContentLicense: CC BY-SA 3.0

Body:
Following code works in Chrome (22.0) but not in Safari (6.0)

<!DOCTYPE html>

  <input type="file" id="file" name="file" />
  <input type="submit" id="go" onclick="onGo()" value="Go" />

In Safari, neither callback (loadeddata nor error) is called.
The content used is an mp3 file, which is normally played back with audio tag.
Is there any special care needed for Safari?

Body:
Many years later, I believe the example in the OP should work just fine. As long as you somehow set the mime type when creating the blob, like the OP does above with the type property of the options passed in:

new Blob([data], {type: 'audio/mpeg'});

You could also use a <source> element inside of an audio element and set the type attribute of the <source> element. I have an example of this here:

https://lastmjs.github.io/safari-object-url-test

And here is the code:

const response = await window.fetch('https://upload.wikimedia.org/wikipedia/commons/transcoded/a/ab/Alexander_Graham_Bell%27s_Voice.ogg/Alexander_Graham_Bell%27s_Voice.ogg.mp3');

const audioArrayBuffer = await response.arrayBuffer();
const audioBlob = new Blob([audioArrayBuffer]);
const audioObjectURL = window.URL.createObjectURL(audioBlob);

const audioElement = document.createElement('audio');

audioElement.setAttribute('controls', true);
document.body.appendChild(audioElement);

const sourceElement = document.createElement('source');

audioElement.appendChild(sourceElement);

sourceElement.src = audioObjectURL;
sourceElement.type = 'audio/mp3';

I prefer just setting the mime type of the blob when creating it. The <source> element src attribute/property cannot be updated dynamically.


问:
Cannot get data from SQLite database
I am trying to runn the following query:

```<code>SELECT nfc_film.title, nfc_film.film_id, nfc_film.description, nfc_film.release_year, nfc_film.rating, nfc_film.last_update, nfc_category.name
  FROM nfc_film
JOIN nfc_film_category
  ON nfc_film.film_id = nfc_film_category.film_id
JOIN nfc_category
  ON nfc_film_category.category_id = nfc_category.category_id  LIMIT 10 OFFSET 0
</code>```

This works if i put it into 'DB Browser for SQLite', the right fields are returned.

But when trying to implement this in PHP it doesn't work:

```<code>$filmQuery = "
SELECT nfc_film.title, nfc_film.film_id, nfc_film.description, nfc_film.release_year, nfc_film.rating, nfc_film.last_update, nfc_category.name
  FROM nfc_film
JOIN nfc_film_category
  ON nfc_film.film_id = nfc_film_category.film_id
JOIN nfc_category
  ON nfc_film_category.category_id = nfc_category.category_id ";

if($search_term && $category){
  $filmQuery .= "
  WHERE
    nfc_film.title LIKE :searchterm
  AND
    nfc_category.name = :category";
} else if ($search_term && !$category) {
  $filmQuery .= "
  WHERE
    nfc_film.title LIKE :searchterm";
} else if (!$search_term && $category) {
  $filmQuery .= "
  WHERE
    nfc_category.name = :category";
}

$filmQuery .= " LIMIT 10 OFFSET :page";
</code>```

When neither category or searchterm are found, then this resolves to:

```<code>SELECT nfc_film.title, nfc_film.film_id, nfc_film.description, nfc_film.release_year, nfc_film.rating, nfc_film.last_update, nfc_category.name
      FROM nfc_film
    JOIN nfc_film_category
      ON nfc_film.film_id = nfc_film_category.film_id
    JOIN nfc_category
      ON nfc_film_category.category_id = nfc_category.category_id  LIMIT 10 OFFSET :page
</code>```

I then prepare, bind, and execute the query:

```<code>$sqlGetFilms = $dbConn->prepare($filmQuery);
$sqlGetFilms->bindParam(':searchterm', $sqlSearchTerm);
$sqlGetFilms->bindParam(':category', $category);
$sqlGetFilms->bindParam(':page', $page);
$sqlGetFilms->execute();
$query = $sqlGetFilms->fetchAll();
</code>```

When noth searchterm and category are found, records are returned. But any other situation that appears in this code does not return any records, even though they appear when run in 'DB Browser for SQLite'

EDIT:
I have tried hardcoding

```<code>SELECT nfc_film.title, nfc_film.film_id, nfc_film.description, nfc_film.release_year, nfc_film.rating, nfc_film.last_update, nfc_category.name
      FROM nfc_film
    JOIN nfc_film_category
      ON nfc_film.film_id = nfc_film_category.film_id
    JOIN nfc_category
      ON nfc_film_category.category_id = nfc_category.category_id
      WHERE
        nfc_film.title LIKE '%k%' LIMIT 10 OFFSET 0
</code>```

and nothing was returned

答:
You may find that when you only use one or the other terms that you get an error which is something like trying to bind to a non-existent variable.

This (I think) is down to where you conditionally build the SQL, you may have :searchterm or :category or both - BUT you always try and bind to both of them.

So instead, if there is a value to bind - then bind each term individually...

```<code>if(!empty($search_term)){
    $sqlGetFilms->bindParam(':searchterm', $sqlSearchTerm);
}
if(!empty($category)) {
    $sqlGetFilms->bindParam(':category', $category);
}
</code>```

Title: Cannot get data from SQLite database

Body:
I am trying to runn the following query:

SELECT nfc_film.title, nfc_film.film_id, nfc_film.description, nfc_film.release_year, nfc_film.rating, nfc_film.last_update, nfc_category.name
  FROM nfc_film
JOIN nfc_film_category
  ON nfc_film.film_id = nfc_film_category.film_id
JOIN nfc_category
  ON nfc_film_category.category_id = nfc_category.category_id  LIMIT 10 OFFSET 0

This works if i put it into 'DB Browser for SQLite', the right fields are returned.

But when trying to implement this in PHP it doesn't work:

$filmQuery = "
SELECT nfc_film.title, nfc_film.film_id, nfc_film.description, nfc_film.release_year, nfc_film.rating, nfc_film.last_update, nfc_category.name
  FROM nfc_film
JOIN nfc_film_category
  ON nfc_film.film_id = nfc_film_category.film_id
JOIN nfc_category
  ON nfc_film_category.category_id = nfc_category.category_id ";

if($search_term && $category){
  $filmQuery .= "
  WHERE
    nfc_film.title LIKE :searchterm
  AND
    nfc_category.name = :category";
} else if ($search_term && !$category) {
  $filmQuery .= "
  WHERE
    nfc_film.title LIKE :searchterm";
} else if (!$search_term && $category) {
  $filmQuery .= "
  WHERE
    nfc_category.name = :category";
}

$filmQuery .= " LIMIT 10 OFFSET :page";

When neither category or searchterm are found, then this resolves to:

SELECT nfc_film.title, nfc_film.film_id, nfc_film.description, nfc_film.release_year, nfc_film.rating, nfc_film.last_update, nfc_category.name
      FROM nfc_film
    JOIN nfc_film_category
      ON nfc_film.film_id = nfc_film_category.film_id
    JOIN nfc_category
      ON nfc_film_category.category_id = nfc_category.category_id  LIMIT 10 OFFSET :page

I then prepare, bind, and execute the query:

$sqlGetFilms = $dbConn->prepare($filmQuery);
$sqlGetFilms->bindParam(':searchterm', $sqlSearchTerm);
$sqlGetFilms->bindParam(':category', $category);
$sqlGetFilms->bindParam(':page', $page);
$sqlGetFilms->execute();
$query = $sqlGetFilms->fetchAll();

When noth searchterm and category are found, records are returned. But any other situation that appears in this code does not return any records, even though they appear when run in 'DB Browser for SQLite'

EDIT:
I have tried hardcoding

SELECT nfc_film.title, nfc_film.film_id, nfc_film.description, nfc_film.release_year, nfc_film.rating, nfc_film.last_update, nfc_category.name
      FROM nfc_film
    JOIN nfc_film_category
      ON nfc_film.film_id = nfc_film_category.film_id
    JOIN nfc_category
      ON nfc_film_category.category_id = nfc_category.category_id
      WHERE
        nfc_film.title LIKE '%k%' LIMIT 10 OFFSET 0

and nothing was returned

Body:
You may find that when you only use one or the other terms that you get an error which is something like trying to bind to a non-existent variable.

This (I think) is down to where you conditionally build the SQL, you may have :searchterm or :category or both - BUT you always try and bind to both of them.

So instead, if there is a value to bind - then bind each term individually...

if(!empty($search_term)){
    $sqlGetFilms->bindParam(':searchterm', $sqlSearchTerm);
}
if(!empty($category)) {
    $sqlGetFilms->bindParam(':category', $category);
}


问:
Can I use Thread in Timer?
this code starts with start button, but this code is used if radiobutton countdown is selected, when the countdown is at 0 the second Frame appears and should change colors by the speed that user entered called "brzinaTreperenja2"(the object that is converted to int and then multiplied by 1000 for miliseconds) with my color red. Blinking does happen when I don't have the second actionListener and the blinking works with speed of 1 second, but when I do, the program freezes. Can you help me with this?</p>

```<code>start.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e) {
        if(countdown.isSelected()){

        final Timer p = new Timer();
        display.setFont(new Font("Ariel", Font.BOLD,25));
        display.setBounds(150,75,120,20);
        p.scheduleAtFixedRate(new TimerTask(){
        int i = Integer.parseInt(odbrojavanje.getText());
        @Override
        public void run(){
        display.setText(""+(i--));
        if(i<0){
            p.cancel();
            drugi.setVisible(true);
            Thread t = new Thread();
            while(true){
                ActionListener al3 = new ActionListener(){
                public void actionPerformed(ActionEvent h){
            drugi.getContentPane().setBackground(boja.getBackground());
                try {
                    t.sleep(brzinaTreperenja2);
                } catch (InterruptedException ex) {
                    Logger.getLogger(PrviProzor.class.getName()).log(Level.SEVERE, null, ex);
                }
            drugi.getContentPane().setBackground(Color.red);
                try {
                    t.sleep(brzinaTreperenja2);
                } catch (InterruptedException ex) {
                    Logger.getLogger(PrviProzor.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            };
                javax.swing.Timer p = new javax.swing.Timer(1000, al3);
                p.start();
            }
        }
        }
        },0,1000);
    }
    }
});`
</code>```

答:
Your code is flouting Swing threading rules:

You're making Swing calls from background threads, and this is dangerous to do and can cause exceptions to be thrown unpredictably.

You're using a java.uti.Timer, and should be using a javax.swing.Timer since the latter's repeated code runs on the Swing event thread.

You have while (true) loops that don't belong. The timer takes over the function of a loop.

You're repeatedly creating and starting a Swing timer from within a while loop -- why?

For example the following code uses a JSlider to set the blink frequency and a check box to start/stop a Swing Timer that blinks the background color of the main JPanel:

```<code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class BlinkEg extends JPanel {
    public static final Color COLOR = Color.RED;
    private JSlider slider = new JSlider(100, 1000, 500);
    private JCheckBox blinkBox = new JCheckBox("Blink");
    private Timer timer = new Timer(slider.getValue(), new TimerListener());

    public BlinkEg() {
        slider.setOpaque(false);
        slider.setMajorTickSpacing(200);
        slider.setMinorTickSpacing(10);
        slider.setPaintTicks(true);
        slider.setPaintLabels(true);
        setPreferredSize(new Dimension(400, 200));
        JPanel bottomPanel = new JPanel();
        bottomPanel.add(blinkBox);
        bottomPanel.setOpaque(false);

        blinkBox.setOpaque(false);
        blinkBox.addItemListener(evt -> {
            if (evt.getStateChange() == ItemEvent.SELECTED) {
                timer.start();
            } else {
                timer.stop();
                setBackground(null);
            }
        });

        slider.addChangeListener(evt -> {
            int value = slider.getValue();
            timer.setDelay(value);
        });

        setLayout(new BorderLayout());
        add(slider);
        add(bottomPanel, BorderLayout.PAGE_END);
    }

    private class TimerListener implements ActionListener {
        private boolean drawColor = false;

        @Override
        public void actionPerformed(ActionEvent e) {
            Color color = drawColor ? null : COLOR;
            BlinkEg.this.setBackground(color);
            drawColor = !drawColor;
        }
    }

    private static void createAndShowGui() {
        BlinkEg mainPanel = new BlinkEg();

        JFrame frame = new JFrame("BlinkEg");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}
</code>```

Note that to change the timing of the Swing Timer, simply call its setDelay(...) method:

```<code>// timer changed to rate set by JSlider:
slider.addChangeListener(evt -> {
    int value = slider.getValue();
    timer.setDelay(value);
});
</code>```

To start and stop the blinking, simply start and stop the Timer:

```<code>// timer start and stopped based on JCheckBox state
blinkBox.addItemListener(evt -> {
    if (evt.getStateChange() == ItemEvent.SELECTED) {
        timer.start();
    } else {
        timer.stop();
        setBackground(null);  // so always stops with baseline color
    }
});
</code>```

The Swing Timer uses an ActionListener that uses a boolean to decide what color to set the background to, then swaps the value of the boolean

```<code>private class TimerListener implements ActionListener {
    private boolean drawColor = false;

    @Override
    public void actionPerformed(ActionEvent e) {
        // choose color based on the state of drawColor
        Color color = drawColor ? null : COLOR;
        BlinkEg.this.setBackground(color);

        drawColor = !drawColor; // now toggle drawColor's boolean value
    }
}
</code>```

Title: Can I use Thread in Timer?

Body:
this code starts with start button, but this code is used if radiobutton countdown is selected, when the countdown is at 0 the second Frame appears and should change colors by the speed that user entered called "brzinaTreperenja2"(the object that is converted to int and then multiplied by 1000 for miliseconds) with my color red. Blinking does happen when I don't have the second actionListener and the blinking works with speed of 1 second, but when I do, the program freezes. Can you help me with this?

start.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e) {
        if(countdown.isSelected()){

        final Timer p = new Timer();
        display.setFont(new Font("Ariel", Font.BOLD,25));
        display.setBounds(150,75,120,20);
        p.scheduleAtFixedRate(new TimerTask(){
        int i = Integer.parseInt(odbrojavanje.getText());
        @Override
        public void run(){
        display.setText(""+(i--));
        if(i<0){
            p.cancel();
            drugi.setVisible(true);
            Thread t = new Thread();
            while(true){
                ActionListener al3 = new ActionListener(){
                public void actionPerformed(ActionEvent h){
            drugi.getContentPane().setBackground(boja.getBackground());
                try {
                    t.sleep(brzinaTreperenja2);
                } catch (InterruptedException ex) {
                    Logger.getLogger(PrviProzor.class.getName()).log(Level.SEVERE, null, ex);
                }
            drugi.getContentPane().setBackground(Color.red);
                try {
                    t.sleep(brzinaTreperenja2);
                } catch (InterruptedException ex) {
                    Logger.getLogger(PrviProzor.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            };
                javax.swing.Timer p = new javax.swing.Timer(1000, al3);
                p.start();
            }
        }
        }
        },0,1000);
    }
    }
});`

Body:
Your code is flouting Swing threading rules:

You're making Swing calls from background threads, and this is dangerous to do and can cause exceptions to be thrown unpredictably.

You're using a java.uti.Timer, and should be using a javax.swing.Timer since the latter's repeated code runs on the Swing event thread.

You have while (true) loops that don't belong. The timer takes over the function of a loop.

You're repeatedly creating and starting a Swing timer from within a while loop -- why?

For example the following code uses a JSlider to set the blink frequency and a check box to start/stop a Swing Timer that blinks the background color of the main JPanel:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class BlinkEg extends JPanel {
    public static final Color COLOR = Color.RED;
    private JSlider slider = new JSlider(100, 1000, 500);
    private JCheckBox blinkBox = new JCheckBox("Blink");
    private Timer timer = new Timer(slider.getValue(), new TimerListener());

    public BlinkEg() {
        slider.setOpaque(false);
        slider.setMajorTickSpacing(200);
        slider.setMinorTickSpacing(10);
        slider.setPaintTicks(true);
        slider.setPaintLabels(true);
        setPreferredSize(new Dimension(400, 200));
        JPanel bottomPanel = new JPanel();
        bottomPanel.add(blinkBox);
        bottomPanel.setOpaque(false);

        blinkBox.setOpaque(false);
        blinkBox.addItemListener(evt -> {
            if (evt.getStateChange() == ItemEvent.SELECTED) {
                timer.start();
            } else {
                timer.stop();
                setBackground(null);
            }
        });

        slider.addChangeListener(evt -> {
            int value = slider.getValue();
            timer.setDelay(value);
        });

        setLayout(new BorderLayout());
        add(slider);
        add(bottomPanel, BorderLayout.PAGE_END);
    }

    private class TimerListener implements ActionListener {
        private boolean drawColor = false;

        @Override
        public void actionPerformed(ActionEvent e) {
            Color color = drawColor ? null : COLOR;
            BlinkEg.this.setBackground(color);
            drawColor = !drawColor;
        }
    }

    private static void createAndShowGui() {
        BlinkEg mainPanel = new BlinkEg();

        JFrame frame = new JFrame("BlinkEg");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

Note that to change the timing of the Swing Timer, simply call its setDelay(...) method:

// timer changed to rate set by JSlider:
slider.addChangeListener(evt -> {
    int value = slider.getValue();
    timer.setDelay(value);
});

To start and stop the blinking, simply start and stop the Timer:

// timer start and stopped based on JCheckBox state
blinkBox.addItemListener(evt -> {
    if (evt.getStateChange() == ItemEvent.SELECTED) {
        timer.start();
    } else {
        timer.stop();
        setBackground(null);  // so always stops with baseline color
    }
});

The Swing Timer uses an ActionListener that uses a boolean to decide what color to set the background to, then swaps the value of the boolean

private class TimerListener implements ActionListener {
    private boolean drawColor = false;

    @Override
    public void actionPerformed(ActionEvent e) {
        // choose color based on the state of drawColor
        Color color = drawColor ? null : COLOR;
        BlinkEg.this.setBackground(color);

        drawColor = !drawColor; // now toggle drawColor's boolean value
    }
}


问:
Android LinearLayout and RecyclerView BottomNavigation Alignment
so I can't figure out how to align my bottom navigation in a LinearLayout under a RecyclerView. The items are RecyclerView:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".CategoryActivity">

   <android.support.design.widget.AppBarLayout
           android:theme="@style/AppTheme.AppBarOverlay"
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

       <android.support.v7.widget.Toolbar
               android:id="@+id/toolbar"
               android:background="?attr/colorPrimary"
               app:popupTheme="@style/AppTheme.PopupOverlay"
               android:layout_width="match_parent"
               android:layout_height="?attr/actionBarSize">
       </android.support.v7.widget.Toolbar>

   </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_category"
            android:layout_margin="8dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
    </android.support.v7.widget.RecyclerView>

    <android.support.design.widget.BottomNavigationView
            android:id="@+id/nav_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?android:attr/windowBackground"
            android:layout_alignParentBottom="true"
            app:menu="@menu/bottom_nav_menu"/>

</LinearLayout>
</code>```

The navigation should be always at the bottom.

答:
You Can't adjust your BottomNavigationView properly inside LinearLayout. If there are so many items in your RecyclerView then BottomNavigationView will be hidden at the bottom. So you must use RelativeLayout to align it at the bottom and other layouts above of BottomNavigationView. Please check the bellow modified layout.

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_category"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/nav_view"
        android:layout_below="@+id/appbar"
        android:layout_margin="8dp"
        android:orientation="vertical" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="?android:attr/windowBackground"
        app:menu="@menu/menu_navigation" />

</RelativeLayout>
</code>```

Body:
so I can't figure out how to align my bottom navigation in a LinearLayout under a RecyclerView. The items are RecyclerView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".CategoryActivity">

   <android.support.design.widget.AppBarLayout
           android:theme="@style/AppTheme.AppBarOverlay"
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

       <android.support.v7.widget.Toolbar
               android:id="@+id/toolbar"
               android:background="?attr/colorPrimary"
               app:popupTheme="@style/AppTheme.PopupOverlay"
               android:layout_width="match_parent"
               android:layout_height="?attr/actionBarSize">
       </android.support.v7.widget.Toolbar>

   </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_category"
            android:layout_margin="8dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
    </android.support.v7.widget.RecyclerView>

    <android.support.design.widget.BottomNavigationView
            android:id="@+id/nav_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?android:attr/windowBackground"
            android:layout_alignParentBottom="true"
            app:menu="@menu/bottom_nav_menu"/>

</LinearLayout>

The navigation should be always at the bottom.

Body:
You Can't adjust your BottomNavigationView properly inside LinearLayout. If there are so many items in your RecyclerView then BottomNavigationView will be hidden at the bottom. So you must use RelativeLayout to align it at the bottom and other layouts above of BottomNavigationView. Please check the bellow modified layout.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_category"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/nav_view"
        android:layout_below="@+id/appbar"
        android:layout_margin="8dp"
        android:orientation="vertical" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="?android:attr/windowBackground"
        app:menu="@menu/menu_navigation" />

</RelativeLayout>


问:
convert a list of dictionaries to a dictionary with dict comprehension
Original:

```<code># abs is not a string, it's a function name
[{'name': 'abs'}, {'op': abs}]
</code>```

to

```<code>{'name': 'abs', 'op': abs}
</code>```

My code:

```<code>op = [{'name': 'abs'}, {'op': abs}] # key value is unique
new_dict = {}
for item in op:
    new_dict.update(item)
</code>```

Is there a way to do the same with dict comprehension?

答:
Code:

```<code>list_of_dicts = [{'name': 'abs'}, {'op': abs}]
new_dict = {k: v for element in list_of_dicts for k, v in element.items()}
</code>```

Output:

```<code>{'name': 'abs', 'op': <built-in function abs>}
</code>```

Body:
Original:

# abs is not a string, it's a function name
[{'name': 'abs'}, {'op': abs}]

to

{'name': 'abs', 'op': abs}

My code:

op = [{'name': 'abs'}, {'op': abs}] # key value is unique
new_dict = {}
for item in op:
    new_dict.update(item)

Is there a way to do the same with dict comprehension?

Body:
Code:

list_of_dicts = [{'name': 'abs'}, {'op': abs}]
new_dict = {k: v for element in list_of_dicts for k, v in element.items()}

Output:

{'name': 'abs', 'op': <built-in function abs>}


问:
List directories in a path recursively using only NodeJS
I'm trying to make an elegant way to list all the directories and files inside them recursively. I want to list the files under each directories/sub-directories so that they are distinguishable. And the directory path must be provided by the user. My efforts are as below, the code is completely reproducible but I keep getting empty directories and the files are listed multiple times. What could be a better way to  accomplish the listing here?

```<code>//server.js
"use strict";
const fs = require("fs");
const rlp = require("readline");
const path = require("path");
const filesReadService = require("./filesReadService");
const handleFolders = require("./handleFolders");
//   var basePath = "C:\\Users\\My Computer\\Videos\\Captures";
const rl = rlp.createInterface({
  input: process.stdin,
  output: process.stdout
});

function directoryInput() {
  return new Promise((resolve, reject) => {
    rl.question("Please enter a valid directory: ", input => resolve(input));
  });
}

directoryInput().then(async userInput => {
  rl.close();
  let filesAndFolders = await handleFolders(userInput);
  await filesReadService(userInput, filesAndFolders);
});
</code>```

...

```<code>//handleFolders.js
const fs = require("fs");

const handleFolders = (directory, isRecursive) => {
  return new Promise((resolve, reject) => {
    fs.readdir(directory, (err, files) => {
      if (err) {
        reject(err);
        return;
      }
      resolve(files);
    });
  });
};

module.exports = handleFolders;
</code>```

...

```<code>//filesReadService.js
"use strict";
const fs = require("fs");
const path = require("path");
const handleFolders = require("./handleFolders");

const filesReadService = async (directoryPath, files) => {
  let fullPath;
  let obj = {};
  var promises = files.map(file => {
    fullPath = path.join(directoryPath, file);
    return new Promise((resolve, reject) => {
      fs.stat(fullPath, (err, stat) => {
        if (err) {
          reject(err);
          return;
        }
        if (stat.isFile()) {
          obj = {
            file,
            isFile: true
          };
        } else if (stat.isDirectory()) {
          obj = {
            file,
            isFolder: true
          };
        }

        resolve(obj);
      });
    });
  });

  Promise.all(promises).then(
    values => {
      console.log("The files in this directory:");
      values
        .filter(value => value.isFile)
        .forEach(value => console.log(value.file));
      console.log("\nThe folders in this directory:");

      values
        .filter(value => value.isFolder === true)
        .forEach(async value => {
          let folderPath = path.join(directoryPath, value.file);
          let foldersAndFiles = await handleFolders(folderPath, true);
          console.log(value.file, ":\t", foldersAndFiles);
          await filesReadService(folderPath, foldersAndFiles);
        });
    },
    err => {
      console.log(err);
    }
  );
};

module.exports = filesReadService;
</code>```

答:
```<code>const fs = require("fs"), path = require("path");
function recursivelyListDir(dir, callback) {
  fs.readdirSync(dir).forEach(f => {
    let dirPath = path.join(dir, f);
    let isDirectory = fs.statSync(dirPath).isDirectory();
    isDirectory
      ? recursivelyListDir(dirPath, callback)
      : callback(path.join(dir, f));
  });
}

// Function Usage.

recursivelyListDir(__dirname, function(filePath) {
  const fileContents = fs.readFileSync(filePath, "utf8");
  console.log(filePath);
});
</code>```

Body:
I'm trying to make an elegant way to list all the directories and files inside them recursively. I want to list the files under each directories/sub-directories so that they are distinguishable. And the directory path must be provided by the user. My efforts are as below, the code is completely reproducible but I keep getting empty directories and the files are listed multiple times. What could be a better way to  accomplish the listing here?

//server.js
"use strict";
const fs = require("fs");
const rlp = require("readline");
const path = require("path");
const filesReadService = require("./filesReadService");
const handleFolders = require("./handleFolders");
//   var basePath = "C:\\Users\\My Computer\\Videos\\Captures";
const rl = rlp.createInterface({
  input: process.stdin,
  output: process.stdout
});

function directoryInput() {
  return new Promise((resolve, reject) => {
    rl.question("Please enter a valid directory: ", input => resolve(input));
  });
}

directoryInput().then(async userInput => {
  rl.close();
  let filesAndFolders = await handleFolders(userInput);
  await filesReadService(userInput, filesAndFolders);
});

...

//handleFolders.js
const fs = require("fs");

const handleFolders = (directory, isRecursive) => {
  return new Promise((resolve, reject) => {
    fs.readdir(directory, (err, files) => {
      if (err) {
        reject(err);
        return;
      }
      resolve(files);
    });
  });
};

module.exports = handleFolders;

...

//filesReadService.js
"use strict";
const fs = require("fs");
const path = require("path");
const handleFolders = require("./handleFolders");

const filesReadService = async (directoryPath, files) => {
  let fullPath;
  let obj = {};
  var promises = files.map(file => {
    fullPath = path.join(directoryPath, file);
    return new Promise((resolve, reject) => {
      fs.stat(fullPath, (err, stat) => {
        if (err) {
          reject(err);
          return;
        }
        if (stat.isFile()) {
          obj = {
            file,
            isFile: true
          };
        } else if (stat.isDirectory()) {
          obj = {
            file,
            isFolder: true
          };
        }

        resolve(obj);
      });
    });
  });

  Promise.all(promises).then(
    values => {
      console.log("The files in this directory:");
      values
        .filter(value => value.isFile)
        .forEach(value => console.log(value.file));
      console.log("\nThe folders in this directory:");

      values
        .filter(value => value.isFolder === true)
        .forEach(async value => {
          let folderPath = path.join(directoryPath, value.file);
          let foldersAndFiles = await handleFolders(folderPath, true);
          console.log(value.file, ":\t", foldersAndFiles);
          await filesReadService(folderPath, foldersAndFiles);
        });
    },
    err => {
      console.log(err);
    }
  );
};

module.exports = filesReadService;


问:
How do I use the ID in one API to get info from another API in Redux?
So the API link www.api.com/id_list gives me IDs for some information in another API with link www.api.com/{id}.

I'm using Redux and I can get the id list however I am struggling to get the info needed via the IDs. It keeps telling me it's undefined.

So here's my code:

```<code>
    export const EVENT_DETAIL = 'EVENT_DETAIL';

    export const eventDetail = (payload) => {
     return {
       type: EVENT_DETAIL,
       data: payload.data,
       index: payload.index
      };
    }

    export const getDetail = (events, index) =>  {
        return function(dispatch) {
        const url = `${URL2}/${events}`;
        axios.get(url)
            .then (function (response) {
                   dispatch(eventDetail({
                   data: response.data.events,
                   index: index
               }))
            })
            .catch(function(error) {
                console.log(error);
            })
        }
    }

    componentDidMount = () =>  {
        this.props.getDetail();
        console.log(this.props.getDetail())
       }

</code>```

Any ideas why I can't get the information to show up?

Keep getting the follow error:

```<code>Error: Request failed with status code 404
    at createError (createError.js:17)
    at settle (settle.js:19)
    at XMLHttpRequest.handleLoad (xhr.js:78)
</code>```

答:
Your getDetail action is returning a function that doesn't itself return anything - this is why undefined is logged to your console. Put a return infront of your axios.get function, this will your request in form of a promise.

```<code>return axios.get(url)
  .then (function (response) {
    dispatch(eventDetail({
      data: response.data.events,
      index: index
    }))
  })
  .catch(function(error) {
    console.log(error);
  })
}
</code>```

To get the response from your request, you need to wait for it to resolve. This is done by calling .then on the promise. Your componentDidMount would look like this.

```<code>componentDidMount = () =>  {
  this.props.getDetail()
  .then(res => console.log(res))
}
</code>```

Body:
So the API link www.api.com/id_list gives me IDs for some information in another API with link www.api.com/{id}.

I'm using Redux and I can get the id list however I am struggling to get the info needed via the IDs. It keeps telling me it's undefined.

So here's my code:

    export const EVENT_DETAIL = 'EVENT_DETAIL';

    export const eventDetail = (payload) => {
     return {
       type: EVENT_DETAIL,
       data: payload.data,
       index: payload.index
      };
    }

    export const getDetail = (events, index) =>  {
        return function(dispatch) {
        const url = `${URL2}/${events}`;
        axios.get(url)
            .then (function (response) {
                   dispatch(eventDetail({
                   data: response.data.events,
                   index: index
               }))
            })
            .catch(function(error) {
                console.log(error);
            })
        }
    }

    componentDidMount = () =>  {
        this.props.getDetail();
        console.log(this.props.getDetail())
       }

Any ideas why I can't get the information to show up?

Keep getting the follow error:

Error: Request failed with status code 404
    at createError (createError.js:17)
    at settle (settle.js:19)
    at XMLHttpRequest.handleLoad (xhr.js:78)

Body:
Your getDetail action is returning a function that doesn't itself return anything - this is why undefined is logged to your console. Put a return infront of your axios.get function, this will your request in form of a promise.

return axios.get(url)
  .then (function (response) {
    dispatch(eventDetail({
      data: response.data.events,
      index: index
    }))
  })
  .catch(function(error) {
    console.log(error);
  })
}

To get the response from your request, you need to wait for it to resolve. This is done by calling .then on the promise. Your componentDidMount would look like this.

componentDidMount = () =>  {
  this.props.getDetail()
  .then(res => console.log(res))
}


问:
Line to line intersection works only on one side
I'm creating a raycasting engine on javascript using p5js and there is an issue with the line to line (raycast to wall) intersection.

I found a lot of line to line collision algorithms, including p5 collide library, but the problem appears on every one of them.

```<code>   this.intersects = function (raycastStart, raycastEnd) {
        var x1 = this.startPoint.x;  //Start point is the first point of a line.
        var y1 = this.startPoint.y;
        var x2 = this.endPoint.x;  //End point is the second point of a line.
        var y2 = this.endPoint.y;
        var x3 = raycastStart.x;
        var y3 = raycastStart.y;
        var x4 = raycastEnd.x;
        var y4 = raycastEnd.y;

        var a_dx = x2 - x1;
        var a_dy = y2 - y1;
        var b_dx = x4 - x3;
        var b_dy = y4 - y3;
        var s = (-a_dy * (x1 - x3) + a_dx * (y1 - y3)) / (-b_dx * a_dy + a_dx * b_dy);
        var t = (+b_dx * (y1 - y3) - b_dy * (x1 - x3)) / (-b_dx * a_dy + a_dx * b_dy);

        //Vector2 is simply class with two fields: x and y.
        return (s >= 0 && s <= 1 && t >= 0 && t <= 1) ? new Vector2(x1 + t * a_dx, y1 + t * a_dy) : null;
    }
</code>```

The line to line collision works on one side properly, but on the other, it works incorrect, according to my y position.

this is my map.

on one side it works perfectly

but on the other, it checks collision for line segments, that are lower than my Y position

答:
(I would comment, but don't have enough reputation to do so...)

It appears that your line collision algorithm is working.  But what appears to be missing is a check to determine which raycaster-to-line intersection is closer.  That is, in your working example the raycast never casts across two line segments, so there is no question about which line segment constrains your raycast.  But in your non-working example, the raycaster hits 2 of your 4 segments, so you now need to determine which of the 2 intersection points is closer to the raycast start, in order to determine which line segment is closer.

Body:
I'm creating a raycasting engine on javascript using p5js and there is an issue with the line to line (raycast to wall) intersection.

I found a lot of line to line collision algorithms, including p5 collide library, but the problem appears on every one of them.

   this.intersects = function (raycastStart, raycastEnd) {
        var x1 = this.startPoint.x;  //Start point is the first point of a line.
        var y1 = this.startPoint.y;
        var x2 = this.endPoint.x;  //End point is the second point of a line.
        var y2 = this.endPoint.y;
        var x3 = raycastStart.x;
        var y3 = raycastStart.y;
        var x4 = raycastEnd.x;
        var y4 = raycastEnd.y;

        var a_dx = x2 - x1;
        var a_dy = y2 - y1;
        var b_dx = x4 - x3;
        var b_dy = y4 - y3;
        var s = (-a_dy * (x1 - x3) + a_dx * (y1 - y3)) / (-b_dx * a_dy + a_dx * b_dy);
        var t = (+b_dx * (y1 - y3) - b_dy * (x1 - x3)) / (-b_dx * a_dy + a_dx * b_dy);

        //Vector2 is simply class with two fields: x and y.
        return (s >= 0 && s <= 1 && t >= 0 && t <= 1) ? new Vector2(x1 + t * a_dx, y1 + t * a_dy) : null;
    }

The line to line collision works on one side properly, but on the other, it works incorrect, according to my y position.

this is my map.

on one side it works perfectly

but on the other, it checks collision for line segments, that are lower than my Y position


问:
Kubernetes 1.14.2 HA Master NGINX load balancer log.go:172] http: TLS handshake error from 192.168.5.32:43148: remote error: tls: bad certificate
This is driving me crazy, I am NO Kubernetes expert but I am also not a novice.

I have tried unsuccessfully for three days to get past this issue but I can't and I am at the end of my rope.

I can query the cluster from my desktop after I copied the certificates from (kube-apiserver-1:/etc/kubernetes/pki/*) to my desktop.

```<code>$ kubectl -n kube-system get nodes
NAME               STATUS   ROLES    AGE   VERSION
kube-apiserver-1   Ready    master   71m   v1.14.2
</code>```

The Kubernetes cluster appears healthy when I query the kube-system pods:

```<code>$ kubectl -n kube-system get pods
NAME                                       READY   STATUS    RESTARTS   AGE
coredns-fb8b8dccf-6c85q                    1/1     Running   3          65m
coredns-fb8b8dccf-qwxlp                    1/1     Running   3          65m
kube-apiserver-kube-apiserver-1            1/1     Running   2          72m
kube-controller-manager-kube-apiserver-1   1/1     Running   2          72m
kube-flannel-ds-amd64-phntk                1/1     Running   2          62m
kube-proxy-swxrz                           1/1     Running   2          65m
kube-scheduler-kube-apiserver-1            1/1     Running   1          54m
</code>```

but when I query the api kubelet:

```<code>$ kubectl -n kube-system logs kube-apiserver-kube-apiserver-1
...
I0526 04:33:51.523828       1 log.go:172] http: TLS handshake error from 192.168.5.32:43122: remote error: tls: bad certificate
I0526 04:33:51.537258       1 log.go:172] http: TLS handshake error from 192.168.5.32:43124: remote error: tls: bad certificate
I0526 04:33:51.540617       1 log.go:172] http: TLS handshake error from 192.168.5.32:43126: remote error: tls: bad certificate
I0526 04:33:52.333817       1 log.go:172] http: TLS handshake error from 192.168.5.32:43130: remote error: tls: bad certificate
I0526 04:33:52.334354       1 log.go:172] http: TLS handshake error from 192.168.5.32:43128: remote error: tls: bad certificate
I0526 04:33:52.335570       1 log.go:172] http: TLS handshake error from 192.168.5.32:43132: remote error: tls: bad certificate
I0526 04:33:52.336703       1 log.go:172] http: TLS handshake error from 192.168.5.32:43134: remote error: tls: bad certificate
I0526 04:33:52.338792       1 log.go:172] http: TLS handshake error from 192.168.5.32:43136: remote error: tls: bad certificate
I0526 04:33:52.391557       1 log.go:172] http: TLS handshake error from 192.168.5.32:43138: remote error: tls: bad certificate
I0526 04:33:52.396566       1 log.go:172] http: TLS handshake error from 192.168.5.32:43140: remote error: tls: bad certificate
I0526 04:33:52.519666       1 log.go:172] http: TLS handshake error from 192.168.5.32:43142: remote error: tls: bad certificate
I0526 04:33:52.524702       1 log.go:172] http: TLS handshake error from 192.168.5.32:43144: remote error: tls: bad certificate
I0526 04:33:52.537127       1 log.go:172] http: TLS handshake error from 192.168.5.32:43146: remote error: tls: bad certificate
I0526 04:33:52.550177       1 log.go:172] http: TLS handshake error from 192.168.5.32:43150: remote error: tls: bad certificate
I0526 04:33:52.550613       1 log.go:172] http: TLS handshake error from 192.168.5.32:43148: remote error: tls: bad certificate
</code>```

On the NGINX load balancer (IP: 192.168.5.32) I have configured the TCP passthrough option as specified in the Kubernetes documentation:

```<code>upstream kubernetes-api-cluster {
   server 192.168.5.19:6443;
   server 192.168.5.29:6443;
}
server {
   listen 6443;
   ssl_certificate /etc/nginx/ssl/kube-apiserver.pem;
   ssl_certificate_key /etc/nginx/ssl/private/kube-apiserver.key;
   ssl_prefer_server_ciphers on;
   ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
   ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS;
   proxy_pass kubernetes-api-cluster;
}
</code>```

I can query the API server directly from the NGINX LB (IP: 192.168.5.32):

```<code>$ curl -v https://192.168.5.29:6443
* Rebuilt URL to: https://192.168.5.29:6443/
*   Trying 192.168.5.29...
* TCP_NODELAY set
* Connected to 192.168.5.29 (192.168.5.29) port 6443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Request CERT (13):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Certificate (11):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Client hello (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use h2
* Server certificate:
*  subject: CN=kube-apiserver
*  start date: May 26 03:39:36 2019 GMT
*  expire date: May 25 03:39:36 2020 GMT
*  subjectAltName: host "192.168.5.29" matched cert's IP address!
*  issuer: CN=kubernetes
*  SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x55840f1d9900)
> GET / HTTP/2
> Host: 192.168.5.29:6443
> User-Agent: curl/7.58.0
> Accept: */*
</code>```

I can also query the api using the DNS entry to the api as specified in the documents:

```<code>curl -v https://kube-apiserver.mydomain.com:6443
* Rebuilt URL to: https://kube-apiserver.mydomain.com:6443/
*   Trying 10.50.1.50...
* TCP_NODELAY set
* Connected to kube-apiserver.mydomain.com (10.50.1.50) port 6443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Request CERT (13):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Certificate (11):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Client hello (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use h2
* Server certificate:
*  subject: CN=kube-apiserver
*  start date: May 26 03:39:36 2019 GMT
*  expire date: May 25 03:39:36 2020 GMT
*  subjectAltName: host "kube-apiserver.mydomain.com" matched cert's "kube-apiserver.mydomain.com"
*  issuer: CN=kubernetes
*  SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x564287cbd900)
> GET / HTTP/2
> Host: kube-apiserver.mydomain.com:6443
> User-Agent: curl/7.58.0
> Accept: */*
</code>```

I can query the api server using curl as well on the API server:

```<code>curl -v https://kube-apiserver.mydomain.com:6443
* Rebuilt URL to: https://kube-apiserver.mydomain.com:6443/
*   Trying 10.50.1.50...
* TCP_NODELAY set
* Connected to kube-apiserver.epc-instore.com (10.50.1.50) port 6443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Request CERT (13):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Certificate (11):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Client hello (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use h2
* Server certificate:
*  subject: CN=kube-apiserver
*  start date: May 26 03:39:36 2019 GMT
*  expire date: May 25 03:39:36 2020 GMT
*  subjectAltName: host "kube-apiserver.mydomain.com" matched cert's "kube-apiserver.mydomain.com"
*  issuer: CN=kubernetes
*  SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x5628b9dbc900)
> GET / HTTP/2
> Host: kube-apiserver.mydomain.com:6443
> User-Agent: curl/7.58.0
> Accept: */*
</code>```

The manifest on the api server contains:

```<code>cat /etc/kubernetes/manifest/kube-apiserver.yaml
...
  - command:
    - kube-apiserver
    - --advertise-address=192.168.5.29
    - --allow-privileged=true
    - --authorization-mode=Node,RBAC
    - --client-ca-file=/etc/kubernetes/pki/ca.crt
    - --enable-admission-plugins=NodeRestriction
    - --enable-bootstrap-token-auth=true
    - --etcd-servers=http://etcd-cluster.mydomain.com:2379
    - --insecure-port=0
    - --kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt
    - --kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key
    - --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname
    - --proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.crt
    - --proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client.key
    - --requestheader-allowed-names=front-proxy-client
    - --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt
    - --requestheader-extra-headers-prefix=X-Remote-Extra-
    - --requestheader-group-headers=X-Remote-Group
    - --requestheader-username-headers=X-Remote-User
    - --secure-port=6443
    - --service-account-key-file=/etc/kubernetes/pki/sa.pub
    - --service-cluster-ip-range=10.96.0.0/12
    - --tls-cert-file=/etc/kubernetes/pki/apiserver.crt
    - --tls-private-key-file=/etc/kubernetes/pki/apiserver.key
    image: k8s.gcr.io/kube-apiserver:v1.14.2
    imagePullPolicy: IfNotPresent
...
</code>```

If you have any idea or hints on how to fix this I am all ears.  I am so frustrated with this issue, it really has gotten to me at this point.  I will continue to work on it but if anyone has a clue about this issue and can help it will be great.

Thank you.

答:
This is more of a troubleshooting idea to really target the source of the problem.
 If you can do:

```<code>kubectl --kubeconfig /etc/kubernetes/admin.conf get nodes
</code>```

from the api server and you get a response then the problem is NOT the load balancer.  To further prove this you can copy the appropriate certificates and files to a remote workstation and do the same:

```<code>kubectl --kubeconfig [workstation location]/admin.conf get nodes
</code>```

This second one obviously implies that you have direct access to the load balancer.

If this works too you have confirmation that the certificates are being passed through the TCP load balancer.

However, the error will persist as the load balancer has a check "availability" of a backend server.  This check does NOT use a certificate which produces the exception.

Body:
This is driving me crazy, I am NO Kubernetes expert but I am also not a novice.

I have tried unsuccessfully for three days to get past this issue but I can't and I am at the end of my rope.

I can query the cluster from my desktop after I copied the certificates from (kube-apiserver-1:/etc/kubernetes/pki/*) to my desktop.

$ kubectl -n kube-system get nodes
NAME               STATUS   ROLES    AGE   VERSION
kube-apiserver-1   Ready    master   71m   v1.14.2

The Kubernetes cluster appears healthy when I query the kube-system pods:

$ kubectl -n kube-system get pods
NAME                                       READY   STATUS    RESTARTS   AGE
coredns-fb8b8dccf-6c85q                    1/1     Running   3          65m
coredns-fb8b8dccf-qwxlp                    1/1     Running   3          65m
kube-apiserver-kube-apiserver-1            1/1     Running   2          72m
kube-controller-manager-kube-apiserver-1   1/1     Running   2          72m
kube-flannel-ds-amd64-phntk                1/1     Running   2          62m
kube-proxy-swxrz                           1/1     Running   2          65m
kube-scheduler-kube-apiserver-1            1/1     Running   1          54m

but when I query the api kubelet:

$ kubectl -n kube-system logs kube-apiserver-kube-apiserver-1
...
I0526 04:33:51.523828       1 log.go:172] http: TLS handshake error from 192.168.5.32:43122: remote error: tls: bad certificate
I0526 04:33:51.537258       1 log.go:172] http: TLS handshake error from 192.168.5.32:43124: remote error: tls: bad certificate
I0526 04:33:51.540617       1 log.go:172] http: TLS handshake error from 192.168.5.32:43126: remote error: tls: bad certificate
I0526 04:33:52.333817       1 log.go:172] http: TLS handshake error from 192.168.5.32:43130: remote error: tls: bad certificate
I0526 04:33:52.334354       1 log.go:172] http: TLS handshake error from 192.168.5.32:43128: remote error: tls: bad certificate
I0526 04:33:52.335570       1 log.go:172] http: TLS handshake error from 192.168.5.32:43132: remote error: tls: bad certificate
I0526 04:33:52.336703       1 log.go:172] http: TLS handshake error from 192.168.5.32:43134: remote error: tls: bad certificate
I0526 04:33:52.338792       1 log.go:172] http: TLS handshake error from 192.168.5.32:43136: remote error: tls: bad certificate
I0526 04:33:52.391557       1 log.go:172] http: TLS handshake error from 192.168.5.32:43138: remote error: tls: bad certificate
I0526 04:33:52.396566       1 log.go:172] http: TLS handshake error from 192.168.5.32:43140: remote error: tls: bad certificate
I0526 04:33:52.519666       1 log.go:172] http: TLS handshake error from 192.168.5.32:43142: remote error: tls: bad certificate
I0526 04:33:52.524702       1 log.go:172] http: TLS handshake error from 192.168.5.32:43144: remote error: tls: bad certificate
I0526 04:33:52.537127       1 log.go:172] http: TLS handshake error from 192.168.5.32:43146: remote error: tls: bad certificate
I0526 04:33:52.550177       1 log.go:172] http: TLS handshake error from 192.168.5.32:43150: remote error: tls: bad certificate
I0526 04:33:52.550613       1 log.go:172] http: TLS handshake error from 192.168.5.32:43148: remote error: tls: bad certificate

On the NGINX load balancer (IP: 192.168.5.32) I have configured the TCP passthrough option as specified in the Kubernetes documentation:

upstream kubernetes-api-cluster {
   server 192.168.5.19:6443;
   server 192.168.5.29:6443;
}
server {
   listen 6443;
   ssl_certificate /etc/nginx/ssl/kube-apiserver.pem;
   ssl_certificate_key /etc/nginx/ssl/private/kube-apiserver.key;
   ssl_prefer_server_ciphers on;
   ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
   ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS;
   proxy_pass kubernetes-api-cluster;
}

I can query the API server directly from the NGINX LB (IP: 192.168.5.32):

$ curl -v https://192.168.5.29:6443
* Rebuilt URL to: https://192.168.5.29:6443/
*   Trying 192.168.5.29...
* TCP_NODELAY set
* Connected to 192.168.5.29 (192.168.5.29) port 6443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Request CERT (13):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Certificate (11):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Client hello (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use h2
* Server certificate:
*  subject: CN=kube-apiserver
*  start date: May 26 03:39:36 2019 GMT
*  expire date: May 25 03:39:36 2020 GMT
*  subjectAltName: host "192.168.5.29" matched cert's IP address!
*  issuer: CN=kubernetes
*  SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x55840f1d9900)
> GET / HTTP/2
> Host: 192.168.5.29:6443
> User-Agent: curl/7.58.0
> Accept: */*

I can also query the api using the DNS entry to the api as specified in the documents:

curl -v https://kube-apiserver.mydomain.com:6443
* Rebuilt URL to: https://kube-apiserver.mydomain.com:6443/
*   Trying 10.50.1.50...
* TCP_NODELAY set
* Connected to kube-apiserver.mydomain.com (10.50.1.50) port 6443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Request CERT (13):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Certificate (11):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Client hello (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use h2
* Server certificate:
*  subject: CN=kube-apiserver
*  start date: May 26 03:39:36 2019 GMT
*  expire date: May 25 03:39:36 2020 GMT
*  subjectAltName: host "kube-apiserver.mydomain.com" matched cert's "kube-apiserver.mydomain.com"
*  issuer: CN=kubernetes
*  SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x564287cbd900)
> GET / HTTP/2
> Host: kube-apiserver.mydomain.com:6443
> User-Agent: curl/7.58.0
> Accept: */*

I can query the api server using curl as well on the API server:

curl -v https://kube-apiserver.mydomain.com:6443
* Rebuilt URL to: https://kube-apiserver.mydomain.com:6443/
*   Trying 10.50.1.50...
* TCP_NODELAY set
* Connected to kube-apiserver.epc-instore.com (10.50.1.50) port 6443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Request CERT (13):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Certificate (11):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Client hello (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use h2
* Server certificate:
*  subject: CN=kube-apiserver
*  start date: May 26 03:39:36 2019 GMT
*  expire date: May 25 03:39:36 2020 GMT
*  subjectAltName: host "kube-apiserver.mydomain.com" matched cert's "kube-apiserver.mydomain.com"
*  issuer: CN=kubernetes
*  SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x5628b9dbc900)
> GET / HTTP/2
> Host: kube-apiserver.mydomain.com:6443
> User-Agent: curl/7.58.0
> Accept: */*

The manifest on the api server contains:

cat /etc/kubernetes/manifest/kube-apiserver.yaml
...
  - command:
    - kube-apiserver
    - --advertise-address=192.168.5.29
    - --allow-privileged=true
    - --authorization-mode=Node,RBAC
    - --client-ca-file=/etc/kubernetes/pki/ca.crt
    - --enable-admission-plugins=NodeRestriction
    - --enable-bootstrap-token-auth=true
    - --etcd-servers=http://etcd-cluster.mydomain.com:2379
    - --insecure-port=0
    - --kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt
    - --kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key
    - --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname
    - --proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.crt
    - --proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client.key
    - --requestheader-allowed-names=front-proxy-client
    - --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt
    - --requestheader-extra-headers-prefix=X-Remote-Extra-
    - --requestheader-group-headers=X-Remote-Group
    - --requestheader-username-headers=X-Remote-User
    - --secure-port=6443
    - --service-account-key-file=/etc/kubernetes/pki/sa.pub
    - --service-cluster-ip-range=10.96.0.0/12
    - --tls-cert-file=/etc/kubernetes/pki/apiserver.crt
    - --tls-private-key-file=/etc/kubernetes/pki/apiserver.key
    image: k8s.gcr.io/kube-apiserver:v1.14.2
    imagePullPolicy: IfNotPresent
...

If you have any idea or hints on how to fix this I am all ears.  I am so frustrated with this issue, it really has gotten to me at this point.  I will continue to work on it but if anyone has a clue about this issue and can help it will be great.

Thank you.

Body:
This is more of a troubleshooting idea to really target the source of the problem.
 If you can do:

kubectl --kubeconfig /etc/kubernetes/admin.conf get nodes

from the api server and you get a response then the problem is NOT the load balancer.  To further prove this you can copy the appropriate certificates and files to a remote workstation and do the same:

kubectl --kubeconfig [workstation location]/admin.conf get nodes

This second one obviously implies that you have direct access to the load balancer.

If this works too you have confirmation that the certificates are being passed through the TCP load balancer.

However, the error will persist as the load balancer has a check "availability" of a backend server.  This check does NOT use a certificate which produces the exception.


问:
How to Force using my ID on category, not the auto-increment of prestashop category. PrestaShop
I want to define my own Category id like(999,2222,3333) and force using it on the PrestaShop database but when I execute it does(1,2,3)
How can I force using my own id </p>

```<code>        foreach ($XMLRSString->Families->Family as $family)
        {
            $_GET['forceIDs'] = true;

            $category = new Category($family->Code);

            $category->id = array((int)Configuration::get('PS_LANG_DEFAULT') =>  $family->Code);

            $category->id_category = array((int)Configuration::get('PS_LANG_DEFAULT') =>  $family->Code);

            $category->id_category_default = array((int)Configuration::get('PS_LANG_DEFAULT') =>  $family->Code);

            $category->is_root_category = false;

            $category->name = array((int)Configuration::get('PS_LANG_DEFAULT') => $family->Designation);

            $category->id_parent = Configuration::get('PS_HOME_CATEGORY');

            $category->link_rewrite = array((int)Configuration::get('PS_LANG_DEFAULT') =>  $family->Code);

            $category->add();

        }
</code>```

答:
In PrestaShop, if you'd like to force the ID of a specific object (Category, Product, Order, etc.) to bypass the SQL auto-increment during DB insertion, you have to set the force_id parameter to true.

Here's a minimalist example that works for a Category:

```<code>$category = new Category();
$category->id = 42;
$category->force_id = true;
$category->is_root_category = false;
$category->name = array((int)Configuration::get('PS_LANG_DEFAULT') => 'Test');
$category->link_rewrite = array((int)Configuration::get('PS_LANG_DEFAULT') =>  'test');
$category->id_parent = Configuration::get('PS_HOME_CATEGORY');
$category->add();
</code>```

This will work with all versions of PrestaShop and can be found in the ObjectModel class (parent class for all Objects):

```<code>/** @var bool Enables to define an ID before adding object. */
public $force_id = false;
</code>```

It is then checked right before adding the object in DB, in the same class:

```<code>public function add($auto_date = true, $null_values = false)
{
    if (isset($this->id) && !$this->force_id)
        unset($this->id);

    ...
</code>```

I hope this helps!

Body:
I want to define my own Category id like(999,2222,3333) and force using it on the PrestaShop database but when I execute it does(1,2,3)
How can I force using my own id

        foreach ($XMLRSString->Families->Family as $family)
        {
            $_GET['forceIDs'] = true;

            $category = new Category($family->Code);

            $category->id = array((int)Configuration::get('PS_LANG_DEFAULT') =>  $family->Code);

            $category->id_category = array((int)Configuration::get('PS_LANG_DEFAULT') =>  $family->Code);

            $category->id_category_default = array((int)Configuration::get('PS_LANG_DEFAULT') =>  $family->Code);

            $category->is_root_category = false;

            $category->name = array((int)Configuration::get('PS_LANG_DEFAULT') => $family->Designation);

            $category->id_parent = Configuration::get('PS_HOME_CATEGORY');

            $category->link_rewrite = array((int)Configuration::get('PS_LANG_DEFAULT') =>  $family->Code);

            $category->add();

        }

Body:
In PrestaShop, if you'd like to force the ID of a specific object (Category, Product, Order, etc.) to bypass the SQL auto-increment during DB insertion, you have to set the force_id parameter to true.

Here's a minimalist example that works for a Category:

$category = new Category();
$category->id = 42;
$category->force_id = true;
$category->is_root_category = false;
$category->name = array((int)Configuration::get('PS_LANG_DEFAULT') => 'Test');
$category->link_rewrite = array((int)Configuration::get('PS_LANG_DEFAULT') =>  'test');
$category->id_parent = Configuration::get('PS_HOME_CATEGORY');
$category->add();

This will work with all versions of PrestaShop and can be found in the ObjectModel class (parent class for all Objects):

/** @var bool Enables to define an ID before adding object. */
public $force_id = false;

It is then checked right before adding the object in DB, in the same class:

public function add($auto_date = true, $null_values = false)
{
    if (isset($this->id) && !$this->force_id)
        unset($this->id);

    ...

I hope this helps!


问:
Django check if model has related object before deleting the model
After looking for a way to check if a model instance can be deleted in django, I found many options, but none was working as expected. Hope this solution can help.

Let start by creating an Abstract model class which can be inherited by other model

```<code>class ModelIsDeletable(models.Model):
    name = models.CharField(max_length=200, blank=True, null=True, unique=True)
    description = models.CharField(max_length=200, blank=True, null=True)
    date_modified = models.DateTimeField(auto_now_add=True)

    def is_deletable(self):
        # get all the related object
        for rel in self._meta.get_fields():
            try:
                # check if there is a relationship with at least one related object
                related = rel.related_model.objects.filter(**{rel.field.name: self})
                if related.exists():
                    # if there is return a Tuple of flag = False the related_model object
                    return False, related
            except AttributeError:  # an attribute error for field occurs when checking for AutoField
                pass  # just pass as we dont need to check for AutoField
        return True, None

     class Meta:
        abstract = True
</code>```

Example

So let say we have three model  Organization and Department and StaffType
So many Department can be in an Organization
And an Organization has a particular StaffType

```<code>class StaffType(ModelIsDeletable):
    pensionable = models.BooleanField(default=False)

class Organization(ModelIsDeletable):
    staff_type = models.ForeignKey(to=StaffType)

class Department(ModelIsDeletable):
    organization = models.ForeignKey(to=Organization, to_field="id")
</code>```

so let say after adding some information you want to remove an organization model instance
that is already tied to a Department

For instance we have
Organization Table => (name = Engineering, pk = 1)
Department Table => (name=Developer, organization_fk=1, pk=1)

Now when you try to delete an organization after get it with the pk

```<code>a_org = Organization.objects.get(pk=1)
</code>```

With this at hand you can check if it deletable

```<code>deletable, related_obj = a_org.is_deletable()

if not deletable:
    # do some stuff with the related_obj list

else:
    # call the delete function
    a_org.delete()
</code>```

答:
Your question appears to be "How to detect what related model objects would be deleted if I delete this model object?" or "How to detect what related rows would be deleted if I delete this row?"

Another option is to use a transaction, do the delete, save the information provided by django, but rollback before committing the change. This works in databases like Postgres and MySQL, but I don't know about others.

In this example I want to know what will be deleted if I delete my organization named 'pdemo', and I see that it has 408 related Property objects.

https://gist.github.com/cgthayer/25aa97bb4b74efb75e3467fb7bbdaacb

```<code>>>> from django.db import transaction
>>> transaction.set_autocommit(autocommit=False)
>>> o = Organization_v2.objects.get(name='pdemo')
>>> del_info = o.delete()
>>> del_info
(1404, {'data.Property': 408, [..more stuff..], 'data.Organization_v2': 1})
>>> Property.objects.filter(scope__organization_id=o).count()
0
>>> transaction.rollback()
>>> o = Organization_v2.objects.get(name='pdemo')
>>> Property.objects.filter(scope__organization_id=o).count()
408
</code>```

This could be translated into a generic function.

When looking into this, I found many old solutions that use the functions in the django.contrib.admin to determine this, but that's an undocumented api that seems to change from time to time, so using transactions seems to be easier iff your database supports it.

Body:
After looking for a way to check if a model instance can be deleted in django, I found many options, but none was working as expected. Hope this solution can help.

Let start by creating an Abstract model class which can be inherited by other model

class ModelIsDeletable(models.Model):
    name = models.CharField(max_length=200, blank=True, null=True, unique=True)
    description = models.CharField(max_length=200, blank=True, null=True)
    date_modified = models.DateTimeField(auto_now_add=True)

    def is_deletable(self):
        # get all the related object
        for rel in self._meta.get_fields():
            try:
                # check if there is a relationship with at least one related object
                related = rel.related_model.objects.filter(**{rel.field.name: self})
                if related.exists():
                    # if there is return a Tuple of flag = False the related_model object
                    return False, related
            except AttributeError:  # an attribute error for field occurs when checking for AutoField
                pass  # just pass as we dont need to check for AutoField
        return True, None

     class Meta:
        abstract = True

Example

So let say we have three model  Organization and Department and StaffType
So many Department can be in an Organization
And an Organization has a particular StaffType

class StaffType(ModelIsDeletable):
    pensionable = models.BooleanField(default=False)

class Organization(ModelIsDeletable):
    staff_type = models.ForeignKey(to=StaffType)

class Department(ModelIsDeletable):
    organization = models.ForeignKey(to=Organization, to_field="id")

so let say after adding some information you want to remove an organization model instance
that is already tied to a Department

For instance we have
Organization Table => (name = Engineering, pk = 1)
Department Table => (name=Developer, organization_fk=1, pk=1)

Now when you try to delete an organization after get it with the pk

a_org = Organization.objects.get(pk=1)

With this at hand you can check if it deletable

deletable, related_obj = a_org.is_deletable()

if not deletable:
    # do some stuff with the related_obj list

else:
    # call the delete function
    a_org.delete()

Body:
Your question appears to be "How to detect what related model objects would be deleted if I delete this model object?" or "How to detect what related rows would be deleted if I delete this row?"

Another option is to use a transaction, do the delete, save the information provided by django, but rollback before committing the change. This works in databases like Postgres and MySQL, but I don't know about others.

In this example I want to know what will be deleted if I delete my organization named 'pdemo', and I see that it has 408 related Property objects.

https://gist.github.com/cgthayer/25aa97bb4b74efb75e3467fb7bbdaacb

>>> from django.db import transaction
>>> transaction.set_autocommit(autocommit=False)
>>> o = Organization_v2.objects.get(name='pdemo')
>>> del_info = o.delete()
>>> del_info
(1404, {'data.Property': 408, [..more stuff..], 'data.Organization_v2': 1})
>>> Property.objects.filter(scope__organization_id=o).count()
0
>>> transaction.rollback()
>>> o = Organization_v2.objects.get(name='pdemo')
>>> Property.objects.filter(scope__organization_id=o).count()
408

This could be translated into a generic function.

When looking into this, I found many old solutions that use the functions in the django.contrib.admin to determine this, but that's an undocumented api that seems to change from time to time, so using transactions seems to be easier iff your database supports it.


问:
How to provide the index of the clicked button which is created dynamically by instance?

I am trying to pass the index of the clicked button in Repeat(int value) and wrote this -
    gp.GetComponentInChildren ().onClick.AddListener(() =>
    Repeat(rep));

But when I click any button I got the last index of the button for all.
I want to know is there any way, I can pass the index of that button which i clicked in Repeat()?

```<code>void chatDialogs() {

        foreach (Transform child in this.transform) {
            GameObject.Destroy (child.gameObject);
        }

        for (int i = 5; i > 0 ; i--) {
            int currentStep = Laststep - i;
            if (currentStep >= 0) {
                 gp = (GameObject)Instantiate (playerPreFab);
                 gp.transform.SetParent (this.transform);
            }
            gp.GetComponentInChildren<Button> ().onClick.AddListener(() =>
            Repeat(**transform.GetSiblingIndex()**));
        }
    public void Repeat(int speakstep) {
        Application.ExternalCall("textspeak", speakstep);
    }
</code>```

in speakstep object of Repeat() the clicked button index should be passed, but its getting the last index in every button I click.

答:
I think you can do something like this:

```<code>AddButtonListener(gp.GetComponentInChildren<Button> (), i);
</code>```

inside your for loop,
when AddButtonListener is defined as:

```<code>void AddButtonListener(Button b, int index)
{
    b.onClick.AddListener(()=>{Repeat(index)});
}
</code>```

This way you capture the button index in the listener function (but I'm not sure what the correct name of this pattern is), and I wrote this without actually running it. Hope you have enough info now to get it working.

Body:
I am trying to pass the index of the clicked button in Repeat(int value) and wrote this -
    gp.GetComponentInChildren ().onClick.AddListener(() =>
    Repeat(rep));

But when I click any button I got the last index of the button for all.
I want to know is there any way, I can pass the index of that button which i clicked in Repeat()?

void chatDialogs() {

        foreach (Transform child in this.transform) {
            GameObject.Destroy (child.gameObject);
        }

        for (int i = 5; i > 0 ; i--) {
            int currentStep = Laststep - i;
            if (currentStep >= 0) {
                 gp = (GameObject)Instantiate (playerPreFab);
                 gp.transform.SetParent (this.transform);
            }
            gp.GetComponentInChildren<Button> ().onClick.AddListener(() =>
            Repeat(**transform.GetSiblingIndex()**));
        }
    public void Repeat(int speakstep) {
        Application.ExternalCall("textspeak", speakstep);
    }

in speakstep object of Repeat() the clicked button index should be passed, but its getting the last index in every button I click.

Body:
I think you can do something like this:

AddButtonListener(gp.GetComponentInChildren<Button> (), i);

inside your for loop,
when AddButtonListener is defined as:

void AddButtonListener(Button b, int index)
{
    b.onClick.AddListener(()=>{Repeat(index)});
}

This way you capture the button index in the listener function (but I'm not sure what the correct name of this pattern is), and I wrote this without actually running it. Hope you have enough info now to get it working.


问:
Causal inference - IPTW vs nearest neighbour matching
I am doing a quasi experimentation and am interested in getting ATT. i have a data with 260k entries where Ti = 0 and 5k entries where Ti = 1. I am calculating ATT with iptw technique where I achieve a great balance and the treatment effect -on treated as -ve 450 euros but not significant.

Weight calculation:
(If treatment = 1, weight = 1 else propensity score / (1-propensity score)

Then, to compare against other methodology, I use nearest neighbour matching with ratio = 1, the balance is again achieved.  I get treatment effect (which is ATT by default in matching) as +very 750 and significant.

Shouldn't both method generate similar result ? Which method should I go for in this case and why?

答:
When you match, is there any treated individuals without a match?

In expectation, IPTW and matching should both give the same answer. One possible explanation is that some treated individuals don't have a close match, so they are dropped. When this happens, the population for which the causal effect is defined changes. This could results in different answer between the methods


问:
Remove Unused CSS Selectors other than 'Dust Me Selectors'?
I would like to remove all unused CSS selectors from a common CSS file. While the Firefox extension "Dust Me Selectors" works well, it only works per page. It reports unused selectors for a page but some could be used on other pages.

Is there a tool which can go through a folder, scan all the files and bring up a list of selectors which are not used anywhere?

答: I'm not sure why you can't use Dust Me Selectors, you can right-click on the symbol and select "Spider Sitemap" to do an entire website at once.</p>

OwnerDisplayName: Abdu

OwnerDisplayName: Daniel Lew

ContentLicense: CC BY-SA 2.5