问:
How to write a proper for loop for API calls?
I am trying to write a for loop that provides the author's short ID to a database called RePEc and gets the affiliation data. So far, this is what I have (NB: USERCODE only works on my IP):

```<code>url <- "https://api.repec.org/call.cgi?code=USERCODE&getauthorrecordraw="
for(i in 1:length(df_affiliations)){
Sys.sleep(1)
affiliation_fun <- paste(url,df_affiliations$author_reg_1[i])
affiliation_run <- fromJSON(txt=affiliation_fun) %>% select("affiliation") %>% unlist(use.names=FALSE)
affiliation_1 <- paste(unlist(affiliation_run), collapse =" ")
df_affiliations$vector <- rbind(affiliation_1)
}
</code>```

Every time I try this, I either get only the last value or a HTTP Error 400. For loops are not my strong suit. Can anyone figure out where I've gone wrong? Thanks in advance for your help!

答:
Your loop is over writing your output variable on each iteration.  A solution here is to initialize an empty vector outside of the loop and then assign the value to each index:

```<code>url <- "https://api.repec.org/call.cgi?code=USERCODE&getauthorrecordraw="

#define empty vector
affiliation_1<-vector(length=length(df_affiliations))
for(i in 1:length(df_affiliations)){
  Sys.sleep(1)
  affiliation_fun <- paste0(url,df_affiliations$author_reg_1[i])
  affiliation_run <- fromJSON(affiliation_fun) %>% select(affiliation) %>% unlist(use.names=FALSE)
  affiliation_1[i] <- paste(unlist(affiliation_run), collapse =" ")
}
</code>```

This is untested since the question is not reproducible, but should provide a starting point for your final solution.

Body:
I am trying to write a for loop that provides the author's short ID to a database called RePEc and gets the affiliation data. So far, this is what I have (NB: USERCODE only works on my IP):

url <- "https://api.repec.org/call.cgi?code=USERCODE&getauthorrecordraw="
for(i in 1:length(df_affiliations)){
Sys.sleep(1)
affiliation_fun <- paste(url,df_affiliations$author_reg_1[i])
affiliation_run <- fromJSON(txt=affiliation_fun) %>% select("affiliation") %>% unlist(use.names=FALSE)
affiliation_1 <- paste(unlist(affiliation_run), collapse =" ")
df_affiliations$vector <- rbind(affiliation_1)
}

Every time I try this, I either get only the last value or a HTTP Error 400. For loops are not my strong suit. Can anyone figure out where I've gone wrong? Thanks in advance for your help!

Body:
Your loop is over writing your output variable on each iteration.  A solution here is to initialize an empty vector outside of the loop and then assign the value to each index:

url <- "https://api.repec.org/call.cgi?code=USERCODE&getauthorrecordraw="

#define empty vector
affiliation_1<-vector(length=length(df_affiliations))
for(i in 1:length(df_affiliations)){
  Sys.sleep(1)
  affiliation_fun <- paste0(url,df_affiliations$author_reg_1[i])
  affiliation_run <- fromJSON(affiliation_fun) %>% select(affiliation) %>% unlist(use.names=FALSE)
  affiliation_1[i] <- paste(unlist(affiliation_run), collapse =" ")
}

This is untested since the question is not reproducible, but should provide a starting point for your final solution.


来源: stackexchange

问:
jsGrid: How to pass additional variables from javascript to php using ajax
I'm using jsGrid for my project. View here for original source code

I want to pass an additional variable call $user_session to use for mysql select query in fetch.php but failed. Below is what i have been trying.

```<code><script>

var user_session = "<?php echo $user_session; ?>"; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

//......

 controller: {
  loadData: function(){
   return $.ajax({
    type: "GET",
    url: "fetch_data.php",
    data: {user_session:user_session} //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   });
  },

 //......
</code>```

Here's the fetch.php file

```<code><?php

if($method == 'GET')
{
 $user_session = $_GET['user_session']; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

 $query = "SELECT * FROM sample_data WHERE first_name=? ORDER BY id DESC";
 $statement = $connect->prepare($query);
 $statement->execute($user_session); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output[] = array(
   'id'    => $row['id'],
   'first_name'  => $row['first_name'],
   'last_name'   => $row['last_name'],
   'age'    => $row['age'],
   'gender'   => $row['gender']
  );
 }
 header("Content-Type: application/json");
 echo json_encode($output);
}
//......
?>
</code>```

What is the proper way to do this?

答:
I'm able to do by this way.

```<code><script>

//......

 controller: {
  loadData: function(filter){
    var user_session = "<?php echo $user_session; ?>"; //<<<<<<<<<<<<<<<<<<<<<<<<<<<
   return $.ajax({
    type: "GET",
    url: "fetch_data.php",
    data: {filter,
           user_session:user_session //<<<<<<<<<<<<<<<<<<<<<<<<<<<
          },
   });
  },

 //......
</script>
</code>```

In fetch.php i do this.

```<code><?php

if($method == 'GET')
{
 $user_session = $_GET['user_session'];//<<<<<<<<<<<<<<<<<<<<<<<<<<<

 $query = "SELECT * FROM sample_data WHERE first_name=? ORDER BY id DESC";
 $statement = $connect->prepare($query);
 $statement->execute([$user_session]); //<<<<<<<<<<<<<<<<<<<<<<<<<<<
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output[] = array(
   'id'    => $row['id'],
   'first_name'  => $row['first_name'],
   'last_name'   => $row['last_name'],
   'age'    => $row['age'],
   'gender'   => $row['gender']
  );
 }
 header("Content-Type: application/json");
 echo json_encode($output);
}
//......
?>
</code>```

For the security issue mentioned by @Andrea Golin, i will post another question.
Thanks.

ContentLicense: CC BY-SA 4.0

Body:
I'm able to do by this way.

<script>

//......

 controller: {
  loadData: function(filter){
    var user_session = "<?php echo $user_session; ?>"; //<<<<<<<<<<<<<<<<<<<<<<<<<<<
   return $.ajax({
    type: "GET",
    url: "fetch_data.php",
    data: {filter,
           user_session:user_session //<<<<<<<<<<<<<<<<<<<<<<<<<<<
          },
   });
  },

 //......
</script>

In fetch.php i do this.

<?php

if($method == 'GET')
{
 $user_session = $_GET['user_session'];//<<<<<<<<<<<<<<<<<<<<<<<<<<<

 $query = "SELECT * FROM sample_data WHERE first_name=? ORDER BY id DESC";
 $statement = $connect->prepare($query);
 $statement->execute([$user_session]); //<<<<<<<<<<<<<<<<<<<<<<<<<<<
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output[] = array(
   'id'    => $row['id'],
   'first_name'  => $row['first_name'],
   'last_name'   => $row['last_name'],
   'age'    => $row['age'],
   'gender'   => $row['gender']
  );
 }
 header("Content-Type: application/json");
 echo json_encode($output);
}
//......
?>

For the security issue mentioned by @Andrea Golin, i will post another question.
Thanks.


问:
Sampling from a normal distribution using a for loop
So I am trying to sample from a uniform distribution 1000 times each time computing the mean of 20 random samples from said uniform distribution.

```<code>Now let's loop through 1000 times, sampling 20 values from a uniform distribution and computing the mean of the sample, saving this mean to a variable called sampMean within a tibble called uniformSampleMeans.
{r 2c}

unif_sample_size = 20 # sample size
n_samples = 1000 # number of samples

# set up q data frame to contain the results
uniformSampleMeans <- tibble(sampMean = runif(n_samples, unif_sample_size))

# loop through all samples.  for each one, take a new random sample,
# compute the mean, and store it in the data frame

for (i in 1:n_samples){
  uniformSampleMeans$sampMean[i] = summarize(uniformSampleMeans = mean(unif_sample_size))
}
</code>```

I successfully generate a tibble, however the values are "NaN". Additionally when I get to my for loop I get an error.

```<code>Error in summarise_(.data, .dots = compat_as_lazy_dots(...)) : argument ".data" is missing, with no default
</code>```

Any insight would be much appreciated!

答:
You don't need dplyr for this.</p>

```<code>rep<-1000
size<-20

# initialize the dataframe
res<-data.frame(rep=NA,mean=NA)

for ( i in 1:rep) {
        samp<-rnorm(size) # here you actually create your sample of 20 numbers from the normal distribution
        res[i,]$rep<-i #save in the first column the number of the replicate sampling (optional)
        res[i,]$mean<-mean(samp) # here you calculate the mean of the random sample and store it into the datafra
}
res
</code>```

Body:
So I am trying to sample from a uniform distribution 1000 times each time computing the mean of 20 random samples from said uniform distribution.

Now let's loop through 1000 times, sampling 20 values from a uniform distribution and computing the mean of the sample, saving this mean to a variable called sampMean within a tibble called uniformSampleMeans.
{r 2c}

unif_sample_size = 20 # sample size
n_samples = 1000 # number of samples

# set up q data frame to contain the results
uniformSampleMeans <- tibble(sampMean = runif(n_samples, unif_sample_size))

# loop through all samples.  for each one, take a new random sample,
# compute the mean, and store it in the data frame

for (i in 1:n_samples){
  uniformSampleMeans$sampMean[i] = summarize(uniformSampleMeans = mean(unif_sample_size))
}

I successfully generate a tibble, however the values are "NaN". Additionally when I get to my for loop I get an error.

Error in summarise_(.data, .dots = compat_as_lazy_dots(...)) : argument ".data" is missing, with no default

Any insight would be much appreciated!

Body:
You don't need dplyr for this.

rep<-1000
size<-20

# initialize the dataframe
res<-data.frame(rep=NA,mean=NA)

for ( i in 1:rep) {
        samp<-rnorm(size) # here you actually create your sample of 20 numbers from the normal distribution
        res[i,]$rep<-i #save in the first column the number of the replicate sampling (optional)
        res[i,]$mean<-mean(samp) # here you calculate the mean of the random sample and store it into the datafra
}
res


问:
c++ fold expression with user defined class
I'd like make a log function with multiple parameters, and I also want to call the log function with my class.

Here is my code (compiler : Visual studio 2019 or x86-64 gcc9.2)

Question 1> I cannot understand log function.
Is it possible to use fold expression like this ?
(this function comes from spdlog library)

Question 2>
How could I use the log function with Mystruct class ?

log(1, MyStruct(1, 1.1f, "hello world"s)); // compiler error

```<code>#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>

template<typename ... Args>
void log(int level, Args const& ... args)
{
    std::ostringstream stream;
    using List = int[];
    (void)List {
        0, ((void)(stream << args), 0) ...
    };
    std::cout << stream.str() << std::endl;
}

class MyStruct
{
public:
    int val1 = 0;
    float val2 = 0.f;
    std::string val3;

    MyStruct(int v1, float v2, std::string_view const& v3) : val1(v1), val2(v2), val3(v3) {};
    std::string to_string() const
    {
        std::stringstream stream;
        stream << "val1=" << val1 << ", val2=" << val2 << ",val3=" << val3;
        return stream.str();
    }
};

std::ostringstream& operator<< (std::ostringstream& stream, MyStruct&& val)
{
    auto str = val.to_string();
    std::operator <<(stream, str);
    return stream;
}

void work_good()
{
    using namespace std::string_literals;
    log(1, 1.1f, "hello world"s);
}

void compile_error()
{
    using namespace std::string_literals;
    log(1, MyStruct(1, 1.1f, "hello world"s));
}

int main()
{
    work_good();
}
</code>```

答:
Question 1> I cannot understand log function. Is it possible to use
  fold expression like this ?

To be precise, it's not using fold expression (since C++17). See pack expansion, which was supported from C++11, and yes it's valid usage as in log.

A pattern followed by an ellipsis, in which the name of at least one parameter pack appears at least once, is expanded into zero or more comma-separated instantiations of the pattern, where the name of the parameter pack is replaced by each of the elements from the pack, in order.

and

Question 2> How could I use log function with Mystruct class ?

You declared operator<< taking MyStruct as rvalue-reference, but in log arguments are passed to operator<< as lvalue, which can't be bound to rvalue-reference. You can change the operator<< to taking lvalue-referenct to const, which is applicable for both lvalues and rvalues. e.g.

```<code>std::ostringstream& operator<< (std::ostringstream& stream, const MyStruct& val)
{
    auto str = val.to_string();
    std::operator <<(stream, str);
    return stream;
}
</code>```

LIVE

Body:
I'd like make a log function with multiple parameters, and I also want to call the log function with my class.

Here is my code (compiler : Visual studio 2019 or x86-64 gcc9.2)

Question 1> I cannot understand log function.
Is it possible to use fold expression like this ?
(this function comes from spdlog library)

Question 2>
How could I use the log function with Mystruct class ?

log(1, MyStruct(1, 1.1f, "hello world"s)); // compiler error

#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>

template<typename ... Args>
void log(int level, Args const& ... args)
{
    std::ostringstream stream;
    using List = int[];
    (void)List {
        0, ((void)(stream << args), 0) ...
    };
    std::cout << stream.str() << std::endl;
}

class MyStruct
{
public:
    int val1 = 0;
    float val2 = 0.f;
    std::string val3;

    MyStruct(int v1, float v2, std::string_view const& v3) : val1(v1), val2(v2), val3(v3) {};
    std::string to_string() const
    {
        std::stringstream stream;
        stream << "val1=" << val1 << ", val2=" << val2 << ",val3=" << val3;
        return stream.str();
    }
};

std::ostringstream& operator<< (std::ostringstream& stream, MyStruct&& val)
{
    auto str = val.to_string();
    std::operator <<(stream, str);
    return stream;
}

void work_good()
{
    using namespace std::string_literals;
    log(1, 1.1f, "hello world"s);
}

void compile_error()
{
    using namespace std::string_literals;
    log(1, MyStruct(1, 1.1f, "hello world"s));
}

int main()
{
    work_good();
}

Body:
Question 1> I cannot understand log function. Is it possible to use
  fold expression like this ?

To be precise, it's not using fold expression (since C++17). See pack expansion, which was supported from C++11, and yes it's valid usage as in log.

A pattern followed by an ellipsis, in which the name of at least one parameter pack appears at least once, is expanded into zero or more comma-separated instantiations of the pattern, where the name of the parameter pack is replaced by each of the elements from the pack, in order.

and

Question 2> How could I use log function with Mystruct class ?

You declared operator<< taking MyStruct as rvalue-reference, but in log arguments are passed to operator<< as lvalue, which can't be bound to rvalue-reference. You can change the operator<< to taking lvalue-referenct to const, which is applicable for both lvalues and rvalues. e.g.

std::ostringstream& operator<< (std::ostringstream& stream, const MyStruct& val)
{
    auto str = val.to_string();
    std::operator <<(stream, str);
    return stream;
}

LIVE


问:
How would I use this Factory class and whats the point?
This is my first ever post to SO and am very new to C# with most of my IT experience in databases. I am starting to look at some of our code and would like to understand how I would use this class and it methods for resusability purposes.

```<code>public class FileCreator
{
    public string Territory { get; set; }
    public string CV { get; set; }
    public string AdDate { get; set; }
    public string Category { get; set; }
    public string Advertiser { get; set; }
    public string Brand { get; set; }
    public decimal SumOfSpend { get; set; }
    public decimal SumOfVolume { get; set; }
    public string Spots { get; set; }
    public string PageNumber { get; set; }

    internal static List<FileCreator> Create(DataSet data)
    {
        var result = new List<FileCreator>();

        if (data.Tables.Count > 0)
        {
            result = Create(data.Tables[0]);
        }

        return result;
    }

    public static List<FileCreator> Create(DataTable dataTable)
    {
        var result = new List<FileCreator>();

        foreach (DataRow row in dataTable.Rows)
        {
            result.Add(Create(row));
        }

        return result;
    }

    private static FileCreator Create(DataRow row)
    {
        var fileCreator = new FileCreator();

        fileCreator.Territory = (row["Territory"].ToString());
        fileCreator.CV = row["CV"].ToString();
        fileCreator.AdDate = row["Ad_date"].ToString();
        fileCreator.Category = row["Category"].ToString();
        fileCreator.Advertiser = row["Advertiser"].ToString();
        fileCreator.Brand = row["Brand"].ToString();
        fileCreator.SumOfSpend = Convert.ToDecimal(row["SumOfSpend"].ToString());
        fileCreator.SumOfVolume = Convert.ToDecimal(row["SumOfVolume"].ToString());
        fileCreator.Spots = row["Spots"].ToString();
        fileCreator.PageNumber = row["Page Number"].ToString();

        return fileCreator;
    }
}
</code>```

Why not just create a new instance of a datatable i.e. var dt = new Datatable()?

I must be missing the point of this approach. How will I benefit from this approach when I normally just create multiple datatables?

Go easy. It's my first post

Thank you

答:
The point of this is get a strongly typed class instead of relying on hard-coded strings to get the data out and then casting everything to the type you are expecting.  Instead, its taking data from the Datatable and transforming it to a "Dto" (Data Transfer Object) where you know all the properties (columns) that exist and their types because they are explicitly declared.  There is no guessing! :)

While the given approach here works, I hope it is more for legacy sake.  It is more efficient to simply create this Dto class directly instead of creating a Datatable and then mapping it.

Body:
This is my first ever post to SO and am very new to C# with most of my IT experience in databases. I am starting to look at some of our code and would like to understand how I would use this class and it methods for resusability purposes.

public class FileCreator
{
    public string Territory { get; set; }
    public string CV { get; set; }
    public string AdDate { get; set; }
    public string Category { get; set; }
    public string Advertiser { get; set; }
    public string Brand { get; set; }
    public decimal SumOfSpend { get; set; }
    public decimal SumOfVolume { get; set; }
    public string Spots { get; set; }
    public string PageNumber { get; set; }

    internal static List<FileCreator> Create(DataSet data)
    {
        var result = new List<FileCreator>();

        if (data.Tables.Count > 0)
        {
            result = Create(data.Tables[0]);
        }

        return result;
    }

    public static List<FileCreator> Create(DataTable dataTable)
    {
        var result = new List<FileCreator>();

        foreach (DataRow row in dataTable.Rows)
        {
            result.Add(Create(row));
        }

        return result;
    }

    private static FileCreator Create(DataRow row)
    {
        var fileCreator = new FileCreator();

        fileCreator.Territory = (row["Territory"].ToString());
        fileCreator.CV = row["CV"].ToString();
        fileCreator.AdDate = row["Ad_date"].ToString();
        fileCreator.Category = row["Category"].ToString();
        fileCreator.Advertiser = row["Advertiser"].ToString();
        fileCreator.Brand = row["Brand"].ToString();
        fileCreator.SumOfSpend = Convert.ToDecimal(row["SumOfSpend"].ToString());
        fileCreator.SumOfVolume = Convert.ToDecimal(row["SumOfVolume"].ToString());
        fileCreator.Spots = row["Spots"].ToString();
        fileCreator.PageNumber = row["Page Number"].ToString();

        return fileCreator;
    }
}

Why not just create a new instance of a datatable i.e. var dt = new Datatable()?

I must be missing the point of this approach. How will I benefit from this approach when I normally just create multiple datatables?

Go easy. It's my first post

Thank you


问:
Sending values from one form to another without returning to form 1
I've been trying to figure out how to have a user input a string into a text box in Form1 and then hit a "Done" button and display Form2 with a Label containing the text from the text box in Form1.

I had come across this question which almost solved my problem (Send values from one form to another form) but the answer to the above question showed you how to hit a button, display Form2, then input a string, and hit another button returning to form 1 where the label displayed the text inputted in Form2.

I want to be able to input the string into a text box in Form 1 and when you hit a button display Form 2 with the label containing the string from the text box in Form 1.

I've spent a good hour or so trying to deconstruct the tiny bit of code from the linked question and get it to work how I want, but I just can't seem to understand it. If theres anyone who could either explain how to get a label in Form2 to contain a string from a text box in Form1 or show me the code necessary so I may look over it and understand it, it'd be greatly appreciated. As I currently cannot seem to get a grasp of how the code works in the previous question I linked.

This is the bit of code I used from the above linked question

```<code>// Form 1
// inside the button click event
using(Form2 form2 = new Form2())
{
    if(form2.ShowDialog() == DialogResult.OK)
    {
        someControlOnForm1.Text = form2.TheValue;
    }
}
</code>```

And...

```<code>// Inside Form2
// Create a public property to serve the value
public string TheValue
{
    get { return someTextBoxOnForm2.Text; }
}
</code>```

答:
Create Form1 with a label (label1) and a button (button1)

Create Form2 with a textbox (textBox1)

Form1.cs

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2(this.SetTextFromForm2, label1.Text);
            form2.ShowDialog();
        }

        private void SetTextFromForm2(string str)
        {
            label1.Text = str;
        }
    }
}
</code>```

Explain :

```<code>Form2 form2 = new Form2(this.SetTextFromForm2, label1.Text);
</code>```

Send 2 informations to Form2 : method to change Text of label on Form1, and current text of that label

Form2.cs

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

public delegate void SetTextToForm1(string str);

namespace WindowsFormsApp1
{

    public partial class Form2 : Form
    {
        public SetTextToForm1 setTextToForm1 { get; set; }

        public Form2(SetTextToForm1 SetTextMethod, string strTextFromForm1)
        {
            InitializeComponent();

            this.setTextToForm1 = SetTextMethod;
            this.textBox1.Text = strTextFromForm1;
        }

        private void TextBox1_TextChanged(object sender, EventArgs e)
        {
            setTextToForm1(textBox1.Text);
        }
    }
}
</code>```

Explain :

```<code>public delegate void SetTextToForm1(string str);
</code>```

"A delegate is a reference type variable that holds the reference to a method"

```<code>setTextToForm1(textBox1.Text);
</code>```

Call Form1's method to change text of label on Form1

Answer your question :

This bit of code did basically exactly what I'm looking for, but do
  you know if theres any way to essentially reverse it? I see when you
  input text into the textBox in Form 2 it does put that into the label,
  so it works perfectly. But is there a way to have the text box in Form
  1 and when you hit the button just have Form 2 pop up with the label
  containing the text from the text box in Form 1?

Create Form1 with a textbox (textBox1) and a button (button1)

Create Form2 with a label (label1)

Form1.cs

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

public delegate void SetTextToForm2(string str);

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        Form2 form2 = new Form2();

        public SetTextToForm2 setTextToForm2 { get; set; }

        public Form1()
        {
            InitializeComponent();

            setTextToForm2 = form2.SetTextFromForm1;
        }

        private void TextBox1_TextChanged(object sender, EventArgs e)
        {
            setTextToForm2(textBox1.Text);
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            form2.Visible = !form2.Visible;
        }
    }
}
</code>```

Form2.cs

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        public void SetTextFromForm1(string str)
        {
            label1.Text = str;
        }
    }
}
</code>```

Body:
I've been trying to figure out how to have a user input a string into a text box in Form1 and then hit a "Done" button and display Form2 with a Label containing the text from the text box in Form1.

I had come across this question which almost solved my problem (Send values from one form to another form) but the answer to the above question showed you how to hit a button, display Form2, then input a string, and hit another button returning to form 1 where the label displayed the text inputted in Form2.

I want to be able to input the string into a text box in Form 1 and when you hit a button display Form 2 with the label containing the string from the text box in Form 1.

I've spent a good hour or so trying to deconstruct the tiny bit of code from the linked question and get it to work how I want, but I just can't seem to understand it. If theres anyone who could either explain how to get a label in Form2 to contain a string from a text box in Form1 or show me the code necessary so I may look over it and understand it, it'd be greatly appreciated. As I currently cannot seem to get a grasp of how the code works in the previous question I linked.

This is the bit of code I used from the above linked question

// Form 1
// inside the button click event
using(Form2 form2 = new Form2())
{
    if(form2.ShowDialog() == DialogResult.OK)
    {
        someControlOnForm1.Text = form2.TheValue;
    }
}

And...

// Inside Form2
// Create a public property to serve the value
public string TheValue
{
    get { return someTextBoxOnForm2.Text; }
}

Body:
Create Form1 with a label (label1) and a button (button1)

Create Form2 with a textbox (textBox1)

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2(this.SetTextFromForm2, label1.Text);
            form2.ShowDialog();
        }

        private void SetTextFromForm2(string str)
        {
            label1.Text = str;
        }
    }
}

Explain :

Form2 form2 = new Form2(this.SetTextFromForm2, label1.Text);

Send 2 informations to Form2 : method to change Text of label on Form1, and current text of that label

Form2.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

public delegate void SetTextToForm1(string str);

namespace WindowsFormsApp1
{

    public partial class Form2 : Form
    {
        public SetTextToForm1 setTextToForm1 { get; set; }

        public Form2(SetTextToForm1 SetTextMethod, string strTextFromForm1)
        {
            InitializeComponent();

            this.setTextToForm1 = SetTextMethod;
            this.textBox1.Text = strTextFromForm1;
        }

        private void TextBox1_TextChanged(object sender, EventArgs e)
        {
            setTextToForm1(textBox1.Text);
        }
    }
}

Explain :

public delegate void SetTextToForm1(string str);

"A delegate is a reference type variable that holds the reference to a method"

setTextToForm1(textBox1.Text);

Call Form1's method to change text of label on Form1

Answer your question :

This bit of code did basically exactly what I'm looking for, but do
  you know if theres any way to essentially reverse it? I see when you
  input text into the textBox in Form 2 it does put that into the label,
  so it works perfectly. But is there a way to have the text box in Form
  1 and when you hit the button just have Form 2 pop up with the label
  containing the text from the text box in Form 1?

Create Form1 with a textbox (textBox1) and a button (button1)

Create Form2 with a label (label1)

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

public delegate void SetTextToForm2(string str);

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        Form2 form2 = new Form2();

        public SetTextToForm2 setTextToForm2 { get; set; }

        public Form1()
        {
            InitializeComponent();

            setTextToForm2 = form2.SetTextFromForm1;
        }

        private void TextBox1_TextChanged(object sender, EventArgs e)
        {
            setTextToForm2(textBox1.Text);
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            form2.Visible = !form2.Visible;
        }
    }
}

Form2.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        public void SetTextFromForm1(string str)
        {
            label1.Text = str;
        }
    }
}


问:
How can I separate the horizontal rule from the table. They are mixed together. I want the horizontal rule below my table
My horizontal rule is mixed up with part of the information on a table

So, my issue is to create two separate tables side by side, instead of one table below the other like usual. I did something that made it work but now my
 tag is mixed together with the tables.

Skills

      Sleeping
      ★★★★

      Eating
      ★★★

      Gaming
      ★★★★★

      Reading
      ★★★★★

```

That is the code. Can someone please help me put the horizontal rule below the table? As you can see from my code, the hr tag comes after closing the second table tag but my final output has mixed up the horizontal rule together with the table, instead of below it. What error have I made in my code? Any help would be appreciated, especially from my code. Somebody advise me on what's wrong with my code.

Also, I'm not pretty sure what is the work of the div tag since this was kinda an assignment if anybody can explain to me well, and why I put it in my code, I honestly don't know.

答:
table {
  float: left
}

hr {
  clear: both
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3>Skills</h3>
<table>
  <tr>
    <td>Sleeping</td>
    <td>★★★★</td>
  </tr>
  <tr>
    <td>Eating</td>
    <td>★★★</td>
  </tr>
</table>
<table style="float: left">
  <tr>
    <td>Gaming</td>
    <td>★★★★★</td>
  </tr>
  <tr>
    <td>Reading</td>
    <td>★★★★★</td>
</table>
<hr size="3" noshade="3"></code>```

Body:
My horizontal rule is mixed up with part of the information on a table

So, my issue is to create two separate tables side by side, instead of one table below the other like usual. I did something that made it work but now my
 tag is mixed together with the tables.

Skills

      Sleeping
      ★★★★

      Eating
      ★★★

      Gaming
      ★★★★★

      Reading
      ★★★★★

That is the code. Can someone please help me put the horizontal rule below the table? As you can see from my code, the hr tag comes after closing the second table tag but my final output has mixed up the horizontal rule together with the table, instead of below it. What error have I made in my code? Any help would be appreciated, especially from my code. Somebody advise me on what's wrong with my code.

Also, I'm not pretty sure what is the work of the div tag since this was kinda an assignment if anybody can explain to me well, and why I put it in my code, I honestly don't know.

Body:
table {
  float: left
}

hr {
  clear: both
}

<h3>Skills</h3>
<table>
  <tr>
    <td>Sleeping</td>
    <td>&#9733;&#9733;&#9733;&#9733;</td>
  </tr>
  <tr>
    <td>Eating</td>
    <td>&#9733;&#9733;&#9733;</td>
  </tr>
</table>
<table style="float: left">
  <tr>
    <td>Gaming</td>
    <td>&#9733;&#9733;&#9733;&#9733;&#9733;</td>
  </tr>
  <tr>
    <td>Reading</td>
    <td>&#9733;&#9733;&#9733;&#9733;&#9733;</td>
</table>
<hr size="3" noshade="3">


问:
How to add a day to a year,month,day datetime object
I found similar posts but had issues with them.
The problem I have is:
I have a date in the format year, month, day example - 2019:01:21
and I want to use a loop likely something like
for i in range(365):
       # add to the date by a single day and return something in the form 2019:01:22</p>

答:
You could use datetime.strptime() to parse the given date in string format to a python date format. Then you could use datetime.timedelta() to specify an interval of n days and shift the parsed date by this delta. Here is a short demo:

```<code>from datetime import datetime, timedelta

date = datetime.strptime("2019:01:21", "%Y:%m:%d")

for i in range(365):
    delta = timedelta(days=1 + i)
    print(date + delta)
</code>```

Output:

```<code>2019-01-22 00:00:00
2019-01-23 00:00:00
2019-01-24 00:00:00
...
</code>```

Body:
You could use datetime.strptime() to parse the given date in string format to a python date format. Then you could use datetime.timedelta() to specify an interval of n days and shift the parsed date by this delta. Here is a short demo:

from datetime import datetime, timedelta

date = datetime.strptime("2019:01:21", "%Y:%m:%d")

for i in range(365):
    delta = timedelta(days=1 + i)
    print(date + delta)

Output:

2019-01-22 00:00:00
2019-01-23 00:00:00
2019-01-24 00:00:00
...


问:
CSS content attribute: loading text from a TXT file
I need to know if it's possible to load text from a TXT file with the CSS "content" attribute? I searched around and didn't find anything.

I have the following CSS:

```<code>.custom div.ot-loginPageCopyright::after {
    content: url('copyright.txt');
    text-indent: 0;
    display: block;
    line-height: initial;
}
</code>```

The browser does request and download the .txt file, but nothing is displayed. It will display the text when it is a string literal in the CSS, but I was hoping to have some copyright information stored separately from the CSS in a text file, in case it needs to be updated, you could just update the text file without touching the CSS.

Note: I know how to do this via JS, but this has to be done via CSS, as no changes can be made to the HTML or JS. So please: no comments suggesting that this should be done in some other way except CSS (if it's possible).

Thanks!

答: Thanks for the comment @rawnewdlz! I saw the hack for using a SVG, but I was wondering if it was at all possible feeding in a text file into the content, which is not possible.</p>

Body:
I need to know if it's possible to load text from a TXT file with the CSS "content" attribute? I searched around and didn't find anything.

I have the following CSS:

.custom div.ot-loginPageCopyright::after {
    content: url('copyright.txt');
    text-indent: 0;
    display: block;
    line-height: initial;
}

The browser does request and download the .txt file, but nothing is displayed. It will display the text when it is a string literal in the CSS, but I was hoping to have some copyright information stored separately from the CSS in a text file, in case it needs to be updated, you could just update the text file without touching the CSS.

Note: I know how to do this via JS, but this has to be done via CSS, as no changes can be made to the HTML or JS. So please: no comments suggesting that this should be done in some other way except CSS (if it's possible).

Thanks!


问:
php first word only from mb string
I used preg_match but its returning pdf as it English that's why may be.

But I want to get only 練馬春日町Ⅳ

Is there any way to detect it for mb string.

```<code><?php
// Initialize a sentence to a variable
$sentence = '練馬春日町Ⅳ　清掃レポート.pdf';

// Use preg_match() function to get the
// first word of a string
preg_match('/\b\w+\b/i', $sentence, $result);

// Display result
echo "The first word of string is: ".$result[0];

?>
</code>```

FIDDLE

答:
To make your code work you just need to add the u flag to the regex so that it matches unicode characters:

```<code>preg_match('/^\w+/iu', $sentence, $result);
echo "\nThe first word of string is: ".$result[0];
</code>```

Output:

```<code>The first word of string is: 練馬春日町Ⅳ
</code>```

Note that since you want the first word you can simply anchor your regex with ^ and the second \b is not required as \w+ will match as many word characters as it can i.e. until it gets to the first word break.

Alternatively you can use mb_split with a regex of \p{Z} which matches any unicode whitespace or invisible separator:

```<code>$sentence = '練馬春日町Ⅳ　清掃レポート.pdf';
$first_word = mb_split('\p{Z}', $sentence);
echo $first_word[0];
</code>```

Output:

```<code>練馬春日町Ⅳ
</code>```

Demo on 3v4l.org

Title: php first word only from mb string

Body:
I used preg_match but its returning pdf as it English that's why may be.

But I want to get only 練馬春日町Ⅳ

Is there any way to detect it for mb string.

<?php
// Initialize a sentence to a variable
$sentence = '練馬春日町Ⅳ　清掃レポート.pdf';

// Use preg_match() function to get the
// first word of a string
preg_match('/\b\w+\b/i', $sentence, $result);

// Display result
echo "The first word of string is: ".$result[0];

?>

FIDDLE

Body:
To make your code work you just need to add the u flag to the regex so that it matches unicode characters:

preg_match('/^\w+/iu', $sentence, $result);
echo "\nThe first word of string is: ".$result[0];

Output:

The first word of string is: 練馬春日町Ⅳ

Note that since you want the first word you can simply anchor your regex with ^ and the second \b is not required as \w+ will match as many word characters as it can i.e. until it gets to the first word break.

Alternatively you can use mb_split with a regex of \p{Z} which matches any unicode whitespace or invisible separator:

$sentence = '練馬春日町Ⅳ　清掃レポート.pdf';
$first_word = mb_split('\p{Z}', $sentence);
echo $first_word[0];

Output:

練馬春日町Ⅳ

Demo on 3v4l.org


问:
Running Save Participants runs forever on File Save
Unfortunately I am not sure how to debug or even begin to debug this error. If someone can help me out it would be a huge help. I wish I could provide more info but essentially when I try to save a file, this comes up and it does not go away and runs forever. It prevents me from saving any file.

Things I have tried.
1. Restarting VS Code
2. Rebooting computer
3. Disabling all VS Code Extensions.
4. Updating VS Code and running as Administrator.

Any suggestions?

答:
I don't know if this'll help you but I also just recently encounter this issue. And this is how I fix it:

Close all tabs in vscode (try to revert any changes if possible).

Close vscode itself and open it again.

When you open vscode try to notice the initializing part at the bottom left, wait until it's done initializing.

Now, try to edit any file and save it.


问:
How to merge lists of objects based on their id's using the spread operator (ES6)
say i have two lists of objects,

```<code>list1 = [{id: 1, name: "tom", age:25}, {id: 2, name: "brad", age:35}, {id: 3, name: "marry", age:23}]
</code>```

and

```<code>list2 = [{id: 1, OS: "Windows"}, {id: 2, OS: "Mac"}];
</code>```

how do I obtain

```<code>finalList = [{id: 1, name: "tom", age:25, OS: "Windows"}, {id: 2, name: "brad", age:35, OS: "Mac"}, {id: 3, name: "marry", age:23}
</code>```

I would like to achieve this with the spread operator if at all possible, handling the scenarios where the lists are of different lenghts, and some objects dont hav id's.

答:
This will merge object of any length and any number of arguments

function merge(...args) {
    const max_pointer = Math.max(...args.map(arg=>arg.length));
    const test = []
    for (let i = 0; i < max_pointer; i++) {
        let e = args.map(arg=>arg[i]);
        let new_obj = Object.assign({}, ...e);
        test.push(new_obj);
    }
    return test;
}

const list1 = [{id: 1, name: "tom", age:25}, {id: 2, name: "brad", age:35}, {id: 3, name: "marry", age:23}]
const list2 = [{id: 1, OS: "Windows"}, {id: 2, OS: "Mac"}];

console.log(merge(list1, list2));```

Body:
say i have two lists of objects,

list1 = [{id: 1, name: "tom", age:25}, {id: 2, name: "brad", age:35}, {id: 3, name: "marry", age:23}]

and

list2 = [{id: 1, OS: "Windows"}, {id: 2, OS: "Mac"}];

how do I obtain

finalList = [{id: 1, name: "tom", age:25, OS: "Windows"}, {id: 2, name: "brad", age:35, OS: "Mac"}, {id: 3, name: "marry", age:23}

I would like to achieve this with the spread operator if at all possible, handling the scenarios where the lists are of different lenghts, and some objects dont hav id's.


问:
calculate dynamically elapsed time with vue js
I am trying to show the dynamically elapsed time from a start time

```<code><template>
  <div class="dashboard-editor-container">

      <div class="wrapper__body">

          <el-row :gutter="30">
             <el-col v-for="item in options" :key="item.value" align="middle" :xs="24" :sm="24" :md="24" :lg="4" :xl="24" style="margin-bottom:10px">

                 <el-button type="primary"  style="width: 180px;height:120px ;"  >{{item.label}} - {{getTimer(item.FechaHora)}}</el-button>
             </el-col>

          </el-row>

      </div>

  </div>
</template>
</code>```

js

```<code> <script>
    export default {
      data() {

       return {
            options: [{
              value: '01',
              label: 'Room 1',
              FechaHoraInicio:'2020-02-18T18:17:53.56',
              FechaHoraSalida:'2020-02-18T18:17:53.56',
            }, {
              value: '02',
              label: 'Room 2',
              FechaHoraStartTime:'2020-02-18T18:17:53.56',
              FechaHoraSalida:'2020-02-18T18:17:53.56',
            }, {
              value: '03',
              label: 'Room 2',
              FechaHoraStartTime:'2020-02-18T18:17:53.56',
              FechaHoraSalida:'2020-02-18T18:17:53.56',
            },
    }
    }
    },
 computed: {

    getTimer : function(FechaHoraInicio) {

       setInterval(function(){
           return  Date.now()-new Date(FechaHoraInicio)
       }, 3000);

    },
  },
    }

    </script>
</code>```

the buttons are created dynamically and will have a start time, and after that I want to calculate dynamically

I dynamically create each button with its respective start time, and I need that dynamically as a clock the time that elapses is shown, subtracting the current time with the start time

the time that has elapsed, since the room was rented

答:
i hope this works for you:

new Vue({
  el: "#app",
  data() {
    return {
      options: [
        {
          value: "01",
          label: "Room 1",
          FechaHoraStartTime: "2020-02-18T18:17:53.56",
          FechaHoraSalida: "2020-02-18T18:17:53.56"
        },
        {
          value: "02",
          label: "Room 2",
          FechaHoraStartTime: "2020-02-18T18:17:53.56",
          FechaHoraSalida: "2020-02-18T18:17:53.56"
        },
        {
          value: "03",
          label: "Room 2",
          FechaHoraStartTime: "2020-02-18T18:17:53.56",
          FechaHoraSalida: "2020-02-18T18:17:53.56"
        }
      ],
      intervalEvents: []
    };
  },

  created() {
    this.setTimers();
  },

  beforeDestroy() {
    this.intervalEvents.map(intervalEvent => {
      clearInterval(intervalEvent)
    })
  },

  methods: {
    setTimers() {
      this.options = this.options.map(option => ({
        ...option,
        elapsed: "",
        startTimeAsDate: new Date(option.FechaHoraStartTime)
      }));

      this.options.map(option => {
        const event = setInterval(() => {
          option.elapsed = new Date(new Date().getTime() - option.startTimeAsDate).toLocaleTimeString();
        }, 1000);

        this.intervalEvents.push(event)
      });
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link
  rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>

<div id="app">
  <div class="dashboard-editor-container">
    <div class="wrapper__body">
      <el-row :gutter="30">
        <el-col
          v-for="(option, index) in options"
          :key="index"
          align="middle"
          :xs="24" :sm="24" :md="24" :lg="4" :xl="24"
          style="margin-bottom:10px"
        >
          <el-button type="primary" style="width:180px;height:120px ;">
          {{option.label}} {{ option.elapsed }}
          </el-button>
        </el-col>
      </el-row>
    </div>
  </div>
</div></code>```

Body:
I am trying to show the dynamically elapsed time from a start time

<template>

          <el-row :gutter="30">
             <el-col v-for="item in options" :key="item.value" align="middle" :xs="24" :sm="24" :md="24" :lg="4" :xl="24" style="margin-bottom:10px">

                 <el-button type="primary"  style="width: 180px;height:120px ;"  >{{item.label}} - {{getTimer(item.FechaHora)}}</el-button>
             </el-col>

          </el-row>

</template>

js

the buttons are created dynamically and will have a start time, and after that I want to calculate dynamically

I dynamically create each button with its respective start time, and I need that dynamically as a clock the time that elapses is shown, subtracting the current time with the start time

the time that has elapsed, since the room was rented

Body:
i hope this works for you:

new Vue({
  el: "#app",
  data() {
    return {
      options: [
        {
          value: "01",
          label: "Room 1",
          FechaHoraStartTime: "2020-02-18T18:17:53.56",
          FechaHoraSalida: "2020-02-18T18:17:53.56"
        },
        {
          value: "02",
          label: "Room 2",
          FechaHoraStartTime: "2020-02-18T18:17:53.56",
          FechaHoraSalida: "2020-02-18T18:17:53.56"
        },
        {
          value: "03",
          label: "Room 2",
          FechaHoraStartTime: "2020-02-18T18:17:53.56",
          FechaHoraSalida: "2020-02-18T18:17:53.56"
        }
      ],
      intervalEvents: []
    };
  },

  created() {
    this.setTimers();
  },

  beforeDestroy() {
    this.intervalEvents.map(intervalEvent => {
      clearInterval(intervalEvent)
    })
  },

  methods: {
    setTimers() {
      this.options = this.options.map(option => ({
        ...option,
        elapsed: "",
        startTimeAsDate: new Date(option.FechaHoraStartTime)
      }));

      this.options.map(option => {
        const event = setInterval(() => {
          option.elapsed = new Date(new Date().getTime() - option.startTimeAsDate).toLocaleTimeString();
        }, 1000);

        this.intervalEvents.push(event)
      });
    }
  }
});

<link
  rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>

<div id="app">
  <div class="dashboard-editor-container">
    <div class="wrapper__body">
      <el-row :gutter="30">
        <el-col
          v-for="(option, index) in options"
          :key="index"
          align="middle"
          :xs="24" :sm="24" :md="24" :lg="4" :xl="24"
          style="margin-bottom:10px"
        >
          <el-button type="primary" style="width:180px;height:120px ;">
          {{option.label}} {{ option.elapsed }}
          </el-button>
        </el-col>
      </el-row>
    </div>
  </div>
</div>


答:
If what you want to do is generate 1000 replications of a sample from random uniform distribution with 20 observations (and minimums of 0 and maximums of 1), and then take the mean of each sample, here's a concise way to do it with tidyverse :

```<code>library(tidyverse)

uniform_samples <- map(1:1000, ~ runif(20, 0, 1))
uniform_sample_means <- map_dbl(uniform_samples, ~ mean(.x))

</code>```

Title: Sampling from a normal distribution using a for loop

Body:
If what you want to do is generate 1000 replications of a sample from random uniform distribution with 20 observations (and minimums of 0 and maximums of 1), and then take the mean of each sample, here's a concise way to do it with tidyverse :

library(tidyverse)

uniform_samples <- map(1:1000, ~ runif(20, 0, 1))
uniform_sample_means <- map_dbl(uniform_samples, ~ mean(.x))


问:
ajax call returns 404
I am trying to submit my form to the controller as JSON data to be further processed. I am using jquery to and use following code to submit the data:

My js code:

```<code>    $(document).ready(function(){
        alert('hi');
        $("#btn-save").click(function(event) {
               var data = {}
               alert($("#name").val());
            data["name"] = $("#name").val();
            data["address"] = $("#address").val();
            data["phone"] = $("#phone").val();
            data["zipCode"] = $("#zipCode").val();
            $("#btn-save").prop("disabled", true);
            alert('1'+JSON.stringify(data));
            $.ajax({
                 type: "POST",
                 contentType: "application/json",
                 url: "/saveUser",
                 data: JSON.stringify(data),
                 dataType: 'json',
                 timeout: 600000,
                 success: function (data) {
                    alert('success');
                 },
                 error: function(xhr, status, error){
                     var errorMessage = xhr.status + ': ' + xhr.statusText
                     alert('Error - ' + errorMessage);
                 }
        });
           });
    });
</script>
</code>```

I have written my controller class which is expected to handle the requests. but the execution never reaches this method.
This is expected to call the controller class:

```<code>@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public @ResponseBody SysUserDto  saveUser(@RequestBody SysUserDto user) {
    System.out.println("Save code******");
    return user;
}
</code>```

I even tried with out response body and having the return as void instead of SysUserDto
But i see 404 error as the execution goes to error block. Please help

答:
You can tried this. assuming your form id is called 'uploadForm'

```<code> $(document).ready(function(){
            alert('hi');
            $("#btn-save").click(function(event) {
             event.preventDefault();
             var user= new FormData($('#uploadForm')[0]);
                $.ajax({
                    contentType : false,
                    processData : false,
                     type: 'POST',
                     url: "/saveUser",
                     data: user,
                     timeout: 600000,
                     success: function (data) {
                        alert('success');
                     },
                     error: function(xhr, status, error){
                         var errorMessage = xhr.status + ': ' + xhr.statusText
                         alert('Error - ' + errorMessage);
                     }
            });
               });
        });
    </script>
</code>```

controller:

```<code>@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public @ResponseBody String saveUser(SysUserDto user) {
    System.out.println("Save code******");
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(user);
    System.out.println(json);
    return json;
}
</code>```

ObjectMapper is from jackson library.

Title: ajax call returns 404

Body:
I am trying to submit my form to the controller as JSON data to be further processed. I am using jquery to and use following code to submit the data:

My js code:

    $(document).ready(function(){
        alert('hi');
        $("#btn-save").click(function(event) {
               var data = {}
               alert($("#name").val());
            data["name"] = $("#name").val();
            data["address"] = $("#address").val();
            data["phone"] = $("#phone").val();
            data["zipCode"] = $("#zipCode").val();
            $("#btn-save").prop("disabled", true);
            alert('1'+JSON.stringify(data));
            $.ajax({
                 type: "POST",
                 contentType: "application/json",
                 url: "/saveUser",
                 data: JSON.stringify(data),
                 dataType: 'json',
                 timeout: 600000,
                 success: function (data) {
                    alert('success');
                 },
                 error: function(xhr, status, error){
                     var errorMessage = xhr.status + ': ' + xhr.statusText
                     alert('Error - ' + errorMessage);
                 }
        });
           });
    });
</script>

I have written my controller class which is expected to handle the requests. but the execution never reaches this method.
This is expected to call the controller class:

@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public @ResponseBody SysUserDto  saveUser(@RequestBody SysUserDto user) {
    System.out.println("Save code******");
    return user;
}

I even tried with out response body and having the return as void instead of SysUserDto
But i see 404 error as the execution goes to error block. Please help

Body:
You can tried this. assuming your form id is called 'uploadForm'

 $(document).ready(function(){
            alert('hi');
            $("#btn-save").click(function(event) {
             event.preventDefault();
             var user= new FormData($('#uploadForm')[0]);
                $.ajax({
                    contentType : false,
                    processData : false,
                     type: 'POST',
                     url: "/saveUser",
                     data: user,
                     timeout: 600000,
                     success: function (data) {
                        alert('success');
                     },
                     error: function(xhr, status, error){
                         var errorMessage = xhr.status + ': ' + xhr.statusText
                         alert('Error - ' + errorMessage);
                     }
            });
               });
        });
    </script>

controller:

@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public @ResponseBody String saveUser(SysUserDto user) {
    System.out.println("Save code******");
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(user);
    System.out.println(json);
    return json;
}

ObjectMapper is from jackson library.


问:
ScriptManager.RegisterStartupScript
in an usercontrol with update panel when using the scriptManger to register a script this code is works:

```<code>ScriptManager.RegisterStartupScript
        (this.updatePanel, this.updatePanel.GetType(), "printing", Keys.URL, true);
</code>```

but this one does not work

```<code>ScriptManager.RegisterStartupScript(this, this.GetType(), "printing", Keys.URL, true);
</code>```

i cant figure why?

答: I would think it's because in the first example you're registering a script for the UpdatePanel (which would be updated on an asynchronous postback - enabling the script to be written), whereas in the second example you're doing it at the page level, which wouldn't be updated as it falls outside the UpdatePanel.

ContentLicense: CC BY-SA 3.0

Title: ScriptManager.RegisterStartupScript

Body:
in an usercontrol with update panel when using the scriptManger to register a script this code is works:

ScriptManager.RegisterStartupScript
        (this.updatePanel, this.updatePanel.GetType(), "printing", Keys.URL, true);

but this one does not work

ScriptManager.RegisterStartupScript(this, this.GetType(), "printing", Keys.URL, true);

i cant figure why?


问:
Command output to console & grep to assert success status
I am running a python script which creates google cloud dataflow job. The command looks like this

```<code>python -m runpipline <command_options ...>
</code>```

The output of this command gives if the job was created successfully or not. In case of successful creation, the command ends like this

```<code>INFO:apache_beam.runners.dataflow.internal.apiclient:Create job: <Job
 createTime: '2020-02-18T20:39:44.885028Z'
 currentStateTime: '1970-01-01T00:00:00Z'
 id: '2020-02-18_12_39_43-1111111111111111111'
 location: 'us-central1'
 name: '<name_of_the_job>'
 projectId: '<project_name>'
 stageStates: []
 startTime: '2020-02-18T20:39:44.885028Z'
 steps: []
 tempFiles: []
 type: TypeValueValuesEnum(JOB_TYPE_STREAMING, 2)>
INFO:apache_beam.runners.dataflow.internal.apiclient:Created job with id: [2020-02-18_12_39_43-1111111111111111111]
INFO:apache_beam.runners.dataflow.internal.apiclient:To access the Dataflow monitoring console, please navigate to https://console.cloud.google.com/dataflow/jobsDetail/locations/us-central1/jobs/2020-02-18_12_39_43-1111111111111111111?project_name%
</code>```

This script is being run by github action and is using ubunt-latest image. What I want to do is

The output of the command should be print to console AND I should be able to extract the job_id from the command

If I am able to extract job id, i should be able to do next X command.

If job_id doesn't exist then I should fail the script.

I used grep to do this python -m runpipline <command_options ...> | grep -E "\d{4}-\d{2}-\d{2}_\d{2}_\d{2}_\d{2}-\d{19}\]" but this would stop me from outputing to console. Also, It just gives me the line which matches this criteria. not the job id. So not sure what to do

答:
Here is a simple solution that does what you need:

```<code>#!/bin/bash

cmd_output=$(python -m main --project_id <project_name> --topic_name <topic_name> --job_name <job_name>i) #captures the INFO output to a variable
id=$(grep -m 1 -o '[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}_[0-9]\{2\}_[0-9]\{2\}_[0-9]\{2\}-[0-9]\{19\}' <<<  $cmd_output ) #extracts the job id from the variable

#now we can see if a valid id was generated
if [[ -n $id ]]; then
  >&2 echo "$cmd_output" #you wanted to output both the INFO and id.  This outputs the INFO to stderr
  echo "$id" #this outputs the ID to stdout and can be captured as the result of your script
  #put next commands here
else
  #you can put an error message here if you want
  exit 1 #non-zero exit indicates failure
fi
</code>```

Let me know if you need anything else.

Body:
I am running a python script which creates google cloud dataflow job. The command looks like this

python -m runpipline <command_options ...>

The output of this command gives if the job was created successfully or not. In case of successful creation, the command ends like this

INFO:apache_beam.runners.dataflow.internal.apiclient:Create job: <Job
 createTime: '2020-02-18T20:39:44.885028Z'
 currentStateTime: '1970-01-01T00:00:00Z'
 id: '2020-02-18_12_39_43-1111111111111111111'
 location: 'us-central1'
 name: '<name_of_the_job>'
 projectId: '<project_name>'
 stageStates: []
 startTime: '2020-02-18T20:39:44.885028Z'
 steps: []
 tempFiles: []
 type: TypeValueValuesEnum(JOB_TYPE_STREAMING, 2)>
INFO:apache_beam.runners.dataflow.internal.apiclient:Created job with id: [2020-02-18_12_39_43-1111111111111111111]
INFO:apache_beam.runners.dataflow.internal.apiclient:To access the Dataflow monitoring console, please navigate to https://console.cloud.google.com/dataflow/jobsDetail/locations/us-central1/jobs/2020-02-18_12_39_43-1111111111111111111?project_name%

This script is being run by github action and is using ubunt-latest image. What I want to do is

The output of the command should be print to console AND I should be able to extract the job_id from the command

If I am able to extract job id, i should be able to do next X command.

If job_id doesn't exist then I should fail the script.

I used grep to do this python -m runpipline <command_options ...> | grep -E "\d{4}-\d{2}-\d{2}_\d{2}_\d{2}_\d{2}-\d{19}\]" but this would stop me from outputing to console. Also, It just gives me the line which matches this criteria. not the job id. So not sure what to do

Body:
Here is a simple solution that does what you need:

#!/bin/bash

cmd_output=$(python -m main --project_id <project_name> --topic_name <topic_name> --job_name <job_name>i) #captures the INFO output to a variable
id=$(grep -m 1 -o '[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}_[0-9]\{2\}_[0-9]\{2\}_[0-9]\{2\}-[0-9]\{19\}' <<<  $cmd_output ) #extracts the job id from the variable

#now we can see if a valid id was generated
if [[ -n $id ]]; then
  >&2 echo "$cmd_output" #you wanted to output both the INFO and id.  This outputs the INFO to stderr
  echo "$id" #this outputs the ID to stdout and can be captured as the result of your script
  #put next commands here
else
  #you can put an error message here if you want
  exit 1 #non-zero exit indicates failure
fi

Let me know if you need anything else.


问:
Why is my method undefined for this type?
I'm not sure why Eclipse is giving me this error, I cannot run the exchange method for any of my desired classes:

The method exchange(Currency, double) is undefined for the type Currency

Some of the code methods listed have not been fully implemented due to my issues compiling to begin with.

What simple mistake am I making?

```<code>public abstract class Currency {
  String currencyName;
  double totalFunds;

  //Exchange money between planets
  public abstract double toEarthDollars(double amount);

  public abstract double fromEarthDollars(double EarthDollars);

  public static void main(String[] args) {
    //TEST INPUT CODE
    Currency mars = new Mars(100.00);
    Currency neptune = new Neptune(100.00);
    Currency saturn = new Saturn(100.00);

    System.out.println("----- Exchanges -----");

    mars.exchange(saturn,25.0);
    neptune.exchange(saturn, 10.0);
    saturn.exchange(mars, 122.0);
    saturn.exchange(mars, 121.0);
  }
}

public interface Exchangeable {
  //rates should be encapsulated and accessed from here
  double EarthDollar = 1;
  double MarsMoney = 1.3;
  double SaturnSilver = 0.87;
  double NeptuneNuggets = 2;

  public void exchange(Exchangeable other, double amount);
}

public class Mars extends Currency implements Exchangeable {
  public Mars(double amount) {
    currencyName = "MarsMoney";
    totalFunds = amount;
  }

  public double toEarthDollars(double amount) {
    return amount * (Exchangeable.EarthDollar/Exchangeable.MarsMoney);
  }

  public double fromEarthDollars(double EarthDollars) {
    return EarthDollars * (Exchangeable.MarsMoney/Exchangeable.EarthDollar);
  }

  public void exchange(Exchangeable other, double amount) {
    System.out.println("Hello");
    //double transfer = this.toEarthDollars(amount);
    //transfer = ((Mars) other).fromEarthDollars(transfer);
  }
}
</code>```

答:
Your abstract Currency class does not implement the Exchangeable interface. Change

```<code>public abstract class Currency {
</code>```

to

```<code>public abstract class Currency implements Exchangeable {
</code>```

Body:
I'm not sure why Eclipse is giving me this error, I cannot run the exchange method for any of my desired classes:

The method exchange(Currency, double) is undefined for the type Currency

Some of the code methods listed have not been fully implemented due to my issues compiling to begin with.

What simple mistake am I making?

public abstract class Currency {
  String currencyName;
  double totalFunds;

  //Exchange money between planets
  public abstract double toEarthDollars(double amount);

  public abstract double fromEarthDollars(double EarthDollars);

  public static void main(String[] args) {
    //TEST INPUT CODE
    Currency mars = new Mars(100.00);
    Currency neptune = new Neptune(100.00);
    Currency saturn = new Saturn(100.00);

    System.out.println("----- Exchanges -----");

    mars.exchange(saturn,25.0);
    neptune.exchange(saturn, 10.0);
    saturn.exchange(mars, 122.0);
    saturn.exchange(mars, 121.0);
  }
}

public interface Exchangeable {
  //rates should be encapsulated and accessed from here
  double EarthDollar = 1;
  double MarsMoney = 1.3;
  double SaturnSilver = 0.87;
  double NeptuneNuggets = 2;

  public void exchange(Exchangeable other, double amount);
}

public class Mars extends Currency implements Exchangeable {
  public Mars(double amount) {
    currencyName = "MarsMoney";
    totalFunds = amount;
  }

  public double toEarthDollars(double amount) {
    return amount * (Exchangeable.EarthDollar/Exchangeable.MarsMoney);
  }

  public double fromEarthDollars(double EarthDollars) {
    return EarthDollars * (Exchangeable.MarsMoney/Exchangeable.EarthDollar);
  }

  public void exchange(Exchangeable other, double amount) {
    System.out.println("Hello");
    //double transfer = this.toEarthDollars(amount);
    //transfer = ((Mars) other).fromEarthDollars(transfer);
  }
}

Body:
Your abstract Currency class does not implement the Exchangeable interface. Change

public abstract class Currency {

to

public abstract class Currency implements Exchangeable {


答:
DolphinDB offers a function isDuplicated to remove duplicated values.</p>

```<code>select * from t where not isDuplicated(date, LAST)
</code>```

Title: How to drop duplicated values in DolphinDB?

Body:
I have a huge table with duplicated values in the column "date"(e.g. 2019.01.01,2019.01.01,2019.01.02...), and I want to delete the rows with repeated values in the column "date". Here are several rows of the table:

date       tick1     tick2     tick3     tick4
---------- --------- --------- --------- ---------
2019.01.01 8.229311  2.1392    45.886541 6.313477
2019.01.01 23.231155 25.810208 28.9341   1.128805
2019.01.01 11.540543 29.549798 31.069421 33.857873
2019.01.01 23.962028 6.652761  12.066605 5.232747
2019.01.01 39.342321 27.167645 2.171752  13.253192
2019.01.02 48.061951 19.817751 27.240194 38.289626
2019.01.02 0.678149  34.418003 5.43372   15.001061
2019.01.02 10.293357 5.26047   32.7181   0.55811
2019.01.03 23.540395 11.903505 28.543388 41.287217
2019.01.03 44.962452 50.714795 12.316604 30.056682
2019.01.03 14.342974 24.605586 14.026185 27.834454
2019.01.04 40.417088 4.122359  16.789886 50.838232
2019.01.04 3.968208  30.333996 14.35784  30.425456
2019.01.05 30.455829 16.391236 41.437266 43.053634
2019.01.06 35.302785 47.013003 4.511764  33.360219

I can get the distinct values in this way:

diff=exec distinct(date) from tb

But how to do then to keep the newest record of each value in vector "diff" and delete the old records?

For example, in the table above, only keep this recod for date equaling to 2019.01.01:

2019.01.01 39.342321 27.167645 2.171752  13.253192

So, how can I write SQL script to remove the repeated rows of the table?

Body:
DolphinDB offers a function isDuplicated to remove duplicated values.

select * from t where not isDuplicated(date, LAST)


答:
Since we don't have that api with us which generates your shown output so not tested it fully, could you please try following once.

```<code>cat script.ksh
OUT_FILE="/complete_path/output_file"
python -m runpipline <command_options ... > "$OUT_FILE"
if [[ -s "$OUT_FILE" ]]
then
     cat "$OUT_FILE"
     JOB_ID=$(grep -ioP ".*Created job with id:\s+\[\d{4}-\d{2}-\d{2}_(\d{2}_){2}\d{2}-\K(\d+)(?=])"  "$OUT_FILE")
     if [[ -n "$JOB_ID" ]]
     then
          echo "Run your further programs here......"
     else
          echo "Looks like NO job id found, exiting from script now... bye!!"
          exit 1
     fi
else
     echo "Please check your Python program has NOT created output file."
     exit 1
fi
</code>```

What does script do?

Script is having a BASH variable named OUT_FILE whose value is COMPLETE PATH of your file with file name where we want to store output of your Python command.

Then it runs your mentioned Python api(you could fill complete command there, I just used an example only provided by you in your samples).

It saves output of it in output_file at given by your complete path.

Now comes an if condition which checks if output_file is having size in it, means NOT NULL size then it goes further else it comes out of the script saying "Your python command didn't create any output file."

Now it uses GNU grep command to find out the job's id with  \K and regex and saves it into variable named JOB_ID.

Next is a condition if variable is NOT NULL then you could run your further commands there where I mentioned like Run your further programs here......

In case there is NO job id found if variable JOB_ID value is NOT NULL then script will exit saying Looks like NO job id found, exiting from script now... bye!!

Title: Command output to console & grep to assert success status

Body:
Since we don't have that api with us which generates your shown output so not tested it fully, could you please try following once.

cat script.ksh
OUT_FILE="/complete_path/output_file"
python -m runpipline <command_options ... > "$OUT_FILE"
if [[ -s "$OUT_FILE" ]]
then
     cat "$OUT_FILE"
     JOB_ID=$(grep -ioP ".*Created job with id:\s+\[\d{4}-\d{2}-\d{2}_(\d{2}_){2}\d{2}-\K(\d+)(?=])"  "$OUT_FILE")
     if [[ -n "$JOB_ID" ]]
     then
          echo "Run your further programs here......"
     else
          echo "Looks like NO job id found, exiting from script now... bye!!"
          exit 1
     fi
else
     echo "Please check your Python program has NOT created output file."
     exit 1
fi

What does script do?

Script is having a BASH variable named OUT_FILE whose value is COMPLETE PATH of your file with file name where we want to store output of your Python command.

Then it runs your mentioned Python api(you could fill complete command there, I just used an example only provided by you in your samples).

It saves output of it in output_file at given by your complete path.

Now comes an if condition which checks if output_file is having size in it, means NOT NULL size then it goes further else it comes out of the script saying "Your python command didn't create any output file."

Now it uses GNU grep command to find out the job's id with  \K and regex and saves it into variable named JOB_ID.

Next is a condition if variable is NOT NULL then you could run your further commands there where I mentioned like Run your further programs here......

In case there is NO job id found if variable JOB_ID value is NOT NULL then script will exit saying Looks like NO job id found, exiting from script now... bye!!


问:
Convert axis x-value to figure value
How can I convert an axis' x coordinate value into the figure's x coordinate value?

I want to align some text with the axis left side, but I want to draw it in a static position on the figure.

答:
So there are different ways to do what you want, I think this link provides two methods: one is placing text based on point coordinates and the second is placing text based relatively to an axis

https://riptutorial.com/matplotlib/example/16030/coordinate-systems-and-text

Title: Convert axis x-value to figure value


问:
Filter list of dicts based on some condition
I have following list

```<code>[
<class 'supapi.classes.Offer'>: {'currency': 'RUR', 'date_from': '2020-02-18', 'rub_value': '62.00'},
<class 'supapi.classes.Offer'>: {'currency': 'RUR', 'date_from': '2020-02-16', 'rub_value': '50.00'},
<class 'supapi.classes.Offer'>: {'currency': 'RUR', 'date_from': '2020-02-30', 'rub_value': '0.00'},
<class 'supapi.classes.Offer'>: {'currency': 'RUR', 'date_from': '2019-11-25', 'rub_value': '5.00'}
]
</code>```

I would like to filter that list based on last date condition and not future date.
For example, after filtration i want get only [<class 'supapi.classes.Offer'>: {'currency': 'RUR', 'date_from': '2020-02-18', 'rub_value': '62.00'}] because it's last current date and not future date

I figure out that i can compare date using datetime.datetime.strptime(date_string, '%Y-%m-%d')

答:
I also figure out own solution</p>

```<code>return list(
            filter(
                lambda e: datetime.strptime(e.date_from, '%Y-%m-%d') == max(
                    [datetime.strptime(item.date_from, '%Y-%m-%d') for item in list_to_sort
                     if datetime.strptime(item.date_from, '%Y-%m-%d') <= datetime.today()]
                ), offers)
        )
</code>```

Body:
I have following list

[
<class 'supapi.classes.Offer'>: {'currency': 'RUR', 'date_from': '2020-02-18', 'rub_value': '62.00'},
<class 'supapi.classes.Offer'>: {'currency': 'RUR', 'date_from': '2020-02-16', 'rub_value': '50.00'},
<class 'supapi.classes.Offer'>: {'currency': 'RUR', 'date_from': '2020-02-30', 'rub_value': '0.00'},
<class 'supapi.classes.Offer'>: {'currency': 'RUR', 'date_from': '2019-11-25', 'rub_value': '5.00'}
]

I would like to filter that list based on last date condition and not future date.
For example, after filtration i want get only [<class 'supapi.classes.Offer'>: {'currency': 'RUR', 'date_from': '2020-02-18', 'rub_value': '62.00'}] because it's last current date and not future date

I figure out that i can compare date using datetime.datetime.strptime(date_string, '%Y-%m-%d')

Body:
I also figure out own solution

return list(
            filter(
                lambda e: datetime.strptime(e.date_from, '%Y-%m-%d') == max(
                    [datetime.strptime(item.date_from, '%Y-%m-%d') for item in list_to_sort
                     if datetime.strptime(item.date_from, '%Y-%m-%d') <= datetime.today()]
                ), offers)
        )


问:
Can Azure azcopy pull file from on-prem server?
I am very new to Azure, so posting this query. I just want to copy a flat file from an on-prem server to Azure BLOB storage daily basis. I thought "azcopy" will be a good solution for this requirement. But challenge is we can not configure "azcopy" utility in that on-prem server and can not schedule any cron job as this sever is owing by our client. So we thought of running "azcopy" utility from one of the Unix VM in Azure cloud and want to pull the file and transfer to Azure BLOB storage.

I am not getting any clear idea from documentation that "azcopy" can work as a pull manner or not.

Can anyone help me to understand whether my approach will work or not   ? and if not then please give me some idea how to do this.

Please see below diagram depicting what I want to achieve.

答:
AzCopy is not designed to be used in that way.

If there's any way for you to access the file, that will be up to your customer and you'd have to ask their network security folks how they would expect it to be done. But most customers (or at least all the ones I worked with before joining Microsoft) prefer push not pull models, since the security for push is more standard and easier to set up.


问:
Unable to link Shared Library with Eclipse on Ubuntu
Disclaimer: I am not a Eclipse coder on Linux and I will refrain calling it names after being unable to create a shell for a simple EXE with linked Shared Library (a DLL in English).

Please be patient - I will describe in detail what I did...

I'd appreciate if anybody can tell me what's going on... I worked with C/C++ Visual Studio for decades but can't figure out what's going on in this medieval tool (Eclipse)...

I installed Eclipse 2019-x on Ubunty 18.04 and also installed CDT.

I have created and built a shared library, a C++ Project. The library has a C-style API and a C++ class. It is located at /home/leon/Projects/RLV2
It builds OK.

RLV2Shared.h

```<code>#ifndef RLV2SHARED_H_
#define RLV2SHARED_H_

#include "Logger.h"
using namespace CPlusPlusLogging;

#include "shared_EXPORTS.h"  // automatically generated by cmake
                         // by the GENERATE_EXPORT_HEADER macro

extern "C" int SHARED_EXPORT ValidateCryptoLicense(const char* token, char* signedMsg, int& signedMsgLen);
//extern "C" int ValidateCryptoLicense(const char* token, char* signedMsg, int& signedMsgLen);

class SHARED_EXPORT RLV
//class RLV
{
public:

    CPlusPlusLogging::Logger* mpLogger = NULL; // Create the object pointer for Logger Class

    RLV();
    void mRLV();
    void InitLogger();
};

#endif /* RLV2SHARED_H_ */
</code>```

RLV2Shared.cpp

```<code>#include <string>
#include <iostream>
#include <fstream>
#include <stdio.h>

#include "Logger.h"
#include "RLV2Shared.h"

using namespace CPlusPlusLogging;
using namespace std;

int ValidateCryptoLicense(const char* token, char* signedMsg, int& signedMsgLen)
{
    cout << "!!!Hello from ValidateCryptoLicense!!!" << endl;
    LOG_INFO("ValidateCryptoLicense has been called from external module\n");
    return 5;
}

RLV::RLV()
{
    InitLogger();

    LOG_INFO("RLV class constructor has been called\n");
}

void RLV::mRLV()
{
    LOG_INFO("RLV::mRLV function has been called)\n");
}
</code>```

I also created and built another simple C++ project, "Hello World", a Console application located at /home/leon/Projects/RLVTest2.
I also created subdir 'lib' under RLVTest2 and in a post-build step of RLV2 I copy the file libRLV2.so to that 'lib'
It also builds OK.

```<code>#include "Logger.h"
#include "RLV2Shared.h"
</code>```

int ValidateCryptoLicense(const char* token, char* signedMsg, int& signedMsgLen)
{
    cout << "!!!Hello from ValidateCryptoLicense!!!" << endl;
    LOG_INFO("ValidateCryptoLicense has been called from external module\n");
    return 5;
}

RLV::RLV()
{
    InitLogger();

```<code>LOG_INFO("RLV class constructor has been called\n");
</code>```

}

void RLV::mRLV()
{
    LOG_INFO("RLV::mRLV function has been called)\n");
}

Then I add shared library to exe project:
Project > Properties > C++ Build -> Settings -> GNCC C++ Linker -> Libraries has the absolute path to the library.
-L/home/leon/Projects/RLVTest2/lib
I also added the same path to the library path under C++ General > Path and Symbols > Library Path
I also added the libRLV2.so library to C++ General > Path and Symbols > Libraries of the exe project

Here is the result of the building of exe:

Building target: RLVTest2
Invoking: GCC C++ Linker
g++ -L/home/leon/Projects/RLVTest2/lib -pthread -o "RLVTest2"  ./src/RLVTest2.o   -llibRLV2.so
/usr/bin/ld: cannot find -llibRLV2.so
collect2: error: ld returned 1 exit status
makefile:48: recipe for target 'RLVTest2' failed
make: *** [RLVTest2] Error 1
"make all" terminated with exit code 2. Build might be incomplete.

When add library path in the linker as a full path it also complains the same...

Building target: RLVTest2
Invoking: GCC C++ Linker
g++ -L/home/leon/Projects/RLVTest2/lib -pthread -o "RLVTest2"  ./src/RLVTest2.o   -l/home/leon/Projects/RLVTest2/lib/libRLV2.so
/usr/bin/ld: cannot find -l/home/leon/Projects/RLVTest2/lib/libRLV2.so
makefile:48: recipe for target 'RLVTest2' failed
collect2: error: ld returned 1 exit status
make: *** [RLVTest2] Error 1
"make all" terminated with exit code 2. Build might be incomplete.

答:
I cannot describe how angry I am at the Eclipse developers (creators)...
I don't care that it is free - if you do something, do it right - without a thought: "I'll do something so smart that they gonna build a monument for me"...

When I changed the content of Project > Properties > C++ Build -> Settings -> GNCC C++ Linker -> Libraries (-l option) to RLV2 linked work just fine...

Body:
Disclaimer: I am not a Eclipse coder on Linux and I will refrain calling it names after being unable to create a shell for a simple EXE with linked Shared Library (a DLL in English).

Please be patient - I will describe in detail what I did...

I'd appreciate if anybody can tell me what's going on... I worked with C/C++ Visual Studio for decades but can't figure out what's going on in this medieval tool (Eclipse)...

I installed Eclipse 2019-x on Ubunty 18.04 and also installed CDT.

I have created and built a shared library, a C++ Project. The library has a C-style API and a C++ class. It is located at /home/leon/Projects/RLV2
It builds OK.

RLV2Shared.h

#ifndef RLV2SHARED_H_
#define RLV2SHARED_H_

#include "Logger.h"
using namespace CPlusPlusLogging;

#include "shared_EXPORTS.h"  // automatically generated by cmake
                         // by the GENERATE_EXPORT_HEADER macro

extern "C" int SHARED_EXPORT ValidateCryptoLicense(const char* token, char* signedMsg, int& signedMsgLen);
//extern "C" int ValidateCryptoLicense(const char* token, char* signedMsg, int& signedMsgLen);

class SHARED_EXPORT RLV
//class RLV
{
public:

    CPlusPlusLogging::Logger* mpLogger = NULL; // Create the object pointer for Logger Class

    RLV();
    void mRLV();
    void InitLogger();
};

#endif /* RLV2SHARED_H_ */

RLV2Shared.cpp

#include <string>
#include <iostream>
#include <fstream>
#include <stdio.h>

#include "Logger.h"
#include "RLV2Shared.h"

using namespace CPlusPlusLogging;
using namespace std;

int ValidateCryptoLicense(const char* token, char* signedMsg, int& signedMsgLen)
{
    cout << "!!!Hello from ValidateCryptoLicense!!!" << endl;
    LOG_INFO("ValidateCryptoLicense has been called from external module\n");
    return 5;
}

RLV::RLV()
{
    InitLogger();

    LOG_INFO("RLV class constructor has been called\n");
}

void RLV::mRLV()
{
    LOG_INFO("RLV::mRLV function has been called)\n");
}

I also created and built another simple C++ project, "Hello World", a Console application located at /home/leon/Projects/RLVTest2.
I also created subdir 'lib' under RLVTest2 and in a post-build step of RLV2 I copy the file libRLV2.so to that 'lib'
It also builds OK.

#include "Logger.h"
#include "RLV2Shared.h"

int ValidateCryptoLicense(const char* token, char* signedMsg, int& signedMsgLen)
{
    cout << "!!!Hello from ValidateCryptoLicense!!!" << endl;
    LOG_INFO("ValidateCryptoLicense has been called from external module\n");
    return 5;
}

RLV::RLV()
{
    InitLogger();

LOG_INFO("RLV class constructor has been called\n");

}

void RLV::mRLV()
{
    LOG_INFO("RLV::mRLV function has been called)\n");
}

Then I add shared library to exe project:
Project > Properties > C++ Build -> Settings -> GNCC C++ Linker -> Libraries has the absolute path to the library.
-L/home/leon/Projects/RLVTest2/lib
I also added the same path to the library path under C++ General > Path and Symbols > Library Path
I also added the libRLV2.so library to C++ General > Path and Symbols > Libraries of the exe project

Here is the result of the building of exe:

Building target: RLVTest2
Invoking: GCC C++ Linker
g++ -L/home/leon/Projects/RLVTest2/lib -pthread -o "RLVTest2"  ./src/RLVTest2.o   -llibRLV2.so
/usr/bin/ld: cannot find -llibRLV2.so
collect2: error: ld returned 1 exit status
makefile:48: recipe for target 'RLVTest2' failed
make: *** [RLVTest2] Error 1
"make all" terminated with exit code 2. Build might be incomplete.

When add library path in the linker as a full path it also complains the same...

Building target: RLVTest2
Invoking: GCC C++ Linker
g++ -L/home/leon/Projects/RLVTest2/lib -pthread -o "RLVTest2"  ./src/RLVTest2.o   -l/home/leon/Projects/RLVTest2/lib/libRLV2.so
/usr/bin/ld: cannot find -l/home/leon/Projects/RLVTest2/lib/libRLV2.so
makefile:48: recipe for target 'RLVTest2' failed
collect2: error: ld returned 1 exit status
make: *** [RLVTest2] Error 1
"make all" terminated with exit code 2. Build might be incomplete.


问:
requests post function result is forbidden
I am currently trying to scrape the result from https://omia.org/search/ by inputting values into Trait id (OMIA id): input box using BeautifulSoup.
Since I am trying to get a response from a page, I know that I have to use the requests.post(). However, if I use response = requests.post("https://omia.org/search/",params = {"omia_id":179}), I get 403 status code along with message saying I need to do something with CSRF cookie.

What do I need to do to get the correct response using .post()?

答:
If you're getting a CSRF error, it is likely that you need to include the CSRF header and cookie. For this case, you will need the csrftoken cookie and a matching csrfmiddlewaretoken in the request body.

```<code>import requests
from bs4 import BeautifulSoup

with requests.Session() as s:
    res = s.get("https://omia.org/search/")
    cookies = '; '.join([x+"="+y for x,y in res.cookies.items()])

    soup = BeautifulSoup(res.text,"lxml")
    csrfmiddleware = soup.select_one('[name="csrfmiddlewaretoken"]')['value']

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3835.0 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Cookie': cookies
    }

    data = f'csrfmiddlewaretoken={csrfmiddleware}&search_type=simple&query=test&query_type=or&result_type=phene'

    response = s.post('https://omia.org/results/', headers=headers, data=data, verify=False)
    print(response)
</code>```

<Response [200]>

Body:
If you're getting a CSRF error, it is likely that you need to include the CSRF header and cookie. For this case, you will need the csrftoken cookie and a matching csrfmiddlewaretoken in the request body.

import requests
from bs4 import BeautifulSoup

with requests.Session() as s:
    res = s.get("https://omia.org/search/")
    cookies = '; '.join([x+"="+y for x,y in res.cookies.items()])

    soup = BeautifulSoup(res.text,"lxml")
    csrfmiddleware = soup.select_one('[name="csrfmiddlewaretoken"]')['value']

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3835.0 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Cookie': cookies
    }

    data = f'csrfmiddlewaretoken={csrfmiddleware}&search_type=simple&query=test&query_type=or&result_type=phene'

    response = s.post('https://omia.org/results/', headers=headers, data=data, verify=False)
    print(response)

<Response [200]>


问:
Using shared user-defined Kusto functions in Log Analytics
I have a number of queries in Log Analytics that share a few common parts that I have expressed in functions that I defined. There is a way to save them, but there is a problem invoking them from queries. Specifically, I can save and invoke a subquery, but I cannot save and invoke a scalar function.

For example, suppose I save the following query under name fiveEntries:

```<code>StormEvents
| limit 5
</code>```

I can then invoke it as:

```<code>fiveEntries
</code>```

Now I want to define a scalar function and save it under name value5:

```<code>let value5 = () {5};
</code>```

I cannot invoke it by name and get an error:

```<code>StormEvents
| limit value5()

Syntax Error
Body of the callable expression cannot be empty
If issue persists, please open a support ticket.
Request id: 4b79daef-...
</code>```

It looks like external user-defined scalar (and tabular) functions are not supported (and this  seems to be confirmed by another writeup).

My questions:

Is this correct, or is there a way to get this to work?

If this is a real limitation, are there plans to add support for such functions (and when)?

Are there recommended ways of building and maintaining sets of common functions to be used across multiple Log Analytics queries?

Thanks in advance!

答:
Best to my knowledge, Stored User-defined Scalar functions are not yet supported. I believe it is worth adding this feature request to the backlog of the Azure Log Analytics.

Links for reference: Kusto Functions Stored Functions User-defined Functions

With regards 3rd point on maintaining common functions across multiple Log Analytics queries - Use Shared Queries option under Save to while saving the query.

Body:
I have a number of queries in Log Analytics that share a few common parts that I have expressed in functions that I defined. There is a way to save them, but there is a problem invoking them from queries. Specifically, I can save and invoke a subquery, but I cannot save and invoke a scalar function.

For example, suppose I save the following query under name fiveEntries:

StormEvents
| limit 5

I can then invoke it as:

fiveEntries

Now I want to define a scalar function and save it under name value5:

let value5 = () {5};

I cannot invoke it by name and get an error:

StormEvents
| limit value5()

Syntax Error
Body of the callable expression cannot be empty
If issue persists, please open a support ticket.
Request id: 4b79daef-...

It looks like external user-defined scalar (and tabular) functions are not supported (and this  seems to be confirmed by another writeup).

My questions:

Is this correct, or is there a way to get this to work?

If this is a real limitation, are there plans to add support for such functions (and when)?

Are there recommended ways of building and maintaining sets of common functions to be used across multiple Log Analytics queries?

Thanks in advance!


答:
I think your Currency class does not know a method of exchange only Exchangeable has that.

So you might want to cast:

```<code>  Currency mars = new Mars(100.00);
  Exchangeable marsEx = (Exchangeable)mars;
  Exchangeable saturnEx = (Exchangeable)saturn;
  marsEx.exchange(saturnEx,25.0);
</code>```

You also might want to check if that Currency can be casted to Exchangeable as maybe not all currencies are exchangeable.

Also you might need to cast saturn, as Currency can not be passed to the exchange method.

Title: Why is my method undefined for this type?

Body:
I think your Currency class does not know a method of exchange only Exchangeable has that.

So you might want to cast:

  Currency mars = new Mars(100.00);
  Exchangeable marsEx = (Exchangeable)mars;
  Exchangeable saturnEx = (Exchangeable)saturn;
  marsEx.exchange(saturnEx,25.0);

You also might want to check if that Currency can be casted to Exchangeable as maybe not all currencies are exchangeable.

Also you might need to cast saturn, as Currency can not be passed to the exchange method.


问:
Use write() to write char* to file from user input
I'm trying to write a function that takes in a path from stdin and saves that path to a file.
Despite many attempts, I have lost any kind of sense of how to properly do it. Can someone show me how to do it right?
This is my code:

```<code>void char_to_file(const char *pathname, const char *dest)
{
        int fd_1;
        if (fd_1 = open(dest, O_WRONLY | O_CREAT | O_TRUNC, 0666) == -1)
                custom_error_shout("OPEN FD_1");
        while (*(pathname) != '\0')
        {
                *(pathname++);
                if (write(fd_1, &pathname, 1) == -1)
                        custom_error_shout("WRITE TO FILE");
        }

        if (close(fd_1) == -1)
                custom_error_shout("CLOSE FD_1");
}
</code>```

The file will be created but nothing will be written in it. No errors have come out of this.

答:
The reason nothing is written is you reset fd_1 to the result of the conditional open(..) == -1, which unless open fails means the result will be 0 (STDIN_FILENO). If the open() does fail and returns -1, then fd_1 will equal 1 (STDOUT_FILENO). So you are trying to write to stdin unless open() fails.

This is due to your failure to wrap your assignment in parentheses, e.g. if (fd_1 = open() == -1) -- which should be if ((fd_1 = open()) == -1). Otherwise == (relational operator) has higher operator precedence than = (simple assignment) and the result of open(..) == -1 is assigned to fd_1.

To correct the problem, you need:

```<code>if ((fd_1 = open(dest, O_WRONLY | O_CREAT | O_TRUNC, 0666)) == -1)
</code>```

(note: your choice of mode of 0666 will be subject to the system umask and will likely results in actual permissions of 0644. See man 2 umask)

Your write command should pass the address of the first character, not a pointer to that address, e.g.

```<code>    if (write(fd_1, pathname, 1) == -1)
</code>```

You should enable compiler warnings. E.g. -Wall -Wextra -pedantic for gcc/clang or /W3 for VS (for other compilers, check the options). With warnings enable, you should receive the warning about a computed value not used with:

```<code>    *(pathname++);
</code>```

To advance the pointer, simply use pathname++;. Dereferencing the result has no purpose if it is not being assigned or otherwise being used.

If you have no other issues with the strings in pathname or dest, and your error macros work properly -- then this should fix your problem. (with the note, using fopen and file-stream operations like fputs() makes much more sense).

Let me know if you have further questions.

Body:
I'm trying to write a function that takes in a path from stdin and saves that path to a file.
Despite many attempts, I have lost any kind of sense of how to properly do it. Can someone show me how to do it right?
This is my code:

void char_to_file(const char *pathname, const char *dest)
{
        int fd_1;
        if (fd_1 = open(dest, O_WRONLY | O_CREAT | O_TRUNC, 0666) == -1)
                custom_error_shout("OPEN FD_1");
        while (*(pathname) != '\0')
        {
                *(pathname++);
                if (write(fd_1, &pathname, 1) == -1)
                        custom_error_shout("WRITE TO FILE");
        }

        if (close(fd_1) == -1)
                custom_error_shout("CLOSE FD_1");
}

The file will be created but nothing will be written in it. No errors have come out of this.

Body:
The reason nothing is written is you reset fd_1 to the result of the conditional open(..) == -1, which unless open fails means the result will be 0 (STDIN_FILENO). If the open() does fail and returns -1, then fd_1 will equal 1 (STDOUT_FILENO). So you are trying to write to stdin unless open() fails.

This is due to your failure to wrap your assignment in parentheses, e.g. if (fd_1 = open() == -1) -- which should be if ((fd_1 = open()) == -1). Otherwise == (relational operator) has higher operator precedence than = (simple assignment) and the result of open(..) == -1 is assigned to fd_1.

To correct the problem, you need:

if ((fd_1 = open(dest, O_WRONLY | O_CREAT | O_TRUNC, 0666)) == -1)

(note: your choice of mode of 0666 will be subject to the system umask and will likely results in actual permissions of 0644. See man 2 umask)

Your write command should pass the address of the first character, not a pointer to that address, e.g.

    if (write(fd_1, pathname, 1) == -1)

You should enable compiler warnings. E.g. -Wall -Wextra -pedantic for gcc/clang or /W3 for VS (for other compilers, check the options). With warnings enable, you should receive the warning about a computed value not used with:

    *(pathname++);

To advance the pointer, simply use pathname++;. Dereferencing the result has no purpose if it is not being assigned or otherwise being used.

If you have no other issues with the strings in pathname or dest, and your error macros work properly -- then this should fix your problem. (with the note, using fopen and file-stream operations like fputs() makes much more sense).

Let me know if you have further questions.