问:
Squeezing pandas DataFrame to have non-null values and modify column names
I have the following sample DataFrame

```<code>import numpy as np
import pandas as pd

df = pd.DataFrame({'Tom': [2, np.nan, np.nan],
                   'Ron': [np.nan, 5, np.nan],
                   'Jim': [np.nan, np.nan, 6],
                   'Mat': [7, np.nan, np.nan],},
                   index=['Min', 'Max', 'Avg'])
</code>```

that looks like this where each row have only one non-null value

```<code>    Tom Ron Jim Mat
Min 2.0 NaN NaN 7.0
Max NaN 5.0 NaN NaN
Avg NaN NaN 6.0 NaN
</code>```

Desired Outcome

For each column, I want to have the non-null value and then append the index of the corresponding non-null value to the name of the column. So the final result should look like this

```<code>    Tom_Min Ron_Max Jim_Avg Mat_Min
0     2.0    5.0      6.0    7.0
</code>```

My attempt

Using list comprehensions: Find the non-null value, and append the corresponding index to the column name and then create a new DataFrame

```<code>values = [df[col][~pd.isna(df[col])].values[0] for col in df.columns]

# [2.0, 5.0, 6.0, 7.0]

new_cols = [col + '_{}'.format(df[col][~pd.isna(df[col])].index[0]) for col in df.columns]

# ['Tom_Min', 'Ron_Max', 'Jim_Avg', 'Mat_Min']

df_new = pd.DataFrame([values], columns=new_cols)
</code>```

My question

Is there some in-built functionality in pandas which can do this without using for loops and list comprehensions?

答:
Use:

```<code>s = df.T.stack()
s.index = s.index.map('_'.join)
df = s.to_frame().T
</code>```

Result:

```<code># print(df)

   Tom_Min  Ron_Max  Jim_Avg  Mat_Min
0      2.0      5.0      6.0      7.0
</code>```

Body:
I have the following sample DataFrame

import numpy as np
import pandas as pd

df = pd.DataFrame({'Tom': [2, np.nan, np.nan],
                   'Ron': [np.nan, 5, np.nan],
                   'Jim': [np.nan, np.nan, 6],
                   'Mat': [7, np.nan, np.nan],},
                   index=['Min', 'Max', 'Avg'])

that looks like this where each row have only one non-null value

    Tom Ron Jim Mat
Min 2.0 NaN NaN 7.0
Max NaN 5.0 NaN NaN
Avg NaN NaN 6.0 NaN

Desired Outcome

For each column, I want to have the non-null value and then append the index of the corresponding non-null value to the name of the column. So the final result should look like this

    Tom_Min Ron_Max Jim_Avg Mat_Min
0     2.0    5.0      6.0    7.0

My attempt

Using list comprehensions: Find the non-null value, and append the corresponding index to the column name and then create a new DataFrame

values = [df[col][~pd.isna(df[col])].values[0] for col in df.columns]

# [2.0, 5.0, 6.0, 7.0]

new_cols = [col + '_{}'.format(df[col][~pd.isna(df[col])].index[0]) for col in df.columns]

# ['Tom_Min', 'Ron_Max', 'Jim_Avg', 'Mat_Min']

df_new = pd.DataFrame([values], columns=new_cols)

My question

Is there some in-built functionality in pandas which can do this without using for loops and list comprehensions?

Body:
Use:

s = df.T.stack()
s.index = s.index.map('_'.join)
df = s.to_frame().T

Result:

# print(df)

   Tom_Min  Ron_Max  Jim_Avg  Mat_Min
0      2.0      5.0      6.0      7.0


来源: stackexchange

问:
Rename remote branch without deleting it
I need your help to rename a remote branch.

I created a PR but now I need to rename the remote branch name.

I don't want to follow the process where I have to rename the local branch then push and delete the old branch because it will clear the PR.

Is there a way to just rename the remote branch and PR should stay as it is. thanks.

答:
I don't want to follow the process where I have to rename the local branch then push and delete the old branch.

I don't think there's any other way. You could try to change the branch in the PR screen, but I suppose you would've tried it already.

Pull or merge requests are not part of git itself, but a feature of hosting services, such as GitHub or BitBucket. As it's a standard, so to say, the implementation is completely up to the system.

ContentLicense: CC BY-SA 4.0


问:
get the date for xarray rolling min or max
Calling foo.rolling(time=100).mean() will give the mean for a rolling period of 100 days.
I would like to find the minimum and maximum values within this 100 day period. Easy with foo.rolling(time=100).min()

However, how can I find the exact day of this minimum and maximum? I want to know what dates the min and max periods are during this rolling 100 day window. Or will I need to write my own function to do this?

```<code>num=4000
data = np.random.rand(num, 3)
locs = ['one', 'two', 'three']
times = pd.date_range('2000-01-01', periods=num)
foo = xr.DataArray(data, coords=[times, locs], dims=['time', 'space'])

foo.rolling(time=100).max()
foo.rolling(time=100).min()
</code>```

Thanks

答: Could you use argmin with rolling(...).reduce, then use those values to select dates from the rolling window.

Body:
Calling foo.rolling(time=100).mean() will give the mean for a rolling period of 100 days.
I would like to find the minimum and maximum values within this 100 day period. Easy with foo.rolling(time=100).min()

However, how can I find the exact day of this minimum and maximum? I want to know what dates the min and max periods are during this rolling 100 day window. Or will I need to write my own function to do this?

num=4000
data = np.random.rand(num, 3)
locs = ['one', 'two', 'three']
times = pd.date_range('2000-01-01', periods=num)
foo = xr.DataArray(data, coords=[times, locs], dims=['time', 'space'])

foo.rolling(time=100).max()
foo.rolling(time=100).min()

Thanks


问:
Why does Tomcat start with 0.0.0.0:8000 open?
I know the short answer is "You told it to." But of course, I'm not sure how I told Tomcat to start with the 8000 default debug port open, but on 0.0.0.0 instead of the expected 127.0.0.1. Here's a couple of context commands directly after Ubuntu 10.10 boots.

```<code>$ netstat -lnt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:8000            0.0.0.0:*               LISTEN
tcp6       0      0 127.0.0.1:8080          :::*                    LISTEN
tcp6       0      0 ::1:631                 :::*                    LISTEN
tcp6       0      0 127.0.0.1:8005          :::*                    LISTEN

/usr/share/tomcat6/bin$ grep -C 5 8000 catalina.sh
#
#   JPDA_TRANSPORT  (Optional) JPDA transport used when the "jpda start"
#                   command is executed. The default is "dt_socket".
#
#   JPDA_ADDRESS    (Optional) Java runtime options used when the "jpda start"
#                   command is executed. The default is 8000.
#
#   JPDA_SUSPEND    (Optional) Java runtime options used when the "jpda start"
#                   command is executed. Specifies whether JVM should suspend
#                   execution immediately after startup. Default is "n".
#
--
if [ "$1" = "jpda" ] ; then
  if [ -z "$JPDA_TRANSPORT" ]; then
    JPDA_TRANSPORT="dt_socket"
  fi
  if [ -z "$JPDA_ADDRESS" ]; then
    JPDA_ADDRESS="8000"
  fi
  if [ -z "$JPDA_SUSPEND" ]; then
    JPDA_SUSPEND="n"
  fi
  if [ -z "$JPDA_OPTS" ]; then
</code>```

Given these two outputs, I expect to find out that there's a further configuration file somewhere that I unknowingly modified, since the only way that catalina.sh would open 8000 is if it was passed the jpda switch, and even then it seems like it will start on localhost and no 0.0.0.0. .bashrc is clean of tomcat tomfoolery, and I'm stumped where else to look!

答:
Time to brush up on RFC4632, memory got rusty.

0.0.0.0 is the default route, and in the case of Tomcat is used to indicate that any IP on port 8000 will be routed into Tomcat (presumably for debugging).

To restate, on Tomcat 0.0.0.0:xxxx will route any request with xxxx port into Tomcat.

ContentLicense: CC BY-SA 3.0

Body:
I know the short answer is "You told it to." But of course, I'm not sure how I told Tomcat to start with the 8000 default debug port open, but on 0.0.0.0 instead of the expected 127.0.0.1. Here's a couple of context commands directly after Ubuntu 10.10 boots.

$ netstat -lnt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:8000            0.0.0.0:*               LISTEN
tcp6       0      0 127.0.0.1:8080          :::*                    LISTEN
tcp6       0      0 ::1:631                 :::*                    LISTEN
tcp6       0      0 127.0.0.1:8005          :::*                    LISTEN

/usr/share/tomcat6/bin$ grep -C 5 8000 catalina.sh
#
#   JPDA_TRANSPORT  (Optional) JPDA transport used when the "jpda start"
#                   command is executed. The default is "dt_socket".
#
#   JPDA_ADDRESS    (Optional) Java runtime options used when the "jpda start"
#                   command is executed. The default is 8000.
#
#   JPDA_SUSPEND    (Optional) Java runtime options used when the "jpda start"
#                   command is executed. Specifies whether JVM should suspend
#                   execution immediately after startup. Default is "n".
#
--
if [ "$1" = "jpda" ] ; then
  if [ -z "$JPDA_TRANSPORT" ]; then
    JPDA_TRANSPORT="dt_socket"
  fi
  if [ -z "$JPDA_ADDRESS" ]; then
    JPDA_ADDRESS="8000"
  fi
  if [ -z "$JPDA_SUSPEND" ]; then
    JPDA_SUSPEND="n"
  fi
  if [ -z "$JPDA_OPTS" ]; then

Given these two outputs, I expect to find out that there's a further configuration file somewhere that I unknowingly modified, since the only way that catalina.sh would open 8000 is if it was passed the jpda switch, and even then it seems like it will start on localhost and no 0.0.0.0. .bashrc is clean of tomcat tomfoolery, and I'm stumped where else to look!


问:
How make cygwin faster?
I have to use cygwin on Windows but altough (like many users complain) the boot is fast, the execution of commands is very, very, very slow. When run on Linux partition it takes at least one tenth of the time. Is there some way to make it work faster? I followed the steps found here (second answer) but it didn't work.</p>

答:
In Cygwin what is slow is the execution of the fork call. As Microsoft systems do not provide the tools to easily mimic a POSIX fork, Cygwin DLL implements a lot of trick to execute a fork and that makes the full process slow.

Running a single program that does not fork is as fast as a normal Windows program.

Title: How make cygwin faster?


问:
How would I go About Getting a Global Variables value in another form?
So I am new to Programming and I am working In Visual Studios c# Windows application Forms,
and I have a button on the first form That needs to set a Glabel Bool To true when pressed while also opening the second form.

On the second forms startup I need it to tell if that bool is set to true or false, to enable a button(on the second Form) or keep it disabled(if False.

Here Is the First Forms Code:

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

namespace Project
{
    public partial class FirstPage: Form
    {
        public FirstPage()
        {
            InitializeComponent();
        }

        public bool IsManager = false;

        public static class Global
        {
            public static bool IsManager = false;
        }

        private void Button_Btn_Click(object sender, EventArgs e)
        {
            this.hide();
            Form2 f2 = new form2(IsManager);
            f2.ShowDialog();

            IsManager = true;
        }
    }
}
</code>```

Here is my second Forms Code:

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

namespace Project
{
    public partial class SecondPage : Form
    {
        public FirstPage()
        {
            InitializeComponent();
            IsManager = isManager;
        }
        private bool isManager;

        private void setButtonVisibility()
        {
            if(isManager == true)
            {
                MessageBox.Show("Button Message Display")
            }
        {

        //Need to check if the Global variable is true or false on page load to set a button to either enabled or disabled
    }
}
</code>```

Hopefully this makes sense If not let me know :) Thank You!

答:
Well after reading your question I am assuming that you're trying to set a value to the global bool IsManager and want to do some action in the other second form based on this value.

You can achieve this in multiple ways one passes your global bool in the constructor of second form something like this

```<code>public partial class SecondPage: Form
{
    bool _isManager;
    public SecondPage(bool IsManager)
    {
        InitializeComponent();
       _isManager = IsManager; // the problem was isManager as mistakenkly i used small "i"
    }
}
</code>```

and from the first form pass value like

```<code> private void Button_Btn_Click(object sender, EventArgs e)
 {
    this.hide();
    IsManager = true;
    Form2 f2 = new form2(IsManager);
    f2.ShowDialog();
 }
</code>```

Body:
So I am new to Programming and I am working In Visual Studios c# Windows application Forms,
and I have a button on the first form That needs to set a Glabel Bool To true when pressed while also opening the second form.

On the second forms startup I need it to tell if that bool is set to true or false, to enable a button(on the second Form) or keep it disabled(if False.

Here Is the First Forms Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Project
{
    public partial class FirstPage: Form
    {
        public FirstPage()
        {
            InitializeComponent();
        }

        public bool IsManager = false;

        public static class Global
        {
            public static bool IsManager = false;
        }

        private void Button_Btn_Click(object sender, EventArgs e)
        {
            this.hide();
            Form2 f2 = new form2(IsManager);
            f2.ShowDialog();

            IsManager = true;
        }
    }
}

Here is my second Forms Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Project
{
    public partial class SecondPage : Form
    {
        public FirstPage()
        {
            InitializeComponent();
            IsManager = isManager;
        }
        private bool isManager;

        private void setButtonVisibility()
        {
            if(isManager == true)
            {
                MessageBox.Show("Button Message Display")
            }
        {

        //Need to check if the Global variable is true or false on page load to set a button to either enabled or disabled
    }
}

Hopefully this makes sense If not let me know :) Thank You!

Body:
Well after reading your question I am assuming that you're trying to set a value to the global bool IsManager and want to do some action in the other second form based on this value.

You can achieve this in multiple ways one passes your global bool in the constructor of second form something like this

public partial class SecondPage: Form
{
    bool _isManager;
    public SecondPage(bool IsManager)
    {
        InitializeComponent();
       _isManager = IsManager; // the problem was isManager as mistakenkly i used small "i"
    }
}

and from the first form pass value like

 private void Button_Btn_Click(object sender, EventArgs e)
 {
    this.hide();
    IsManager = true;
    Form2 f2 = new form2(IsManager);
    f2.ShowDialog();
 }


问:
How do I save a matplotlib figure in the normalized [0,1] range?
I am generating annotation files for image segmentation learning.
For that I am relying on matplotlibs fill_between() method.
I need to save the figure borderless and in a value range of [0,1] .

How do I do that?

I found out that fig.savefig() can pass arguments to the pillow backend when saving as .png, however i can not find the right arguments to pass to save it in [0,1] range instead of [0,255]

答:
You can't save a png image in a real valued range of [0,1]. Image intensity values in RGB format are only defined for natural numbers of [0,255]. It would also makes little sense to visualise an image with such low intensity values, because it would appear pretty much black.

What you could do instead if you are interested in persisting your data is normalising your matrix to your range and save it as a numpy array instead using numpys save() function.


问:
Merge a single list of dictionaries with the same key value
I can see many similar questions on here but not one that I can find that helps me get the desired output.

I have a single list of dictionaries that have the same ID but with different key value pairs, id like to join all those key values pairs into a single list entry, below is a sample of data and the desired output.

Thanks for your help

```<code>data = [
    {'id': '10', 'animal' : 'cat'},
    {'id': '11', 'animal' : 'dog'},
    {'id': '3', 'animal' : 'pigeon'},
    {'id': '10', 'color' : 'yellow'},
    {'id': '11', 'color' : 'brown'},
    {'id': '3', 'color' : 'grey'},
    {'id': '10', 'type' : 'furry'},
    {'id': '11', 'type' : 'fluffy'},
    {'id': '3', 'type' : 'dirty'},
]
</code>```

desired output

```<code>data = [
    {'id': '10', 'animal' : 'cat', 'color' : 'yellow', 'type' : 'furry'},
    {'id': '11', 'animal' : 'dog', 'color' : 'brown', 'type' : 'fluffy'},
    {'id': '3', 'animal' : 'pigeon', 'color' : 'grey', 'type' : 'dirty'},
]
</code>```

答:
There are multiple ways to achieve this, one of which is defaultdict:

In [1]: data = [
   ...:     {'id': '10', 'animal' : 'cat'},
   ...:     {'id': '11', 'animal' : 'dog'},
   ...:     {'id': '3', 'animal' : 'pigeon'},
   ...:     {'id': '10', 'color' : 'yellow'},
   ...:     {'id': '11', 'color' : 'brown'},
   ...:     {'id': '3', 'color' : 'grey'},
   ...:     {'id': '10', 'type' : 'furry'},
   ...:     {'id': '11', 'type' : 'fluffy'},
   ...:     {'id': '3', 'type' : 'dirty'},
   ...: ]

In [2]: from collections import defaultdict
   ...: ids = defaultdict(dict)
   ...: for d in data:
   ...:     ids[d["id"]].update(d)
   ...:

In [6]: list(ids.values())
Out[6]:
[{'id': '10', 'animal': 'cat', 'color': 'yellow', 'type': 'furry'},
 {'id': '11', 'animal': 'dog', 'color': 'brown', 'type': 'fluffy'},
 {'id': '3', 'animal': 'pigeon', 'color': 'grey', 'type': 'dirty'}]

```

Body:
I can see many similar questions on here but not one that I can find that helps me get the desired output.

I have a single list of dictionaries that have the same ID but with different key value pairs, id like to join all those key values pairs into a single list entry, below is a sample of data and the desired output.

Thanks for your help

data = [
    {'id': '10', 'animal' : 'cat'},
    {'id': '11', 'animal' : 'dog'},
    {'id': '3', 'animal' : 'pigeon'},
    {'id': '10', 'color' : 'yellow'},
    {'id': '11', 'color' : 'brown'},
    {'id': '3', 'color' : 'grey'},
    {'id': '10', 'type' : 'furry'},
    {'id': '11', 'type' : 'fluffy'},
    {'id': '3', 'type' : 'dirty'},
]

desired output

data = [
    {'id': '10', 'animal' : 'cat', 'color' : 'yellow', 'type' : 'furry'},
    {'id': '11', 'animal' : 'dog', 'color' : 'brown', 'type' : 'fluffy'},
    {'id': '3', 'animal' : 'pigeon', 'color' : 'grey', 'type' : 'dirty'},
]


问:
Carrot2 - Entering private PubMed api key
I'm using Carrot2-Workbench 3.16.3.0 for PubMed queries.

Mostly, I run into the "payload" and "api key" problem. I have a private PubMed key. But, neither the Workbench nor the online version allows me to enter it.

Is there any easy way to use it, or is it hard-coded in the source?

答: Previous versions did not support PubMed API keys, the latest on-line version does, it's under the "options" button:


问:
Send List<T> as an optional parameter in the post body in ASP.NET Core Web Api
I had this model which was taking optional params for a post request body:

```<code> public class ReportFilterModel
{

    public int? ReportStatusId { get; set; }
    public Guid? AreaID { get; set; }
}
</code>```

This would do a search in DB according to the filters given by user:

```<code> var report = _context.tbl_Reports.AsQueryable();

                if (model.ReportStatusId.IsNotNull())
                    report = report.Where(x => x.IsDeleted == false && x.ReportStatusId == (StatusEnum)model.ReportStatusId.Value);

                if (model.Area.IsNotNull())
                    report = report.Where(x => x.IsDeleted == false && x.Area.Id == model.AreaId);
</code>```

And then it'd finally return this:

```<code> finalReports = await report
                    .Where(x => x.IsDeleted == false)
                    .Select(x => new ReportsWithFiltersModel
                    {
                        Id = x.Id,

                        Area = Id,
                        UserId = x.UserId,
                        ReportStatus = x.ReportStatusId.GetEnumDescription(),

                    }).ToListAsync();
</code>```

All this working absolutely fine, but now I want to give a list of optional params like this:

```<code>public class ReportFilterModel
{

    public List<int>? ReportStatusId { get; set; }
    public List<Guid>? AreaID { get; set; }
}
</code>```

This is giving an exception

```<code>'List<int>' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'List<int>' could be found (are you missing a using directive or an assembly reference?)
</code>```

How do I fix this?

答:
You are mixing two concepts nullable value types and nullable reference types (added in C# 8.0). Nullabale value types marked with ? are basically shortcut for Nullable<T> and they have Value property. List<T> (in your case List<int> and List<Guid>) is reference type and it does not have Value property and marking it with ? makes compiler aware that this property can contain null reference and make it able to enforce rules to ensure that you've correctly checked this property for a null reference. So in the nutshell your List<int>? ReportStatusId and List<Guid>? AreaID already "optional" and ? makes compiler aware of that.

Hot to fix that?

Change

```<code> if (model.ReportStatusId.IsNotNull())
     report = report.Where(x => x.IsDeleted == false && x.ReportStatusId == (StatusEnum)model.ReportStatusId.Value);
</code>```

to

```<code>if (model.ReportStatusId.IsNotNull() && model.ReportStatusId.Any())
     var statuses = model.ReportStatusId.Cast<StatusEnum>().ToList();
     report = report.Where(x => x.IsDeleted == false && statuses.Contains(x.ReportStatusId));
</code>```

Body:
I had this model which was taking optional params for a post request body:

 public class ReportFilterModel
{

    public int? ReportStatusId { get; set; }
    public Guid? AreaID { get; set; }
}

This would do a search in DB according to the filters given by user:

 var report = _context.tbl_Reports.AsQueryable();

                if (model.ReportStatusId.IsNotNull())
                    report = report.Where(x => x.IsDeleted == false && x.ReportStatusId == (StatusEnum)model.ReportStatusId.Value);

                if (model.Area.IsNotNull())
                    report = report.Where(x => x.IsDeleted == false && x.Area.Id == model.AreaId);

And then it'd finally return this:

 finalReports = await report
                    .Where(x => x.IsDeleted == false)
                    .Select(x => new ReportsWithFiltersModel
                    {
                        Id = x.Id,

                        Area = Id,
                        UserId = x.UserId,
                        ReportStatus = x.ReportStatusId.GetEnumDescription(),

                    }).ToListAsync();

All this working absolutely fine, but now I want to give a list of optional params like this:

public class ReportFilterModel
{

    public List<int>? ReportStatusId { get; set; }
    public List<Guid>? AreaID { get; set; }
}

This is giving an exception

'List<int>' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'List<int>' could be found (are you missing a using directive or an assembly reference?)

How do I fix this?

Body:
You are mixing two concepts nullable value types and nullable reference types (added in C# 8.0). Nullabale value types marked with ? are basically shortcut for Nullable<T> and they have Value property. List<T> (in your case List<int> and List<Guid>) is reference type and it does not have Value property and marking it with ? makes compiler aware that this property can contain null reference and make it able to enforce rules to ensure that you've correctly checked this property for a null reference. So in the nutshell your List<int>? ReportStatusId and List<Guid>? AreaID already "optional" and ? makes compiler aware of that.

Hot to fix that?

Change

 if (model.ReportStatusId.IsNotNull())
     report = report.Where(x => x.IsDeleted == false && x.ReportStatusId == (StatusEnum)model.ReportStatusId.Value);

to

if (model.ReportStatusId.IsNotNull() && model.ReportStatusId.Any())
     var statuses = model.ReportStatusId.Cast<StatusEnum>().ToList();
     report = report.Where(x => x.IsDeleted == false && statuses.Contains(x.ReportStatusId));


问:
how to resolve 403 forbidden in 3dwarehouse?
while I am trying to signup on 3dwarehouse it gives me an error of 403 forbidden.
here is the link to the website.
https://3dwarehouse.sketchup.com/
your help will be appreciated.
thanks in advance.</p>

答:
if you're using google chrome then try to search this link on Mozilla firefox or uinstall google chrome then install it.
Your issue will be resolve by this.</p>


问:
How to combine HTML web component with HTML file? innerHTML = foo("myfile.html")
With the HTML web components, I understand I can set their HTML code with:

```<code>this.innerHTML = `<h1></h1>`;
</code>```

The problem I have with this is I miss out on the convenience of Emmet Abbreviation and if I'm making a lot of components, this slows me down.

I need a function which returns the HTML file as a string so I can make it equal to the innerHTML like this:

```<code>this.innerHTML = getHTML("myfile.hmtl");
</code>```

How can this be done?

答:
You can do it with fetch().

Note that it's an asynchronous function so you should use async/await or Promise().

```<code>this.innerHTML = await fetch( 'myfile.html' ).then( s => s.text() )
</code>```

2 implementation examples for Web Components:

a minimal example with async/await,

a more complete one with Promise.

Body:
With the HTML web components, I understand I can set their HTML code with:

this.innerHTML = `<h1></h1>`;

The problem I have with this is I miss out on the convenience of Emmet Abbreviation and if I'm making a lot of components, this slows me down.

I need a function which returns the HTML file as a string so I can make it equal to the innerHTML like this:

this.innerHTML = getHTML("myfile.hmtl");

How can this be done?

Body:
You can do it with fetch().

Note that it's an asynchronous function so you should use async/await or Promise().

this.innerHTML = await fetch( 'myfile.html' ).then( s => s.text() )

2 implementation examples for Web Components:

a minimal example with async/await,

a more complete one with Promise.


问:
RxDB leader-ship blocks all sockets in chrome
I used the waitForLeadership to let only one tab sync the db. And it looks like it works. But if I activate this feature and open more than 3 tabs, the next tabs won't load.
Chrome always says, waiting for available socket...

Did anyone had/have the same issue?

What did I do wrong? Did I have to manually start the sync process? If I insert in one instance, master or not, it is visible in all correctly. But it seems, that multiple instances try to open a socket/long polling.

```<code>newRxDb.waitForLeadership().then(() => {
   console.log(`isLeader now`);
});
</code>```

答:
I think there's some issue in your service worker no problem, this issue may have been resolved by the release of rxdb v 9.0.0

But I think the problem may be that you are opening multiple browser consoles for the same url, so you can try to check for leadership directly in your title

Whichever page is leader will be prefixed as Online along with the title name

```<code>    // show who's the leader in page's title
    db.waitForLeadership().then(() => {
      document.title = 'Online ' + document.title;
    });
</code>```

This is just my opinion, hope this helps

Body:
I used the waitForLeadership to let only one tab sync the db. And it looks like it works. But if I activate this feature and open more than 3 tabs, the next tabs won't load.
Chrome always says, waiting for available socket...

Did anyone had/have the same issue?

What did I do wrong? Did I have to manually start the sync process? If I insert in one instance, master or not, it is visible in all correctly. But it seems, that multiple instances try to open a socket/long polling.

newRxDb.waitForLeadership().then(() => {
   console.log(`isLeader now`);
});

Body:
I think there's some issue in your service worker no problem, this issue may have been resolved by the release of rxdb v 9.0.0

But I think the problem may be that you are opening multiple browser consoles for the same url, so you can try to check for leadership directly in your title

Whichever page is leader will be prefixed as Online along with the title name

    // show who's the leader in page's title
    db.waitForLeadership().then(() => {
      document.title = 'Online ' + document.title;
    });

This is just my opinion, hope this helps


问:
Git authentication fails after enabling 2FA
I just enabled 2FA (I can't think of any other changes I made) and git asked for my username and password. I provided both, but they were "wrong". I tried many of the solutions here: Git push requires username and password but that didn't work. In particular, when switching from https to ssh, the ssh key gives

Permission denied (publickey).
fatal: Could not read from remote repository.

```<code>$ git push
warning: push.default is unset; its implicit value is changing in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the current behavior after the default changes, use:

  git config --global push.default matching

To squelch this message and adopt the new behavior now, use:

  git config --global push.default simple

See 'git help config' and search for 'push.default' for further information.
(the 'simple' mode was introduced in Git 1.7.11. Use the similar mode
'current' instead of 'simple' if you sometimes use older versions of Git)

Username for 'https://github.com': **********
Password for 'https://mlbileschi@github.com':
remote: Invalid username or password.
fatal: Authentication failed for 'https://github.com/mlbileschi/scala.git/'
</code>```

Any tips?

答:
This worked for me after enabling 2FA on Github:

Create a Personal Access Token: https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line.

NOTE: Remember to select the correct permissions for the token.

Run:

git clone https://github.com/username/repo.git

Username: your_username

Password: your_token

Further reading: https://help.github.com/en/github/using-git/which-remote-url-should-i-use

Body:
I just enabled 2FA (I can't think of any other changes I made) and git asked for my username and password. I provided both, but they were "wrong". I tried many of the solutions here: Git push requires username and password but that didn't work. In particular, when switching from https to ssh, the ssh key gives

Permission denied (publickey).
fatal: Could not read from remote repository.

$ git push
warning: push.default is unset; its implicit value is changing in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the current behavior after the default changes, use:

  git config --global push.default matching

To squelch this message and adopt the new behavior now, use:

  git config --global push.default simple

See 'git help config' and search for 'push.default' for further information.
(the 'simple' mode was introduced in Git 1.7.11. Use the similar mode
'current' instead of 'simple' if you sometimes use older versions of Git)

Username for 'https://github.com': **********
Password for 'https://mlbileschi@github.com':
remote: Invalid username or password.
fatal: Authentication failed for 'https://github.com/mlbileschi/scala.git/'

Any tips?


问:
How to delete an object by it's class attributes, and return it's object value?
I created an array of objects in main() used for a shopping list(groceryitems is the class name)

groceryitems items[10];

So basically while adding items to this list, it's assigned a code by the user as it's attribute.

I would like to remove an object (from the array) by inputting it's code(the attribute), so let's say item 3 has a code of 10000, how do I remove this item with the user inputting 10000?

How do I search which object has a code attribute of 10000 and then return it's value to delete it from the main? Or can I delete it with a function from within the class?

答:
In C++ an array has a static size. You can't resize arrays. You can't add or remove objects. For your use case I recommend std::unordered_map. If the code is unique you can store the objects by their code. You can also find and delete them by code.

Alternatively you can use std::vector, search with std::find and delete objects with std::vector::erase


问:
Create columns with the frequency of a code per ID
I have to perform a query where I can count the number of distinct codes per Id.

```<code>   |Id  | Code
   ------------
   | 1  |   C
   | 1  |   I
   | 2  |   I
   | 2  |   C
   | 2  |   D
   | 2  |   D
   | 3  |   C
   | 3  |   I
   | 3  |   D
   | 4  |   I
   | 4  |   C
   | 4  |   C
</code>```

The output should be something like:

```<code>   |Id  | Count | #Code C | #Code I | #Code D
   -------------------------------------------
   | 1  | 2     |    1    |    1    |   0
   | 2  | 3     |    1    |    0    |   2
   | 3  | 3     |    1    |    1    |   1
   | 4  | 2     |    2    |    1    |   0
</code>```

Can you give me some advise on this?

答:
Use conditional aggregation:</p>

```<code>select id, count(*) as cnt,
       sum(case when code = 'C' then 1 else 0 end) as code_c,
       sum(case when code = 'I' then 1 else 0 end) as code_i,
       sum(case when code = 'D' then 1 else 0 end) as code_d
from t
group by id;
</code>```

Body:
I have to perform a query where I can count the number of distinct codes per Id.

   |Id  | Code
   ------------
   | 1  |   C
   | 1  |   I
   | 2  |   I
   | 2  |   C
   | 2  |   D
   | 2  |   D
   | 3  |   C
   | 3  |   I
   | 3  |   D
   | 4  |   I
   | 4  |   C
   | 4  |   C

The output should be something like:

   |Id  | Count | #Code C | #Code I | #Code D
   -------------------------------------------
   | 1  | 2     |    1    |    1    |   0
   | 2  | 3     |    1    |    0    |   2
   | 3  | 3     |    1    |    1    |   1
   | 4  | 2     |    2    |    1    |   0

Can you give me some advise on this?

Body:
Use conditional aggregation:

select id, count(*) as cnt,
       sum(case when code = 'C' then 1 else 0 end) as code_c,
       sum(case when code = 'I' then 1 else 0 end) as code_i,
       sum(case when code = 'D' then 1 else 0 end) as code_d
from t
group by id;


问:
How to replace values of each cell on a dataframe without looping it
How can I apply for each cell of my dataframe this conditional (check if I have a string and if its found, replace with a 0) in an easier way?

```<code>for col in data.columns:
    for day in data.index:
        if (type(data_input_df.loc[day, col]) == 'str'):
            data_input_df[col][day] = 0
</code>```

The data dataframe is:

```<code>                           Log      1233.de ...      asdad.w.1    fff.op
Tagname                                     ...
01/06/2008 00:00            ON      343.04  ...        73.75      79.03
02/06/2008 00:00            ON      332.31  ...        73.71      79.21
03/06/2008 00:00            ON      339.25  ...        75.77      80.11
04/06/2008 00:00            ON      353.25  ...        76.47      79.75
05/06/2008 00:00            ON      353.44  ...        77.35      82.48
</code>```

Which is uploaded as:

```<code>dat =  pd.read_csv('data.csv', header = 0, index_col = "Tagname")
data = pd.DataFrame(data)
</code>```

答:
First select all columns filled by objects, here because data from read_csv are all objects strings, create dictionary and set 0 in DataFrame.assign:

```<code>d = dict.fromkeys(df.select_dtypes(object).columns, 0)
df = df.assign(**d)

print (df)
                  Log  1233.de  asdad.w.1  fff.op
Tagname
01/06/2008 00:00    0   343.04      73.75   79.03
02/06/2008 00:00    0   332.31      73.71   79.21
03/06/2008 00:00    0   339.25      75.77   80.11
04/06/2008 00:00    0   353.25      76.47   79.75
05/06/2008 00:00    0   353.44      77.35   82.48
</code>```

What if the dtypes of all columns are all object because of some string appearing in later rows?

Then if not missing values use to_numeric for convert all columns to numeric with errors='coerce' for missing values if not numbers and last only replace all missing values to 0:

```<code>df = df.apply(pd.to_numeric, errors='coerce').fillna(0)
</code>```

If possible missing values and need not change them is not possible use fillna (because replaced all NaNs), so is used DataFrame.mask with chained tested original data with new one:

```<code>df = df.apply(pd.to_numeric, errors='coerce').mask(lambda x: x.isna() & df.notna(), 0)
</code>```

Body:
How can I apply for each cell of my dataframe this conditional (check if I have a string and if its found, replace with a 0) in an easier way?

for col in data.columns:
    for day in data.index:
        if (type(data_input_df.loc[day, col]) == 'str'):
            data_input_df[col][day] = 0

The data dataframe is:

                           Log      1233.de ...      asdad.w.1    fff.op
Tagname                                     ...
01/06/2008 00:00            ON      343.04  ...        73.75      79.03
02/06/2008 00:00            ON      332.31  ...        73.71      79.21
03/06/2008 00:00            ON      339.25  ...        75.77      80.11
04/06/2008 00:00            ON      353.25  ...        76.47      79.75
05/06/2008 00:00            ON      353.44  ...        77.35      82.48

Which is uploaded as:

dat =  pd.read_csv('data.csv', header = 0, index_col = "Tagname")
data = pd.DataFrame(data)

Body:
First select all columns filled by objects, here because data from read_csv are all objects strings, create dictionary and set 0 in DataFrame.assign:

d = dict.fromkeys(df.select_dtypes(object).columns, 0)
df = df.assign(**d)

print (df)
                  Log  1233.de  asdad.w.1  fff.op
Tagname
01/06/2008 00:00    0   343.04      73.75   79.03
02/06/2008 00:00    0   332.31      73.71   79.21
03/06/2008 00:00    0   339.25      75.77   80.11
04/06/2008 00:00    0   353.25      76.47   79.75
05/06/2008 00:00    0   353.44      77.35   82.48

What if the dtypes of all columns are all object because of some string appearing in later rows?

Then if not missing values use to_numeric for convert all columns to numeric with errors='coerce' for missing values if not numbers and last only replace all missing values to 0:

df = df.apply(pd.to_numeric, errors='coerce').fillna(0)

If possible missing values and need not change them is not possible use fillna (because replaced all NaNs), so is used DataFrame.mask with chained tested original data with new one:

df = df.apply(pd.to_numeric, errors='coerce').mask(lambda x: x.isna() & df.notna(), 0)


问:
AnyLogic: Arrivals defined by rate & matching variables
I want to insert vehicles via an source block into a specific plant. My plants are a population based on an agent type where I want to program a generally applicable logic.

The arrival is defined by an arrival rate (e.g. 5 per week) which I want to read from the database. The database consists of the following columns: start (Name of the plant where the vehicle should start), depatures_per_week (rate), destination (destination of vehicle).

For example:

start= city1, depatures_per_week = 2, destination= dest1

start= city1, depatures_per_week = 0.5, destination= dest2

Now I have 2 rates for one source block. I want to add them up to one rate and write the destination according to the departures per week in the variable v_destination of the vehicle. So 0.2 % would get the dest2 and 0.8 % the dest1.

How can I write a code to define the destinations of the vehicles according to the individual rates?

Thanks!

答:
First, it seems you need to obtain the probability for each destination given the source. You can do this using a subquery which you consecutively join to the main query, or by using a window function. Personally I find the window function a bit clearer, so here is an example using a window function

```<code> SELECT
      start,
      destination,
      depatures_per_week / SUM(depatures_per_week) OVER (
            PARTITION BY start
            ORDER BY  destination
            ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
      ) * 100 as percentage
 FROM trains
</code>```

Full example:

```<code>postgres=# select start, destination,     departures_per_week /
SUM(departures_per_week) OVER (  PARTITION BY start  ORDER BY  destination
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) * 100 as percentage
from (values ( 'city1', 2.0, 'dest1') , ('city1', 0.5, 'dest2' )) as
trains(start, departures_per_week, destination);
 start | destination |       percentage
-------+-------------+-------------------------
 city1 | dest1       | 80.00000000000000000000
 city1 | dest2       | 20.00000000000000000000
(2 rows)
</code>```

It's possible to construct Window functions in QueryDSL SQL using WindowFunction. Window functions are not available in JPA however.

Body:
First, it seems you need to obtain the probability for each destination given the source. You can do this using a subquery which you consecutively join to the main query, or by using a window function. Personally I find the window function a bit clearer, so here is an example using a window function

 SELECT
      start,
      destination,
      depatures_per_week / SUM(depatures_per_week) OVER (
            PARTITION BY start
            ORDER BY  destination
            ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
      ) * 100 as percentage
 FROM trains

Full example:

postgres=# select start, destination,     departures_per_week /
SUM(departures_per_week) OVER (  PARTITION BY start  ORDER BY  destination
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) * 100 as percentage
from (values ( 'city1', 2.0, 'dest1') , ('city1', 0.5, 'dest2' )) as
trains(start, departures_per_week, destination);
 start | destination |       percentage
-------+-------------+-------------------------
 city1 | dest1       | 80.00000000000000000000
 city1 | dest2       | 20.00000000000000000000
(2 rows)

It's possible to construct Window functions in QueryDSL SQL using WindowFunction. Window functions are not available in JPA however.


问:
Import Webdrivemanager not resolved
Tried adding this maven dependency in Selenium for Webdrivermanager

```<code>    <!-- https://mvnrepository.com/artifact/io.github.bonigarcia/webdrivermanager -->
    <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>4.0.0</version>
            <scope>test</scope>
        </dependency>
</code>```

But still it complains as not resolved.

It was not automatically importing the package , so tried adding import io.github.bonigarcia.wdm.WebDriverManager; manually.

Still the issue is there.

Checked the previous post as of Apr 2020 , but not working for me.

答:
```<code>import io.github.bonigarcia.wdm.ChromeDriverManager;
import io.github.bonigarcia.wdm.FirefoxDriverManager;
</code>```

You can try to import specifically WebDriver managers.

And also could you please try older versions of bonigarcia like;

```<code><dependency>
   <groupId>io.github.bonigarcia</groupId>
   <artifactId>webdrivermanager</artifactId>
   <version>2.2.4</version>
 </dependency>
</code>```

Title: Import Webdrivemanager not resolved

Body:
Tried adding this maven dependency in Selenium for Webdrivermanager

    <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>4.0.0</version>
            <scope>test</scope>
        </dependency>

But still it complains as not resolved.

It was not automatically importing the package , so tried adding import io.github.bonigarcia.wdm.WebDriverManager; manually.

Still the issue is there.

Checked the previous post as of Apr 2020 , but not working for me.

Body:
import io.github.bonigarcia.wdm.ChromeDriverManager;
import io.github.bonigarcia.wdm.FirefoxDriverManager;

You can try to import specifically WebDriver managers.

And also could you please try older versions of bonigarcia like;

<dependency>
   <groupId>io.github.bonigarcia</groupId>
   <artifactId>webdrivermanager</artifactId>
   <version>2.2.4</version>
 </dependency>


问:
Replace \r from json in shell
I have below JSON in a variable name TASK_DEFINTIION
It has a \r character at the end of "image": "700707367057.dkr.ecr.us-east-1.amazonaws.com/php-demo:feature-feature01\r" under containerDefinitions

I am using TASK_DEFINITION_AFTER= 'echo $TASK_DEFINTIION | sed "s/\\r//g"' to remove the \r but seems it is removing all the hidden carriage return but not removing the one which is visible as regular character.

Any help would be highly appriciated.

```<code>{
      "memory": "1024",
      "networkMode": "awsvpc",
      "family": "ecs-php-demo",
      "placementConstraints": [],
      "cpu": "512",
      "executionRoleArn": "arn:aws:iam::700707367057:role/ecsTaskExecutionRole",
      "volumes": [],
      "requiresCompatibilities": [
        "FARGATE"
      ],
      "taskRoleArn": "arn:aws:iam::700707367057:role/ecsTaskExecutionRole",
      "containerDefinitions": [
        {
          "memoryReservation": 256,
          "environment": [],
          "name": "ecs-php-demo",
          "mountPoints": [],
          "image": "700707367057.dkr.ecr.us-east-1.amazonaws.com/php-demo:feature-feature01\r",
          "cpu": 0,
          "portMappings": [
            {
              "protocol": "tcp",
              "containerPort": 8080,
              "hostPort": 8080
            }
          ],
          "logConfiguration": {
            "logDriver": "awslogs",
            "options": {
              "awslogs-region": "us-east-1",
              "awslogs-stream-prefix": "ecs",
              "awslogs-group": "/ecs/ecs-php-demo"
            }
          },
          "essential": true,
          "volumesFrom": []
        }
      ]
    }
</code>```

答:
In your command, first \ escapes the second \, so sed sees only one \

You need :

```<code>TASK_DEFINITION_AFTER="$(echo $TASK_DEFINTIION | sed "s/\\\\r//g")"
</code>```

Title: Replace \r from json in shell

Body:
I have below JSON in a variable name TASK_DEFINTIION
It has a \r character at the end of "image": "700707367057.dkr.ecr.us-east-1.amazonaws.com/php-demo:feature-feature01\r" under containerDefinitions

I am using TASK_DEFINITION_AFTER= 'echo $TASK_DEFINTIION | sed "s/\\r//g"' to remove the \r but seems it is removing all the hidden carriage return but not removing the one which is visible as regular character.

Any help would be highly appriciated.

{
      "memory": "1024",
      "networkMode": "awsvpc",
      "family": "ecs-php-demo",
      "placementConstraints": [],
      "cpu": "512",
      "executionRoleArn": "arn:aws:iam::700707367057:role/ecsTaskExecutionRole",
      "volumes": [],
      "requiresCompatibilities": [
        "FARGATE"
      ],
      "taskRoleArn": "arn:aws:iam::700707367057:role/ecsTaskExecutionRole",
      "containerDefinitions": [
        {
          "memoryReservation": 256,
          "environment": [],
          "name": "ecs-php-demo",
          "mountPoints": [],
          "image": "700707367057.dkr.ecr.us-east-1.amazonaws.com/php-demo:feature-feature01\r",
          "cpu": 0,
          "portMappings": [
            {
              "protocol": "tcp",
              "containerPort": 8080,
              "hostPort": 8080
            }
          ],
          "logConfiguration": {
            "logDriver": "awslogs",
            "options": {
              "awslogs-region": "us-east-1",
              "awslogs-stream-prefix": "ecs",
              "awslogs-group": "/ecs/ecs-php-demo"
            }
          },
          "essential": true,
          "volumesFrom": []
        }
      ]
    }

Body:
In your command, first \ escapes the second \, so sed sees only one \

You need :

TASK_DEFINITION_AFTER="$(echo $TASK_DEFINTIION | sed "s/\\\\r//g")"


问:
R quantile function fails with small values
R quantile function fails at finding deciles of very small values, is there any algorithm that works better than others?</p>

答:
The R quantile function doesn't fail at finding deciles of very small values; it's just that the concept of deciles becomes ambiguous if you don't have many samples in your set. There are actually 9 different ways to calculate quantiles using the quantile function in R, which you can change by setting the type parameter.

Here is an example of attempting to extract the deciles of the vector c(1, 2, 3), with each of the 9 methods available. Do any of these meet your expectations? Personally, I like method 7 here, but I guess it really depends on how you define a decile, and for what purposes.

```<code>sapply(1:9, function(x) quantile(c(1:3), probs = seq(0, 1, 0.1), type = x))
#>      [,1] [,2] [,3] [,4] [,5] [,6] [,7]     [,8]  [,9]
#> 0%      1    1    1  1.0  1.0  1.0  1.0 1.000000 1.000
#> 10%     1    1    1  1.0  1.0  1.0  1.2 1.000000 1.000
#> 20%     1    1    1  1.0  1.1  1.0  1.4 1.000000 1.025
#> 30%     1    1    1  1.0  1.4  1.2  1.6 1.333333 1.350
#> 40%     2    2    1  1.2  1.7  1.6  1.8 1.666667 1.675
#> 50%     2    2    2  1.5  2.0  2.0  2.0 2.000000 2.000
#> 60%     2    2    2  1.8  2.3  2.4  2.2 2.333333 2.325
#> 70%     3    3    2  2.1  2.6  2.8  2.4 2.666667 2.650
#> 80%     3    3    2  2.4  2.9  3.0  2.6 3.000000 2.975
#> 90%     3    3    3  2.7  3.0  3.0  2.8 3.000000 3.000
#> 100%    3    3    3  3.0  3.0  3.0  3.0 3.000000 3.000
</code>```

Body:
The R quantile function doesn't fail at finding deciles of very small values; it's just that the concept of deciles becomes ambiguous if you don't have many samples in your set. There are actually 9 different ways to calculate quantiles using the quantile function in R, which you can change by setting the type parameter.

Here is an example of attempting to extract the deciles of the vector c(1, 2, 3), with each of the 9 methods available. Do any of these meet your expectations? Personally, I like method 7 here, but I guess it really depends on how you define a decile, and for what purposes.

sapply(1:9, function(x) quantile(c(1:3), probs = seq(0, 1, 0.1), type = x))
#>      [,1] [,2] [,3] [,4] [,5] [,6] [,7]     [,8]  [,9]
#> 0%      1    1    1  1.0  1.0  1.0  1.0 1.000000 1.000
#> 10%     1    1    1  1.0  1.0  1.0  1.2 1.000000 1.000
#> 20%     1    1    1  1.0  1.1  1.0  1.4 1.000000 1.025
#> 30%     1    1    1  1.0  1.4  1.2  1.6 1.333333 1.350
#> 40%     2    2    1  1.2  1.7  1.6  1.8 1.666667 1.675
#> 50%     2    2    2  1.5  2.0  2.0  2.0 2.000000 2.000
#> 60%     2    2    2  1.8  2.3  2.4  2.2 2.333333 2.325
#> 70%     3    3    2  2.1  2.6  2.8  2.4 2.666667 2.650
#> 80%     3    3    2  2.4  2.9  3.0  2.6 3.000000 2.975
#> 90%     3    3    3  2.7  3.0  3.0  2.8 3.000000 3.000
#> 100%    3    3    3  3.0  3.0  3.0  3.0 3.000000 3.000


问:
jsf navigation question
I have a JSF2 project with a "view user" page that reads the currently selected user from a session bean; userHandler.selectedUser.

The page is intended to be visited by navigating with links in the app.

However, if the user attempts to hit the "view user" page directly by this URL ...

http://localhost:8080/webapp/userView.jsf

... they see the page with no data on it (because there's no selected user in the userHandler).

I think what I'd like to do is redirect the user to the main page of the app if they try to hit it directly like that.  What is a simple and elegant way of handling this problem?

Thanks,
Rob

答:
You'd like to hook on the preRenderView event and then send a redirect when this is the case.

```<code><f:metadata>
    <f:event type="preRenderView" listener="#{bean.preRenderView}" />
</f:metadata>
</code>```

with

```<code>public void preRenderView() throws IOException {
    if (userHandler.getSelectedUser() == null) {
        FacesContext.getCurrentInstance().getExternalContext().redirect("home.jsf");
    }
}
</code>```

Title: jsf navigation question

Body:
You'd like to hook on the preRenderView event and then send a redirect when this is the case.

<f:metadata>
    <f:event type="preRenderView" listener="#{bean.preRenderView}" />
</f:metadata>

with

public void preRenderView() throws IOException {
    if (userHandler.getSelectedUser() == null) {
        FacesContext.getCurrentInstance().getExternalContext().redirect("home.jsf");
    }
}


问:
Apollo GraphQl react. How to clear query cache for all variable combinations?
I am using apollo graphql in my react application.
Say I have the following query:

```<code>query ListQuery($filter: String!) {
   items(filter: $filter) {
     id
     name
   }
}
</code>```

This query lets me query a list of items using a filter. Say I used filter string A, and then used filter string B. The cache would now contain two entries: ListQuery(A) and ListQuery(B).

Now let's say I use a mutation to add a new item. How can I remove all the cached queries from the cache? So in this case, I want to remove both ListQuery(A) and ListQuery(B) from the cache.

How can I accomplish this?

答:
Try this:

```<code> query ListQuery($filter: String!) {
       items(filter: $filter) {
         id
         name
       }
    },
    fetchPolicy: 'no-cache'
</code>```

More here:
https://www.apollographql.com/docs/react/caching/cache-interaction/#bypassing-the-cache

Body:
I am using apollo graphql in my react application.
Say I have the following query:

query ListQuery($filter: String!) {
   items(filter: $filter) {
     id
     name
   }
}

This query lets me query a list of items using a filter. Say I used filter string A, and then used filter string B. The cache would now contain two entries: ListQuery(A) and ListQuery(B).

Now let's say I use a mutation to add a new item. How can I remove all the cached queries from the cache? So in this case, I want to remove both ListQuery(A) and ListQuery(B) from the cache.

How can I accomplish this?

Body:
Try this:

 query ListQuery($filter: String!) {
       items(filter: $filter) {
         id
         name
       }
    },
    fetchPolicy: 'no-cache'

More here:
https://www.apollographql.com/docs/react/caching/cache-interaction/#bypassing-the-cache


问:
How to publish multiple Fitnesse result reports in one Jenkins job?
I set up one Jenkins job to run two Fitnesse tests at the build section:

Therefore I have two result files:

/data/test-automation/FitNesseResults/Home.Test1/results.xml

/data/test-automation/FitNesseResults/Home.Test2/results.xml

The job is working fine, but I can't publish the results of both FitNesse tests at the Post Build Actions section:

It only provides one input field. I have heard it should be possible to specify two result files with an ant pattern, but haven't found an example.
How can I publish both result xmls?

答:
You could use a file pattern like results*.xml

In your example you can store your test results like:

```<code>data/test-automation/FitNesseResults/HomeTest1.results.xml

data/test-automation/FitNesseResults/HomeTest2.results.xml
</code>```

And you set the "Publish Fitnesse results report" to:

```<code>/data/test-automation/FitNesseResults/*.results.xml
</code>```

Body:
You could use a file pattern like results*.xml

In your example you can store your test results like:

data/test-automation/FitNesseResults/HomeTest1.results.xml

data/test-automation/FitNesseResults/HomeTest2.results.xml

And you set the "Publish Fitnesse results report" to:

/data/test-automation/FitNesseResults/*.results.xml


问:
How to count years in the text in R?
I want to count years found between the opening and closing brackets in the following text named txt.

```<code>library(stringr)
txt <- "Text Mining exercise (2020) Mining, p. 628508; Computer Science text analysis (1998) Computer Science, p.345-355; Introduction to data mining (2015) J. Data Science, pp. 31-33"
</code>```

lengths(strsplit(txt,"\\(\\d{4}\\)")) gives me 4 which is wrong. Any help, please?

答:
I think you are looking for stringr::str_count():

```<code>str_count(txt, "\\([0-9]{4}\\)")
[1] 3
</code>```

To include only number of four digits within parentheses that also start with 1 or 2 followed by either 0 or 9:

```<code>str_count(txt, "\\([1-2][0|9][0-9]{2}\\)")
</code>```

Strictly starting with either 19 or 20:

```<code>str_count(txt, "\\(19[0-9]{2}\\)|\\(20[0-9]{2}\\)")
# In R 4.0
str_count(txt, r"(\(19[0-9]{2}\)|\(20[0-9]{2}\))")
</code>```

Title: How to count years in the text in R?

Body:
I want to count years found between the opening and closing brackets in the following text named txt.

library(stringr)
txt <- "Text Mining exercise (2020) Mining, p. 628508; Computer Science text analysis (1998) Computer Science, p.345-355; Introduction to data mining (2015) J. Data Science, pp. 31-33"

lengths(strsplit(txt,"\\(\\d{4}\\)")) gives me 4 which is wrong. Any help, please?

Body:
I think you are looking for stringr::str_count():

str_count(txt, "\\([0-9]{4}\\)")
[1] 3

To include only number of four digits within parentheses that also start with 1 or 2 followed by either 0 or 9:

str_count(txt, "\\([1-2][0|9][0-9]{2}\\)")

Strictly starting with either 19 or 20:

str_count(txt, "\\(19[0-9]{2}\\)|\\(20[0-9]{2}\\)")
# In R 4.0
str_count(txt, r"(\(19[0-9]{2}\)|\(20[0-9]{2}\))")


Title: How to convert the byte datatype to dataframe?

Body:
I am downloading a elnino dataset from UCI ML repository. Please refer to attached link for dataset.

https://archive.ics.uci.edu/ml/machine-learning-databases/el_nino-mld/elnino.gz

I used the following code to unpack the .gz file.

import gzip

with gzip.open('C:\\Users\\suel.abbasi\\Downloads\\tao-all2.dat.gz', 'r') as file:
    for line in file:
        print(line)

The output for the above code is below

b'1 80 3 7 800307 -0.02 -109.46 -6.8 0.7 . 26.14 26.24\n'
b'2 80 3 8 800308 -0.02 -109.46 -4.9 1.1 . 25.66 25.97\n'
b'3 80 3 9 800309 -0.02 -109.46 -4.5 2.2 . 25.69 25.28\n'
b'4 80 3 10 800310 -0.02 -109.46 -3.8 1.9 . 25.57 24.31\n'
b'5 80 3 11 800311 -0.02 -109.46 -4.2 1.5 . 25.3 23.19\n'
b'6 80 3 12 800312 -0.02 -109.46 -4.4 0.3 . 24.72 23.64\n'
b'7 80 3 13 800313 -0.02 -109.46 -3.2 0.1 . 24.66 24.34\n'
b'8 80 3 14 800314 -0.02 -109.46 -3.1 0.6 . 25.17 24.14\n'
b'9 80 3 15 800315 -0.02 -109.46 -3 1 . 25.59 24.24\n'
b'10 80 3 16 800316 -0.02 -109.46 -1.2 1 . 26.71 25.94\n'
b'11 80 3 17 800317 -0.02 -109.46 -0.1 0.7 . 27.28 26.65\n'
b'12 80 3 18 800318 -0.02 -109.46 -1.2 2.3 . 26.86 27.13\n'
b'13 80 3 19 800319 -0.02 -109.46 -4.1 -0.3 . 26.38 26.35\n'
b'14 80 3 20 800320 -0.02 -109.46 -4.8 -0.8 . 26.19 25.87\n'
b'15 80 3 21 800321 -0.02 -109.46 -5.2 2 . 26.08 25.38\n'
b'16 80 3 22 800322 -0.02 -109.46 -2.7 2.7 . 26.24 .\n'
b'17 80 3 23 800323 -0.02 -109.46 -4.4 1.1 . 26.05 .\n'
b'18 80 3 24 800324 -0.02 -109.46 -4.3 0.7 . 25.67 .\n'
b'19 80 3 25 800325 -0.02 -109.46 -3.8 0.5 . 25.39 .\n'

Now, I am not able to figure out how to convert this to a dataframe?
Please help

Body:
Pandas can read zipped text (csv) files with read_csv, just specify the separator:

df = pd.read_csv('elnino.gz', sep='\s+', header=None)

Result:

      0   1     2       3     4     5     6      7      8
0     1   1  8.96 -140.32  -6.3  -6.4  83.5  27.32  27.57
1     1   2  8.95 -140.32  -5.7  -3.6  86.4  26.70  27.62
2     1   3  8.96 -140.32  -6.2  -5.8  83.0  27.36  27.68
3     1   4  8.96 -140.34  -6.4  -5.3  82.2  27.32  27.70
4     1   5  8.96 -140.33  -4.9  -6.2  87.3  27.09  27.85
..   ..  ..   ...     ...   ...   ...   ...    ...    ...
777  59  10 -8.04  164.82     .     .  93.6  26.89  28.52
778  59  11 -8.04  164.82     .     .  92.3  27.62  28.44
779  59  12 -8.03  164.81     .     .  93.2  28.33  28.43
780  59  13 -8.04  164.82     .     .  95.5  28.44  28.51
781  59  14 -8.04  164.81     .     .  93.4  28.67  28.61

[782 rows x 9 columns]

PS: column names you can get from elnino.col this way:

df.columns = pd.read_csv('elnino.col', header=None).iloc[:,0].values


问:
Combining date and time using moment causing deprecation warning
In my nodejs application, I have user-based input for starting date and starting time for achieving some task. I need to combine start date and start time input by the user and insert it into one DateTime object format as: 2020-05-29T10:43:39.278Z. Here is the code:

```<code>function(start_time, start_date){
    const time = moment(start_time).format('LT');
    console.log('show timing', time); // gives, 4:12 PM

    const d = moment(start_date).format('L');
    console.log('new date', d); //gives, 05/29/2020

    const final_start_date = moment(d +' '+ time).format();
    console.log('final_start_date', final_start_date)
  }
</code>```

But console.log('final_start_date', final_start_date) throws an error as :

```<code>Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments:
[0] _isAMomentObject: true, _isUTC: false, _useUTC: false, _l: undefined, _i: 05/29/2020 4:12 PM, _f: undefined, _strict: undefined, _locale: [object Object]
Error
</code>```

The arguments start_time and start_date are stored in MongoDB as ISO format with a Date type.
I am unable to understand where things are getting wrong, kindly help to resolve the issue.

------------------UPDATION------------------

```<code> const START_TIME = moment(start_time, "hh:mm:ss").format("LT"),
    END_TIME = moment(end_time, "hh:mm:ss").format("LT");

  const START_DATE = moment(start_date, "DD/MM/YYYY").format("L"),
    END_DATE = moment(end_date, "DD/MM/YYYY").format("L");

    console.log("START-TIME: ", START_TIME);
    console.log("END-TIME: ", END_TIME)

    console.log("START-DATE: ", START_DATE);
    console.log("END-DATE: ", END_DATE)

  const START_AT = moment(START_DATE + " " + START_TIME, "DD/MM/YYYY hh:mm:ss").format(),
    END_AT = moment(END_DATE + " " + END_TIME, "DD/MM/YYYY hh:mm:ss").format();

    console.log("START-AT: ", START_AT);
    console.log("END-AT: ", END_AT)
</code>```

console.logs()

```<code>START-TIME:  8:29 PM
END-TIME:  8:30 PM
START-DATE:  05/29/2020
END-DATE:  05/29/2020
START-AT:  Invalid date
END-AT:  Invalid date
</code>```

答:
It's best to use an ISO 8601 format when passing a string to moment (without a format string), we can do this by formatting the time and date to this format separately, then concatenating.

function createFinalStartDate(start_time, start_date){
    const time = moment(start_time).format('HH:mm:ss');
    console.log('Time component:', time);
    const d = moment(start_date).format('YYYY-MM-DD');
    console.log('Date component:', d);
    let isoTimestamp = `${d}T${time}`;
    console.log("ISO 8601 timestamp:", isoTimestamp);
    const final_start_date = moment(isoTimestamp).format();
    console.log('final_start_date', final_start_date)
}

function test() {
    let start_time = new Date();
    let start_date = new Date();
    createFinalStartDate(start_time, start_date);
}

test();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script></code>```

Body:
In my nodejs application, I have user-based input for starting date and starting time for achieving some task. I need to combine start date and start time input by the user and insert it into one DateTime object format as: 2020-05-29T10:43:39.278Z. Here is the code:

function(start_time, start_date){
    const time = moment(start_time).format('LT');
    console.log('show timing', time); // gives, 4:12 PM

    const d = moment(start_date).format('L');
    console.log('new date', d); //gives, 05/29/2020

    const final_start_date = moment(d +' '+ time).format();
    console.log('final_start_date', final_start_date)
  }

But console.log('final_start_date', final_start_date) throws an error as :

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments:
[0] _isAMomentObject: true, _isUTC: false, _useUTC: false, _l: undefined, _i: 05/29/2020 4:12 PM, _f: undefined, _strict: undefined, _locale: [object Object]
Error

The arguments start_time and start_date are stored in MongoDB as ISO format with a Date type.
I am unable to understand where things are getting wrong, kindly help to resolve the issue.

------------------UPDATION------------------

 const START_TIME = moment(start_time, "hh:mm:ss").format("LT"),
    END_TIME = moment(end_time, "hh:mm:ss").format("LT");

  const START_DATE = moment(start_date, "DD/MM/YYYY").format("L"),
    END_DATE = moment(end_date, "DD/MM/YYYY").format("L");

    console.log("START-TIME: ", START_TIME);
    console.log("END-TIME: ", END_TIME)

    console.log("START-DATE: ", START_DATE);
    console.log("END-DATE: ", END_DATE)

  const START_AT = moment(START_DATE + " " + START_TIME, "DD/MM/YYYY hh:mm:ss").format(),
    END_AT = moment(END_DATE + " " + END_TIME, "DD/MM/YYYY hh:mm:ss").format();

    console.log("START-AT: ", START_AT);
    console.log("END-AT: ", END_AT)

console.logs()

START-TIME:  8:29 PM
END-TIME:  8:30 PM
START-DATE:  05/29/2020
END-DATE:  05/29/2020
START-AT:  Invalid date
END-AT:  Invalid date

Body:
It's best to use an ISO 8601 format when passing a string to moment (without a format string), we can do this by formatting the time and date to this format separately, then concatenating.

function createFinalStartDate(start_time, start_date){
    const time = moment(start_time).format('HH:mm:ss');
    console.log('Time component:', time);
    const d = moment(start_date).format('YYYY-MM-DD');
    console.log('Date component:', d);
    let isoTimestamp = `${d}T${time}`;
    console.log("ISO 8601 timestamp:", isoTimestamp);
    const final_start_date = moment(isoTimestamp).format();
    console.log('final_start_date', final_start_date)
}

function test() {
    let start_time = new Date();
    let start_date = new Date();
    createFinalStartDate(start_time, start_date);
}

test();

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>


问:
Blynk.syncVirtual(V1) not updating Virtual Pins values
I was trying this code to run stepper motors and print Blynk app joystick's X and Y coordinates. But the code is only getting the joystick values once. But it works fine when I use if condition instead of while(). I needed while condition to run stepper motors continuously but with if condition they turn off and on very quickly decrease the speed of stepper motors.

Please help me deal this situation

Code

```<code>#define BLYNK_PRINT Serial

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <AccelStepper.h>
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "LRTCZUnCI06P-pqh5rlPXRbuOUgQ_uGH";

AccelStepper stepper_1(1,D2,D1);
AccelStepper stepper_2(1,D5,D6);

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "Airtel_7599998800";
char pass[] = "air71454";

int prev_x = 0;
int prev_y = 0;

BLYNK_WRITE(V1) {
  int x = param[0].asInt();
  int y = param[1].asInt();

  // Do something with x and y
  Serial.print("X = ");
  Serial.print(x);
  Serial.print("; Y = ");
  Serial.println(y);

  MoveControls(x , y);
}

void setup()
{
  // Debug console
  Serial.begin(9600);

  stepper_1.setAcceleration(1000);
  stepper_2.setAcceleration(1000);

  Blynk.begin(auth, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
  //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);
// ESP.wdtDisable();
// ESP.wdtEnable(WDTO_8S);
}

void loop()
{// ESP.wdtFeed();

  Blynk.run();
 // Serial.println("A");
}

void MoveControls(int x, int y) {

 ///////////////////////////////////////////Move Forward////////////////////////////////////////////////////

  if(y >= 150 && x <= 150 && x >= -150){
    stepper_1.enableOutputs();
    stepper_2.enableOutputs();

    stepper_1.setMaxSpeed(1000);
    stepper_2.setMaxSpeed(1000);

    stepper_1.move(1000);
    stepper_2.move(1000);

    while(x != prev_x && y != prev_y){

    stepper_1.run();
    stepper_2.run();

    Blynk.syncVirtual(V1);
    Blynk.run();

    Serial.print("X = ");
    Serial.print(x);
    Serial.print("; Y = ");
    Serial.println(y);
    }

    prev_x = x;
    prev_y = y;

  }

 ///////////////////////////////////////////Neutral Zone////////////////////////////////////////////////////
 if(y <= 150 && x <= 150 && x >= -150 && y >= -150){
    stepper_1.disableOutputs();
    stepper_2.disableOutputs();

  prev_x = x;
  prev_y = y;
  }

  yield();
  }
</code>```

This is that while loop

```<code>while(x != prev_x && y != prev_y){

    stepper_1.run();
    stepper_2.run();

    Blynk.syncVirtual(V1);
    Blynk.run();

    Serial.print("X = ");
    Serial.print(x);
    Serial.print("; Y = ");
    Serial.println(y);
    }

    prev_x = x;
    prev_y = y;

  }
</code>```

I know that the code is very much wrong and doesn't make much sense but I need to fix only the Blynk.syncVirtual() issue.

I also tried to add Blynk.run() after Blynk.syncVirtual() because someone told in Blynk Community to do that
https://community.blynk.cc/t/blynk-syncvirtual-doesnt-work-as-expected/40047/4

答:
Does this work?</p>

```<code>while(y <= 150 && x <= 150 && x >= -150 && y >= -150) {

stepper_1.run();
stepper_2.run();

Blynk.syncVirtual(V1);
Blynk.run();

Serial.print("X = ");
Serial.print(x);
Serial.print("; Y = ");
Serial.println(y);
}

//prev_x = x;
//prev_y = y;
</code>```

Body:
I was trying this code to run stepper motors and print Blynk app joystick's X and Y coordinates. But the code is only getting the joystick values once. But it works fine when I use if condition instead of while(). I needed while condition to run stepper motors continuously but with if condition they turn off and on very quickly decrease the speed of stepper motors.

Please help me deal this situation

Code

#define BLYNK_PRINT Serial

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <AccelStepper.h>
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "LRTCZUnCI06P-pqh5rlPXRbuOUgQ_uGH";

AccelStepper stepper_1(1,D2,D1);
AccelStepper stepper_2(1,D5,D6);

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "Airtel_7599998800";
char pass[] = "air71454";

int prev_x = 0;
int prev_y = 0;

BLYNK_WRITE(V1) {
  int x = param[0].asInt();
  int y = param[1].asInt();

  // Do something with x and y
  Serial.print("X = ");
  Serial.print(x);
  Serial.print("; Y = ");
  Serial.println(y);

  MoveControls(x , y);
}

void setup()
{
  // Debug console
  Serial.begin(9600);

  stepper_1.setAcceleration(1000);
  stepper_2.setAcceleration(1000);

  Blynk.begin(auth, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
  //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);
// ESP.wdtDisable();
// ESP.wdtEnable(WDTO_8S);
}

void loop()
{// ESP.wdtFeed();

  Blynk.run();
 // Serial.println("A");
}

void MoveControls(int x, int y) {

 ///////////////////////////////////////////Move Forward////////////////////////////////////////////////////

  if(y >= 150 && x <= 150 && x >= -150){
    stepper_1.enableOutputs();
    stepper_2.enableOutputs();

    stepper_1.setMaxSpeed(1000);
    stepper_2.setMaxSpeed(1000);

    stepper_1.move(1000);
    stepper_2.move(1000);

    while(x != prev_x && y != prev_y){

    stepper_1.run();
    stepper_2.run();

    Blynk.syncVirtual(V1);
    Blynk.run();

    Serial.print("X = ");
    Serial.print(x);
    Serial.print("; Y = ");
    Serial.println(y);
    }

    prev_x = x;
    prev_y = y;

  }

 ///////////////////////////////////////////Neutral Zone////////////////////////////////////////////////////
 if(y <= 150 && x <= 150 && x >= -150 && y >= -150){
    stepper_1.disableOutputs();
    stepper_2.disableOutputs();

  prev_x = x;
  prev_y = y;
  }

  yield();
  }

This is that while loop

while(x != prev_x && y != prev_y){

    stepper_1.run();
    stepper_2.run();

    Blynk.syncVirtual(V1);
    Blynk.run();

    Serial.print("X = ");
    Serial.print(x);
    Serial.print("; Y = ");
    Serial.println(y);
    }

    prev_x = x;
    prev_y = y;

  }

I know that the code is very much wrong and doesn't make much sense but I need to fix only the Blynk.syncVirtual() issue.

I also tried to add Blynk.run() after Blynk.syncVirtual() because someone told in Blynk Community to do that
https://community.blynk.cc/t/blynk-syncvirtual-doesnt-work-as-expected/40047/4

Body:
Does this work?

while(y <= 150 && x <= 150 && x >= -150 && y >= -150) {

stepper_1.run();
stepper_2.run();

Blynk.syncVirtual(V1);
Blynk.run();

Serial.print("X = ");
Serial.print(x);
Serial.print("; Y = ");
Serial.println(y);
}

//prev_x = x;
//prev_y = y;


问:
Plotly Dash: How to resolve the error dash_html_components.Div detected a component for a prop other than children
I am trying to add text in line with my plots such that my text are easy to understand with the results of the plots. When I try to structure the first tab, I get the following error:

```<code>TypeError: The dash_html_components.Divcomponent (version 1.0.3) with the ID "Div(children=(Br(None), P('Select a year and month to query'), Br(None)), id='paragraph1')" detected a Component for a prop other thanchildrenDid you forget to wrap multiplechildren in an array? Prop n_clicks has value Div(children=[Dropdown(id='month', options=[{'label': 'January', 'value': 1}, {'label': 'February', 'value': 2}, {'label': 'March', 'value': 3}, {'label': 'April', 'value': 4}, {'label': 'May', 'value': 5}, {'label': 'June', 'value': 6}, {'label': 'July', 'value': 7}, {'label': 'August', 'value': 8}, {'label': 'September', 'value': 9}, {'label': 'October', 'value': 10}, {'label': 'November', 'value': 11}, {'label': 'December', 'value': 12}], value=3, style={'width': '50%'})], style={'width': '100%', 'display': 'flex', 'flex-direction': 'row'})
</code>```

And here is the section of the code that is buggy:

```<code>def tab_layout():

     return html.Div(

            html.Div(

                        id="markdown-container",

                        children=dcc.Markdown(

                            children=(

                                """

                                    my text text

                                    ### Funnel Area Chat

                                    more text more text more text

                    """

                            ),

                            style={"color": "white"}

                        ),

                    ),

            html.Div(

                id="paragraph1",

                children= (

                    html.Br(),

                    html.P("Select a year and month to query"),

                    html.Br()

                )

            ),

             html.Div([

                dcc.Dropdown(

                    id="month",

                    options= month_options(),

                    value=3,

                    style={"width": "50%"}

                    ),

                    ], style={"width": "100%", "display": "flex", "flex-direction": "row"}),

                 dcc.Dropdown(

                     id="year",

                     options=[

                         {"label": "2019", "value": 2019},

                         {"label": "2020", "value": 2020}

                     ],

                     value=2020,

                     style={"width": "50%", "display": "flex", "flex-direction": "row",

                            "justify-content": "left"}

                     ),

            html.Div([

                dcc.Graph(id="funnel_plot",

                          config= {

                              "displaylogo": False,

                              "toImageButtonOptions": {"width": None, "height": None}

                          }

                        )

                ], style={"width": "100%", "display": "inline-block"})

                )
</code>```

What could be wrong? The compiler does not see any error?

答:
When you include multiple elements in the children property of an html.Div() you need to make sure that they are enclosed in square brackets, as the children property of an html.Div() is a list (see the documentation).

```<code>import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go

app = dash.Dash()

app.layout = html.Div(children=[

    html.Div(children=[

        html.Div(

            id="markdown-container",

            children=dcc.Markdown(

                children="""

                        my text text

                        ### Funnel Area Chat

                        more text more text more text

                    """,

                style={"color": "white"}

            ),

        ),

        html.Div(

            id="paragraph1",

            children=[

                html.Br(),

                html.P("Select a year and month to query"),

                html.Br()

            ]

        ),

        html.Div(children=[

            dcc.Dropdown(

                id="month",

                value=3,

                style={"width": "50%"}

            ),

        ], style={"width": "100%", "display": "flex", "flex-direction": "row"}),

        dcc.Dropdown(

            id="year",

            options=[

                {"label": "2019", "value": 2019},

                {"label": "2020", "value": 2020}

            ],

            value=2020,

            style={"width": "50%", "display": "flex", "flex-direction": "row",

                   "justify-content": "left"}

        ),

        html.Div(children=[

            dcc.Graph(id="funnel_plot",

                      config={

                          "displaylogo": False,

                          "toImageButtonOptions": {"width": None, "height": None}

                      }

            ),

        ], style={"width": "100%", "display": "inline-block"}),

    ])

])

app.run_server(debug=False)
</code>```

Body:
I am trying to add text in line with my plots such that my text are easy to understand with the results of the plots. When I try to structure the first tab, I get the following error:

TypeError: The dash_html_components.Divcomponent (version 1.0.3) with the ID "Div(children=(Br(None), P('Select a year and month to query'), Br(None)), id='paragraph1')" detected a Component for a prop other thanchildrenDid you forget to wrap multiplechildren in an array? Prop n_clicks has value Div(children=[Dropdown(id='month', options=[{'label': 'January', 'value': 1}, {'label': 'February', 'value': 2}, {'label': 'March', 'value': 3}, {'label': 'April', 'value': 4}, {'label': 'May', 'value': 5}, {'label': 'June', 'value': 6}, {'label': 'July', 'value': 7}, {'label': 'August', 'value': 8}, {'label': 'September', 'value': 9}, {'label': 'October', 'value': 10}, {'label': 'November', 'value': 11}, {'label': 'December', 'value': 12}], value=3, style={'width': '50%'})], style={'width': '100%', 'display': 'flex', 'flex-direction': 'row'})

And here is the section of the code that is buggy:

def tab_layout():

     return html.Div(

            html.Div(

                        id="markdown-container",

                        children=dcc.Markdown(

                            children=(

                                """

                                    my text text

                                    ### Funnel Area Chat

                                    more text more text more text

                    """

                            ),

                            style={"color": "white"}

                        ),

                    ),

            html.Div(

                id="paragraph1",

                children= (

                    html.Br(),

                    html.P("Select a year and month to query"),

                    html.Br()

                )

            ),

             html.Div([

                dcc.Dropdown(

                    id="month",

                    options= month_options(),

                    value=3,

                    style={"width": "50%"}

                    ),

                    ], style={"width": "100%", "display": "flex", "flex-direction": "row"}),

                 dcc.Dropdown(

                     id="year",

                     options=[

                         {"label": "2019", "value": 2019},

                         {"label": "2020", "value": 2020}

                     ],

                     value=2020,

                     style={"width": "50%", "display": "flex", "flex-direction": "row",

                            "justify-content": "left"}

                     ),

            html.Div([

                dcc.Graph(id="funnel_plot",

                          config= {

                              "displaylogo": False,

                              "toImageButtonOptions": {"width": None, "height": None}

                          }

                        )

                ], style={"width": "100%", "display": "inline-block"})

                )

What could be wrong? The compiler does not see any error?

Body:
When you include multiple elements in the children property of an html.Div() you need to make sure that they are enclosed in square brackets, as the children property of an html.Div() is a list (see the documentation).

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go

app = dash.Dash()

app.layout = html.Div(children=[

    html.Div(children=[

        html.Div(

            id="markdown-container",

            children=dcc.Markdown(

                children="""

                        my text text

                        ### Funnel Area Chat

                        more text more text more text

                    """,

                style={"color": "white"}

            ),

        ),

        html.Div(

            id="paragraph1",

            children=[

                html.Br(),

                html.P("Select a year and month to query"),

                html.Br()

            ]

        ),

        html.Div(children=[

            dcc.Dropdown(

                id="month",

                value=3,

                style={"width": "50%"}

            ),

        ], style={"width": "100%", "display": "flex", "flex-direction": "row"}),

        dcc.Dropdown(

            id="year",

            options=[

                {"label": "2019", "value": 2019},

                {"label": "2020", "value": 2020}

            ],

            value=2020,

            style={"width": "50%", "display": "flex", "flex-direction": "row",

                   "justify-content": "left"}

        ),

        html.Div(children=[

            dcc.Graph(id="funnel_plot",

                      config={

                          "displaylogo": False,

                          "toImageButtonOptions": {"width": None, "height": None}

                      }

            ),

        ], style={"width": "100%", "display": "inline-block"}),

    ])

])

app.run_server(debug=False)


问:
How to fix Alexa problem requested skill response?
I've been working on an Alexa skill for a while. This skill was working fine for weeks but now I only get the response "There was a problem with the requested skill's response" anymore. When I send the same request wtih postman everthing works fine so the function app is not the problem. Then I thought ngRok might have been the problem and I uploaded the Azure function to the online platform. But still I get the same error.
Has anyone an idea of what might be wrong? The only thing I could think of is the endpoint but the url is correct and the Azure function works like it is supposed to.

When I used ngRok no requested even reaches my function, this is probaly also the case with the online Azure function.

Thanks in advance.

答:
You need to activate Display Interface in the interfaces panel.

On the left Menu, under "JSON Editor" you have "Interfaces".
Click on it and activate "Display Interface". Then, rebuild your Skill.

For more details, you could refer to this issue.


问:
Configure MinGW-w64 for 32bit and 64bit Executables
I honestly have spent too long Googling this.

I would like to setup MinGW-w64 so that I can simply pass the -w32 flag in order to create a 32-bit executable, and leave it as default to create a 64-bit executable.

During the setup of MinGW-w64, I have numerous options. For Architecture there is i686 and x86_64. For exception there is dwarf, SJIJ, and SEH.

This thread here (How do I compile and link a 32-bit Windows executable using mingw-w64) suggests that only SJIJ allows the -m32 flag to be passed in order to create a 32-bit binary, however I have found conflicting information elsewhere.

How can I set up MinGW so that I can easily both 32-bit and 64-bit architectures?

Thanks

答:
What I do is set up seperate MinGW-w64 toolchains, one for 32-bit and one for 64-bit Windows.

That way there is no confusion and the 2 won't ever accidentally get mixed up if some parameter is forgotten.

You ca get a recent version of both toolchains from http://winlibs.com/


问:
Laravel - Get records between two dates from second table
I have something like this:

Table 1: Training Name, created_at, user_id (Plan_Treninga)

Table 2: user_id, created_at, expire_at (InvoiceUser)

I want to pull all from Table 1 where created_at is between Table 2 created_at and expire_at.

This is something what i am trying to..

```<code>$plan = Plan_Treninga::whereBetween(function($q) use ($id){
          $inv = InvoiceUser::where([
            ["user_id",$id],
            ["status","paid"],
          ])->latest("id")->first();
        })
</code>```

I haven't finished it yet, but my brain stopped working so I have to ask here.

答:
If I understand what you want clearly is. you want to query all from table 1 which created exist between table 2 created and expire_at right? if so you can use where exist query to achieve this.

```<code>// assume your table name is plan_treningas & invoice_users
Plan_Treninga::whereExists(function ($query) {
    $query->select(DB::raw(1))
          ->from('invoice_users')
          ->whereRaw('plan_treningas.created_at BETWEEN invoice_users.created_at AND invoice_users.expire_at'); // add more query depend your logic
})->get();

</code>```

for more you can take a look at docs

or if you want to use raw query

```<code>SELECT
*
FROM plan_treningas
WHERE EXISTS (
    SELECT 1 FROM invoice_users WHERE plan_treningas.created_at BETWEEN invoice_users.created_at AND invoice_users.expire_at
)

</code>```

Body:
I have something like this:

Table 1: Training Name, created_at, user_id (Plan_Treninga)

Table 2: user_id, created_at, expire_at (InvoiceUser)

I want to pull all from Table 1 where created_at is between Table 2 created_at and expire_at.

This is something what i am trying to..

$plan = Plan_Treninga::whereBetween(function($q) use ($id){
          $inv = InvoiceUser::where([
            ["user_id",$id],
            ["status","paid"],
          ])->latest("id")->first();
        })

I haven't finished it yet, but my brain stopped working so I have to ask here.

Body:
If I understand what you want clearly is. you want to query all from table 1 which created exist between table 2 created and expire_at right? if so you can use where exist query to achieve this.

// assume your table name is plan_treningas & invoice_users
Plan_Treninga::whereExists(function ($query) {
    $query->select(DB::raw(1))
          ->from('invoice_users')
          ->whereRaw('plan_treningas.created_at BETWEEN invoice_users.created_at AND invoice_users.expire_at'); // add more query depend your logic
})->get();

for more you can take a look at docs

or if you want to use raw query

SELECT
*
FROM plan_treningas
WHERE EXISTS (
    SELECT 1 FROM invoice_users WHERE plan_treningas.created_at BETWEEN invoice_users.created_at AND invoice_users.expire_at
)


问:
Best practices for tagging a ECS task?
We can add tags to EC2 instances to help us better track billing usages and to manage instances. </p>

<p>Is there a way to achieve when deploying containers in ECS? I would like the running container to have the ability to know what tag it currently have attached. </p>

答:
Just found this while trying to work out the current situation. For future searchers: I believe tagging was added some time after this question, in late 2018.

I've not yet worked out if you can set this up in the Console or if it's a feature of the API only, but e.g. the Terraform AWS provider now lets you set service or task definition tags to 'bubble through' to tasks – including Fargate ones – via propagate_tags.

I've just enabled this and it works but forces a new ECS service – I guess this is related to it not being obviously editable in the Console UI.

Title: Best practices for tagging a ECS task?

Body:
We can add tags to EC2 instances to help us better track billing usages and to manage instances.

Is there a way to achieve when deploying containers in ECS? I would like the running container to have the ability to know what tag it currently have attached.


问:
Aggregating column values based on range
I'm new to SQL and stackoverflow, forgive if my question is trivial. I have record of customers purchase quantities in a table, so I want a count of customers whose purchase fall in a range.

```<code>TABLE:
+-------------+----------------+
| customer_id | order_quantity |
+-------------+----------------+
|         123 |          10000 |
|         143 |           5000 |
|         999 |         200000 |
|         555 |          50000 |
+-------------+----------------+
</code>```

The goal is to count how many customers buy < 5000, between 5000-50000 and 50000-100000 order quantities.

I used:

```<code>SELECT customer_id,
      CASE
         WHEN COUNT(order_quantity) < 5000
         ....
FROM purchases
</code>```

Which isn't correct (don't even work).

答:
You can use:

```<code>select (case when order_quantity < 5000 then '[0-5000)'
             when order_quantity < 10000 then '[5000-10000)'
             else '10000+'
        end) as grp,
       count(*) as num_purchases,
       count(distinct customer_id) as num_customers
from t
group by grp
order by min(order_quantity);
</code>```

If a customer makes more than one purchase in a given group, it is not clear if you want to count the number of purchases or the number of customers.  This does both.

Body:
I'm new to SQL and stackoverflow, forgive if my question is trivial. I have record of customers purchase quantities in a table, so I want a count of customers whose purchase fall in a range.

TABLE:
+-------------+----------------+
| customer_id | order_quantity |
+-------------+----------------+
|         123 |          10000 |
|         143 |           5000 |
|         999 |         200000 |
|         555 |          50000 |
+-------------+----------------+

The goal is to count how many customers buy < 5000, between 5000-50000 and 50000-100000 order quantities.

I used:

SELECT customer_id,
      CASE
         WHEN COUNT(order_quantity) < 5000
         ....
FROM purchases

Which isn't correct (don't even work).

Body:
You can use:

select (case when order_quantity < 5000 then '[0-5000)'
             when order_quantity < 10000 then '[5000-10000)'
             else '10000+'
        end) as grp,
       count(*) as num_purchases,
       count(distinct customer_id) as num_customers
from t
group by grp
order by min(order_quantity);

If a customer makes more than one purchase in a given group, it is not clear if you want to count the number of purchases or the number of customers.  This does both.


问:
How do I create JSON array in this specific structure
This is the array format [{"name":"Rose","number":"+919224512555"},{"name":"smith","number":"+91975555224"}] I got from my angular form that having a dynamic table with columns name and number respectively.

I want to convert above mentioned array into the below mentioned format to store in database.

```<code>"name": [
            {
                "first_name": "Rose",
                "formatted_name": "Rose",
            },
            {
                "first_name": "smith",
                "formatted_name": "Smith",
            },
        ] ,

"phones": [
            {
                "phone": "+919224512555",
                "type": "HOME"
            },
            {
                "phone": "+91975555224",
                "type": "HOME",
            }
        ],
</code>```

I'm using angular for front-end development and laravel for back-end

答:
The below code should do help you restructure your JSON object</p>

```<code>const req_body = [
    { name:"Rose", number:"+919224512555" },
    { name:"smith", number:"+91975555224"}
]

const restrutured_body = {
    name: [],
    phone: []
};

req_body.forEach((item) => {
    restrutured_body.name.push({
        first_name: item.name,
        formatted_name: item.name
    });

    restrutured_body.phone.push({
        phone: item.number,
        type: 'HOME'
    });
});

console.log(restrutured_body);
</code>```

Body:
This is the array format [{"name":"Rose","number":"+919224512555"},{"name":"smith","number":"+91975555224"}] I got from my angular form that having a dynamic table with columns name and number respectively.

I want to convert above mentioned array into the below mentioned format to store in database.

"name": [
            {
                "first_name": "Rose",
                "formatted_name": "Rose",
            },
            {
                "first_name": "smith",
                "formatted_name": "Smith",
            },
        ] ,

"phones": [
            {
                "phone": "+919224512555",
                "type": "HOME"
            },
            {
                "phone": "+91975555224",
                "type": "HOME",
            }
        ],

I'm using angular for front-end development and laravel for back-end

Body:
The below code should do help you restructure your JSON object

const req_body = [
    { name:"Rose", number:"+919224512555" },
    { name:"smith", number:"+91975555224"}
]

const restrutured_body = {
    name: [],
    phone: []
};

req_body.forEach((item) => {
    restrutured_body.name.push({
        first_name: item.name,
        formatted_name: item.name
    });

    restrutured_body.phone.push({
        phone: item.number,
        type: 'HOME'
    });
});

console.log(restrutured_body);