问:
Using JavaScript to refresh or retrieve current information on button click
I'll preface this with I'm still new to JavaScript.  So problem is in a larger application, our controller is passing in a list of information to the view where certain JavaScript functions rely on certain ViewModel properties.  I've written a simple application to hopefully illustrate what I'm getting at.

Below is a sample controller that's passing in List to the Index page:

```<code>    public ActionResult Index() {
        List<int> activeIds = new List<int>();
        SqlConnection sqlConn = new SqlConnection(connection_String);

        sqlConn.Open();

        string sqlStr = "SELECT * FROM dbo.[JS-Test] WHERE Active = 1";
        SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
        SqlDataReader sqlDR = sqlCmd.ExecuteReader();

        if(sqlDR.HasRows) {
            while (sqlDR.Read()) {
                activeIds.Add((int)sqlDR["ID"]);
            }
        }

        sqlDR.Close();
        sqlCmd.Dispose();
        sqlConn.Close();

        return View(activeIds);
    }
</code>```

This returns the current "active" items in the database. The (rough) view is as follows...

```<code>@model List<int>

@{
    ViewBag.Title = "Index";
}

<p>Current Recognized Count: @Model.Count() </p>
<a href="#" id="printBtn">Print</a>

<script>
$(document).ready(function () {
    $('#printBtn').click(function () {

        var numberOfActiveIds = @Model.Count();

        $.ajax({
            type: "POST",
            url: "/Home/PostResults",
            data: { ids: numberOfActiveIds},
            success: function (results) {
                if(results == "Success") {
                    window.location.href = '/Home/Results';
                }
            }
        });
    });
});
</script>
</code>```

The issue is getting the current number of active items from the database when the button is clicked.  Let's say that the user remains idle on the page after it loads for a few minutes.  When their page originally loaded, the model returned 5 items listed as active... but while they've been waiting 3 additional items were switched to active in the database for a total of 8.  However, when the user finally clicks the button it'll submit 5 items instead of the current 8.

I'm unable to run the query to get the current number of active items in the "/Home/PostResults" ActionResult due to the nature of how the larger application is set up.  Is there a way I could refresh the page (getting the updated model) before the rest of the function carries out using values of the refreshed model?

If you have any additional questions, please let me know and I will gladly comply.  I've looked at other questions and answers on SO but I haven't found one that quite works for my situation.  Thanks!

Edit #1

So, I've added this function to the Home controller which just returns the list count as Json.

```<code>    public ActionResult GetIds(){
        List<int> activeIds = new List<int>();
        SqlConnection sqlConn = new SqlConnection(connection_String);

        sqlConn.Open();

        string sqlStr = "SELECT * FROM dbo.[JS-Test] WHERE Active = 1";
        SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
        SqlDataReader sqlDR = sqlCmd.ExecuteReader();

        if (sqlDR.HasRows) {
            while (sqlDR.Read()) {
                activeIds.Add((int)sqlDR["ID"]);
            }
        }

        sqlDR.Close();
        sqlCmd.Dispose();
        sqlConn.Close();

        return Json(activeIds.Count());
    }
</code>```

The view script now looks like this...

```<code><script>
$(document).ready(function () {
    $('#printBtn').click(function () {

        var numberOfActiveIds = @Model.Count();

        $.ajax({
            type: "GET",
            url: "/Home/GetIds",
            success: function(response) {
                numberOfActiveIds = response;

                $.ajax({
                    type: "POST",
                    url: "/Home/PostResults",
                    data: { ids: numberOfActiveIds},
                    success: function (results) {
                        if(results == "Success") {
                            window.location.href = '/Home/Results';
                        }
                    }
                });
            }
        });
    });
});
</script>
</code>```

I'm currently getting the following error...

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Edit #2

I had to set the JsonRequestBehavior to AllowGet for it to work properly.  Thanks again, everyone!

答:
I can give you an idea, i hope it can help,

run another ajax 1st on btnclick to get the data(or datat count) again, if the record count is greater then current then update the view and don't PostResults and if its same then just PostResults

on ajax success you can reload the data or view
and on failure(when no new record) just do PostResults

Body:
I'll preface this with I'm still new to JavaScript.  So problem is in a larger application, our controller is passing in a list of information to the view where certain JavaScript functions rely on certain ViewModel properties.  I've written a simple application to hopefully illustrate what I'm getting at.

Below is a sample controller that's passing in List to the Index page:

    public ActionResult Index() {
        List<int> activeIds = new List<int>();
        SqlConnection sqlConn = new SqlConnection(connection_String);

        sqlConn.Open();

        string sqlStr = "SELECT * FROM dbo.[JS-Test] WHERE Active = 1";
        SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
        SqlDataReader sqlDR = sqlCmd.ExecuteReader();

        if(sqlDR.HasRows) {
            while (sqlDR.Read()) {
                activeIds.Add((int)sqlDR["ID"]);
            }
        }

        sqlDR.Close();
        sqlCmd.Dispose();
        sqlConn.Close();

        return View(activeIds);
    }

This returns the current "active" items in the database. The (rough) view is as follows...

@model List<int>

@{
    ViewBag.Title = "Index";
}

Current Recognized Count: @Model.Count()

Print

The issue is getting the current number of active items from the database when the button is clicked.  Let's say that the user remains idle on the page after it loads for a few minutes.  When their page originally loaded, the model returned 5 items listed as active... but while they've been waiting 3 additional items were switched to active in the database for a total of 8.  However, when the user finally clicks the button it'll submit 5 items instead of the current 8.

I'm unable to run the query to get the current number of active items in the "/Home/PostResults" ActionResult due to the nature of how the larger application is set up.  Is there a way I could refresh the page (getting the updated model) before the rest of the function carries out using values of the refreshed model?

If you have any additional questions, please let me know and I will gladly comply.  I've looked at other questions and answers on SO but I haven't found one that quite works for my situation.  Thanks!

Edit #1

So, I've added this function to the Home controller which just returns the list count as Json.

    public ActionResult GetIds(){
        List<int> activeIds = new List<int>();
        SqlConnection sqlConn = new SqlConnection(connection_String);

        sqlConn.Open();

        string sqlStr = "SELECT * FROM dbo.[JS-Test] WHERE Active = 1";
        SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
        SqlDataReader sqlDR = sqlCmd.ExecuteReader();

        if (sqlDR.HasRows) {
            while (sqlDR.Read()) {
                activeIds.Add((int)sqlDR["ID"]);
            }
        }

        sqlDR.Close();
        sqlCmd.Dispose();
        sqlConn.Close();

        return Json(activeIds.Count());
    }

The view script now looks like this...

I'm currently getting the following error...

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Edit #2

I had to set the JsonRequestBehavior to AllowGet for it to work properly.  Thanks again, everyone!


来源: stackexchange

问:
Office.context.mailbox.item.body is not defined
I am developing Office Addin for outlook, I struct with the following, please kindly help.

Office.context.mailbox.item.body.getAsync() method is working fine in Office 365 , but when it comes to on premise exchange server 2013, it works in outlook client but not works in outlook web app. Minimum mailbox requirement set version is 1.3

答: This is expected. Office.context.mailbox.item.body.getAsync minimum mailbox requirement version is wet to 1.3 level API. In same time according to "Understanding Outlook API requirement sets" the Outlook Web App (Exchange 2013 On-Premise) supports only 1.1 level API.

ContentLicense: CC BY-SA 3.0


问:
Get coords of the intersection of the line in the plane
I have a canvas with this params:
width = 400, height = 400

and have a line passing through the point cursor[x1,y1] at an angle Q (in degree)

I need get all coords of the intersection of the line in the plane and write it to array. Now i use this equation: y - y1 = k * (x - x1)

to check all point I use this code:

var rad = Q * Math.PI/180;

```<code>for (ctrY = 0; ctrY < 400; ctrY += 1) {
    for (ctrX = 0; ctrX < 400; ctrX += 1) {

        if ( (ctrY - cursor.y) ===
              ~~(Math.tan(rad) * (ctrX - cursor.x)) ) {

            z.push([ctrX, ctrY]);
        }

    }
}
</code>```

For example when 0 < Q < 90 and cursor[x1,y1] = [200,200] z.length = 0 and it's not correct.

Where i'm wrong? Maybe there is a more convenient algorithm?

P.S. Sorry for my english

答:
I imagine an algorithm like this. (I only consider the case when 0 < Q < 90). First I will want to calculate the points where the line will intersect the Ox and Oy axes, considering the origin (0,0)  point the upper left corner and if we imagine that the negative x and y values are respectively to the left and to the top of this point. Let x2 and y2 be the values where the line will intersect Ox and Oy. We want to calculate these values. We now have a system with 2 unknown variables (x2 and y2): Math.tan(rad) = (y1 -y2)/x1 and Math.tan(rad) = y1/(x1-x2). We can deduct these equations by drawing the line on the coordinate system and analyzing a bit. If we solve the system of equations we find something like: x2 = (x1*y1 -x1 * x1 * Math.tan(rad)/(2 * y1-x1)) and y2= y1- x1 * Math.tan(rad) (These need to be verified, I haven't double checked my calculus). A linear equation can be defined by the formula y = a*x + b and in our case a = x2 and b = y2. We can then calculate the points like this:

```<code>for (xIdx = 0; xIdx < 400; xIdx += 1) {
    var ctrX = xIdx;
    var ctrY = x2 * ctrX + y2 //todo: replace with the respective calculated variables x2 and y2(we could also define two functions in js) and proper rounding
    z.push([ctrX, ctrY]);
}
</code>```

I'm not sure if I'm 100% accurate but I hope you understand my idea.

Body:
I have a canvas with this params:
width = 400, height = 400

and have a line passing through the point cursor[x1,y1] at an angle Q (in degree)

I need get all coords of the intersection of the line in the plane and write it to array. Now i use this equation: y - y1 = k * (x - x1)

to check all point I use this code:

var rad = Q * Math.PI/180;

for (ctrY = 0; ctrY < 400; ctrY += 1) {
    for (ctrX = 0; ctrX < 400; ctrX += 1) {

        if ( (ctrY - cursor.y) ===
              ~~(Math.tan(rad) * (ctrX - cursor.x)) ) {

            z.push([ctrX, ctrY]);
        }

    }
}

For example when 0 < Q < 90 and cursor[x1,y1] = [200,200] z.length = 0 and it's not correct.

Where i'm wrong? Maybe there is a more convenient algorithm?

P.S. Sorry for my english

Body:
I imagine an algorithm like this. (I only consider the case when 0 < Q < 90). First I will want to calculate the points where the line will intersect the Ox and Oy axes, considering the origin (0,0)  point the upper left corner and if we imagine that the negative x and y values are respectively to the left and to the top of this point. Let x2 and y2 be the values where the line will intersect Ox and Oy. We want to calculate these values. We now have a system with 2 unknown variables (x2 and y2): Math.tan(rad) = (y1 -y2)/x1 and Math.tan(rad) = y1/(x1-x2). We can deduct these equations by drawing the line on the coordinate system and analyzing a bit. If we solve the system of equations we find something like: x2 = (x1*y1 -x1 * x1 * Math.tan(rad)/(2 * y1-x1)) and y2= y1- x1 * Math.tan(rad) (These need to be verified, I haven't double checked my calculus). A linear equation can be defined by the formula y = a*x + b and in our case a = x2 and b = y2. We can then calculate the points like this:

for (xIdx = 0; xIdx < 400; xIdx += 1) {
    var ctrX = xIdx;
    var ctrY = x2 * ctrX + y2 //todo: replace with the respective calculated variables x2 and y2(we could also define two functions in js) and proper rounding
    z.push([ctrX, ctrY]);
}

I'm not sure if I'm 100% accurate but I hope you understand my idea.


问:
Check first element of the array needs to be unique
I have a semicolon separated text file. The idea is to read the text file line by line. Every line will be splitted to an array element.

Now I want to do some checks like is the ID (first element called "Referenz") unique, are all mandatory "fields" filled, etc...

I guess I have to take the ID and put it to an list. And for the next line I have to compare the ID with the IDs from the list?

So question is that the right way and what / how to realise that.

Here is my code so far:

```<code>public class Test_Line2Array {
public static void main(String[] args) {
String strLine = "Referenz;field2;field3;field4;field5;field6;field7;Titel;Name1;Name2;Name3;field8;field9;field10;field11;field12;field13;field14;Street;field15;ZIP;field16;city;field17;dob;field18;field19;field20;field21;field22;field23;field24;field25;field26;field27;field28;field29;field30;field31;field32;field33;field34;field35;field36;field37;field38;field39;phone;mobile;CustomField1;CustomField2;CustomField3;CustomField4;CustomField5;CustomField6;CustomField7;CustomField8;CustomField9;CustomField10";

//declaration
String[] stringArray;
String delimiter = ";";

// allocates memory for 59 strings
stringArray = new String[59];

// split the String after separator ";"
stringArray = strLine.split(";", -1);

// print array
for(int j = 0; j < stringArray.length; j++) {
        System.out.println(j + " " + stringArray[j]);
    }
}
</code>```

答: For each line, put its Referenz in a HashSet. Then checking if a subsequent Referenz is unique would be as simple as referenzSet.contains(theNewReferenz)

Body:
I have a semicolon separated text file. The idea is to read the text file line by line. Every line will be splitted to an array element.

Now I want to do some checks like is the ID (first element called "Referenz") unique, are all mandatory "fields" filled, etc...

I guess I have to take the ID and put it to an list. And for the next line I have to compare the ID with the IDs from the list?

So question is that the right way and what / how to realise that.

Here is my code so far:

public class Test_Line2Array {
public static void main(String[] args) {
String strLine = "Referenz;field2;field3;field4;field5;field6;field7;Titel;Name1;Name2;Name3;field8;field9;field10;field11;field12;field13;field14;Street;field15;ZIP;field16;city;field17;dob;field18;field19;field20;field21;field22;field23;field24;field25;field26;field27;field28;field29;field30;field31;field32;field33;field34;field35;field36;field37;field38;field39;phone;mobile;CustomField1;CustomField2;CustomField3;CustomField4;CustomField5;CustomField6;CustomField7;CustomField8;CustomField9;CustomField10";

//declaration
String[] stringArray;
String delimiter = ";";

// allocates memory for 59 strings
stringArray = new String[59];

// split the String after separator ";"
stringArray = strLine.split(";", -1);

// print array
for(int j = 0; j < stringArray.length; j++) {
        System.out.println(j + " " + stringArray[j]);
    }
}


问:
condition on hql statements
I have som hql statements running every day like

```<code>drop table if exists table1;
create table table1 as
select ....
from A;
</code>```

But some times create table fails and then my original table is¨deleted without a new one is created

I would like to do this a smarter way
like this pseudo code

```<code>if ( create table table1_tmp as
     select ....
     from A; )
then (    drop table table1 ;
          rename table1_tmp to table1 ;
     )
</code>```

Is it possible to do that in hql or do i have to at
pig, spark, python etc.

答:
INSERT OVERWRITE is the best fit for what you are trying to do.

You might want to keep an eye on your HDFS Trash folder because I think the underlying files always move to /user/<username>/.Trash when you perform an INSERT OVERWRITE

Title: condition on hql statements

Body:
I have som hql statements running every day like

drop table if exists table1;
create table table1 as
select ....
from A;

But some times create table fails and then my original table is¨deleted without a new one is created

I would like to do this a smarter way
like this pseudo code

if ( create table table1_tmp as
     select ....
     from A; )
then (    drop table table1 ;
          rename table1_tmp to table1 ;
     )

Is it possible to do that in hql or do i have to at
pig, spark, python etc.


问:
Unable to load JSON
I have the code

```<code>data = open('wg.json', 'r').read()
data_parsed = json.loads(data)
</code>```

And have received the error: ValueError: No JSON object could be decoded

With my JSON file being a python dictionary put into a json file:

```<code>{"wind_degrees":103, "dew_p": "73 F (23 C)", "wind_kph": 5.8}
</code>```

答:
```<code>$ cat wg.json
{"wind_degrees":103, "dew_p": "73 F (23 C)", "wind_kph": 5.8}
$python
>>> import json
>>> data = open('wg.json', 'r').read()
>>> data_parsed = json.loads(data)
>>> data_parsed
{u'wind_degrees': 103, u'wind_kph': 5.8, u'dew_p': u'73 F (23 C)'}
>>>
</code>```

I can't reproduce your problem.  Your code works fine.

Note that you can streamline your code a little:

```<code>with open('wg.json', 'r') as fp:
    data_parsed = json.load(fp)
</code>```

Title: Unable to load JSON

Body:
I have the code

data = open('wg.json', 'r').read()
data_parsed = json.loads(data)

And have received the error: ValueError: No JSON object could be decoded

With my JSON file being a python dictionary put into a json file:

{"wind_degrees":103, "dew_p": "73 F (23 C)", "wind_kph": 5.8}

Body:
$ cat wg.json
{"wind_degrees":103, "dew_p": "73 F (23 C)", "wind_kph": 5.8}
$python
>>> import json
>>> data = open('wg.json', 'r').read()
>>> data_parsed = json.loads(data)
>>> data_parsed
{u'wind_degrees': 103, u'wind_kph': 5.8, u'dew_p': u'73 F (23 C)'}
>>>

I can't reproduce your problem.  Your code works fine.

Note that you can streamline your code a little:

with open('wg.json', 'r') as fp:
    data_parsed = json.load(fp)


问:
Async transactions in javascript
First of all rollback is something that I do not care about.

I would like to be able to lock a sequence of async functions/promises/tasks (let's call it a "transaction") with a name/id (or array of names), so that they happen in sequence, and so that any other "transaction" with the same name(s) that are run by another part of the system are delayed from starting until the running transaction using the same name(s) has completed.  So it basically is queueing the sequences of async tasks, or "transaction"s.

Here is some example code of the situation:

```<code>function a()
{
  // do stuff
  return new Promise(/*...*/);
}

function b()
{
  // do stuff
  return new Promise(/*...*/);
}

function c()
{
  // do stuff
  return a.then(() => b());
}
</code>```

Now at any time the system could call a, b, or c, and when it does I don't want c and b running at the same time, but obvious c depends on b.

I've been looking for a package on npm to help with this but I haven't found anything, I wonder if anyone can suggest something that I might have missed that would help with this?

答:
Use async/await and have babel transpile it. Async Babel Docs</p>

```<code>function a()
{
  // do stuff
  return new Promise(/*...*/);
}

async function b()
{
  const aData = await a();
  // do stuff
  return new Promise(/*...*/);
}

async function c()
{
  const bData = await b();
  // do stuff
  return bData;
}
</code>```

Title: Async transactions in javascript

Body:
First of all rollback is something that I do not care about.

I would like to be able to lock a sequence of async functions/promises/tasks (let's call it a "transaction") with a name/id (or array of names), so that they happen in sequence, and so that any other "transaction" with the same name(s) that are run by another part of the system are delayed from starting until the running transaction using the same name(s) has completed.  So it basically is queueing the sequences of async tasks, or "transaction"s.

Here is some example code of the situation:

function a()
{
  // do stuff
  return new Promise(/*...*/);
}

function b()
{
  // do stuff
  return new Promise(/*...*/);
}

function c()
{
  // do stuff
  return a.then(() => b());
}

Now at any time the system could call a, b, or c, and when it does I don't want c and b running at the same time, but obvious c depends on b.

I've been looking for a package on npm to help with this but I haven't found anything, I wonder if anyone can suggest something that I might have missed that would help with this?

Body:
Use async/await and have babel transpile it. Async Babel Docs

function a()
{
  // do stuff
  return new Promise(/*...*/);
}

async function b()
{
  const aData = await a();
  // do stuff
  return new Promise(/*...*/);
}

async function c()
{
  const bData = await b();
  // do stuff
  return bData;
}


问:
Color legend not consequent in R plotly subplot
I want to make a plotly bar chart of two synchronized variables. Origin is visits of individuals to a site where two properties are measured in time. In this example individual "a" visits the site twice.

Bars should display the measurement value, be ordered in time and colored according to tag (not variable!).

Let's create some data first.

```<code># R version 3.4.0
set.seed(123)
df <- data.frame(id=factor(rep(c("a", "b", "c", "a"), each=10)),
                 time=as.POSIXct(1:40, origin="2017-01-01"),
                 var1=abs(rnorm(40)),
                 var2=abs(rnorm(40)))

# > head(df)
#   id                time        var1      var2
# 1  a 2017-01-01 01:00:01 0.005764186 0.1176466
# 2  a 2017-01-01 01:00:02 0.385280401 0.9474746
# 3  a 2017-01-01 01:00:03 0.370660032 0.4905574
# 4  a 2017-01-01 01:00:04 0.644376549 0.2560922
# 5  a 2017-01-01 01:00:05 0.220486562 1.8438620
# 6  a 2017-01-01 01:00:06 0.331781964 0.6519499
</code>```

Now make two plots of each separate variable, assign to same legend group and hide the legend of the second plot.

```<code>library(plotly) # version 4.7.0
p1 <- plot_ly(df, x=~time, y=~var1, color=~id, type="bar",
              legendgroup=~id)
p2 <- plot_ly(df, x=~time, y=~var2, color=~id, type="bar",
              legendgroup=~id, showlegend=FALSE)
</code>```

Then add both plots to a single plot with shared X axis.

```<code>subplot(p1, p2, shareX=TRUE, nrows=2)
</code>```

I'm not sure how to add an HTML page in an SO question, but the above code should provide a reproducible example. PNGs added below for reference.

Looks good, right? But for some reason, the legend "selector" does not work properly. Deselecting "a" only affects plot 1 (unexpected behavior), while deselecting "c" affects both plots (expected).

What's going on here? Possible bug, or am I missing something?

I'm aware of ggplotly and could get similar plot by using facets. The problem there is that I cannot output a ggplotly HTML that scales with page width (at least not to my knowledge). I want the resulting image to be an HTML that scales with the browser window, which is what plotly does by default.

答:
probably It could be a bug. I noticed reordering the data according to the variable get the right result.
It's not the first time btw, I noticed a similar behaviour</p>

```<code>df<-df[order(df$id),]
library(plotly) # version 4.7.0
p1 <- plot_ly(df, x=~time, y=~var1, color=~id, type="bar",
              legendgroup=~id)
p2 <- plot_ly(df, x=~time, y=~var2, color=~id, type="bar",
              legendgroup=~id, showlegend=FALSE)
subplot(p1, p2, shareX=TRUE, nrows=2)
</code>```

Body:
I want to make a plotly bar chart of two synchronized variables. Origin is visits of individuals to a site where two properties are measured in time. In this example individual "a" visits the site twice.

Bars should display the measurement value, be ordered in time and colored according to tag (not variable!).

Let's create some data first.

# R version 3.4.0
set.seed(123)
df <- data.frame(id=factor(rep(c("a", "b", "c", "a"), each=10)),
                 time=as.POSIXct(1:40, origin="2017-01-01"),
                 var1=abs(rnorm(40)),
                 var2=abs(rnorm(40)))

# > head(df)
#   id                time        var1      var2
# 1  a 2017-01-01 01:00:01 0.005764186 0.1176466
# 2  a 2017-01-01 01:00:02 0.385280401 0.9474746
# 3  a 2017-01-01 01:00:03 0.370660032 0.4905574
# 4  a 2017-01-01 01:00:04 0.644376549 0.2560922
# 5  a 2017-01-01 01:00:05 0.220486562 1.8438620
# 6  a 2017-01-01 01:00:06 0.331781964 0.6519499

Now make two plots of each separate variable, assign to same legend group and hide the legend of the second plot.

library(plotly) # version 4.7.0
p1 <- plot_ly(df, x=~time, y=~var1, color=~id, type="bar",
              legendgroup=~id)
p2 <- plot_ly(df, x=~time, y=~var2, color=~id, type="bar",
              legendgroup=~id, showlegend=FALSE)

Then add both plots to a single plot with shared X axis.

subplot(p1, p2, shareX=TRUE, nrows=2)

I'm not sure how to add an HTML page in an SO question, but the above code should provide a reproducible example. PNGs added below for reference.

Looks good, right? But for some reason, the legend "selector" does not work properly. Deselecting "a" only affects plot 1 (unexpected behavior), while deselecting "c" affects both plots (expected).

What's going on here? Possible bug, or am I missing something?

I'm aware of ggplotly and could get similar plot by using facets. The problem there is that I cannot output a ggplotly HTML that scales with page width (at least not to my knowledge). I want the resulting image to be an HTML that scales with the browser window, which is what plotly does by default.

Body:
probably It could be a bug. I noticed reordering the data according to the variable get the right result.
It's not the first time btw, I noticed a similar behaviour

df<-df[order(df$id),]
library(plotly) # version 4.7.0
p1 <- plot_ly(df, x=~time, y=~var1, color=~id, type="bar",
              legendgroup=~id)
p2 <- plot_ly(df, x=~time, y=~var2, color=~id, type="bar",
              legendgroup=~id, showlegend=FALSE)
subplot(p1, p2, shareX=TRUE, nrows=2)


问:
Update source and sink dynamically in cycle js?
I'm writing a very simple app using redux-cycle, with 3 elements:

A text field to input url

A "connect" button to connect to a websocket end point

An output panel to show incoming messages

I have written a very simple websocket driver based on this answer https://stackoverflow.com/a/42926532/842860

The wire up code is like this:

const cycleMiddleware = createCycleMiddleware();
const {makeActionDriver} = cycleMiddleware;

function main(sources) {
    return {
        ACTION: sources.WEBSOCKET // The websocket driver emits commands which are consumed by reducers
    }
}

const store = createStore(
    reducer, // Update redux state
    applyMiddleware(cycleMiddleware)
);

run(main, {
    WEBSOCKET: WSDriver("ws://localhost:3000/something"), // The initial connection string
    ACTION: makeActionDriver()
});
```

The question is how to make the websocket reconnect to another end point when the connect button is clicked?  Do I need to modify my websocket driver to capture the event and reconnect, or does cyclejs provide a way to dynamically update the source/sink?

答:
I think the appropriate method would be to, indeed, update the WSDriver to take a sink$ as input. This sink$ could contain the url you want to connect to.

Your driver would look like this

```<code>function WSDriver(endpoint$) {
  var activeConnection;
  return endpoint$
    .map(endpointUrl => xs.create({
      start: listener => {
       activeConnection = new WebSocket('ws://localhost:4000');
       /* no change here */
      },
      stop: () => {
        activeConnection.close();
      }
    }))
    .flatten() // it's a stream of stream, so we need to flatten it
}
</code>```

On the app side you would need to change this

```<code>run(main, {
    WEBSOCKET: WSDriver(), // < no initial connection
    ACTION: makeActionDriver()
});
</code>```

And in your main

```<code>function main(sources) {
    return {
        ACTION: sources.WEBSOCKET,
        WEBSOCKET: newConnection$.startWith("ws://localhost:3000/something")
    }
}
</code>```

Given that the newConnection$ comes from the click events on the button.

Hope it helps

Body:
I'm writing a very simple app using redux-cycle, with 3 elements:

A text field to input url

A "connect" button to connect to a websocket end point

An output panel to show incoming messages

I have written a very simple websocket driver based on this answer https://stackoverflow.com/a/42926532/842860

The wire up code is like this:

const cycleMiddleware = createCycleMiddleware();
const {makeActionDriver} = cycleMiddleware;

function main(sources) {
    return {
        ACTION: sources.WEBSOCKET // The websocket driver emits commands which are consumed by reducers
    }
}

const store = createStore(
    reducer, // Update redux state
    applyMiddleware(cycleMiddleware)
);

run(main, {
    WEBSOCKET: WSDriver("ws://localhost:3000/something"), // The initial connection string
    ACTION: makeActionDriver()
});

The question is how to make the websocket reconnect to another end point when the connect button is clicked?  Do I need to modify my websocket driver to capture the event and reconnect, or does cyclejs provide a way to dynamically update the source/sink?

Body:
I think the appropriate method would be to, indeed, update the WSDriver to take a sink$ as input. This sink$ could contain the url you want to connect to.

Your driver would look like this

function WSDriver(endpoint$) {
  var activeConnection;
  return endpoint$
    .map(endpointUrl => xs.create({
      start: listener => {
       activeConnection = new WebSocket('ws://localhost:4000');
       /* no change here */
      },
      stop: () => {
        activeConnection.close();
      }
    }))
    .flatten() // it's a stream of stream, so we need to flatten it
}

On the app side you would need to change this

run(main, {
    WEBSOCKET: WSDriver(), // < no initial connection
    ACTION: makeActionDriver()
});

And in your main

function main(sources) {
    return {
        ACTION: sources.WEBSOCKET,
        WEBSOCKET: newConnection$.startWith("ws://localhost:3000/something")
    }
}

Given that the newConnection$ comes from the click events on the button.

Hope it helps


问:
using the 'is' keyword in a switch in c#
I'm currently adding some new extended classes to this code:

```<code>foreach (BaseType b in CollectionOfExtendedTypes) {
  if (b is ExtendedType1) {
    ((ExtendedType1) b).foo = this;

  }
  else if (b is ExtendedType2) {
    ((ExtenedType2) b).foo = this;

  }
  else {
    b.foo = this;

  }
}
</code>```

and was curious if there is a way to use the is keyword functionality in a switch statement?

答:
Type-cases and object oriented code don't seem to get on that well together in my experience.  The approach I prefer in this situation is the double dispatch pattern.  In short:

Create a listener type with an empty virtual method Process(ExtendedTypeN arg) for each extended type you will be dispatching over.

Add a virtual method Dispatch(Listener listener) to the base type that takes a listener as argument.  Its implementation will be to call listener.Process((Base) this).

Override the Dispatch method in each extended type to call the appropriate overload of Process in the listener type.

Extend the listener type by overriding the appropriate Process method for each subtype you are interested in.

The argument shuffling dance eliminates the narrowing cast by folding it into the call to Dispatch -- the receiver knows its exact type, and communicates it by calling back the exact overload of Process for its type.  This is also a big performance win in implementations such as .NET Compact Framework, in which narrowing casts are extremely slow but virtual dispatch is fast.

The result will be something like this:

```<code>
public class Listener
{
    public virtual void Process(Base obj) { }
    public virtual void Process(Derived obj) { }
    public virtual void Process(OtherDerived obj) { }
}

public class Base
{
    public virtual void Dispatch(Listener l) { l.Process(this); }
}

public class Derived
{
    public override void Dispatch(Listener l) { l.Process(this); }
}

public class OtherDerived
{
    public override void Dispatch(Listener l) { l.Process(this); }
}

public class ExampleListener
{
    public override void Process(Derived obj)
    {
        Console.WriteLine("I got a Derived");
    }

    public override void Process(OtherDerived obj)
    {
        Console.WriteLine("I got an OtherDerived");
    }

    public void ProcessCollection(IEnumerable collection)
    {
        foreach (Base obj in collection) obj.Dispatch(this);
    }
}
</code>```

OwnerDisplayName: sre

ContentLicense: CC BY-SA 2.5

Body:
I'm currently adding some new extended classes to this code:

foreach (BaseType b in CollectionOfExtendedTypes) {
  if (b is ExtendedType1) {
    ((ExtendedType1) b).foo = this;

  }
  else if (b is ExtendedType2) {
    ((ExtenedType2) b).foo = this;

  }
  else {
    b.foo = this;

  }
}

and was curious if there is a way to use the is keyword functionality in a switch statement?

LastEditorDisplayName: Matt J

Body:
Type-cases and object oriented code don't seem to get on that well together in my experience.  The approach I prefer in this situation is the double dispatch pattern.  In short:

Create a listener type with an empty virtual method Process(ExtendedTypeN arg) for each extended type you will be dispatching over.

Add a virtual method Dispatch(Listener listener) to the base type that takes a listener as argument.  Its implementation will be to call listener.Process((Base) this).

Override the Dispatch method in each extended type to call the appropriate overload of Process in the listener type.

Extend the listener type by overriding the appropriate Process method for each subtype you are interested in.

The argument shuffling dance eliminates the narrowing cast by folding it into the call to Dispatch -- the receiver knows its exact type, and communicates it by calling back the exact overload of Process for its type.  This is also a big performance win in implementations such as .NET Compact Framework, in which narrowing casts are extremely slow but virtual dispatch is fast.

The result will be something like this:

public class Listener
{
    public virtual void Process(Base obj) { }
    public virtual void Process(Derived obj) { }
    public virtual void Process(OtherDerived obj) { }
}

public class Base
{
    public virtual void Dispatch(Listener l) { l.Process(this); }
}

public class Derived
{
    public override void Dispatch(Listener l) { l.Process(this); }
}

public class OtherDerived
{
    public override void Dispatch(Listener l) { l.Process(this); }
}

public class ExampleListener
{
    public override void Process(Derived obj)
    {
        Console.WriteLine("I got a Derived");
    }

    public override void Process(OtherDerived obj)
    {
        Console.WriteLine("I got an OtherDerived");
    }

    public void ProcessCollection(IEnumerable collection)
    {
        foreach (Base obj in collection) obj.Dispatch(this);
    }
}

OwnerDisplayName: Jeffrey Hantin


问:
How to get the percentage of apt get output through regex?
Can someone please help me with a regular expression to get the percentage from the below bash output through regex?

```<code>Get:11 http://us.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 libvlc$

Get:12 http://us.archive.ubuntu.com/ubuntu xenial/main amd64 fonts-freefont-ttf$

40% [12 fonts-freefont-ttf 855 kB/4,140 kB 21%]
</code>```

I just need to get the 40% from the above example..

Thanks.

答:
```<code> awk '$1 ~ /[[:digit:]]{1,3}%/ { print $1 }'
</code>```

Check that the first delimited piece of the line pattern matches to 1-3 digits followed by a %. If it does, print the first piece.

Body:
Can someone please help me with a regular expression to get the percentage from the below bash output through regex?

Get:11 http://us.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 libvlc$

Get:12 http://us.archive.ubuntu.com/ubuntu xenial/main amd64 fonts-freefont-ttf$

40% [12 fonts-freefont-ttf 855 kB/4,140 kB 21%]

I just need to get the 40% from the above example..

Thanks.

Body:
 awk '$1 ~ /[[:digit:]]{1,3}%/ { print $1 }'

Check that the first delimited piece of the line pattern matches to 1-3 digits followed by a %. If it does, print the first piece.


问:
How to bottom-align an element inside a flex item?
I have a flex container with three flex items and inside each item a link that should be aligned on the bottom (all links bottom middle aligned).

Flex-items are stretched and do not have a fix height, same as flex container. Thanks!

.flex-container {
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  -ms-flex-direction: row;
  flex-direction: row;
  -webkit-flex-wrap: nowrap;
  -ms-flex-wrap: nowrap;
  flex-wrap: nowrap;
  -webkit-justify-content: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-align-content: flex-start;
  -ms-flex-line-pack: start;
  align-content: flex-start;
  -webkit-align-items: flex-start;
  -ms-flex-align: start;
  align-items: flex-start;
}

.flex-item {
  -webkit-order: 0;
  -ms-flex-order: 0;
  order: 0;
  -webkit-flex: 1 0 0;
  -ms-flex: 1 0 0;
  flex: 1 0 0;
  -webkit-align-self: stretch;
  -ms-flex-item-align: stretch;
  align-self: stretch;
  padding: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="main-section">
  <div class="container">
    <div class="flex-container">
      <div class="flex-item">
        <p class="subTitle">Titel</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus. Sed pellentesque non arcu et interdum. Aenean venenatis, ipsum a viverra interdum, neque nisl tincidunt
          arcu, non vulputate justo metus nec quam. Nullam blandit, purus id pretium congue, turpis diam semper sapien, vel suscipit est velit eget leo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent
          consequat urna quis commodo varius. Praesent hendrerit at augue in fermentum. Ut sed dolor blandit, lacinia orci eget, ultrices elit. Nulla luctus, risus eu viverra eleifend, leo orci posuere nulla, ut vestibulum orci metus in nisi. Aenean et
          porttitor lacus.</p>
        Link
      </div>
      <div class="flex-item">
        <p class="subTitle">Titel</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus.</p>
        Link
      </div>
      <div class="flex-item">
        <p class="subTitle">Titel</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus. Sed pellentesque non arcu et interdum. Aenean venenatis, ipsum a viverra interdum, neque nisl tincidunt
          arcu, non vulputate justo metus nec quam. Nullam blandit, purus id pretium congue, turpis diam semper sapien, vel suscipit est velit eget leo.</p>
        Link
      </div>
    </div>
  </div>
</section></code>```

https://jsfiddle.net/ABoooo/dns5zr1p/

答:
First, remove align-items: flex-start from the container. That's overriding the stretch default, so the columns are not stretching the full height of the container. They are only as high as their content.

Second, make your flex items into (nested) flex containers with flex-direction: column. You can then use an auto margin on the link to fix it to the bottom.

.flex-container {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: center;
  align-content: flex-start;
  /* align-items: flex-start; <--------- REMOVE */
}

.flex-item {
  flex: 1 0 0;
  padding: 15px;

  display: flex;                /* NEW */
  flex-direction: column;       /* NEW */
}

.flex-item > a {
  margin-top: auto;             /* NEW */
  align-self: center;           /* NEW (optional; horizontal centering) */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="main-section">
  <div class="container">
    <div class="flex-container">
      <div class="flex-item">
        <p class="subTitle">Titel</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus. Sed pellentesque non arcu et interdum. Aenean venenatis, ipsum a viverra interdum, neque nisl tincidunt
          arcu, non vulputate justo metus nec quam. Nullam blandit, purus id pretium congue, turpis diam semper sapien, vel suscipit est velit eget leo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent
          consequat urna quis commodo varius. Praesent hendrerit at augue in fermentum. Ut sed dolor blandit, lacinia orci eget, ultrices elit. Nulla luctus, risus eu viverra eleifend, leo orci posuere nulla, ut vestibulum orci metus in nisi. Aenean et
          porttitor lacus.</p>
        Link
      </div>
      <div class="flex-item">
        <p class="subTitle">Titel</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus.</p>
        Link
      </div>
      <div class="flex-item">
        <p class="subTitle">Titel</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus. Sed pellentesque non arcu et interdum. Aenean venenatis, ipsum a viverra interdum, neque nisl tincidunt
          arcu, non vulputate justo metus nec quam. Nullam blandit, purus id pretium congue, turpis diam semper sapien, vel suscipit est velit eget leo.</p>
        Link
      </div>
    </div>
  </div>
</section></code>```

revised fiddle

More info on flex auto margins:

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

Body:
I have a flex container with three flex items and inside each item a link that should be aligned on the bottom (all links bottom middle aligned).

Flex-items are stretched and do not have a fix height, same as flex container. Thanks!

.flex-container {
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  -ms-flex-direction: row;
  flex-direction: row;
  -webkit-flex-wrap: nowrap;
  -ms-flex-wrap: nowrap;
  flex-wrap: nowrap;
  -webkit-justify-content: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-align-content: flex-start;
  -ms-flex-line-pack: start;
  align-content: flex-start;
  -webkit-align-items: flex-start;
  -ms-flex-align: start;
  align-items: flex-start;
}

.flex-item {
  -webkit-order: 0;
  -ms-flex-order: 0;
  order: 0;
  -webkit-flex: 1 0 0;
  -ms-flex: 1 0 0;
  flex: 1 0 0;
  -webkit-align-self: stretch;
  -ms-flex-item-align: stretch;
  align-self: stretch;
  padding: 15px;
}

Titel

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus. Sed pellentesque non arcu et interdum. Aenean venenatis, ipsum a viverra interdum, neque nisl tincidunt
          arcu, non vulputate justo metus nec quam. Nullam blandit, purus id pretium congue, turpis diam semper sapien, vel suscipit est velit eget leo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent
          consequat urna quis commodo varius. Praesent hendrerit at augue in fermentum. Ut sed dolor blandit, lacinia orci eget, ultrices elit. Nulla luctus, risus eu viverra eleifend, leo orci posuere nulla, ut vestibulum orci metus in nisi. Aenean et
          porttitor lacus.

        Link

Titel

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus.

        Link

Titel

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus. Sed pellentesque non arcu et interdum. Aenean venenatis, ipsum a viverra interdum, neque nisl tincidunt
          arcu, non vulputate justo metus nec quam. Nullam blandit, purus id pretium congue, turpis diam semper sapien, vel suscipit est velit eget leo.

        Link

https://jsfiddle.net/ABoooo/dns5zr1p/

Body:
First, remove align-items: flex-start from the container. That's overriding the stretch default, so the columns are not stretching the full height of the container. They are only as high as their content.

Second, make your flex items into (nested) flex containers with flex-direction: column. You can then use an auto margin on the link to fix it to the bottom.

.flex-container {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: center;
  align-content: flex-start;
  /* align-items: flex-start; <--------- REMOVE */
}

.flex-item {
  flex: 1 0 0;
  padding: 15px;

  display: flex;                /* NEW */
  flex-direction: column;       /* NEW */
}

.flex-item > a {
  margin-top: auto;             /* NEW */
  align-self: center;           /* NEW (optional; horizontal centering) */
}

<section class="main-section">
  <div class="container">
    <div class="flex-container">
      <div class="flex-item">
        <p class="subTitle">Titel</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus. Sed pellentesque non arcu et interdum. Aenean venenatis, ipsum a viverra interdum, neque nisl tincidunt
          arcu, non vulputate justo metus nec quam. Nullam blandit, purus id pretium congue, turpis diam semper sapien, vel suscipit est velit eget leo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent
          consequat urna quis commodo varius. Praesent hendrerit at augue in fermentum. Ut sed dolor blandit, lacinia orci eget, ultrices elit. Nulla luctus, risus eu viverra eleifend, leo orci posuere nulla, ut vestibulum orci metus in nisi. Aenean et
          porttitor lacus.</p>
        <a href="#">Link</a>
      </div>
      <div class="flex-item">
        <p class="subTitle">Titel</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus.</p>
        <a href="#">Link</a>
      </div>
      <div class="flex-item">
        <p class="subTitle">Titel</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus. Sed pellentesque non arcu et interdum. Aenean venenatis, ipsum a viverra interdum, neque nisl tincidunt
          arcu, non vulputate justo metus nec quam. Nullam blandit, purus id pretium congue, turpis diam semper sapien, vel suscipit est velit eget leo.</p>
        <a href="#">Link</a>
      </div>
    </div>
  </div>
</section>

revised fiddle

More info on flex auto margins:

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?


问:
How to use Gitlab CI to build a Java Maven project?
I have been experimenting with no success whatsoever, I am running a Gitlab hosted on Linux, and trying to get my head around the CI functionality.

According to the Gitlab documentation you only need to create a .gitlab-ci.yml file, the Gitlab implementation of Travis-CI. Now from the looks of it you can accomplish a lot with the .gitlab-ci.yml, but a lot of the documentation is referencing Ruby and other languages. Nothing is said about how to build Java Maven projects.

How can I build a simple application in Java? Can I use the shared runner, or should I be using a specific runner, in that case what or which runner implementation should I choose: ssh, docker, or shell? Then, what should I put in the .gitlab-ci.yml file at least to build the project with Maven?

答:
I spent a fair amount of time trying to set up our Java projects on Gitlab CI. I got it working with some degree of success. As mentioned by rolve, the most straight forward solution is to use an image from the official repo:  https://hub.docker.com/_/maven

However, we have a corporate proxy which was causing my builds to get timeout requests when fetching the project's dependencies. I tried many solutions and finally came across this post: https://gitlab.com/gitlab-org/gitlab-ce/issues/15167.

The post itself is about setting up maven to cache downloaded dependencies in a local repo which can be accessed among builds. The idea is that you can write a local maven configuration file by in .gitlab-ci.yml to set up your cache directory and your proxy.

```<code>before_script:
  -echo '<settings
          xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
          https://maven.apache.org/xsd/settings-1.0.0.xsd">
          <localRepository>/cache/.m2</localRepository>
          <proxies>
              <proxy>
                  <active>true</active>
                  <protocol>'$PROXY_PROTOCOL'</protocol>
                  <host>'$PROXY_HOST'</host>
                  <port>'$PROXY_PORT'</port>
              </proxy>
          </proxies>
      </settings>' > $HOME/.m2/settings.xml

build_debug1:
  stage: build
  script: "echo $PROXY_HOST"

build_debug2:
  stage: build
  script: "cat $HOME/.m2/settings.xml"

build_maven:
  stage: build
  script: "mvn $MAVEN_CLI_OPTS package"
  artifacts:
    paths:
      - target/*.jar

deploy_debug1:
  stage: package
  script: "ls target/"
</code>```

Notice the build debug jobs are only to see whether the proxy settings were being correctly injected. You can set the proxy environment variables as secrets using Gitlab by going to Project -> Settings -> CI/CD Pipelines -> Secret Variables.

The last deploy_debug job is to see what was generated in your target directory.

Body:
I spent a fair amount of time trying to set up our Java projects on Gitlab CI. I got it working with some degree of success. As mentioned by rolve, the most straight forward solution is to use an image from the official repo:  https://hub.docker.com/_/maven

However, we have a corporate proxy which was causing my builds to get timeout requests when fetching the project's dependencies. I tried many solutions and finally came across this post: https://gitlab.com/gitlab-org/gitlab-ce/issues/15167.

The post itself is about setting up maven to cache downloaded dependencies in a local repo which can be accessed among builds. The idea is that you can write a local maven configuration file by in .gitlab-ci.yml to set up your cache directory and your proxy.

before_script:
  -echo '<settings
          xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
          https://maven.apache.org/xsd/settings-1.0.0.xsd">
          <localRepository>/cache/.m2</localRepository>
          <proxies>
              <proxy>
                  <active>true</active>
                  <protocol>'$PROXY_PROTOCOL'</protocol>
                  <host>'$PROXY_HOST'</host>
                  <port>'$PROXY_PORT'</port>
              </proxy>
          </proxies>
      </settings>' > $HOME/.m2/settings.xml

build_debug1:
  stage: build
  script: "echo $PROXY_HOST"

build_debug2:
  stage: build
  script: "cat $HOME/.m2/settings.xml"

build_maven:
  stage: build
  script: "mvn $MAVEN_CLI_OPTS package"
  artifacts:
    paths:
      - target/*.jar

deploy_debug1:
  stage: package
  script: "ls target/"

Notice the build debug jobs are only to see whether the proxy settings were being correctly injected. You can set the proxy environment variables as secrets using Gitlab by going to Project -> Settings -> CI/CD Pipelines -> Secret Variables.

The last deploy_debug job is to see what was generated in your target directory.


问:
How to open visual studio code from url
I'm followed this to open a file from a URL in Visual Studio Code already provided:

And this is how I do it in my file:

```<code><a href="vscode:/file/Users/abc/Desktop/about.html">Launch VS Code</a>
</code>```

This opens the visual studio code but doesn't open the file.

What I need is to open the file in the editor along with the project in the IDE. Is there a way anyone knows to do this? Thanks in advance!

答: It looks like you're missing a forward slash - vscode://file vs vscode:/file.

Title: How to open visual studio code from url

Body:
I'm followed this to open a file from a URL in Visual Studio Code already provided:

And this is how I do it in my file:

Launch VS Code

This opens the visual studio code but doesn't open the file.

What I need is to open the file in the editor along with the project in the IDE. Is there a way anyone knows to do this? Thanks in advance!


问:
linq to sql optimized a group with multiple joins
I need help generating a more efficient LINQ query:

```<code>Table: Positions
-PositionID
-Name

Table: Person
-PersonID
-Name, etc...

Table: PersonPosition
-PersonID
-PositionID
</code>```

I need a result set that groups the people assigned to each position:

```<code>PositionID  Person
1           John
            Bob
            Frank

2           Bill
            Tom
            Frank, etc...
</code>```

My first thought was this LINQ query:

```<code>from perspos in PersonPositions
join pers in Persons            on perspos.PersonID equals pers.PersonID
group pers by perspos.PositionID into groups
select new {groups.Key, groups}
</code>```

Which works great, but produces the following SQL:

```<code>SELECT [t0].[PositionID] AS [Key]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
GROUP BY [t0].[PositionID]
GO

-- Region Parameters
DECLARE @x1 Int = 3
-- EndRegion
SELECT [t1].[PersonID], [t1].[UserID], [t1].[Firstname], [t1].[Lastname], [t1].[Email], [t1].[Phone], [t1].[Mobile], [t1].[Comment], [t1].[Permissions]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
WHERE @x1 = [t0].[PositionID]
GO

-- Region Parameters
DECLARE @x1 Int = 4
-- EndRegion
SELECT [t1].[PersonID], [t1].[UserID], [t1].[Firstname], [t1].[Lastname], [t1].[Email], [t1].[Phone], [t1].[Mobile], [t1].[Comment], [t1].[Permissions]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
WHERE @x1 = [t0].[PositionID]
GO

-- Region Parameters
DECLARE @x1 Int = 5
-- EndRegion
SELECT [t1].[PersonID], [t1].[UserID], [t1].[Firstname], [t1].[Lastname], [t1].[Email], [t1].[Phone], [t1].[Mobile], [t1].[Comment], [t1].[Permissions]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
WHERE @x1 = [t0].[PositionID]
GO

on and on...
</code>```

Is there a better LINQ query that translates to a more efficient SQL statement?

答:
You should already have the relationship defined in your database, and also on your dbml.

Avoid doing joins when you don't have to; they are really tedious.  Let LINQ-to-SQL do this for you.  Something like this should work:

```<code>var data = context.PersonPositions
    .Select(pos => new { pos.PositionID, pos.Person });
return data.GroupBy(pos => pos.PositionID);
</code>```

or

```<code>return context.Positions.Select(pos =>
    new { pos, pos.PersonPositions.Select(pp => pp.Person).ToList() }).ToList();
</code>```

Body:
I need help generating a more efficient LINQ query:

Table: Positions
-PositionID
-Name

Table: Person
-PersonID
-Name, etc...

Table: PersonPosition
-PersonID
-PositionID

I need a result set that groups the people assigned to each position:

PositionID  Person
1           John
            Bob
            Frank

2           Bill
            Tom
            Frank, etc...

My first thought was this LINQ query:

from perspos in PersonPositions
join pers in Persons            on perspos.PersonID equals pers.PersonID
group pers by perspos.PositionID into groups
select new {groups.Key, groups}

Which works great, but produces the following SQL:

SELECT [t0].[PositionID] AS [Key]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
GROUP BY [t0].[PositionID]
GO

-- Region Parameters
DECLARE @x1 Int = 3
-- EndRegion
SELECT [t1].[PersonID], [t1].[UserID], [t1].[Firstname], [t1].[Lastname], [t1].[Email], [t1].[Phone], [t1].[Mobile], [t1].[Comment], [t1].[Permissions]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
WHERE @x1 = [t0].[PositionID]
GO

-- Region Parameters
DECLARE @x1 Int = 4
-- EndRegion
SELECT [t1].[PersonID], [t1].[UserID], [t1].[Firstname], [t1].[Lastname], [t1].[Email], [t1].[Phone], [t1].[Mobile], [t1].[Comment], [t1].[Permissions]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
WHERE @x1 = [t0].[PositionID]
GO

-- Region Parameters
DECLARE @x1 Int = 5
-- EndRegion
SELECT [t1].[PersonID], [t1].[UserID], [t1].[Firstname], [t1].[Lastname], [t1].[Email], [t1].[Phone], [t1].[Mobile], [t1].[Comment], [t1].[Permissions]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
WHERE @x1 = [t0].[PositionID]
GO

on and on...

Is there a better LINQ query that translates to a more efficient SQL statement?

Body:
You should already have the relationship defined in your database, and also on your dbml.

Avoid doing joins when you don't have to; they are really tedious.  Let LINQ-to-SQL do this for you.  Something like this should work:

var data = context.PersonPositions
    .Select(pos => new { pos.PositionID, pos.Person });
return data.GroupBy(pos => pos.PositionID);

or

return context.Positions.Select(pos =>
    new { pos, pos.PersonPositions.Select(pp => pp.Person).ToList() }).ToList();


问:
Library and examples of parsing multipart/form-data from inputstream
The response to one kind of HTTP request I send is a multipart/form-data looks something like:

```<code>--------boundary123
Content-Disposition: form-data; name="json"
Content-Type: application/json

{"some":"json"}
--------boundary123
Content-Disposition: form-data; name="bin"
Content-Type: application/octet-stream

<file data>

--------boundary123
</code>```

I've been using apache to send and receive the HTTP requests, but I can't seem to find an easy way to use it to parse the above for easy access of the form fields.

I would prefer not to reinvent the wheel, so I'm looking for a library that allows me to do something similar to:

```<code>MultipartEntity multipart = new MultipartEntity(inputStream);
InputStream bin = multipart.get("bin");
</code>```

Any suggestions?

答:
Example code without using deprecated methods.</p>

```<code>import com.google.common.net.MediaType;
import org.apache.commons.fileupload.RequestContext;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

public class SimpleRequestContext implements RequestContext {
    private final Charset charset;
    private final MediaType contentType;
    private final byte[] content;

    public SimpleRequestContext(Charset charset, MediaType contentType, byte[] content) {
        this.charset = charset;
        this.contentType = contentType;
        this.content = content;
    }

    public String getCharacterEncoding() {
        return charset.displayName();
    }

    public String getContentType() {
        return contentType.toString();
    }

    @Deprecated
    public int getContentLength() {
        return content.length;
    }

    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(content);
    }
}

{
  ...
  Charset encoding = UTF_8;
  RequestContext requestContext = new SimpleRequestContext(encoding, contentType, body.getBytes());
  FileUploadBase fileUploadBase = new PortletFileUpload();
  FileItemFactory fileItemFactory = new DiskFileItemFactory();
  fileUploadBase.setFileItemFactory(fileItemFactory);
  fileUploadBase.setHeaderEncoding(encoding.displayName());
  List<FileItem> fileItems = fileUploadBase.parseRequest(requestContext);
  ...
}
</code>```

Body:
The response to one kind of HTTP request I send is a multipart/form-data looks something like:

--------boundary123
Content-Disposition: form-data; name="json"
Content-Type: application/json

{"some":"json"}
--------boundary123
Content-Disposition: form-data; name="bin"
Content-Type: application/octet-stream

<file data>

--------boundary123

I've been using apache to send and receive the HTTP requests, but I can't seem to find an easy way to use it to parse the above for easy access of the form fields.

I would prefer not to reinvent the wheel, so I'm looking for a library that allows me to do something similar to:

MultipartEntity multipart = new MultipartEntity(inputStream);
InputStream bin = multipart.get("bin");

Any suggestions?

Body:
Example code without using deprecated methods.

import com.google.common.net.MediaType;
import org.apache.commons.fileupload.RequestContext;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

public class SimpleRequestContext implements RequestContext {
    private final Charset charset;
    private final MediaType contentType;
    private final byte[] content;

    public SimpleRequestContext(Charset charset, MediaType contentType, byte[] content) {
        this.charset = charset;
        this.contentType = contentType;
        this.content = content;
    }

    public String getCharacterEncoding() {
        return charset.displayName();
    }

    public String getContentType() {
        return contentType.toString();
    }

    @Deprecated
    public int getContentLength() {
        return content.length;
    }

    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(content);
    }
}

{
  ...
  Charset encoding = UTF_8;
  RequestContext requestContext = new SimpleRequestContext(encoding, contentType, body.getBytes());
  FileUploadBase fileUploadBase = new PortletFileUpload();
  FileItemFactory fileItemFactory = new DiskFileItemFactory();
  fileUploadBase.setFileItemFactory(fileItemFactory);
  fileUploadBase.setHeaderEncoding(encoding.displayName());
  List<FileItem> fileItems = fileUploadBase.parseRequest(requestContext);
  ...
}

ContentLicense: CC BY-SA 4.0


问:
Can same GUID produce different hash codes?
Given same GUID Object.GetHashCode produces different hash codes but Object.Equals shows that same GUID equals.

The whole GUID:

Not same hash code:

Equals == true:

And, obviously, both are System.Guid:

Even when it's the same GUID, they're different values as they are deserialized from two sources.

Is this the expected behavior?

答:
Your test is incorrect. In the final part where you're comparing the .GetType().FullName, you are looking at the .Id, but that is not what you are comparing above that.

So: the problem is in whatever the type is that has a .Id, the thing that is in tags and existingTags. Look at the Equals and GetHashCode of that.


问:
Unit Testing: How to verify and mock onCompleted for an Observable in RxJava within Android
I am trying to write some unit tests for an Android application that is using Retrofit 2, Mockito 1.10 and RXJava 1.0. I am not using a java version that supports lambdas!

My code uses Observables and I can do the following:

```<code>when(myAPI.Complete(anyString(), any(MyContainer.class)))
        .thenReturn(Observable.<GenericResponse>error(new Throwable("An error has occurred!")));

Subscriber genericResponseSubscriber = mock(Subscriber.class);

myPresenter.myUseCase(id, container, genericResponseSubscriber);

verify(genericResponseSubscriber, times(1)).onError(any(Throwable.class));
</code>```

The above code works fine and allows me to throw an error and capture it within the test.

What I need to be able to do as well (of course) :) is to capture positive conditions. I feel like it's obvious but can't find the answer I need.

How can I capture onComplete and onNext cases ?

I know that the verification for onComplete would be...

verify(genericResponseSubscriber, times(1)).onCompleted();

But I can't see what my 'when' clause should be. I tried the following but that fails:

```<code>GenericResponse response = new GenericResponse();
response.setSuccess(true);

when(myAPI.orderComplete(anyString(), any(MyContainer.class)))
        .thenReturn(Observable.just(response));

Subscriber genericResponseSubscriber = mock(Subscriber.class);

myPresenter.myUseCase(id, container, genericResponseSubscriber);

verify(genericResponseSubscriber, times(1)).onCompleted();
</code>```

The failure here is that subscriber.onStart() was instead called.

So, what I would like to know is, how I can mock and verify the 'onComplete' and 'onNext' calls, please and more importantly what I should have looked to be able to have resolved this myself rather than having to ask! :)

As always, any help is appreciated.

Edit..

My onError working test case..

```<code>    public void UseCaseOnError() throws Exception {

     String id = "5";

     order Order = new Order();

     SomeContainer myContainer = new SomeContainer(order);

     when(myRetroFitAPI.complete(anyString(), any(SomeContainer.class)))
</code>```

.thenReturn(Observable.error(new Throwable(“My error!")));

```<code>     Subscriber genericResponseSubscriber = mock(Subscriber.class);

     orderPresenter.doUseCase(id, myContainer, genericResponseSubscriber);

     verify(genericResponseSubscriber,times(1)).onError(any(Throwable.class));

}
</code>```

What I should really add is that, I feel there should be an equivalent for onError in terms of a positive state, i.e. onCompleted. If I do the same but with onCompleted instead, my verification fails as it detects onStart has been called instead which I am finding rather confusing.

I have tried using the ReplaySubject as such:

```<code>public void createOrderOnCompleteError() {
    orderOnCompleteSubject.onError(new Throwable("I am an error"));
}

public void createOrderOnCompleteSuccess() {
    orderOnCompleteSubject.onNext(new GenericResponse().setSuccess(true));
    orderOnCompleteSubject.onCompleted();
}
</code>```

The error mechanism works fine.. the completed mechanism does not...

答:
You should use the class TestObserver for testing the Observable, in this way:

```<code>public Observable<Integer> getObservable() {
     return Observable.just(12, 20, 330);
}

@Test
public void testObservable() {
     Observable<Integer> obs = getObservable();
     TestObserver<Integer> testObserver = TestObserver.create();
     obs.subscribe(testObserver);

     testObserver.assertComplete();
     testObserver.assertResult(12, 20, 330);
 }
</code>```

In this way you can verify that it completes and emits all the expected items.

If you want to create a mocked version of your observable, you can just create a new Observable that has the behaviour that you want. For example:

```<code>public Observable<Integer> mockedObservableCompleteWithResult() {
        return Observable.create(e -> {
            e.onNext(12);
            e.onNext(20);
            e.onNext(330);
            e.onComplete();
        });
    }
</code>```

that can be verified with the above-mentioned test.

Then we can create other mock for modelling other results

```<code>public Observable<Integer> mockedObservableError() {
            return Observable.create(e -> {
                e.onNext(12);
                e.onError(new Throwable("Generic exception"));
            });
        }
</code>```

That can be verified:

```<code>@Test
public void testObservable() throws Exception {
       Observable<Integer> obs = mockedObservableError();
       TestObserver<Integer> testObserver = TestObserver.create();
       obs.subscribe(testObserver);

       testObserver.assertError(Throwable.class);
}
</code>```

Body:
I am trying to write some unit tests for an Android application that is using Retrofit 2, Mockito 1.10 and RXJava 1.0. I am not using a java version that supports lambdas!

My code uses Observables and I can do the following:

when(myAPI.Complete(anyString(), any(MyContainer.class)))
        .thenReturn(Observable.<GenericResponse>error(new Throwable("An error has occurred!")));

Subscriber genericResponseSubscriber = mock(Subscriber.class);

myPresenter.myUseCase(id, container, genericResponseSubscriber);

verify(genericResponseSubscriber, times(1)).onError(any(Throwable.class));

The above code works fine and allows me to throw an error and capture it within the test.

What I need to be able to do as well (of course) :) is to capture positive conditions. I feel like it's obvious but can't find the answer I need.

How can I capture onComplete and onNext cases ?

I know that the verification for onComplete would be...

verify(genericResponseSubscriber, times(1)).onCompleted();

But I can't see what my 'when' clause should be. I tried the following but that fails:

GenericResponse response = new GenericResponse();
response.setSuccess(true);

when(myAPI.orderComplete(anyString(), any(MyContainer.class)))
        .thenReturn(Observable.just(response));

Subscriber genericResponseSubscriber = mock(Subscriber.class);

myPresenter.myUseCase(id, container, genericResponseSubscriber);

verify(genericResponseSubscriber, times(1)).onCompleted();

The failure here is that subscriber.onStart() was instead called.

So, what I would like to know is, how I can mock and verify the 'onComplete' and 'onNext' calls, please and more importantly what I should have looked to be able to have resolved this myself rather than having to ask! :)

As always, any help is appreciated.

Edit..

My onError working test case..

    public void UseCaseOnError() throws Exception {

     String id = "5";

     order Order = new Order();

     SomeContainer myContainer = new SomeContainer(order);

     when(myRetroFitAPI.complete(anyString(), any(SomeContainer.class)))

.thenReturn(Observable.error(new Throwable(“My error!")));

     Subscriber genericResponseSubscriber = mock(Subscriber.class);

     orderPresenter.doUseCase(id, myContainer, genericResponseSubscriber);

     verify(genericResponseSubscriber,times(1)).onError(any(Throwable.class));

}

What I should really add is that, I feel there should be an equivalent for onError in terms of a positive state, i.e. onCompleted. If I do the same but with onCompleted instead, my verification fails as it detects onStart has been called instead which I am finding rather confusing.

I have tried using the ReplaySubject as such:

public void createOrderOnCompleteError() {
    orderOnCompleteSubject.onError(new Throwable("I am an error"));
}

public void createOrderOnCompleteSuccess() {
    orderOnCompleteSubject.onNext(new GenericResponse().setSuccess(true));
    orderOnCompleteSubject.onCompleted();
}

The error mechanism works fine.. the completed mechanism does not...

Body:
You should use the class TestObserver for testing the Observable, in this way:

public Observable<Integer> getObservable() {
     return Observable.just(12, 20, 330);
}

@Test
public void testObservable() {
     Observable<Integer> obs = getObservable();
     TestObserver<Integer> testObserver = TestObserver.create();
     obs.subscribe(testObserver);

     testObserver.assertComplete();
     testObserver.assertResult(12, 20, 330);
 }

In this way you can verify that it completes and emits all the expected items.

If you want to create a mocked version of your observable, you can just create a new Observable that has the behaviour that you want. For example:

public Observable<Integer> mockedObservableCompleteWithResult() {
        return Observable.create(e -> {
            e.onNext(12);
            e.onNext(20);
            e.onNext(330);
            e.onComplete();
        });
    }

that can be verified with the above-mentioned test.

Then we can create other mock for modelling other results

public Observable<Integer> mockedObservableError() {
            return Observable.create(e -> {
                e.onNext(12);
                e.onError(new Throwable("Generic exception"));
            });
        }

That can be verified:

@Test
public void testObservable() throws Exception {
       Observable<Integer> obs = mockedObservableError();
       TestObserver<Integer> testObserver = TestObserver.create();
       obs.subscribe(testObserver);

       testObserver.assertError(Throwable.class);
}


问:
hosting an image with the flask and then processing the same using another view function in the same code
so I am hosting an image using flask and then I want to do a post request to an API using the url all in the same code:

```<code>@app.route('/host')
def host():
    return send_from_directory("C:/images", "image1.png")

@app.route('/post')
def post():
    response = requests.post(url, data={'input':'<url for host>', headers=headers)
    return jsonify(response.json())
</code>```

I believe as both these view functions are in the same python file, post() gets blocked.
Is there a workaround this problem ?

PS: if I host images on a different machine, it works, but that's not what I desire.
Thanks!

答:
I think there are some problems with your code.

First, I don't believe there is an @app.post() decorator in Flask. My guess is that you were trying to specify that that route should be POSTed to by your users. The way to do that would be @app.route('/post', methods=['POST']).

Next, it seems like you want the /post endpoint to send a POST request to a user-specified(?) URL when the user sends an HTTP request to this endpoint. The way you would do that for a user-specified / user-POSTed URL is something like this (I haven't run this code to test it):

```<code>@app.route('/send_post_request', methods=['POST'])
def send_post_request():
    user_posted_data = json.loads(request.data)
    user_specified_url = user_posted_data['url']
    dict_to_post= { 'input': url_for('hosts') }
    headers = {}  # Fill these in
    response = requests.post(user_specified_url , json=dict_to_post, headers=headers)
    return jsonify(response.json())
</code>```

If the URL to send the POST request to is known by the server, you could have your user simply send a GET request:

```<code>@app.route('/send_post_request', methods=['GET'])
def send_post_request():
    dict_to_post = { 'input': url_for('hosts') }
    headers = {}  # Fill these in
    server_specified_url = ''  # Fill this in
    response = requests.post(server_specified_url, json=dict_to_post, headers=headers)
    return jsonify(response.json())
</code>```

Body:
so I am hosting an image using flask and then I want to do a post request to an API using the url all in the same code:

@app.route('/host')
def host():
    return send_from_directory("C:/images", "image1.png")

@app.route('/post')
def post():
    response = requests.post(url, data={'input':'<url for host>', headers=headers)
    return jsonify(response.json())

I believe as both these view functions are in the same python file, post() gets blocked.
Is there a workaround this problem ?

PS: if I host images on a different machine, it works, but that's not what I desire.
Thanks!

Body:
I think there are some problems with your code.

First, I don't believe there is an @app.post() decorator in Flask. My guess is that you were trying to specify that that route should be POSTed to by your users. The way to do that would be @app.route('/post', methods=['POST']).

Next, it seems like you want the /post endpoint to send a POST request to a user-specified(?) URL when the user sends an HTTP request to this endpoint. The way you would do that for a user-specified / user-POSTed URL is something like this (I haven't run this code to test it):

@app.route('/send_post_request', methods=['POST'])
def send_post_request():
    user_posted_data = json.loads(request.data)
    user_specified_url = user_posted_data['url']
    dict_to_post= { 'input': url_for('hosts') }
    headers = {}  # Fill these in
    response = requests.post(user_specified_url , json=dict_to_post, headers=headers)
    return jsonify(response.json())

If the URL to send the POST request to is known by the server, you could have your user simply send a GET request:

@app.route('/send_post_request', methods=['GET'])
def send_post_request():
    dict_to_post = { 'input': url_for('hosts') }
    headers = {}  # Fill these in
    server_specified_url = ''  # Fill this in
    response = requests.post(server_specified_url, json=dict_to_post, headers=headers)
    return jsonify(response.json())


问:
Update REST resource using PUT and POST
I have difficuties understanding REST principled for updating resource.

For example this response contains id of a resource

GET /users/5
{
"user_id": 5
"first_name" : "John",
"last_name" : "Doe",
"minutes_active": 10

}
And this assumes that an id of a resource is one stated in the url of a request

```<code>GET /users/5
{
"first_name" : "John",
"last_name" : "Doe",
"address":
{
"street" : "First Street 10",
"postal" : "0000",
"city": "Dublin"
},
"phones": [
{
"type" : "work",
"number" : "555 473-0000",
},
{
"type" : "home",
"number" : "555 473-0000",
}]
}
</code>```

If i want to update only address I am thinking of using one of the following options.

```<code>1.
POST /users/5
{
"address":
{
"street" : "First Street 10",
"postal" : "0000",
"city": "Dublin"
}
}

2.
PUT /users/5
{
"address":
{
"street" : "First Street 10",
"postal" : "0000",
"city": "Dublin"
}
}

3.
PUT /users/5/address
{
"address":
{
"street" : "First Street 10",
"postal" : "0000",
"city": "Dublin"
}
}
</code>```

Although POST is not idempotent it will always do the same work in this case (act as idempotent), as well as PUT. I somewhere read that this type of request is considered a partial update, and for this types of request we should use PATCH.

At this point I would like to avoid PATCH, and use some alternative.

Furthermore, if I isolate address as a separate resource in /users/5/address i could use PUT and it would be a solution that fully follows REST principles. But this could be a problem I a developer want to update fe. both phones and addresses using a single request.

If I would really want to use options 1 or 2 (and some huge systems such as zendesk, twitter are doing so), could I encounter any serious issues that I dont really see at this point?

答:
The REST answer is: how would you do it with a web site?

You would GET the current representation of the user profile, and included int that representation would be a number of links, with semantic hints that cue the agent (you), as to what each link is for.  You, knowing that your goal is to change the address, would follow GET that link, retrieving a representation that included a form, with a bunch of fields and a link instructing the client how to submit the form.  So you would submit the form: a representation of the data would be sent (POST) to some resource that would in turn communicate with the domain to produce the side effect you wanted.

or...

You would GET the current representation of the user profile, and included int that representation would be a number of links, with semantic hints that cue the agent (you), as to what each link is for.  You, knowing that your goal is to change the address, would follow GET that link, retrieving a representation
of the address, which you would update in your favorite text editor.  Then you would PUT the new representation back to the same resource, which update the servers copy of the address document.

So "REST principles" don't really care if you use POST or PUT -- as long as you use them in a way that is consistent with the RFC.  REST cares a lot about the fact that you use POST and PUT the same way for all resources, and that the representations you send to the client instruct the clients behavior (rather than programming in a custom set of responses).

Furthermore, if I isolate address as a separate resource in /users/5/address i could use PUT and it would be a solution that fully follows REST principles. But this could be a problem I a developer want to update fe. both phones and addresses using a single request.

This isn't a problem - it has two different answers.

One possibility is that you always include the phones with the addresses, and let the agent decide what changes to make.

But the "advanced" answer is that you have two different resources -- one for editing the address along, and a different resource for editing the address and the phone number together.  HTTP Resources are about the integration protocol between your domain and its consumers; if you want to introduce a new protocol, you just implement a new family of resources to support it, and then add links that advertise its existence.

```<code>GET /changeOfAddressForm?user=5

GET /changeContactDetailsForm?user=5
</code>```

Title: Update REST resource using PUT and POST

Body:
I have difficuties understanding REST principled for updating resource.

For example this response contains id of a resource

GET /users/5
{
"user_id": 5
"first_name" : "John",
"last_name" : "Doe",
"minutes_active": 10

}
And this assumes that an id of a resource is one stated in the url of a request

GET /users/5
{
"first_name" : "John",
"last_name" : "Doe",
"address":
{
"street" : "First Street 10",
"postal" : "0000",
"city": "Dublin"
},
"phones": [
{
"type" : "work",
"number" : "555 473-0000",
},
{
"type" : "home",
"number" : "555 473-0000",
}]
}

If i want to update only address I am thinking of using one of the following options.

1.
POST /users/5
{
"address":
{
"street" : "First Street 10",
"postal" : "0000",
"city": "Dublin"
}
}

2.
PUT /users/5
{
"address":
{
"street" : "First Street 10",
"postal" : "0000",
"city": "Dublin"
}
}

3.
PUT /users/5/address
{
"address":
{
"street" : "First Street 10",
"postal" : "0000",
"city": "Dublin"
}
}

Although POST is not idempotent it will always do the same work in this case (act as idempotent), as well as PUT. I somewhere read that this type of request is considered a partial update, and for this types of request we should use PATCH.

At this point I would like to avoid PATCH, and use some alternative.

Furthermore, if I isolate address as a separate resource in /users/5/address i could use PUT and it would be a solution that fully follows REST principles. But this could be a problem I a developer want to update fe. both phones and addresses using a single request.

If I would really want to use options 1 or 2 (and some huge systems such as zendesk, twitter are doing so), could I encounter any serious issues that I dont really see at this point?

Body:
The REST answer is: how would you do it with a web site?

You would GET the current representation of the user profile, and included int that representation would be a number of links, with semantic hints that cue the agent (you), as to what each link is for.  You, knowing that your goal is to change the address, would follow GET that link, retrieving a representation that included a form, with a bunch of fields and a link instructing the client how to submit the form.  So you would submit the form: a representation of the data would be sent (POST) to some resource that would in turn communicate with the domain to produce the side effect you wanted.

or...

You would GET the current representation of the user profile, and included int that representation would be a number of links, with semantic hints that cue the agent (you), as to what each link is for.  You, knowing that your goal is to change the address, would follow GET that link, retrieving a representation
of the address, which you would update in your favorite text editor.  Then you would PUT the new representation back to the same resource, which update the servers copy of the address document.

So "REST principles" don't really care if you use POST or PUT -- as long as you use them in a way that is consistent with the RFC.  REST cares a lot about the fact that you use POST and PUT the same way for all resources, and that the representations you send to the client instruct the clients behavior (rather than programming in a custom set of responses).

Furthermore, if I isolate address as a separate resource in /users/5/address i could use PUT and it would be a solution that fully follows REST principles. But this could be a problem I a developer want to update fe. both phones and addresses using a single request.

This isn't a problem - it has two different answers.

One possibility is that you always include the phones with the addresses, and let the agent decide what changes to make.

But the "advanced" answer is that you have two different resources -- one for editing the address along, and a different resource for editing the address and the phone number together.  HTTP Resources are about the integration protocol between your domain and its consumers; if you want to introduce a new protocol, you just implement a new family of resources to support it, and then add links that advertise its existence.

GET /changeOfAddressForm?user=5

GET /changeContactDetailsForm?user=5


问:
'Settings' object has no attribute 'RECAPTCHA_SECRET_KEY'
I got this Error when user want to register:</p>

```<code>AttributeError at /accounts/register/'

'Settings' object has no attribute 'RECAPTCHA_SECRET_KEY'

Request Method: POST
Request URL:    http://127.0.0.1:8009/accounts/register/

Django Version: 1.11.3
Exception Type: AttributeError
Exception Value:
'Settings' object has no attribute 'RECAPTCHA_SECRET_KEY'

Exception Location: /home/ali/bestoon/.venv/local/lib/python2.7/site-packages/django/conf/__init__.py in __getattr__, line 57

Python Executable:  /home/ali/bestoon/.venv/bin/python

Python Version: 2.7.12
Python Path:
['/home/ali/bestoon/bestoon',
 '/home/ali/bestoon/.venv/lib/python2.7',
 '/home/ali/bestoon/.venv/lib/python2.7/plat-x86_64-linux-gnu',
 '/home/ali/bestoon/.venv/lib/python2.7/lib-tk',
 '/home/ali/bestoon/.venv/lib/python2.7/lib-old',
 '/home/ali/bestoon/.venv/lib/python2.7/lib-dynload',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/home/ali/bestoon/.venv/local/lib/python2.7/site-packages',
 '/home/ali/bestoon/.venv/lib/python2.7/site-packages']
</code>```

答: You are missing the Y from RECAPTCHA_SECRET_KE in your settings.

Body:
I got this Error when user want to register:

AttributeError at /accounts/register/'

'Settings' object has no attribute 'RECAPTCHA_SECRET_KEY'

Request Method: POST
Request URL:    http://127.0.0.1:8009/accounts/register/

Django Version: 1.11.3
Exception Type: AttributeError
Exception Value:
'Settings' object has no attribute 'RECAPTCHA_SECRET_KEY'

Exception Location: /home/ali/bestoon/.venv/local/lib/python2.7/site-packages/django/conf/__init__.py in __getattr__, line 57

Python Executable:  /home/ali/bestoon/.venv/bin/python

Python Version: 2.7.12
Python Path:
['/home/ali/bestoon/bestoon',
 '/home/ali/bestoon/.venv/lib/python2.7',
 '/home/ali/bestoon/.venv/lib/python2.7/plat-x86_64-linux-gnu',
 '/home/ali/bestoon/.venv/lib/python2.7/lib-tk',
 '/home/ali/bestoon/.venv/lib/python2.7/lib-old',
 '/home/ali/bestoon/.venv/lib/python2.7/lib-dynload',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/home/ali/bestoon/.venv/local/lib/python2.7/site-packages',
 '/home/ali/bestoon/.venv/lib/python2.7/site-packages']


问:
Access Angular parent route data from children
I'd like to have the same data in children routes, but I can't find a way for accessing the parent route's data. That is, now I have:

```<code>{ path: 'parent-path', component: parentComponent, children: [
    { path: 'child1', component: child1Component,
      data: { sharedData: 'sharedData', child1Data: 'child1Data' }},
    { path: 'child2', component: child2Component,
      data: { sharedData: 'sharedData', child2Data: 'child2Data' }},
    { path: 'child3', component: child3Component,
      data: { sharedData: 'sharedData', child3Data: 'child3Data' }}
]}
</code>```

What I want is not have to repeat the same sharedData in all children. I tried this:

```<code>{ path: 'parent-path', data: { sharedData: 'sharedData'}, component:
  parentComponent, children: [
    { path: 'child1', component: child1Component,
      data: { child1Data: 'child1Data' }},
    { path: 'child2', component: child2Component,
      data: { child2Data: 'child2Data' }},
    { path: 'child3', component: child3Component,
      data: { child3Data: 'child3Data' }}
]}
</code>```

But, by this way, in each component I only have his own data (childXData).

How could I access the parent route's data from the children?

答: In child you can inject ActivatedRoute (route: ActivatedRoute) and then you can do: route.parent.snapshot.data['sharedData'] or without snapshot if you need observable.</p>

Body:
I'd like to have the same data in children routes, but I can't find a way for accessing the parent route's data. That is, now I have:

{ path: 'parent-path', component: parentComponent, children: [
    { path: 'child1', component: child1Component,
      data: { sharedData: 'sharedData', child1Data: 'child1Data' }},
    { path: 'child2', component: child2Component,
      data: { sharedData: 'sharedData', child2Data: 'child2Data' }},
    { path: 'child3', component: child3Component,
      data: { sharedData: 'sharedData', child3Data: 'child3Data' }}
]}

What I want is not have to repeat the same sharedData in all children. I tried this:

{ path: 'parent-path', data: { sharedData: 'sharedData'}, component:
  parentComponent, children: [
    { path: 'child1', component: child1Component,
      data: { child1Data: 'child1Data' }},
    { path: 'child2', component: child2Component,
      data: { child2Data: 'child2Data' }},
    { path: 'child3', component: child3Component,
      data: { child3Data: 'child3Data' }}
]}

But, by this way, in each component I only have his own data (childXData).

How could I access the parent route's data from the children?


问:
How do I click 1 of 2 links with same name, no id and same class. selenium java
I'm trying to get selenium to click the select button but I can't use by.linkText() because there are two buttons with the same name.
I'm using this xpath ".//*[contains(@id,'view-something_111111_2A22DF2_)']/div/a[text()='Select']"; to find the button but it can't find it.

I've also tried ".//*[contains(@id,'view-something_111111_2A22DF2_)']/div/a";.
I've looked over the Selenium documentation and can't seem to find a solution.

Here is the section of website code:

...

  Select```
</div>
</div>
</p>

<p>for reference, the second Select button has this code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="view-something_111111_2A3B5DF2_0" class="coverage-wrap collapse" aria-expanded="false" style="height: 30px;">...</div>
<div class="btn-raplace">
  Select</code>```

which is why I am using the id in my xpath.

Thanks.

答: You can try this XPATH :- //*[@class="btn-raplace"]/a[@class="btn-beer"][1] here [1] is postion of ur button. Which you want to click

Body:
I'm trying to get selenium to click the select button but I can't use by.linkText() because there are two buttons with the same name.
I'm using this xpath ".//*[contains(@id,'view-something_111111_2A22DF2_)']/div/a[text()='Select']"; to find the button but it can't find it.

I've also tried ".//*[contains(@id,'view-something_111111_2A22DF2_)']/div/a";.
I've looked over the Selenium documentation and can't seem to find a solution.

Here is the section of website code:

...

  Select

for reference, the second Select button has this code:

...

  Select

which is why I am using the id in my xpath.

Thanks.


问:
Could not import cufflinks

Problem

I am trying to install both plotly and cufflinks. However I had a problem.

The installation of both plotly and cufflinks were successful. Although, I can't import cufflinks.

Below is a picture of the problem. It seems to be a dependency error:

I tried manually downloading and installing "talib" but I keep getting failures. (Shown below).

```<code>talib\common.c(240): fatal error C1083: Cannot open include file: 'ta_libc.h': No such file or directory
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2
</code>```

Any Ideas? I tried re-installing both modules and Anaconda. Nothing So far.

Other infos:

Cufflinks version: 0.11.0

Plotly version: 2.0.10

Anaconda version: 3-4.4.0 (But I don't think it have anything to do with it)

Python version: 3.6.1

答: I have now removed all dependencies on talib. All studies are pure python based now and you should not face any of this errors. </p>

Title: Could not import cufflinks

Body:
Problem

I am trying to install both plotly and cufflinks. However I had a problem.

The installation of both plotly and cufflinks were successful. Although, I can't import cufflinks.

Below is a picture of the problem. It seems to be a dependency error:

I tried manually downloading and installing "talib" but I keep getting failures. (Shown below).

talib\common.c(240): fatal error C1083: Cannot open include file: 'ta_libc.h': No such file or directory
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2

Any Ideas? I tried re-installing both modules and Anaconda. Nothing So far.

Other infos:

Cufflinks version: 0.11.0

Plotly version: 2.0.10

Anaconda version: 3-4.4.0 (But I don't think it have anything to do with it)

Python version: 3.6.1


问:
Splitting data in R - simple by rows
All, I have what is likely a very simple question in R, but I'm having trouble sorting out a few issues with the existing answers pertaining to this problem.

I want to split my dataset in two, so that I can use the predict() function.  My dataset is 27 rows, not including headers.  I only want to split it into a 20 row and 7 row set (two sets).  When I use the split function, not only can I only figure out how to split into groups that are multiples of the total number of rows, but the resulting object changes the variable/header names, prefacing each with X1..

The current code that I've tried and like is,

data=newdata
indexes = sample(1:nrow(newdata), size=0.8*nrow(newdata))
test = data[indexes,]
train = data[-indexes,]

But this results in a random grouping of rows, not the first approximately 20.  How can I get a result that returns the first 20 and last 7?  Apologies for the simple question, any insight is very much appreciated!

答:
If you just want to separate the first twenty rows from the remaining rows:</p>

```<code>first_twenty <- newdata[1:20 , ]
last_seven <- newdata[21:nrow(newdata), ]
</code>```

Title: Splitting data in R - simple by rows

Body:
If you just want to separate the first twenty rows from the remaining rows:

first_twenty <- newdata[1:20 , ]
last_seven <- newdata[21:nrow(newdata), ]


问:
How do I delete all the rows of a table with a recursive structure (MySQL)?
I have a table in my DB, in which every row has a parent id which is the id of another row in the table (the table represents a tree-like structure). I would like to empty the table. But when I perform

```<code>DELETE FROM table_name WHERE true;
</code>```

I get an error (foreign key constraint). How do I empty the table anyway?

Clarification: I want to delete the whole table's contents, not the tables themselves.

答:
If you can't change the ON DELETE behavior, you can do this repeatedly until the table is empty:</p>

```<code>DELETE FROM table_name WHERE id NOT IN (SELECT parent_id FROM table_name)
</code>```

Body:
I have a table in my DB, in which every row has a parent id which is the id of another row in the table (the table represents a tree-like structure). I would like to empty the table. But when I perform

DELETE FROM table_name WHERE true;

I get an error (foreign key constraint). How do I empty the table anyway?

Clarification: I want to delete the whole table's contents, not the tables themselves.

Body:
If you can't change the ON DELETE behavior, you can do this repeatedly until the table is empty:

DELETE FROM table_name WHERE id NOT IN (SELECT parent_id FROM table_name)