问:
Can we create a WCF service which publishes events?
I want to create a push web application.

The service layer is built on WCF.

The presentation layer is built on Asp.net 4

The service listens to events and updates its static property (a shared collection list) from the data layer.
I am polling in my presentation layer and calling a method of WCF every second and getting the updated collection.

If a collection is unmodified, I return empty list to save network bandwidth.

To save the round trips, I want the WCF service to publish an event if and when the collection is modified.  Is that possible?  How do I achieve this?

Thank you

答: WCF services allows duplex communication, so it can send messages to client.</p>


来源: stackexchange

问:
Spotify API - Promise stuck on pending
I'm new to Javascript so please bear with. I'm trying to scrape together a site that I can go to to view my currently playing song on Spotify. It is supposed to make a GET request through the fetch method to the Spotify API every 1000 ms and update the SongNameElement on screen without the user having to refresh.

I used this code I found online to get the self-updating div done through a publiclly accessible JSON file.

I also used this code to supply the request headers (token etc).

Example JSON Data can be found here. I need the value of this

The Spotify API returns a JSON file. I have managed to implement it in Python so far so it's not an issue with authentication to the API. I'm running a flask Python web server that returns JavaScript and HTML (see code below) however whenever it makes a request to the API, the promise is marked as pending however I'm not sure why it is not being completed. Below is my code:

```<code>import spotipy.util as util
from bs4 import BeautifulSoup
from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    return """
    <div id="SongName">Song Name</div>
    <div id="ArtistName">Artist Name</div>
    <script>
      function updateDataOnScreen() {
        const SongNameElement = document.getElementById("SongName")
        FetchResponse = fetch("https://api.spotify.com/v1/me/player/currently-playing", {
          method: 'GET', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer (my token goes here, but has been redacted)'
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        })
        .then(response => response.json())
        .then(json => SongNameElement.innerHTML = FetchResponse)
        .catch(error => console.error(error));
        console.log(FetchResponse)
      }
      document.addEventListener("DOMContentLoaded", function(event) {
        setInterval(updateDataOnScreen, 1000) // interval value in milliseconds
      })
    </script>
    """

if __name__ == '__main__':
    app.run(debug=True)
</code>```

Developer Tools shows this constantly.

N.B. I have redacted my token from the headers, so if you run this for yourself, you will need to replace it with your Sptify Token, which you can get here.

答:
not sure what I did,  but it works. Cheers Quentin for getting my mind going!</p>
```<code>import requests
from bs4 import BeautifulSoup
from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    return """
    <div id="SongName">Song Name</div>
    <script>
      function updateDataOnScreen() {
        const SongNameElement = document.getElementById("SongName")
        FetchResponse = fetch("https://api.spotify.com/v1/me/player/currently-playing", {
          method: 'GET', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer (AUTHKEY)'
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        })
        .then(response => response.json())
        .then(response => SongNameElement.innerHTML = (response.item.name))
        .catch(error => console.error(error));
      }
      document.addEventListener("DOMContentLoaded", function(event) {
        setInterval(updateDataOnScreen, 1000) // interval value in milliseconds
      })
    </script>
    """

if __name__ == '__main__':
    app.run(debug=True)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Spotify API - Promise stuck on pending

Body:
I'm new to Javascript so please bear with. I'm trying to scrape together a site that I can go to to view my currently playing song on Spotify. It is supposed to make a GET request through the fetch method to the Spotify API every 1000 ms and update the SongNameElement on screen without the user having to refresh.

I used this code I found online to get the self-updating div done through a publiclly accessible JSON file.

I also used this code to supply the request headers (token etc).

Example JSON Data can be found here. I need the value of this

The Spotify API returns a JSON file. I have managed to implement it in Python so far so it's not an issue with authentication to the API. I'm running a flask Python web server that returns JavaScript and HTML (see code below) however whenever it makes a request to the API, the promise is marked as pending however I'm not sure why it is not being completed. Below is my code:

import spotipy.util as util
from bs4 import BeautifulSoup
from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    return """

Song Name

Artist Name

    """

if __name__ == '__main__':
    app.run(debug=True)

Developer Tools shows this constantly.

N.B. I have redacted my token from the headers, so if you run this for yourself, you will need to replace it with your Sptify Token, which you can get here.

Body:
not sure what I did,  but it works. Cheers Quentin for getting my mind going!

import requests
from bs4 import BeautifulSoup
from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    return """
    <div id="SongName">Song Name</div>
    <script>
      function updateDataOnScreen() {
        const SongNameElement = document.getElementById("SongName")
        FetchResponse = fetch("https://api.spotify.com/v1/me/player/currently-playing", {
          method: 'GET', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer (AUTHKEY)'
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        })
        .then(response => response.json())
        .then(response => SongNameElement.innerHTML = (response.item.name))
        .catch(error => console.error(error));
      }
      document.addEventListener("DOMContentLoaded", function(event) {
        setInterval(updateDataOnScreen, 1000) // interval value in milliseconds
      })
    </script>
    """

if __name__ == '__main__':
    app.run(debug=True)


问:
My Loop of the Loop is painstakingly slow
I have an object $Posts which contain a title, and a SimTitles field amongst a few others.  I need to compare each title to the other titles and give it a Similarity score in the SimTitles field.  So if I have 80 $Posts, it will need to cover 6400 re-iterations as each title needs to be scored vs the others.

Apart from the Measure-TitleSimilarity routine which I believe is optimized, can anyone see a way to improve the speed of this double loop that I am missing?

Edit: I have included the function Measure-TitleSimilarity.  I am actually passing the array to the function.  The whole topic of quantifying arrays for likeness is fascinating.  I have tried with Title.ToCharArray() which changes the magic number to a much higher number.  It also can produce a match with two completely different titles as long as the characters are the same.  (Ex: 'Mother Teresa' would closely match 'Earthmovers' or 'Thermometer' yet clearly not the same meaning).  Cosine Similarity if just one method but it seemed easiest to process.
@Mclayton and @bryancook - I see the light with your suggestion, but can't grasp tracking what no longer needs to be looked at for similar words.

```<code>Function Get-SimTitles([psobject]$NewPosts) {

  $CKTitles = $NewPosts.title

  foreach ($Ck in $CkTitles) {
    $NewPosts | & {
      process {
        if ((Measure-TitleSimilarity $Ck.split(' ') $_.title.split(' ') -gt .2) {
          $_.SimTitles = $_.SimTitles + 1
        }
      }
    }
  }
}

Function Measure-TitleSimilarity
{
## Based on VectorSimilarity by .AUTHOR Lee Holmes
## Modified slightly to match use

[CmdletBinding()]
param(

    [Parameter(Position = 0)]
    $Title1,

    [Parameter(Position = 1)]
    $Title2

)

$allkeys = @($Title1) + @($Title2) |  Sort-Object -Unique

$set1Hash = @{}
$set2Hash = @{}
$setsToProcess = @($Title1, $Set1Hash), @($Title2, $Set2Hash)

foreach($set in $setsToProcess)
{
    $set[0] | Foreach-Object {
         $value = 1
         $set[1][$_] = $value
    }
}

$dot = 0
$mag1 = 0
$mag2 = 0

foreach($key in $allkeys)
{
    $dot += $set1Hash[$key] * $set2Hash[$key]
    $mag1 +=  ($set1Hash[$key] * $set1Hash[$key])
    $mag2 +=  ($set2Hash[$key] * $set2Hash[$key])
}

$mag1 = [Math]::Sqrt($mag1)
$mag2 = [Math]::Sqrt($mag2)

return [Math]::Round($dot / ($mag1 * $mag2), 3)

}
</code>```

答:
I tried other ways to measure the similarity of titles including word frequency vs frequency of words in a specific title.  I think comparing the titles is a topic for a separate post though.  I still like the idea of only looping once through.

@MikeSh - based on your answer this is what I came up with.

```<code>Function Get-SimTitles([psobject]$NewPosts) {

  $i=0
  $end = $NewPosts.Count - 1

  For($i =0; $i -lt $end; $i++){

      $k=$i+1
      $k..$end | Where{{$NewPosts[$i].source -ne $NewPosts[$_].source}} |
      Where-Object {(Measure-TitleSimilarity $NewPosts[$i].title.split(' ') $NewPosts[$_].title.split(' ')) -gt .35}  |
       & {process {$NewPosts[$_].SimTitles = $NewPosts[$_].SimTitles + 1; $NewPosts[$i].SimTitles+=1} }
       }

 }
</code>```

Body:
I have an object $Posts which contain a title, and a SimTitles field amongst a few others.  I need to compare each title to the other titles and give it a Similarity score in the SimTitles field.  So if I have 80 $Posts, it will need to cover 6400 re-iterations as each title needs to be scored vs the others.

Apart from the Measure-TitleSimilarity routine which I believe is optimized, can anyone see a way to improve the speed of this double loop that I am missing?

Edit: I have included the function Measure-TitleSimilarity.  I am actually passing the array to the function.  The whole topic of quantifying arrays for likeness is fascinating.  I have tried with Title.ToCharArray() which changes the magic number to a much higher number.  It also can produce a match with two completely different titles as long as the characters are the same.  (Ex: 'Mother Teresa' would closely match 'Earthmovers' or 'Thermometer' yet clearly not the same meaning).  Cosine Similarity if just one method but it seemed easiest to process.
@Mclayton and @bryancook - I see the light with your suggestion, but can't grasp tracking what no longer needs to be looked at for similar words.

Function Get-SimTitles([psobject]$NewPosts) {

  $CKTitles = $NewPosts.title

  foreach ($Ck in $CkTitles) {
    $NewPosts | & {
      process {
        if ((Measure-TitleSimilarity $Ck.split(' ') $_.title.split(' ') -gt .2) {
          $_.SimTitles = $_.SimTitles + 1
        }
      }
    }
  }
}

Function Measure-TitleSimilarity
{
## Based on VectorSimilarity by .AUTHOR Lee Holmes
## Modified slightly to match use

[CmdletBinding()]
param(

    [Parameter(Position = 0)]
    $Title1,

    [Parameter(Position = 1)]
    $Title2

)

$allkeys = @($Title1) + @($Title2) |  Sort-Object -Unique

$set1Hash = @{}
$set2Hash = @{}
$setsToProcess = @($Title1, $Set1Hash), @($Title2, $Set2Hash)

foreach($set in $setsToProcess)
{
    $set[0] | Foreach-Object {
         $value = 1
         $set[1][$_] = $value
    }
}

$dot = 0
$mag1 = 0
$mag2 = 0

foreach($key in $allkeys)
{
    $dot += $set1Hash[$key] * $set2Hash[$key]
    $mag1 +=  ($set1Hash[$key] * $set1Hash[$key])
    $mag2 +=  ($set2Hash[$key] * $set2Hash[$key])
}

$mag1 = [Math]::Sqrt($mag1)
$mag2 = [Math]::Sqrt($mag2)

return [Math]::Round($dot / ($mag1 * $mag2), 3)

}

Body:
I tried other ways to measure the similarity of titles including word frequency vs frequency of words in a specific title.  I think comparing the titles is a topic for a separate post though.  I still like the idea of only looping once through.

@MikeSh - based on your answer this is what I came up with.

Function Get-SimTitles([psobject]$NewPosts) {

  $i=0
  $end = $NewPosts.Count - 1

  For($i =0; $i -lt $end; $i++){

      $k=$i+1
      $k..$end | Where{{$NewPosts[$i].source -ne $NewPosts[$_].source}} |
      Where-Object {(Measure-TitleSimilarity $NewPosts[$i].title.split(' ') $NewPosts[$_].title.split(' ')) -gt .35}  |
       & {process {$NewPosts[$_].SimTitles = $NewPosts[$_].SimTitles + 1; $NewPosts[$i].SimTitles+=1} }
       }

 }


问:
how to handle click opening new window cypress
How to handle the windows in Cypress?

The problem I'm facing is that when I click a button, a new browser window gets opened in a new tab with the actual page to test.

I have tried everything -> window.open and window.location.replace without success (the target _blank is not possible because there is not that tag in the button)

How can I handle that functionality?

Thanks in advance.

答:
The problem is window.open can't be stubbed in the usual (simple) way, a security feature to prevent browser hijack.

This article Stub window.open has an alternative

TLDR - modify the window before it hits the browser

// ✅ CORRECT SOLUTION
it('opens a new window', () => {
  // create a single stub we will use
  const stub = cy.stub().as('open')
  cy.on('window:before:load', (win) => {
    cy.stub(win, 'open').callsFake(stub)
  })

  cy.visit('/')
  // triggers the application to call window.open
  cy.get('button').click('Open new window')
  cy.get('@open').should('have.been.calledOnce')
```


问:
How to add space beetween a pair of consecutive letters and not add space beetween two characters that are not both letters?
For example:
The string BINGO!
should be B I N G O!

I have already tried:

```<code>s = "BINGO!"
print(" ".join(s[::1]))
</code>```

答:
You can use a single lookahead to assert a char a-z to the right and make the pattern case insensitive.

In the replacement use the full match and a space using \g<0>

```<code>(?i)[A-Z](?=[A-Z])
</code>```

(?i) Inline modifier for a case insensitive match

[A-Z] Match a single char A-Z

(?=[A-Z]) Positive lookahead, assert a char A-Z to the right of the current position

See a regex demo and a Python demo.

Example

```<code>import re

print(re.sub(r'(?i)[A-Z](?=[A-Z])', '\g<0> ', 'BINGO!'))
</code>```

Output

```<code>B I N G O!
</code>```

Body:
For example:
The string BINGO!
should be B I N G O!

I have already tried:

s = "BINGO!"
print(" ".join(s[::1]))

Body:
You can use a single lookahead to assert a char a-z to the right and make the pattern case insensitive.

In the replacement use the full match and a space using \g<0>

(?i)[A-Z](?=[A-Z])

(?i) Inline modifier for a case insensitive match

[A-Z] Match a single char A-Z

(?=[A-Z]) Positive lookahead, assert a char A-Z to the right of the current position

See a regex demo and a Python demo.

Example

import re

print(re.sub(r'(?i)[A-Z](?=[A-Z])', '\g<0> ', 'BINGO!'))

Output

B I N G O!


问:
Access specific value of select element using Mootools
I've got a select element in my HTML page and I'd like to do a specific action using Mootools when a particular value of this select is chosen but I don't know how to access the element.

My element has cars_number as id and to access value 1 of this select element I've tried cars_number[1] but it doesn't work.

答:
Try with:

```<code>$('cars_number').getSelected();
</code>```

MooTools Documentation

ContentLicense: CC BY-SA 3.0

Body:
Try with:

$('cars_number').getSelected();

MooTools Documentation


问:
Is it possible to make a toggleable button that changes text when clicked
I have made a JFrame that shows a start button, and changes to stop when clicked. How to make it so that it changes its text to start when stop is clicked. Here is the source code:</p>
```<code>public class FRMCountdown extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    FRMCountdown frame = new FRMCountdown();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public FRMCountdown() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton Start_Stop_btn = new JButton("Start");
        Start_Stop_btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Start_Stop_btn.setText("Stop");
            }

        });
        Start_Stop_btn.setBounds(10, 188, 89, 23);
        contentPane.add(Start_Stop_btn);
    }
}
</code>```

答:
Oracle has a helpful tutorial, Creating a GUI With Swing.  Skip the Learning Swing with the NetBeans IDE section.

Swing was designed to be used with layout managers.  I used a FlowLayout to place one JButton.  Null layouts and absolute positioning lead to problems.

Java field names start with a lower case letter,  Java method names start with a lower case letter.  Java class names start with an upper case letter.

Here's the modified code.

```<code>import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ToggleJButton {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ToggleJButton();
            }
        });
    }

    public ToggleJButton() {
        JFrame frame = new JFrame("Toggle JButton");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(createMainPanel(), BorderLayout.CENTER);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createMainPanel() {
        JPanel panel = new JPanel(new FlowLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 100, 5, 100));

        JButton startStopButton = new JButton("Start");
        startStopButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                JButton button = (JButton) event.getSource();
                String text = button.getText();
                if (text.contentEquals("Start")) {
                    text = "Stop";
                } else {
                    text = "Start";
                }
                button.setText(text);
            }

        });
        panel.add(startStopButton);

        return panel;
    }

}
</code>```

Body:
I have made a JFrame that shows a start button, and changes to stop when clicked. How to make it so that it changes its text to start when stop is clicked. Here is the source code:

public class FRMCountdown extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    FRMCountdown frame = new FRMCountdown();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public FRMCountdown() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton Start_Stop_btn = new JButton("Start");
        Start_Stop_btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Start_Stop_btn.setText("Stop");
            }

        });
        Start_Stop_btn.setBounds(10, 188, 89, 23);
        contentPane.add(Start_Stop_btn);
    }
}

Body:
Oracle has a helpful tutorial, Creating a GUI With Swing.  Skip the Learning Swing with the NetBeans IDE section.

Swing was designed to be used with layout managers.  I used a FlowLayout to place one JButton.  Null layouts and absolute positioning lead to problems.

Java field names start with a lower case letter,  Java method names start with a lower case letter.  Java class names start with an upper case letter.

Here's the modified code.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ToggleJButton {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ToggleJButton();
            }
        });
    }

    public ToggleJButton() {
        JFrame frame = new JFrame("Toggle JButton");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(createMainPanel(), BorderLayout.CENTER);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createMainPanel() {
        JPanel panel = new JPanel(new FlowLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 100, 5, 100));

        JButton startStopButton = new JButton("Start");
        startStopButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                JButton button = (JButton) event.getSource();
                String text = button.getText();
                if (text.contentEquals("Start")) {
                    text = "Stop";
                } else {
                    text = "Start";
                }
                button.setText(text);
            }

        });
        panel.add(startStopButton);

        return panel;
    }

}


问:
Neighbors sum of numpy array with mask
I have two large arrays, one containing values, and one being a mask basically. The code below shows the function I want to implement.

```<code>from scipy.signal import convolve2d
import numpy as np

sample = np.array([[6, 4, 5, 5, 5],
                   [7, 1, 0, 8, 3],
                   [2, 5, 4, 8, 4],
                   [2, 0, 2, 6, 0],
                   [5, 7, 2, 3, 2]])

mask = np.array([[1, 0, 1, 1, 0],
                 [0, 0, 1, 0, 1],
                 [0, 1, 0, 0, 0],
                 [0, 0, 0, 1, 0],
                 [1, 1, 0, 0, 1]])

neighbors_sum = convolve2d(sample, np.ones((3,3), dtype=int), mode='same', boundary='wrap')

# neighbors_sum = np.array([[40, 37, 35, 33, 44],
#                           [37, 34, 40, 42, 48],
#                           [24, 23, 34, 35, 40],
#                           [27, 29, 37, 31, 32],
#                           [31, 33, 34, 30, 34]])

result = np.where(mask, neighbors_sum, 0)

print(result)
</code>```

This code works, and gets me what I expects:

```<code>np.array([[40,  0, 35, 33,  0],
          [ 0,  0, 40,  0, 48],
          [ 0, 23,  0,  0,  0],
          [ 0,  0,  0, 31,  0],
          [31, 33,  0,  0, 34]])
</code>```

So far, so good. However, where I'm encountering some large issue is when I increase the size of the arrays. In my case, instead of a 5x5 input and a 3x3 summing mask, I need a 50,000x20,000 input and a 100x100 summing mask. And when I move to that, the convolve2d function is in all kinds of trouble and the calculation is extremely long.

Given that I only care about the masked result, and thus only care about the summation from convolve2d at those points, can anyone think of a smart approach to take here? Going to a for loop and selecting only the points of interest would lose the speed advantage of the vectorization so I'm not convinced this would be worth it.

Any suggestion welcome!

答:
convolve2d is very inefficient in this case. Since the mask is np.ones, you can split the filter in two trivial ones thanks to separable filtering: one np.ones(100, 1) filter and one np.ones(1, 100) filter. Moreover, a rolling sum can be used to speed up even more the computation.

Here is a simple solution without a rolling sum:

# Simple faster implementation

tmp = convolve2d(sample, np.ones((1,100), dtype=int), mode='same', boundary='wrap')
neighbors_sum = convolve2d(tmp, np.ones((100,1), dtype=int), mode='same', boundary='wrap')
result = np.where(mask, neighbors_sum, 0)
```
<p>You can compute the rolling sum efficiently using <strong>Numba</strong>. The strategy is to split the computation in 3 parts: the horizontal rolling sum, the vertical rolling sum and the final masking. Each step can be fully parallelized using <strong>multiple threads</strong> (although parallelizing the vertical rolling sum is harder with Numba). Each part needs to work line by line so to be <em>cache friendly</em>.</p>
<pre class="lang-py prettyprint-override"><code># Complex very-fast implementation

import numba as nb

# Numerical results may diverge if the input contains big
# values with many small ones.
# Does not support inputs containing NaN values or +/- Inf ones.
@nb.njit('float64[:,::1](float64[:,::1], int_)', parallel=True, fastmath=True)
def horizontalRollingSum(sample, filterSize):
    n, m = sample.shape
    fs = filterSize

    # Make the wrapping part of the rolling sum much simpler
    assert fs >= 1
    assert n >= fs and m >= fs

    # Horizontal rolling sum.
    tmp = np.empty((n, m), dtype=np.float64)
    for i in nb.prange(n):
        s = 0.0
        lShift = fs//2
        rShift = (fs-1)//2
        for j in range(m-lShift, m):
            s += sample[i, j]
        for j in range(0, rShift+1):
            s += sample[i, j]
        tmp[i, 0] = s
        for j in range(1, m):
            jLeft, jRight = (j-1-lShift)%m, (j+rShift)%m
            s += sample[i, jRight] - sample[i, jLeft]
            tmp[i, j] = s

    return tmp

@nb.njit('float64[:,::1](float64[:,::1], int_)', fastmath=True)
def verticaltalRollingSum(sample, filterSize):
    n, m = sample.shape
    fs = filterSize

    # Make the wrapping part of the rolling sum much simpler
    assert fs >= 1
    assert n >= fs and m >= fs

    # Horizontal rolling sum.
    tmp = np.empty((n, m), dtype=np.float64)
    tShift = fs//2
    bShift = (fs-1)//2
    for j in range(m):
        tmp[0, j] = 0.0
    for i in range(n-tShift, n):
        for j in range(m):
            tmp[0, j] += sample[i, j]
    for i in range(0, bShift+1):
        for j in range(m):
            tmp[0, j] += sample[i, j]
    for i in range(1, n):
        iTop = (i-1-tShift)%n
        iBot = (i+bShift)%n
        for j in range(m):
            tmp[i, j] = tmp[i-1, j] + (sample[iBot, j] - sample[iTop, j])

    return tmp

@nb.njit('float64[:,::1](float64[:,::1], int_[:,::1], int_)', parallel=True, fastmath=True)
def compute(sample, mask, filterSize):
    n, m = sample.shape
    tmp = horizontalRollingSum(sample, filterSize)
    neighbors_sum = verticaltalRollingSum(tmp, filterSize)
    res = np.empty((n, m), dtype=np.float64)

    for i in nb.prange(n):
        for j in range(n):
            res[i, j] = neighbors_sum[i, j] * mask[i, j]

    return res
</code>```

Benchmark & Notes

Here is the testing code:

n, m = 5000, 2000
sample = np.random.rand(n, m)
mask = (np.random.rand(n, m) < 0.05).astype(int)
```
<p>Here are the results on my 6-core machine:</p>
<pre class="lang-none prettyprint-override"><code>Initial solution:           174366 ms   (x1)
With separate filters:        5710 ms   (x31)
Final Numba solution:           40 ms   (x4359)
Optimal theoretical time:       10 ms   (optimistic)
</code>```

Thus, the Numba implementation is 4359 times faster than the initial one.

That being said, be careful of possible numerical issues that this last implementation can have regarding the input array (see the comments in the code). It should be fine as long as np.std(sample) is relatively small and np.all(np.isfinite(sample)) is true.

Note that the code can be further optimized: the vertical rolling sum can be parallelized; modulus operations can be avoided in the horizontal rolling sum; the vertical rolling sum and the masking steps can be merged together (ie. by computing res on-the-fly and not storing tmp); tiling can be used to compute all the steps simultaneously in a more cache-friendly way. However, these optimizations make the code more complex and some of them are very hard to perform (especially the last one with Numba).

Note that using a boolean mask (instead of an integer-based one) should make the algorithm faster since it takes less memory and processors can fetch values faster.

Title: Neighbors sum of numpy array with mask

Body:
I have two large arrays, one containing values, and one being a mask basically. The code below shows the function I want to implement.

from scipy.signal import convolve2d
import numpy as np

sample = np.array([[6, 4, 5, 5, 5],
                   [7, 1, 0, 8, 3],
                   [2, 5, 4, 8, 4],
                   [2, 0, 2, 6, 0],
                   [5, 7, 2, 3, 2]])

mask = np.array([[1, 0, 1, 1, 0],
                 [0, 0, 1, 0, 1],
                 [0, 1, 0, 0, 0],
                 [0, 0, 0, 1, 0],
                 [1, 1, 0, 0, 1]])

neighbors_sum = convolve2d(sample, np.ones((3,3), dtype=int), mode='same', boundary='wrap')

# neighbors_sum = np.array([[40, 37, 35, 33, 44],
#                           [37, 34, 40, 42, 48],
#                           [24, 23, 34, 35, 40],
#                           [27, 29, 37, 31, 32],
#                           [31, 33, 34, 30, 34]])

result = np.where(mask, neighbors_sum, 0)

print(result)

This code works, and gets me what I expects:

np.array([[40,  0, 35, 33,  0],
          [ 0,  0, 40,  0, 48],
          [ 0, 23,  0,  0,  0],
          [ 0,  0,  0, 31,  0],
          [31, 33,  0,  0, 34]])

So far, so good. However, where I'm encountering some large issue is when I increase the size of the arrays. In my case, instead of a 5x5 input and a 3x3 summing mask, I need a 50,000x20,000 input and a 100x100 summing mask. And when I move to that, the convolve2d function is in all kinds of trouble and the calculation is extremely long.

Given that I only care about the masked result, and thus only care about the summation from convolve2d at those points, can anyone think of a smart approach to take here? Going to a for loop and selecting only the points of interest would lose the speed advantage of the vectorization so I'm not convinced this would be worth it.

Any suggestion welcome!

Body:
convolve2d is very inefficient in this case. Since the mask is np.ones, you can split the filter in two trivial ones thanks to separable filtering: one np.ones(100, 1) filter and one np.ones(1, 100) filter. Moreover, a rolling sum can be used to speed up even more the computation.

Here is a simple solution without a rolling sum:

# Simple faster implementation

tmp = convolve2d(sample, np.ones((1,100), dtype=int), mode='same', boundary='wrap')
neighbors_sum = convolve2d(tmp, np.ones((100,1), dtype=int), mode='same', boundary='wrap')
result = np.where(mask, neighbors_sum, 0)

You can compute the rolling sum efficiently using Numba. The strategy is to split the computation in 3 parts: the horizontal rolling sum, the vertical rolling sum and the final masking. Each step can be fully parallelized using multiple threads (although parallelizing the vertical rolling sum is harder with Numba). Each part needs to work line by line so to be cache friendly.

# Complex very-fast implementation

import numba as nb

# Numerical results may diverge if the input contains big
# values with many small ones.
# Does not support inputs containing NaN values or +/- Inf ones.
@nb.njit('float64[:,::1](float64[:,::1], int_)', parallel=True, fastmath=True)
def horizontalRollingSum(sample, filterSize):
    n, m = sample.shape
    fs = filterSize

    # Make the wrapping part of the rolling sum much simpler
    assert fs >= 1
    assert n >= fs and m >= fs

    # Horizontal rolling sum.
    tmp = np.empty((n, m), dtype=np.float64)
    for i in nb.prange(n):
        s = 0.0
        lShift = fs//2
        rShift = (fs-1)//2
        for j in range(m-lShift, m):
            s += sample[i, j]
        for j in range(0, rShift+1):
            s += sample[i, j]
        tmp[i, 0] = s
        for j in range(1, m):
            jLeft, jRight = (j-1-lShift)%m, (j+rShift)%m
            s += sample[i, jRight] - sample[i, jLeft]
            tmp[i, j] = s

    return tmp

@nb.njit('float64[:,::1](float64[:,::1], int_)', fastmath=True)
def verticaltalRollingSum(sample, filterSize):
    n, m = sample.shape
    fs = filterSize

    # Make the wrapping part of the rolling sum much simpler
    assert fs >= 1
    assert n >= fs and m >= fs

    # Horizontal rolling sum.
    tmp = np.empty((n, m), dtype=np.float64)
    tShift = fs//2
    bShift = (fs-1)//2
    for j in range(m):
        tmp[0, j] = 0.0
    for i in range(n-tShift, n):
        for j in range(m):
            tmp[0, j] += sample[i, j]
    for i in range(0, bShift+1):
        for j in range(m):
            tmp[0, j] += sample[i, j]
    for i in range(1, n):
        iTop = (i-1-tShift)%n
        iBot = (i+bShift)%n
        for j in range(m):
            tmp[i, j] = tmp[i-1, j] + (sample[iBot, j] - sample[iTop, j])

    return tmp

@nb.njit('float64[:,::1](float64[:,::1], int_[:,::1], int_)', parallel=True, fastmath=True)
def compute(sample, mask, filterSize):
    n, m = sample.shape
    tmp = horizontalRollingSum(sample, filterSize)
    neighbors_sum = verticaltalRollingSum(tmp, filterSize)
    res = np.empty((n, m), dtype=np.float64)

    for i in nb.prange(n):
        for j in range(n):
            res[i, j] = neighbors_sum[i, j] * mask[i, j]

    return res

Benchmark & Notes

Here is the testing code:

n, m = 5000, 2000
sample = np.random.rand(n, m)
mask = (np.random.rand(n, m) < 0.05).astype(int)

Here are the results on my 6-core machine:

Initial solution:           174366 ms   (x1)
With separate filters:        5710 ms   (x31)
Final Numba solution:           40 ms   (x4359)
Optimal theoretical time:       10 ms   (optimistic)

Thus, the Numba implementation is 4359 times faster than the initial one.

That being said, be careful of possible numerical issues that this last implementation can have regarding the input array (see the comments in the code). It should be fine as long as np.std(sample) is relatively small and np.all(np.isfinite(sample)) is true.

Note that the code can be further optimized: the vertical rolling sum can be parallelized; modulus operations can be avoided in the horizontal rolling sum; the vertical rolling sum and the masking steps can be merged together (ie. by computing res on-the-fly and not storing tmp); tiling can be used to compute all the steps simultaneously in a more cache-friendly way. However, these optimizations make the code more complex and some of them are very hard to perform (especially the last one with Numba).

Note that using a boolean mask (instead of an integer-based one) should make the algorithm faster since it takes less memory and processors can fetch values faster.


问:
How to outer-join two CSV files, using shell script?
I have two CSV files, like the following:

file1.csv

label,"Part-A"
"ABC mn","2.0"
"XYZ","3.0"
"PQR SN","6"
```
<p><strong>file2.csv</strong></p>
<pre class="lang-none prettyprint-override"><code>label,"Part-B"
"XYZ","4.0"
"LMN Wv","8"
"PQR SN","6"
"EFG","1.0"
</code>```

Desired Output.csv

label,"Part-A","Part-B"
"ABC mn","2.0",NA
"EFG",NA,"1.0"
"LMN Wv",NA,"8"
"PQR SN","6","6"
"XYZ","3.0","4.0"
```
<p>Currently with the below awk command i am able to combine the matching one's which have entries for label in both the files like PQR and XYZ but unable to append the ones that are not having label values present in both the files:</p>
```awk -F, 'NR==FNR{a[$1]=substr($0,length($1)+2);next} ($1 in a){print $0","a[$1]}' file1.csv file2.csv
```

答:
I would like to introduce Miller to you. It is a tool that can do a few things with a few file formats and that is available as a stand-alone binary. You just have to download the archive, put the mlr executable somewhere (preferably in your PATH) and you're done with the installation.

mlr --csv \
    join -f file1.csv -j 'label' --ul --ur \
    then \
    unsparsify --fill-with 'NA' \
    then \
    sort -f 'label' \
    file2.csv
```
<p><strong>Command parts:</strong></p>
<ul>
<li><code>mlr --csv</code><br>
means that you want to read CSV files and output a CSV format. As an other example, if you want to read CSV files and output a JSON format it would be <code>mlr --icsv --ojson</code></li>
<li><code>join -f file1.csv -j 'label' --ul --ur</code> ...... <code>file2.csv</code><br>
means to join <code>file1.csv</code> and <code>file2.csv</code> on the field <code>label</code> and emit the unmatching records of both files</li>
<li><code>then</code> is Miller's way of chaining operations</li>
<li><code>unsparsify --fill-with 'NA'</code><br>
means to create the fields that didn't exist in each file and fill them with <code>NA</code>. It's needed for the records that had a uniq label</li>
<li><code>then</code> <code>sort -f 'label'</code><br>
means to sort the records on the field <code>label</code></li>
</ul>
<hr />
<p><strong>Regarding the updated question:</strong> <code>mlr</code> handles the CSV quoting on its own. The only difference with your new expected output is that it removes the superfluous quotes:</p>
```label,Part-A,Part-B
ABC mn,2.0,NA
EFG,NA,1.0
LMN Wv,NA,8
PQR SN,6,6
XYZ,3.0,4.0
```

Body:
I have two CSV files, like the following:

file1.csv

label,"Part-A"
"ABC mn","2.0"
"XYZ","3.0"
"PQR SN","6"

file2.csv

label,"Part-B"
"XYZ","4.0"
"LMN Wv","8"
"PQR SN","6"
"EFG","1.0"

Desired Output.csv

label,"Part-A","Part-B"
"ABC mn","2.0",NA
"EFG",NA,"1.0"
"LMN Wv",NA,"8"
"PQR SN","6","6"
"XYZ","3.0","4.0"

Currently with the below awk command i am able to combine the matching one's which have entries for label in both the files like PQR and XYZ but unable to append the ones that are not having label values present in both the files:

awk -F, 'NR==FNR{a[$1]=substr($0,length($1)+2);next} ($1 in a){print $0","a[$1]}' file1.csv file2.csv

Body:
I would like to introduce Miller to you. It is a tool that can do a few things with a few file formats and that is available as a stand-alone binary. You just have to download the archive, put the mlr executable somewhere (preferably in your PATH) and you're done with the installation.

mlr --csv \
    join -f file1.csv -j 'label' --ul --ur \
    then \
    unsparsify --fill-with 'NA' \
    then \
    sort -f 'label' \
    file2.csv

Command parts:

mlr --csv

means that you want to read CSV files and output a CSV format. As an other example, if you want to read CSV files and output a JSON format it would be mlr --icsv --ojson

join -f file1.csv -j 'label' --ul --ur ...... file2.csv

means to join file1.csv and file2.csv on the field label and emit the unmatching records of both files

then is Miller's way of chaining operations

unsparsify --fill-with 'NA'

means to create the fields that didn't exist in each file and fill them with NA. It's needed for the records that had a uniq label

then sort -f 'label'

means to sort the records on the field label

Regarding the updated question: mlr handles the CSV quoting on its own. The only difference with your new expected output is that it removes the superfluous quotes:

label,Part-A,Part-B
ABC mn,2.0,NA
EFG,NA,1.0
LMN Wv,NA,8
PQR SN,6,6
XYZ,3.0,4.0


问:
Heroku, can't login: "Must authenticate with password to create client authorizations."
When I try to login to id.heroku.com, I get "Must authenticate with password to create client authorizations." after 2FA works. No clue what this means or how I fix it. If anyone has an idea of what to do, I'd appreciate it.

答: I had this issue today. Resetting my password fixed it for some reason.</p>


问:
Jira for bug tracking and customer support?
We are thinking of using Jira for bug tracking and to integrate it with Git to connect bug fixes with version handling. </p>

<p>Do you recommend Jira also for customer support or should we find another system like for example Zendesk for that purpose? I know that it is possible somehow to integrate for example Hipchat with Jira to enable chat functionality with customers but is Jira too complex for Customer Service to handle? What is your experience? </p>

答:
Do you recommend Jira also for customer support or should we find
another system like for example Zendesk for that purpose?

Full disclosure: I'm the creator of DoneDone but this question is basically why our product exists.

DoneDone is a simple bug tracker and customer support/shared inbox tool rolled into one. We use it for general customer support (both via our support email address and the contact form on our website). The shared inbox tool lets you have private discussion on emails, along with allowing you to assign, prioritize, tag, and create/change statuses on them (e.g. "Open", "In Progress", etc.)

DoneDone lets you connect customer conversations (a.k.a. incoming support email) to internal tasks. So, if your company has distinct support and client-facing people while also having internal devs and you want to separate their work, you can create any number of subtasks from an incoming conversation.

If your looking for a good way to organize internal work with customer support feedback, it might be worth signing up for a free trial.

Body:
We are thinking of using Jira for bug tracking and to integrate it with Git to connect bug fixes with version handling.

Do you recommend Jira also for customer support or should we find another system like for example Zendesk for that purpose? I know that it is possible somehow to integrate for example Hipchat with Jira to enable chat functionality with customers but is Jira too complex for Customer Service to handle? What is your experience?


问:
Sending a message to a queue on different Host in Rebus
In my setup I have two RabbitMQ servers that are used by different applications employing Rebus ESB. What I would like to know is if I can map a message to a queue on a different Host the way I can with MassTransit.

I also would like to know if I can send messages in a batch mode the same way with MassTransit.
Thanks In Advance.

答:
In my setup I have two RabbitMQ servers that are used by different applications employing Rebus ESB. What I would like to know is if I can map a message to a queue on a different Host the way I can with MassTransit.

I am not sure how this works with MassTransit, but I'm pretty sure it's not readily possible with Rebus.

With Rebus, you're encouraged to treat this as you would any other integration scenario, where you'd put a ICanSendToOtherSystem in your IoC container, which just happens to be implemented by CanSendToOtherSystemUsingRebus. Your CanSendToOtherSystemUsingRebus class would probably look somewhat like this:

public class CanSendToOtherSystemUsingRebus : ICanSendToOtherSystem, IDisposable
{
    readonly IBus _bus;

    public CanSendToOtherSystemUsingRebus(string connectionString)
    {
        _bus = Configure.With(new BuiltinHandlerActivator())
            .Transport(t => t.UseRabbitMqAsOneWayClient(connectionString))
            .Start();
    }

    public Task Send(object message) => _bus.Send(message);

    public void Dispose() => _bus.Dispose();
}
```
<p>(i.e. just something that wraps a one-way client that can connect to that other RabbitMQ host, registered as a SINGLETON in the container)</p>
<blockquote>
<p>I also would like to know if I can send messages in a batch mode the same way with MassTransit. Thanks In Advance.</p>
</blockquote>
<p>Don't know how this works with MassTransit, but with Rebus, you can give the transport more convenient circumstances for optimizing the send operation(s) by  using scopes:</p>
<pre class="lang-cs prettyprint-override"><code>using var scope = new RebusTransactionScope();

foreach (var message in lotsOfMessages)
{
    // scope is automagically detected
    await bus.Send(message);
}

await scope.CompleteAsync();
</code>```

which will improve the rate with which you can send/publish with most transports. Just remember that the scope results in queuing up messages in memory before actually sending them, so you'll probably not want to send millions of messages in each batch.

I hope that answered your questions

Body:
In my setup I have two RabbitMQ servers that are used by different applications employing Rebus ESB. What I would like to know is if I can map a message to a queue on a different Host the way I can with MassTransit.

I am not sure how this works with MassTransit, but I'm pretty sure it's not readily possible with Rebus.

With Rebus, you're encouraged to treat this as you would any other integration scenario, where you'd put a ICanSendToOtherSystem in your IoC container, which just happens to be implemented by CanSendToOtherSystemUsingRebus. Your CanSendToOtherSystemUsingRebus class would probably look somewhat like this:

public class CanSendToOtherSystemUsingRebus : ICanSendToOtherSystem, IDisposable
{
    readonly IBus _bus;

    public CanSendToOtherSystemUsingRebus(string connectionString)
    {
        _bus = Configure.With(new BuiltinHandlerActivator())
            .Transport(t => t.UseRabbitMqAsOneWayClient(connectionString))
            .Start();
    }

    public Task Send(object message) => _bus.Send(message);

    public void Dispose() => _bus.Dispose();
}

(i.e. just something that wraps a one-way client that can connect to that other RabbitMQ host, registered as a SINGLETON in the container)

I also would like to know if I can send messages in a batch mode the same way with MassTransit. Thanks In Advance.

Don't know how this works with MassTransit, but with Rebus, you can give the transport more convenient circumstances for optimizing the send operation(s) by  using scopes:

using var scope = new RebusTransactionScope();

foreach (var message in lotsOfMessages)
{
    // scope is automagically detected
    await bus.Send(message);
}

await scope.CompleteAsync();

which will improve the rate with which you can send/publish with most transports. Just remember that the scope results in queuing up messages in memory before actually sending them, so you'll probably not want to send millions of messages in each batch.

I hope that answered your questions


问:
Ordering Test Cases in Azure-Devops
The new version of Azure-DevOps no longer allows me to order Test Cases within a Test Suite. Previously there was an 'Order tests' button on the top of the view. Does anyone know how I do this in the new version, please?

答: You can click and drag the test cases in the Define tab to reorder them. It's not very discoverable, but it works just fine. Then you can sort by order as the first answer describes.</p>

Title: Ordering Test Cases in Azure-Devops


问:
Component still rendering after unmount?
I have a component that look like this where I clear the state on unmount, however this is causing me problems. After the component has unmounted, the state is successfully cleared but then I get an error saying undefined is not an object (evaluating someState.first). I don't understand why this is still being rendered after unmount, from what I understand after a component has been unmounted the component shouldn't render anymore?

```<code>const SomeComponent = () => {
  const [someState, setSomeState] = ({
    first: 'John',
    last: 'Doe'
  });

  useEffect(()=>{
    someFunction();
    return () => {setSomeState()}
  }, []);

  const someFunction = () => {
    setSomeState({
      first: 'John',
      last: 'Doe',
    });
  }

  return (
    <View>
      <Text>{someState.first + ' ' + someState.last}</Text>
    </View>
  )
}
</code>```

答:
What are you doing for unmounting the component? In react native if you are using stack navigation, components will not be unmounted until you press back or remove them from the stack. Also please make sure to check your render and change it like this:</p>
```<code>  return (
    <View>
      {someState && <Text>{someState.first + ' ' + someState.last}</Text>}
    </View>
</code>```

Body:
I have a component that look like this where I clear the state on unmount, however this is causing me problems. After the component has unmounted, the state is successfully cleared but then I get an error saying undefined is not an object (evaluating someState.first). I don't understand why this is still being rendered after unmount, from what I understand after a component has been unmounted the component shouldn't render anymore?

const SomeComponent = () => {
  const [someState, setSomeState] = ({
    first: 'John',
    last: 'Doe'
  });

  useEffect(()=>{
    someFunction();
    return () => {setSomeState()}
  }, []);

  const someFunction = () => {
    setSomeState({
      first: 'John',
      last: 'Doe',
    });
  }

  return (
    <View>
      <Text>{someState.first + ' ' + someState.last}</Text>
    </View>
  )
}

Body:
What are you doing for unmounting the component? In react native if you are using stack navigation, components will not be unmounted until you press back or remove them from the stack. Also please make sure to check your render and change it like this:

  return (
    <View>
      {someState && <Text>{someState.first + ' ' + someState.last}</Text>}
    </View>


问:
Fit ion-card to child image in ionic swiper
I'm using the swiperJs framework inside a Ionic application. In this component, with sliding image, i need the ion-card fit exactly the image width.

```<code><ion-card>
  <swiper class="horizontal-swiper" [config]="imageSwiperConfig">
    <ng-template swiperSlide *ngFor="let image of images">
      <img class="full-screen-image" src="./assets/{{image}}">
    </ng-template>
  </swiper>
</ion-card>

ion-card {
  border-radius: 2%;
  margin: auto;
  height: 100%;
}

.horizontal-swiper {
  height: 100%;
}

.full-screen-image {
  height: 100%;
  width: auto;
}

public imageSwiperConfig: SwiperOptions = {
  slidesPerView: 'auto',
  preloadImages: true,
  pagination: true,

</code>```

答:
try changing the class .full-screen-image to be like below

```<code>.full-screen-image {
  height: 100%;
  width: 100%;
  object-fit: cover;
}
</code>```

Body:
I'm using the swiperJs framework inside a Ionic application. In this component, with sliding image, i need the ion-card fit exactly the image width.

<ion-card>
  <swiper class="horizontal-swiper" [config]="imageSwiperConfig">
    <ng-template swiperSlide *ngFor="let image of images">

    </ng-template>
  </swiper>
</ion-card>

ion-card {
  border-radius: 2%;
  margin: auto;
  height: 100%;
}

.horizontal-swiper {
  height: 100%;
}

.full-screen-image {
  height: 100%;
  width: auto;
}

public imageSwiperConfig: SwiperOptions = {
  slidesPerView: 'auto',
  preloadImages: true,
  pagination: true,

Body:
try changing the class .full-screen-image to be like below

.full-screen-image {
  height: 100%;
  width: 100%;
  object-fit: cover;
}


问:
Reactor TestPublisher not working with non-completing flux
I think this is a very basic question about unit testing with project reactor (java), but I've been looking at the docs and can't figure out what my misunderstanding is. I've been trying to use TestPublisher and StepVerifier to test a flux that is supposed to be never-ending, so my scenario doesn't include a terminal signal.

Whereas using a regular sink created with Sinks.many().unicast() works as I expect, using TestPublisher doesn't:

```<code>import org.junit.jupiter.api.Test;
import reactor.core.publisher.Sinks;
import reactor.test.StepVerifier;
import reactor.test.publisher.TestPublisher;

import java.time.Duration;

public class ExploreStepVerifier {

    // this test fails: Did not observe any item or terminal signal within 1000ms in 'source(FluxSource)'
    @Test
    void test_with_test_publisher() {
        TestPublisher<String> publisher = TestPublisher.create();
        publisher.next("hello");
        var result = publisher.flux();
        StepVerifier.create(result)
            .expectNext("hello").as("initial message received")
            .verifyTimeout(Duration.ofSeconds(1));
    }

    // this test succeeds
    @Test
    void test_with_sink() {
        Sinks.Many<String> sink = Sinks.many().unicast().onBackpressureBuffer();
        sink.tryEmitNext("hello");
        var result = sink.asFlux();
        StepVerifier.create(result)
            .expectNext("hello").as("initial message received")
            .verifyTimeout(Duration.ofSeconds(1));
    }
}
</code>```

I expected that I'd be able to  substitute  TestPublisher for sink as shown in test_with_test_publisher, but it doens't work.  Can anyone explain?
Thanks--

答: That sink variant "warms up" and retains a (limited) number of signals if they occur before any subscribers comes in, whereas the TestPublisher doesnt (if nobody's listening, the value is dropped) unless you use the cold variant Test Publisher.createCold()

Body:
I think this is a very basic question about unit testing with project reactor (java), but I've been looking at the docs and can't figure out what my misunderstanding is. I've been trying to use TestPublisher and StepVerifier to test a flux that is supposed to be never-ending, so my scenario doesn't include a terminal signal.

Whereas using a regular sink created with Sinks.many().unicast() works as I expect, using TestPublisher doesn't:

import org.junit.jupiter.api.Test;
import reactor.core.publisher.Sinks;
import reactor.test.StepVerifier;
import reactor.test.publisher.TestPublisher;

import java.time.Duration;

public class ExploreStepVerifier {

    // this test fails: Did not observe any item or terminal signal within 1000ms in 'source(FluxSource)'
    @Test
    void test_with_test_publisher() {
        TestPublisher<String> publisher = TestPublisher.create();
        publisher.next("hello");
        var result = publisher.flux();
        StepVerifier.create(result)
            .expectNext("hello").as("initial message received")
            .verifyTimeout(Duration.ofSeconds(1));
    }

    // this test succeeds
    @Test
    void test_with_sink() {
        Sinks.Many<String> sink = Sinks.many().unicast().onBackpressureBuffer();
        sink.tryEmitNext("hello");
        var result = sink.asFlux();
        StepVerifier.create(result)
            .expectNext("hello").as("initial message received")
            .verifyTimeout(Duration.ofSeconds(1));
    }
}

I expected that I'd be able to  substitute  TestPublisher for sink as shown in test_with_test_publisher, but it doens't work.  Can anyone explain?
Thanks--


问:
I can't apply two rules at the same time in htaccess
and thanks to read me.
My goal is to have the same htaccess code in local and production.
First, I need to rewrite example.com/index.php?action=somepage to example.com/somepage.
Second, I must rewrite http://example.com to https://example.com, but only in production, not on localhost.
So far this is my code:

```<code>RewriteEngine on
RewriteBase /
# For Ionos
RewriteRule ^([0-9a-zA-Z/\ -]+)(?:&([0-9a-zA-Z&=_\ -]+))?$ index.php?action=$1&$2
# $1 : route name and framework parameters
# $2 : classic $_GET parameters (&param=value)
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,NE,R=301]
</code>```

When I use https:// to connect, no problem, the first rule concerning index and action apply.
When I use http://, the adress become https://, BUT the index/action rule doesn't apply.

Thanks a lot!

Edit : this works :

```<code>RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,R=301]
# For Ionos, http => https
RewriteRule ^([0-9a-zA-Z/\ -]+)(?:&([0-9a-zA-Z&=_\ -]+))?$ index.php?action=$1&$2
# $1 : route name and framework parameters
# $2 : classic $_GET parameters (&param=value)
</code>```

But I have a last problem.
My folder in like this:

```<code>[] example
...[]public
......htaccess
...htaccess
</code>```

The code shown above is the htaccess of public directory. The htaccess of example directory redirect to public:

```<code>RewriteEngine on
RewriteBase /
# for Ionos
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]
</code>```

The problem is while http://example.com redirect to https://example.com, http://example.com/somepage redirect to https://example.com/public/somepage and I can't remove the "public" part.

Thanks!

答:
Your two rules "were" in the wrong order. Your external redirect (HTTP to HTTPS) needs to be before the internal rewrite. Your first rule (rewrite) would have still applied, but it would have resulted in an external redirect to index.php?action=... (exposing your internal file/URL structure).

However, you are also missing L flags on both these rules.

```<code>RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,R=301]
</code>```

If this is in the /public/.htaccess file and the /public subdirectory is hidden (ie. it's being internally rewritten to) then you need to change the RewriteRule to read:

```<code>RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
</code>```

After the request is internally rewritten by the parent config, the REQUEST_URI server variable contains the full URL-path, including the "hidden" /public subdirectory, so if you redirect to REQUEST_URI it will expose the hidden subdirectory. Whereas, if you use a backreference to the matched RewriteRule pattern, which matches against a URL-path that is relative to the current directory then this naturally excludes the /public subdirectory.

Body:
and thanks to read me.
My goal is to have the same htaccess code in local and production.
First, I need to rewrite example.com/index.php?action=somepage to example.com/somepage.
Second, I must rewrite http://example.com to https://example.com, but only in production, not on localhost.
So far this is my code:

RewriteEngine on
RewriteBase /
# For Ionos
RewriteRule ^([0-9a-zA-Z/\ -]+)(?:&([0-9a-zA-Z&=_\ -]+))?$ index.php?action=$1&$2
# $1 : route name and framework parameters
# $2 : classic $_GET parameters (&param=value)
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,NE,R=301]

When I use https:// to connect, no problem, the first rule concerning index and action apply.
When I use http://, the adress become https://, BUT the index/action rule doesn't apply.

Thanks a lot!

Edit : this works :

RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,R=301]
# For Ionos, http => https
RewriteRule ^([0-9a-zA-Z/\ -]+)(?:&([0-9a-zA-Z&=_\ -]+))?$ index.php?action=$1&$2
# $1 : route name and framework parameters
# $2 : classic $_GET parameters (&param=value)

But I have a last problem.
My folder in like this:

[] example
...[]public
......htaccess
...htaccess

The code shown above is the htaccess of public directory. The htaccess of example directory redirect to public:

RewriteEngine on
RewriteBase /
# for Ionos
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]

The problem is while http://example.com redirect to https://example.com, http://example.com/somepage redirect to https://example.com/public/somepage and I can't remove the "public" part.

Thanks!

Body:
Your two rules "were" in the wrong order. Your external redirect (HTTP to HTTPS) needs to be before the internal rewrite. Your first rule (rewrite) would have still applied, but it would have resulted in an external redirect to index.php?action=... (exposing your internal file/URL structure).

However, you are also missing L flags on both these rules.

RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,R=301]

If this is in the /public/.htaccess file and the /public subdirectory is hidden (ie. it's being internally rewritten to) then you need to change the RewriteRule to read:

RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]

After the request is internally rewritten by the parent config, the REQUEST_URI server variable contains the full URL-path, including the "hidden" /public subdirectory, so if you redirect to REQUEST_URI it will expose the hidden subdirectory. Whereas, if you use a backreference to the matched RewriteRule pattern, which matches against a URL-path that is relative to the current directory then this naturally excludes the /public subdirectory.


问:
Python MySQL Docker error: Unknown database named main when migrating
I am trying to migrate my python changes to my docker project, however when I try to run the command python manage.py db migrate I get the error unknown database 'main', however when I look inside of my docker-compose.yml file I see that main is indeed defined inside of the MYSQL_DATABASE variable inside of the container db. I have tried some solutions found on StackOverflow as well as Github like getting the restart: always out of my docker-compose.yml script and making a Windows PowerShell script that will run to restart my docker container as found here: MYSQL Docker container gives "unknown database" error, and trying to change my DATA_SAVE_PATH variable and other such variables in my docker-compose.yml: https://github.com/laradock/laradock/issues/1017 and I have also tried to change the MYSQL_DATABASE variable to a different name but that doesn't work either.

Here is the full error that I am receiving when I run my code:

```<code>sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (1049, "Unknown database 'main'")
(Background on this error at: http://sqlalche.me/e/13/e3q8)
</code>```

Here is my docker-compose.yml script:

```<code>version: '3.9'
services:
  backend:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - 8001:5000
    volumes:
      - .:/app
    depends_on:
      - db

  db:
    image: mysql:5.7.22
    restart: always
    environment:
      MYSQL_DATABASE: main
      MYSQL_USER: root
      MYSQL_PASSWORD: root
      MYSQL_ROOT_PASSWORD: root
    volumes:
      - .dbdata:/var/lib/mysql
    ports:
      - 33067:3306
</code>```

Here is my Dockerfile:

```<code>FROM python:3.9
ENV PYTHONUNBUFFERED 1
WORKDIR /app
COPY requirements.txt /app/requirements.txt
RUN pip install -r requirements.txt
COPY . /app
CMD python main.py
</code>```

Here is my main.py file:

```<code>from flask_cors import CORS
from sqlalchemy import UniqueConstraint
from vegaaimain.vegamain import main
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql://root:root@db/main'
CORS(app)

db = SQLAlchemy(app)

class VegaScriptRun(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=False)
    title = db.Column(db.String(200))
    description = db.Column(db.String(400))
    image = db.Column(db.String(200))
    main()

class VegaScriptUser(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer)
    title = db.Column(db.String(200))
    description = db.Column(db.String(400))
    image = db.Column(db.String(200))

    UniqueConstraint('user_id', 'title', 'description', 'image', name='user_experiment_unique')
@app.route('/')
def index():
    return 'Hello'

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
</code>```

And finally my manage.py file, and requirements.txt file:

```<code>from main import app, db
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager

migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()
</code>```

requirements.txt

```<code>Flask==1.1.2
Flask-SQLAlchemy==2.4.4
SQLAlchemy==1.3.20
Flask-Migrate==3.0.0
Flask-Script==2.0.6
Flask-Cors==3.0.9
requests==2.25.0
mysqlclient==2.0.1
pika==1.1.0
wolframalpha==5.0.0
</code>```

What exactly am I missing or doing wrong here, thank you!

答:
I solved this problem by looking in my .dbdata folder and found my service, I then changed the MYSQL_DATABASE variable and the app configuration to the same variable as MYSQL_DATABASE which was vegatest instead of main.

So I ran the same command python manager.py db migrate and I got a successful migration.

Body:
I am trying to migrate my python changes to my docker project, however when I try to run the command python manage.py db migrate I get the error unknown database 'main', however when I look inside of my docker-compose.yml file I see that main is indeed defined inside of the MYSQL_DATABASE variable inside of the container db. I have tried some solutions found on StackOverflow as well as Github like getting the restart: always out of my docker-compose.yml script and making a Windows PowerShell script that will run to restart my docker container as found here: MYSQL Docker container gives "unknown database" error, and trying to change my DATA_SAVE_PATH variable and other such variables in my docker-compose.yml: https://github.com/laradock/laradock/issues/1017 and I have also tried to change the MYSQL_DATABASE variable to a different name but that doesn't work either.

Here is the full error that I am receiving when I run my code:

sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (1049, "Unknown database 'main'")
(Background on this error at: http://sqlalche.me/e/13/e3q8)

Here is my docker-compose.yml script:

version: '3.9'
services:
  backend:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - 8001:5000
    volumes:
      - .:/app
    depends_on:
      - db

  db:
    image: mysql:5.7.22
    restart: always
    environment:
      MYSQL_DATABASE: main
      MYSQL_USER: root
      MYSQL_PASSWORD: root
      MYSQL_ROOT_PASSWORD: root
    volumes:
      - .dbdata:/var/lib/mysql
    ports:
      - 33067:3306

Here is my Dockerfile:

FROM python:3.9
ENV PYTHONUNBUFFERED 1
WORKDIR /app
COPY requirements.txt /app/requirements.txt
RUN pip install -r requirements.txt
COPY . /app
CMD python main.py

Here is my main.py file:

from flask_cors import CORS
from sqlalchemy import UniqueConstraint
from vegaaimain.vegamain import main
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql://root:root@db/main'
CORS(app)

db = SQLAlchemy(app)

class VegaScriptRun(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=False)
    title = db.Column(db.String(200))
    description = db.Column(db.String(400))
    image = db.Column(db.String(200))
    main()

class VegaScriptUser(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer)
    title = db.Column(db.String(200))
    description = db.Column(db.String(400))
    image = db.Column(db.String(200))

    UniqueConstraint('user_id', 'title', 'description', 'image', name='user_experiment_unique')
@app.route('/')
def index():
    return 'Hello'

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

And finally my manage.py file, and requirements.txt file:

from main import app, db
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager

migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()

requirements.txt

Flask==1.1.2
Flask-SQLAlchemy==2.4.4
SQLAlchemy==1.3.20
Flask-Migrate==3.0.0
Flask-Script==2.0.6
Flask-Cors==3.0.9
requests==2.25.0
mysqlclient==2.0.1
pika==1.1.0
wolframalpha==5.0.0

What exactly am I missing or doing wrong here, thank you!


问:
Show this custom text in one specific category
How to alter this custom text, so it will only be shown in one specific category, let's say: ONLY in category: tables?

add_action( 'woocommerce_after_shop_loop_item', 'show_meer_varianten_loop', 100 );
function show_meer_varianten_loop() { ?>

✓ Meer varianten

    <?php
}
```
<p>in css:</p>
<pre class="lang-php prettyprint-override"><code>.products .product:not(.product-type-variable) .custom-label-variable {
    display: none;
}
</code>```

答:
Try this..I think it works ..</p>
```<code>add_action(
'woocommerce_after_shop_loop_item',
'show_meer_varianten_loop', 100 );
function show_meer_varianten_loop()
{
global $product;
if ( has_term( 'tables',
'product_cat', $product->ID ) ) { ?>
 <div class="custom-label-
  variable">✓ Meer varianten</div>
  <?php
}
}
</code>```

Body:
How to alter this custom text, so it will only be shown in one specific category, let's say: ONLY in category: tables?

add_action( 'woocommerce_after_shop_loop_item', 'show_meer_varianten_loop', 100 );
function show_meer_varianten_loop() { ?>

✓ Meer varianten

    <?php
}

in css:

.products .product:not(.product-type-variable) .custom-label-variable {
    display: none;
}

Body:
Try this..I think it works ..

add_action(
'woocommerce_after_shop_loop_item',
'show_meer_varianten_loop', 100 );
function show_meer_varianten_loop()
{
global $product;
if ( has_term( 'tables',
'product_cat', $product->ID ) ) { ?>
 <div class="custom-label-
  variable">✓ Meer varianten</div>
  <?php
}
}


问:
Dynamic routing svelte
I am trying to build a simple blog with Svelte and Strapi v4 as backend.
I have 2 pages : list of all posts page (no problem here) and the post page (problem here).
For the list of posts, I manage to fetch my datas from Strapi using onMount. Works fine.

```<code><script>
import { onMount } from "svelte";

let posts = []

onMount(async() => {
        const response = await fetch('http://localhost:1337/api/blogs')
        posts = await response.json()
}) //etc...
</code>```

The link to go to the specific post page [id].svelte works :

```<code><p class="link"><a href={`/blog/${post.id}`}>En savoir plus >>></a></p>
</code>```

But I get then an error. I don't manage to tell Svelte : fetch this specific id datas in the [id].svelte page.
Using the below code in [id].svelte does not work, I get a 404 in the console.

```<code><script>
import { page } from '$app/stores';
console.log(page)
</code>```

I also tried with this method with no success :

```<code>    <script context="module">
export async function load(context = useContext(contextValue)) {
    console.log(context);
</code>```

I am blocked and don't know how to move forward. Getting also lost between SvelteKit, Svelte...
Thanks for your great help.

Here is the file tree of the route :

I am also using svelte-routing in my App.svelte file. I use this below code trying to tell Svelte to find my [id] page. But I always get a return saying the page is not found on the server...

```<code><!-- App.svelte -->
<script>
  import { Router, Route } from "svelte-routing";

  import Index from "./App.svelte";
  import id from "./blog/[id].svelte";

  export let url = "";
</script>

<Router url="{url}">

  <Route path="blog/:id" let:params>
  <posteid id="{params.id}" /></Route>
  <Route path="/" component="{Index}" />
</Router>`
</code>```

答:
Thank you @johannchopin.
I can now access my [id].svelte page, using this route in my app.svelte :

```<code><Route path="blog/:id" let:params/>
</code>```

The link to the specific [id] works fine. Don't really know if "let:params" is the correct parameter to use here in my case.

However, I am still totally blocked whatever the method in trying to get the specific data of a specific [id].

Example 1 : does not work =>

```<code> <script>
  export const load = async context => {
console.log('context', context)}
</script>
</code>```

I get nothing in the console, no 'context'.

Example 2 : does not work =>

```<code>       <script context = "module">
  export async function load({ fetch, page }) {
  const id = page.params.id
  const res = await fetch(`http://localhost:1337/api/blogs/${id}`)
  const blogpost = await res.json()

  if (res.ok) {
    return {
      props: {
        blogpost
      }
    }
  }
}

</code>```

Example 3 : does not work =>

```<code><script>
      import { onMount } from "svelte";

let blogpost = []

    onMount(async () => {
      const response  = await fetch('http://localhost:1337/api/blogs/${id}')
        blogpost = await response.json()
        console.log(blogpost)
    }   )

</script>
</code>```

No blogpost in the console. I think this is because "id" is not defined, but I don't know how to declare it, get this "id" and fetch this specific data actually.

Cannot see the solution. I am sorry for my ignorance.

Title: Dynamic routing svelte

Body:
I am trying to build a simple blog with Svelte and Strapi v4 as backend.
I have 2 pages : list of all posts page (no problem here) and the post page (problem here).
For the list of posts, I manage to fetch my datas from Strapi using onMount. Works fine.

<Router url="{url}">

  <Route path="blog/:id" let:params>
  <posteid id="{params.id}" /></Route>
  <Route path="/" component="{Index}" />
</Router>`

Body:
Thank you @johannchopin.
I can now access my [id].svelte page, using this route in my app.svelte :

<Route path="blog/:id" let:params/>

The link to the specific [id] works fine. Don't really know if "let:params" is the correct parameter to use here in my case.

However, I am still totally blocked whatever the method in trying to get the specific data of a specific [id].

Example 1 : does not work =>

 <script>
  export const load = async context => {
console.log('context', context)}
</script>

I get nothing in the console, no 'context'.

Example 2 : does not work =>

       <script context = "module">
  export async function load({ fetch, page }) {
  const id = page.params.id
  const res = await fetch(`http://localhost:1337/api/blogs/${id}`)
  const blogpost = await res.json()

  if (res.ok) {
    return {
      props: {
        blogpost
      }
    }
  }
}

Example 3 : does not work =>

<script>
      import { onMount } from "svelte";

let blogpost = []

    onMount(async () => {
      const response  = await fetch('http://localhost:1337/api/blogs/${id}')
        blogpost = await response.json()
        console.log(blogpost)
    }   )

</script>

No blogpost in the console. I think this is because "id" is not defined, but I don't know how to declare it, get this "id" and fetch this specific data actually.

Cannot see the solution. I am sorry for my ignorance.


问:
How do i pass a javascript object in an input feild
hello i am trying to map items stored in my redux into a form . I created a component called PAYMENT.js that gives a format of how the item should be arranged
THIS IS A REACT PROJECT

PAYMENT.JS

```<code>import React from "react";

function Payment({ name, price, count, itemSize }) {

  return (
    <div>
      <p> {name}, {itemSize}, {count} </p>
    </div>
  );
}

export default Payment;
</code>```

I want it to be mapped in an input feild , this feild would be readable .

Here is it

```<code><div class="telephone">
                <label for="name"></label>
                <input
                  className="payment_form"
                  type="text"
                  placeholder="My address"
                  name="telephone"
                  value={items.map((item, id) => (
                    <Payment
                      id={items.id}
                      key={id}
                      name={item.name}
                      price={item.price}
                      size={item.size}
                      image1={item.image1}
                      itemSize={item.itemSize}
                      count={item.count}
                    />
                  ))}
                  id="telephone_input"
                  required
                />
              </div>
</code>```

i get [OBJECT , OBJECT ][OBJECT , OBJECT ]
Instead of the actual object . Putting the map function in a p tag and iget the value of the items in the redux

```<code><p>
                {" "}
                {items.map((item, id) => (
                  <Payment
                    id={items.id}
                    key={id}
                    name={item.name}
                    price={item.price}
                    size={item.size}
                    image1={item.image1}
                    itemSize={item.itemSize}
                    count={item.count}
                  />
                ))}
              </p>
</code>```

OUTPUT
Von dutch pink, Xtra large, 1

Von dutch camoeo, Xtra large, 2

Von dutch pink, Xtra large, 3

I want this out put to show in the input feild so i can send it over

答: note that you should not give the attribute "value" an array value because a value attribute must be a string</p>

Body:
hello i am trying to map items stored in my redux into a form . I created a component called PAYMENT.js that gives a format of how the item should be arranged
THIS IS A REACT PROJECT

PAYMENT.JS

import React from "react";

function Payment({ name, price, count, itemSize }) {

  return (

 {name}, {itemSize}, {count}

  );
}

export default Payment;

I want it to be mapped in an input feild , this feild would be readable .

Here is it

                <input
                  className="payment_form"
                  type="text"
                  placeholder="My address"
                  name="telephone"
                  value={items.map((item, id) => (
                    <Payment
                      id={items.id}
                      key={id}
                      name={item.name}
                      price={item.price}
                      size={item.size}
                      image1={item.image1}
                      itemSize={item.itemSize}
                      count={item.count}
                    />
                  ))}
                  id="telephone_input"
                  required
                />

i get [OBJECT , OBJECT ][OBJECT , OBJECT ]
Instead of the actual object . Putting the map function in a p tag and iget the value of the items in the redux

                {" "}
                {items.map((item, id) => (
                  <Payment
                    id={items.id}
                    key={id}
                    name={item.name}
                    price={item.price}
                    size={item.size}
                    image1={item.image1}
                    itemSize={item.itemSize}
                    count={item.count}
                  />
                ))}

OUTPUT
Von dutch pink, Xtra large, 1

Von dutch camoeo, Xtra large, 2

Von dutch pink, Xtra large, 3

I want this out put to show in the input feild so i can send it over


问:
Access JSON Array without array name
I have a JSON object:

```<code>{
   "login_name":"hello@gmail.com",
   "login_pass":"abc123",
   "created_on":"2021-01-17 19:20:07",
   "user_id":"1",
   "active":"1"
}
</code>```

I don't know how to access it because it doesn't have a name.
This is using Volley:

```<code>val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
    { response ->
        val obj = JSONObject(response.toString()) // this works and outputs the JSON object
        val test: JSONObject = obj.getJSONObject("login_name") // this doesn't work

        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
    },
    { error ->
        Toast.makeText(this@Login, "Error!", Toast.LENGTH_LONG).show()
    }
)
</code>```

I also tried converting the Json object to an array but that didn't work either...

Looked at:
Get JSONArray without array name, How can i write Android Json parsing without array name

EDIT:

```<code>val obj = JSONObject(response)
</code>```

That didn't work for me because:
None of the following functions can be called with the arguments supplied.
(String!) defined in org.json.JSONObject
((MutableMap<Any?, Any?>..Map<*, *>?)) defined in org.json.JSONObject
(JSONTokener!) defined in org.json.JSONObject

But after 2 days of trying, this worked... Didn't think I could just do that

```<code>val test = response.getString("login_name")
</code>```

答:
response is indeed a jsonObject, you could use it without know its name:

```<code>String login_name= response.getString("login_name");
</code>```

Title: Access JSON Array without array name

Body:
I have a JSON object:

{
   "login_name":"hello@gmail.com",
   "login_pass":"abc123",
   "created_on":"2021-01-17 19:20:07",
   "user_id":"1",
   "active":"1"
}

I don't know how to access it because it doesn't have a name.
This is using Volley:

val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
    { response ->
        val obj = JSONObject(response.toString()) // this works and outputs the JSON object
        val test: JSONObject = obj.getJSONObject("login_name") // this doesn't work

        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
    },
    { error ->
        Toast.makeText(this@Login, "Error!", Toast.LENGTH_LONG).show()
    }
)

I also tried converting the Json object to an array but that didn't work either...

Looked at:
Get JSONArray without array name, How can i write Android Json parsing without array name

EDIT:

val obj = JSONObject(response)

That didn't work for me because:
None of the following functions can be called with the arguments supplied.
(String!) defined in org.json.JSONObject
((MutableMap<Any?, Any?>..Map<*, *>?)) defined in org.json.JSONObject
(JSONTokener!) defined in org.json.JSONObject

But after 2 days of trying, this worked... Didn't think I could just do that

val test = response.getString("login_name")

Body:
response is indeed a jsonObject, you could use it without know its name:

String login_name= response.getString("login_name");


问:
How to match a value in one column to another column based on hierarchy level
I have a table that contains 4 columns: entry_id, NAME, type, upper_id.

Each entry_id corresponds to a specific upper_id. There can be many different entry_id's that correspond to SAME upper_id. The column type represent the level of that entry in terms of hierarchy.

```<code>1 --> First level
2 --> Second level
3 --> Third level
</code>```

I need to match what is in the upper_id to the entry_id in order to add another column for upper_name which will be found in the same table column name. In the example above, if upper_id = '1001' for an entry_id, I need to find this value in the entry_id and grab the name found.

An entry_id with type = '1' will always have an upper_id that has a value in the entry_id with a type = '2'. And an entry_id with a type = '2' will always have an upper id that has a value in entry_id with a type = '3'. An entry_id with type = '3' will never have an upper_id, and its upper_name column will be NULL.

The results will  look like this:

```<code>CREATE TABLE TBL_1
(     ENTRY_ID int,
      NAME string,
      TYPE int,
      UPPER_ID int
);

INSERT INTO TBL_1
values
(1234,'bichon',1,'1001'),
(1124,'yorkie',1,'1001'),
(1009,'golden',1,'1001'),
(6722,'poodle',1,'1001'),
(1001,'canine',2,'2002'),
(2002,'animal',3,NULL)
</code>```

Do you know how I can formulate a query that allows me to include an "upper_name" column from the data already in the table?

答:
LEFT JOIN is the key.

```<code>WITH table_data (ENTRY_ID, NAME, TYPE, UPPER_ID) AS (
  SELECT *
  FROM values
    (1234,'bichon',1,1001),
    (1124,'yorkie',1,1001),
    (1009,'golden',1,1001),
    (6722,'poodle',1,1001),
    (1001,'canine',2,2002),
    (2002,'animal',3,NULL)
)
SELECT t1.*,
    t2.name as upper_name
FROM table_data AS t1
LEFT JOIN table_data AS t2
    ON t1.UPPER_ID = t2.ENTRY_ID
        AND t1.type +1 = t2.type
</code>```

gives:

ENTRY_ID
NAME
TYPE
UPPER_ID
UPPER_NAME

1234
bichon
1
1001
canine

1124
yorkie
1
1001
canine

1009
golden
1
1001
canine

6722
poodle
1
1001
canine

1001
canine
2
2002
animal

2002
animal
3

Body:
I have a table that contains 4 columns: entry_id, NAME, type, upper_id.

Each entry_id corresponds to a specific upper_id. There can be many different entry_id's that correspond to SAME upper_id. The column type represent the level of that entry in terms of hierarchy.

1 --> First level
2 --> Second level
3 --> Third level

I need to match what is in the upper_id to the entry_id in order to add another column for upper_name which will be found in the same table column name. In the example above, if upper_id = '1001' for an entry_id, I need to find this value in the entry_id and grab the name found.

An entry_id with type = '1' will always have an upper_id that has a value in the entry_id with a type = '2'. And an entry_id with a type = '2' will always have an upper id that has a value in entry_id with a type = '3'. An entry_id with type = '3' will never have an upper_id, and its upper_name column will be NULL.

The results will  look like this:

CREATE TABLE TBL_1
(     ENTRY_ID int,
      NAME string,
      TYPE int,
      UPPER_ID int
);

INSERT INTO TBL_1
values
(1234,'bichon',1,'1001'),
(1124,'yorkie',1,'1001'),
(1009,'golden',1,'1001'),
(6722,'poodle',1,'1001'),
(1001,'canine',2,'2002'),
(2002,'animal',3,NULL)

Do you know how I can formulate a query that allows me to include an "upper_name" column from the data already in the table?

Body:
LEFT JOIN is the key.

WITH table_data (ENTRY_ID, NAME, TYPE, UPPER_ID) AS (
  SELECT *
  FROM values
    (1234,'bichon',1,1001),
    (1124,'yorkie',1,1001),
    (1009,'golden',1,1001),
    (6722,'poodle',1,1001),
    (1001,'canine',2,2002),
    (2002,'animal',3,NULL)
)
SELECT t1.*,
    t2.name as upper_name
FROM table_data AS t1
LEFT JOIN table_data AS t2
    ON t1.UPPER_ID = t2.ENTRY_ID
        AND t1.type +1 = t2.type

gives:

ENTRY_ID
NAME
TYPE
UPPER_ID
UPPER_NAME

1234
bichon
1
1001
canine

1124
yorkie
1
1001
canine

1009
golden
1
1001
canine

6722
poodle
1
1001
canine

1001
canine
2
2002
animal

2002
animal
3