问:
How to give each cell random digit number
I want to give each cell a random double-digit number between 50-500
i'm trying to use math.floor(math.random() as function but no success so far

also how I can target only one cell, for example i have 5x5 slots 5 rows 5 col, and I want to target the top left cell in the corner alone, and instead of random generated numbers like the rest cells, i want to give it a symbol where i can control it, so if the symbol is in top left corner, i click on middle for example and it moves there, replacing the generated number which was in the middle and keeping the top left right corner empty

sorry for the trouble, any help really appreciated

```<code><html>
<head>
<style>
td{
border:2px solid black;
width:10px;
height:10px;
}
td:hover{background-color:lightgreen;}
.grn{
background-color:green;
color:white;
}
</style>

<body>
<div id='ff'></div>

<script>
var isCol=0;
var board=[];
for(r=0;r<7;r++){
    var line=[];
    for(c=0;c<7;c++){
        line.push(r);
    }
    board.push(line);
}

function prs(c,r){
    showTable(c,r);
    isCol=(isCol+1)%2;
}

function toColor(col,row,chosen_col,chosen_row){
var ret=false;
switch(isCol){
    case 0:
        if(row==chosen_row){
            ret=true;
        }
        break;
    case 1:
        if(col==chosen_col){
            ret=true;
        }
        break;
}

return ret;
}

function showTable(chosen_col,chosen_row){
var str="";
str+="<table border=1>";
for(row=0;row<7;row++){
    str+="<tr>";
    for(col=0;col<7;col++){
        str+="<td onclick='prs("+col+","+row+")'";
        if(toColor(col,row,chosen_col,chosen_row)){
            str+=" class='grn' ";
        }
        str+=">";
str+=board[row][col];
        str+="</td>";
    }
    str+="</tr>";
}
str+="</table>";

 document.getElementById("ff").innerHTML=str;
}

showTable(-1);
</script>
</body>
</html>

</code>```

答:
I hope I understand you correctly.

Pay attention to Math.floor(Math.random() * (MAX - MIN + 1)) + MIN, don't forget about "+ 1". Without this you will never get 500 (499 is maximum, I try to prove it in comments).

Also you don't have to create single callback to each cell. Better to create one callback to event "click" on table. And than check in what element this event appear. I recommend you to read something about Event Bubbling and Propagation in JavaScript. It's exectly about your task.

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Table</title>
    <style>
        td{
            border:2px solid black;
            width:10px;
            height:10px;
        }

        td:hover{
            background-color:lightgreen;
        }

        .grn {
            background-color:green;
            color:white;
        }
    </style>
</head>
<body>
    <div id="ff"></div>
    <script>
        'use strict';

        const SIZE = 10;        // Size of the table (SIZE x SIZE)
        const MIN = 50;         // Minimal number in cell
        const MAX = 500;        // Maximum number in cell
        const CHOSEN_COL = 0;   // Column where chosen cell is
        const CHOSEN_ROW = 0;   // Row where chosen cell is
        const SYMBOL = 'S';     // Yours 'symbol'

        function showTable() {
            let table = document.createElement('table');
            let chosenTd;   // <td> element of chosen cell

            for (let i = 0; i < SIZE; i++) {
                let tr = document.createElement('tr');
                for (let j = 0; j < SIZE; j++) {
                    let td = document.createElement('td');

                    // 1) Math.random() returns values from 0 (inclusive) to 1 (exclusive)
                    // 2) Math.random() * (MAX - MIN) returns values from 0 (inclusive)
                    // to (MAX - MIN) (exclusive)
                    // 3) Math.random() * (MAX - MIN + 1) returns values from 0 (inclusive)
                    // to (MAX - MIN + 1) (exclusive)
                    // 4) Math.floor(Math.random() * (MAX - MIN + 1)) returns values from 0 (inclusive)
                    // to (MAX - MIN) (inclusive!!!)
                    // 5) Math.floor(Math.random() * (MAX - MIN + 1)) + MIN returns values from
                    // MIN (inclusive) to MAX (inclusive) - exectly what we need
                    //
                    // Pay attention to 'inclusive' and 'exclusive'
                    td.textContent = Math.floor(Math.random() * (MAX - MIN + 1)) + MIN;

                    // Obvious (I hope)
                    if (i == CHOSEN_ROW && j == CHOSEN_COL) {
                        chosenTd = td;
                        chosenTd.className = 'grn';
                        chosenTd.textContent = SYMBOL;
                    }

                    tr.append(td);
                }
                table.append(tr);
            }

            table.onclick = function(e) {
                // If we click not at chosen cell (you call it 'symbol')
                if (e.target != chosenTd) {
                    // Now just free cell where 'symbol' is
                    // And 'move' the 'symbol'

                    e.target.textContent = chosenTd.textContent;

                    chosenTd.className = '';
                    chosenTd.textContent = '';

                    chosenTd = e.target;
                    chosenTd.className = 'grn';
                }
            }

            document.querySelector('#ff').append(table);
        }
    </script>
</body>
</html>
</code>```

Of course, you also have to check that e.target is a cell, not row or full table, for example. But I'm sure, you can do it by yourself.

Body:
I hope I understand you correctly.

Pay attention to Math.floor(Math.random() * (MAX - MIN + 1)) + MIN, don't forget about "+ 1". Without this you will never get 500 (499 is maximum, I try to prove it in comments).

Also you don't have to create single callback to each cell. Better to create one callback to event "click" on table. And than check in what element this event appear. I recommend you to read something about Event Bubbling and Propagation in JavaScript. It's exectly about your task.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Table</title>
    <style>
        td{
            border:2px solid black;
            width:10px;
            height:10px;
        }

        td:hover{
            background-color:lightgreen;
        }

        .grn {
            background-color:green;
            color:white;
        }
    </style>
</head>
<body>
    <div id="ff"></div>
    <script>
        'use strict';

        const SIZE = 10;        // Size of the table (SIZE x SIZE)
        const MIN = 50;         // Minimal number in cell
        const MAX = 500;        // Maximum number in cell
        const CHOSEN_COL = 0;   // Column where chosen cell is
        const CHOSEN_ROW = 0;   // Row where chosen cell is
        const SYMBOL = 'S';     // Yours 'symbol'

        function showTable() {
            let table = document.createElement('table');
            let chosenTd;   // <td> element of chosen cell

            for (let i = 0; i < SIZE; i++) {
                let tr = document.createElement('tr');
                for (let j = 0; j < SIZE; j++) {
                    let td = document.createElement('td');

                    // 1) Math.random() returns values from 0 (inclusive) to 1 (exclusive)
                    // 2) Math.random() * (MAX - MIN) returns values from 0 (inclusive)
                    // to (MAX - MIN) (exclusive)
                    // 3) Math.random() * (MAX - MIN + 1) returns values from 0 (inclusive)
                    // to (MAX - MIN + 1) (exclusive)
                    // 4) Math.floor(Math.random() * (MAX - MIN + 1)) returns values from 0 (inclusive)
                    // to (MAX - MIN) (inclusive!!!)
                    // 5) Math.floor(Math.random() * (MAX - MIN + 1)) + MIN returns values from
                    // MIN (inclusive) to MAX (inclusive) - exectly what we need
                    //
                    // Pay attention to 'inclusive' and 'exclusive'
                    td.textContent = Math.floor(Math.random() * (MAX - MIN + 1)) + MIN;

                    // Obvious (I hope)
                    if (i == CHOSEN_ROW && j == CHOSEN_COL) {
                        chosenTd = td;
                        chosenTd.className = 'grn';
                        chosenTd.textContent = SYMBOL;
                    }

                    tr.append(td);
                }
                table.append(tr);
            }

            table.onclick = function(e) {
                // If we click not at chosen cell (you call it 'symbol')
                if (e.target != chosenTd) {
                    // Now just free cell where 'symbol' is
                    // And 'move' the 'symbol'

                    e.target.textContent = chosenTd.textContent;

                    chosenTd.className = '';
                    chosenTd.textContent = '';

                    chosenTd = e.target;
                    chosenTd.className = 'grn';
                }
            }

            document.querySelector('#ff').append(table);
        }
    </script>
</body>
</html>

Of course, you also have to check that e.target is a cell, not row or full table, for example. But I'm sure, you can do it by yourself.


来源: stackexchange

问:
Mapbox Leaflet Add Popup to GeoJson
I've setup a leaflet map with a mapbox style, which is loading an external GeoJson. That works fine, except it doesn't import any styling parameters from the GeoJson such as the marker-color. Like f.e. :

```<code>   "properties": {
    "marker-color": "#4de21b",
    "marker-size": "medium",
</code>```

Is shown in the default blue'ish marker-color after import.
So that's the first issue. And I guess my second (and more important) issue is connected with this. I'd like to add an infobox-popup for each marker based on the geoJson. Is that possible and how?

Thanks for advice in advance!

My webcode:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>
<script>
// Add AJAX request for data
    var counties = $.ajax({
      url:"https://myurl.net/wp-content/uploads/2020/02/geojson-example2.geojson",
      dataType: "json",
      success: console.log("County data successfully loaded."),
      error: function (xhr) {
        alert(xhr.statusText)
      }
    })
    // Specify that this code should run once the county data request is complete
    $.when(counties).done(function() {
        var map = L.map('map')
            .setView([51.1656914, 10.4515257], 5);
            var basemap = L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
            attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses            /by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
            maxZoom: 18,
            id: 'mapbox/dark-v10',
            accessToken: 'mytoken'}).addTo(map);
        // Add requested external GeoJSON to map
        var kyCounties = L.geoJSON(counties.responseJSON).addTo(map);
    });
</script>
</code>```

The GeoJson

```<code>{  "type": "FeatureCollection",  "features": [
{
  "type": "Feature",
  "properties": {
    "marker-color": "#4de21b",
    "marker-size": "medium",
    "marker-symbol": "",
    "icon":"purpleIcon"
  },
  "geometry": {
    "type": "Point",
    "coordinates": [
      10.52490234375,
      51.631657349449995
    ]
  }
},
{
  "type": "Feature",
  "properties": {
    "marker-color": "#af2ecf",
    "marker-size": "medium",
    "marker-symbol": ""
  },
  "geometry": {
    "type": "Point",
    "coordinates": [
      9.47021484375,
      52.17393169256849
    ]
  }    }  ]}
</code>```

答:
You can use L.geoJSON's pointToLayer & onEachFeature respectively to achieve the desired behavior by passing the color as an argument to return the desired marker icon and again by conditionally checking the geojson feature properties to generate the marker popup.
Below you can find a demo to illustrate the above mentioned by simulating a fake async call to retrieve the geojson as in your case.

<!DOCTYPE html>

  <title>Quick Start - Leaflet</title>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

 <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>

```

ContentLicense: CC BY-SA 4.0

Title: Mapbox Leaflet Add Popup to GeoJson

Body:
I've setup a leaflet map with a mapbox style, which is loading an external GeoJson. That works fine, except it doesn't import any styling parameters from the GeoJson such as the marker-color. Like f.e. :

   "properties": {
    "marker-color": "#4de21b",
    "marker-size": "medium",

Is shown in the default blue'ish marker-color after import.
So that's the first issue. And I guess my second (and more important) issue is connected with this. I'd like to add an infobox-popup for each marker based on the geoJson. Is that possible and how?

Thanks for advice in advance!

My webcode:

The GeoJson

{  "type": "FeatureCollection",  "features": [
{
  "type": "Feature",
  "properties": {
    "marker-color": "#4de21b",
    "marker-size": "medium",
    "marker-symbol": "",
    "icon":"purpleIcon"
  },
  "geometry": {
    "type": "Point",
    "coordinates": [
      10.52490234375,
      51.631657349449995
    ]
  }
},
{
  "type": "Feature",
  "properties": {
    "marker-color": "#af2ecf",
    "marker-size": "medium",
    "marker-symbol": ""
  },
  "geometry": {
    "type": "Point",
    "coordinates": [
      9.47021484375,
      52.17393169256849
    ]
  }    }  ]}

Body:
You can use L.geoJSON's pointToLayer & onEachFeature respectively to achieve the desired behavior by passing the color as an argument to return the desired marker icon and again by conditionally checking the geojson feature properties to generate the marker popup.
Below you can find a demo to illustrate the above mentioned by simulating a fake async call to retrieve the geojson as in your case.

<!DOCTYPE html>
<html>

<head>
  <title>Quick Start - Leaflet</title>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

 <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script>

</head>

<body>
  <div id="mapid" style="height: 100vh;"></div>
  <script>
    var map = L.map("mapid").setView([51.1656914, 10.4515257], 7);

    L.tileLayer(
      "https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw", {
        maxZoom: 18,
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
          '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
          'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
        id: "mapbox/streets-v11",
        tileSize: 512,
        zoomOffset: -1
      }
    ).addTo(map);

    const geojson = {
      type: "FeatureCollection",
      features: [{
          type: "Feature",
          properties: {
            "marker-color": "#4de21b",
            "marker-size": "medium",
            "marker-symbol": "",
            icon: "purpleIcon"
          },
          geometry: {
            type: "Point",
            coordinates: [10.52490234375, 51.631657349449995]
          }
        },
        {
          type: "Feature",
          properties: {
            "marker-color": "#af2ecf",
            "marker-size": "medium",
            "marker-symbol": ""
          },
          geometry: {
            type: "Point",
            coordinates: [9.47021484375, 52.17393169256849]
          }
        }
      ]
    };

    const simulateAsyncCall = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(geojson);
        }, 1000);
      });
    };

    function onEachFeature(feature, layer) {
      const popupContent = `I have marker color <b>${
          feature.properties["marker-color"]
        }</b>, and marker size <b>${feature.properties["marker-size"]}</b>`;

      if (feature.properties && feature.properties.popupContent) {
        popupContent += feature.properties.popupContent;
      }

      layer.bindPopup(popupContent);
    }

    const icon = color =>
      new L.Icon({
        iconUrl: `https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-${
            color === "#af2ecf" ? "violet" : "green"
          }.png`,
        shadowUrl: "https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png",
        iconSize: [25, 41],
        iconAnchor: [12, 41],
        popupAnchor: [1, -34],
        shadowSize: [41, 41]
      });

    simulateAsyncCall().then(geojson => {
      console.log(geojson);
      L.geoJSON(geojson, {
        pointToLayer: function(feature, latlng) {
          const color = feature.properties["marker-color"];
          return L.marker(latlng, {
            icon: icon(color)
          });
        },
        onEachFeature
      }).addTo(map);
    });
  </script>
</body>

</html>


问:
How show list certain row in view?
The list in the view is limited to showing columns. I want to include the column that I want in the columns shown in the view.

How should I do?

```<code>@State var showMyRow = false

var body: some view {
   Vstack {
     Button(“bt”) {
          self.showMyRow.toggle()
      }
    ImageView
     ....
   List {
            ForEach
            .
            .
            . // if showMyRow is true, view show this row
    }
  }
}
</code>```

Above image, showMyRow is false.

After button action, showMyRow is true.
If showMyRow is true, show me at the 7row

答:
I'm guessing that you're trying to present multiple columns horizontally on the screen?

If so, then you can put the Lists inside a Stack

```<code>HStack {
    List {
        Text("Hello")
    }
    List {
        Text("There")
    }
}
</code>```

And if there's a lot of columns, then you can wrap the HStack inside a scroll view.

```<code>var body: some View {
    ScrollView(.horizontal) {
        HStack {
            List {
                Text("column 1")
            }
            List {
                Text("column 2")
            }
            List {
                Text("column 3")
            }
            List {
                Text("column 4")
            }
        }
            .frame(width: 1000, height: 800)
            .background(Color.red)
    }
}
</code>```

Title: How show list certain row in view?

Body:
The list in the view is limited to showing columns. I want to include the column that I want in the columns shown in the view.

How should I do?

@State var showMyRow = false

var body: some view {
   Vstack {
     Button(“bt”) {
          self.showMyRow.toggle()
      }
    ImageView
     ....
   List {
            ForEach
            .
            .
            . // if showMyRow is true, view show this row
    }
  }
}

Above image, showMyRow is false.

After button action, showMyRow is true.
If showMyRow is true, show me at the 7row

Body:
I'm guessing that you're trying to present multiple columns horizontally on the screen?

If so, then you can put the Lists inside a Stack

HStack {
    List {
        Text("Hello")
    }
    List {
        Text("There")
    }
}

And if there's a lot of columns, then you can wrap the HStack inside a scroll view.

var body: some View {
    ScrollView(.horizontal) {
        HStack {
            List {
                Text("column 1")
            }
            List {
                Text("column 2")
            }
            List {
                Text("column 3")
            }
            List {
                Text("column 4")
            }
        }
            .frame(width: 1000, height: 800)
            .background(Color.red)
    }
}


问:
How to make an undo feature for a board game in c#?
I'm finding it difficult implementing an undo feature for a game that I have developed using c# forms. I would like to have a button on the game screen which ,when clicked, reverses the move the player just made. </p>

<p>Anyone have an ideas how I would go about doing this ? I have been told that a stack is the best way to go about doing this but I'm unsure how to implement it. </p>

答:
You can wrap your game events into actions that can have methods Do() and Undo().

Lets take Paint program as an example. User draws line on the given coordinates, you put LineDrawnEvent on the stack with all related data, and invoke Do() method, which actually draws a line on the canvas. When user clicks undo button, you pop item from your stack and invoke Undo() method, which in LineDrawnEvent should remove the line which user has drawn.

You can also have interface for that, something like IProgramAction with Do() and Undo() methods, so you can have different events, for example CircleDrawnEvent and RectangularDrawnEvent in the same stack.

And stack in your code will look something like

```<code>public Stack<IProgramAction> ProgramStack { get; set; }
</code>```

Body:
I'm finding it difficult implementing an undo feature for a game that I have developed using c# forms. I would like to have a button on the game screen which ,when clicked, reverses the move the player just made.

Anyone have an ideas how I would go about doing this ? I have been told that a stack is the best way to go about doing this but I'm unsure how to implement it.

Body:
You can wrap your game events into actions that can have methods Do() and Undo().

Lets take Paint program as an example. User draws line on the given coordinates, you put LineDrawnEvent on the stack with all related data, and invoke Do() method, which actually draws a line on the canvas. When user clicks undo button, you pop item from your stack and invoke Undo() method, which in LineDrawnEvent should remove the line which user has drawn.

You can also have interface for that, something like IProgramAction with Do() and Undo() methods, so you can have different events, for example CircleDrawnEvent and RectangularDrawnEvent in the same stack.

And stack in your code will look something like

public Stack<IProgramAction> ProgramStack { get; set; }


问:
Deserializing C data
I'm receiving a struct over a network from a C server to my Python client. The protocol is UDP. I have no control over the server and it's protocols/data formats. It consists of this struct (yes, an IPv4 + port):

```<code>struct ip_s {
    uint8_t i1;
    uint8_t i2;
    uint8_t i3;
    uint8_t i4;
    uint16_t port; // big endian
};
</code>```

Apart from the port which is converted to big-endian the data is sent "as-is", casted to a (char*).

How can I receive this struct to a format that is processable by Python?

Misc info:

Python 2.7 or 3.x

Cross-platform

Preferably solution using only built-in modules

答:
Look into struct.unpack

It will probably look something like this:

```<code># socket setup

(buffer, sockaddress) = mysocket.recvfrom(6)
if len(buffer)== 6:
    i1,i2,i3,i4, port = struct.unpack('!BBBBH', buffer)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Deserializing C data

Body:
I'm receiving a struct over a network from a C server to my Python client. The protocol is UDP. I have no control over the server and it's protocols/data formats. It consists of this struct (yes, an IPv4 + port):

struct ip_s {
    uint8_t i1;
    uint8_t i2;
    uint8_t i3;
    uint8_t i4;
    uint16_t port; // big endian
};

Apart from the port which is converted to big-endian the data is sent "as-is", casted to a (char*).

How can I receive this struct to a format that is processable by Python?

Misc info:

Python 2.7 or 3.x

Cross-platform

Preferably solution using only built-in modules

Body:
Look into struct.unpack

It will probably look something like this:

# socket setup

(buffer, sockaddress) = mysocket.recvfrom(6)
if len(buffer)== 6:
    i1,i2,i3,i4, port = struct.unpack('!BBBBH', buffer)


问:
Getting coordinates of the closest data point on matplotlib plot
I am using matplotlib with NavigationToolbar2QT.  The toolbar is showing the position of the cursor.  But I would like that the cursor snaps to the nearest data point (when close enough) or simply show the coordinate of nearest data point.  Can that be somehow arranged?

答:
The following code will print the coordinates of the dot closest to the mouse when you click.</p>

```<code>import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
fig,ax = plt.subplots()
plt.scatter(x, y)
points = list(zip(x,y))
def distance(a,b):
    return(sum([(k[0]-k[1])**2 for k in zip(a,b)])**0.5)
def onclick(event):
    dists = [distance([event.xdata, event.ydata],k) for k in points]
    print(points[dists.index(min(dists))])
fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
</code>```

Body:
The following code will print the coordinates of the dot closest to the mouse when you click.

import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
fig,ax = plt.subplots()
plt.scatter(x, y)
points = list(zip(x,y))
def distance(a,b):
    return(sum([(k[0]-k[1])**2 for k in zip(a,b)])**0.5)
def onclick(event):
    dists = [distance([event.xdata, event.ydata],k) for k in points]
    print(points[dists.index(min(dists))])
fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()


问:
How to mix two types of navigation in react native
I'm working on an application using React Native. I would like to have a bottom navigation on my application (5.x). After this done, I also would like to let user to navigate on other users profile view.
But, I don't want that this new screen appear on the bottom navigation. I don't know how to do that. Does I need to mix stack navigation and bottom navigation ? How to do that ? </p>

答:
I've add a bottom tab navigator like this :

import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

import DetailsScreen from '../Screens/DetailsScreen';
import HomeScreen from '../Screens/HomeScreen';
import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import TestScreen from '../Screens/TestScreen';
import {StyleSheet} from 'react-native';

const Tab = createBottomTabNavigator();

export default class Navigation {
    render() {
        return (
            <NavigationContainer style={styles.navigationContainer}>
                <Tab.Navigator style={styles.tabNavigator}>
                    <Tab.Screen style={styles.tabScreen} name="Detail" component={DetailsScreen} />
                    <Tab.Screen style={styles.tabScreen} name="Home" component={HomeScreen} />
                    <Tab.Screen style={styles.tabScreen} name="Test" component={TestScreen} hide={true} />
                </Tab.Navigator>
            </NavigationContainer>
        );
    }
}

const styles = StyleSheet.create({

});```
</div>
</div>
</p>

<p>This works fine ! After that, I added a stack navigator into my home screen (in order to have navigation through screens that are not in the tab navigator).</p>

<p>But, it doesn't works fine because it split my screen. My stack navigator looks like this : </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import { createStackNavigator } from '@react-navigation/stack';
import HomeScreen from '../Screens/HomeScreen';
import DetailsScreen from '../Screens/DetailsScreen';
import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
const Stack = createStackNavigator();

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

I added those two files into my App file like using the tags  and , after import.

import ....

class App extends React.Component{

  render(){
    return (
        <View style={styles.container}>
          <Navigation />
          <StackNavigation />
        </View>
    );
  }
};```

Body:
I've add a bottom tab navigator like this :

import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

import DetailsScreen from '../Screens/DetailsScreen';
import HomeScreen from '../Screens/HomeScreen';
import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import TestScreen from '../Screens/TestScreen';
import {StyleSheet} from 'react-native';

const Tab = createBottomTabNavigator();

export default class Navigation {
    render() {
        return (
            <NavigationContainer style={styles.navigationContainer}>
                <Tab.Navigator style={styles.tabNavigator}>
                    <Tab.Screen style={styles.tabScreen} name="Detail" component={DetailsScreen} />
                    <Tab.Screen style={styles.tabScreen} name="Home" component={HomeScreen} />
                    <Tab.Screen style={styles.tabScreen} name="Test" component={TestScreen} hide={true} />
                </Tab.Navigator>
            </NavigationContainer>
        );
    }
}

const styles = StyleSheet.create({

});

This works fine ! After that, I added a stack navigator into my home screen (in order to have navigation through screens that are not in the tab navigator).

But, it doesn't works fine because it split my screen. My stack navigator looks like this :

import { createStackNavigator } from '@react-navigation/stack';
import HomeScreen from '../Screens/HomeScreen';
import DetailsScreen from '../Screens/DetailsScreen';
import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
const Stack = createStackNavigator();

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

I added those two files into my App file like using the tags  and , after import.

import ....

class App extends React.Component{

  render(){
    return (
        <View style={styles.container}>
          <Navigation />
          <StackNavigation />
        </View>
    );
  }
};


问:
R renaming file extension
I have tried looking at File extension renaming in R and using the script without any luck. My question is very much the same.

I have a bunch of files with the a file extension that I want to change. I have used the following code but cannot get the last step to work.

I know similar questions have been asked before but I'm simply stuck and therefore reaching out anyway.

```<code>startingDir<-"/Users/anders/Documents/Juni 2019/DATA"
endDir<-"/Users/anders/Documents/Juni 2019/DATA/formatted"

#List over files in startingDir with the extension .zipwblibcurl that I want to replace
old_files<-list.files(startingDir,pattern = "\\.zipwblibcurl")

#View(old_files)

#Renaming the file extension and making a new list i R changing the file extension from .zipwblibcurl to .zip
new_files <- gsub(".zipwblibcurl", ".zip", old_files)

#View(new_files)

#Replacing the old files in the startingDir. Eventually I would like to move them to newDir. For simplicity I have just tried as in the other post without any luck:...
file.rename( old_files, new_files)
</code>```

After running file.rename I get the output FALSE for every entry.

答:
Like @StéphaneLaurent said, it's most likely that R tries to look in the current working directory for the files and can't find them. You can correct this by adding

file.rename(paste(startingDir, old_files, sep = "/"), paste(newDir, new_files, sep = "/"))

Title: R renaming file extension

Body:
I have tried looking at File extension renaming in R and using the script without any luck. My question is very much the same.

I have a bunch of files with the a file extension that I want to change. I have used the following code but cannot get the last step to work.

I know similar questions have been asked before but I'm simply stuck and therefore reaching out anyway.

startingDir<-"/Users/anders/Documents/Juni 2019/DATA"
endDir<-"/Users/anders/Documents/Juni 2019/DATA/formatted"

#List over files in startingDir with the extension .zipwblibcurl that I want to replace
old_files<-list.files(startingDir,pattern = "\\.zipwblibcurl")

#View(old_files)

#Renaming the file extension and making a new list i R changing the file extension from .zipwblibcurl to .zip
new_files <- gsub(".zipwblibcurl", ".zip", old_files)

#View(new_files)

#Replacing the old files in the startingDir. Eventually I would like to move them to newDir. For simplicity I have just tried as in the other post without any luck:...
file.rename( old_files, new_files)

After running file.rename I get the output FALSE for every entry.


问:
What is Kotlin for C++ push_back() and pop_back() on a string?
In C++ creating and manipulating a mutable stack of characters is rather simple. I use a built-in standard data type (std::string), use a push and pop fuctions that comes with it and can directly print the results. None of this requires creating additional classes or functions.

```<code>#include <iostream>

int main()
{
    std::string path {};
    path.push_back('L');
    path.push_back('R');
    path.pop_back();
    std::cout << path;
}
</code>```

Produces:

```<code>L
</code>```

What is Kotlin for C++ push_back() and pop_back() as a stack of characters?

The question is not how can I implement these as member functions in Kotlin.

C++ Shell code

答:
Strings are immutable, so you won't find an exact equivalent.
While StringBuilder is generally considered to be a decent string buffer type, deleteCharAt copies the entire backing array.

You can use setLength for this purpose. Note that, as with std::string, this does not do anything more than modify the internal length of the string buffer:

```<code>val string = StringBuilder("Hello")
string.append(", world!")
string.setLength(string.length - 1)
</code>```

Alternatively, take the more functional approach and work with immutable values:

```<code>var string = "Hello"
string += ", world!"
string = string.dropLast(1)
</code>```

As already stated by other answerers/commenters, if what you really want is a stack or deque, see Deque and ArrayDeque (seeing as you did not mention std::stack or std::deque in your question, I do not believe this to be the case; not to mention that a stack of characters isn't inherently very useful.)

Taking OP's comment into account, this should be an idiomatic solution:

```<code>enum class Move {
    Left, Right, Forward
}

val moves = ArrayDeque<Move>()

// Push a move:
moves.push(Move.Left)

// Pop a move:
val lastMove = moves.pop()
</code>```

See also Why should I use Deque over Stack? for an explanation of Java's unfortunate history.

Body:
In C++ creating and manipulating a mutable stack of characters is rather simple. I use a built-in standard data type (std::string), use a push and pop fuctions that comes with it and can directly print the results. None of this requires creating additional classes or functions.

#include <iostream>

int main()
{
    std::string path {};
    path.push_back('L');
    path.push_back('R');
    path.pop_back();
    std::cout << path;
}

Produces:

L

What is Kotlin for C++ push_back() and pop_back() as a stack of characters?

The question is not how can I implement these as member functions in Kotlin.

C++ Shell code

Body:
Strings are immutable, so you won't find an exact equivalent.
While StringBuilder is generally considered to be a decent string buffer type, deleteCharAt copies the entire backing array.

You can use setLength for this purpose. Note that, as with std::string, this does not do anything more than modify the internal length of the string buffer:

val string = StringBuilder("Hello")
string.append(", world!")
string.setLength(string.length - 1)

Alternatively, take the more functional approach and work with immutable values:

var string = "Hello"
string += ", world!"
string = string.dropLast(1)

As already stated by other answerers/commenters, if what you really want is a stack or deque, see Deque and ArrayDeque (seeing as you did not mention std::stack or std::deque in your question, I do not believe this to be the case; not to mention that a stack of characters isn't inherently very useful.)

Taking OP's comment into account, this should be an idiomatic solution:

enum class Move {
    Left, Right, Forward
}

val moves = ArrayDeque<Move>()

// Push a move:
moves.push(Move.Left)

// Pop a move:
val lastMove = moves.pop()

See also Why should I use Deque over Stack? for an explanation of Java's unfortunate history.


问:
highlight last 3 number in the string
how to highlight last 3 number in the string:
ab9c5lek94ke72koe8nsk9

i want output:

ab9c5lek94ke72koe8nsk9

i tried following:

```<code>$str = "ab9c5lek94ke72koe8nsk9";
$numbers = preg_replace('/[^0-9]/', '', $str );
$last3 = substr($numbers, -3);
$highlights = str_split($last3);
$output = preg_replace('/'.implode('|', $highlights).'/i', '<b>$0</b>', $str);

</code>```

but it highlight:

ab9c5lek94ke72koe8nsk9

答:
You can split the string on the 3rd from last number, then highlight everything in that sub string and then recombine the substrings.

In my example, I get all of the numbers in the string and put them in array. Then I use that array to get the delimiter (72 in your example), then use that to split the string into two arrays, at that point you can highlight everything in array[1] and then combine it back into array[0]

```<code>$str = "ab9c5lek94ke72koe8nsk9";
// get all of the numbers in order and place into it's own array
$numbers = trim(preg_replace('/[^0-9]/', ' ', $str ));
$numbers = preg_split('/\s+/', $numbers);

// using that get the delimiter to where to split the string. and split.
$delim = $numbers[count($numbers)-3];
$arr = explode($delim, $str);
$arr[1] = $delim . $arr[1];

// then highlight everything in $arr[1]
// then combine $arr[0] and $arr[1]
</code>```

Title: highlight last 3 number in the string

Body:
how to highlight last 3 number in the string:
ab9c5lek94ke72koe8nsk9

i want output:

ab9c5lek94ke72koe8nsk9

i tried following:

$str = "ab9c5lek94ke72koe8nsk9";
$numbers = preg_replace('/[^0-9]/', '', $str );
$last3 = substr($numbers, -3);
$highlights = str_split($last3);
$output = preg_replace('/'.implode('|', $highlights).'/i', '$0', $str);

but it highlight:

ab9c5lek94ke72koe8nsk9

Body:
You can split the string on the 3rd from last number, then highlight everything in that sub string and then recombine the substrings.

In my example, I get all of the numbers in the string and put them in array. Then I use that array to get the delimiter (72 in your example), then use that to split the string into two arrays, at that point you can highlight everything in array[1] and then combine it back into array[0]

$str = "ab9c5lek94ke72koe8nsk9";
// get all of the numbers in order and place into it's own array
$numbers = trim(preg_replace('/[^0-9]/', ' ', $str ));
$numbers = preg_split('/\s+/', $numbers);

// using that get the delimiter to where to split the string. and split.
$delim = $numbers[count($numbers)-3];
$arr = explode($delim, $str);
$arr[1] = $delim . $arr[1];

// then highlight everything in $arr[1]
// then combine $arr[0] and $arr[1]


问:
Transition to view controller in Menu Bar
I finished following this Tutorial on a Menu Side Bar by Gary Tokman (https://www.youtube.com/watch?v=vKh1b3ctCf4  3 PART SERIES), where he creates a menu bar that opens a view that changes color based on the item in the menu bar he presses on.
 However since I actually want to make it open view controllers, I was looking in the comments to see if someone had the same idea, which they did in the top comment.
 However what the user is doing, is everytime a menu item is selected, it just places a subview on top of the current view.
 After using the menu bar a couple of times, you can see that the views are just stacking on each other and memory is building up.
 Is there a viable way to remove each view when a new menu item is selected or some other method.
 Also another side question of this would be: when the menu bar is opened is there a way to touch the black part of the screen and close it without selecting a menu item. Thanks in advance!

答:
For changing view controller implementation of container view controller seems to be the best solution. As for your questions:

Is there a viable way to remove each view when a new menu item is selected or some other method.

Yes, it looks like that (for example in HomeViewController):
before adding new view call this method

```<code>func clearSubviews() {
            for v in self.view.subviews {
                    v.removeFromSuperview()
                }
        }
</code>```

For when the menu bar is opened is there a way to touch the black part of the screen and close it without selecting a menu item.

just create a method for transitioning back - basically like animateTransition(...) but without changing anything except frames. Then create gesture recognizer and add it to dimmingView like that:

```<code>var recognizer = UITapGestureRecognizer.init(target: self, action: #selector(transitionBack))
        dimmingView.addGestureRecognizer(recognizer)
</code>```

gesture recognizer shouldn't get called when dimmingView alpha is set to zero so it won't be called when menu is hidden.

of course transitionBack must have @objc adnotation to make it possible to be action in this recognizer.

Good luck!

Body:
For changing view controller implementation of container view controller seems to be the best solution. As for your questions:

Is there a viable way to remove each view when a new menu item is selected or some other method.

Yes, it looks like that (for example in HomeViewController):
before adding new view call this method

func clearSubviews() {
            for v in self.view.subviews {
                    v.removeFromSuperview()
                }
        }

For when the menu bar is opened is there a way to touch the black part of the screen and close it without selecting a menu item.

just create a method for transitioning back - basically like animateTransition(...) but without changing anything except frames. Then create gesture recognizer and add it to dimmingView like that:

var recognizer = UITapGestureRecognizer.init(target: self, action: #selector(transitionBack))
        dimmingView.addGestureRecognizer(recognizer)

gesture recognizer shouldn't get called when dimmingView alpha is set to zero so it won't be called when menu is hidden.

of course transitionBack must have @objc adnotation to make it possible to be action in this recognizer.

Good luck!


问:
Python 3.5 create virtualenv with python2.7
I have Python 3.5 installed in my windows machine and that is the only version I have on my computer. I want to create a python2.7 virtual environment to try out a certain package. Is it possible to create a virtual environment with python2.7 binaries without installing Python 2.7 in my system?</p>

答:
You don't need to have your Python interpreter on $PATH, you can tell virtualenv where to find it. I found this blog post Installing Multiple Python Versions on Windows Using Virtualenv but the TL;DR is:

Open Command Prompt and enter pip install virtualenv.

Download the desired python version (do NOT add to PATH!), and remember the path\to\new_python.exe of the newly installed version.

To create a virtualenv, open Command Prompt and enter virtualenv \path\to\env -p path\to\new_python.exe.

To install packages:

Activate virtualenv: open Command Prompt and enter path\to\env\Scripts\activate.bat.

Install desired packages with pip.

Deactivate with deactivate.

Note python3 -m venv \path\to\env doesn't seem to suppport the -p parameter, you have to use virtualenv.


问:
How to set cart expiration in woocommerce within 15 minutes?
I have a wordpress website that allows non logged-in customers to order with the code below

```<code>global $woocommerce;
$woocommerce->session->set_customer_session_cookie(true);
</code>```

The issue that I am facing right now is that the products left unordered are left in cart because all non-logged-in custumers share the same woocommerce session.

I am thinking of setting an expiry time to the session or the cart so that it can clear products in cart.

The code that I saw in: Woocommerce Set Cart Expiration Interval returns 72 hours in seconds

```<code>add_filter('wc_session_expiring', 'filter_ExtendSessionExpiring' );
add_filter('wc_session_expiration' , 'filter_ExtendSessionExpired' );

function filter_ExtendSessionExpiring($seconds) {
    return 60 * 60 * 71;
}
function filter_ExtendSessionExpired($seconds) {
   return 60 * 60 * 72;
}
</code>```

Do you know how can I make the filter return every 15 minutes?

Any idea is appreciated. Thanks...

答:
Add the following to your themes functions.php file

```<code>add_filter('wc_session_expiring', 28800);
add_filter('wc_session_expiration' , 28800);
</code>```

28800 is 8 hours in seconds so replace this with 900

Body:
I have a wordpress website that allows non logged-in customers to order with the code below

global $woocommerce;
$woocommerce->session->set_customer_session_cookie(true);

The issue that I am facing right now is that the products left unordered are left in cart because all non-logged-in custumers share the same woocommerce session.

I am thinking of setting an expiry time to the session or the cart so that it can clear products in cart.

The code that I saw in: Woocommerce Set Cart Expiration Interval returns 72 hours in seconds

add_filter('wc_session_expiring', 'filter_ExtendSessionExpiring' );
add_filter('wc_session_expiration' , 'filter_ExtendSessionExpired' );

function filter_ExtendSessionExpiring($seconds) {
    return 60 * 60 * 71;
}
function filter_ExtendSessionExpired($seconds) {
   return 60 * 60 * 72;
}

Do you know how can I make the filter return every 15 minutes?

Any idea is appreciated. Thanks...

Body:
Add the following to your themes functions.php file

add_filter('wc_session_expiring', 28800);
add_filter('wc_session_expiration' , 28800);

28800 is 8 hours in seconds so replace this with 900


问:
Pass a maven -D parameter to a java class?
What's is the best approach to use mvn to pass custom parameters to a class?

Example :

```<code>    ~ mvn clean verify -DparamHere=QA1
</code>```

```<code>    // Pseudo code : I need to pass a param for ${paramHere}

    @Config.Sources({"classpath:${paramHere}.properties"})
    public interface EnvConfig extends Config {
     // code here
    }
</code>```

I can use TestNG @Parameters, but I am running a JUNIT test so - TestNG is a no go for me.

答:
Solution: You can still pass the variable via -DparamHere out of the box.
At least in my case @Config.Sources knows where to parse the param.

Body:
What's is the best approach to use mvn to pass custom parameters to a class?

Example :

    ~ mvn clean verify -DparamHere=QA1

    // Pseudo code : I need to pass a param for ${paramHere}

    @Config.Sources({"classpath:${paramHere}.properties"})
    public interface EnvConfig extends Config {
     // code here
    }

I can use TestNG @Parameters, but I am running a JUNIT test so - TestNG is a no go for me.


问:
JavaScript substring without splitting emoji
in my js I am trying to substring() text which generally works but unfortunately decapitates emojis.

```<code>usaText = "AZ"
splitText = usaText.substring(0,2) //"A�"
splitText = usaText.substring(0,3) //"A"
splitText = usaText.substring(0,4) //"A�"
splitText = usaText.substring(0,5) //"A"
</code>```

Is there a way to use substring without breaking emoji? In my production code I cut at about 40 characters and I wouldn't mind if it was 35 or 45. I have thought about simply checking whether the 40th character is a number or between a-z but that wouldn't work if you got a text full of emojis. I could check whether the last character is one that "ends" an emoji by pattern matching but this also seems a bit weird performance-wise.

Am I missing something? With all the bloat that JavaScript carries, is there no built-in count that sees emoji as one?

To the Split JavaScript string into array of codepoints? (taking into account "surrogate pairs" but not "grapheme clusters") thing:

```<code>chrs = Array.from( usaText )
(4) ["A", "", "", "Z"]
0: "A"
1: ""
2: ""
3: "Z"
length: 4
</code>```

That's one too many unfortunately.

答:
Disclaimer: This is just extending the above comment by Mike 'Pomax' Kamermans because to me it is actually a much simpler, applicable answer (for those of us who don't like reading through all the comments):

Array.from(str) splits your string into individual unicode characters without breaking them between bytes.

See Split JavaScript string into array of codepoints? (taking into account "surrogate pairs" but not "grapheme clusters") for details.

Body:
in my js I am trying to substring() text which generally works but unfortunately decapitates emojis.

usaText = "AZ"
splitText = usaText.substring(0,2) //"A�"
splitText = usaText.substring(0,3) //"A"
splitText = usaText.substring(0,4) //"A�"
splitText = usaText.substring(0,5) //"A"

Is there a way to use substring without breaking emoji? In my production code I cut at about 40 characters and I wouldn't mind if it was 35 or 45. I have thought about simply checking whether the 40th character is a number or between a-z but that wouldn't work if you got a text full of emojis. I could check whether the last character is one that "ends" an emoji by pattern matching but this also seems a bit weird performance-wise.

Am I missing something? With all the bloat that JavaScript carries, is there no built-in count that sees emoji as one?

To the Split JavaScript string into array of codepoints? (taking into account "surrogate pairs" but not "grapheme clusters") thing:

chrs = Array.from( usaText )
(4) ["A", "", "", "Z"]
0: "A"
1: ""
2: ""
3: "Z"
length: 4

That's one too many unfortunately.


问:
How do I interact with the four Eloquent models correctly?
The project consists of four related tables:

orders (id, status, client_email, partner_id)

order_products (id, order_id, product_id, quantity, price)

partners (id, email, name)

prods (id, name, price, vendor_id)

creating 4 models:

```<code>    <?php
    //App\Order.php
    namespace App;
    use Illuminate\Database\Eloquent\Model;

    class Order extends Model
    {
        protected $fillable = [
      'id',  'status', 'client_email', 'partner_id',
    ];

public function partner()
  {
    return $this->belongsTo('App\Partner');
  }

public function order_product()
  {
//belongsToMany - server error
    return $this->belongsTo('App\Prod', 'order_products');
  }

public function prod()
  {
    return $this->belongsTo('App\Prod');
  }

    }
</code>```

```<code><?php
//App\Partner.php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Partner extends Model
{
   protected $fillable = ['id', 'email', 'name'];

public function order()
  {
    return $this->hasOne('App\Order');
  }

}
</code>```

```<code>    <?php
    //App\Order_product.php
    namespace App;
    use Illuminate\Database\Eloquent\Model;

    class Order_product extends Model
    {
        protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];

 public function order()
  {
    return $this->hasOne('App\Order');
  }

    }
</code>```

```<code>    <?php
    //App\Prod.php
    namespace App;
    use Illuminate\Database\Eloquent\Model;

    class Prod extends Model
    {
        protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];

    public function order()
  {
    return $this->belongsToMany('App\Order', 'order_products');
  }

    }
</code>```

creating Order Resources:

```<code><?php
//App\Http\Resources\Order.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;

class Order extends JsonResource
{
    public function toArray($request)
{
    return [
        'id'           => $this->id,
        'status'       => $this->status,
        'client_email' => $this->client_email,
        'partner_id'   => $this->partner_id,
        'partner_name' => $this->partner->name,

        //return server error
        'product_id'   => Prod::collection($this->order_product),
        'name'         => $this->prod->name,

    ];

}

}
</code>```

creating Prod Resource:

```<code><?php
//App/Http/Resources\Prode.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;

class Prod extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id'      => $this->id,
            'name'    => $this->name,
            'price'   => $this->price,
        ];
    }
}
</code>```

And return from Order Controller:

```<code><?php
//App\Http\Controllers\Api\OrderController.php
namespace App\Http\Controllers\Api;

use App\Order;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Resources\Order as OrderResource;

class OrderController extends Controller
{
public function index()
  {
    $orders = Order::with(['partner', 'order_product', 'prod'])->get();
    return OrderResource::collection($orders);
   }
}
</code>```

How do I get the product name in the order?

答:
Order_product seems like a name for a pivot table. This isn't necessary in laravel because the frameworks assumes the table structure by default. The recommended approach is creating the following models:

Order

namespace App;
use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $fillable = [
        'id',  'status', 'client_email', 'partner_id',
    ];

    public function partner()
    {
        return $this->belongsTo('App\Partner');
    }

    public function products()
    {
        return $this->belongsToMany('App\Product', 'order_products');
    }

    public function prod()
    {
        return $this->belongsTo('App\Prod');
    }
}
```

<ul>
<li>Product (Prod)</li>
</ul>

<pre class="lang-php prettyprint-override"><code>namespace App;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'prod';
    protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];

    public function orders()
    {
        return $this->belongsToMany('App\Order', 'order_products');
    }
}
</code>```

and with the following resources:

OrderResource

```<code><?php
//App\Http\Resources\Order.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;

class OrderResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id'           => $this->id,
            'status'       => $this->status,
            'partner_id'   => $this->partner_id,
            'partner_name' => $this->partner->name,
           'products'    =>  ProductResource::collection($this->products),
           'name'          => $this->prod->name,
        ];

    }
}
</code>```

ProductResource

```<code><?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;

class ProductResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id'           => $this->id,
            'name'       => $this->name,
            'price'   => $this->price,
        ];

    }
}
</code>```

more details over many to many relations can be found in the docs.

Body:
The project consists of four related tables:

orders (id, status, client_email, partner_id)

order_products (id, order_id, product_id, quantity, price)

partners (id, email, name)

prods (id, name, price, vendor_id)

creating 4 models:

    <?php
    //App\Order.php
    namespace App;
    use Illuminate\Database\Eloquent\Model;

    class Order extends Model
    {
        protected $fillable = [
      'id',  'status', 'client_email', 'partner_id',
    ];

public function partner()
  {
    return $this->belongsTo('App\Partner');
  }

public function order_product()
  {
//belongsToMany - server error
    return $this->belongsTo('App\Prod', 'order_products');
  }

public function prod()
  {
    return $this->belongsTo('App\Prod');
  }

    }

<?php
//App\Partner.php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Partner extends Model
{
   protected $fillable = ['id', 'email', 'name'];

public function order()
  {
    return $this->hasOne('App\Order');
  }

}

    <?php
    //App\Order_product.php
    namespace App;
    use Illuminate\Database\Eloquent\Model;

    class Order_product extends Model
    {
        protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];

 public function order()
  {
    return $this->hasOne('App\Order');
  }

    }

    <?php
    //App\Prod.php
    namespace App;
    use Illuminate\Database\Eloquent\Model;

    class Prod extends Model
    {
        protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];

    public function order()
  {
    return $this->belongsToMany('App\Order', 'order_products');
  }

    }

creating Order Resources:

<?php
//App\Http\Resources\Order.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;

class Order extends JsonResource
{
    public function toArray($request)
{
    return [
        'id'           => $this->id,
        'status'       => $this->status,
        'client_email' => $this->client_email,
        'partner_id'   => $this->partner_id,
        'partner_name' => $this->partner->name,

        //return server error
        'product_id'   => Prod::collection($this->order_product),
        'name'         => $this->prod->name,

    ];

}

}

creating Prod Resource:

<?php
//App/Http/Resources\Prode.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;

class Prod extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id'      => $this->id,
            'name'    => $this->name,
            'price'   => $this->price,
        ];
    }
}

And return from Order Controller:

<?php
//App\Http\Controllers\Api\OrderController.php
namespace App\Http\Controllers\Api;

use App\Order;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Resources\Order as OrderResource;

class OrderController extends Controller
{
public function index()
  {
    $orders = Order::with(['partner', 'order_product', 'prod'])->get();
    return OrderResource::collection($orders);
   }
}

How do I get the product name in the order?

Body:
Order_product seems like a name for a pivot table. This isn't necessary in laravel because the frameworks assumes the table structure by default. The recommended approach is creating the following models:

Order

namespace App;
use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $fillable = [
        'id',  'status', 'client_email', 'partner_id',
    ];

    public function partner()
    {
        return $this->belongsTo('App\Partner');
    }

    public function products()
    {
        return $this->belongsToMany('App\Product', 'order_products');
    }

    public function prod()
    {
        return $this->belongsTo('App\Prod');
    }
}

Product (Prod)

namespace App;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'prod';
    protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];

    public function orders()
    {
        return $this->belongsToMany('App\Order', 'order_products');
    }
}

and with the following resources:

OrderResource

<?php
//App\Http\Resources\Order.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;

class OrderResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id'           => $this->id,
            'status'       => $this->status,
            'partner_id'   => $this->partner_id,
            'partner_name' => $this->partner->name,
           'products'    =>  ProductResource::collection($this->products),
           'name'          => $this->prod->name,
        ];

    }
}

ProductResource

<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;

class ProductResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id'           => $this->id,
            'name'       => $this->name,
            'price'   => $this->price,
        ];

    }
}

more details over many to many relations can be found in the docs.


问:
How do I define a static variable in base class that can be called in generic methods?
I have an extremely complicated relational database, which is causing me to use the same code over and over again. I'm trying to clean it up using a fairly sophisticated TableRow class, however I've came across one major problem. The best way I can explain what I'm trying to do is by some example code:

```<code>public abstract class TableRow
{
    public abstract string TableName { get; }
    public abstract string PrimaryKey { get; }

    //there's a lot of these sort of methods for multi-to-multi links, links by two columns, etc
    protected T GetLinkedRow<T>() where T : TableRow
    {
        //here I need to get TableName and PrimaryKey (without creating a new instance of T)
    }
 }

 public class Person : TableRow
 {
    public override string TableName { get { return "People"; } }
    public override string PrimaryKey { get { return "PersonID"; } }
 }

 public class Dog : TableRow
 {
    public override string TableName { get { return "Dogs"; } }
    public override string PrimaryKey { get { return "DogID"; } }

    public Person GetOwner() { return GetLinkedRow<Person>(); }
 }
</code>```

Now I realise this is not the way to go about what I'm trying to achieve, because I COULD make a class that has a variable value for TableName or PrimaryKey, but I'm not going to. I'd like to be able to override a static property, but I know this is not possible. I did previously have a class per table, but that meant there was 70 fairly useless classes and that's what I'm trying to avoid. What would be a better way to go around this sort of issue?

Update:

I eventually went with creating a new instance of T to get the TableName, as I will be initialising the new instance anyway. Although SLaks' solution is much better than this, it doesn't guarantee that the derived class has the TableName and PrimaryKey attributes. For the majority of people, SLaks' solution will be more appropriate, so I will mark that as the accepted answer.

```<code>protected T GetLinkedRow<T>() where T : TableRow, new()
{
    T row = new T();
    DbDataReader reader = ExecuteReader("SELECT * FROM [" + row.TableName + "] WHERE [" + this.PrimaryKey + "] = " + this.ID);
    if(!reader.Read())
        throw new Exception("No linked row found");
    row.Load(reader);
    return row;
}

//here's the reason I didn't really want to do this in the first place. Many-to-many relationship. quite messy
protected IEnumerable<T> GetLinkedRows<T>(string junctionTable) where T : TableRow, new()
{
    T row = new T();
    DbDataReader reader = ExecuteReader("SELECT * FROM [" + row.TableName + "] INNER JOIN [" + junctionTable + "] ON [" + row.TableName + "].[" + row.PrimaryKey + "] = [" + junctionTable + "].[" + row.PrimaryKey + "] WHERE [" + junctionTable + "].[" + this.PrimaryKey + "] = " + this.ID;
    while(reader.Read()) {
        row.Load(reader);
        yield return row;
        if(reader.HasRows)
            row = new T();
    }
}
</code>```

答:
Based on updated information...

Why bother?  Why not just use an abstract method (or, better, an interface) that defines the method "GetLinkedRow" where the concrete implementation can provide the specifics.

That is, you know that the linked row to Dog will always be a Person, so you have an interface (Warning: Not compiled!)

```<code>public interface ILinkedRow
{
    public TableRow GetLinkedRow();
}
</code>```

Then Dog has this implementation:

```<code>public class Dog : TableRow, ILinkedRow
{
    //Implementation here

    public TableRow GetLinkedRow()
    {
        Person p = //implement method
        return p
    }
}
</code>```

Your handling code can either ignore the fact that the returned row is a Person (if it never needs to know that), or cast it to (Person)myDog.GetLinkedRow();

Body:
I have an extremely complicated relational database, which is causing me to use the same code over and over again. I'm trying to clean it up using a fairly sophisticated TableRow class, however I've came across one major problem. The best way I can explain what I'm trying to do is by some example code:

public abstract class TableRow
{
    public abstract string TableName { get; }
    public abstract string PrimaryKey { get; }

    //there's a lot of these sort of methods for multi-to-multi links, links by two columns, etc
    protected T GetLinkedRow<T>() where T : TableRow
    {
        //here I need to get TableName and PrimaryKey (without creating a new instance of T)
    }
 }

 public class Person : TableRow
 {
    public override string TableName { get { return "People"; } }
    public override string PrimaryKey { get { return "PersonID"; } }
 }

 public class Dog : TableRow
 {
    public override string TableName { get { return "Dogs"; } }
    public override string PrimaryKey { get { return "DogID"; } }

    public Person GetOwner() { return GetLinkedRow<Person>(); }
 }

Now I realise this is not the way to go about what I'm trying to achieve, because I COULD make a class that has a variable value for TableName or PrimaryKey, but I'm not going to. I'd like to be able to override a static property, but I know this is not possible. I did previously have a class per table, but that meant there was 70 fairly useless classes and that's what I'm trying to avoid. What would be a better way to go around this sort of issue?

Update:

I eventually went with creating a new instance of T to get the TableName, as I will be initialising the new instance anyway. Although SLaks' solution is much better than this, it doesn't guarantee that the derived class has the TableName and PrimaryKey attributes. For the majority of people, SLaks' solution will be more appropriate, so I will mark that as the accepted answer.

protected T GetLinkedRow<T>() where T : TableRow, new()
{
    T row = new T();
    DbDataReader reader = ExecuteReader("SELECT * FROM [" + row.TableName + "] WHERE [" + this.PrimaryKey + "] = " + this.ID);
    if(!reader.Read())
        throw new Exception("No linked row found");
    row.Load(reader);
    return row;
}

//here's the reason I didn't really want to do this in the first place. Many-to-many relationship. quite messy
protected IEnumerable<T> GetLinkedRows<T>(string junctionTable) where T : TableRow, new()
{
    T row = new T();
    DbDataReader reader = ExecuteReader("SELECT * FROM [" + row.TableName + "] INNER JOIN [" + junctionTable + "] ON [" + row.TableName + "].[" + row.PrimaryKey + "] = [" + junctionTable + "].[" + row.PrimaryKey + "] WHERE [" + junctionTable + "].[" + this.PrimaryKey + "] = " + this.ID;
    while(reader.Read()) {
        row.Load(reader);
        yield return row;
        if(reader.HasRows)
            row = new T();
    }
}

Body:
Based on updated information...

Why bother?  Why not just use an abstract method (or, better, an interface) that defines the method "GetLinkedRow" where the concrete implementation can provide the specifics.

That is, you know that the linked row to Dog will always be a Person, so you have an interface (Warning: Not compiled!)

public interface ILinkedRow
{
    public TableRow GetLinkedRow();
}

Then Dog has this implementation:

public class Dog : TableRow, ILinkedRow
{
    //Implementation here

    public TableRow GetLinkedRow()
    {
        Person p = //implement method
        return p
    }
}

Your handling code can either ignore the fact that the returned row is a Person (if it never needs to know that), or cast it to (Person)myDog.GetLinkedRow();


问:
Cloudformation packages install on ubuntu
I want to install awslogs packages in ubuntu instance but as given in AWS documentation they are using yum for that like shown below in code (for amazon linux).
My Question for that is

I am using ubuntu can I use apt-get awslogs to install this package . just need to place apt-get instead of yum ..if not then what is the solution to install awslogs in ubuntu using CFN

```<code> Type: 'AWS::AutoScaling::LaunchConfiguration'
    Metadata:
      'AWS::CloudFormation::Init':
        configSets:
          default: !If [HasIAMUserSSHAccess, [awslogs, ssh-access, mount, extras, config], [awslogs, mount, extras, config]]
        awslogs:
          packages:
            yum:
              awslogs: []
          files:
            '/etc/awslogs/awscli.conf':
              content: !Sub |
                [default]
                region = ${AWS::Region}
                [plugins]
                cwlogs = cwlogs
              mode: '000644'
              owner: root
              group: root
            '/etc/awslogs/awslogs.conf':
</code>```

答: I think we can use JUST apt instead of apt-get </p>

Body:
I want to install awslogs packages in ubuntu instance but as given in AWS documentation they are using yum for that like shown below in code (for amazon linux).
My Question for that is

I am using ubuntu can I use apt-get awslogs to install this package . just need to place apt-get instead of yum ..if not then what is the solution to install awslogs in ubuntu using CFN

 Type: 'AWS::AutoScaling::LaunchConfiguration'
    Metadata:
      'AWS::CloudFormation::Init':
        configSets:
          default: !If [HasIAMUserSSHAccess, [awslogs, ssh-access, mount, extras, config], [awslogs, mount, extras, config]]
        awslogs:
          packages:
            yum:
              awslogs: []
          files:
            '/etc/awslogs/awscli.conf':
              content: !Sub |
                [default]
                region = ${AWS::Region}
                [plugins]
                cwlogs = cwlogs
              mode: '000644'
              owner: root
              group: root
            '/etc/awslogs/awslogs.conf':


问:
How does C++ initialize inline variable via "constructor initialization"?
I'm working on a exercise that my professor gave to me in the last exams.

The text is as follow (its translated, original was in italian):

Write a class template SmartP<T> of smart pointers of type T that redefine assignment, copy constructor and destructor of smart pointers. The template SmartP<T> must contain a minimal public interface (with less number of menbers) that allow compiling the following code, the execution will provoke the commented line

```<code>class C {
public:
    int* p;
    C(): p(new int(5)) {}
};

int main() {
    const int a = 1;
    const int *p = &a;
    SmartP<int> r;
    SmartP<int> s(&a);
    SmartP<int> t(s);
    cout << *s << " " << *t << " " << *p << endl; // 1 1 1
    cout << (s == t) << " " << !(s == p) << endl; // 0 1
    *s = 2;
    *t = 3;
    cout << *s << " " << *t << " " << *p << endl; // 2 3 1
    r = t;
    *r = 4;
    cout << *r << " " << *s << " " << *t << " " << *p << endl; // 4 2 3 1
    C c;
    SmartP<C> x(&c);
    SmartP<C> y(x);
    cout << (x == y) << endl; // 0
    cout << *(c.p) << endl; // 5
    *(c.p) = 6;
    cout << *(c.p) << endl; // 6
    SmartP<C> *q = new SmartP<C>(&c);
    delete q;
}
</code>```

The solution provided by my professor is as follow:

```<code>template<class T>
class SmartP{
private:
    T* ptr;
public:
    SmartP(const SmartP& p) { p.ptr!=0 ? ptr(new T(*(p.ptr))) : ptr(nullptr); };
    SmartP(const T* t = 0) { t!=0 ? ptr(new T(*t)) : ptr(nullptr); };
    ~SmartP() { delete ptr;}
    T& operator*() const { return *ptr;}
    bool operator==(const SmartP& p) const { return ptr == p.ptr;}
    SmartP& operator=(const SmartP& p) {
       delete ptr;
       p.ptr!=0 ? ptr(new T(*(p.ptr))) : ptr(nullptr);
       return *this;
    }
};
</code>```

But when i try this, i get an error on every "constructor initialization" that says:

Called object type 'C*' is not a function or function pointer" (note that if i delete the C class i get the same error but instead on 'C*' there is 'int*').

So i was courious about this and i give to it some test:

```<code>    SmartP(const SmartP& p) : ptr(new T(*(p.ptr))) {}; //no error
    SmartP(const SmartP& p) { ptr(new T(*(p.ptr))); }; //error
    SmartP(const SmartP& p) { ptr = new T(*(p.ptr)); }; //no error
    SmartP(const SmartP& p) {
        if(p.ptr!=0){
            ptr(new T(*(p.ptr))); //error
        } else {
            ptr(nullptr);
        }
    };
</code>```

So my question is How does C++ initialize inline variable via "constructor initialization"?

Why if I initialize my variable normally it works, but not with "constructor initialization"?

答:
ptr(new T(*(p.ptr))); Such member initialization is allowed only in a constructor outside its body, a.k.a. member initializer list. If you use this line in a constructor body, it's a call of a function with name ptr or ptr.operator(). The compiler says you exactly the same, ptr of type C* is not a function nor functional object.

Only two ways how to initialize ptr are possible, and all these ways are in your first and third lines, that you marked as no error.

More info: Constructors and member initializer lists

Body:
I'm working on a exercise that my professor gave to me in the last exams.

The text is as follow (its translated, original was in italian):

Write a class template SmartP<T> of smart pointers of type T that redefine assignment, copy constructor and destructor of smart pointers. The template SmartP<T> must contain a minimal public interface (with less number of menbers) that allow compiling the following code, the execution will provoke the commented line

class C {
public:
    int* p;
    C(): p(new int(5)) {}
};

int main() {
    const int a = 1;
    const int *p = &a;
    SmartP<int> r;
    SmartP<int> s(&a);
    SmartP<int> t(s);
    cout << *s << " " << *t << " " << *p << endl; // 1 1 1
    cout << (s == t) << " " << !(s == p) << endl; // 0 1
    *s = 2;
    *t = 3;
    cout << *s << " " << *t << " " << *p << endl; // 2 3 1
    r = t;
    *r = 4;
    cout << *r << " " << *s << " " << *t << " " << *p << endl; // 4 2 3 1
    C c;
    SmartP<C> x(&c);
    SmartP<C> y(x);
    cout << (x == y) << endl; // 0
    cout << *(c.p) << endl; // 5
    *(c.p) = 6;
    cout << *(c.p) << endl; // 6
    SmartP<C> *q = new SmartP<C>(&c);
    delete q;
}

The solution provided by my professor is as follow:

template<class T>
class SmartP{
private:
    T* ptr;
public:
    SmartP(const SmartP& p) { p.ptr!=0 ? ptr(new T(*(p.ptr))) : ptr(nullptr); };
    SmartP(const T* t = 0) { t!=0 ? ptr(new T(*t)) : ptr(nullptr); };
    ~SmartP() { delete ptr;}
    T& operator*() const { return *ptr;}
    bool operator==(const SmartP& p) const { return ptr == p.ptr;}
    SmartP& operator=(const SmartP& p) {
       delete ptr;
       p.ptr!=0 ? ptr(new T(*(p.ptr))) : ptr(nullptr);
       return *this;
    }
};

But when i try this, i get an error on every "constructor initialization" that says:

Called object type 'C*' is not a function or function pointer" (note that if i delete the C class i get the same error but instead on 'C*' there is 'int*').

So i was courious about this and i give to it some test:

    SmartP(const SmartP& p) : ptr(new T(*(p.ptr))) {}; //no error
    SmartP(const SmartP& p) { ptr(new T(*(p.ptr))); }; //error
    SmartP(const SmartP& p) { ptr = new T(*(p.ptr)); }; //no error
    SmartP(const SmartP& p) {
        if(p.ptr!=0){
            ptr(new T(*(p.ptr))); //error
        } else {
            ptr(nullptr);
        }
    };

So my question is How does C++ initialize inline variable via "constructor initialization"?

Why if I initialize my variable normally it works, but not with "constructor initialization"?


问:
Trying to get rid of any heap memory allocation
I know how to do it with heap memory, but I try to get rid of any heap memory allocation in my code.

I cannot use any library which can help me, it means: <string> for example.

How can I do it with using stack memory allocation?

```<code>int main(void) {
    class Animal {
        unsigned char nameLength;
        unsigned char name[];

        setName(unsigned char name[]) {
            memcpy(this->name, name, this->length * sizeof(unsigned char));
        }
    }

    Animal dog;

    // The value '4' isn't constant, it depends on received data from socket
    dog.nameLength = 4;

    // Right now I know how many elements will be in dog.name array

    unsigned char randomName[dog.nameLength];

    // Here will be a for loop, but just for example:
    randomName[0] = "B";
    randomName[1] = "e";
    randomName[2] = "n";
    randomName[3] = "/0";

    dog.setName(randomName);

    // Expected output: dog.name = "Ben\0"
}
</code>```

The for loop will look like:

```<code>unsigned char i;
for (i = 0; i < (dog.nameLength-1); i++) {
    randomName[i] = packet[i];
}
randomName[i] = 0;
</code>```

答:
Your code has multiple issues, please break it down into multiple questions for each problem you are having.

But for the main issue: in general it is a very bad idea to do what you are trying to do (allocate dynamically on the stack), this is exactly what heap allocations are for.

Also, standard C++ does not allow this. There are, however, compiler extensions you could use: Why no variable size array in stack? and linux has alloca: http://man7.org/linux/man-pages/man3/alloca.3.html & C++ How to allocate memory dynamically on stack?

But, again, do not do this unless you really need to and you understand what you are doing.

Also, please listen to the commenters about how to ask a question and provide a minimal example.

Body:
I know how to do it with heap memory, but I try to get rid of any heap memory allocation in my code.

I cannot use any library which can help me, it means: <string> for example.

How can I do it with using stack memory allocation?

int main(void) {
    class Animal {
        unsigned char nameLength;
        unsigned char name[];

        setName(unsigned char name[]) {
            memcpy(this->name, name, this->length * sizeof(unsigned char));
        }
    }

    Animal dog;

    // The value '4' isn't constant, it depends on received data from socket
    dog.nameLength = 4;

    // Right now I know how many elements will be in dog.name array

    unsigned char randomName[dog.nameLength];

    // Here will be a for loop, but just for example:
    randomName[0] = "B";
    randomName[1] = "e";
    randomName[2] = "n";
    randomName[3] = "/0";

    dog.setName(randomName);

    // Expected output: dog.name = "Ben\0"
}

The for loop will look like:

unsigned char i;
for (i = 0; i < (dog.nameLength-1); i++) {
    randomName[i] = packet[i];
}
randomName[i] = 0;


问:
2D array of characters, printing extra character over limit?
The output of code

I want to create an array of character in which there are 'n' rows and each row have a character. In the given code I asked the user to enter the number of rows(n) then I create a variable 'chr' and each row contain only one character. Then I asked the characters one by one and store them in their respective rows but when I take the print of those characters something strange happens. The first row which should only store one character of its own stores all the characters of different rows. Why? can anyone explain to me this?

```<code>#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);

    char chr[n][1];

    for (int i = 0; i < n; i++) {
        printf("Enter the %d character?\n", i);
        scanf("%s", chr[i]);
    }
    // printing
    for (int i = 0; i < n; i++) {
        printf("\n%s\n", chr[i]);
    }
    return 0;
}
</code>```

答:
as to answer why its printing the other caracters, they are directly behind each other in memory, and as others pointed out since you told it to print a string, it treats those chars in a row as one string (which is an array of chars) until it encounters a termination char.

so in memory this

```<code>char array[3][1] = {{'a'},{'b'}{'c'}};
</code>```

looks just like this:

```<code>char array[3] ={'a','b','c'};
</code>```

or this

```<code>char array[3] = {"abc"};
</code>```

the array variable is a pointer to the address in memory where the first char is positioned, if you use [] you just jump sizeof(char) amount of bytes to the next char,

with the 2D array this is similar, the 1st bracket makes you jump sizeof(2darray[0]) bytes, which is in this case the same as sizeof(char) since length is 1

Body:
The output of code

I want to create an array of character in which there are 'n' rows and each row have a character. In the given code I asked the user to enter the number of rows(n) then I create a variable 'chr' and each row contain only one character. Then I asked the characters one by one and store them in their respective rows but when I take the print of those characters something strange happens. The first row which should only store one character of its own stores all the characters of different rows. Why? can anyone explain to me this?

#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);

    char chr[n][1];

    for (int i = 0; i < n; i++) {
        printf("Enter the %d character?\n", i);
        scanf("%s", chr[i]);
    }
    // printing
    for (int i = 0; i < n; i++) {
        printf("\n%s\n", chr[i]);
    }
    return 0;
}

Body:
as to answer why its printing the other caracters, they are directly behind each other in memory, and as others pointed out since you told it to print a string, it treats those chars in a row as one string (which is an array of chars) until it encounters a termination char.

so in memory this

char array[3][1] = {{'a'},{'b'}{'c'}};

looks just like this:

char array[3] ={'a','b','c'};

or this

char array[3] = {"abc"};

the array variable is a pointer to the address in memory where the first char is positioned, if you use [] you just jump sizeof(char) amount of bytes to the next char,

with the 2D array this is similar, the 1st bracket makes you jump sizeof(2darray[0]) bytes, which is in this case the same as sizeof(char) since length is 1


问:
Kotlin sealed class and type inference
im using a sealed class to report back success or error to client code:

```<code>sealed class Result<out T : Any> {
    data class Success<out T : Any>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
}
</code>```

But im stuck getting even the simplest unit test to compile using it:

```<code>    val error = Result.Error(IOException("message"))
    assertThat(error, instanceOf(Result.Error::class.java))
</code>```

I get the message : Type Inference failed. Not enough information to infer parameter T in fun  instanceOf(type : Class<*>) : Matcher!

Looks like im missing something important in Kotlin.

Thanks for helping me out!

答:
To avoid ::class I prefer this.

assertThat(result is Result.Error).isTrue()

Title: Kotlin sealed class and type inference

Body:
im using a sealed class to report back success or error to client code:

sealed class Result<out T : Any> {
    data class Success<out T : Any>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
}

But im stuck getting even the simplest unit test to compile using it:

    val error = Result.Error(IOException("message"))
    assertThat(error, instanceOf(Result.Error::class.java))

I get the message : Type Inference failed. Not enough information to infer parameter T in fun  instanceOf(type : Class<*>) : Matcher!

Looks like im missing something important in Kotlin.

Thanks for helping me out!


问:
@Grape in scripts with multiple files
I'd like to use @Grape in my groovy program but my program consists of several files. The examples on the Groovy Grape page all seem to assume that your script will consist of one file. How can I do this? Should I just add it to one of the files and expect that the imports will work from the others? If so, then is it common to place all the @Grape calls in one file with no other code? Do I need to add the Grape call to all files that will import the package? Do I need to download the JAR and create a Gradle file, which I was getting away without at this point?</p>

答:
In my opinion, it depends how your program is to be run...

If your program is to be run as a collection of standalone scripts, then I'd probably stick the @Grab required for each script at the top of each of them.

If your program is more of a standard style program with a single point of entry, then I'd go for using a build tool like Gradle (as you say), as you get a lot of easy wins by using it.

Firstly, it makes it easy to define your dependencies (and build a single large jar containing all of them)

Secondly, Gradle makes it really easy to start writing tests, include code coverage plugins, or useful tools like codenarc to suggest possible fixes or improvements to your code.  These all become invaluable not only for improving your code (or knowing your code works), but also when refactoring your code, you know you've not broken anything that used to work.

Title: @Grape in scripts with multiple files


问:
await not working for firebase querySnapshot, next line executed
I have an async method to return the length of the documents of a firebase query with condition and o have implemented with await in the method. The code is below.

////////////////////////

```<code>getUreadMsgCount(groupChatId, id).then((result) {
    unReadCount = result;
    print("COUNT WITHIN getUreadMsgCount Method : $unReadCount");
});

print("UNREAD OUTSIDE METHOD : $unReadCount");
</code>```

///////////////////////////////////////

```<code>Future getUreadMsgCount(String groupId, String idFrom) async {
    var respectsQuery = Firestore.instance
        .collection('messages')
        .document(groupId).collection(groupId)
        .where('idFrom', isEqualTo: idFrom).where('isSeen', isEqualTo: 0);
    var querySnapshot = await respectsQuery.getDocuments();
    int totalUnread = querySnapshot.documents.length;
    return totalUnread;
}
</code>```

//////////////OUT PUT/////////////////////////

```<code>I/flutter (28972): UNREAD OUTSIDE METHOD : 0
I/flutter (28972): UNREAD OUTSIDE METHOD : 0
I/flutter (28972): UNREAD OUTSIDE METHOD : 0
I/flutter (28972): COUNT WITHIN getUreadMsgCount Method : 2
I/flutter (28972): COUNT WITHIN getUreadMsgCount Method : 0
I/flutter (28972): COUNT WITHIN getUreadMsgCount Method : 0
</code>```

Here if you notice, it always executes the OUTSIDE METHOD line first hence always get with value as 0

I need to get the value from the method getUreadMsgCount initialized first then proceed with the next line. Any helps?

答:
You need to use await:

```<code>var result = await getUreadMsgCount(groupChatId, id);
    unReadCount = result;
  print("COUNT WITHIN getUreadMsgCount Method : $unReadCount");
  print("UNREAD OUTSIDE METHOD : $unReadCount");
</code>```

This way the code, after the asynchronous method call will get executed after retrieving the data.

The reason this:

```<code>getUreadMsgCount(groupChatId, id).then((result) {
    unReadCount = result;
    print("COUNT WITHIN getUreadMsgCount Method : $unReadCount");
  });

  print("UNREAD OUTSIDE METHOD : $unReadCount");

</code>```

is not printing as you want, is because the method getUreadMsgCount is asynchronous, then the code after the then() method will be executed first and when the data is fully retrieved, the code inside the then() method will get executed.

https://dart.dev/codelabs/async-await#execution-flow-with-async-and-await

Body:
I have an async method to return the length of the documents of a firebase query with condition and o have implemented with await in the method. The code is below.

////////////////////////

getUreadMsgCount(groupChatId, id).then((result) {
    unReadCount = result;
    print("COUNT WITHIN getUreadMsgCount Method : $unReadCount");
});

print("UNREAD OUTSIDE METHOD : $unReadCount");

///////////////////////////////////////

Future getUreadMsgCount(String groupId, String idFrom) async {
    var respectsQuery = Firestore.instance
        .collection('messages')
        .document(groupId).collection(groupId)
        .where('idFrom', isEqualTo: idFrom).where('isSeen', isEqualTo: 0);
    var querySnapshot = await respectsQuery.getDocuments();
    int totalUnread = querySnapshot.documents.length;
    return totalUnread;
}

//////////////OUT PUT/////////////////////////

I/flutter (28972): UNREAD OUTSIDE METHOD : 0
I/flutter (28972): UNREAD OUTSIDE METHOD : 0
I/flutter (28972): UNREAD OUTSIDE METHOD : 0
I/flutter (28972): COUNT WITHIN getUreadMsgCount Method : 2
I/flutter (28972): COUNT WITHIN getUreadMsgCount Method : 0
I/flutter (28972): COUNT WITHIN getUreadMsgCount Method : 0

Here if you notice, it always executes the OUTSIDE METHOD line first hence always get with value as 0

I need to get the value from the method getUreadMsgCount initialized first then proceed with the next line. Any helps?

Body:
You need to use await:

var result = await getUreadMsgCount(groupChatId, id);
    unReadCount = result;
  print("COUNT WITHIN getUreadMsgCount Method : $unReadCount");
  print("UNREAD OUTSIDE METHOD : $unReadCount");

This way the code, after the asynchronous method call will get executed after retrieving the data.

The reason this:

getUreadMsgCount(groupChatId, id).then((result) {
    unReadCount = result;
    print("COUNT WITHIN getUreadMsgCount Method : $unReadCount");
  });

  print("UNREAD OUTSIDE METHOD : $unReadCount");

is not printing as you want, is because the method getUreadMsgCount is asynchronous, then the code after the then() method will be executed first and when the data is fully retrieved, the code inside the then() method will get executed.

https://dart.dev/codelabs/async-await#execution-flow-with-async-and-await