问:
Marker Clustering Not Showing using PHP and MYSQL
I have copied this code from the google map API documentation (Using MySQL and PHP with Google Maps). the markers are showing but I cant get the Marker Clustering to work.

I have 1000s of markers and the example google has given looks like its just for couple of markers. My map is too full of markers making it difficult to click on the correct ones.

I have copied the example into fiddle. The API key is not set but the code is the same in my project.

var customLabel = {
        restaurant: {
          label: 'R'
        },
        bar: {
          label: 'B'
        }
      };

        function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          center: new google.maps.LatLng(-33.863276, 151.207977),
          zoom: 12
        });
        var infoWindow = new google.maps.InfoWindow;

          // Change this depending on the name of your PHP or XML file
          downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName('marker');
            Array.prototype.forEach.call(markers, function(markerElem) {
              var id = markerElem.getAttribute('id');
              var name = markerElem.getAttribute('name');
              var address = markerElem.getAttribute('address');
              var type = markerElem.getAttribute('type');
              var point = new google.maps.LatLng(parseFloat(markerElem.getAttribute('lat')),parseFloat(markerElem.getAttribute('lng')));
              var infowincontent = document.createElement('div');
              var strong = document.createElement('strong');
              strong.textContent = name
              infowincontent.appendChild(strong);                     infowincontent.appendChild(document.createElement('br'));
              var text = document.createElement('text');
              text.textContent = address
              infowincontent.appendChild(text);
              var icon = customLabel[type] || {};
              var marker = new google.maps.Marker({
                map: map,
                position: point,
                label: icon.label
              });
              marker.addListener('click', function() {
                infoWindow.setContent(infowincontent);
                infoWindow.open(map, marker);
              });
            });
          });
        }
      function downloadUrl(url, callback) {
        var request = window.ActiveXObject ?
            new ActiveXObject('Microsoft.XMLHTTP') :
            new XMLHttpRequest;
        request.onreadystatechange = function() {
          if (request.readyState == 4) {
            request.onreadystatechange = doNothing;
            callback(request, request.status);
          }
        };
        request.open('GET', url, true);
        request.send(null);
      }
      function doNothing() {}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }</code>```

```

答:
Works for me if I add the markerclusterer to that example

proof of concept fiddle

updated code snippet:

var customLabel = {
  restaurant: {
    label: 'R'
  },
  bar: {
    label: 'B'
  }
};

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: new google.maps.LatLng(-33.863276, 151.207977),
    zoom: 12
  });
  var infoWindow = new google.maps.InfoWindow;

  // Change this depending on the name of your PHP or XML file
  downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
    var xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName('marker');
    var markerCluster = new MarkerClusterer(map, [], {
      imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
    });
    Array.prototype.forEach.call(markers, function(markerElem) {
      var id = markerElem.getAttribute('id');
      var name = markerElem.getAttribute('name');
      var address = markerElem.getAttribute('address');
      var type = markerElem.getAttribute('type');
      var point = new google.maps.LatLng(parseFloat(markerElem.getAttribute('lat')), parseFloat(markerElem.getAttribute('lng')));
      var infowincontent = document.createElement('div');
      var strong = document.createElement('strong');
      strong.textContent = name
      infowincontent.appendChild(strong);
      infowincontent.appendChild(document.createElement('br'));
      var text = document.createElement('text');
      text.textContent = address
      infowincontent.appendChild(text);
      var icon = customLabel[type] || {};
      var marker = new google.maps.Marker({
        map: map,
        position: point,
        label: icon.label
      });
      marker.addListener('click', function() {
        infoWindow.setContent(infowincontent);
        infoWindow.open(map, marker);
      });
      markerCluster.addMarker(marker);
    });
  });
}

function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
    new ActiveXObject('Microsoft.XMLHTTP') :
    new XMLHttpRequest;
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request, request.status);
    }
  };
  request.open('GET', url, true);
  request.send(null);
}

function doNothing() {}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}</code>```

```

Body:
I have copied this code from the google map API documentation (Using MySQL and PHP with Google Maps). the markers are showing but I cant get the Marker Clustering to work.

I have 1000s of markers and the example google has given looks like its just for couple of markers. My map is too full of markers making it difficult to click on the correct ones.

I have copied the example into fiddle. The API key is not set but the code is the same in my project.

var customLabel = {
        restaurant: {
          label: 'R'
        },
        bar: {
          label: 'B'
        }
      };

        function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          center: new google.maps.LatLng(-33.863276, 151.207977),
          zoom: 12
        });
        var infoWindow = new google.maps.InfoWindow;

          // Change this depending on the name of your PHP or XML file
          downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName('marker');
            Array.prototype.forEach.call(markers, function(markerElem) {
              var id = markerElem.getAttribute('id');
              var name = markerElem.getAttribute('name');
              var address = markerElem.getAttribute('address');
              var type = markerElem.getAttribute('type');
              var point = new google.maps.LatLng(parseFloat(markerElem.getAttribute('lat')),parseFloat(markerElem.getAttribute('lng')));
              var infowincontent = document.createElement('div');
              var strong = document.createElement('strong');
              strong.textContent = name
              infowincontent.appendChild(strong);                     infowincontent.appendChild(document.createElement('br'));
              var text = document.createElement('text');
              text.textContent = address
              infowincontent.appendChild(text);
              var icon = customLabel[type] || {};
              var marker = new google.maps.Marker({
                map: map,
                position: point,
                label: icon.label
              });
              marker.addListener('click', function() {
                infoWindow.setContent(infowincontent);
                infoWindow.open(map, marker);
              });
            });
          });
        }
      function downloadUrl(url, callback) {
        var request = window.ActiveXObject ?
            new ActiveXObject('Microsoft.XMLHTTP') :
            new XMLHttpRequest;
        request.onreadystatechange = function() {
          if (request.readyState == 4) {
            request.onreadystatechange = doNothing;
            callback(request, request.status);
          }
        };
        request.open('GET', url, true);
        request.send(null);
      }
      function doNothing() {}

/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }

Body:
Works for me if I add the markerclusterer to that example

proof of concept fiddle

updated code snippet:

var customLabel = {
  restaurant: {
    label: 'R'
  },
  bar: {
    label: 'B'
  }
};

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: new google.maps.LatLng(-33.863276, 151.207977),
    zoom: 12
  });
  var infoWindow = new google.maps.InfoWindow;

  // Change this depending on the name of your PHP or XML file
  downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
    var xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName('marker');
    var markerCluster = new MarkerClusterer(map, [], {
      imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
    });
    Array.prototype.forEach.call(markers, function(markerElem) {
      var id = markerElem.getAttribute('id');
      var name = markerElem.getAttribute('name');
      var address = markerElem.getAttribute('address');
      var type = markerElem.getAttribute('type');
      var point = new google.maps.LatLng(parseFloat(markerElem.getAttribute('lat')), parseFloat(markerElem.getAttribute('lng')));
      var infowincontent = document.createElement('div');
      var strong = document.createElement('strong');
      strong.textContent = name
      infowincontent.appendChild(strong);
      infowincontent.appendChild(document.createElement('br'));
      var text = document.createElement('text');
      text.textContent = address
      infowincontent.appendChild(text);
      var icon = customLabel[type] || {};
      var marker = new google.maps.Marker({
        map: map,
        position: point,
        label: icon.label
      });
      marker.addListener('click', function() {
        infoWindow.setContent(infowincontent);
        infoWindow.open(map, marker);
      });
      markerCluster.addMarker(marker);
    });
  });
}

function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
    new ActiveXObject('Microsoft.XMLHTTP') :
    new XMLHttpRequest;
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request, request.status);
    }
  };
  request.open('GET', url, true);
  request.send(null);
}

function doNothing() {}

/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
<script async defer src="https://cdnjs.cloudflare.com/ajax/libs/markerclustererplus/2.1.4/markerclusterer.min.js"></script>
<div id="map"></div>


来源: stackexchange

问:
Holy Grail Technique - Problem with Left Container Float
The Container Left is not visible.
I am using Holy Grail Technique.

How can I get it correct? How can I align them?

When I remove margin-left : -100% it the Container Left comes in display but it is not align with other Center and Right Containers.

In CSS file, (*) , I read about this, to solve when left width gets into negative and disappears, we can do this to get into visual point.

* {
  margin: 0;
  padding: 0;
}

body {
  min-width: 630px;
}

.container {
  padding-left: 200px;
  padding-right: 190px;
  overflow: hidden;
}

.container .column {
  position: relative;
  float: left;
}

.center {
  padding: 10px 20px;
  background-color: chartreuse;
  width: 100%;
}

.left {
  background-color: aqua;
  padding: 10px 10px;
  width: 180px;
  right: 240px;
  margin-left: -100%;
}

.right {
  background-color: blueviolet;
  padding: 10px 10px;
  width: 130px;
  margin-right: -190px;
}

.footer {
  clear: both;
}

* html .left {   /* (*) */
  left: 150px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="header">Header</header>
<div class="container">
  <div class="left column">Container Left</div>
  <div class="center column">Container Center</div>
  <div class="right column">Container Right</div>
</div>
<footer class="footer">Footer</footer></code>```

答:
According to my understanding,your let container is not visisble.Do add on your preference on the code below

* {
  margin: 0;
  padding: 0;
}

.container {
  width: 100vw;
  display: flex;
  flex-direction: row;
  align-items: stretch;
}

.column {
  flex-grow: 1;
}

.center {
  padding: 10px 20px;
  background-color: chartreuse;
}

.left {
  background-color: aqua;
  padding: 10px 10px;
}

.right {
  background-color: blueviolet;
  padding: 10px 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="header">Header</header>
<div class="container">
  <div class="left column">Container Left</div>
  <div class="center column">Container Center</div>
  <div class="right column">Container Right</div>
</div>
<footer class="footer">Footer</footer></code>```

ContentLicense: CC BY-SA 4.0

Body:
The Container Left is not visible.
I am using Holy Grail Technique.

How can I get it correct? How can I align them?

When I remove margin-left : -100% it the Container Left comes in display but it is not align with other Center and Right Containers.

In CSS file, (*) , I read about this, to solve when left width gets into negative and disappears, we can do this to get into visual point.

* {
  margin: 0;
  padding: 0;
}

body {
  min-width: 630px;
}

.container {
  padding-left: 200px;
  padding-right: 190px;
  overflow: hidden;
}

.container .column {
  position: relative;
  float: left;
}

.center {
  padding: 10px 20px;
  background-color: chartreuse;
  width: 100%;
}

.left {
  background-color: aqua;
  padding: 10px 10px;
  width: 180px;
  right: 240px;
  margin-left: -100%;
}

.right {
  background-color: blueviolet;
  padding: 10px 10px;
  width: 130px;
  margin-right: -190px;
}

.footer {
  clear: both;
}

* html .left {   /* (*) */
  left: 150px;
}

Header

Container Left

Container Center

Container Right

Footer

Body:
According to my understanding,your let container is not visisble.Do add on your preference on the code below

* {
  margin: 0;
  padding: 0;
}

.container {
  width: 100vw;
  display: flex;
  flex-direction: row;
  align-items: stretch;
}

.column {
  flex-grow: 1;
}

.center {
  padding: 10px 20px;
  background-color: chartreuse;
}

.left {
  background-color: aqua;
  padding: 10px 10px;
}

.right {
  background-color: blueviolet;
  padding: 10px 10px;
}

<header class="header">Header</header>
<div class="container">
  <div class="left column">Container Left</div>
  <div class="center column">Container Center</div>
  <div class="right column">Container Right</div>
</div>
<footer class="footer">Footer</footer>


问:
Is there a way to optimize that code? TCP-server in Go
coders. Here is the basic tcp-server, that accepts connection, reads the incoming data and writes back.

```<code>    package main

    import (
        "bufio"
        "io"
        "log"
        "net"
    )

    func main() {
        li, err := net.Listen("tcp", ":8080")
        if err != nil {
            log.Fatalln(err)
        }

        defer li.Close()

        for {
            conn, err := li.Accept()
            if err != nil {
                log.Fatalln(err)
            }

            scanner := bufio.NewScanner(conn)

            for scanner.Scan() {
                ln := scanner.Text()
                io.WriteString(conn, ln+"\n")
            }

            conn.Close()
        }

    }

</code>```

However, there is a nested loop for scanner and declaring new scanner on each iteration of external loop. I heard, that nested loops lead to extra complexety and maybe declaring new scanner on each iteration of infinite loop leads to some memory leaks. Actually, I don't know how to do it in another way and I'm just want to ask 2 things:

Is it possible to do the same in another way?

Do we actually need more optimization on such low-level server

abstraction?

答:
The outer loop is waiting for new connections, the inner loop is parsing the input data, so from that point of view it's fine. Not all nested loops are evil. However, while you're handling that single connection, the server is not accepting them any more (you can test that by trying to connect to the server from multiple clients). To fix that, handle the connection in a goroutine:</p>

```<code>for {
    conn, err := li.Accept()
    if err != nil {
        log.Fatalln(err)
    }

    go func() {
        defer conn.Close()
        scanner := bufio.NewScanner(conn)

        for scanner.Scan() {
            ln := scanner.Text()
            io.WriteString(conn, ln+"\n")
        }
    }()
}
</code>```

Body:
coders. Here is the basic tcp-server, that accepts connection, reads the incoming data and writes back.

    package main

    import (
        "bufio"
        "io"
        "log"
        "net"
    )

    func main() {
        li, err := net.Listen("tcp", ":8080")
        if err != nil {
            log.Fatalln(err)
        }

        defer li.Close()

        for {
            conn, err := li.Accept()
            if err != nil {
                log.Fatalln(err)
            }

            scanner := bufio.NewScanner(conn)

            for scanner.Scan() {
                ln := scanner.Text()
                io.WriteString(conn, ln+"\n")
            }

            conn.Close()
        }

    }

However, there is a nested loop for scanner and declaring new scanner on each iteration of external loop. I heard, that nested loops lead to extra complexety and maybe declaring new scanner on each iteration of infinite loop leads to some memory leaks. Actually, I don't know how to do it in another way and I'm just want to ask 2 things:

Is it possible to do the same in another way?

Do we actually need more optimization on such low-level server

abstraction?

Body:
The outer loop is waiting for new connections, the inner loop is parsing the input data, so from that point of view it's fine. Not all nested loops are evil. However, while you're handling that single connection, the server is not accepting them any more (you can test that by trying to connect to the server from multiple clients). To fix that, handle the connection in a goroutine:

for {
    conn, err := li.Accept()
    if err != nil {
        log.Fatalln(err)
    }

    go func() {
        defer conn.Close()
        scanner := bufio.NewScanner(conn)

        for scanner.Scan() {
            ln := scanner.Text()
            io.WriteString(conn, ln+"\n")
        }
    }()
}


问:
TensorFlow tutorials Training model with less images than expected
challenge refers to TensorFlow tutorials like:

(1) https://www.tensorflow.org/tutorials/keras/classification

or (2) https://www.tensorflow.org/tutorials/images/cnn

In (1) there is paragraph "Feed the model" https://www.tensorflow.org/tutorials/keras/classification#feed_the_model where output says in each epoch 60000 / 60000.

In (2) there is "Compile and train the model" https://www.tensorflow.org/tutorials/images/cnn#compile_and_train_the_model where output says 50000 / 50000.

In both cases it corresponds with number of images in training datasets.

When I run these tutorials in Google Colab:

(1) https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/keras/classification.ipynb

(2) https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/images/cnn.ipynb

out of the box, without any modifications, I can only get 1875 / 1875 for (1) and 1563 / 1563 for (2).

Any magic behind?
Perhaps known issue?

Thanks in advance!

答:
Seems I have completed this challenge.
When you look at model.fit() you will see explanation for batch_size as follows:

```<code>batch_size: Integer or `None`.
If unspecified, `batch_size` will default to 32.
</code>```

And it finds confirmation in both (1) and (2) tutorials:

(1) 60000 / 32 = 1875

(2) 50000 / 32 = 1563 (rounded up)

So model.fit() in case of these tutorials shows progress in batch numbers, not in image numbers as I initially thought

Body:
Seems I have completed this challenge.
When you look at model.fit() you will see explanation for batch_size as follows:

batch_size: Integer or `None`.
If unspecified, `batch_size` will default to 32.

And it finds confirmation in both (1) and (2) tutorials:

(1) 60000 / 32 = 1875

(2) 50000 / 32 = 1563 (rounded up)

So model.fit() in case of these tutorials shows progress in batch numbers, not in image numbers as I initially thought


问:
Handle optional pattern in macro_rules
I am currently struggling with a use case, where I want to achieve the following things:

This is a simplified version. Basically, I would have a macro to translate customized format to a function

example!(
    name, // is an ident, mandatory
    <expr1>, // is an expr, optional
    [expr2], // is an expr, optional
)

name(Some(expr1), Some(expr2)) // my_macro!(name, <expr1>, [expr2])
name(None, Some(expr2)) // my_macro!(name, [expr2])
name(Some(expr1), None) // my_macro!(name, <expr1>)
name(None, None) // my_macro!(name)

```

<p>I know that I can define multiple patterns to represent cases 1 through 4 and give a proper template. However, if am wondering if there is a more intelligent way or some sys-builtin macros (e.g stringify!) which can handler something like: </p>

<pre class="lang-rust prettyprint-override"><code>#[macro_export]
macro_rules! example {
    ($name:ident, $(($expr1:expr)),? $([$expr2:expr]),?) => {

        let expr_1 = Some( $( $expr1 )? ) // or None
        let expr_2 = Some( $( $expr2 )? ) // or None

        name(expr_1, expr_2)
    }
}
</code>```

答:
I ended up with a solution by adding another macro rules: </p>

<pre class="lang-rust prettyprint-override"><code>#[macro_export]
macro_rules! some_or_none {
    () => { None };
    ($entity:expr) => { Some($entity) }
}

#[macro_export]
macro_rules! example {
    ($name:ident, $(<$expr1:tt>),? $([$expr2:tt]),?) => {

        let expr_1 = some_or_none!($expr1)
        let expr_2 = some_or_none!($expr2)

        $name(expr_1, expr_2)
    }
}

</code>```

Title: Handle optional pattern in macro_rules

Body:
I am currently struggling with a use case, where I want to achieve the following things:

This is a simplified version. Basically, I would have a macro to translate customized format to a function

example!(
    name, // is an ident, mandatory
    <expr1>, // is an expr, optional
    [expr2], // is an expr, optional
)

name(Some(expr1), Some(expr2)) // my_macro!(name, <expr1>, [expr2])
name(None, Some(expr2)) // my_macro!(name, [expr2])
name(Some(expr1), None) // my_macro!(name, <expr1>)
name(None, None) // my_macro!(name)

I know that I can define multiple patterns to represent cases 1 through 4 and give a proper template. However, if am wondering if there is a more intelligent way or some sys-builtin macros (e.g stringify!) which can handler something like:

#[macro_export]
macro_rules! example {
    ($name:ident, $(($expr1:expr)),? $([$expr2:expr]),?) => {

        let expr_1 = Some( $( $expr1 )? ) // or None
        let expr_2 = Some( $( $expr2 )? ) // or None

        name(expr_1, expr_2)
    }
}

Body:
I ended up with a solution by adding another macro rules:

#[macro_export]
macro_rules! some_or_none {
    () => { None };
    ($entity:expr) => { Some($entity) }
}

#[macro_export]
macro_rules! example {
    ($name:ident, $(<$expr1:tt>),? $([$expr2:tt]),?) => {

        let expr_1 = some_or_none!($expr1)
        let expr_2 = some_or_none!($expr2)

        $name(expr_1, expr_2)
    }
}


问:
Stored Procedure doesn't return correct ROWS
I am trying to create a Stored Procedure to filter user input data. Currently, there are two parameters.

Status which is bit and can be 0 or 1 and OrgUnitId which is an int and can be between 0 and 9.

Right now, whatever I create OrgUnitId doesn't return value which I sent.

```<code>DECLARE
@Status bit = 0,
@OrgJed int = 5
BEGIN
IF(@Status = 0)
BEGIN
 SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
  FROM  tblZaposleni_AD
  WHERE Status = @Status
 END

 ELSE IF(@Status = 1)
 SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
  FROM  tblZaposleni_AD
  WHERE Status = @Status

END

IF(@OrgJed = 0)
BEGIN
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed

    IF(@OrgJed = 1)
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed

     IF(@OrgJed = 2)
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed

    IF(@OrgJed = 3)
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed

    IF(@OrgJed = 4)
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed

    IF(@OrgJed = 5)
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed

    IF(@OrgJed = 6)
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed

    IF(@OrgJed = 7)
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed

    IF(@OrgJed = 8)
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed

   IF(@OrgJed = 9)
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed
END
</code>```

I tried to create SELECT statement and It return 12 rows

```<code>SELECT *
FROM [DesignSaoOsig1].[dbo].[tblZaposleni_AD]
WHERE Status = 0 AND OrgUnitID = 5
</code>```

But when I run the stored procedure I get 163 rows, and I see that OrgUnitId is not the value which I sent. I suppose the problem is in IF statement, but whatever I change I get always same result.

答:
Its not clear what your filter criteria is, but a single query should do the job e.g.</p>

```<code>DECLARE
    @Status bit = 0, -- Could be null
    @OrgJed int = 5  -- Could be null
BEGIN
    SET NOCOUNT ON;

    SELECT *
    FROM [DesignSaoOsig1].[dbo].[tblZaposleni_AD]
    WHERE (@Status IS NULL OR [Status] = @Status)
    AND (@OrgJed IS NULL OR OrgUnitID = @OrgJed)
    -- I assume at least one parameter has to be non null
    AND (@Status IS NOT NULL OR @OrgJed IS NOT NULL);

    RETURN 0;
END
</code>```

Body:
I am trying to create a Stored Procedure to filter user input data. Currently, there are two parameters.

Status which is bit and can be 0 or 1 and OrgUnitId which is an int and can be between 0 and 9.

Right now, whatever I create OrgUnitId doesn't return value which I sent.

DECLARE
@Status bit = 0,
@OrgJed int = 5
BEGIN
IF(@Status = 0)
BEGIN
 SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
  FROM  tblZaposleni_AD
  WHERE Status = @Status
 END

 ELSE IF(@Status = 1)
 SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
  FROM  tblZaposleni_AD
  WHERE Status = @Status

END

IF(@OrgJed = 0)
BEGIN
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed

    IF(@OrgJed = 1)
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed

     IF(@OrgJed = 2)
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed

    IF(@OrgJed = 3)
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed

    IF(@OrgJed = 4)
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed

    IF(@OrgJed = 5)
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed

    IF(@OrgJed = 6)
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed

    IF(@OrgJed = 7)
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed

    IF(@OrgJed = 8)
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed

   IF(@OrgJed = 9)
    SELECT PrezimeIme,NetworkLogin,Status,OrgUnitId,DT_Creat,DT_Modif
      FROM  tblZaposleni_AD
      WHERE OrgUnitID = @OrgJed
END

I tried to create SELECT statement and It return 12 rows

SELECT *
FROM [DesignSaoOsig1].[dbo].[tblZaposleni_AD]
WHERE Status = 0 AND OrgUnitID = 5

But when I run the stored procedure I get 163 rows, and I see that OrgUnitId is not the value which I sent. I suppose the problem is in IF statement, but whatever I change I get always same result.

Body:
Its not clear what your filter criteria is, but a single query should do the job e.g.

DECLARE
    @Status bit = 0, -- Could be null
    @OrgJed int = 5  -- Could be null
BEGIN
    SET NOCOUNT ON;

    SELECT *
    FROM [DesignSaoOsig1].[dbo].[tblZaposleni_AD]
    WHERE (@Status IS NULL OR [Status] = @Status)
    AND (@OrgJed IS NULL OR OrgUnitID = @OrgJed)
    -- I assume at least one parameter has to be non null
    AND (@Status IS NOT NULL OR @OrgJed IS NOT NULL);

    RETURN 0;
END


问:
How can you find translations of a word in english to other languages programmatically
The following is a sample set of translations from english --> french

```<code>lundi (monday)
mardi (tuesday)
mercredi (wednesday)
janvier (january)
</code>```

Is there an easier way to find the equivalent words for days and months from english to say french | german | japanese?

答: I would consider using java.text.SimpleDateFormat with a correct Locale - it should provide day/month names in many languages.</p>

ContentLicense: CC BY-SA 3.0

Body:
The following is a sample set of translations from english --> french

lundi (monday)
mardi (tuesday)
mercredi (wednesday)
janvier (january)

Is there an easier way to find the equivalent words for days and months from english to say french | german | japanese?


问:
lottery loop through random numbers in a list find how many counts it took to find it
im very new to python and cant figure out a basic matching game using lottery numbers.

i have 6 numbers. the first 5 numbers are between 1-49 and the last number is 1-7.
i cant seem to loop through where after it checks it, it generates another random number.

edited:

how do i remove duplicates from range(0,4)?

```<code>import random

def lottery(ticket):
    count = 0
    run = True
    while count < 200:
        lottoNum = sorted([random.randint(1,49) for x in range(5)])
        lottoNum.append(random.randint(1,7))

        if lottoNum != ticket:
            count += 1
            print(lottoNum)

        else:
            run = False
            print(lottoNum, count)

lottery([11, 12, 36, 39, 46, 1])
</code>```

答:
You should move the lottoNum definition inside the while loop in order to update it every loop, like this:

```<code>import random

def lottery(ticket):
    count = 0
    while count < 1000:
        lottoNum = [random.randint(1, 49) for x in range(6)]
        lottoNum[-1] = random.randint(1, 7)
        if lottoNum !=  ticket:
            count += 1
            print(lottoNum)

print(lottery([11, 12, 36, 39, 46, 1]))
</code>```

With this correction, you allow 1000 attempts to the lottery function to guess the correct input, stored in ticket.

Moreover, you lottery function does not have a return statement (it returns nothing), so, in Python, such a function returns a value None. This is the reason why there is no point in printing the 'result' of the function in the line print(lottery([11, 12, 36, 39, 46, 1])): this print statement will print always None because your function lottery does not returns anything.

Body:
im very new to python and cant figure out a basic matching game using lottery numbers.

i have 6 numbers. the first 5 numbers are between 1-49 and the last number is 1-7.
i cant seem to loop through where after it checks it, it generates another random number.

edited:

how do i remove duplicates from range(0,4)?

import random

def lottery(ticket):
    count = 0
    run = True
    while count < 200:
        lottoNum = sorted([random.randint(1,49) for x in range(5)])
        lottoNum.append(random.randint(1,7))

        if lottoNum != ticket:
            count += 1
            print(lottoNum)

        else:
            run = False
            print(lottoNum, count)

lottery([11, 12, 36, 39, 46, 1])

Body:
You should move the lottoNum definition inside the while loop in order to update it every loop, like this:

import random

def lottery(ticket):
    count = 0
    while count < 1000:
        lottoNum = [random.randint(1, 49) for x in range(6)]
        lottoNum[-1] = random.randint(1, 7)
        if lottoNum !=  ticket:
            count += 1
            print(lottoNum)

print(lottery([11, 12, 36, 39, 46, 1]))

With this correction, you allow 1000 attempts to the lottery function to guess the correct input, stored in ticket.

Moreover, you lottery function does not have a return statement (it returns nothing), so, in Python, such a function returns a value None. This is the reason why there is no point in printing the 'result' of the function in the line print(lottery([11, 12, 36, 39, 46, 1])): this print statement will print always None because your function lottery does not returns anything.


问:
How to SUM duplicate row in CASE statement calculation
I have a case statement that calculates a score by a flag per item but assigned to the user of the item.

Its a count of compliant/non compliant items, my problem is if an item has 2 rows in the table, its counting this a 2 Non-Compliant, when it should be 1.

This is the basic case statement:

```<code>SELECT
    user.id,
    sum( CASE WHEN SCORE_FLAG = 'Y' THEN 1 ELSE 0  END)  AS 'Compliant_Count',
    sum( CASE WHEN SCORE_FLAG = 'N' THEN 1 ELSE 0  END)  AS 'NonCompliant_Count',
    sum( CASE WHEN SCORE_FLAG = 'Y' or SCORE_FLAG = 'N' then 1 ELSE 0 END) AS 'Total_count'
FROM Table
Group By user.id
</code>```

This is the invalid results below (I added in item column - but this won't be included in my query, as I group by user id only).

```<code>usera   item1   0   1   1
usera   item2   0   2   2--
usera   item3   0   1   1
usera   item4   0   1   1
</code>```

This user has 4 items, but item 2 has 2 rows in the table so is showing a Non-Compliant of 2, when I want it to be 1.

How can I get this to pull back 1 row using the case statement. I have to group the results by user, and not item, as the data is loaded into another table that only contains the user.

Item 2 should only have 1 non compliant count and 1 total count

But when I am grouping the data it is by user, so it should look like this:

```<code>Usera   0   4   4
</code>```

Usera should have a count of 4 non-compliant items, but currently I get a count of 5, as one of them items has 2 rows

答:
Use a COUNT(DISTINCT) instead of a sum

e.g.

```<code>SELECT COUNT(DISTINCT CASE WHEN SCORE_FLAG = 'Y' THEN item ELSE NULL END)
</code>```

Body:
I have a case statement that calculates a score by a flag per item but assigned to the user of the item.

Its a count of compliant/non compliant items, my problem is if an item has 2 rows in the table, its counting this a 2 Non-Compliant, when it should be 1.

This is the basic case statement:

SELECT
    user.id,
    sum( CASE WHEN SCORE_FLAG = 'Y' THEN 1 ELSE 0  END)  AS 'Compliant_Count',
    sum( CASE WHEN SCORE_FLAG = 'N' THEN 1 ELSE 0  END)  AS 'NonCompliant_Count',
    sum( CASE WHEN SCORE_FLAG = 'Y' or SCORE_FLAG = 'N' then 1 ELSE 0 END) AS 'Total_count'
FROM Table
Group By user.id

This is the invalid results below (I added in item column - but this won't be included in my query, as I group by user id only).

usera   item1   0   1   1
usera   item2   0   2   2--
usera   item3   0   1   1
usera   item4   0   1   1

This user has 4 items, but item 2 has 2 rows in the table so is showing a Non-Compliant of 2, when I want it to be 1.

How can I get this to pull back 1 row using the case statement. I have to group the results by user, and not item, as the data is loaded into another table that only contains the user.

Item 2 should only have 1 non compliant count and 1 total count

But when I am grouping the data it is by user, so it should look like this:

Usera   0   4   4

Usera should have a count of 4 non-compliant items, but currently I get a count of 5, as one of them items has 2 rows

Body:
Use a COUNT(DISTINCT) instead of a sum

e.g.

SELECT COUNT(DISTINCT CASE WHEN SCORE_FLAG = 'Y' THEN item ELSE NULL END)


问:
Problem with Placing React Native Youtube Component Inside React Navigation
I'm trying to place the react-native-youtube component inside react-native-navigation screen. But it gives Can't find variable: Youtube error.

Here is my code:

Home.js:

```<code>import * as React from 'react';
import { Button, View, Text } from 'react-native';
import Youtube from 'react-native-youtube';

export default function HomeScreen({navigation}) {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <YouTube
          apiKey="key"
          videoId="video id" // The YouTube video ID
          play="true" // control playback of video with true/false
          fullscreen="true" // control whether the video should play in fullscreen or inline
          loop="false" // control whether the video should loop when ended
          onReady={e => this.setState({ isReady: true })}
          onChangeState={e => this.setState({ status: e.state })}
          onChangeQuality={e => this.setState({ quality: e.quality })}
          onError={e => this.setState({ error: e.error })}
          style={{ alignSelf: 'stretch', height: 300 }}
        />
      </View>
    );
  }
</code>```

App.js:

```<code>import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import HomeScreen from './screens/Home';
import Youtube from 'react-native-youtube';
const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}
export default App;
</code>```

答:
Your import is using simple 't' Youtube so the component should be

Change it to

```<code>     <Youtube
          apiKey="key"
          videoId="video id" // The YouTube video ID
          play="true" // control playback of video with true/false
          fullscreen="true" // control whether the video should play in fullscreen or inline
          loop="false" // control whether the video should loop when ended
          onReady={e => this.setState({ isReady: true })}
          onChangeState={e => this.setState({ status: e.state })}
          onChangeQuality={e => this.setState({ quality: e.quality })}
          onError={e => this.setState({ error: e.error })}
          style={{ alignSelf: 'stretch', height: 300 }}
        />
</code>```

Body:
I'm trying to place the react-native-youtube component inside react-native-navigation screen. But it gives Can't find variable: Youtube error.

Here is my code:

Home.js:

import * as React from 'react';
import { Button, View, Text } from 'react-native';
import Youtube from 'react-native-youtube';

export default function HomeScreen({navigation}) {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <YouTube
          apiKey="key"
          videoId="video id" // The YouTube video ID
          play="true" // control playback of video with true/false
          fullscreen="true" // control whether the video should play in fullscreen or inline
          loop="false" // control whether the video should loop when ended
          onReady={e => this.setState({ isReady: true })}
          onChangeState={e => this.setState({ status: e.state })}
          onChangeQuality={e => this.setState({ quality: e.quality })}
          onError={e => this.setState({ error: e.error })}
          style={{ alignSelf: 'stretch', height: 300 }}
        />
      </View>
    );
  }

App.js:

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import HomeScreen from './screens/Home';
import Youtube from 'react-native-youtube';
const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}
export default App;

Body:
Your import is using simple 't' Youtube so the component should be

Change it to

     <Youtube
          apiKey="key"
          videoId="video id" // The YouTube video ID
          play="true" // control playback of video with true/false
          fullscreen="true" // control whether the video should play in fullscreen or inline
          loop="false" // control whether the video should loop when ended
          onReady={e => this.setState({ isReady: true })}
          onChangeState={e => this.setState({ status: e.state })}
          onChangeQuality={e => this.setState({ quality: e.quality })}
          onError={e => this.setState({ error: e.error })}
          style={{ alignSelf: 'stretch', height: 300 }}
        />


问:
How to get memory usage of program executed by gcc/g++ from MinGW under windows
As I mentioned I dont know how to get memory usage of executed program by gcc/g++ compiler of MinGW under windows. Is there a function like time from Linux on Windows. I tried Measure Command but not showing memory. MinGw under Windows 10

For any responses Very Thankful

答:
You can do this per process using GetProcessMemoryInfo(), see: https://learn.microsoft.com/en-us/windows/win32/psapi/collecting-memory-usage-information-for-a-process

To get the process ID of the running program for example you can use GetCurrentProcessId()


问:
Having a console command work in every user input
I'm trying to make a menu command working in every user input, basically, the user is able to move around the program with input

```<code>string input = Console.ReadLine();
switch(input):
{
    case "Up":
        y++;
        Console.WriteLine("Moving up at x: " + x + ", y: " + y);
        break;
    case "Down":
        y--;
        Console.WriteLine("Moving down at x: " + x + ", y: " + y);
        break;
    case "Left":
        x--;
        Console.WriteLine("Moving left at x: " + x + ", y: " + y);
        break;
    case "Right":
        x++;
        Console.WriteLine("Moving right at x: " + x + ", y: " + y);
        break;
    default:
        Console.WriteLine("Standing still at x: " + x + ", y: " + y);
        break;
}
</code>```

This will be more or less when the user chooses were to move. What I want to make is a menu command which opens a menu every time it's written, without having to put a "menu" case each time (I'm not putting this switch inside a do while, because I need to customize every move). Is there any way to run a code every time a particular input is given by the user at any time during the whole execution of the program?

答:
I've read your question a second time, and it seems like you just need to extract this code into its own method. A simple approach would be to just call HandleDirectionalInput from any menu method.

```<code>public bool HandleDirectionalInput(string input)
{
    switch(input):
    {
        case "Up":
            y++;
            Console.WriteLine("Moving up at x: " + x + ", y: " + y);
            return true;
        case "Down":
            y--;
            Console.WriteLine("Moving down at x: " + x + ", y: " + y);
            return true;
        case "Left":
            x--;
            Console.WriteLine("Moving left at x: " + x + ", y: " + y);
            return true;
        case "Right":
            x++;
            Console.WriteLine("Moving right at x: " + x + ", y: " + y);
            return true;
    }
    return false;
}
</code>```

So you would end up with something like this:

```<code>public void DoMainMenu()
{
    Console.WriteLine("some stuff here");
    string input = Console.ReadLine();
    if (!HandleDirectionalInput(input))
    {
        // do other main menu checks on input
    }
}
</code>```

There are other ways you could do this, such as by creating a list of command handlers which would each have their turn at handling the input, but that's probably more complicated than you need at the moment.

Body:
I'm trying to make a menu command working in every user input, basically, the user is able to move around the program with input

string input = Console.ReadLine();
switch(input):
{
    case "Up":
        y++;
        Console.WriteLine("Moving up at x: " + x + ", y: " + y);
        break;
    case "Down":
        y--;
        Console.WriteLine("Moving down at x: " + x + ", y: " + y);
        break;
    case "Left":
        x--;
        Console.WriteLine("Moving left at x: " + x + ", y: " + y);
        break;
    case "Right":
        x++;
        Console.WriteLine("Moving right at x: " + x + ", y: " + y);
        break;
    default:
        Console.WriteLine("Standing still at x: " + x + ", y: " + y);
        break;
}

This will be more or less when the user chooses were to move. What I want to make is a menu command which opens a menu every time it's written, without having to put a "menu" case each time (I'm not putting this switch inside a do while, because I need to customize every move). Is there any way to run a code every time a particular input is given by the user at any time during the whole execution of the program?

Body:
I've read your question a second time, and it seems like you just need to extract this code into its own method. A simple approach would be to just call HandleDirectionalInput from any menu method.

public bool HandleDirectionalInput(string input)
{
    switch(input):
    {
        case "Up":
            y++;
            Console.WriteLine("Moving up at x: " + x + ", y: " + y);
            return true;
        case "Down":
            y--;
            Console.WriteLine("Moving down at x: " + x + ", y: " + y);
            return true;
        case "Left":
            x--;
            Console.WriteLine("Moving left at x: " + x + ", y: " + y);
            return true;
        case "Right":
            x++;
            Console.WriteLine("Moving right at x: " + x + ", y: " + y);
            return true;
    }
    return false;
}

So you would end up with something like this:

public void DoMainMenu()
{
    Console.WriteLine("some stuff here");
    string input = Console.ReadLine();
    if (!HandleDirectionalInput(input))
    {
        // do other main menu checks on input
    }
}

There are other ways you could do this, such as by creating a list of command handlers which would each have their turn at handling the input, but that's probably more complicated than you need at the moment.


问:
Pygame start menu working, but not Pause menu
I'm trying to integrate a "pause" menu and "main" menu in pygame, along with a screen that will show during the game.  My code first loads the intro, or main menu, which works fine, and then handles a button click to call the main game loop function.  The problem arises when, within that loop, I try to call the function for the pause menu.  I use the same loops to do this so I'm not sure why one works and the other doesn't.  Below I've added code snippets for reference.

The main menu (which is called first in the program):

def intro_screen():
    intro = True
    while intro:

        # Event listeners
        for event in pygame.event.get():

            main_window.fill(tan)
```

<p>...
I also have other buttons etc. which are unimportant, but to get out of the intro, a mouse event sets intro to false and calls the function game_loop:</p>

<pre class="lang-py prettyprint-override"><code># Handle the click event
if click[0] == 1:
    intro = False
    game_loop()
</code>```

The game_loop function has a similar while loop:

def game_loop():
    playing = True
    paused = False

    while playing:
        # This is the main loop

        # Load in the play screens...
        main_window.fill(white)
        play_screen = PlayScreen(main_window)
```

<p>And buttons etc...
But when I set playing to False and paused to True, which calls the pause_screen() function, it doesn't pull up any new screen.  It just stays on the game menu as if no event was received.</p>

<pre class="lang-py prettyprint-override"><code>        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                playing = False

            # Listen for the escape key and bring up the pause menu
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    playing = False
                    paused = True

        pygame.display.update()

    while paused:
        pause_menu()
</code>```

For reference, these are all contained in functions.  The last line of my code simply calls intro_screen(), which works fine.

I can provide the rest of the code if that would be helpful.  The only thing I could think of is that the mouse event works and the keydown event doesn't, but my syntax looks to be correct from what I can tell.

答:
Looks like your while loop for the pause menu is out of the game loop. Try this:</p>

```<code>def game_loop():
    playing = True
    paused = False

while playing:
    # This is the main loop

    # Load in the play screens...
    main_window.fill(white)
    play_screen = PlayScreen(main_window)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            playing = False

        # Listen for the escape key and bring up the pause menu
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                playing = False
                paused = True

    pygame.display.update()

    while paused:
        pause_menu()
</code>```

Body:
I'm trying to integrate a "pause" menu and "main" menu in pygame, along with a screen that will show during the game.  My code first loads the intro, or main menu, which works fine, and then handles a button click to call the main game loop function.  The problem arises when, within that loop, I try to call the function for the pause menu.  I use the same loops to do this so I'm not sure why one works and the other doesn't.  Below I've added code snippets for reference.

The main menu (which is called first in the program):

def intro_screen():
    intro = True
    while intro:

        # Event listeners
        for event in pygame.event.get():

            main_window.fill(tan)

...
I also have other buttons etc. which are unimportant, but to get out of the intro, a mouse event sets intro to false and calls the function game_loop:

# Handle the click event
if click[0] == 1:
    intro = False
    game_loop()

The game_loop function has a similar while loop:

def game_loop():
    playing = True
    paused = False

    while playing:
        # This is the main loop

        # Load in the play screens...
        main_window.fill(white)
        play_screen = PlayScreen(main_window)

And buttons etc...
But when I set playing to False and paused to True, which calls the pause_screen() function, it doesn't pull up any new screen.  It just stays on the game menu as if no event was received.

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                playing = False

            # Listen for the escape key and bring up the pause menu
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    playing = False
                    paused = True

        pygame.display.update()

    while paused:
        pause_menu()

For reference, these are all contained in functions.  The last line of my code simply calls intro_screen(), which works fine.

I can provide the rest of the code if that would be helpful.  The only thing I could think of is that the mouse event works and the keydown event doesn't, but my syntax looks to be correct from what I can tell.

Body:
Looks like your while loop for the pause menu is out of the game loop. Try this:

def game_loop():
    playing = True
    paused = False

while playing:
    # This is the main loop

    # Load in the play screens...
    main_window.fill(white)
    play_screen = PlayScreen(main_window)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            playing = False

        # Listen for the escape key and bring up the pause menu
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                playing = False
                paused = True

    pygame.display.update()

    while paused:
        pause_menu()


问:
Fortran: Pure subroutine of moving in the text of a group of lines from the First line to the Last line after the K-th line
The task is performed in the form of a software project of two modules, in which it is necessary to use unidirectional lists of unknown length in advance.

Task:
Develop a clean routine for moving in the text a group of lines from the First line to the Last line after the K-th line. The values of First, Last, K are set in the second input file. The correct data is the situation when First≤Last, and K does not belong to the interval [First, Last].
Indication The list item is a string.

I did input, output, and retrieve an item from a list. But I can’t understand how to rearrange sentences in the text according to the conditions of the problem.

Code on github: enter link description here

source_process.f90

```<code>module Source_Process
   use Environment
   use Source_IO

   implicit none

contains
   recursive function get_element(current_element, number) result(element)
      type(SourceLine), pointer, intent(in)  :: current_element
      type(SourceLine), pointer :: element
      integer, intent(in) :: number

      element => null()
      if (associated(current_element)) then
         if (number == 0) then
            element => current_element
         else
            element => get_element(current_element%next, number - 1)
         end if
      end if
   end function get_element
end module Source_process
</code>```

Thanks in advance for your reply.

答:
```<code>module Source_Process
   use Environment
   use Source_IO

   implicit none

contains
   subroutine Move_Strings(NB, KB, K, InitialStrings)
      type(SourceLine), pointer, intent(inout)  :: InitialStrings
      integer, intent (in)                      :: NB, KB, K

      type(SourceLine), pointer  :: CurrentInitial, CurrentTmp
      type(SourceLine), pointer  :: CurrentK, CurrentNB, PrevNB, CurrentKB

      integer                    ::  number_string = 1

      CurrentInitial => InitialStrings

      CurrentK  => null()
      CurrentNB => null()
      CurrentKB => null()

      do while (Associated(CurrentInitial))
         if (number_string == K) then
            CurrentK => CurrentInitial
         else if (number_string == NB - 1) then
            PrevNB => CurrentInitial
         else if (number_string == NB) then
            CurrentNB => CurrentInitial
         else if (number_string == KB) then
            CurrentKB => CurrentInitial
         end if
         CurrentInitial => CurrentInitial%Next
         number_string = number_string + 1
      end do

      if (NB == 1) then
         InitialStrings => CurrentKB%next
      else
         PrevNB%next => CurrentKB%next
      end if

      CurrentKB%next => CurrentK%next
      CurrentK%next => CurrentNB

   end subroutine Move_Strings
end module Source_process
</code>```

Problem Solved.

Body:
The task is performed in the form of a software project of two modules, in which it is necessary to use unidirectional lists of unknown length in advance.

Task:
Develop a clean routine for moving in the text a group of lines from the First line to the Last line after the K-th line. The values of First, Last, K are set in the second input file. The correct data is the situation when First≤Last, and K does not belong to the interval [First, Last].
Indication The list item is a string.

I did input, output, and retrieve an item from a list. But I can’t understand how to rearrange sentences in the text according to the conditions of the problem.

Code on github: enter link description here

source_process.f90

module Source_Process
   use Environment
   use Source_IO

   implicit none

contains
   recursive function get_element(current_element, number) result(element)
      type(SourceLine), pointer, intent(in)  :: current_element
      type(SourceLine), pointer :: element
      integer, intent(in) :: number

      element => null()
      if (associated(current_element)) then
         if (number == 0) then
            element => current_element
         else
            element => get_element(current_element%next, number - 1)
         end if
      end if
   end function get_element
end module Source_process

Thanks in advance for your reply.

Body:
module Source_Process
   use Environment
   use Source_IO

   implicit none

contains
   subroutine Move_Strings(NB, KB, K, InitialStrings)
      type(SourceLine), pointer, intent(inout)  :: InitialStrings
      integer, intent (in)                      :: NB, KB, K

      type(SourceLine), pointer  :: CurrentInitial, CurrentTmp
      type(SourceLine), pointer  :: CurrentK, CurrentNB, PrevNB, CurrentKB

      integer                    ::  number_string = 1

      CurrentInitial => InitialStrings

      CurrentK  => null()
      CurrentNB => null()
      CurrentKB => null()

      do while (Associated(CurrentInitial))
         if (number_string == K) then
            CurrentK => CurrentInitial
         else if (number_string == NB - 1) then
            PrevNB => CurrentInitial
         else if (number_string == NB) then
            CurrentNB => CurrentInitial
         else if (number_string == KB) then
            CurrentKB => CurrentInitial
         end if
         CurrentInitial => CurrentInitial%Next
         number_string = number_string + 1
      end do

      if (NB == 1) then
         InitialStrings => CurrentKB%next
      else
         PrevNB%next => CurrentKB%next
      end if

      CurrentKB%next => CurrentK%next
      CurrentK%next => CurrentNB

   end subroutine Move_Strings
end module Source_process

Problem Solved.


问:
Is un-initialized integer always default to 0 in c?
I'm reading source code of nginx and find it's not initializing many of the numerical variables, including ngx_int_t ngx_last_process;,here ngx_int_t defined as long int

```<code>#if 0
    ngx_last_process = 0;
#endif
</code>```

So here @Igor Sysoev think it unnecessary to do the initialization?

But in the programe it's assuming the default value is 0:

```<code>    for (s = 0; s < ngx_last_process; s++) {
        if (ngx_processes[s].pid == -1) {
            break;
        }
    }
</code>```

Is it guranteed that un-initialized variable will have 0 value in c at all?

答:
External and static variables are initialized to zero by default, this is guaranteed. Automatic and register variables that do not have en explicit initializer will have an indeterminate value (either an unspecified value or a trap representation).

From The Standard:

C89

6.5.7:

If an object that has static storage duration is not initialized
  explicitly, it is initialized implicitly as if every member that has
  arithmetic type were assigned 0 and every member that has pointer type
  were assigned a null pointer constant.  If an object that has
  automatic storage duration is not initialized explicitly, its value is
  indeterminate.

C99

6.2.4, §5:

For such an object that does not have a variable length array type, its lifetime extends
  from entry into the block with which it is associated until execution of that block ends in
  anyway.(Entering an enclosed block or calling a function suspends, but does not end,
  execution of the current block.) If the block is entered recursively,anew instance of the
  object is created each time. The initial value of the object is indeterminate. If an
  initialization is specified for the object, it is performed each time the declaration is
  reached in the execution of the block; otherwise, the value becomes indeterminate each
  time the declaration is reached.

6.7.8, §10:

If an object that has automatic storage duration is not initialized explicitly,its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:

— if it has pointer type, it is initialized to a null pointer;

— if it has arithmetic type, it is initialized to (positive orunsigned) zero;

— if it is an aggregate, every member is initialized (recursively) according to these rules;

— if it is a union, the first named member is initialized (recursively) according to these rules.

3.17.2, §1:

indeterminate value: either an unspecified value or a trap representation

3.17.3, §1:

unspecified value: valid value of the relevant type where this International Standard imposes no requirements on which value is chosen in any instance. NOTE An unspecified value cannot be a trap representation.

Body:
I'm reading source code of nginx and find it's not initializing many of the numerical variables, including ngx_int_t ngx_last_process;,here ngx_int_t defined as long int

#if 0
    ngx_last_process = 0;
#endif

So here @Igor Sysoev think it unnecessary to do the initialization?

But in the programe it's assuming the default value is 0:

    for (s = 0; s < ngx_last_process; s++) {
        if (ngx_processes[s].pid == -1) {
            break;
        }
    }

Is it guranteed that un-initialized variable will have 0 value in c at all?


答:
I suspect that you want distinct:

```<code>SELECT
    user_id,
    COALESCE(COUNT(DISTINCT CASE WHEN score_flag = 'Y' THEN item END), 0) AS Compliant_Count,
    COALESCE(COUNT(DISTINCT CASE WHEN score_flag = 'N' THEN item END), 0)  AS NonCompliant_Count,
    COUNT(DISTINCT CASE WHEN score_flag IN ('Y', 'N') THEN item END) AS Total_count
FROM mytable
GROUP BY user_id
</code>```

Notes:

there is no user table alias defined in the query, so user.id is invalid. I renamed it to user_id

do not use single quotes for column aliases - single quotes should used for string literals only

If Y and N are the only possible values, the last expression can be simplified as just COUNT(DISTINCT item)

Title: How to SUM duplicate row in CASE statement calculation

Body:
I suspect that you want distinct:

SELECT
    user_id,
    COALESCE(COUNT(DISTINCT CASE WHEN score_flag = 'Y' THEN item END), 0) AS Compliant_Count,
    COALESCE(COUNT(DISTINCT CASE WHEN score_flag = 'N' THEN item END), 0)  AS NonCompliant_Count,
    COUNT(DISTINCT CASE WHEN score_flag IN ('Y', 'N') THEN item END) AS Total_count
FROM mytable
GROUP BY user_id

Notes:

there is no user table alias defined in the query, so user.id is invalid. I renamed it to user_id

do not use single quotes for column aliases - single quotes should used for string literals only

If Y and N are the only possible values, the last expression can be simplified as just COUNT(DISTINCT item)


问:
Is there a way to schedule Cloud Shell commands in Google Cloud Platform?
I want to schedule some of my BigQuery table load commands that I execute in the Cloud Shell CLI. How can I schedule my CLI commands in Google Cloud Platform?</p>

答:
Use Cloud Scheduler to shell jobs, like a HTTP trigger.

Create a Cloud Run container running the commands you want on HTTP trigger. Here is an example.

This solution is serverless, only runs when it's triggered. Cloud Run allows 2M request for free. Cloud Scheduler allows 3 jobs per month per account free, then Cost/job/month $0.10.


问:
Conditionally use switchmap or exhaustmap angular
Sorry if this question has been answered but I've searched and couldn't find it myself.

What I want to do is call a function that returns data from 1 of 2 places. Either gets cached data or gets new data from API. I am using angular 7 and have been trying to implement an observable that conditionally uses switchMap and exhaustMap. I have a decent understanding of Observables, but I know there's still something I don't understand. I was thinking of using exhaustMap as the default method which pulls from cache. But if I need to get the newest data from the API, I want to use switchMap to ignore retrieving from cache and get fresh data.

I found a stackblitz playground and forked it to do some testing. Here's my attempt https://stackblitz.com/edit/angular7-conditional-data

And this is the relevant code.

```<code>this.observable.pipe(
      map((val: string) => {
        if (/^true/.test(val)) {
          this.mergeVal = 'switch ' + val;
          return switchMap(val => {
            // console.log("SwitchMap val: ", val);
            this.switchVal = val;
            return of(val);
          })
        } else {
          this.mergeVal = 'exhaust ' + val;
          return exhaustMap(val => {
            // console.log("resolve val: ", val);
            return new Promise(resolve => {
              setTimeout(() => {
                this.exhaustVal = val;
                resolve(val);
              }, 3000);
            });
          })
        }
      })
    ).subscribe(
      data => {
      //  this.observable;
      this.subscribeVal = 'data: ' + data;
      },
      err => {
        this.subscribeVal = 'error';
      },
      () => {
        this.subscribeVal = 'complete';
      }
    );
  }
</code>```

UPDATE 2020-06-02
I added a service that makes an api call to better align with my current setup that this is going to be applied to. moved away exhaustMap and switchMap with hopes of solving the same problem using the help from people who have posted here

Now I think the problem I have is in this part of the code but I'm not sure how to fix it

```<code>  dummyAPI = 'https://swapi.dev/api/';

  cacheSubject: Subject<any> = new Subject();
  cacheObservable: Observable<any> = this.cacheSubject.asObservable().pipe(
    startWith(this.http.get(this.dummyAPI).pipe(
      map(val => {
        console.log('startWith: ', val);
        return this.now('dataService', true);
      })
    )),
    concatMap(val => val),
    shareReplay({refCount: true})
  );

  constructor(private http: HttpClient) {}

  now(fromId, val = false) {
    return `${val} ${moment().format('hh:mm:ss')} COMP ${fromId}`;
  }

  updateDataFromAPI(fromId, getFromAPI) {
    const val = this.now(fromId, getFromAPI);
    if (getFromAPI) {
      this.cacheSubject.next(
        this.http.get(this.dummyAPI).pipe(
          tap(val => {
            console.log("tap dummyAPI before delay: ", val);
          }),
          delay(5000),
          tap(val => {
            console.log("tap dummyAPI after delay: ", val);
          }),
        )
      );
    } else {
      this.cacheSubject.next(of(val));
    }
  }

  getData(fromId, getFromAPI?) {
    if (getFromAPI) {
      this.updateDataFromAPI(fromId, getFromAPI);
    }
    return this.cacheObservable.pipe(take(1));
  }
</code>```

The problem I'm having is that the cacheObservable subscription (from getData) isn't waiting for the cacheSubject value (from calling next through updateDataFromAPI) to respond with the api data before cacheObservable completes.

答:
This won't work. Because you want to change the stream based on the emit of this.observable.

The idea of exhaustMap is to skip all emits of this.observable until the child stream of exhaustMap has been finished.

In your case I would suggest to use shareReplay(1) that would keep serving cache until an emit comes from this.observable.

const cachedStream$ = this.observable.pipe(
  startWith(null), // to trigger the first load.
  switchMap(() => this.http.get('http://my-data.url')),
  shareReplay(1),
);

cachedStream$.subscribe(cached => this.cached1 = cached);
cachedStream$.subscribe(cached => this.cached2 = cached);
cachedStream$.subscribe(cached => this.cached3 = cached);

this.observable.next(); // refresh the value from the backend.
```

Body:
Sorry if this question has been answered but I've searched and couldn't find it myself.

What I want to do is call a function that returns data from 1 of 2 places. Either gets cached data or gets new data from API. I am using angular 7 and have been trying to implement an observable that conditionally uses switchMap and exhaustMap. I have a decent understanding of Observables, but I know there's still something I don't understand. I was thinking of using exhaustMap as the default method which pulls from cache. But if I need to get the newest data from the API, I want to use switchMap to ignore retrieving from cache and get fresh data.

I found a stackblitz playground and forked it to do some testing. Here's my attempt https://stackblitz.com/edit/angular7-conditional-data

And this is the relevant code.

this.observable.pipe(
      map((val: string) => {
        if (/^true/.test(val)) {
          this.mergeVal = 'switch ' + val;
          return switchMap(val => {
            // console.log("SwitchMap val: ", val);
            this.switchVal = val;
            return of(val);
          })
        } else {
          this.mergeVal = 'exhaust ' + val;
          return exhaustMap(val => {
            // console.log("resolve val: ", val);
            return new Promise(resolve => {
              setTimeout(() => {
                this.exhaustVal = val;
                resolve(val);
              }, 3000);
            });
          })
        }
      })
    ).subscribe(
      data => {
      //  this.observable;
      this.subscribeVal = 'data: ' + data;
      },
      err => {
        this.subscribeVal = 'error';
      },
      () => {
        this.subscribeVal = 'complete';
      }
    );
  }

UPDATE 2020-06-02
I added a service that makes an api call to better align with my current setup that this is going to be applied to. moved away exhaustMap and switchMap with hopes of solving the same problem using the help from people who have posted here

Now I think the problem I have is in this part of the code but I'm not sure how to fix it

  dummyAPI = 'https://swapi.dev/api/';

  cacheSubject: Subject<any> = new Subject();
  cacheObservable: Observable<any> = this.cacheSubject.asObservable().pipe(
    startWith(this.http.get(this.dummyAPI).pipe(
      map(val => {
        console.log('startWith: ', val);
        return this.now('dataService', true);
      })
    )),
    concatMap(val => val),
    shareReplay({refCount: true})
  );

  constructor(private http: HttpClient) {}

  now(fromId, val = false) {
    return `${val} ${moment().format('hh:mm:ss')} COMP ${fromId}`;
  }

  updateDataFromAPI(fromId, getFromAPI) {
    const val = this.now(fromId, getFromAPI);
    if (getFromAPI) {
      this.cacheSubject.next(
        this.http.get(this.dummyAPI).pipe(
          tap(val => {
            console.log("tap dummyAPI before delay: ", val);
          }),
          delay(5000),
          tap(val => {
            console.log("tap dummyAPI after delay: ", val);
          }),
        )
      );
    } else {
      this.cacheSubject.next(of(val));
    }
  }

  getData(fromId, getFromAPI?) {
    if (getFromAPI) {
      this.updateDataFromAPI(fromId, getFromAPI);
    }
    return this.cacheObservable.pipe(take(1));
  }

The problem I'm having is that the cacheObservable subscription (from getData) isn't waiting for the cacheSubject value (from calling next through updateDataFromAPI) to respond with the api data before cacheObservable completes.


问:
FlatList not visible even if i added it in React Native
I have added searchview then another row below that and then i have added flatlist in my view below the horizontal listview and i want to show it in full remaining height but it is not showing, there is also not any error in the code and also it doesn't show any error in console, here is a code :

```<code> <View style={styles.mainContainer}>

    <View style={styles.searchView}>

      <TextInput
        style={styles.searchInput}
        onChangeText={text => this.SearchFilterFunction(text)}
        value={this.state.searchText}
        underlineColorAndroid="transparent"
        placeholder="Search Services"
        placeholderTextColor={theme.colors.app_blue_light}
      />

      <Image source={Images.search} style={styles.searchImage} />
    </View>

    {/* MapView */}
    <View style={styles.MapToggleContainer}>

      <Text style={styles.titleShop}>Select your shop</Text>

      <Text style={styles.titleToggle}
        onPress={this.toggleView}>List View</Text>

    </View>

    <View style={styles.shopListView}>

      <FlatList
        horizontal
        style={styles.shopsList}
        data={this.state.data}
        renderItem={({ item: rowData }) => {
          return (

            <View style={styles.shopListItem}>

              <Image source={require('./logo.png')} style={styles.shopImage} />

            </View>
          );
        }}
        keyExtractor={(item, index) => index}
      />

    </View>

    <MapboxGL.MapView>
      <MapboxGL.Camera centerCoordinate={this.state.coordinates[0]} zoomLevel={14} />

      <MapboxGL.MarkerView id='marker1' coordinate={this.state.coordinates[0]}>
        <ImageBackground source={require('./chat.png')}
          style={{ borderColor: 'black', borderWidth: 0, width: 80, height: 80, alignContent: 'center' }}>
          <TouchableOpacity style={{ width: '100%', height: '100%', alignItems: 'center', justifyContent: 'center' }}
            onPress={() => {
              this.setState({ toolTipVisible: true })
            }}>
            <Tooltip
              animated
              isVisible={this.state.toolTipVisible}
              content={<View style={{ width: '100%', height: '100%', backgroundColor: 'white' }}>
                <View style={{ flexDirection: 'row' }}>
                  <Image source={require('./chat.png')} />
                  <View style={{ flexDirection: 'column' }}>
                    <Text style={{ marginHorizontal: 10, marginTop: 10 }}>123, Main st,</Text>
                    <Text style={{ marginHorizontal: 10, marginBottom: 10 }}>Chicago, IL 6061</Text>
                  </View>
                </View>
                <TouchableOpacity
                  style={{ backgroundColor: 'orange', margin: 10, alignItems: 'center' }}
                  onPress={() => { }}
                >
                  <Text style={{ margin: 10, color: 'white' }}>Select Shop</Text>
                </TouchableOpacity>
              </View>}
              placement="top"
              onClose={() => this.setState({ toolTipVisible: false })} >

              <Text style={{ color: 'white', fontWeight: 'bold', fontSize: 20 }} >$50.00</Text>

            </Tooltip>

          </TouchableOpacity>

        </ImageBackground>

      </MapboxGL.MarkerView>

    </MapboxGL.MapView>

 </View>
</code>```

Styles

```<code>mainContainer: {
      flex: 1,
      backgroundColor: theme.colors.white
    },
toggleContainer: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      marginTop: '20@ms',
      marginBottom:'10@ms',
      marginHorizontal: '15@ms',
    },
    titleShop: {
      fontFamily: 'Muli-Bold',
      fontSize: '16@ms',
      color: theme.colors.gray4
    },
    titleToggle: {
      fontFamily: 'Muli-Bold',
      fontSize: '11@ms',
      color: theme.colors.gray4,
      textDecorationLine: 'underline',
      alignSelf:'center'
    },
MapToggleContainer:{
      flexDirection: 'row',
      justifyContent: 'space-between',
      marginTop: '10@ms',
      marginBottom:'15@ms',
      marginHorizontal: '15@ms',
    },
    shopListView:{
      height:'60@ms'
    },
    shopsList:{
      marginLeft:'5@ms',
      marginRight:'15@ms',
    },
    shopListItem:{
      elevation:5,
      backgroundColor:'white',
      marginLeft:'10@ms',
      height:'50@ms',
      width:'50@ms',
      alignItems:'center',
      justifyContent:'center',
      borderRadius:'5@ms'
    },
    shopImage:{
      width:'30@ms',
      height:'30@ms',
    },
</code>```

And here is a result, as you can see the mapview below list is not visible

答:
give height and width style to MapboxGL.MapView

```<code><MapboxGL.MapView style={{width:Dimensions.get("window").width,height:400}}>
</code>```

Body:
I have added searchview then another row below that and then i have added flatlist in my view below the horizontal listview and i want to show it in full remaining height but it is not showing, there is also not any error in the code and also it doesn't show any error in console, here is a code :

 <View style={styles.mainContainer}>

    <View style={styles.searchView}>

      <TextInput
        style={styles.searchInput}
        onChangeText={text => this.SearchFilterFunction(text)}
        value={this.state.searchText}
        underlineColorAndroid="transparent"
        placeholder="Search Services"
        placeholderTextColor={theme.colors.app_blue_light}
      />

      <Image source={Images.search} style={styles.searchImage} />
    </View>

    {/* MapView */}
    <View style={styles.MapToggleContainer}>

      <Text style={styles.titleShop}>Select your shop</Text>

      <Text style={styles.titleToggle}
        onPress={this.toggleView}>List View</Text>

    </View>

    <View style={styles.shopListView}>

      <FlatList
        horizontal
        style={styles.shopsList}
        data={this.state.data}
        renderItem={({ item: rowData }) => {
          return (

            <View style={styles.shopListItem}>

              <Image source={require('./logo.png')} style={styles.shopImage} />

            </View>
          );
        }}
        keyExtractor={(item, index) => index}
      />

    </View>

    <MapboxGL.MapView>
      <MapboxGL.Camera centerCoordinate={this.state.coordinates[0]} zoomLevel={14} />

      <MapboxGL.MarkerView id='marker1' coordinate={this.state.coordinates[0]}>
        <ImageBackground source={require('./chat.png')}
          style={{ borderColor: 'black', borderWidth: 0, width: 80, height: 80, alignContent: 'center' }}>
          <TouchableOpacity style={{ width: '100%', height: '100%', alignItems: 'center', justifyContent: 'center' }}
            onPress={() => {
              this.setState({ toolTipVisible: true })
            }}>
            <Tooltip
              animated
              isVisible={this.state.toolTipVisible}
              content={<View style={{ width: '100%', height: '100%', backgroundColor: 'white' }}>
                <View style={{ flexDirection: 'row' }}>
                  <Image source={require('./chat.png')} />
                  <View style={{ flexDirection: 'column' }}>
                    <Text style={{ marginHorizontal: 10, marginTop: 10 }}>123, Main st,</Text>
                    <Text style={{ marginHorizontal: 10, marginBottom: 10 }}>Chicago, IL 6061</Text>
                  </View>
                </View>
                <TouchableOpacity
                  style={{ backgroundColor: 'orange', margin: 10, alignItems: 'center' }}
                  onPress={() => { }}
                >
                  <Text style={{ margin: 10, color: 'white' }}>Select Shop</Text>
                </TouchableOpacity>
              </View>}
              placement="top"
              onClose={() => this.setState({ toolTipVisible: false })} >

              <Text style={{ color: 'white', fontWeight: 'bold', fontSize: 20 }} >$50.00</Text>

            </Tooltip>

          </TouchableOpacity>

        </ImageBackground>

      </MapboxGL.MarkerView>

    </MapboxGL.MapView>

 </View>

Styles

mainContainer: {
      flex: 1,
      backgroundColor: theme.colors.white
    },
toggleContainer: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      marginTop: '20@ms',
      marginBottom:'10@ms',
      marginHorizontal: '15@ms',
    },
    titleShop: {
      fontFamily: 'Muli-Bold',
      fontSize: '16@ms',
      color: theme.colors.gray4
    },
    titleToggle: {
      fontFamily: 'Muli-Bold',
      fontSize: '11@ms',
      color: theme.colors.gray4,
      textDecorationLine: 'underline',
      alignSelf:'center'
    },
MapToggleContainer:{
      flexDirection: 'row',
      justifyContent: 'space-between',
      marginTop: '10@ms',
      marginBottom:'15@ms',
      marginHorizontal: '15@ms',
    },
    shopListView:{
      height:'60@ms'
    },
    shopsList:{
      marginLeft:'5@ms',
      marginRight:'15@ms',
    },
    shopListItem:{
      elevation:5,
      backgroundColor:'white',
      marginLeft:'10@ms',
      height:'50@ms',
      width:'50@ms',
      alignItems:'center',
      justifyContent:'center',
      borderRadius:'5@ms'
    },
    shopImage:{
      width:'30@ms',
      height:'30@ms',
    },

And here is a result, as you can see the mapview below list is not visible

Body:
give height and width style to MapboxGL.MapView

<MapboxGL.MapView style={{width:Dimensions.get("window").width,height:400}}>


问:
how do i create a scatter plot in pycharm 2019 IDE
```<code>import pandas as pd
import matplotlib.pyplot as plt
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
path = "https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DA0101EN/auto.csv"
df = pd.read_csv(path)
headers = ["symboling","normalized-losses","make","fuel-type","aspiration", "num-of-doors","body-style",
         "drive-wheels","engine-location","wheel-base", "length","width","height","curb-weight","engine-type",
         "num-of-cylinders", "engine-size","fuel-system","bore","stroke","compression-ratio","horsepower",
         "peak-rpm","city-mpg","highway-mpg","price"]
df.columns = headers
y = df["price"]
x = df["engine-size"]
plt.xlabel("engine")
plt.ylabel("price")
plt.title("Price Vs Engine size")
plt.scatter(x, y)
</code>```

And after this i get "finished with exit code 0" and i don't see any scatter diagram

答: Have you tried using plt.show() at the end?

Body:
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
path = "https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DA0101EN/auto.csv"
df = pd.read_csv(path)
headers = ["symboling","normalized-losses","make","fuel-type","aspiration", "num-of-doors","body-style",
         "drive-wheels","engine-location","wheel-base", "length","width","height","curb-weight","engine-type",
         "num-of-cylinders", "engine-size","fuel-system","bore","stroke","compression-ratio","horsepower",
         "peak-rpm","city-mpg","highway-mpg","price"]
df.columns = headers
y = df["price"]
x = df["engine-size"]
plt.xlabel("engine")
plt.ylabel("price")
plt.title("Price Vs Engine size")
plt.scatter(x, y)

And after this i get "finished with exit code 0" and i don't see any scatter diagram


问:
Passing a Parameter to the function
I am trying to pass the parameter name to the function, but I am unable to pass</p>

```<code>function interfaceName(x,y,z){
return "<div class='iconRow2 linkrow'><a href='javascript:mcrloadgraphdata('+x+'')'>"+x+"</a></div>";
}

function mcrloadgraphdata(interfaceName)
{
    alert(interfaceName);
}
</code>```

答:
I didnt follow your question too well.
But I guessed what you might be asking.

There appears to be a mistake with Single quote and double quotes in your statement
Try this

```<code>    function interfaceName(x,y,z){
         return "<div class='iconRow2 linkrow'><a href=\"javascript:mcrloadgraphdata('"+x+"')\">"+x+"</a></div>";
    }

    function mcrloadgraphdata(interfaceName) {
        alert(interfaceName);
    }
</code>```

Title: Passing a Parameter to the function

Body:
I am trying to pass the parameter name to the function, but I am unable to pass

function interfaceName(x,y,z){
return "
"+x+"
";
}

function mcrloadgraphdata(interfaceName)
{
    alert(interfaceName);
}

Body:
I didnt follow your question too well.
But I guessed what you might be asking.

There appears to be a mistake with Single quote and double quotes in your statement
Try this

    function interfaceName(x,y,z){
         return "<div class='iconRow2 linkrow'><a href=\"javascript:mcrloadgraphdata('"+x+"')\">"+x+"</a></div>";
    }

    function mcrloadgraphdata(interfaceName) {
        alert(interfaceName);
    }


问:
Heap address decrease, and increase
Why does the heap increase and then decrease after a certain level and then increase again?
In linux os

When i study os, and memory structure, i found some strange address increase...

the program is simple, just recursive call for stack and heap increasing.

```<code>void recursive(int count){
long stack;
long* heap;

heap = (long*)malloc(sizeof(long)*100000000000);

        heap = (long*)malloc(sizeof(long)*100000);
        if((long*)heap >= (long*)&stack){
            printf("heap is contact with stack\n");
            exit(1);
        }

printf("%diteration \\ heap : %p || stack : %p\n",count, heap, &stack);
recursive(++count);
</code>```

}

答:
Your heap pointer does not point to the top of the heap. It points to the allocated memory chunk, which could be anywhere. The closest to what you are looking for is the break pointer, which you can find by calling sbrk(0). Note that in modern systems, you don't necessarily have a continuous heap. Here is a detailed explanation:
What does the brk() system call do?

Title: Heap address decrease, and increase

Body:
Why does the heap increase and then decrease after a certain level and then increase again?
In linux os

When i study os, and memory structure, i found some strange address increase...

the program is simple, just recursive call for stack and heap increasing.

void recursive(int count){
long stack;
long* heap;

heap = (long*)malloc(sizeof(long)*100000000000);

        heap = (long*)malloc(sizeof(long)*100000);
        if((long*)heap >= (long*)&stack){
            printf("heap is contact with stack\n");
            exit(1);
        }

printf("%diteration \\ heap : %p || stack : %p\n",count, heap, &stack);
recursive(++count);

}


问:
Anyone familiar with the git error "missing object 0000000000000000000000000000000000000000 for refs/heads/..."?
We are running git v1.7.1 and have gitweb configured.  We also use gitolite for administration, but I do not believe that is germane to this issue.  From time to time we get an error in the Apache log like:

```<code>missing object 0000000000000000000000000000000000000000 for refs/heads/...
</code>```

Where the elipse at the end is typically a branch name.  I believe that the string of zeros is suppost to be a SHA1 value.  Obviously, all zeros is not a SHA1 value.  It is not clear to me where this value is comming from?

I have run git fsck on the server and it did not report an issue, however git gc resolves the problem.  Also, we are able to pull and push to this repository (and that branch) fine.  Only gitweb appears to be effected.

I know others have seen this issue becuase there is a closed question about it here:
Gitweb failure: fatal: missing object 0000000000000000000000000000000000000000 for refs/heads/master
There is no answer to that question.

Additional Information

We have now seen this isssue on our gitolite-admin repository.  We do not have branches in our gitolite-admin repository, so this was not on a branch.

答:
My solution is discarding some history.
Do git clone to somewhere else. copy .git/refs to overwrite the bad ones.

Body:
We are running git v1.7.1 and have gitweb configured.  We also use gitolite for administration, but I do not believe that is germane to this issue.  From time to time we get an error in the Apache log like:

missing object 0000000000000000000000000000000000000000 for refs/heads/...

Where the elipse at the end is typically a branch name.  I believe that the string of zeros is suppost to be a SHA1 value.  Obviously, all zeros is not a SHA1 value.  It is not clear to me where this value is comming from?

I have run git fsck on the server and it did not report an issue, however git gc resolves the problem.  Also, we are able to pull and push to this repository (and that branch) fine.  Only gitweb appears to be effected.

I know others have seen this issue becuase there is a closed question about it here:
Gitweb failure: fatal: missing object 0000000000000000000000000000000000000000 for refs/heads/master
There is no answer to that question.

Additional Information

We have now seen this isssue on our gitolite-admin repository.  We do not have branches in our gitolite-admin repository, so this was not on a branch.


问:
how to fix this Zabbix alert template to work?
Zabbix Version: 4.0 LTS

```<code># template

Alert: {EVENT.NAME}
Severity: {EVENT.SEVERITY}

Top cpu:
{HOST.NAME:sys.process.top.cpu.last()}

Top mem:
{HOST.NAME:sys.process.top.mem.last()}

Problem started at {EVENT.TIME} on {EVENT.DATE}

</code>```

Render result:

```<code>Alert: test top usage
Severity: Disaster

Top cpu:
*UNKNOWN*

Top mem:
*UNKNOWN*

Problem started at 03:35:00 on 2020.05.29
</code>```

How to fix it to normal? I hope it could get the value of the current host.

答:
You can use {ITEM.VALUE<1-9>} macro, as described in
 macros/supported_by_location.

Functions, like last(), are not supported in alerts.

Body:
Zabbix Version: 4.0 LTS

# template

Alert: {EVENT.NAME}
Severity: {EVENT.SEVERITY}

Top cpu:
{HOST.NAME:sys.process.top.cpu.last()}

Top mem:
{HOST.NAME:sys.process.top.mem.last()}

Problem started at {EVENT.TIME} on {EVENT.DATE}

Render result:

Alert: test top usage
Severity: Disaster

Top cpu:
*UNKNOWN*

Top mem:
*UNKNOWN*

Problem started at 03:35:00 on 2020.05.29

How to fix it to normal? I hope it could get the value of the current host.


问:
Too many images in android app
In my android app i have got something like 70-80 images. This is making my app very heavy. What are my options to reduce the size without loing any image. I mean any way to compress them or anything like that?</p>

答:
krio's answer is probably a pretty good way to go.
If you're looking for alternatives, you can zip resources and assets, and then pull them out of the zip on demand when you need them.
I'm not sure how much extra compression that'll give you over the APK compression (and obviously you'll need to add in the time to pull the file out of the zip). Will only 80 or so files, the time to parse through the zip file and pull a file out should be fairly small.</p>

Title: Too many images in android app


问:
How to refresh an AlertDialog in Flutter?
Currently, I have an AlertDialog with an IconButton. The user can click on the IconButton, I have two colors for each click. The problem is that I need to close the AlertDialog and reopen to see the state change of the color icon. I want to change the IconButton color immediately when the user clicks it.

Here is the code:

```<code>bool pressphone = false;
//....
new IconButton(
   icon: new Icon(Icons.phone),
   color: pressphone ? Colors.grey : Colors.green,
   onPressed: () => setState(() => pressphone = !pressphone),
),
</code>```

答:
First you need to use StatefulBuilder. Then i am setting _setState variable, which even could be used outside StatefulBuilder, to set new state.

```<code>StateSetter _setState;
String _demoText = "test";

showDialog(
  context: context,
  builder: (BuildContext context) {

    return AlertDialog(
      content: StatefulBuilder(  // You need this, notice the parameters below:
        builder: (BuildContext context, StateSetter setState) {
          _setState = setState;
          return Text(_demoText);
        },
      ),
    );
  },
);
</code>```

_setState is used same way as setState method. For example like this:

```<code>_setState(() {
    _demoText = "new test text";
});
</code>```

Body:
Currently, I have an AlertDialog with an IconButton. The user can click on the IconButton, I have two colors for each click. The problem is that I need to close the AlertDialog and reopen to see the state change of the color icon. I want to change the IconButton color immediately when the user clicks it.

Here is the code:

bool pressphone = false;
//....
new IconButton(
   icon: new Icon(Icons.phone),
   color: pressphone ? Colors.grey : Colors.green,
   onPressed: () => setState(() => pressphone = !pressphone),
),

Body:
First you need to use StatefulBuilder. Then i am setting _setState variable, which even could be used outside StatefulBuilder, to set new state.

StateSetter _setState;
String _demoText = "test";

showDialog(
  context: context,
  builder: (BuildContext context) {

    return AlertDialog(
      content: StatefulBuilder(  // You need this, notice the parameters below:
        builder: (BuildContext context, StateSetter setState) {
          _setState = setState;
          return Text(_demoText);
        },
      ),
    );
  },
);

_setState is used same way as setState method. For example like this:

_setState(() {
    _demoText = "new test text";
});