问:
Detach Goroutine into Independent Process
I have a function that plays a sound that I want to continue executing after my main program prints to standard output and exits. My reasoning is that I want the sound to finish playing after the program has exited but I don't want the main program to wait for the sound to finish playing before it exits.

I found a method for executing the sound in an independent process by turning it into an executable named playsound and doing go install. Then in my main program, I call this at the end of main():

func startPlaySound() {
    cmd := exec.Command("playsound")
    cmd.Start()
}

main() {
   // code that prints and exits

   startPlaySound()
}
```

<p>This works but I would like to be able to play the sound after the main program exits without creating an executable file. I would rather run the equivalent of <code>cmd.Start()</code> on the function containing the code to play the sound.</p>

<p>In other words, I would like it to look something like this:</p>

```func playSound() {
    // code that plays the sound
}

func startPlaySound() {
   cmd := CmdFromFunction(playSound)
   cmd.Start()
}

main() {
   // code that prints and exits

   startPlaySound()
}
```

Does something like CmdFromFunction exist?

Response to Question Feedback

This is not a duplicate of How do I fork a go process?. I am not trying to fork the main goroutine. I am trying to detach playSound into a separate process that will continue executing after the main goroutine exits. Both of the answers to that question involve executing an external program, which is exactly what I am trying to avoid.

"go routines are not meant to be processes" - I literally turned the code from playSound into an executable called playsound and am now executing it as a process using cmd.Start(). I'm just trying to find a more direct route for doing that than creating an entirely separate executable file.

答:
GO routines are not meant to be processes

This might work. I have done this myself, But you might be restricted to bash shell.

```<code>cmd := exec.Command("bash", "-c", "playsound", "&")
</code>```

Body:
I have a function that plays a sound that I want to continue executing after my main program prints to standard output and exits. My reasoning is that I want the sound to finish playing after the program has exited but I don't want the main program to wait for the sound to finish playing before it exits.

I found a method for executing the sound in an independent process by turning it into an executable named playsound and doing go install. Then in my main program, I call this at the end of main():

func startPlaySound() {
    cmd := exec.Command("playsound")
    cmd.Start()
}

main() {
   // code that prints and exits

   startPlaySound()
}

This works but I would like to be able to play the sound after the main program exits without creating an executable file. I would rather run the equivalent of cmd.Start() on the function containing the code to play the sound.

In other words, I would like it to look something like this:

func playSound() {
    // code that plays the sound
}

func startPlaySound() {
   cmd := CmdFromFunction(playSound)
   cmd.Start()
}

main() {
   // code that prints and exits

   startPlaySound()
}

Does something like CmdFromFunction exist?

Response to Question Feedback

This is not a duplicate of How do I fork a go process?. I am not trying to fork the main goroutine. I am trying to detach playSound into a separate process that will continue executing after the main goroutine exits. Both of the answers to that question involve executing an external program, which is exactly what I am trying to avoid.

"go routines are not meant to be processes" - I literally turned the code from playSound into an executable called playsound and am now executing it as a process using cmd.Start(). I'm just trying to find a more direct route for doing that than creating an entirely separate executable file.

Body:
GO routines are not meant to be processes

This might work. I have done this myself, But you might be restricted to bash shell.

cmd := exec.Command("bash", "-c", "playsound", "&")


来源: stackexchange

问:
Swift Convert date string to Date
I got a date string from server side, which is Tue, 28 May 2019 13:24:06 +0000. I tried to do following:

```<code>let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
let date = dateFormatter.date(from: "Tue, 28 May 2019 13:24:06 +0000")
</code>```

result is nil

How can I convert a string like this to a Date?

答:
You need to set a specific dateFormat. And when doing so, set the date formatter's locale to en_US_POSIX.

```<code>let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
let date = dateFormatter.date(from: "Tue, 28 May 2019 13:24:06 +0000")
</code>```

See the documentation for dateFormat for links that take you a full description of what all of the format specifiers mean.

Keep in mind that when converting a Date to a String for display to the user, then using date and time styles is the best solution. But for parsing a String into a Date, use dateFormat.

ContentLicense: CC BY-SA 4.0

Title: Swift Convert date string to Date

Body:
I got a date string from server side, which is Tue, 28 May 2019 13:24:06 +0000. I tried to do following:

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
let date = dateFormatter.date(from: "Tue, 28 May 2019 13:24:06 +0000")

result is nil

How can I convert a string like this to a Date?

Body:
You need to set a specific dateFormat. And when doing so, set the date formatter's locale to en_US_POSIX.

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
let date = dateFormatter.date(from: "Tue, 28 May 2019 13:24:06 +0000")

See the documentation for dateFormat for links that take you a full description of what all of the format specifiers mean.

Keep in mind that when converting a Date to a String for display to the user, then using date and time styles is the best solution. But for parsing a String into a Date, use dateFormat.


问:
ValueError: invalid literal for int() with base 10: '-'
I'm saving up some data using python as a CSV file while trying to convert the string(numeric icons) to int.

```<code>style_tag = soup.select('style')
icons = (str(style_tag[1]).split("."))
mp = {}
for e in icons:
if "icon-" in e:
if "content" in e:
mp[e.split("{")[0].split(":")[0]] = (int(e.split('"')[1][-2:])) - 1
</code>```

The above lines shows the error

```<code>mp[e.split("{")[0].split(":")[0]] = (int(e.split('"')[1][-2:])) - 1
ValueError: invalid literal for int() with base 10: '-'
</code>```

答:
In stead of this single line :

```<code>mp[e.split("{")[0].split(":")[0]] = (int(e.split('"')[1][-2:])) - 1
</code>```

Try this :

```<code>key_ = e.split("{")[0].split(":")[0]
val_ = e.split('"')[1][-2:]
try:
    val_int = int(val_) - 1
    mp[key_] = val_int
except Exception:
    pass
</code>```

Body:
I'm saving up some data using python as a CSV file while trying to convert the string(numeric icons) to int.

style_tag = soup.select('style')
icons = (str(style_tag[1]).split("."))
mp = {}
for e in icons:
if "icon-" in e:
if "content" in e:
mp[e.split("{")[0].split(":")[0]] = (int(e.split('"')[1][-2:])) - 1

The above lines shows the error

mp[e.split("{")[0].split(":")[0]] = (int(e.split('"')[1][-2:])) - 1
ValueError: invalid literal for int() with base 10: '-'

Body:
In stead of this single line :

mp[e.split("{")[0].split(":")[0]] = (int(e.split('"')[1][-2:])) - 1

Try this :

key_ = e.split("{")[0].split(":")[0]
val_ = e.split('"')[1][-2:]
try:
    val_int = int(val_) - 1
    mp[key_] = val_int
except Exception:
    pass


问:
How to get particular page selected by default?
I have a pagination as shown in here https://jsfiddle.net/solodev/yw7y4wez/

I want to get some page selected or highlighted by default (suppose page 8)

I tried following code but it doesn't work

```<code>page = '@Model.CurrentPageIndex';
$('.page-active').removeClass('page-active');
$('#page' + page).addClass('page-active');
</code>```

where '@Model.CurrentPageIndex' contains page no. (e.g. 8)

答:
Try below:</p>

```<code>var page = '@Model.CurrentPageIndex';
$('.page-active').removeClass('page-active');

$('ul.pagination li a.page-link').each(function(index) {
    if (Number($(this).html()) === Number(page)) {
     $(this).closest('li').addClass('page-active');
    }
});
</code>```

Body:
I have a pagination as shown in here https://jsfiddle.net/solodev/yw7y4wez/

I want to get some page selected or highlighted by default (suppose page 8)

I tried following code but it doesn't work

page = '@Model.CurrentPageIndex';
$('.page-active').removeClass('page-active');
$('#page' + page).addClass('page-active');

where '@Model.CurrentPageIndex' contains page no. (e.g. 8)

Body:
Try below:

var page = '@Model.CurrentPageIndex';
$('.page-active').removeClass('page-active');

$('ul.pagination li a.page-link').each(function(index) {
    if (Number($(this).html()) === Number(page)) {
     $(this).closest('li').addClass('page-active');
    }
});


问:
BizTalk - Exception Handling and Send Alert to System Administrator
In Microsoft BizTalk Application when exception occurred then Services or port will goes to in suspended mode and need to manually start application or port.

What i want is when any exceptions occurred during message processing should send one email alert to system administrator and details of exception should be stored in separate database for further process.

Anyone have any better suggestion how we can do it.

Regards,

Rakesh

答: To handle the message failure secnario see using Failed Message Routing.  As far as monitoring ports when they shut down you can either use MOM (expensive) or write a script to do what you want.  There are many posts here in stackoverflow that address this... here is one such post.</p>

ContentLicense: CC BY-SA 3.0


答:
Try following,</p>

```<code>page = '@Model.CurrentPageIndex';
$('#pagination-demo').twbsPagination('show', page);
</code>```

Title: How to get particular page selected by default?

Body:
Try following,

page = '@Model.CurrentPageIndex';
$('#pagination-demo').twbsPagination('show', page);


问:
Android Studio : Error running 'app' Default activity not found
I'm new to android studio and doing my first project.  I made changes to my layout xml file after which getting the above mentioned error. i didn't add any new activity and also the android manifest.xml file has default activity mentioned.

I have tried to invalidate the cache and restart the Android studio but still the error exists and I'm not able to execute my program.

答: You can configure it from "app" -> "Configurations"


问:
How to call update on component, only when poll is finish in Primefaces. From the View
 The update="" is being called on each interval. Is there a way to call an update only when the poll is stopped, and only once?

Eksample: How do I update button-fragment only once, when the poll stops?

```<code><p:poll interval="2" update="@(.button-fragment)" stop="#{stopMethod()}">
</code>```

Edit: I would like to do it from the view

答:
Besides the fact that your poll never stops, I would do something similar to

```<code><p:poll interval="2" stop="isPollStopped()" listener="updateOnPollStop()">
</code>```

and in the view bean

```<code>public boolean isPollStopped() {
    return ...;
}

public void updateOnPollStop() {
    final boolean pollStopped = this.isPollStopped();

    if (pollStopped) {
        RequestContext.getCurrentInstance().update("@(.button-fragment)");
    }
}
</code>```

Edit:

Totally not tested, but perhaps this might work:

```<code><p:poll interval="2" oncomplete="handlePollComplete(xhr, status, args)" stop="#{stopMethod()}">

function handlePollComplete(xhr, status, args) {
    if (!PF(<YOUR_POLL_ID>).active) {
        PF(<YOUR_UPDATEE_ID>).update()
    }
}
</code>```

Edit 2 (using remoteCommand)

```<code><p:remoteCommand name="updateOnPollStop" update="@(.button-fragment)"/>
<p:poll widgetVar="myPoll" interval="2" oncomplete="handlePollComplete(xhr, status, args)" stop="#{stopMethod()}">

function handlePollComplete(xhr, status, args) {
    if (!PF('myPoll').active) {
        updateOnPollStop()
    }
}
</code>```

Body:
 The update="" is being called on each interval. Is there a way to call an update only when the poll is stopped, and only once?

Eksample: How do I update button-fragment only once, when the poll stops?

Edit: I would like to do it from the view

Body:
Besides the fact that your poll never stops, I would do something similar to

<p:poll interval="2" stop="isPollStopped()" listener="updateOnPollStop()">

and in the view bean

public boolean isPollStopped() {
    return ...;
}

public void updateOnPollStop() {
    final boolean pollStopped = this.isPollStopped();

    if (pollStopped) {
        RequestContext.getCurrentInstance().update("@(.button-fragment)");
    }
}

Edit:

Totally not tested, but perhaps this might work:

<p:poll interval="2" oncomplete="handlePollComplete(xhr, status, args)" stop="#{stopMethod()}">

function handlePollComplete(xhr, status, args) {
    if (!PF(<YOUR_POLL_ID>).active) {
        PF(<YOUR_UPDATEE_ID>).update()
    }
}

Edit 2 (using remoteCommand)

<p:remoteCommand name="updateOnPollStop" update="@(.button-fragment)"/>
<p:poll widgetVar="myPoll" interval="2" oncomplete="handlePollComplete(xhr, status, args)" stop="#{stopMethod()}">

function handlePollComplete(xhr, status, args) {
    if (!PF('myPoll').active) {
        updateOnPollStop()
    }
}


问:
DataTables read ajax response with your own parameters
Using DataTables 1.10.15 in Server Side mode. I've created a PHP script to provide a JSON response which includes the parameters they mention in the documentation: https://datatables.net/manual/server-side#Returned-data

I want to add my own parameters to the JSON response, e.g.

```<code>$response = [
    'data' => [ ], // Required by DataTables
    'form_errors' => [ ] // Not required by DataTables
];
echo json_encode($response);
</code>```

The js which I have for the ajax call looks like this:

```<code>var myTable = $('#myTable').DataTable( {
    "serverSide": true,
    "ajax": {
        "url" : "/response.php",
        "method" : "POST"
    },
});
</code>```

How can I read the ajax response? I've seen in the API that there is a .on('xhr') method (https://datatables.net/reference/event/xhr) which fires when the ajax request has been completed, e.g.

```<code>var myTable = $('#myTable').DataTable( {
    "serverSide": true,
    "ajax": {
        "url" : "/response.php",
        "method" : "POST"
    },
}).on( 'xhr.dt', function () {
    // Read response here?
});
</code>```

But I cannot find a way to read the ajax response data at that point.

Does anyone know if this is possible?

答:
This should be ajax property of DataTable

```<code>"dataSrc": function(json) {
if (json.CustomVariable) {
    $("#some_span").html(json.CustomVariable);
}
// You can also modify `json.data` if required
return json.data;
</code>```

A full example according to the code in question can be

```<code>var myTable = $('#myTable').DataTable({
            "serverSide": true,
            "ajax": {
                "url": "/response.php",
                "method": "POST",
                "dataSrc": function(json) {
                    if (json.CustomVariable) {
                        $("#some_span").html(json.CustomVariable);
                    }
                    // You can also modify `json.data` if required
                    return json.data;
                },
            });
</code>```

Reference DataTables > Return custom variables from server side to datatables ajax call

Body:
Using DataTables 1.10.15 in Server Side mode. I've created a PHP script to provide a JSON response which includes the parameters they mention in the documentation: https://datatables.net/manual/server-side#Returned-data

I want to add my own parameters to the JSON response, e.g.

$response = [
    'data' => [ ], // Required by DataTables
    'form_errors' => [ ] // Not required by DataTables
];
echo json_encode($response);

The js which I have for the ajax call looks like this:

var myTable = $('#myTable').DataTable( {
    "serverSide": true,
    "ajax": {
        "url" : "/response.php",
        "method" : "POST"
    },
});

How can I read the ajax response? I've seen in the API that there is a .on('xhr') method (https://datatables.net/reference/event/xhr) which fires when the ajax request has been completed, e.g.

var myTable = $('#myTable').DataTable( {
    "serverSide": true,
    "ajax": {
        "url" : "/response.php",
        "method" : "POST"
    },
}).on( 'xhr.dt', function () {
    // Read response here?
});

But I cannot find a way to read the ajax response data at that point.

Does anyone know if this is possible?

Body:
This should be ajax property of DataTable

"dataSrc": function(json) {
if (json.CustomVariable) {
    $("#some_span").html(json.CustomVariable);
}
// You can also modify `json.data` if required
return json.data;

A full example according to the code in question can be

var myTable = $('#myTable').DataTable({
            "serverSide": true,
            "ajax": {
                "url": "/response.php",
                "method": "POST",
                "dataSrc": function(json) {
                    if (json.CustomVariable) {
                        $("#some_span").html(json.CustomVariable);
                    }
                    // You can also modify `json.data` if required
                    return json.data;
                },
            });

Reference DataTables > Return custom variables from server side to datatables ajax call


问:
Databinding falls behind event notification - discussion
Found an interesting problem that I first found in WinForms, and found again in Silverlight, and more than likely WPF as well when it comes to databinding.

I have a tab control with several tabs.  As users click across the tabs, each time should be valid before allowing the user to switch from the tab.

For example, user is in a text box which is updated.  Binding of text boxes is not flushed until the control loses focus.  Loss of focus occurs when the cursor is moved from the control, and focus is given to another control.

In this scenario, the user tabs into a control (let's use text box for this example), and updates the text box.  At this point the databinding has not flushed the control, and hence the VM has not yet seen the change.  The user then uses their mouse to click the next tab of the control.

At this point things get interesting.  I used the PreviewSelectionChanged (Telerik RadTabControl), as I want to check things out before the jump to the next tab occurs, and it also gives me the ability to cancel the event.

However, when I look at the VM, in this event, it still does not have the updated data.  I see the VM is clean, and go ahead and allow the jump to the next tab.

As soon as this event is over however, the databindings flush, and the VM gets updated. what now? The events are out of sync!  When the mouse was used to click the next tab, the textbox should have lost focus, flushed it's bindings, before the Preview of the Tab click! It's to late to jump back and say oops we didn't catch that in time!

I think I found an interesting work around to this issue - but I'm not 100% sure it will work 100% of the time.  I cancel the current event, but then I use the Dispatcher and create a delegate pointing to another method with the same signature as the current event.  The Dispatcher will add this message to the message pump, which by this time will now (hopefully?) be behind the messages of the VM updating...

My two questions are:
1) I'm assuming that the textbox control either didn't flush when the mouse left the control, or the process that was fired was too slow and hence the preview message was on the pump before the databinding - either way I see this to be a major issue.

2) Is the workaround a good solution?

答:
Ok, first to answer question 1:

Just because the mouse left the textbox area, doesn't mean that the textbox lost focus. It only loses focus once something else gets focus. For example, if you moved the mouse out of the textbox and click on some other control on your page (it can be anything from a scroll viewer to another textbox, etc.) then your textbox will lose focus.

Now, based on that, the events do not happen in the wrong order. What happens is; your click event on the other tab triggers both the textbox to lose focus (and the data binding to take place) and the move to the next frame, and based on that, you basically get a race condition where the moving to the next tab happens before the databinding takes place.

About question 2:

What you can do is, set the UpdateSourceTrigger to Explicit, you will however be forced to then have some kind of text_changed event and manually update the binding.

You can read more about that here. It might not be the most complete explanation but is a good place to start.

On the other hand, you can associate some events to the textbox and force the textbox to lose focus on those events (e.g. mouse out).

ContentLicense: CC BY-SA 2.5


答:
The problem come from

int(e.split('"')[1][-2:])
```

<p>The result of the expressions that you try to convert in int is the character '-' and python cant interpret this as a int.
The problem is just that you didn't select the right part of ur data with </p>

<pre class="lang-py prettyprint-override"><code>e.split('"')[1][-2:]
</code>```

To help you more we will need a sample of your data.

Title: ValueError: invalid literal for int() with base 10: '-'

Body:
The problem come from

int(e.split('"')[1][-2:])

The result of the expressions that you try to convert in int is the character '-' and python cant interpret this as a int.
The problem is just that you didn't select the right part of ur data with

e.split('"')[1][-2:]

To help you more we will need a sample of your data.


问:
Cannot connect to local SQL Server with SequelizeJS
I'm trying to connect to my local SQL Server, but it shows an error SequelizeHostNotFoundError. I can connect with it on SSMS.

```<code>instance = new Sequelize('database', 'local123', 'local123', {
   host: "tcp:NETWORK-PC\\MYCOMPANYSQL,49172",
   dialect: 'mssql',
   port: 49172,
   operatorsAliases: false,
   dialectOptions: {
      options: {
          encrypt: true,
      }
   },
   pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000
   },
})
</code>```

Errors: SequelizeHostNotFoundError: Failed to connect to tcp:NETWORK-PC\MYCOMPANYSQL,49172 - getaddrinfo ENOTFOUND tcp:NETWORK-PC\MYCOMPANYSQL,49172

答: Local at what level? Have you tried "localhost" as a host?</p>

Body:
I'm trying to connect to my local SQL Server, but it shows an error SequelizeHostNotFoundError. I can connect with it on SSMS.

instance = new Sequelize('database', 'local123', 'local123', {
   host: "tcp:NETWORK-PC\\MYCOMPANYSQL,49172",
   dialect: 'mssql',
   port: 49172,
   operatorsAliases: false,
   dialectOptions: {
      options: {
          encrypt: true,
      }
   },
   pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000
   },
})

Errors: SequelizeHostNotFoundError: Failed to connect to tcp:NETWORK-PC\MYCOMPANYSQL,49172 - getaddrinfo ENOTFOUND tcp:NETWORK-PC\MYCOMPANYSQL,49172


问:
Having issue converting response in UTF-8 format
I am getting an error with this line:

```<code>Data(from: responseValue.utf8 as! Decoder)
</code>```

)

Cannot convert value of type 'Data' to expected argument type 'Data'

```<code>do{
    let responseData = try JSONDecoder().decode(forget_Base.self, from: Data(from: responseValue.utf8 as! Decoder))
    if responseData.code == 200
    {
        let message = isNilValue(assignValue: responseData.message)
        let alert = UIAlertController(title: "", message: message, preferredStyle: .alert)
        let action = UIAlertAction(title: "OK", style: .default, handler: {(_action) -> Void in
            let next = self.storyboard?.instantiateViewController(withIdentifier: "SetPasswordVCSID")
            self.navigationController?.pushViewController(next!, animated: true)
        })
        alert.addAction(action)
        self.present(alert, animated: true, completion: nil)
    }
    else
    {
    }
}
catch
{
    print("error")
}
</code>```

How can I resolve it? I already tried too many things but I am stuck with it.

答:
Use responseValue as it is.
Here's the code:
change the following

```<code>let responseData = try JSONDecoder().decode(forget_Base.self, from: Data(from: responseValue.utf8 as! Decoder))
</code>```

to

```<code>let responseData = try JSONDecoder().decode(forget_Base.self, from:responseValue)

</code>```

Body:
I am getting an error with this line:

Data(from: responseValue.utf8 as! Decoder)

)

Cannot convert value of type 'Data' to expected argument type 'Data'

do{
    let responseData = try JSONDecoder().decode(forget_Base.self, from: Data(from: responseValue.utf8 as! Decoder))
    if responseData.code == 200
    {
        let message = isNilValue(assignValue: responseData.message)
        let alert = UIAlertController(title: "", message: message, preferredStyle: .alert)
        let action = UIAlertAction(title: "OK", style: .default, handler: {(_action) -> Void in
            let next = self.storyboard?.instantiateViewController(withIdentifier: "SetPasswordVCSID")
            self.navigationController?.pushViewController(next!, animated: true)
        })
        alert.addAction(action)
        self.present(alert, animated: true, completion: nil)
    }
    else
    {
    }
}
catch
{
    print("error")
}

How can I resolve it? I already tried too many things but I am stuck with it.

Body:
Use responseValue as it is.
Here's the code:
change the following

let responseData = try JSONDecoder().decode(forget_Base.self, from: Data(from: responseValue.utf8 as! Decoder))

to

let responseData = try JSONDecoder().decode(forget_Base.self, from:responseValue)


问:
Converting csv read hex string values to uint8_t in c++
So I am currently able to read some hex values from a csv file using ifstream. I am able to read the values and assign them to a string variable. But I want to convert them to uint8_t values. So essentially I want something like this uint8_t A = 0x41;

I have tried atoi ,  stoi , and strtol but i don't seem to get any valid output.(I might be using them wrong)

int read_csv(){
using namespace std;
ifstream fin;
fin.open("simpletrajhex.txt");
while (fin.good ()){
      char[] line;
      getline (fin, line, ',');
      uint8_t hex1 = (uint8_t)stoi(line,NULL,16);
      cout << line << " " << hex1 << endl;
    }
  return 1;
}
```

<p>When I read my csv file i get something similar</p>

```0xFF
0x5F
0x02
0x00
0xFF
```

But these are strings and I need each value to be converted to uint8_t
and when I try convert nothing shows up.

答:
You have a number of problems with your code, but two primary problems related to your conversion to uint8_t. A general problem with attempting to read a .csv file with getline (fin, line, ','); is you have no way of tracking the number of values present in each line. Reading with the ',' delimiter will cause getline to skip the line-ending and simple read the next value until EOF is encountered. Better to read an entire line into line with getline (fin, line); and then create a stringstream from line allowing  you to read the value in the line until the end of the stringstream is reached (limiting the value conversions to those within each line).

The primary obstacle to storing the values as uint8_t is your failure the validate the the result of the stoi conversion is within the range of uint8_t before making the assignment. Further, since uint8_t is an unsigned value, use of stoul is more appropriate. While the C-style cast to (uint8_t) is valid, it is better to use a static_cast<uint8_t>(...) (though both provide the same result). Finally, your attempt to output << hex1 ... will always fail as the << operator expects an int (or unsigned) value.

Putting all of those pieces together, you can rework your read_csv() to take the name of the file to open as a parameter rather than hardcoding the filename in the function (don't do that) and do something like:

```<code>int read_csv (const string& name)
{
    string line;
    ifstream fin (name);

    while (getline (fin, line)) {           /* read entire line into line */
        stringstream ss (line);             /* create stringstream from line */
        string field;                       /* string to hold each field */
        cout << "line: " << line << '\n';
        while (getline (ss, field, ',')) {  /* read each hex value from line */
            uint64_t tmp = stoul (field, 0, 0); /* convert to uint64_t */
            if (tmp <= UINT8_MAX) {         /* validate in range of uint8_t */
                uint8_t hex1 = static_cast<uint8_t>(tmp);   /* store uint8_t */
                /* output with cast to unsigned for << */
                cout << "  " << field << " -> " <<
                        static_cast<uint32_t>(hex1) << '\n';
            }
        }
    }
    return 1;
}
</code>```

note: rather than casing within cout you can also precede hex1 with a numeric + to force the promotion, e.g.

```<code>cout << "  " << field << " -> " << +hex1 << '\n';
</code>```

also note: that using 0 for the base in stoul, the numeric base is auto-detected: if the prefix is 0, the base is octal, if the prefix is 0x or 0X, the base is hexadecimal, otherwise the base is decimal.

A short example making use of the function could be:

```<code>#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdint>

using namespace std;

int read_csv (const string& name)
{
    string line;
    ifstream fin (name);

    while (getline (fin, line)) {           /* read entire line into line */
        stringstream ss (line);             /* create stringstream from line */
        string field;                       /* string to hold each field */
        cout << "line: " << line << '\n';
        while (getline (ss, field, ',')) {  /* read each hex value from line */
            uint64_t tmp = stoul (field, 0, 0); /* convert to uint64_t */
            if (tmp <= UINT8_MAX) {         /* validate in range of uint8_t */
                uint8_t hex1 = static_cast<uint8_t>(tmp);   /* store uint8_t */
                /* output with cast to unsigned for << */
                cout << "  " << field << " -> " <<
                        static_cast<uint32_t>(hex1) << '\n';
            }
        }
    }
    return 1;
}

int main (int argc, char **argv) {

    if (argc < 2) {
        cerr << "error: insufficient input\n" <<
                "usage: " << argv[0] << " <file>\n";
        return 1;
    }

    read_csv (argv[1]);
}
</code>```

(note: using namespace std; is generally encouraged, so while it can ease typing for short example programs, you will generally want to avoid including the entire std namespace in each source file (and especially avoid including it in header files))

Example Input File

```<code>$ cat dat/hexcsv.csv
0xff,0x5f
0x02,0x00
0xff,0xaa
</code>```

Example Use/Output

Each of the numeric values are store in the uint8_t variable hex1 before being output in decimal.

```<code>$ ./bin/read_csv_uint8 dat/hexcsv.csv
line: 0xff,0x5f
  0xff -> 255
  0x5f -> 95
line: 0x02,0x00
  0x02 -> 2
  0x00 -> 0
line: 0xff,0xaa
  0xff -> 255
  0xaa -> 170
</code>```

Body:
So I am currently able to read some hex values from a csv file using ifstream. I am able to read the values and assign them to a string variable. But I want to convert them to uint8_t values. So essentially I want something like this uint8_t A = 0x41;

I have tried atoi ,  stoi , and strtol but i don't seem to get any valid output.(I might be using them wrong)

int read_csv(){
using namespace std;
ifstream fin;
fin.open("simpletrajhex.txt");
while (fin.good ()){
      char[] line;
      getline (fin, line, ',');
      uint8_t hex1 = (uint8_t)stoi(line,NULL,16);
      cout << line << " " << hex1 << endl;
    }
  return 1;
}

When I read my csv file i get something similar

0xFF
0x5F
0x02
0x00
0xFF

But these are strings and I need each value to be converted to uint8_t
and when I try convert nothing shows up.

Body:
You have a number of problems with your code, but two primary problems related to your conversion to uint8_t. A general problem with attempting to read a .csv file with getline (fin, line, ','); is you have no way of tracking the number of values present in each line. Reading with the ',' delimiter will cause getline to skip the line-ending and simple read the next value until EOF is encountered. Better to read an entire line into line with getline (fin, line); and then create a stringstream from line allowing  you to read the value in the line until the end of the stringstream is reached (limiting the value conversions to those within each line).

The primary obstacle to storing the values as uint8_t is your failure the validate the the result of the stoi conversion is within the range of uint8_t before making the assignment. Further, since uint8_t is an unsigned value, use of stoul is more appropriate. While the C-style cast to (uint8_t) is valid, it is better to use a static_cast<uint8_t>(...) (though both provide the same result). Finally, your attempt to output << hex1 ... will always fail as the << operator expects an int (or unsigned) value.

Putting all of those pieces together, you can rework your read_csv() to take the name of the file to open as a parameter rather than hardcoding the filename in the function (don't do that) and do something like:

int read_csv (const string& name)
{
    string line;
    ifstream fin (name);

    while (getline (fin, line)) {           /* read entire line into line */
        stringstream ss (line);             /* create stringstream from line */
        string field;                       /* string to hold each field */
        cout << "line: " << line << '\n';
        while (getline (ss, field, ',')) {  /* read each hex value from line */
            uint64_t tmp = stoul (field, 0, 0); /* convert to uint64_t */
            if (tmp <= UINT8_MAX) {         /* validate in range of uint8_t */
                uint8_t hex1 = static_cast<uint8_t>(tmp);   /* store uint8_t */
                /* output with cast to unsigned for << */
                cout << "  " << field << " -> " <<
                        static_cast<uint32_t>(hex1) << '\n';
            }
        }
    }
    return 1;
}

note: rather than casing within cout you can also precede hex1 with a numeric + to force the promotion, e.g.

cout << "  " << field << " -> " << +hex1 << '\n';

also note: that using 0 for the base in stoul, the numeric base is auto-detected: if the prefix is 0, the base is octal, if the prefix is 0x or 0X, the base is hexadecimal, otherwise the base is decimal.

A short example making use of the function could be:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdint>

using namespace std;

int read_csv (const string& name)
{
    string line;
    ifstream fin (name);

    while (getline (fin, line)) {           /* read entire line into line */
        stringstream ss (line);             /* create stringstream from line */
        string field;                       /* string to hold each field */
        cout << "line: " << line << '\n';
        while (getline (ss, field, ',')) {  /* read each hex value from line */
            uint64_t tmp = stoul (field, 0, 0); /* convert to uint64_t */
            if (tmp <= UINT8_MAX) {         /* validate in range of uint8_t */
                uint8_t hex1 = static_cast<uint8_t>(tmp);   /* store uint8_t */
                /* output with cast to unsigned for << */
                cout << "  " << field << " -> " <<
                        static_cast<uint32_t>(hex1) << '\n';
            }
        }
    }
    return 1;
}

int main (int argc, char **argv) {

    if (argc < 2) {
        cerr << "error: insufficient input\n" <<
                "usage: " << argv[0] << " <file>\n";
        return 1;
    }

    read_csv (argv[1]);
}

(note: using namespace std; is generally encouraged, so while it can ease typing for short example programs, you will generally want to avoid including the entire std namespace in each source file (and especially avoid including it in header files))

Example Input File

$ cat dat/hexcsv.csv
0xff,0x5f
0x02,0x00
0xff,0xaa

Example Use/Output

Each of the numeric values are store in the uint8_t variable hex1 before being output in decimal.

$ ./bin/read_csv_uint8 dat/hexcsv.csv
line: 0xff,0x5f
  0xff -> 255
  0x5f -> 95
line: 0x02,0x00
  0x02 -> 2
  0x00 -> 0
line: 0xff,0xaa
  0xff -> 255
  0xaa -> 170


问:
Picking the smallest value in a list using recursion
This is a function I defined in order to find the smallest value in a list using recursion.However,I called the function twice within itself, which I think it's a bit weird.
Is there a way around the function append()?. We haven't studied it yet so I'm asking whether there could be a simpler way to get the same solution by not using append()?

```<code>def minimum(lst):
    """
    parameters : lst of type list
    return : the value of the smallest element in the lst
    """
    if len(lst) == 1:
        return lst[0]

    if lst[0] < lst[1]:
        lst.append(lst[0])
        return(minimum(lst[1:]))
    return(minimum(lst[1:]))
</code>```

答:
In Python 3, I'd be tempted to try:

```<code>def minimum(lst):
    if not lst:
        return None

    a, *rest = lst

    if rest:
        b = minimum(rest)

        if b < a:
            return b

    return a
</code>```

Most of the proposed solutions, with the exception of @roeen30 (+1) but including the currently accepted one, don't defend themselves against minimum([]).   Many go into an infinite recursion as a result!

Body:
This is a function I defined in order to find the smallest value in a list using recursion.However,I called the function twice within itself, which I think it's a bit weird.
Is there a way around the function append()?. We haven't studied it yet so I'm asking whether there could be a simpler way to get the same solution by not using append()?

def minimum(lst):
    """
    parameters : lst of type list
    return : the value of the smallest element in the lst
    """
    if len(lst) == 1:
        return lst[0]

    if lst[0] < lst[1]:
        lst.append(lst[0])
        return(minimum(lst[1:]))
    return(minimum(lst[1:]))

Body:
In Python 3, I'd be tempted to try:

def minimum(lst):
    if not lst:
        return None

    a, *rest = lst

    if rest:
        b = minimum(rest)

        if b < a:
            return b

    return a

Most of the proposed solutions, with the exception of @roeen30 (+1) but including the currently accepted one, don't defend themselves against minimum([]).   Many go into an infinite recursion as a result!


问:
PHP/MySQL If FROM Statements
sorry for the extremely basic question!! I'm very new to PHP/MySQL

How would it be possible to do an if statement referencing wherever or not data was from a certain table.

Would this work?

```<code>if ( $search FROM "table2" )
{
function for table2.. etc
}
</code>```

TABLE:INSTRUMENTS

COLUMNS:

```<code> id   instrument    grade   standard    comments
      instrument2   grade2  standard2   comments2
      instrument3   grade3  standard3   comments3
      instrument4   grade4  standard4   comments4
      instrument5   grade5  standard5   comments5
</code>```

TABLE: PEOPLE

COLUMNS:

```<code>id  first  last  snumber  course  email  graduate  inumber
</code>```

Basically a person from the PEOPLE table is linked via ID to instruments in the INSTRUMENTS table, I have an e-mail search function that I need to send out the relative data to the relative instruments.

I want to get the comments[i] , grade[i], standard[i] of the matching instrument[i]

答:
You would need to store what table the search result was from in a variable, and compare the two variables.

```<code>if($search === "table2")
</code>```

There is no from operator in PHP.

Title: PHP/MySQL If FROM Statements

Body:
sorry for the extremely basic question!! I'm very new to PHP/MySQL

How would it be possible to do an if statement referencing wherever or not data was from a certain table.

Would this work?

if ( $search FROM "table2" )
{
function for table2.. etc
}

TABLE:INSTRUMENTS

COLUMNS:

 id   instrument    grade   standard    comments
      instrument2   grade2  standard2   comments2
      instrument3   grade3  standard3   comments3
      instrument4   grade4  standard4   comments4
      instrument5   grade5  standard5   comments5

TABLE: PEOPLE

COLUMNS:

id  first  last  snumber  course  email  graduate  inumber

Basically a person from the PEOPLE table is linked via ID to instruments in the INSTRUMENTS table, I have an e-mail search function that I need to send out the relative data to the relative instruments.

I want to get the comments[i] , grade[i], standard[i] of the matching instrument[i]

Body:
You would need to store what table the search result was from in a variable, and compare the two variables.

if($search === "table2")

There is no from operator in PHP.


问:
For loop to read file names
I am new to python. I want to create a for loop that prints all the file names in my folder.

This is what I have :

```<code>import cf
f = cf.read('/home/cd_files')
for i in f:
  print f
</code>```

The file names are string values. I am guessing what I failed to include in my code.

答:
you can try below code to print all the files under the directory and sub directories. </p>

```<code>   for root, dir, files in os.walk("/home/cd_files"):
        for file in files:
            print file
</code>```

Title: For loop to read file names

Body:
I am new to python. I want to create a for loop that prints all the file names in my folder.

This is what I have :

import cf
f = cf.read('/home/cd_files')
for i in f:
  print f

The file names are string values. I am guessing what I failed to include in my code.

Body:
you can try below code to print all the files under the directory and sub directories.

   for root, dir, files in os.walk("/home/cd_files"):
        for file in files:
            print file


问:
KMeans Clustering on Movielens Dataset
I am working on the Movielens dataset and I wanted to apply K-Means algorithm on it. I would like to know what columns to choose for this purpose and How can I proceed further Or Should I directly use the KNN algorithm.</p>

答:
Well, K-Means is a clustering Algorithm so you can use it to cluster the movies based on the genres.
Columns: movieId, genres

There's a new dataset which includes relevant tags for each movie, so you can also cluster them based on those tags.

However, you can also make use of K-Nearest Neighbors to find out how users are similar to each other.

In the reviews dataset, you would use the following columns:
Columns: userId, rating

While in the movies dataset you would use the movieId.
The idea is to figure out which movies every user has viewed, then use those movies to compute the similarity index of users (eg; user1, user2)

Title: KMeans Clustering on Movielens Dataset


问:
Remove S3 object after assign tag
I'd like to delete AWS S3 Object 30 days after assign tag. It seems to be easy when I tagged a new file during creation, but what if the file was created more than 30 days ago and I still want to be compliant  with retention policy (30 days) and do not delete it too early.

I was hoping that I could use transaction Lifecycle policy to the Glacier and then delete the file but it also based on creation date.

Is there another option without lambda usage?

```<code>{
    "Rules": [
        {
            "Status": "Enabled",
            "NoncurrentVersionExpiration": {
                "NoncurrentDays": 31
            },
            "NoncurrentVersionTransitions": [
                {
                    "NoncurrentDays": 1,
                    "StorageClass": "GLACIER"
                }
            ],
            "Filter": {
                "Tag": {
                    "Value": "true",
                    "Key": "toDelete"
                }
            },
            "Expiration": {
                "Days": 31
            },
            "Transitions": [
                {
                    "Days": 1,
                    "StorageClass": "GLACIER"
                }
            ],
            "ID": "delete-tagged-toDelete-after-31days"
        }
    ]
}
</code>```

答:
There is no "out-of-the-box" solution for what you wish to do.

Amazon S3 Lifecycle Rules are based on Creation Date. Adding a tag to an object is not sufficient to "reset the clock" for a lifecycle rule.

Some ideas:

You might be able to copy the object to itself and add a tag. This might should the Create Date on the object.

You can create an AWS Lambda function, triggered on a regular schedule by an Amazon CloudWatch Events rule, that scans the bucket for objects and deletes them based on tag. The tag could contain a delete date that the Lambda function uses to determine whether the delete date has passed.

Title: Remove S3 object after assign tag

Body:
I'd like to delete AWS S3 Object 30 days after assign tag. It seems to be easy when I tagged a new file during creation, but what if the file was created more than 30 days ago and I still want to be compliant  with retention policy (30 days) and do not delete it too early.

I was hoping that I could use transaction Lifecycle policy to the Glacier and then delete the file but it also based on creation date.

Is there another option without lambda usage?

{
    "Rules": [
        {
            "Status": "Enabled",
            "NoncurrentVersionExpiration": {
                "NoncurrentDays": 31
            },
            "NoncurrentVersionTransitions": [
                {
                    "NoncurrentDays": 1,
                    "StorageClass": "GLACIER"
                }
            ],
            "Filter": {
                "Tag": {
                    "Value": "true",
                    "Key": "toDelete"
                }
            },
            "Expiration": {
                "Days": 31
            },
            "Transitions": [
                {
                    "Days": 1,
                    "StorageClass": "GLACIER"
                }
            ],
            "ID": "delete-tagged-toDelete-after-31days"
        }
    ]
}


答:
According to the error message it's simply

```<code>let responseData = try JSONDecoder().decode(forget_Base.self, from: Data(responseValue.utf8))
</code>```

A type cast to Decoder is pointless anyway.

And please conform to the naming convention, forget_Base is horrible, name it ForgetBase

Title: Having issue converting response in UTF-8 format

Body:
According to the error message it's simply

let responseData = try JSONDecoder().decode(forget_Base.self, from: Data(responseValue.utf8))

A type cast to Decoder is pointless anyway.

And please conform to the naming convention, forget_Base is horrible, name it ForgetBase


问:
Trim the string data fetched from the table in delphi using ado dataset
I have got a table column of datatype char and by making use of ADO dataset I am fetching the data. But because of type char, it displays the data with trailing extra spaces. And the form on which this ADO dataset lies is inherited by many forms. I want to trim the extra spaces by making  some change in the Delphi code on parent form by using some ADO dataset property

I have made use of FixedChar property of the data field by making it to false but that did not work

答:
```<code>Select Cast(mycharcolumn as varchar(10)) as mynewcharcolumn from tablename
</code>```

If you can change the query that retrieves the data, like I've shown here, then you effectively convert your char columns to varchar columns at the dataset level.

If you are unable to make changes to the query, then another way is to add a calculated column to the Tfield list of the dataset, and in the OnCalcFields event handler, you can Trim(mycharcolumn) to 'calculate' the value of the calculated field, which you then use in the code, in place of the original field.

Body:
Select Cast(mycharcolumn as varchar(10)) as mynewcharcolumn from tablename

If you can change the query that retrieves the data, like I've shown here, then you effectively convert your char columns to varchar columns at the dataset level.

If you are unable to make changes to the query, then another way is to add a calculated column to the Tfield list of the dataset, and in the OnCalcFields event handler, you can Trim(mycharcolumn) to 'calculate' the value of the calculated field, which you then use in the code, in place of the original field.


问:
Performance issue with @angular/material autocomplete
I am using Angular/Material Autocomplete. While loading data to the Autocomplete getting serious performance issues,like the rendering takes around 30 seconds and it takes more than 10 seconds to become stable,data is loaded from the server, and the data received from the server is quite fast. To Over Come that issue i used cdkVirtualScroll, after scrolling down to end and clicking again the text box it's loading empty popup after scroll its loading values.

html

```<code>   <mat-form-field>
      <input type="text" placeholder="Pick one" aria-label="Number" matInput [matAutocomplete]="auto">
      <mat-autocomplete #auto="matAutocomplete" (opened)="panelOpened()">
        <cdk-virtual-scroll-viewport itemSize="48" style="height: 240px" minBufferPx="96" maxBufferPx="144">
          <mat-option *cdkVirtualFor="let option of options" [value]="option">
            {{option}}
          </mat-option>
        </cdk-virtual-scroll-viewport>
        </mat-autocomplete>
    </mat-form-field>
</code>```

TS

```<code>export class AppComponent  {
  options: string[] = [];

  @ViewChild(CdkVirtualScrollViewport, {static: true}) viewport: CdkVirtualScrollViewport;

  constructor() {
    for (let i = 0; i < 10000; i++) {
      this.options.push("#"+i);
    }
  }

  panelOpened() {
    if (this.viewport) {
      this.viewport.checkViewportSize();
    }
  }
}
</code>```

Check the ex: https://stackblitz.com/edit/angular-7vcohv?file=src%2Fapp%2Fapp.component.html

答:
I'm not sure how many options the mat-autocomplete is targeted to support, but my suggestions to improve the performance are:

Fill the autocomplete only after the user typed at least 2 characters.

Implement a server-side search and fill the auto-complete options after you got smaller amount of options.

If you think this is an issue with the mat-autocomplete component, you can open an issue in the @angular/material repository.

Body:
I am using Angular/Material Autocomplete. While loading data to the Autocomplete getting serious performance issues,like the rendering takes around 30 seconds and it takes more than 10 seconds to become stable,data is loaded from the server, and the data received from the server is quite fast. To Over Come that issue i used cdkVirtualScroll, after scrolling down to end and clicking again the text box it's loading empty popup after scroll its loading values.

html

   <mat-form-field>
      <input type="text" placeholder="Pick one" aria-label="Number" matInput [matAutocomplete]="auto">
      <mat-autocomplete #auto="matAutocomplete" (opened)="panelOpened()">
        <cdk-virtual-scroll-viewport itemSize="48" style="height: 240px" minBufferPx="96" maxBufferPx="144">
          <mat-option *cdkVirtualFor="let option of options" [value]="option">
            {{option}}
          </mat-option>
        </cdk-virtual-scroll-viewport>
        </mat-autocomplete>
    </mat-form-field>

TS

export class AppComponent  {
  options: string[] = [];

  @ViewChild(CdkVirtualScrollViewport, {static: true}) viewport: CdkVirtualScrollViewport;

  constructor() {
    for (let i = 0; i < 10000; i++) {
      this.options.push("#"+i);
    }
  }

  panelOpened() {
    if (this.viewport) {
      this.viewport.checkViewportSize();
    }
  }
}

Check the ex: https://stackblitz.com/edit/angular-7vcohv?file=src%2Fapp%2Fapp.component.html


问:
Installation of Firefox from Alpine Edge
I appear to be missing something when attempting to install Firefox from the Alpine Edge Repository

Firefox (Version 61.0.1-r0) Repo

as distinct from installing

Firefox-ESR (Version 52.8.1-r0) Repo

I perform the necessary repository modification as documented here which causes my repository to look like:

```<code>http://dl-cdn.alpinelinux.org/alpine/edge/main
http://dl-cdn.alpinelinux.org/alpine/edge/community
</code>```

Following up with:

```<code>apk upgrade --update-cache --available
</code>```

Works fine and does all the necessary pulls.  However, when attempting:

```<code>apk add --no-cache firefox
</code>```

Returns

ERROR: unsatisfiable constraints:
    firefox (missing):
      required by: world[firefox]

Which is what I would expect from the non-edge repositories.  I'm sure I'm missing something simple and obvious.  Suggestions?

答:
Try with
RUN apk add \
firefox-esr</p>

Body:
I appear to be missing something when attempting to install Firefox from the Alpine Edge Repository

Firefox (Version 61.0.1-r0) Repo

as distinct from installing

Firefox-ESR (Version 52.8.1-r0) Repo

I perform the necessary repository modification as documented here which causes my repository to look like:

http://dl-cdn.alpinelinux.org/alpine/edge/main
http://dl-cdn.alpinelinux.org/alpine/edge/community

Following up with:

apk upgrade --update-cache --available

Works fine and does all the necessary pulls.  However, when attempting:

apk add --no-cache firefox

Returns

ERROR: unsatisfiable constraints:
    firefox (missing):
      required by: world[firefox]

Which is what I would expect from the non-edge repositories.  I'm sure I'm missing something simple and obvious.  Suggestions?

Body:
Try with
RUN apk add \
firefox-esr


问:
Border-bottom is not extended to full width under a tag(angular)
I want the border-bottom of my tags in a list extends to its full length. however, it only covers the tag only I believe it is because How I set up things. ( I am writing my code in Angular)

the html code :

```<code><fa (click)="backToHome()" class="arrow" name="chevron-left"></fa>
<h1>جستجو</h1>
<br /><br /><br /><br />
  <div class="search">
    <input class="input" [(ngModel)]="item" required placeholder="جستجو میان محصولات و برندها" />
    <fa class="icon" name="search" (click)="fetchProducts()"></fa>
  </div>
<p>تاریخچه جستجو</p>
<br />
<br />

  <ul *ngIf="resultSearch && resultSearch.length">
    <li *ngFor="let product of resultSearch">
        <a (click)="backToHome()">{{product.name}}</a>
    </li>
  </ul>
<p *ngIf="condition()">!نتیجه ای یافت نشد</p>

<router-outlet></router-outlet>
</code>```

and the Css code:

```<code>.search{
    position: relative;
    width: 330px;
    height: 40px;
    line-height: 40px;
    padding: 0px;
    margin: 5px;
    border-radius: 6px;

}
.input{
    background: #e7e5e5;
    width: 90%;
    height: 30px;
    font-size: 15px;
    border-radius: 6px;
    padding: 5px 15px;
    text-align: right;
    line-height: 30px;
    overflow: hidden;
    display: block;
    outline: none;
    border: none;
    box-sizing: border-box;
}
.history{

    color:grey;

}
.icon{
    position: absolute;
    left: 5px;
    top: -3px;
    color:grey;
    cursor: pointer;
}
.arrow{

    position: absolute;
    top:20px;
    left: 5%;
    color: gray;
    cursor: pointer;

}
h1{
    position: absolute;
    right:40px;
    float: right;
}
p{

    position: absolute;
    right:0;
    color: grey;
}
::placeholder{
    font-family: iransans;
    color: grey;
}
ul{
    border:1px solid red;
    list-style: none;
    float: right;
    display: block;

}
ul li a{

    cursor: pointer;
    border-bottom: 1px solid grey;
    border-width: thin;
    color: grey;
    text-decoration: none;
}
</code>```

http://8upload.ir/uploads/f39852.jpg (the way it is now)
http://8upload.ir/uploads/f66439623.jpg(the way it should be)

答:
Give that a a class="whatever". Then in the CSS do .whatever { display: block; }. That will make the link take the full width of the li parent.

```<code><ul *ngIf="resultSearch && resultSearch.length">
    <li *ngFor="let product of resultSearch">
        <a (click)="backToHome()" class="whatever">{{product.name}}</a>
    </li>
</ul>
<style>
  .whatever { display: block; }
</style>
</code>```

Or simply do (according to the CSS you currently have):

```<code>ul li a { display: block; }
</code>```

Body:
I want the border-bottom of my tags in a list extends to its full length. however, it only covers the tag only I believe it is because How I set up things. ( I am writing my code in Angular)

the html code :

<fa (click)="backToHome()" class="arrow" name="chevron-left"></fa>

جستجو

    <input class="input" [(ngModel)]="item" required placeholder="جستجو میان محصولات و برندها" />
    <fa class="icon" name="search" (click)="fetchProducts()"></fa>

تاریخچه جستجو

        {{product.name}}

!نتیجه ای یافت نشد

<router-outlet></router-outlet>

and the Css code:

.search{
    position: relative;
    width: 330px;
    height: 40px;
    line-height: 40px;
    padding: 0px;
    margin: 5px;
    border-radius: 6px;

}
.input{
    background: #e7e5e5;
    width: 90%;
    height: 30px;
    font-size: 15px;
    border-radius: 6px;
    padding: 5px 15px;
    text-align: right;
    line-height: 30px;
    overflow: hidden;
    display: block;
    outline: none;
    border: none;
    box-sizing: border-box;
}
.history{

    color:grey;

}
.icon{
    position: absolute;
    left: 5px;
    top: -3px;
    color:grey;
    cursor: pointer;
}
.arrow{

    position: absolute;
    top:20px;
    left: 5%;
    color: gray;
    cursor: pointer;

}
h1{
    position: absolute;
    right:40px;
    float: right;
}
p{

    position: absolute;
    right:0;
    color: grey;
}
::placeholder{
    font-family: iransans;
    color: grey;
}
ul{
    border:1px solid red;
    list-style: none;
    float: right;
    display: block;

}
ul li a{

    cursor: pointer;
    border-bottom: 1px solid grey;
    border-width: thin;
    color: grey;
    text-decoration: none;
}

http://8upload.ir/uploads/f39852.jpg (the way it is now)
http://8upload.ir/uploads/f66439623.jpg(the way it should be)

Body:
Give that a a class="whatever". Then in the CSS do .whatever { display: block; }. That will make the link take the full width of the li parent.

<ul *ngIf="resultSearch && resultSearch.length">
    <li *ngFor="let product of resultSearch">
        <a (click)="backToHome()" class="whatever">{{product.name}}</a>
    </li>
</ul>
<style>
  .whatever { display: block; }
</style>

Or simply do (according to the CSS you currently have):

ul li a { display: block; }


答:
```<code>import os
for file in os.listdir('your/directory'):
    print(file)
</code>```

Title: For loop to read file names


问:
Tensorflow: Input pipeline with sparse data for the SVM estimator

Introduction:

I am trying to train the tensorflow svm estimator tensorflow.contrib.learn.python.learn.estimators.svm with sparse data. Sample usage with sparse data at the github repo at tensorflow/contrib/learn/python/learn/estimators/svm_test.py#L167 (I am not allowed to post more links, so here the relative path).

The svm estimator expects as parameter example_id_column and feature_columns, where the feature columns should be derived of class FeatureColumn such as tf.contrib.layers.feature_column.sparse_column_with_hash_bucket. See Github repo at tensorflow/contrib/learn/python/learn/estimators/svm.py#L85 and the documentation at tensorflow.org at python/contrib.layers#Feature_columns.

Question:

How do I have to set up my input pipeline to format sparse data in such a way that I can use one of the tf.contrib.layers feature_columns as input for the svm estimator.

How would a dense input function with many features look like?

Background

The data that I use is the a1a dataset from the LIBSVM website. The data set has 123 features (that would correspond to 123 feature_columns if the data would be dense). I wrote an user op to read the data like tf.decode_csv() but for the LIBSVM format. The op returns the labels as dense tensor and the features as sparse tensor. My input pipeline:

NUM_FEATURES = 123
batch_size = 200

# my op to parse the libsvm data
decode_libsvm_module = tf.load_op_library('./libsvm.so')

def input_pipeline(filename_queue, batch_size):
    with tf.name_scope('input'):
        reader = tf.TextLineReader(name="TextLineReader_")
        _, libsvm_row = reader.read(filename_queue, name="libsvm_row_")
        min_after_dequeue = 1000
        capacity = min_after_dequeue + 3 * batch_size
        batch = tf.train.shuffle_batch([libsvm_row], batch_size=batch_size,
                                       capacity=capacity,
                                       min_after_dequeue=min_after_dequeue,
                                       name="text_line_batch_")
        labels, sp_indices, sp_values, sp_shape = \
            decode_libsvm_module.decode_libsvm(records=batch,
                                               num_features=123,
                                               OUT_TYPE=tf.int64,
                                               name="Libsvm_decoded_")
        # Return the features as sparse tensor and the labels as dense
        return tf.SparseTensor(sp_indices, sp_values, sp_shape), labels
```

<p>Here is an example batch with <code>batch_size = 5</code>.</p>

<pre class="lang-py prettyprint-override"><code>def input_fn(dataset_name):
    maybe_download()

    filename_queue_train = tf.train.string_input_producer([dataset_name],
                                                        name="queue_t_")
    features, labels = input_pipeline(filename_queue_train, batch_size)

    return {
        'example_id': tf.as_string(tf.range(1,123,1,dtype=tf.int64)),
        'features': features
    }, labels
</code>```

This is what I tried so far:

with tf.Session().as_default() as sess:
    sess.run(tf.global_variables_initializer())

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)

    feature_column = tf.contrib.layers.sparse_column_with_hash_bucket(
        'features', hash_bucket_size=1000, dtype=tf.int64)

    svm_classifier = svm.SVM(feature_columns=[feature_column],
                             example_id_column='example_id',
                             l1_regularization=0.0,
                             l2_regularization=1.0)
    svm_classifier.fit(input_fn=lambda: input_fn(TRAIN),
                       steps=30)

    accuracy = svm_classifier.evaluate(
        input_fn= lambda: input_fn(features, labels),
        steps=1)['accuracy']
    print(accuracy)
    coord.request_stop()

    coord.join(threads)
    sess.close()
```

答:
Since TensorFlow 1.5.0 there is an inbuilt function to read LIBSVM data,
refer to my answer here
https://stackoverflow.com/a/56354308/3885491</p>

Body:
Introduction:

I am trying to train the tensorflow svm estimator tensorflow.contrib.learn.python.learn.estimators.svm with sparse data. Sample usage with sparse data at the github repo at tensorflow/contrib/learn/python/learn/estimators/svm_test.py#L167 (I am not allowed to post more links, so here the relative path).

The svm estimator expects as parameter example_id_column and feature_columns, where the feature columns should be derived of class FeatureColumn such as tf.contrib.layers.feature_column.sparse_column_with_hash_bucket. See Github repo at tensorflow/contrib/learn/python/learn/estimators/svm.py#L85 and the documentation at tensorflow.org at python/contrib.layers#Feature_columns.

Question:

How do I have to set up my input pipeline to format sparse data in such a way that I can use one of the tf.contrib.layers feature_columns as input for the svm estimator.

How would a dense input function with many features look like?

Background

The data that I use is the a1a dataset from the LIBSVM website. The data set has 123 features (that would correspond to 123 feature_columns if the data would be dense). I wrote an user op to read the data like tf.decode_csv() but for the LIBSVM format. The op returns the labels as dense tensor and the features as sparse tensor. My input pipeline:

NUM_FEATURES = 123
batch_size = 200

# my op to parse the libsvm data
decode_libsvm_module = tf.load_op_library('./libsvm.so')

def input_pipeline(filename_queue, batch_size):
    with tf.name_scope('input'):
        reader = tf.TextLineReader(name="TextLineReader_")
        _, libsvm_row = reader.read(filename_queue, name="libsvm_row_")
        min_after_dequeue = 1000
        capacity = min_after_dequeue + 3 * batch_size
        batch = tf.train.shuffle_batch([libsvm_row], batch_size=batch_size,
                                       capacity=capacity,
                                       min_after_dequeue=min_after_dequeue,
                                       name="text_line_batch_")
        labels, sp_indices, sp_values, sp_shape = \
            decode_libsvm_module.decode_libsvm(records=batch,
                                               num_features=123,
                                               OUT_TYPE=tf.int64,
                                               name="Libsvm_decoded_")
        # Return the features as sparse tensor and the labels as dense
        return tf.SparseTensor(sp_indices, sp_values, sp_shape), labels

Here is an example batch with batch_size = 5.

def input_fn(dataset_name):
    maybe_download()

    filename_queue_train = tf.train.string_input_producer([dataset_name],
                                                        name="queue_t_")
    features, labels = input_pipeline(filename_queue_train, batch_size)

    return {
        'example_id': tf.as_string(tf.range(1,123,1,dtype=tf.int64)),
        'features': features
    }, labels

This is what I tried so far:

with tf.Session().as_default() as sess:
    sess.run(tf.global_variables_initializer())

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)

    feature_column = tf.contrib.layers.sparse_column_with_hash_bucket(
        'features', hash_bucket_size=1000, dtype=tf.int64)

    svm_classifier = svm.SVM(feature_columns=[feature_column],
                             example_id_column='example_id',
                             l1_regularization=0.0,
                             l2_regularization=1.0)
    svm_classifier.fit(input_fn=lambda: input_fn(TRAIN),
                       steps=30)

    accuracy = svm_classifier.evaluate(
        input_fn= lambda: input_fn(features, labels),
        steps=1)['accuracy']
    print(accuracy)
    coord.request_stop()

    coord.join(threads)
    sess.close()


问:
How should I write destructor in this code
Im learning linked list and using dynamic memory allocation but i dont understand how to write destructor because there are methods which are using new and out of scope for destructor method. By the way Node is basically a  class with 2 private members, one int and one pointer to itself(Node).</p>

```<code>List::List()
{
HeadNode = new Node();
HeadNode->SetNext(nullptr);
CurrentNode = nullptr;
LastCurrentNode = nullptr;
Size = 0;
}

void List::Add(int AddObject)
{
Node* NewNode = new Node();
NewNode->Set(AddObject);
if (CurrentNode != nullptr)
{
    NewNode->SetNext(CurrentNode->GetNext());
    CurrentNode->SetNext(NewNode);
    LastCurrentNode = CurrentNode;
    CurrentNode = NewNode;
}
else
{
    NewNode->SetNext(nullptr);
    HeadNode->SetNext(NewNode);
    LastCurrentNode = HeadNode;
    CurrentNode = NewNode;
}
Size++;
}

int List::Get()
{
if (CurrentNode != nullptr)
{
    return CurrentNode->Get();
}
}

bool List::Next()
{
if (CurrentNode == nullptr)
{
    return false;
}
LastCurrentNode = CurrentNode;
CurrentNode = CurrentNode->GetNext();
if ((CurrentNode == nullptr) || (Size = 0))
{
    return false;
}
else
{
    return true;
}
}

void List::Remove()
{
if (CurrentNode != nullptr && CurrentNode != HeadNode)
{
    LastCurrentNode->SetNext(CurrentNode->GetNext());
    delete CurrentNode;
    CurrentNode = LastCurrentNode->GetNext();
    Size--;
}
}
</code>```

答:
Destructor should delete all nodes, and you can use Remove() to do that.

```<code>List::~List() {
    while (Size > 0) {
        Remove(CurrentNode);
    }
    delete HeadNode;
}
</code>```

Also you have a bug in Next(), I think you mean Size == 0.

Body:
Im learning linked list and using dynamic memory allocation but i dont understand how to write destructor because there are methods which are using new and out of scope for destructor method. By the way Node is basically a  class with 2 private members, one int and one pointer to itself(Node).

List::List()
{
HeadNode = new Node();
HeadNode->SetNext(nullptr);
CurrentNode = nullptr;
LastCurrentNode = nullptr;
Size = 0;
}

void List::Add(int AddObject)
{
Node* NewNode = new Node();
NewNode->Set(AddObject);
if (CurrentNode != nullptr)
{
    NewNode->SetNext(CurrentNode->GetNext());
    CurrentNode->SetNext(NewNode);
    LastCurrentNode = CurrentNode;
    CurrentNode = NewNode;
}
else
{
    NewNode->SetNext(nullptr);
    HeadNode->SetNext(NewNode);
    LastCurrentNode = HeadNode;
    CurrentNode = NewNode;
}
Size++;
}

int List::Get()
{
if (CurrentNode != nullptr)
{
    return CurrentNode->Get();
}
}

bool List::Next()
{
if (CurrentNode == nullptr)
{
    return false;
}
LastCurrentNode = CurrentNode;
CurrentNode = CurrentNode->GetNext();
if ((CurrentNode == nullptr) || (Size = 0))
{
    return false;
}
else
{
    return true;
}
}

void List::Remove()
{
if (CurrentNode != nullptr && CurrentNode != HeadNode)
{
    LastCurrentNode->SetNext(CurrentNode->GetNext());
    delete CurrentNode;
    CurrentNode = LastCurrentNode->GetNext();
    Size--;
}
}

Body:
Destructor should delete all nodes, and you can use Remove() to do that.

List::~List() {
    while (Size > 0) {
        Remove(CurrentNode);
    }
    delete HeadNode;
}

Also you have a bug in Next(), I think you mean Size == 0.


问:
How to insert a date into a google spreadsheet?
In a google spreadsheet I define some vertical cells with Format 'Date' as '29.5.2019' (i.e. day.month.year). In the cell below I define a formula

```<code>=A3+7
</code>```

to get the date one week later. But no matter what I enter in "A2", I get an error like:

```<code>Function ADD parameter 1 expects number values. But '29.5.2019' is a text and cannot be coerced to a number.
</code>```

So although I think that the format in A2 is a date, the spreadsheet thinks its a text. So how to fix that?

答: Date should be in the format dd/mm/yyyy.</p>

Body:
In a google spreadsheet I define some vertical cells with Format 'Date' as '29.5.2019' (i.e. day.month.year). In the cell below I define a formula

=A3+7

to get the date one week later. But no matter what I enter in "A2", I get an error like:

Function ADD parameter 1 expects number values. But '29.5.2019' is a text and cannot be coerced to a number.

So although I think that the format in A2 is a date, the spreadsheet thinks its a text. So how to fix that?


答:
Somewhere in your code you must already have specified the table to select from. You can use the same logic to see which table you initially used?

For example:

```<code>$sTable = 'table2';
$rResult = mysql_query(sprintf($sQuery, $sTable));
if ($sTable == 'table2') { // use $rResult }
</code>```

Title: PHP/MySQL If FROM Statements

Body:
Somewhere in your code you must already have specified the table to select from. You can use the same logic to see which table you initially used?

For example:

$sTable = 'table2';
$rResult = mysql_query(sprintf($sQuery, $sTable));
if ($sTable == 'table2') { // use $rResult }


问:
npm ERR! code E407 Proxy Authentication Required
While I am trying to run npm command, I am getting an error.

The error log is reproduced below:

```<code>0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'install',
1 verbose cli   'graph' ]
2 info using npm@6.4.1
3 info using node@v10.15.3
4 verbose npm-session 7743923ae4798761
5 silly install loadCurrentTree
6 silly install readLocalPackageData
7 http fetch GET 407 https://registry.npmjs.org/graph 7681ms
8 silly fetchPackageMetaData error for graph@latest 407 Proxy Authentication Required: graph@latest
9 timing stage:rollbackFailedOptional Completed in 9ms
10 timing stage:runTopLevelLifecycles Completed in 8056ms
11 verbose stack Error: 407 Proxy Authentication Required: graph@latest
11 verbose stack     at fetch.then.res (C:\Program Files\nodejs\node_modules\npm\node_modules\pacote\lib\fetchers\registry\fetch.js:42:19)
11 verbose stack     at tryCatcher (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\util.js:16:23)
11 verbose stack     at Promise._settlePromiseFromHandler (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:512:31)
11 verbose stack     at Promise._settlePromise (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:569:18)
11 verbose stack     at Promise._settlePromise0 (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:614:10)
11 verbose stack     at Promise._settlePromises (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:693:18)
11 verbose stack     at Async._drainQueue (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:133:16)
11 verbose stack     at Async._drainQueues (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:143:10)
11 verbose stack     at Immediate.Async.drainQueues [as _onImmediate] (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:17:14)
11 verbose stack     at runCallback (timers.js:705:18)
11 verbose stack     at tryOnImmediate (timers.js:676:5)
11 verbose stack     at processImmediate (timers.js:658:5)
12 verbose cwd C:\Windows\system32
13 verbose Windows_NT 6.1.7601
14 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "graph"
15 verbose node v10.15.3
16 verbose npm  v6.4.1
17 error code E407
18 error 407 Proxy Authentication Required: graph@latest
19 verbose exit [ 1, true ]
</code>```

答:
This error is most likely because you are behind a proxy, or may be you are in your organisation which uses proxy.
To find the PROXY name and the PORT you need to do the following steps:

1.go to run

2.type "inetcpl.cpl"

3.Go to Connection tab

4. Go to LAN Setting
There you will find address and the port

After you get the "address" and the "port" replace it with "proxy_name" and "port" in the below command and replace "username" with "your username" and "password" with "your password" and run

npm config set proxy http://username:password@proxy_name:port

npm config set http-proxy http://username:password@proxy_name:port

Afterwards run npm.

This should work possibly

Edit:
Before running npm config the URL should be encoded and this can be done by just copy pasting the URL to this website https://www.urlencoder.io/

Body:
While I am trying to run npm command, I am getting an error.

The error log is reproduced below:

0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'install',
1 verbose cli   'graph' ]
2 info using npm@6.4.1
3 info using node@v10.15.3
4 verbose npm-session 7743923ae4798761
5 silly install loadCurrentTree
6 silly install readLocalPackageData
7 http fetch GET 407 https://registry.npmjs.org/graph 7681ms
8 silly fetchPackageMetaData error for graph@latest 407 Proxy Authentication Required: graph@latest
9 timing stage:rollbackFailedOptional Completed in 9ms
10 timing stage:runTopLevelLifecycles Completed in 8056ms
11 verbose stack Error: 407 Proxy Authentication Required: graph@latest
11 verbose stack     at fetch.then.res (C:\Program Files\nodejs\node_modules\npm\node_modules\pacote\lib\fetchers\registry\fetch.js:42:19)
11 verbose stack     at tryCatcher (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\util.js:16:23)
11 verbose stack     at Promise._settlePromiseFromHandler (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:512:31)
11 verbose stack     at Promise._settlePromise (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:569:18)
11 verbose stack     at Promise._settlePromise0 (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:614:10)
11 verbose stack     at Promise._settlePromises (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:693:18)
11 verbose stack     at Async._drainQueue (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:133:16)
11 verbose stack     at Async._drainQueues (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:143:10)
11 verbose stack     at Immediate.Async.drainQueues [as _onImmediate] (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:17:14)
11 verbose stack     at runCallback (timers.js:705:18)
11 verbose stack     at tryOnImmediate (timers.js:676:5)
11 verbose stack     at processImmediate (timers.js:658:5)
12 verbose cwd C:\Windows\system32
13 verbose Windows_NT 6.1.7601
14 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "graph"
15 verbose node v10.15.3
16 verbose npm  v6.4.1
17 error code E407
18 error 407 Proxy Authentication Required: graph@latest
19 verbose exit [ 1, true ]


问:
JSF 2.0 + Primefaces richtext editor
```<code><p:editor value="#{editorBean.value}"  widgetVar="editor" width="686"
height="390" language="en" align="center">
</p:editor>
</code>```

Following is my rich-text editor bean picked up from primefaces

```<code>@ManagedBean(name = "editorBean")
@SessionScoped
public class EditorBean {
    private static final String MANAGED_BEAN_NAME = "editorBean";
    private String value;
    public static EditorBean getCurrentInstance() {
        return (EditorBean) FacesContext.getCurrentInstance()
            .getExternalContext().getRequestMap().get(MANAGED_BEAN_NAME);
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}
</code>```

Apart from this I have another bean say A. I have a method inside A that populates a HTML table. What I want is when the user opens the editor, it should be pre-populated with that HTML table data and of course the changes should get reflected into (String: value). Therefore, you can say that I am trying to tie up both the values together. I think it needs to be done with DI but somehow its not working. If someone can guide or quote an example, it would be really helpful.

答:
One way to do it is rewrite your getValue() method to pick up the value from bean A.
And yes, the reference to your A bean should come from DI:

```<code>//injecting a reference to A
@ManagedPropery(value="#{A}") //or whatever is the name of your bean
private A beanA;

public void setBeanA(A beanA) {
    this.beanA = beanA;
}
</code>```

Or, with CDI, just:

```<code>@Inject private A beanA
</code>```

Finally, your getValue method

```<code>public String getValue() {
    return beanA.getValue()
}
</code>```

Title: JSF 2.0 + Primefaces richtext editor

Body:
Following is my rich-text editor bean picked up from primefaces

@ManagedBean(name = "editorBean")
@SessionScoped
public class EditorBean {
    private static final String MANAGED_BEAN_NAME = "editorBean";
    private String value;
    public static EditorBean getCurrentInstance() {
        return (EditorBean) FacesContext.getCurrentInstance()
            .getExternalContext().getRequestMap().get(MANAGED_BEAN_NAME);
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}

Apart from this I have another bean say A. I have a method inside A that populates a HTML table. What I want is when the user opens the editor, it should be pre-populated with that HTML table data and of course the changes should get reflected into (String: value). Therefore, you can say that I am trying to tie up both the values together. I think it needs to be done with DI but somehow its not working. If someone can guide or quote an example, it would be really helpful.

Body:
One way to do it is rewrite your getValue() method to pick up the value from bean A.
And yes, the reference to your A bean should come from DI:

//injecting a reference to A
@ManagedPropery(value="#{A}") //or whatever is the name of your bean
private A beanA;

public void setBeanA(A beanA) {
    this.beanA = beanA;
}

Or, with CDI, just:

@Inject private A beanA

Finally, your getValue method

public String getValue() {
    return beanA.getValue()
}


问:
How to get particular page selected by default?
I have a pagination as shown in here https://jsfiddle.net/solodev/yw7y4wez/

I want to get some page selected or highlighted by default (suppose page 8)

I tried following code but it doesn't work

```<code>page = '@Model.CurrentPageIndex';
$('.page-active').removeClass('page-active');
$('#page' + page).addClass('page-active');
</code>```

where '@Model.CurrentPageIndex' contains page no. (e.g. 8)

答:
Pagination allows you to set the startpage. You have it in your jsfiddle example. </p>

```<code>$('#pagination-demo').twbsPagination({
totalPages: 5,
// the current page that show on start
startPage: 2, //THIS IS THE LINE THAT CHANGES START PAGE

// maximum visible pages
visiblePages: 5,

initiateStartPageClick: true,

// template for pagination links
href: false,

// variable name in href template for page number
hrefVariable: '{{number}}',

// Text labels
first: 'First',
prev: 'Previous',
next: 'Next',
last: 'Last',

// carousel-style pagination
loop: false,

// callback function
onPageClick: function (event, page) {
    $('.page-active').removeClass('page-active');
  $('#page'+page).addClass('page-active');
},

// pagination Classes
paginationClass: 'pagination',
nextClass: 'next',
prevClass: 'prev',
lastClass: 'last',
firstClass: 'first',
pageClass: 'page',
activeClass: 'active',
disabledClass: 'disabled',

});
</code>```

<p>When you are using this plugin, it is probably be best to use its functions rather than add your own functionality on top. This way, it ensures that other functions such as "previous", and "last" still works. </p>

Body:
I have a pagination as shown in here https://jsfiddle.net/solodev/yw7y4wez/

I want to get some page selected or highlighted by default (suppose page 8)

I tried following code but it doesn't work

page = '@Model.CurrentPageIndex';
$('.page-active').removeClass('page-active');
$('#page' + page).addClass('page-active');

where '@Model.CurrentPageIndex' contains page no. (e.g. 8)

Body:
Pagination allows you to set the startpage. You have it in your jsfiddle example.

$('#pagination-demo').twbsPagination({
totalPages: 5,
// the current page that show on start
startPage: 2, //THIS IS THE LINE THAT CHANGES START PAGE

// maximum visible pages
visiblePages: 5,

initiateStartPageClick: true,

// template for pagination links
href: false,

// variable name in href template for page number
hrefVariable: '{{number}}',

// Text labels
first: 'First',
prev: 'Previous',
next: 'Next',
last: 'Last',

// carousel-style pagination
loop: false,

// callback function
onPageClick: function (event, page) {
    $('.page-active').removeClass('page-active');
  $('#page'+page).addClass('page-active');
},

// pagination Classes
paginationClass: 'pagination',
nextClass: 'next',
prevClass: 'prev',
lastClass: 'last',
firstClass: 'first',
pageClass: 'page',
activeClass: 'active',
disabledClass: 'disabled',

});

When you are using this plugin, it is probably be best to use its functions rather than add your own functionality on top. This way, it ensures that other functions such as "previous", and "last" still works.


问:
How to configure environment variables in Azure DevOps pipeline?
I have an Azure Function (.NET Core) that is configured to read application settings from both a JSON file and environment variables:

```<code>var configurationBuilder = new ConfigurationBuilder()
                                .SetBasePath(_baseConfigurationPath)
                                .AddJsonFile("appsettings.json", optional: true)
                                .AddEnvironmentVariables()
                                .Build();

BuildAgentMonitorConfiguration configuration = configurationBuilder.Get<BuildAgentMonitorConfiguration>();
</code>```

appsettings.json has the following structure:

```<code>{
  "ProjectBaseUrl": "https://my-project.visualstudio.com/",
  "ProjectName": "my-project",
  "AzureDevOpsPac": ".....",
  "SubscriptionId": "...",
  "AgentPool": {
    "PoolId": 38,
    "PoolName": "MyPool",
    "MinimumAgentCount": 2,
    "MaximumAgentCount": 10
  },
  "ContainerRegistry": {
    "Username": "mycontainer",
    "LoginServer": "mycontainer.azurecr.io",
    "Password": "..."
  },
  "ActiveDirectory": {
    "ClientId": "...",
    "TenantId": "...",
    "ClientSecret": "..."
  }
}
</code>```

Some of these settings are configured as environment variables in the Azure Function. Everything works as expected:

The problem now is to configure some of these variables in a build pipeline, which are used in unit and integration tests. I've tried adding a variable group as follows and linking it to the pipeline:

But the environment variables are not being set and the tests are failing. What am I missing here?

答:
I also have the same use case in which I want some environment variable to be set up using the azure build pipeline so that the test cases can access that environment variable to get the test passed.
Directly setting the env variable using the EXPORT,ENV command does not work for the subsequent task so to have the environment variable set up for subsequent task follow the syntax as mentioned on https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch
ie the
task.set variable with the script tag

Correct way of setting ENV variable using build pipeline

```<code>- script: |
    echo '##vso[task.setvariable variable=LD_LIBRARY_PATH]$(Build.SourcesDirectory)/src/Projectname/bin/Release/netcoreapp2.0/x64'
  displayName: set environment variable for subsequent steps
</code>```

Please be careful of the spaces as its is yaml. The above script tags set up the variable LD_LIBRARY_PATH (used in Linux to define path for .so files) to the directory defined.

This style of setting the environment variable works for subsequent task also , but if we set the env variable like mentioned below the enviroment variable will be set for the specefic shell instance and will not be applicable for subsequent tasks

Wrong way of setting env variable :

```<code>- script: export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$(Build.SourcesDirectory)/src/CorrectionLoop.HttpApi/bin/Release/netcoreapp2.0/x64
  displayName: Set environment variable
</code>```

You can use the similar syntax for the setting up your environment variable.

Body:
I have an Azure Function (.NET Core) that is configured to read application settings from both a JSON file and environment variables:

var configurationBuilder = new ConfigurationBuilder()
                                .SetBasePath(_baseConfigurationPath)
                                .AddJsonFile("appsettings.json", optional: true)
                                .AddEnvironmentVariables()
                                .Build();

BuildAgentMonitorConfiguration configuration = configurationBuilder.Get<BuildAgentMonitorConfiguration>();

appsettings.json has the following structure:

{
  "ProjectBaseUrl": "https://my-project.visualstudio.com/",
  "ProjectName": "my-project",
  "AzureDevOpsPac": ".....",
  "SubscriptionId": "...",
  "AgentPool": {
    "PoolId": 38,
    "PoolName": "MyPool",
    "MinimumAgentCount": 2,
    "MaximumAgentCount": 10
  },
  "ContainerRegistry": {
    "Username": "mycontainer",
    "LoginServer": "mycontainer.azurecr.io",
    "Password": "..."
  },
  "ActiveDirectory": {
    "ClientId": "...",
    "TenantId": "...",
    "ClientSecret": "..."
  }
}

Some of these settings are configured as environment variables in the Azure Function. Everything works as expected:

The problem now is to configure some of these variables in a build pipeline, which are used in unit and integration tests. I've tried adding a variable group as follows and linking it to the pipeline:

But the environment variables are not being set and the tests are failing. What am I missing here?

Body:
I also have the same use case in which I want some environment variable to be set up using the azure build pipeline so that the test cases can access that environment variable to get the test passed.
Directly setting the env variable using the EXPORT,ENV command does not work for the subsequent task so to have the environment variable set up for subsequent task follow the syntax as mentioned on https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch
ie the
task.set variable with the script tag

Correct way of setting ENV variable using build pipeline

- script: |
    echo '##vso[task.setvariable variable=LD_LIBRARY_PATH]$(Build.SourcesDirectory)/src/Projectname/bin/Release/netcoreapp2.0/x64'
  displayName: set environment variable for subsequent steps

Please be careful of the spaces as its is yaml. The above script tags set up the variable LD_LIBRARY_PATH (used in Linux to define path for .so files) to the directory defined.

This style of setting the environment variable works for subsequent task also , but if we set the env variable like mentioned below the enviroment variable will be set for the specefic shell instance and will not be applicable for subsequent tasks

Wrong way of setting env variable :

- script: export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$(Build.SourcesDirectory)/src/CorrectionLoop.HttpApi/bin/Release/netcoreapp2.0/x64
  displayName: Set environment variable

You can use the similar syntax for the setting up your environment variable.


问:
It appears that my ajax works but nothing is being posted
I am trying to post the value of my selector to a php file but it isnt working. My success function works and when i go to "your_php_script.php" the page works and the php runs as expected. Why wont the php page show up on the page with the ajax? I edited my post to add the database connection function from database_connection.php</p>

```<code>// html & jquery
 <select name="rooftop" id="rooftop" class="selectMenu">
            <option value="">Select an option</option>
            <option value="Yes">Yes</option>
            <option value="No">No</option>
        </select>

    <button id="barButton">click</button>

    <div id="showBars">

    </div>

    <script type="text/javascript">

        $(document).ready(function(){

                          $("#barButton").click(function() {
                            var selected = $("#rooftop").val();
                            $.ajax({
                                   type: "POST",
                                   url: "your_php_script.php",
                                   data: {selected: selected},
                                   success: function(){
                                   alert("works");
                                   }

                            });
                          });

// code on your_php_script.php
<?php

require_once("database_connection.php");
$db = db_connect();

 echo "<script type='text/javascript'> alert('works1'); </script>";
    $selected = $_POST["selected"];
    if(isset($selected)){
        echo "<script type='text/javascript'> alert('works2'); </script>";
        $sql = "SELECT bar_name, area, hourStart, hourEnd FROM barInfo WHERE rooftop = 1";
        $result = mysqli_query($connection, $sql);
        if (mysqli_num_rows($result) > 0) {
            echo "<table id='list'><tr><th><h3>Name</h3></th><th><h3> Area</h3></th><th><h3>Happy Hour Times</h3></th></tr>";
            while($row = mysqli_fetch_assoc($result)) {
                echo "<tr> <th> <h6> " . $row["bar_name"] . "</h6> </th> <th> <h6>" . $row["area"] . "</h6> </th> <th> <h6>" . $row["hourStart"] . "-" . $row["hourEnd"] . "</h6> </th> </tr>";
            }
            echo "</table";
        }

    }
db_disconnect($db);

?>

// database connection
function db_connect() {
        global $connection, $servername, $username, $password, $database;
        $connection = new mysqli($servername, $username, $password, $database) or die("Unable to Connect");
        return $connection;
    }
</code>```

答:
First you since you are using echo in your php response you must define that there will be a response in your Ajax request.

So your Ajax will be replaced by something like this

```<code>$.ajax({
    type: "POST",
    dataType: "text"
    url: "your_php_script.php",
    data: {
        selected: selected
    },
    success: function() {
        alert("works");
    }
});
</code>```

Body:
I am trying to post the value of my selector to a php file but it isnt working. My success function works and when i go to "your_php_script.php" the page works and the php runs as expected. Why wont the php page show up on the page with the ajax? I edited my post to add the database connection function from database_connection.php

// html & jquery
 <select name="rooftop" id="rooftop" class="selectMenu">
            <option value="">Select an option</option>
            <option value="Yes">Yes</option>
            <option value="No">No</option>
        </select>

    <button id="barButton">click</button>

    ";
    $selected = $_POST["selected"];
    if(isset($selected)){
        echo "";
        $sql = "SELECT bar_name, area, hourStart, hourEnd FROM barInfo WHERE rooftop = 1";
        $result = mysqli_query($connection, $sql);
        if (mysqli_num_rows($result) > 0) {
            echo "

Name

 Area

Happy Hour Times

";
            while($row = mysqli_fetch_assoc($result)) {
                echo "

 " . $row["bar_name"] . "

" . $row["area"] . "

" . $row["hourStart"] . "-" . $row["hourEnd"] . "

";
            }
            echo "

// database connection
function db_connect() {
        global $connection, $servername, $username, $password, $database;
        $connection = new mysqli($servername, $username, $password, $database) or die("Unable to Connect");
        return $connection;
    }

Body:
First you since you are using echo in your php response you must define that there will be a response in your Ajax request.

So your Ajax will be replaced by something like this

$.ajax({
    type: "POST",
    dataType: "text"
    url: "your_php_script.php",
    data: {
        selected: selected
    },
    success: function() {
        alert("works");
    }
});


问:
PHP convert MCRYPT_ENCRYPT to OPENSSL_ENCRYPT (SOAP header)
I need to encrypt some SOAP header fields, and I currently have the following code working in a project with PHP 5.6 version.

```<code>function getBaseEncoded($data, $key)
{
    $size       = $this->pkcs5_pad($data, mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB));
    $iv         = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND);
    $result     = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $size, MCRYPT_MODE_ECB, $iv);

    return trim(base64_encode($result));
}

private function pkcs5_pad($text, $blocksize)
{
   $pad = $blocksize - (strlen($text) % $blocksize);
   return $text . str_repeat (chr($pad), $pad);
}
</code>```

What happens is that now I have in my hands a similiar project but with PHP 7, and the function MCRYPT is deprecated and I need to switch it to OPENSSL_ENCRYPT.

The code below is my first attempt:

```<code>function getBaseEncoded($data, $key)
{
    $result = openssl_encrypt($data, 'AES-128-ECB', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING);

    return trim(base64_encode($result));
}
</code>```

But I'm now receiving a SOAP error with the message

SoapFault => Could not connect to host

and it got me thinking if the problem is on my new function?

答:
```<code>echo encrypt_openssl($data, $key);

function encrypt_openssl($msg, $key, $iv = null) {
        $iv_size = openssl_cipher_iv_length('AES-128-ECB');
        if (!$iv) {
            $iv = openssl_random_pseudo_bytes($iv_size);
        }
        $encryptedMessage = openssl_encrypt($msg, 'AES-128-ECB', $key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($iv . $encryptedMessage);
    }
</code>```

Body:
I need to encrypt some SOAP header fields, and I currently have the following code working in a project with PHP 5.6 version.

function getBaseEncoded($data, $key)
{
    $size       = $this->pkcs5_pad($data, mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB));
    $iv         = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND);
    $result     = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $size, MCRYPT_MODE_ECB, $iv);

    return trim(base64_encode($result));
}

private function pkcs5_pad($text, $blocksize)
{
   $pad = $blocksize - (strlen($text) % $blocksize);
   return $text . str_repeat (chr($pad), $pad);
}

What happens is that now I have in my hands a similiar project but with PHP 7, and the function MCRYPT is deprecated and I need to switch it to OPENSSL_ENCRYPT.

The code below is my first attempt:

function getBaseEncoded($data, $key)
{
    $result = openssl_encrypt($data, 'AES-128-ECB', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING);

    return trim(base64_encode($result));
}

But I'm now receiving a SOAP error with the message

SoapFault => Could not connect to host

and it got me thinking if the problem is on my new function?