问:
Read data from database and store result to DataSet
I am trying to read data from a database and store it to DataSet as result. The point of this is that I want to create a Report in DevExpress which contains multiple parameter. When I store data to dataset I want to filter report based on User Input.

```<code>    public void BindToData(int OrgId, bool Status)
    {
        try
        {
            string connString = @"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True";
            string strproc = "TestReport";
            using (SqlDataAdapter sda = new SqlDataAdapter(strproc, connString))
            {
                sda.SelectCommand.CommandType = CommandType.StoredProcedure;
                sda.SelectCommand.Parameters.Add("@Status", SqlDbType.Bit).Value = Status;
                sda.SelectCommand.Parameters.Add("@OrgJed", SqlDbType.Int).Value = OrgId;

                DataSet ds = new DataSet();
                sda.Fill(ds);
                XtraReport report = new XtraReport();
                report.DataSource = ds;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
</code>```

Button click to run function

```<code>        protected void Button1_Click(object sender, EventArgs e)
        {
            int OrgId = 1;
            bool Status = true;
            BindToData(OrgId,Status);
        }
</code>```

So far this is code which I wrote but when I run it report.DataSource = ds doesn't get any result.

When I debug it, I didn't see where the error is.

Stored Procedure

```<code>USE [DesignSaoOsig1]
GO
/****** Object:  StoredProcedure [dbo].[TestReport]    Script Date: 29. 5. 2020. 09:20:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[TestReport]
(
    @Status bit,
    @OrgJed int
)
AS
BEGIN

    SELECT TOP 1 OrgUnitID
    FROM    tblZaposleni_AD
    --WHERE  Status =    @Status AND
    --  OrgUnitID = @OrgJed
END
</code>```

答:
I have just run your exact code with a different connection string:

```<code>        try
        {
            string connString = @"Confidential";
            string strproc = "TestReport";
            using (SqlDataAdapter sda = new SqlDataAdapter(strproc, connString))
            {
                sda.SelectCommand.CommandType = CommandType.StoredProcedure;
                sda.SelectCommand.Parameters.Add("@Status", SqlDbType.Bit).Value = true;
                sda.SelectCommand.Parameters.Add("@OrgJed", SqlDbType.Int).Value = 1;

                DataSet ds = new DataSet();
                sda.Fill(ds);

                string temp = "123"; // Line to set breakpoint on
            }
        }
        catch (Exception)
        {
            throw;
        }
</code>```

And it gives me a single table result with a single row as show in the watch window below:

Note in addition to selecting the id from a table I have selected the input parameters so they are visible and can be checked that what comes out is the same as what went in.

Body:
I am trying to read data from a database and store it to DataSet as result. The point of this is that I want to create a Report in DevExpress which contains multiple parameter. When I store data to dataset I want to filter report based on User Input.

    public void BindToData(int OrgId, bool Status)
    {
        try
        {
            string connString = @"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True";
            string strproc = "TestReport";
            using (SqlDataAdapter sda = new SqlDataAdapter(strproc, connString))
            {
                sda.SelectCommand.CommandType = CommandType.StoredProcedure;
                sda.SelectCommand.Parameters.Add("@Status", SqlDbType.Bit).Value = Status;
                sda.SelectCommand.Parameters.Add("@OrgJed", SqlDbType.Int).Value = OrgId;

                DataSet ds = new DataSet();
                sda.Fill(ds);
                XtraReport report = new XtraReport();
                report.DataSource = ds;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

Button click to run function

        protected void Button1_Click(object sender, EventArgs e)
        {
            int OrgId = 1;
            bool Status = true;
            BindToData(OrgId,Status);
        }

So far this is code which I wrote but when I run it report.DataSource = ds doesn't get any result.

When I debug it, I didn't see where the error is.

Stored Procedure

USE [DesignSaoOsig1]
GO
/****** Object:  StoredProcedure [dbo].[TestReport]    Script Date: 29. 5. 2020. 09:20:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[TestReport]
(
    @Status bit,
    @OrgJed int
)
AS
BEGIN

    SELECT TOP 1 OrgUnitID
    FROM    tblZaposleni_AD
    --WHERE  Status =    @Status AND
    --  OrgUnitID = @OrgJed
END

Body:
I have just run your exact code with a different connection string:

        try
        {
            string connString = @"Confidential";
            string strproc = "TestReport";
            using (SqlDataAdapter sda = new SqlDataAdapter(strproc, connString))
            {
                sda.SelectCommand.CommandType = CommandType.StoredProcedure;
                sda.SelectCommand.Parameters.Add("@Status", SqlDbType.Bit).Value = true;
                sda.SelectCommand.Parameters.Add("@OrgJed", SqlDbType.Int).Value = 1;

                DataSet ds = new DataSet();
                sda.Fill(ds);

                string temp = "123"; // Line to set breakpoint on
            }
        }
        catch (Exception)
        {
            throw;
        }

And it gives me a single table result with a single row as show in the watch window below:

Note in addition to selecting the id from a table I have selected the input parameters so they are visible and can be checked that what comes out is the same as what went in.


来源: stackexchange

问:
text not centered with background color
so i have created this flexbox container with some flex-items:

so what i have is when i press on overview or alerts, it doesn't have this white border background color, when i press on one of them it will trigger a class called .selected and will color the background in white.

the problem is when i press on one of them the white border is not spamming the entire width ( from start to end) also the text inside the background is not centered in the middle when i press it and i don't know why

code:

```<code><div className="container">
            <div className="flex-item item-1 item">John Smith</div>
            <div className="flex-item item-2 item">Male, 26 years old</div>
            <div className='flex-item item-3 item'onClick={setSelectedItem} style={style} > Overview</div>
            <div className='flex-item item-4 item'onClick={setSelectedItem} style={style}>Alerts</div>
            </div>
        </div>
</code>```

css code:

```<code>.container {
    border: 2px solid #57c0e8;
    background-color: #57c0e8;
    margin-top: 5%;
    float: left;
    border-top-right-radius: 20px;
    border-bottom-right-radius: 20px;
    color:white;
    display: flex;
    flex-direction: column;
    height:40rem;
    width:15rem;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-items: flex-start;
    font-size:0.9rem;
}

.flex-item{
    margin-top: 2rem;
}

.selected{
    background-color: white;
    color: #57c0e8;
    border-radius: 50px 0 0 50px;
    box-shadow: 2px 2px 5px lightgray;
    width: 14rem;
    height: 5%;
    text-align: left;
}
</code>```

答: for .selected, remove border-radius and make width:100%

ContentLicense: CC BY-SA 4.0

Title: text not centered with background color

Body:
so i have created this flexbox container with some flex-items:

so what i have is when i press on overview or alerts, it doesn't have this white border background color, when i press on one of them it will trigger a class called .selected and will color the background in white.

the problem is when i press on one of them the white border is not spamming the entire width ( from start to end) also the text inside the background is not centered in the middle when i press it and i don't know why

code:

John Smith

Male, 26 years old

 Overview

Alerts

css code:

.container {
    border: 2px solid #57c0e8;
    background-color: #57c0e8;
    margin-top: 5%;
    float: left;
    border-top-right-radius: 20px;
    border-bottom-right-radius: 20px;
    color:white;
    display: flex;
    flex-direction: column;
    height:40rem;
    width:15rem;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-items: flex-start;
    font-size:0.9rem;
}

.flex-item{
    margin-top: 2rem;
}

.selected{
    background-color: white;
    color: #57c0e8;
    border-radius: 50px 0 0 50px;
    box-shadow: 2px 2px 5px lightgray;
    width: 14rem;
    height: 5%;
    text-align: left;
}


问:
Using Httprequest to get pictures from given URL
I'm trying to get pictures from webcams. There is a php-python web service to get the pictures from webcams and serve them: it serves the picture like http://ip/jpeg/camera=1.

```<code>private HttpWebRequest request;
private HttpWebResponse response;
private CookieContainer container;
private Uri uri;
private string _user;
private string _pass;
private string _ip;
//Login code as seen in the previous section should be here
//GetImages is meant to run as a separate thread
private void GetImages(string camNo)
{
//create the GET request for the JPEG snapshot (found at /jpeg on the IP Camera)
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://" + deviceIP + "/jpeg/camera"+camNo);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = container;

//attempt to get a response from the IP110, event if error

try
{
    response = (HttpWebResponse)request.GetResponse();
}
catch (WebException e)
{
    ConnectionError(new ConnectionErrorEventArgs(e.Message));
}

//Get the stream containing the JPEG image.
Stream stream = response.GetResponseStream();

//Read the stream to memory.
byte[] buffer = new byte[100000];
int read, total = 0;

while ((read = stream.Read(buffer, total, 1000)) != 0)
{
    total += read;
}

//create a BMP image from the stream
Bitmap bmp = (Bitmap)Bitmap.FromStream(new MemoryStream(buffer, 0, total));

//send the bmp image to where you would like to display it.
 }
</code>```

... then I store that bitmap as a jpeg to a folder.  My problem starts here; I want to do that process as fast as possible.  I want to take pictures from 50 webcams using that code and store as jpeg, and it has to be fast - I mean every 10 seconds I have to get new pictures from 50 cams.

I used timercontrol, and give it 500 ms every 500ms program use that code above up to camera
number and save the jpeg, but it work one after another so performance gets low!

50ms x 500cams = 25000 ms (25sec), if I arrange timer control's interval 100 ms program freeze.
When I use the code above I get bitmap bmp in 200 ms but when it tries to write as jpeg on disc it takes a long time.

What can I do to write to disk faster? I looked for memory mapped - would it help? I want to store jpegs on disc becouse I will serve these pictures on a web site and share them with people. Can I use memory mapped and serve it publicly via a web site?

UPDATE:
I also used WebClient class for async works,
http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=571

The result was: To get a picture like 300 ms and writing it to disk about 700ms
So I have to find a solution to write to disk as much as possible.

Which one is better? To write the pictures to disk or to send images to database?
I tried to store the pictures to make them ready for serve, because on the website people have to see updated pictures. Which one is better for thousands of client query? To store them on disk or store them on database as binary?

答:
Any time you need to get responses back faster than stacked responses allow, you end up having to complete multiple pieces of work at once, using more than one thread (last word is the clue here).

In .NET, this means either setting up your own threading library, using TPL, etc.

ADDED: This could mean, as pointed out by a comment below, using asynchronous calls and allowing the framework to implicitly create threads for you, instead of controlling them yourself. In fact, you could use thread pooling and still choose asynch or synch without controlling the number of threads created. If you really want to get down to the metal, you can even offload threading to the OS using an interrupt handler at the OS level (a menthod used by Ruby, for example, prior to 1.9, which introduced "true" threading rather than "green" threads - yeah, TMI).

The answer still stands if you have 2 minutes worth of work to get done and 30 seconds to get it done in, you need a multi-threaded solution, whether you are aware you are actually threading (explicit creation) or not (implicit creation handled by framework/OS).

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get pictures from webcams. There is a php-python web service to get the pictures from webcams and serve them: it serves the picture like http://ip/jpeg/camera=1.

private HttpWebRequest request;
private HttpWebResponse response;
private CookieContainer container;
private Uri uri;
private string _user;
private string _pass;
private string _ip;
//Login code as seen in the previous section should be here
//GetImages is meant to run as a separate thread
private void GetImages(string camNo)
{
//create the GET request for the JPEG snapshot (found at /jpeg on the IP Camera)
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://" + deviceIP + "/jpeg/camera"+camNo);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = container;

//attempt to get a response from the IP110, event if error

try
{
    response = (HttpWebResponse)request.GetResponse();
}
catch (WebException e)
{
    ConnectionError(new ConnectionErrorEventArgs(e.Message));
}

//Get the stream containing the JPEG image.
Stream stream = response.GetResponseStream();

//Read the stream to memory.
byte[] buffer = new byte[100000];
int read, total = 0;

while ((read = stream.Read(buffer, total, 1000)) != 0)
{
    total += read;
}

//create a BMP image from the stream
Bitmap bmp = (Bitmap)Bitmap.FromStream(new MemoryStream(buffer, 0, total));

//send the bmp image to where you would like to display it.
 }

... then I store that bitmap as a jpeg to a folder.  My problem starts here; I want to do that process as fast as possible.  I want to take pictures from 50 webcams using that code and store as jpeg, and it has to be fast - I mean every 10 seconds I have to get new pictures from 50 cams.

I used timercontrol, and give it 500 ms every 500ms program use that code above up to camera
number and save the jpeg, but it work one after another so performance gets low!

50ms x 500cams = 25000 ms (25sec), if I arrange timer control's interval 100 ms program freeze.
When I use the code above I get bitmap bmp in 200 ms but when it tries to write as jpeg on disc it takes a long time.

What can I do to write to disk faster? I looked for memory mapped - would it help? I want to store jpegs on disc becouse I will serve these pictures on a web site and share them with people. Can I use memory mapped and serve it publicly via a web site?

UPDATE:
I also used WebClient class for async works,
http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=571

The result was: To get a picture like 300 ms and writing it to disk about 700ms
So I have to find a solution to write to disk as much as possible.

Which one is better? To write the pictures to disk or to send images to database?
I tried to store the pictures to make them ready for serve, because on the website people have to see updated pictures. Which one is better for thousands of client query? To store them on disk or store them on database as binary?


问:
php why str_replace not working with html
why here str_replace not working

```<code><?php
$str= '<div class=\"droppable\" ondrop=\"drop(event)\" ondragover=\"allowDrop(event)\"></div>';
echo str_replace('\"','"', $str);
</code>```

i want to use str_replace with HTML tag.

答:
As I get you want to remove the \s to get proper HTML.

Better way should be -

```<code>stripslashes('<div class=\"droppable\" ondrop=\"drop(event)\" ondragover=\"allowDrop(event)\"></div>');
</code>```

Output

```<code><div class="droppable" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</code>```

stripslashes

Body:
why here str_replace not working

<?php
$str= '

';
echo str_replace('\"','"', $str);

i want to use str_replace with HTML tag.

Body:
As I get you want to remove the \s to get proper HTML.

Better way should be -

stripslashes('<div class=\"droppable\" ondrop=\"drop(event)\" ondragover=\"allowDrop(event)\"></div>');

Output

<div class="droppable" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

stripslashes


问:
Filter through a table
I ran into an issue in using a search bar to filter through table.

I don't seem to be able to get the function to filter through the tbody section of this table.

The tbody information is printed through JS using innerHTML using the "planes" as ID

function searchBar() {
  var input, filter, table, tr, j, td, txtval;
  input = document.getElementById("search")
  filter = input.value.toUpperCase();
  table = document.getElementById("planes")
  tr = table.getElementByTagName("tr")

  //loop
  for (j = 0; j
 -1) {
        tr[j].style.display = "";
      } else {
        tr[j].style.display = "none";
      }
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content-grid mdl-grid" style="padding-top:50px;  justify-content: center; text-align: center">

  <table class="mdl-data-table mdl-js-data-table mdl-data-table mdl-shadow--2dp">
    <thead>
      <tr>
        <th style="text-align: center"> Plane Registration </th>
        <th style="text-align: center"> Plane location </th>
        <th style="text-align: center"> Range (KM) </th>
        <th style="text-align: center"> Average Speed <br>(Knots) </th>
        <th style="text-align: center"> Plane Type </th>
        <th style="text-align: center"> Status </th>
        <th style="text-align: center"> Airline </th>
      </tr>
    </thead>
    <tbody id="planes">

    </tbody>
  </table>
</div></code>```

答:
You have several issues.

getElementByTagName should be plural getElementsByTagName

You replace the td for each assignment, but if you fixed that

You would show when found and then immediately hide when not found in the next cell

window.addEventListener("load", function() {
  document.getElementById("search").addEventListener("input", function() {
    const filter = this.value.trim().toUpperCase();
    [...document.querySelectorAll("#planes tr")].forEach(tr => {
      const found = [...tr.querySelectorAll("td")].some(td => {
        const txtval = (td.textContext || td.innerText).toUpperCase();
        return (txtval.includes(filter))
      })
      const hide = filter !== "" && !found;
      tr.classList.toggle("hide", hide);
    })
  })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide {
  display: none
}</code>```

<input type="text" id="search" />

         Plane Registration
         Plane location
         Range (KM)
         Average Speed
(Knots)
         Plane Type
         Status
         Airline

        ONYX
        Texas
        3000
        200
        Cessna
        Active
        Texas Airline

        AAAA
        Heathrow
        30000
        800
        747
        Active
        BA

```

Title: Filter through a table

Body:
I ran into an issue in using a search bar to filter through table.

I don't seem to be able to get the function to filter through the tbody section of this table.

The tbody information is printed through JS using innerHTML using the "planes" as ID

function searchBar() {
  var input, filter, table, tr, j, td, txtval;
  input = document.getElementById("search")
  filter = input.value.toUpperCase();
  table = document.getElementById("planes")
  tr = table.getElementByTagName("tr")

  //loop
  for (j = 0; j
 -1) {
        tr[j].style.display = "";
      } else {
        tr[j].style.display = "none";
      }
    }
  }
}

         Plane Registration
         Plane location
         Range (KM)
         Average Speed
(Knots)
         Plane Type
         Status
         Airline

Body:
You have several issues.

getElementByTagName should be plural getElementsByTagName

You replace the td for each assignment, but if you fixed that

You would show when found and then immediately hide when not found in the next cell

window.addEventListener("load", function() {
  document.getElementById("search").addEventListener("input", function() {
    const filter = this.value.trim().toUpperCase();
    [...document.querySelectorAll("#planes tr")].forEach(tr => {
      const found = [...tr.querySelectorAll("td")].some(td => {
        const txtval = (td.textContext || td.innerText).toUpperCase();
        return (txtval.includes(filter))
      })
      const hide = filter !== "" && !found;
      tr.classList.toggle("hide", hide);
    })
  })
})

.hide {
  display: none
}

<input type="text" id="search" />
<div class="content-grid mdl-grid" style="padding-top:50px;  justify-content: center; text-align: center">

  <table class="mdl-data-table mdl-js-data-table mdl-data-table mdl-shadow--2dp">
    <thead>
      <tr>
        <th style="text-align: center"> Plane Registration </th>
        <th style="text-align: center"> Plane location </th>
        <th style="text-align: center"> Range (KM) </th>
        <th style="text-align: center"> Average Speed <br>(Knots) </th>
        <th style="text-align: center"> Plane Type </th>
        <th style="text-align: center"> Status </th>
        <th style="text-align: center"> Airline </th>
      </tr>
    </thead>
    <tbody id="planes">
      <tr>
        <td>ONYX</td>
        <td>Texas</td>
        <td>3000</td>
        <td>200</td>
        <td>Cessna</td>
        <td>Active</td>
        <td>Texas Airline</td>
      </tr>
      <tr>
        <td>AAAA</td>
        <td>Heathrow</td>
        <td>30000</td>
        <td>800</td>
        <td>747</td>
        <td>Active</td>
        <td>BA</td>
      </tr>
    </tbody>
  </table>
</div>


问:
cannot connect to mongo local DB from Node JS
I am learning Mongo DB, Mongoose and Node JS and I can't seem to connect my Node JS to local Mongo DB.

Here is my code:

dbtest.js

```<code>    var express  = require('express');
    var app      = express();                               // create our app w/ express
    var mongoose = require('mongoose');                     // mongoose for mongodb
    var morgan = require('morgan');             // log requests to the console (express4)
    var bodyParser = require('body-parser');    // pull information from HTML POST (express4)
    var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)

    var options = {
          useMongoClient: true,
          autoIndex: false, // Don't build indexes
          reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
          reconnectInterval: 500, // Reconnect every 500ms
          poolSize: 10, // Maintain up to 10 socket connections
          // If not connected, return errors immediately rather than waiting for reconnect
          bufferMaxEntries: 0
};

    var Todo = mongoose.model('Todo', {
        text : String
    }, 'test');

    var status = {
    "status": "not connected"
    };

    app.get('/api/todos', function(req, res) {

            mongoose.connect('mongodb://127.0.0.1:27017/exampleDB',options,function(err)
    {
              if (err) {
              res.json(status);
            } else {
                res.json('Connected');
            }
    });
    });

    app.listen(8080);
    console.log("App listening on port 8080");
</code>```

When I call api/todos GET request, the status JSON object is returned, meaning I cannot connect to the database.

I installed MongoDB Enterprise Server 3.14.10 completely and have it running but I don't know why my NodeJS application cannot connect.

Any suggestions are appreciated.

答:
For connecting to a local mongodb, you can use this URI, replacing USER, PASSWORD are DB with your values :

```<code>mongodb://USER:PASSWORD@127.0.0.1/DB?authSource=admin
</code>```

You don't need to provide the port 27017, because it's the default one for mongodb.

The trick here is to add with 'authSource=admin' for enabling the authentication.

Documentation :
https://docs.mongodb.com/manual/reference/connection-string/#examples

Body:
I am learning Mongo DB, Mongoose and Node JS and I can't seem to connect my Node JS to local Mongo DB.

Here is my code:

dbtest.js

    var express  = require('express');
    var app      = express();                               // create our app w/ express
    var mongoose = require('mongoose');                     // mongoose for mongodb
    var morgan = require('morgan');             // log requests to the console (express4)
    var bodyParser = require('body-parser');    // pull information from HTML POST (express4)
    var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)

    var options = {
          useMongoClient: true,
          autoIndex: false, // Don't build indexes
          reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
          reconnectInterval: 500, // Reconnect every 500ms
          poolSize: 10, // Maintain up to 10 socket connections
          // If not connected, return errors immediately rather than waiting for reconnect
          bufferMaxEntries: 0
};

    var Todo = mongoose.model('Todo', {
        text : String
    }, 'test');

    var status = {
    "status": "not connected"
    };

    app.get('/api/todos', function(req, res) {

            mongoose.connect('mongodb://127.0.0.1:27017/exampleDB',options,function(err)
    {
              if (err) {
              res.json(status);
            } else {
                res.json('Connected');
            }
    });
    });

    app.listen(8080);
    console.log("App listening on port 8080");

When I call api/todos GET request, the status JSON object is returned, meaning I cannot connect to the database.

I installed MongoDB Enterprise Server 3.14.10 completely and have it running but I don't know why my NodeJS application cannot connect.

Any suggestions are appreciated.

Body:
For connecting to a local mongodb, you can use this URI, replacing USER, PASSWORD are DB with your values :

mongodb://USER:PASSWORD@127.0.0.1/DB?authSource=admin

You don't need to provide the port 27017, because it's the default one for mongodb.

The trick here is to add with 'authSource=admin' for enabling the authentication.

Documentation :
https://docs.mongodb.com/manual/reference/connection-string/#examples


问:
What is a good way to maintain a set of constants in Python project?
Have a .py file with below content ?

```<code>class Set1(Enum):
   A = 1
   B = 2

class Set2(Enum):
  hi=1
  hello=2
</code>```

OR simply

```<code>Set1 = {"A":1,"B":2}
Set2 = {"C"="hi","D"="Hello"}
</code>```

Please note that these constants will be used by different modules in the project.

答:
Usually, you define constants in a file like this:

some_file.py :

```<code>FOO = 0
BAR = "baz"
</code>```

And if you need to use it:

```<code>import some_file

print(some_file.FOO)
print(some_file.BAR)
</code>```

Body:
Have a .py file with below content ?

class Set1(Enum):
   A = 1
   B = 2

class Set2(Enum):
  hi=1
  hello=2

OR simply

Set1 = {"A":1,"B":2}
Set2 = {"C"="hi","D"="Hello"}

Please note that these constants will be used by different modules in the project.

Body:
Usually, you define constants in a file like this:

some_file.py :

FOO = 0
BAR = "baz"

And if you need to use it:

import some_file

print(some_file.FOO)
print(some_file.BAR)


问:
Expressjs REST API explorer
I've been playing with loopback and it has very nice API Explorer (somehow reminds me Java's JMX),
apparently it is integrated inside the framework itself.

Is there a simple way to recreate the same experience with any of the npm packages?
If not, how do you expose your API to clients side devs in a convenient way except a google doc?

答:
You can use expressjs-api-explorer from here

But I guess you have to register all your routes into your root (app.js or server.js or similar) file.I have registered my routes into the separate module (eg. post.routes.js , users.routes.js) and in my app.js I have only one route for 'server:port/' i.e. app.get('/' ,handler) and  expressjs-api-explorer returns only that one on the UI :

You need to also install "jade" as a dependency. Hope this helps.Cheers!

Title: Expressjs REST API explorer


问:
AzureStorage Blob Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature
I'm trying to upload a image in Windows Azure Blob and I'm geting the following error which I can't handle.

Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.

The error occurs when I try to create a container.

container.CreateIfNotExists()
```
<p>Here is my code</p>
<pre class="lang-cs prettyprint-override"><code>try
{
    Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

    // Retrieve a reference to a container.
    CloudBlobContainer container = blobClient.GetContainerReference("samples");

    // Create the container if it doesn't already exist.
    // here is the error
    if (container.CreateIfNotExists())
    {
        container.SetPermissions(
            new BlobContainerPermissions
            {
                PublicAccess = BlobContainerPublicAccessType.Blob
            });
    }

    CloudBlockBlob blockBlob = container.GetBlockBlobReference("Image1");
    using (var fileStream = System.IO.File.OpenRead(@"Path"))
    {
        blockBlob.UploadFromStream(fileStream);
    }
}
catch (StorageException ex1)
{
    throw ex1;
}
</code>```

I have tried a lot of options in my code but still getting the error.

答:
I migrated an app from one machine to another, migrating the connection string across.
The public IP was unchanged and the URL was not expired, yet I got this error.

It appears that once used a connection string URL is tied to that machine - perhaps other fingerprints are added on first use.

I have no evidence for this but it worked after generating a new connection string.

Body:
I'm trying to upload a image in Windows Azure Blob and I'm geting the following error which I can't handle.

Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.

The error occurs when I try to create a container.

container.CreateIfNotExists()

Here is my code

try
{
    Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

    // Retrieve a reference to a container.
    CloudBlobContainer container = blobClient.GetContainerReference("samples");

    // Create the container if it doesn't already exist.
    // here is the error
    if (container.CreateIfNotExists())
    {
        container.SetPermissions(
            new BlobContainerPermissions
            {
                PublicAccess = BlobContainerPublicAccessType.Blob
            });
    }

    CloudBlockBlob blockBlob = container.GetBlockBlobReference("Image1");
    using (var fileStream = System.IO.File.OpenRead(@"Path"))
    {
        blockBlob.UploadFromStream(fileStream);
    }
}
catch (StorageException ex1)
{
    throw ex1;
}

I have tried a lot of options in my code but still getting the error.


问:
Anaconda Installation stuck at - 'Setting up the package cache'
I am trying to install Anaconda V 3.7 on Windows 10 - 64 bit system.
Download was successful.In installation step extraction of packages also completed.
After that it gets stuck at one point where message shown on window is - 'Setting up the package cache'.

I removed all previous versions of Python/Conda from my system.Removed path from environment variable still getting this error.

答:
I too was desperate on this.But being on a limited data-plan, I couldn't reattempt another download of the previous version of Anaconda as suggested in the above answer. So instead I waited and in 9 minutes exactly, the status changed from Setting up the package cache to Setting up the base environment.

I would suggest wait a little more and hopefully, the installation would finish!


问:
Jest allow multi types for object structure match
I am trying to create a test with jest which has to check if an object key is a string or a number.

Simple like this, but I cannot find anything in the documentation.

Test Example:

```<code>test('Assets structure is right', () => {
    const assetExpectedStructure = {
      id: expect.any(String),
      source_type: expect.any(String),
      media_types: expect.any(Array),
      source_id: expect.any(String)   // <------------ HERE  String or Number
    }

    for (const asset of assets) {
        expect(asset).toMatchObject(assetExpectedStructure)
    }
 }
</code>```

I could do expect.anything(), but this gets also other types  (Boolean, Objects etc.) which I don't want.

Does someone have an idea how to do this?

答:
Without adding custom matchers via expect.extend, try:

```<code>test('Assets structure is right', () => {
    const assetExpectedStructure = {
      id: expect.any(String),
      source_type: expect.any(String),
      media_types: expect.any(Array),
      source_id: expect.stringMatching(/\d+/) // regex will match only alpha numerical string
    }

    for (const asset of assets) {
        expect(asset).toMatchObject(assetExpectedStructure)
    }
 }
</code>```

Checkout https://jestjs.io/docs/en/expect#expectstringmatchingstring--regexp

Body:
I am trying to create a test with jest which has to check if an object key is a string or a number.

Simple like this, but I cannot find anything in the documentation.

Test Example:

test('Assets structure is right', () => {
    const assetExpectedStructure = {
      id: expect.any(String),
      source_type: expect.any(String),
      media_types: expect.any(Array),
      source_id: expect.any(String)   // <------------ HERE  String or Number
    }

    for (const asset of assets) {
        expect(asset).toMatchObject(assetExpectedStructure)
    }
 }

I could do expect.anything(), but this gets also other types  (Boolean, Objects etc.) which I don't want.

Does someone have an idea how to do this?

Body:
Without adding custom matchers via expect.extend, try:

test('Assets structure is right', () => {
    const assetExpectedStructure = {
      id: expect.any(String),
      source_type: expect.any(String),
      media_types: expect.any(Array),
      source_id: expect.stringMatching(/\d+/) // regex will match only alpha numerical string
    }

    for (const asset of assets) {
        expect(asset).toMatchObject(assetExpectedStructure)
    }
 }

Checkout https://jestjs.io/docs/en/expect#expectstringmatchingstring--regexp


问:
Shifting elements in an Array of objects
I need to insert an Appointment in a Planner class that takes Appointment A1 as a parameter and places A1 in proper order to an array Appoint. I have already created the Array which only has 4 default appointments and has a length of 20. I also created a method to compare two objects of the Array and return true if A1 is smaller than A2. I have a method which allows me to insert info into the Array if array[i{ = null. However I have no idea how to sort it as I have to shift elements not sort the entire array </p>

答: You'd better use a PriorityQueue instead of an Array. The PriorityQueue is based on a priority heap, once you add an element it will be shifted up/down the tree which takes O(log(N)) time complexity. If you shift an element in Array, it will take O(N).


问:
How to sort list of string in ascending way?
I have a list of strings. They are actually files.

```<code>image_files = ["1.jpg", "3.jpg", "2.jpg", "4.jpg", "6.jpg", "5.jpg", "20.jpg", "29.jpg", "11.jpg", "9.jpg"]
</code>```

I want to sort them like:

```<code>['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '9.jpg', '11.jpg', '20.jpg', '29.jpg']
</code>```

I tried with sorted(image_files, key = len) but failed.

答:
```<code>image_files = ["1.jpg", "3.jpg", "2.jpg", "4.jpg", "6.jpg", "5.jpg", "20.jpg", "29.jpg", "11.jpg", "9.jpg"]

image_files.sort(key=lambda item: (len(item), item))

print(image_files)
</code>```

Try this.

Body:
I have a list of strings. They are actually files.

image_files = ["1.jpg", "3.jpg", "2.jpg", "4.jpg", "6.jpg", "5.jpg", "20.jpg", "29.jpg", "11.jpg", "9.jpg"]

I want to sort them like:

['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '9.jpg', '11.jpg', '20.jpg', '29.jpg']

I tried with sorted(image_files, key = len) but failed.

Body:
image_files = ["1.jpg", "3.jpg", "2.jpg", "4.jpg", "6.jpg", "5.jpg", "20.jpg", "29.jpg", "11.jpg", "9.jpg"]

image_files.sort(key=lambda item: (len(item), item))

print(image_files)

Try this.


问:
3D rigid body transform decomposition reorder
I have this idea in my head and I am trying to figure out how to implement it. One of the parts that I am struggling with is how to take a 3D rigid-body transform and decompose it into dx, dy, dz, theta_X, theta_Y, and theta_Z.

This of course is a very well document algorithm. My problem is that matrix algebra is noncommutative. I would like to reorder the components such that it goes (dx*dy*theta_Z)*(dz*theta_X*theta_Y).

For any of you who wants to know why I want to do this is because I would like to do apply the transform (dx*dy*theta_Z) on a 3D image followed by then another operation followed by the completion of the rigid body transform. Does anyone know how to do this?

答:
If I get it right you want to isolate XY plane transform separately from a 3D transform that is possible only if the theta_Z rotation is applied first (as you want it to be first). If not then you would need to convert your order of Euler angles first for example with this:

Is there a way to calculate 3D rotation on X and Y axis from a 4x4 matrix

If you do not know the translations you can obtain them directly from matrix see:

Understanding 4x4 homogenous transform matrices

now its just a matter of using the translations in corect coordinate system (depends on order of your transformations)

As you did not provide any specific data nor MCVE I can not go in more details as there are quite a few combinations of possible solutions.


问:
Changing navigation bar color in Swift
I am using a Picker View to allow the user to choose the colour theme for the entire app.

I am planning on changing the colour of the navigation bar, background and possibly the tab bar (if that is possible).

I've been researching how to do this but can't find any Swift examples. Could anyone please give me an example of the code I would need to use to change the navigation bar colour and navigation bar text colour?

The Picker View is set up, I'm just looking for the code to change the UI colours.

答:
This version also removes the 1px shadow line under the navigation bar:

Swift 5: Put this in your AppDelegate didFinishLaunchingWithOptions

```<code>UINavigationBar.appearance().barTintColor = UIColor.black
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
UINavigationBar.appearance().isTranslucent = false
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
UINavigationBar.appearance().shadowImage = UIImage()
</code>```

Title: Changing navigation bar color in Swift

Body:
This version also removes the 1px shadow line under the navigation bar:

Swift 5: Put this in your AppDelegate didFinishLaunchingWithOptions

UINavigationBar.appearance().barTintColor = UIColor.black
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
UINavigationBar.appearance().isTranslucent = false
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
UINavigationBar.appearance().shadowImage = UIImage()


问:
Generate Buttons inside Wrap from List<String> flutter
I have a List<String> and I want to generate, inside a Wrap widget, N Buttons (N string lenght).

I read about a List.generate, I'm trying to implement it, do you know how I can do that?

答:
I solved in this way :

```<code>List<Widget> _ButtonsList(){
  List<String> list = _getLanguages();
  List listings = new List<Widget>();
  int lenght = list.length;
  for (int i=0;i<=lenght; i++){
    listings.add(_getrandomButton(list[i]));
  }
return listings;
}

Widget _myWrap(){
Wrap(
 spacing: 12,
 children: _ButtonsList(),
);
}
</code>```

But it said me that I called list.split on null

```<code>Future<String> _read(String filename) async {
  try {
  final file = await _localFile(filename);

// Read the file.
return await file.readAsString();
} catch (e) {
// If encountering an error, return 0.
return "Can't read";
 }
}

String _myRead( String filename){
var _bio;

_read(filename).then((String) {
  _bio = String;
 });
 return _bio;
}

List<String> _getLanguages() {
 String _bio= _myRead("bio.txt");
 List<String> list =_bio.split(",");
 return list;
}
</code>```

This is what I have inside "bio.txt" :
    English,Italian,Chinese

Body:
I solved in this way :

List<Widget> _ButtonsList(){
  List<String> list = _getLanguages();
  List listings = new List<Widget>();
  int lenght = list.length;
  for (int i=0;i<=lenght; i++){
    listings.add(_getrandomButton(list[i]));
  }
return listings;
}

Widget _myWrap(){
Wrap(
 spacing: 12,
 children: _ButtonsList(),
);
}

But it said me that I called list.split on null

Future<String> _read(String filename) async {
  try {
  final file = await _localFile(filename);

// Read the file.
return await file.readAsString();
} catch (e) {
// If encountering an error, return 0.
return "Can't read";
 }
}

String _myRead( String filename){
var _bio;

_read(filename).then((String) {
  _bio = String;
 });
 return _bio;
}

List<String> _getLanguages() {
 String _bio= _myRead("bio.txt");
 List<String> list =_bio.split(",");
 return list;
}

This is what I have inside "bio.txt" :
    English,Italian,Chinese


问:
Remember me option not working using cookies in ASP .Net MVC
I have created login using asp .net MVC and I have added a cookie for users who select the "Remember me" option. Below is the code used to add a cookie

```<code> if (model.LoginViewModel.RememberMe)
 {
    var authTicket = new FormsAuthenticationTicket(
                        1,
                        model.LoginViewModel.Email,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(20), // expiry
                        model.LoginViewModel.RememberMe, //true to remember
                        "",
                        "/");

    //encrypt the ticket and add it to a cookie
    HttpCookie cookie = new HttpCookie(
                           FormsAuthentication.FormsCookieName,
                           FormsAuthentication.Encrypt(authTicket));
    Response.Cookies.Add(cookie);
 }
</code>```

and I have added this configuration to the web.config as well.

```<code><authentication mode="Forms">
  <forms loginUrl="~/candidate" timeout="2880" />
</authentication>
</code>```

I still can't see my login details when I am going to login for the second time.

Do I have missed something here or are there any other way achieve this?

答:
The bare minimum to replicate FormsAuthentication using OWIN would use something similar to this:

using System.Collections.Generic;
using System.Security.Claims;
using System.Web;
//
using Microsoft.Owin.Security;

namespace YourProjectNamespace
{
    public class ClaimsAuthManager
    {
        public void SignIn(string userName, string displayName = "", bool createPersistantLogin = false)
        {
            var claims = new List<Claim>();

            claims.Add(new Claim(ClaimTypes.Name, userName));
            claims.Add(new Claim(ClaimTypes.IsPersistent, createPersistantLogin.ToString()));

            claims.Add(new Claim(ClaimTypes.GivenName, string.IsNullOrWhiteSpace(displayName) ? userName : displayName));

            var identity = new ClaimsIdentity(claims, AuthenticationTypes.ApplicationCookie);

            GetAuthenticationContext().SignIn(new AuthenticationProperties { IsPersistent = createPersistantLogin }, identity);
        }

        public void SignOut()
        {
            GetAuthenticationContext().SignOut(AuthenticationTypes.ApplicationCookie);
        }

        private IAuthenticationManager GetAuthenticationContext()
        {
            return HttpContext.Current.GetOwinContext().Authentication;
        }
    }
}
```

<p>Unlike FormsAuthentication, this is not a static/singleton object, so you'd need to either inject it into the controller, or create a new instance each time you wanted to sign the user in or out. Something like this:</p>

<pre class="lang-cs prettyprint-override"><code>new ClaimsAuthManager().SignIn(model.LoginViewModel.Email, null, model.LoginViewModel.RememberMe);
</code>```

Body:
I have created login using asp .net MVC and I have added a cookie for users who select the "Remember me" option. Below is the code used to add a cookie

 if (model.LoginViewModel.RememberMe)
 {
    var authTicket = new FormsAuthenticationTicket(
                        1,
                        model.LoginViewModel.Email,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(20), // expiry
                        model.LoginViewModel.RememberMe, //true to remember
                        "",
                        "/");

    //encrypt the ticket and add it to a cookie
    HttpCookie cookie = new HttpCookie(
                           FormsAuthentication.FormsCookieName,
                           FormsAuthentication.Encrypt(authTicket));
    Response.Cookies.Add(cookie);
 }

and I have added this configuration to the web.config as well.

<authentication mode="Forms">
  <forms loginUrl="~/candidate" timeout="2880" />
</authentication>

I still can't see my login details when I am going to login for the second time.

Do I have missed something here or are there any other way achieve this?

Body:
The bare minimum to replicate FormsAuthentication using OWIN would use something similar to this:

using System.Collections.Generic;
using System.Security.Claims;
using System.Web;
//
using Microsoft.Owin.Security;

namespace YourProjectNamespace
{
    public class ClaimsAuthManager
    {
        public void SignIn(string userName, string displayName = "", bool createPersistantLogin = false)
        {
            var claims = new List<Claim>();

            claims.Add(new Claim(ClaimTypes.Name, userName));
            claims.Add(new Claim(ClaimTypes.IsPersistent, createPersistantLogin.ToString()));

            claims.Add(new Claim(ClaimTypes.GivenName, string.IsNullOrWhiteSpace(displayName) ? userName : displayName));

            var identity = new ClaimsIdentity(claims, AuthenticationTypes.ApplicationCookie);

            GetAuthenticationContext().SignIn(new AuthenticationProperties { IsPersistent = createPersistantLogin }, identity);
        }

        public void SignOut()
        {
            GetAuthenticationContext().SignOut(AuthenticationTypes.ApplicationCookie);
        }

        private IAuthenticationManager GetAuthenticationContext()
        {
            return HttpContext.Current.GetOwinContext().Authentication;
        }
    }
}

Unlike FormsAuthentication, this is not a static/singleton object, so you'd need to either inject it into the controller, or create a new instance each time you wanted to sign the user in or out. Something like this:

new ClaimsAuthManager().SignIn(model.LoginViewModel.Email, null, model.LoginViewModel.RememberMe);


问:
?: ?? Operators Instead Of IF|ELSE
```<code>public string Source
{
    get
    {
        /*
        if ( Source == null ){
            return string . Empty;
        } else {
            return Source;
        }
        */
        return Source ?? string.Empty;
    }
    set
    {
        /*
        if ( Source == null ) {
            Source = string . Empty;
        } else {
            if ( Source == value ) {
                Source = Source;
            } else {
                Source = value;
            }
        }
        */
        Source == value ? Source : value ?? string.Empty;
        RaisePropertyChanged ( "Source" );
    }
}
</code>```

Can I use ?: ?? operators EXACTLY as If/Else?

My Question :

How to write the following with ?: ?? operators

[ 1 ]

```<code>if ( Source == null ){
    // Return Nothing
} else {
    return Source;
}
</code>```

[ 2 ]

```<code>if ( Source == value ){
    // Do Nothing
} else {
    Source = value;
    RaisePropertyChanged ( "Source" );
}
</code>```

Briefly : How to do nothing, return nothing and do multiple instructions with ?: ?? operator?

答: I don't think you can its an operator and its suppose to return one or the other.  It's not if else statement replacement although it can be use for that on certain case.</p>

Title: ?: ?? Operators Instead Of IF|ELSE

Body:
public string Source
{
    get
    {
        /*
        if ( Source == null ){
            return string . Empty;
        } else {
            return Source;
        }
        */
        return Source ?? string.Empty;
    }
    set
    {
        /*
        if ( Source == null ) {
            Source = string . Empty;
        } else {
            if ( Source == value ) {
                Source = Source;
            } else {
                Source = value;
            }
        }
        */
        Source == value ? Source : value ?? string.Empty;
        RaisePropertyChanged ( "Source" );
    }
}

Can I use ?: ?? operators EXACTLY as If/Else?

My Question :

How to write the following with ?: ?? operators

[ 1 ]

if ( Source == null ){
    // Return Nothing
} else {
    return Source;
}

[ 2 ]

if ( Source == value ){
    // Do Nothing
} else {
    Source = value;
    RaisePropertyChanged ( "Source" );
}

Briefly : How to do nothing, return nothing and do multiple instructions with ?: ?? operator?


问:
Compile lisp / scheme in Notepad++
I'm pretty much into lisp at the moment, and unfortunately i'm only available to code on windows. Is is possible to let Notepad++ take care of the interpreting of my scripts, and display the output in the compiler window?

If yes, what interpreter would be the best to use?

Thanks!

答: You can set up Notepad++ to run your code using Clisp for Windows.  Click on run and type . clisp -i  "$(FULL_CURRENT_PATH)" and click on save. -i is to keep the clisp window open after execution.

OwnerDisplayName: Alexander Nyquist

ContentLicense: CC BY-SA 2.5

Title: Compile lisp / scheme in Notepad++


问:
HEREWego in Tizen Application
I am creating Tizen application, from the Tizen application i am able to open HereWeGo application explicitly.

I want to pass coordinates and display routes when i request for Map from my application.

How to do it?

```<code>app_control_h a_control_inner = NULL;
app_control_create(&a_control_inner);
app_control_set_operation(a_control_inner, APP_CONTROL_OPERATION_DEFAULT);
app_control_set_app_id(a_control_inner, "com.here.tizen.herewego"); //
app_control_set_uri(a_control_inner,"latitude:12.76333,longitude:80.003500000000003");
app_control_add_extra_data(a_control_inner, "latitude:12.76333", "longitude:80.003500000000003");
int applauch= app_control_send_launch_request(a_control_inner, loc_launch_cb, NULL);
</code>```

答:
Could you try to use Common Application Controls? https://docs.tizen.org/application/native/guides/app-management/common-appcontrols/
You can find two types related with Maps.
- Showing a Location on a Map
- Picking a Location from the Map</p>

Title: HEREWego in Tizen Application

Body:
I am creating Tizen application, from the Tizen application i am able to open HereWeGo application explicitly.

I want to pass coordinates and display routes when i request for Map from my application.

How to do it?

app_control_h a_control_inner = NULL;
app_control_create(&a_control_inner);
app_control_set_operation(a_control_inner, APP_CONTROL_OPERATION_DEFAULT);
app_control_set_app_id(a_control_inner, "com.here.tizen.herewego"); //
app_control_set_uri(a_control_inner,"latitude:12.76333,longitude:80.003500000000003");
app_control_add_extra_data(a_control_inner, "latitude:12.76333", "longitude:80.003500000000003");
int applauch= app_control_send_launch_request(a_control_inner, loc_launch_cb, NULL);


问:
How to convert JSON Object into key value pair in JS?
```<code>{"1":"val1","2":"val2","3":"val3"}
</code>```

i want it to converted like this:

```<code>{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}
</code>```

little Help Please would be much appricated

答:
You can convert your large object to several small objects and store them in an array as this snippet shows. (It could be much shorter, but this verbose demo should be easier to understand.)

// Defines a single object with several properties
const originalObject = { "1" : "val1", "2" : "val2", "3" : "val3" }

// Defines an empty array where we can add small objects
const destinationArray = [];

// Object.entries gives us an array of "entries", which are length-2 arrays
const entries = Object.entries(originalObject);

// `for...of` loops through an array
for(let currentEntry of entries){

  // Each "entry" is an array with two elements
  const theKey = currentEntry[0]; // First element is the key
  const theValue = currentEntry[1]; // Second element is the value

  // Uses the two elements as values in a new object
  const smallObject = { id: theKey, value: theValue };

  // Adds the new object to our array
  destinationArray.push(smallObject);

} // End of for loop (reiterates if there are more entries)

// Prints completed array of small objects to the browser console
console.log(destinationArray);```

Body:
{"1":"val1","2":"val2","3":"val3"}

i want it to converted like this:

{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}

little Help Please would be much appricated


问:
Tkinter transparant frame text is not showing
I am working on a time widget using python tkinter. I want a transparent frame with text but when I add text to my transparent frame the text is not showing. How do I fix this?
This is my code</p>

```<code>import tkinter

app = tkinter.Tk()

app.title("Time")
app.geometry("200x300")
#app.wm_attributes("-aplha", 1)
T = tkinter.Text(app, height=2, width=30)
T.pack()
T.insert(tkinter.END, "Just a text Widget\nin two lines\n")
app.wm_attributes('-alpha', 0.5)

app.mainloop()
</code>```

答:
This code adjusts transparency with buttons.

It works well for me. Maybe your computer doesn't support transparency. Try this and see if the text mysteriously disappears, or if it doesn't:

```<code>import time
from tkinter import *

tk = Tk()

def more_alpha():
    global alpha
    alpha += 0.05
    if alpha >= 1: # correct alpha to prevent errors
        alpha = 0.99
    update()

def less_alpha():
    global alpha
    alpha -= 0.05
    if alpha <= 0: # correct alpha to prevent errors
        alpha = 0.01
    update()

def update():
    global alpha
    tk.wm_attributes('-alpha', alpha)

alpha = 0.5
update()

Button(tk, text="More visibility", command=more_alpha).grid(padx=25, pady=5)
Button(tk, text="Less visibility", command=less_alpha).grid(padx=25, pady=5)

tk.mainloop()
</code>```

Body:
I am working on a time widget using python tkinter. I want a transparent frame with text but when I add text to my transparent frame the text is not showing. How do I fix this?
This is my code

import tkinter

app = tkinter.Tk()

app.title("Time")
app.geometry("200x300")
#app.wm_attributes("-aplha", 1)
T = tkinter.Text(app, height=2, width=30)
T.pack()
T.insert(tkinter.END, "Just a text Widget\nin two lines\n")
app.wm_attributes('-alpha', 0.5)

app.mainloop()

Body:
This code adjusts transparency with buttons.

It works well for me. Maybe your computer doesn't support transparency. Try this and see if the text mysteriously disappears, or if it doesn't:

import time
from tkinter import *

tk = Tk()

def more_alpha():
    global alpha
    alpha += 0.05
    if alpha >= 1: # correct alpha to prevent errors
        alpha = 0.99
    update()

def less_alpha():
    global alpha
    alpha -= 0.05
    if alpha <= 0: # correct alpha to prevent errors
        alpha = 0.01
    update()

def update():
    global alpha
    tk.wm_attributes('-alpha', alpha)

alpha = 0.5
update()

Button(tk, text="More visibility", command=more_alpha).grid(padx=25, pady=5)
Button(tk, text="Less visibility", command=less_alpha).grid(padx=25, pady=5)

tk.mainloop()


问:
How do I link my Python code to Google Cloud's services? Which service should I use?
I have some Python code that I want to use in a flutter app. The code imports quite a few python packages. It is designed to take an input from a flutter app, then process it - partly with the help of the packages - then send the output back. I had a look at the various Google Cloud products, and correct me if I'm wrong, but Cloud functions cannot be used with imported python packages, so that rules it out. So I'm left with App Engine and Cloud Run (?). In that case, which of the two should I use to host the backend code, and how can I get started in doing so? Thanks in advance and cheers.</p>

答:
You can use Cloud Functions with Python, it is a very popular option.

The guide on how to do it is described in this quickstart.

The code should be put in the main.py part and the importst that you used have to be described in a requirements.txt file. Which you can get from you environment, from answer.


问:
Does Kotlin coroutine runs in the same process where the application live?
I am new to kotlin coroutine, I need to know how kotlin coroutine manage its threading work internally.

Does it uses separate thread for each task ?

Does kotlin coroutine stays in the same process where the application
  live ?

Does kotlin coroutine change the process during any intermediate task
  ?

答:
As far as I know, Coroutine uses a thread pool to run tasks.

So we can say as the point of Coroutine users' view each task will run on a separate thread but under the hood, it's just a thread pool.

And for the process yes. It's in the same process as the application is.


问:
Match conditionally upon current node value
Given the following XML:

```<code><current>
  <login_name>jd</login_name>
</current>
<people>
  <person>
    <first>John</first>
    <last>Doe</last>
    <login_name>jd</login_name>
  </preson>
  <person>
    <first>Pierre</first>
    <last>Spring</last>
    <login_name>ps</login_name>
  </preson>
</people>
</code>```

How can I get "John Doe" from within the current/login matcher?

I tried the following:

```<code><xsl:template match="current/login_name">
  <xsl:value-of select="../people/first[login_name = .]"/>
  <xsl:text> </xsl:text>
  <xsl:value-of select="../people/last[login_name = .]"/>
</xsl:template>
</code>```

答:
Just to add my thoughts to the stack

```<code><xsl:template match="login_name[parent::current]">
 <xsl:variable name="login" select="text()"/>
 <xsl:value-of select='concat(ancestor::people/child::person[login_name=$login]/child::first/text()," ",ancestor::people/child::person[login_name=$login]/child::last/text())'/>
</xsl:template>
</code>```

I always prefer to use the axes explicitly in my XPath, more verbose but clearer IMHO.

Depending on how the rest of the XML documents looks (assuming this is just a fragment) you might need to constrain the reference to "ancestor::people" for example using "ancestor::people[1]" to constrain to the first people ancestor.

OwnerDisplayName: caillou

Body:
Given the following XML:

<current>
  <login_name>jd</login_name>
</current>
<people>
  <person>
    <first>John</first>
    <last>Doe</last>
    <login_name>jd</login_name>
  </preson>
  <person>
    <first>Pierre</first>
    <last>Spring</last>
    <login_name>ps</login_name>
  </preson>
</people>

How can I get "John Doe" from within the current/login matcher?

I tried the following:

<xsl:template match="current/login_name">
  <xsl:value-of select="../people/first[login_name = .]"/>
  <xsl:text> </xsl:text>
  <xsl:value-of select="../people/last[login_name = .]"/>
</xsl:template>

Body:
Just to add my thoughts to the stack

<xsl:template match="login_name[parent::current]">
 <xsl:variable name="login" select="text()"/>
 <xsl:value-of select='concat(ancestor::people/child::person[login_name=$login]/child::first/text()," ",ancestor::people/child::person[login_name=$login]/child::last/text())'/>
</xsl:template>

I always prefer to use the axes explicitly in my XPath, more verbose but clearer IMHO.

Depending on how the rest of the XML documents looks (assuming this is just a fragment) you might need to constrain the reference to "ancestor::people" for example using "ancestor::people[1]" to constrain to the first people ancestor.

OwnerDisplayName: Matt Large


问:
Null SelectInput for Filtering in a Table in Shiny
I have ran into an issue, where I would like to filter a DT table using the values input from SelectInput. This works well, but the table will only appear if I have completed all values that I am filtering against.

I would like the table to appear if the values in the SelectInput are NULL, however, this does not work. I am wondering if anyone has some advice for how to show the table when SelectInput in NULL for all the categories or just for some. In other words, I would like to turn off the SelectInput filtering if nothing is selected.

An excerpt of the code that is relevant to this issue is below.

```<code>box(selectInput("category", "Select Category", sources_cat, selected = NULL, multiple = TRUE),
                                      selectInput("age", "Select Age Group", sources_age, selected = NULL, multiple = TRUE),
                                      selectInput("country", "Select Country", sources_count, selected = NULL, multiple = TRUE)),
                                  box(HTML("<br/> <h5><b>Topic Definitions</b></h5> <br/>")),
                                  ),
                              box(width = NULL, dataTableOutput('table'))
                      ),

server <- function(input, output){

output$table <- DT::renderDataTable({

    cat <- input$category
    country_input <- input$country
    age_select <- input$age
    input1 <- input1
    input2 <- input2

    fsources <- sources %>%
        filter(grepl(country_input[1], country) | grepl(country_input[2], country) | grepl(country_input[3], country) |
               grepl(country_input[4], country))

    fsources <- fsources %>%
        filter(grepl(age_select[1], age) | grepl(age_select[2], age) | grepl(age_select[3], age))

    fsources <- fsources %>%
        filter(grepl(cat[1], topics) | grepl(cat[2], topics) | grepl(cat[3], topics) |
                   grepl(cat[4], topics))

    #this output table only appears if there is a country and a topic selected. If not, it has an error. One must chose a country or a topic
    datatable(fsources, extensions = 'Buttons', options = list(
        dom = 'Bfrtip',
        buttons = c('copy', 'csv', 'excel', 'pdf', 'print')
    ))

})
</code>```

The error message when SelectInput == NULL

答:
Place each of your filters in an if statement, such as

```<code>if (all(!is.null(country_input)) {
  fsources <- sources %>%
                filter(
                  grepl(country_input[1], country) |
                  grepl(country_input[2], country) |
                  grepl(country_input[3], country) |
                  grepl(country_input[4], country)
  )
}
</code>```

That will solve the particular problem you've asked.  More generally, I'd suggest separating the derivation of the table from its presentation.  This is good programming practice because it makes your code reusable.

Also, you are more likely to get quicker and more useful replies if you provide a simple self-contained example.  Please see this post for more information.  My code is untested because you haven't done so in this case.

Body:
I have ran into an issue, where I would like to filter a DT table using the values input from SelectInput. This works well, but the table will only appear if I have completed all values that I am filtering against.

I would like the table to appear if the values in the SelectInput are NULL, however, this does not work. I am wondering if anyone has some advice for how to show the table when SelectInput in NULL for all the categories or just for some. In other words, I would like to turn off the SelectInput filtering if nothing is selected.

An excerpt of the code that is relevant to this issue is below.

box(selectInput("category", "Select Category", sources_cat, selected = NULL, multiple = TRUE),
                                      selectInput("age", "Select Age Group", sources_age, selected = NULL, multiple = TRUE),
                                      selectInput("country", "Select Country", sources_count, selected = NULL, multiple = TRUE)),
                                  box(HTML("

Topic Definitions

")),
                                  ),
                              box(width = NULL, dataTableOutput('table'))
                      ),

server <- function(input, output){

output$table <- DT::renderDataTable({

    cat <- input$category
    country_input <- input$country
    age_select <- input$age
    input1 <- input1
    input2 <- input2

    fsources <- sources %>%
        filter(grepl(country_input[1], country) | grepl(country_input[2], country) | grepl(country_input[3], country) |
               grepl(country_input[4], country))

    fsources <- fsources %>%
        filter(grepl(age_select[1], age) | grepl(age_select[2], age) | grepl(age_select[3], age))

    fsources <- fsources %>%
        filter(grepl(cat[1], topics) | grepl(cat[2], topics) | grepl(cat[3], topics) |
                   grepl(cat[4], topics))

    #this output table only appears if there is a country and a topic selected. If not, it has an error. One must chose a country or a topic
    datatable(fsources, extensions = 'Buttons', options = list(
        dom = 'Bfrtip',
        buttons = c('copy', 'csv', 'excel', 'pdf', 'print')
    ))

})

The error message when SelectInput == NULL

Body:
Place each of your filters in an if statement, such as

if (all(!is.null(country_input)) {
  fsources <- sources %>%
                filter(
                  grepl(country_input[1], country) |
                  grepl(country_input[2], country) |
                  grepl(country_input[3], country) |
                  grepl(country_input[4], country)
  )
}

That will solve the particular problem you've asked.  More generally, I'd suggest separating the derivation of the table from its presentation.  This is good programming practice because it makes your code reusable.

Also, you are more likely to get quicker and more useful replies if you provide a simple self-contained example.  Please see this post for more information.  My code is untested because you haven't done so in this case.


问:
While creating the Android Application using Android Kotlin, could'nt display map, even though the App is working normally
While creating the Android Application using Android Kotlin, could'nt display map, even though the App is working normally, the map is blank without any content in it.

Also tried by changing the Api key

```<code>package com.example.currentlocationexample

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    private lateinit var mMap: GoogleMap

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment = supportFragmentManager
                .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }

    override fun onMapReady(googleMap: GoogleMap) {

        mMap = googleMap

        // Add a marker in Sydney and move the camera
        val sydney = LatLng(-34.0, 151.0)
        mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
    }
}
</code>```

Code developed automatically after creating maps activity but does'nt show the map after running on AVD.

```<code>2020-05-29 11:23:31.146 8721-8791/com.example.currentlocationexample E/Google Maps Android API: Authorization failure.  Please see https://developers.google.com/maps/documentation/android-api/start for how to correctly set up the map.
2020-05-29 11:23:31.148 212-212/? I/hwservicemanager: getTransport: Cannot find entry android.hardware.graphics.allocator@4.0::IAllocator/default in either framework or device manifest.
2020-05-29 11:23:31.156 8721-8791/com.example.currentlocationexample E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
    Ensure that the "Google Maps Android API v2" is enabled.
    Ensure that the following Android Key exists:
        API Key: AIzaSyAUhYTWyk24s2_73aD4BlvIuP_4UZP
        Android Application (<cert_fingerprint>;<package_name>): 73:E8:C1:5C:01:85:AF:F5:58:D1:28:B5:4E:E8:B8:08:18:F0:24:9C;com.example.currentlocationexample
</code>```

Also tried using different API keys

答:
Login to Google Developer Console (https://console.developers.google.com) and
Ensure that the "Google Maps Android API v2" is enabled.</p>

Body:
While creating the Android Application using Android Kotlin, could'nt display map, even though the App is working normally, the map is blank without any content in it.

Also tried by changing the Api key

package com.example.currentlocationexample

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    private lateinit var mMap: GoogleMap

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment = supportFragmentManager
                .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }

    override fun onMapReady(googleMap: GoogleMap) {

        mMap = googleMap

        // Add a marker in Sydney and move the camera
        val sydney = LatLng(-34.0, 151.0)
        mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
    }
}

Code developed automatically after creating maps activity but does'nt show the map after running on AVD.

2020-05-29 11:23:31.146 8721-8791/com.example.currentlocationexample E/Google Maps Android API: Authorization failure.  Please see https://developers.google.com/maps/documentation/android-api/start for how to correctly set up the map.
2020-05-29 11:23:31.148 212-212/? I/hwservicemanager: getTransport: Cannot find entry android.hardware.graphics.allocator@4.0::IAllocator/default in either framework or device manifest.
2020-05-29 11:23:31.156 8721-8791/com.example.currentlocationexample E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
    Ensure that the "Google Maps Android API v2" is enabled.
    Ensure that the following Android Key exists:
        API Key: AIzaSyAUhYTWyk24s2_73aD4BlvIuP_4UZP
        Android Application (<cert_fingerprint>;<package_name>): 73:E8:C1:5C:01:85:AF:F5:58:D1:28:B5:4E:E8:B8:08:18:F0:24:9C;com.example.currentlocationexample

Also tried using different API keys


问:
hive auto increment after certain number
I have a to insert data into a  target table where all columns should be populated from different source tables except the surrogate key column; which should be maximum value of the target table plus auto increment value starting 1. I can generate auto increment value by using row_number() function, but in the same query how should I get the max value of surrogate key from target table. Is there any concept in HIVE where I can select the max value of surrogate key and save it in a temporary variable? Or is there any other simple way to achieve this result? </p>

答:
create table autoincrement1 ( id int, name string)

insert into autoincrement1

select if(isnull(max(id)) ,0 , max(id) ) +1, 'sagar' from autoincrement1


问:
Sizeof(uint8_t*) is always 4?
I create a vector of uint_8t* sometimes with 3, 4 or 5 bytes but when I make the sizeof my array, I always get 4. How can I solve this?

After creating my array I want to get the length of it.

Example:

```<code>uint_8t* u8;

u8[0]=...;
u8[1]=...;

</code>```

sizeof(u8)=4 instead of 2.

sizeof(uint8_t) is 1, I Alo triedsizeof(u8)/sizeof(u8[0])` and I get 4

答:
sizeof(uint8_t*) is the size of pointer. Which is typically 4 for 32-bit architectures and 8 for 64-bit architectures. Also typically this doesn't depend on the underlying structure (should be the same for uint8_t*, std::string*, long*, and so on), although this is not guaranteed.

sizeof(uint8_t) is 1 because that's what uint8_t is: a 1 byte.

It seems that you want to know the size of the memory which uint8_t* points at. There is no way to do that given a pointer only. You have to track the size manually. Typically by using std::vector<uint8_t> instead of raw pointers.

Title: Sizeof(uint8_t*) is always 4?

Body:
I create a vector of uint_8t* sometimes with 3, 4 or 5 bytes but when I make the sizeof my array, I always get 4. How can I solve this?

After creating my array I want to get the length of it.

Example:

uint_8t* u8;

u8[0]=...;
u8[1]=...;

sizeof(u8)=4 instead of 2.

sizeof(uint8_t) is 1, I Alo triedsizeof(u8)/sizeof(u8[0])` and I get 4


答:
the ?: is the itinerary operator. (believe i spelled that properly) and it's simple to use.
as in a boolean predicate ? iftrue : ifalse; But you must have a rvalue/lvalue as in rvalue = predicate ? iftrue: iffalse;

ex int i = x < 7 ? x : 7;

if x was less than 7, i would get assigned x, if not i would be 7.

you can also use it in a return, as in return x < 7 ? x : 7;

again, as above , this would have the same affect.

so, Source = Source == value ? Source : string.Empty; i believe is what your trying to acheive.

Title: ?: ?? Operators Instead Of IF|ELSE


答:
Using List Comprehensions

```<code>items = [item for array in array.tolist() for item in array]
</code>```

Using Numpy Module

```<code>np.concatenate(list).ravel().tolist()
</code>```

Title: How to convert list of arrays to single list in python?

Body:
I have a list of arrays as follows:

list = [
         array([4.1,3.2,5.2]),
         array([4.1,8.5]),
         array([1.2,4.5,7.4])
        ]

I want to convert the above list into a single list as below:

list = [4.1,3.2,5.2,4.1,8.5,1.2,4.5,7.4]

I want to do the above thing in python.

EDIT:

The code I used to generate the list is

  result = []
  result.append(mfccs_processed)
  result.append(chroma_processed)
  result.append(mel_processed)

Now result is showing as follows:

[array([-445.43651286,  111.90097184,  -21.00590592,   31.34361885,
      9.39596702,   -4.40772227,    2.3648624 ,   -1.68017743,
     -6.39975114,   -1.12694295,   -9.34500736,   -1.13545822,
     -7.88168904,  -10.9743485 ,   -2.77344424,   -1.23599528,
     -7.39119564,   -2.44394294,   -3.75691633,   -4.80426688,
     -1.94571499,   -3.95747011,   -5.72427054,   -4.81378321,
     -3.70200738,   -5.19167481,   -4.47207894,   -4.2216418 ,
     -4.1305041 ,   -5.10309738,   -3.89591536,   -2.67058964,
     -4.04656319,   -4.78655754,   -2.44667325,   -3.05293339,
     -4.17915009,   -2.90706455,   -2.8132492 ]), array([0.548945  , 0.59981299, 0.58249648, 0.5834056 , 0.62918682,
   0.58651369, 0.51776701, 0.5152288 , 0.56039473, 0.5606346 ,
   0.59585897, 0.56108877]), array([5.36600691e-05, 3.20399714e-04, 1.19905308e-03, 3.57715592e-03,
   5.45226355e-03, 7.65769149e-02, 9.67304585e-01, 1.37048258e+00,
   2.20317190e+00, 1.47716846e+00, 7.10145651e-01, 7.23264577e-02,
   3.20378431e-02, 2.13741716e-01, 3.50276892e-01, 3.25545211e-01,
   8.23071739e-01, 1.10485735e+00, 5.16918943e-01, 8.84181377e-01,
   9.06340752e-01, 3.95779410e-01, 3.13891357e-01, 1.13048804e-01,
   6.61881599e-01, 1.70450985e+00, 1.82170031e+00, 6.18310782e-01,
   4.05325714e-01, 5.89335840e-01, 4.31023403e-01, 9.29283876e-02,
   4.11129880e-02, 1.71606268e-01, 1.41923368e-01, 9.29835332e-02,
   1.45740019e-01, 1.27688893e-01, 2.34819748e-02, 9.72517361e-03,
   3.63473003e-02, 5.93138929e-02, 3.11671706e-02, 1.18442648e-02,
   8.33423898e-03, 1.87190944e-02, 3.29460414e-02, 2.69168857e-02,
   9.29586223e-03, 6.80686607e-03, 9.94785389e-03, 1.27595168e-02,
   8.88170288e-03, 7.44158290e-03, 9.98228524e-03, 1.63925465e-02,
   9.53423946e-03, 1.05554487e-02, 1.54851110e-02, 2.05146191e-02,
   1.30264012e-02, 7.20523041e-03, 1.83835207e-02, 1.00800192e-02,
   9.16292185e-03, 2.75197205e-02, 1.26532376e-02, 5.50722000e-03,
   8.06991937e-03, 4.67484356e-03, 9.11601494e-03, 9.94969137e-03,
   8.82691376e-03, 1.35812921e-02, 3.38891723e-02, 5.48777803e-02,
   5.47833810e-02, 3.91788967e-02, 2.34909778e-02, 1.59119884e-02,
   1.76145638e-02, 2.31054147e-02, 2.95776919e-02, 4.17103322e-02,
   2.07705960e-02, 1.08400124e-02, 6.43834017e-03, 4.46195474e-03,
   4.44256498e-03, 5.25020141e-03, 1.14951221e-02, 1.41466409e-02,
   1.73377342e-02, 1.41098637e-02, 7.04262356e-03, 3.99505900e-03,
   2.48446049e-03, 1.61739298e-03, 9.00339387e-04, 3.25213392e-04,
   2.93450309e-04, 3.10071719e-04, 2.85876075e-04, 1.78957305e-04,
   1.38316595e-04, 1.07859368e-04, 1.15453318e-04, 8.50033585e-05,
   7.25839567e-05, 3.80280533e-05, 3.57639077e-05, 2.47069514e-05,
   1.57980270e-05, 1.50489378e-05, 1.12732923e-05, 1.08223414e-05,
   1.21111000e-05, 1.57062296e-05, 1.11814270e-05, 9.70704523e-06,
   8.27147728e-06, 6.56079447e-06, 5.53983257e-06, 5.31472585e-06,
   2.77939077e-06, 1.77413323e-06, 1.03589758e-06, 6.50496670e-08])]

Since I already converted my whole dataset using this code above. Now I want to convert the above generated lists into a single list as I explained above. I hope this clarifies the problem. Could you help me out.

Body:
Using List Comprehensions

items = [item for array in array.tolist() for item in array]

Using Numpy Module

np.concatenate(list).ravel().tolist()


问:
AWS ElasticSearch Request not giving response in Postman
https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-use-postman-to-call-api.html

I am following above document, to connect to my AWS Elastic Search via Postman.

What I want to achieve sent request & get the response.

I put all things related Authentication as well, still it is giving timeout error.

It is giving error 'Could not get any response'.

My Postman settings related to SSL is also correct

Sample URL :

```<code>https://vpc-abc-yqb7jfwa6tw6ebwzphynyfvaka.ap-southeast-1.es.amazonaws.com/elasticsearch_index/_search?source={"query":{"bool":{"should":[{"multi_match":{"query":"abc","fields":["name.suggestion"],"fuzziness":1}}]}},"size":10,"_source":["name"],"highlight":{"fields":{"name.suggestion":{}},"pre_tags":["\u003Cem\u003E"],"post_tags":["\u003C\/em\u003E"]}}&source_content_type=application/json
</code>```

答:
For creating and managing ES domain you can refer this documentation.

While creating ES domain in the Network configuration section, you can choose either VPC access or Public access. If you select public access, you can secure your domain with an access policy that only allows specific users or IP addresses to access the domain.

To know more about access policies, you can refer this SO answer.

So, if you create your ES domain outside VPC, in public access you can easily send request and get response through postman, without adding any Authorization.

The endpoint in the url, is the endpoint that is generated when you have created your ES domain.

To create an index

For adding data into the index

Get API to get the mapping of index created

Now, you can check it from your AWS console, that this index is created in the ES domain

Body:
https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-use-postman-to-call-api.html

I am following above document, to connect to my AWS Elastic Search via Postman.

What I want to achieve sent request & get the response.

I put all things related Authentication as well, still it is giving timeout error.

It is giving error 'Could not get any response'.

My Postman settings related to SSL is also correct

Sample URL :

https://vpc-abc-yqb7jfwa6tw6ebwzphynyfvaka.ap-southeast-1.es.amazonaws.com/elasticsearch_index/_search?source={"query":{"bool":{"should":[{"multi_match":{"query":"abc","fields":["name.suggestion"],"fuzziness":1}}]}},"size":10,"_source":["name"],"highlight":{"fields":{"name.suggestion":{}},"pre_tags":["\u003Cem\u003E"],"post_tags":["\u003C\/em\u003E"]}}&source_content_type=application/json


问:
Return HTTP CODE in custom validator Spring Rest
I'm working on an API REST using Spring and I'm trying to create a new custom validator with 2 validations.

For each validator I want to return a different HTTP CODE to the users but I'm stuck on it, I just know that I can return a boolean in the isValid method.

I hope someone could help me or give me a better way to accomplish this thing.

UserController.java

```<code>@RestController
@RequestMapping("user")
public class UserController {
@PostMapping
public ResponseEntity<?> addUser(@Valid @RequestBody User
     user, Errors errors)  {

    //Here I don't now How to read just one error from Validator class, I just want to return 1 error using the HTTP CODE
    if (errors.hasErrors()) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT); //I'm just using a generic but I want to use the returned by Validator which has 2 validations and should return different errors
    }
    return new ResponseEntity<>(user, HttpStatus.OK);
  }
 }
</code>```

User.java

```<code>public class User {

    @NotNull
    private final String name;

    @NotNull
    @UserConstraint
    private final Integer age;

    public User(@JsonProperty("name") String name, @JsonProperty("age") Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }

}
</code>```

UserConstraint.java

```<code>@Documented
@Constraint(validatedBy = UserValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserConstraint {
   String message() default "Invalid age";
   Class<?>[] groups() default {};
   Class<? extends Payload>[] payload() default {};
}
</code>```

UserValidator.java

```<code>public class UserValidator implements ConstraintValidator<UserConstraint, Integer>  {

        @Override
        public void initialize(UserConstraint constraintAnnotation) {
        }

        @Override
        public boolean isValid(Integer age, ConstraintValidatorContext context) {

          if(age > 60) {
              //Here I want to return HTTP CODE 402 to the user
              return false;
          } else if(age < 18) {
              //Here I want to return HTTP CODE 422 to the user
              return false;
          }
          return true;
    }
}
</code>```

As you can see I'm trying to do some validations with the age and I want to return a different HTTP CODE to users.

答:
You could throw a ResponseStatusException

```<code>throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "error message");
</code>```

Body:
I'm working on an API REST using Spring and I'm trying to create a new custom validator with 2 validations.

For each validator I want to return a different HTTP CODE to the users but I'm stuck on it, I just know that I can return a boolean in the isValid method.

I hope someone could help me or give me a better way to accomplish this thing.

UserController.java

@RestController
@RequestMapping("user")
public class UserController {
@PostMapping
public ResponseEntity<?> addUser(@Valid @RequestBody User
     user, Errors errors)  {

    //Here I don't now How to read just one error from Validator class, I just want to return 1 error using the HTTP CODE
    if (errors.hasErrors()) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT); //I'm just using a generic but I want to use the returned by Validator which has 2 validations and should return different errors
    }
    return new ResponseEntity<>(user, HttpStatus.OK);
  }
 }

User.java

public class User {

    @NotNull
    private final String name;

    @NotNull
    @UserConstraint
    private final Integer age;

    public User(@JsonProperty("name") String name, @JsonProperty("age") Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }

}

UserConstraint.java

@Documented
@Constraint(validatedBy = UserValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserConstraint {
   String message() default "Invalid age";
   Class<?>[] groups() default {};
   Class<? extends Payload>[] payload() default {};
}

UserValidator.java

public class UserValidator implements ConstraintValidator<UserConstraint, Integer>  {

        @Override
        public void initialize(UserConstraint constraintAnnotation) {
        }

        @Override
        public boolean isValid(Integer age, ConstraintValidatorContext context) {

          if(age > 60) {
              //Here I want to return HTTP CODE 402 to the user
              return false;
          } else if(age < 18) {
              //Here I want to return HTTP CODE 422 to the user
              return false;
          }
          return true;
    }
}

As you can see I'm trying to do some validations with the age and I want to return a different HTTP CODE to users.

Body:
You could throw a ResponseStatusException

throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "error message");


问:
Programattically set barbutton " System Item"
I want to set share button on rightbarbuttonitem of navigation controller.
I don't want to add custom images , I want use share button image provided by Xcode.This is how I do in storyboard.
I set Style , and set System_Item as Action.

Now the question is how do I set System_Item programatically, if I create barbuttonitem programatically ?

```<code>let shareButton = UIBarButtonItem(title: "",
                                  style: .plain,
                                  target: self,
                                  action: #selector(shareAction(sender:)))
    shareButton.tintColor = AppColor.barButtonColor

    navigationItem.rightBarButtonItem = shareButton
</code>```

答:
You can create an extension to do this ->

public extension UIViewController {

    func setRightBarButtonItem(tintColor: UIColor = AppColor.barButtonColor) {
        let button = UIButton(type: .system)

        button.tintColor = tintColor
        button.setImage(UIImage(.action), for: .normal) // <-- Set system icon to button

        button.translatesAutoresizingMaskIntoConstraints = false

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tap))
        button.addGestureRecognizer(tapGesture)

        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
    }

    @objc func tap() {
        // Do stuff
    }
}
```

<p>Then in your ViewController</p>

<pre class="lang-swift prettyprint-override"><code>override func viewDidLoad() {
    super.viewDidLoad()
    setRightBarButtonItem()

    // OR

    setRightBarButtonItem(tintColor: .blue)
}
</code>```

UIImage extension to use system icons without version control

extension UIImage {

  public convenience init?(_ systemItem: UIBarButtonItem.SystemItem) {

    guard let sysImage = UIImage.imageFrom(systemItem: systemItem)?.cgImage else {
      return nil
    }

    self.init(cgImage: sysImage)
  }

  private class func imageFrom(systemItem: UIBarButtonItem.SystemItem) -> UIImage? {

    let sysBarButtonItem = UIBarButtonItem(barButtonSystemItem: systemItem, target: nil, action: nil)

    let toolBar = UIToolbar()
    toolBar.setItems([sysBarButtonItem], animated: false)
    toolBar.snapshotView(afterScreenUpdates: true)

    if let buttonView = sysBarButtonItem.value(forKey: "view") as? UIView{
      for subView in buttonView.subviews where subView is UIButton {
        let button = subView as! UIButton
        let image = button.imageView!.image!
        return image
      }
    }
    return nil
  }
}
```

Body:
I want to set share button on rightbarbuttonitem of navigation controller.
I don't want to add custom images , I want use share button image provided by Xcode.This is how I do in storyboard.
I set Style , and set System_Item as Action.

Now the question is how do I set System_Item programatically, if I create barbuttonitem programatically ?

let shareButton = UIBarButtonItem(title: "",
                                  style: .plain,
                                  target: self,
                                  action: #selector(shareAction(sender:)))
    shareButton.tintColor = AppColor.barButtonColor

    navigationItem.rightBarButtonItem = shareButton

Body:
You can create an extension to do this ->

public extension UIViewController {

    func setRightBarButtonItem(tintColor: UIColor = AppColor.barButtonColor) {
        let button = UIButton(type: .system)

        button.tintColor = tintColor
        button.setImage(UIImage(.action), for: .normal) // <-- Set system icon to button

        button.translatesAutoresizingMaskIntoConstraints = false

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tap))
        button.addGestureRecognizer(tapGesture)

        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
    }

    @objc func tap() {
        // Do stuff
    }
}

Then in your ViewController

override func viewDidLoad() {
    super.viewDidLoad()
    setRightBarButtonItem()

    // OR

    setRightBarButtonItem(tintColor: .blue)
}

UIImage extension to use system icons without version control

extension UIImage {

  public convenience init?(_ systemItem: UIBarButtonItem.SystemItem) {

    guard let sysImage = UIImage.imageFrom(systemItem: systemItem)?.cgImage else {
      return nil
    }

    self.init(cgImage: sysImage)
  }

  private class func imageFrom(systemItem: UIBarButtonItem.SystemItem) -> UIImage? {

    let sysBarButtonItem = UIBarButtonItem(barButtonSystemItem: systemItem, target: nil, action: nil)

    let toolBar = UIToolbar()
    toolBar.setItems([sysBarButtonItem], animated: false)
    toolBar.snapshotView(afterScreenUpdates: true)

    if let buttonView = sysBarButtonItem.value(forKey: "view") as? UIView{
      for subView in buttonView.subviews where subView is UIButton {
        let button = subView as! UIButton
        let image = button.imageView!.image!
        return image
      }
    }
    return nil
  }
}


问:
Steps for a highly imbalanced classification steps. Should I up-sample & under-sample data or just up-sample the imbalanced class
I have a highly imbalanced binary (yes/no) classification dataset.
The dataset currently has appx 0.008% 'yes'.

I need to balance the dataset using SMOTE.

I came across 2 method to deal with the imbalance.
The following steps after I have run MinMaxScaler on the variables

```<code>from imblearn.pipeline import Pipeline
oversample = SMOTE(sampling_strategy = 0.1, random_state=42)
undersample = RandomUnderSampler(sampling_strategy=0.5, random_state=42)
steps = [('o', oversample), ('u', undersample)]
pipeline = Pipeline(steps=steps)
x_scaled_s, y_s = pipeline.fit_resample(X_scaled, y)
</code>```

This results in a reduction in the size of the dataset from 2.4million rows to 732000 rows
And the imbalance improves from 0.008% to 33.33%

While this approach

```<code>sm = SMOTE(random_state=42)
X_sm , y_sm = sm.fit_sample(X_scaled, y)
</code>```

This increases the number of rows from 2.4million rows to 4.8 million rows and the imbalance is now 50%.

After these steps I need to split data into Train Test datasets....

What is the right approach here?

What factors do I need to consider before I choose any of these methods?

Should I run the X_test, y_test on unsampled data. This would mean, I split the data and do upsampling/undersampling only on the train data.

Thank you.

JD

答:
After these steps I need to split data into Train Test datasets....

No! Any resampling techniques should be applied only on the train set. This will ensure that the test set reflects the reality. The model performance obtained on such a test set will be a good estimate of your model's generalization ability. If the resampling is performed on the whole dataset, your model's performance is going to be overly optimistic.

Steps:

Split your dataset into train and test sets.

Upsample/undersample only the train set.

Train your model on the resampled train set.

Estimate the performance on your untouched test set.

Body:
I have a highly imbalanced binary (yes/no) classification dataset.
The dataset currently has appx 0.008% 'yes'.

I need to balance the dataset using SMOTE.

I came across 2 method to deal with the imbalance.
The following steps after I have run MinMaxScaler on the variables

from imblearn.pipeline import Pipeline
oversample = SMOTE(sampling_strategy = 0.1, random_state=42)
undersample = RandomUnderSampler(sampling_strategy=0.5, random_state=42)
steps = [('o', oversample), ('u', undersample)]
pipeline = Pipeline(steps=steps)
x_scaled_s, y_s = pipeline.fit_resample(X_scaled, y)

This results in a reduction in the size of the dataset from 2.4million rows to 732000 rows
And the imbalance improves from 0.008% to 33.33%

While this approach

sm = SMOTE(random_state=42)
X_sm , y_sm = sm.fit_sample(X_scaled, y)

This increases the number of rows from 2.4million rows to 4.8 million rows and the imbalance is now 50%.

After these steps I need to split data into Train Test datasets....

What is the right approach here?

What factors do I need to consider before I choose any of these methods?

Should I run the X_test, y_test on unsampled data. This would mean, I split the data and do upsampling/undersampling only on the train data.

Thank you.

JD