问:
Chart.js stacked bar chart text on top of the stacked bars
I have Chart.js chart inside a div element. The way that I got so far is good looking and it is what I need, but it is missing one big part, a dynamic text that has to aggregate the data of the chart and show a summary. Not bar by bar , but a summary of the two bars. This is where I got so far:

var chart;
var opts = {
  layout: {
    padding: {
      left: 0,
      right: 0,
      top: 0,
      bottom: 0
    }
  },
  responsive: true,
  maintainAspectRatio: false,
  legend: {
    display: false,
  },
  tooltips: {
    enabled: false,
  },
  scales: {
    xAxes: [{
      stacked: true,
      display: false,
      ticks: {
        fontColor: "#fff",
      }
    }, ],
    yAxes: [{
      stacked: true,
      display: false,
      ticks: {
        fontColor: "#fcafe4",
        mirror: true
      }
    }]
  }
};

var datasets = [{
    label: "My Label",
    backgroundColor: ["#FF3A2F"],
    data: [],
  },
  {
    label: "Your Label",
    backgroundColor: ["#0CB04A"],
    data: [],
  }
];

var labels = ['Label 1'];

var ctx = document.getElementById('chart-canvas');

chart = new Chart(ctx, {
  type: "horizontalBar",
  data: {
    labels: labels,
    datasets: datasets
  },
  options: opts
});

function refresh() {

  chart.data.datasets[0].data[0] = Math.floor(Math.random() * 1000) + 1;
  chart.data.datasets[1].data[0] = Math.floor(Math.random() * 1000) + 1;
  chart.config.options.scales.xAxes[0].ticks.max = chart.data.datasets[0].data[0] + chart.data.datasets[1].data[0];
  chart.update();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<div class="row">
  <div class="col-lg-5 small">My Stacked Chart</div>
  <div class="col-lg-6">
    <div class="chart-container">
      <canvas id="chart-canvas"></canvas>
    </div>
  </div>
  <div class="col-lg-1 my-auto">
    <div class="btn-group">
      <button type="button" class="btn btn-primary btn-md btn-sm" onClick="refresh()">
                            Refresh
                        </button>
    </div>
  </div>
</div></code>```

I'm wondering if there is a way that I can add a text that will be in the middle of the canvas and will show data that is in the chart. For example XXXX of Total and will be updated every time the Refresh button is clicked. Something like that:

Thanks in advance!
Julian

答:
The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterDraw hook to draw text directly on the canvas using CanvasRenderingContext2D.fillText().

```<code>chart = new Chart(ctx, {
  type: "horizontalBar",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var value =  chart.config.data.datasets[0].data[0];
      var total = chart.config.data.datasets.reduce((t, ds) => t + ds.data[0], 0);
      var percent = Math.round(1000 / total * value) / 10;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      ctx.save();
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.font = "24px Arial";
      ctx.fillText(value + ' (' + percent + '%) of ' + total, xAxis.right / 2, (yAxis.bottom + yAxis.top) / 2);
      ctx.restore();
    }
  }],
  ...
</code>```

Please have a look at your amended code below.

var chart;
var opts = {
  layout: {
    padding: {
      left: 0,
      right: 0,
      top: 0,
      bottom: 0
    }
  },
  responsive: true,
  maintainAspectRatio: false,
  legend: {
    display: false,
  },
  tooltips: {
    enabled: false,
  },
  scales: {
    xAxes: [{
      stacked: true,
      display: false,
      ticks: {
        fontColor: "#fff",
      }
    }, ],
    yAxes: [{
      stacked: true,
      display: false,
      ticks: {
        fontColor: "#fcafe4",
        mirror: true
      }
    }]
  }
};

var datasets = [{
    label: "My Label",
    backgroundColor: ["#FF3A2F"],
    data: [],
  },
  {
    label: "Your Label",
    backgroundColor: ["#0CB04A"],
    data: [],
  }
];

var labels = ['Label 1'];

var ctx = document.getElementById('chart-canvas');

chart = new Chart(ctx, {
  type: "horizontalBar",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var value =  chart.config.data.datasets[0].data[0];
      var total = chart.config.data.datasets.reduce((t, ds) => t + ds.data[0], 0);
      var percent = Math.round(1000 / total * value) / 10;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      ctx.save();
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.font = "24px Arial";
      ctx.fillText(value + ' (' + percent + '%) of ' + total, xAxis.right / 2, (yAxis.bottom + yAxis.top) / 2);
      ctx.restore();
    }
  }],
  data: {
    labels: labels,
    datasets: datasets
  },
  options: opts
});
refresh();

function refresh() {
  chart.data.datasets[0].data[0] = Math.floor(Math.random() * 1000) + 1;
  chart.data.datasets[1].data[0] = Math.floor(Math.random() * 1000) + 1;
  chart.config.options.scales.xAxes[0].ticks.max = chart.data.datasets[0].data[0] + chart.data.datasets[1].data[0];
  chart.update();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<div class="row">
  <div class="col-lg-5 small">My Stacked Chart</div>
  <div class="col-lg-6">
    <div class="chart-container">
      <canvas id="chart-canvas"></canvas>
    </div>
  </div>
  <div class="col-lg-1 my-auto">
    <div class="btn-group">
      <button type="button" class="btn btn-primary btn-md btn-sm" onClick="refresh()">
          Refresh
      </button>
    </div>
  </div>
</div></code>```

Body:
I have Chart.js chart inside a div element. The way that I got so far is good looking and it is what I need, but it is missing one big part, a dynamic text that has to aggregate the data of the chart and show a summary. Not bar by bar , but a summary of the two bars. This is where I got so far:

var chart;
var opts = {
  layout: {
    padding: {
      left: 0,
      right: 0,
      top: 0,
      bottom: 0
    }
  },
  responsive: true,
  maintainAspectRatio: false,
  legend: {
    display: false,
  },
  tooltips: {
    enabled: false,
  },
  scales: {
    xAxes: [{
      stacked: true,
      display: false,
      ticks: {
        fontColor: "#fff",
      }
    }, ],
    yAxes: [{
      stacked: true,
      display: false,
      ticks: {
        fontColor: "#fcafe4",
        mirror: true
      }
    }]
  }
};

var datasets = [{
    label: "My Label",
    backgroundColor: ["#FF3A2F"],
    data: [],
  },
  {
    label: "Your Label",
    backgroundColor: ["#0CB04A"],
    data: [],
  }
];

var labels = ['Label 1'];

var ctx = document.getElementById('chart-canvas');

chart = new Chart(ctx, {
  type: "horizontalBar",
  data: {
    labels: labels,
    datasets: datasets
  },
  options: opts
});

function refresh() {

  chart.data.datasets[0].data[0] = Math.floor(Math.random() * 1000) + 1;
  chart.data.datasets[1].data[0] = Math.floor(Math.random() * 1000) + 1;
  chart.config.options.scales.xAxes[0].ticks.max = chart.data.datasets[0].data[0] + chart.data.datasets[1].data[0];
  chart.update();
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.css" rel="stylesheet" />

My Stacked Chart

      <canvas id="chart-canvas"></canvas>

      <button type="button" class="btn btn-primary btn-md btn-sm" onClick="refresh()">
                            Refresh
                        </button>

I'm wondering if there is a way that I can add a text that will be in the middle of the canvas and will show data that is in the chart. For example XXXX of Total and will be updated every time the Refresh button is clicked. Something like that:

Thanks in advance!
Julian

Body:
The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterDraw hook to draw text directly on the canvas using CanvasRenderingContext2D.fillText().

chart = new Chart(ctx, {
  type: "horizontalBar",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var value =  chart.config.data.datasets[0].data[0];
      var total = chart.config.data.datasets.reduce((t, ds) => t + ds.data[0], 0);
      var percent = Math.round(1000 / total * value) / 10;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      ctx.save();
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.font = "24px Arial";
      ctx.fillText(value + ' (' + percent + '%) of ' + total, xAxis.right / 2, (yAxis.bottom + yAxis.top) / 2);
      ctx.restore();
    }
  }],
  ...

Please have a look at your amended code below.

var chart;
var opts = {
  layout: {
    padding: {
      left: 0,
      right: 0,
      top: 0,
      bottom: 0
    }
  },
  responsive: true,
  maintainAspectRatio: false,
  legend: {
    display: false,
  },
  tooltips: {
    enabled: false,
  },
  scales: {
    xAxes: [{
      stacked: true,
      display: false,
      ticks: {
        fontColor: "#fff",
      }
    }, ],
    yAxes: [{
      stacked: true,
      display: false,
      ticks: {
        fontColor: "#fcafe4",
        mirror: true
      }
    }]
  }
};

var datasets = [{
    label: "My Label",
    backgroundColor: ["#FF3A2F"],
    data: [],
  },
  {
    label: "Your Label",
    backgroundColor: ["#0CB04A"],
    data: [],
  }
];

var labels = ['Label 1'];

var ctx = document.getElementById('chart-canvas');

chart = new Chart(ctx, {
  type: "horizontalBar",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var value =  chart.config.data.datasets[0].data[0];
      var total = chart.config.data.datasets.reduce((t, ds) => t + ds.data[0], 0);
      var percent = Math.round(1000 / total * value) / 10;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      ctx.save();
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.font = "24px Arial";
      ctx.fillText(value + ' (' + percent + '%) of ' + total, xAxis.right / 2, (yAxis.bottom + yAxis.top) / 2);
      ctx.restore();
    }
  }],
  data: {
    labels: labels,
    datasets: datasets
  },
  options: opts
});
refresh();

function refresh() {
  chart.data.datasets[0].data[0] = Math.floor(Math.random() * 1000) + 1;
  chart.data.datasets[1].data[0] = Math.floor(Math.random() * 1000) + 1;
  chart.config.options.scales.xAxes[0].ticks.max = chart.data.datasets[0].data[0] + chart.data.datasets[1].data[0];
  chart.update();
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<div class="row">
  <div class="col-lg-5 small">My Stacked Chart</div>
  <div class="col-lg-6">
    <div class="chart-container">
      <canvas id="chart-canvas"></canvas>
    </div>
  </div>
  <div class="col-lg-1 my-auto">
    <div class="btn-group">
      <button type="button" class="btn btn-primary btn-md btn-sm" onClick="refresh()">
          Refresh
      </button>
    </div>
  </div>
</div>


来源: stackexchange

问:
How to configure dynamic routes with express.js
I have a route.js which looks like this:

```<code>module.exports = function(app) {

  app.get('/tip', function(req, res) {
    res.render("tip");
  });

  app.get('/article', function(req, res) {
   res.render("article");
  });

  app.get('/article1', function(req, res) {
   res.render("article1");
  });

  app.get('/article2', function(req, res) {
   res.render("article2");
  });

  app.get('/article3', function(req, res) {
   res.render("article3");
  });

  app.get('/modules/:name', function(req, res) {
    var name = req.params.name;
    res.render('modules/' + name);
  });

  app.get('/modules/esaver/:name', function(req, res) {
    var name = req.params.name;
    res.render('modules/esaver/' + name);
  });

};
</code>```

Considering i have over 200 different routes to create, i would end up with stuff like 'article1', 'article2' etc

and my app.js is like:

```<code>var express = require('express')
  ,http = require('http')
  ,fs = require('fs')
  ,path = require('path');

var app = express();

html_templates = __dirname + '/html_templates';

app.set('views', html_templates + '/views');
app.set('view engine', 'jade');

app.use('/Core', express.static(__dirname + '/Core'));

app.listen(3000, function () {
 console.log("express has started on port 3000");
});

require('./html_templates/controller/routes.js')(app);
</code>```

Is there any dynamic way to create this?

答:
It's work on my project</p>

```<code>routesPath = path.join(__dirname, 'routes');

fs.readdirSync(routesPath).forEach(function(file) {
  require(routesPath + '/' + file)(app);
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a route.js which looks like this:

module.exports = function(app) {

  app.get('/tip', function(req, res) {
    res.render("tip");
  });

  app.get('/article', function(req, res) {
   res.render("article");
  });

  app.get('/article1', function(req, res) {
   res.render("article1");
  });

  app.get('/article2', function(req, res) {
   res.render("article2");
  });

  app.get('/article3', function(req, res) {
   res.render("article3");
  });

  app.get('/modules/:name', function(req, res) {
    var name = req.params.name;
    res.render('modules/' + name);
  });

  app.get('/modules/esaver/:name', function(req, res) {
    var name = req.params.name;
    res.render('modules/esaver/' + name);
  });

};

Considering i have over 200 different routes to create, i would end up with stuff like 'article1', 'article2' etc

and my app.js is like:

var express = require('express')
  ,http = require('http')
  ,fs = require('fs')
  ,path = require('path');

var app = express();

html_templates = __dirname + '/html_templates';

app.set('views', html_templates + '/views');
app.set('view engine', 'jade');

app.use('/Core', express.static(__dirname + '/Core'));

app.listen(3000, function () {
 console.log("express has started on port 3000");
});

require('./html_templates/controller/routes.js')(app);

Is there any dynamic way to create this?

Body:
It's work on my project

routesPath = path.join(__dirname, 'routes');

fs.readdirSync(routesPath).forEach(function(file) {
  require(routesPath + '/' + file)(app);
});

ContentLicense: CC BY-SA 4.0


问:
Dynamically appending text lines
The goal of the code is to create a new input line each time the last line is focused, until a certain amount of lines.
I was offered this solution which works great:

```<code>$(function() {
    $("#qc>div:last-of-type>input").live('focus', function() {
        $(this).parent().after($(this).parent().clone().attr('id', 'ansInput' + $('#qc>div').length).find('input').val('').end());
    });
});
</code>```

but I also want to change each time the text before the line, so clone won't cut it

I modified it to write a pre-ready HTML line, but it doesn't work:

```<code>function questionsForm() {
    $("#qc>div:last-of-type>input").live('focus', function() {

        lineNum = $('#qc>div').length
        newLine = ("<div id='ansInput{0}'>Answer {0}: <input type='text' name='ans{0}' /></div><!--ans1-->").format(lineNum);

        if ($('#qc>div').length <= 4) {
            $(this).parent().after(newLine);
        }
    });
}
</code>```

(the .format method is predefined)

I would like to understand why my code isn't working, and how to chamge it, but not completely different solutions (unless of course my code has some fundamental errors..)

答:
you are missing a semicolon after lineNum = $('#qc>div').length

why is that code in the questionsForm() function?

you could just place it in the jquery ready function $(function(){ ... });

Also what does your format function look like?

Title: Dynamically appending text lines

Body:
The goal of the code is to create a new input line each time the last line is focused, until a certain amount of lines.
I was offered this solution which works great:

$(function() {
    $("#qc>div:last-of-type>input").live('focus', function() {
        $(this).parent().after($(this).parent().clone().attr('id', 'ansInput' + $('#qc>div').length).find('input').val('').end());
    });
});

but I also want to change each time the text before the line, so clone won't cut it

I modified it to write a pre-ready HTML line, but it doesn't work:

function questionsForm() {
    $("#qc>div:last-of-type>input").live('focus', function() {

        lineNum = $('#qc>div').length
        newLine = ("
Answer {0}: <input type='text' name='ans{0}' />
").format(lineNum);

        if ($('#qc>div').length <= 4) {
            $(this).parent().after(newLine);
        }
    });
}

(the .format method is predefined)

I would like to understand why my code isn't working, and how to chamge it, but not completely different solutions (unless of course my code has some fundamental errors..)


问:
Powershell where-object not playing well with PSdrive
I'm trying to exclude two drives from a file search.  I'm getting an error when running the code: "Get-ChildItem : Access to the path 'C:\Windows\system32\LogFiles...'".  The search shouldn't touch C.  Help!!  What am I doing wrong?  Code attached.

$Drives = Get-PSDrive -PSProvider FileSystem | where { -not ('c','u' -eq $_.name) }

$FS='(.*18)\.FOO'

$FPath=@(foreach($Drive in $drives) {
    Get-ChildItem -Path $Drive.Root -Recurse | Where-Object {$_.Name -match $FS} -ErrorAction SilentlyContinue | %{$_.Name}
})
```

答:
I think you are looking for

```<code>Get-PSDrive -PSProvider FileSystem |
    Where-Object {"c","u" -notcontains $_.name} |
    ForEach-Object{
        Get-ChildItem -Path $_.Root -Recurse |
        Where-Object {$_.Name -match '(.*18)\.FOO'} -ErrorAction SilentlyContinue |
        select Name
    }
</code>```

Seems based on your comments you are still getting the error. Lets trouble shoot it a bit. Lets output the drive that it really seems to error on.

```<code>Get-PSDrive -PSProvider FileSystem |
    Where-Object {"c","u" -notcontains $_.name} |
    ForEach-Object{
        $Drive = $_.Name
        try{
            Get-ChildItem -Path $_.Root -Recurse |
            Where-Object {$_.Name -match '(.*18)\.FOO'} -ErrorAction SilentlyContinue |
            Select Name
        }catch{
            @{
                Drive = $Drive
            }
        }
    }
</code>```

Body:
I think you are looking for

Get-PSDrive -PSProvider FileSystem |
    Where-Object {"c","u" -notcontains $_.name} |
    ForEach-Object{
        Get-ChildItem -Path $_.Root -Recurse |
        Where-Object {$_.Name -match '(.*18)\.FOO'} -ErrorAction SilentlyContinue |
        select Name
    }

Seems based on your comments you are still getting the error. Lets trouble shoot it a bit. Lets output the drive that it really seems to error on.

Get-PSDrive -PSProvider FileSystem |
    Where-Object {"c","u" -notcontains $_.name} |
    ForEach-Object{
        $Drive = $_.Name
        try{
            Get-ChildItem -Path $_.Root -Recurse |
            Where-Object {$_.Name -match '(.*18)\.FOO'} -ErrorAction SilentlyContinue |
            Select Name
        }catch{
            @{
                Drive = $Drive
            }
        }
    }


问:
c# minimal code for creating instance on-the-fly
Suppose we want to create a collection of services, which may or may be not used by:

```<code>  class ServiceCollection {
     public MyService MyService = new MyService(arg1,arg2,...);
     public MySecondService MySecondService = new MySecondService(arg1,arg2,...);
     ...
</code>```

As we don't know if a service instance will be used or not - we wanted to create a service instance on-the-fly:

```<code>  class ServiceCollection {
     private MyService _MyService = null;
     public MyService MyService {
        get {
           if (_MyService==null) _MyService = new MyService(arg1,arg2,...);
           return _MyService;
       }
     }
</code>```

It is a requirement in case the user code refers to a service twice - the same service instance should be used. As the code above is ... kinda long ... I wonder is the following resulution is correct or not:

```<code>  class ServiceCollection {
     private MyService _MyService = null;
     public MyService MyService => _MyService = _MyService ?? new MyService(arg1, ...);
</code>```

Or does any other (more elegant and short) solution exist for this simple problem?

答:
I am trying to understand the architecture. In general, you can load different services, on the fly, with dependency injection. So I don't see a reason to go through the difficulty you are trying.

Or, are you trying to load balance on your side of the equation? If so, why?

There are two potential ideas here.

I don't want to load a service until it is used

I want to balance the load between multiple services

Architecturally, the first is great for loading dependencies via injection. The latter is better if you have the API team provide the scale for you.

Am I missing something?

Body:
Suppose we want to create a collection of services, which may or may be not used by:

  class ServiceCollection {
     public MyService MyService = new MyService(arg1,arg2,...);
     public MySecondService MySecondService = new MySecondService(arg1,arg2,...);
     ...

As we don't know if a service instance will be used or not - we wanted to create a service instance on-the-fly:

  class ServiceCollection {
     private MyService _MyService = null;
     public MyService MyService {
        get {
           if (_MyService==null) _MyService = new MyService(arg1,arg2,...);
           return _MyService;
       }
     }

It is a requirement in case the user code refers to a service twice - the same service instance should be used. As the code above is ... kinda long ... I wonder is the following resulution is correct or not:

  class ServiceCollection {
     private MyService _MyService = null;
     public MyService MyService => _MyService = _MyService ?? new MyService(arg1, ...);

Or does any other (more elegant and short) solution exist for this simple problem?


问:
Can't download additional tools for xcode 11.4

I can't download additional tools for Xcode. Anyone else having the same issues?

答: I figured it out. It turns out that I had to download it from Safari for it to finish the download.</p>


问:
How to find a correlation between a numeric variable and a factor variable in R?
I am new to R and I am trying to find run both a correlation and a t-test between a numerical variable and a factor variable. The factor variable is gender (F, M) and the numerical variable is weight. How do I do this?

I tried with cor.test(weight, gender) and
t.test(weight, gender)but kept getting errors.

These are the errors:

cor.test(weight, gender)
  Error in cor.test.default(weight, gender) :
    'x' and 'y' must have the same length

and:

t.test(weight, gender)
  Error in var(y) : Calling var(x) on a factor x is defunct.
    Use something like 'all(duplicated(x)[-1L])' to test for a constant vector.
  In addition: Warning message:
  In mean.default(y) : argument is not numeric or logical: returning NA

答:
What you need to do here is to form a vector of weights where Gender = M and Gender = F, and then run the t.test function on these vectors. This is because a t-test between "gender" (treated as a 0/1 integer) and "weight" would be statistically illogical. This will require subsetting your data.

I will use ChickWeights here as an example, since it has both a Weight (numeric) and Diet (factor) variables. i.e. :

```<code>str(ChickWeights)
</code>```

We will imagine that chicks on the first diet are males and chicks on the second diet are females.

```<code>m_weights <- ChickWeight$weight[ChickWeight$Diet == 2]
f_weights <- ChickWeight$weight[ChickWeight$Diet == 3]
</code>```

You can then run the t-test.

```<code>t.test(x = m_weights,y = f_weights)
</code>```

If you want to correlate the variables "gender" and "weight", you will need to use something other than a standard correlation test - e.g. a Point-biserial correlation coefficient.

You could also do a correlation test between the paired groups of males and females by subsetting the data appropriately (the vectors would need to be equal length). This, however would not likely be logical based on how I understand the structure of your data. Nonetheless, here is how to do that:

```<code>ChickWeight_filt <- ChickWeight[ChickWeight$Diet %in% c(1,2) & ChickWeight$Time %in% c(0,2) & ChickWeight$Chick %in% c(1:10,21:30),]

m_weights_filt <- ChickWeight_filt$weight[ChickWeight_filt$Diet == 1]
f_weights_filt <- ChickWeight_filt$weight[ChickWeight_filt $Diet == 2]

cor.test(x = as.numeric(m_weights_filt),y = as.numeric(f_weights_filt))
</code>```

If you have follow questions around statistics as a result of this, you might be best to ask here: https://stats.stackexchange.com/

Body:
What you need to do here is to form a vector of weights where Gender = M and Gender = F, and then run the t.test function on these vectors. This is because a t-test between "gender" (treated as a 0/1 integer) and "weight" would be statistically illogical. This will require subsetting your data.

I will use ChickWeights here as an example, since it has both a Weight (numeric) and Diet (factor) variables. i.e. :

str(ChickWeights)

We will imagine that chicks on the first diet are males and chicks on the second diet are females.

m_weights <- ChickWeight$weight[ChickWeight$Diet == 2]
f_weights <- ChickWeight$weight[ChickWeight$Diet == 3]

You can then run the t-test.

t.test(x = m_weights,y = f_weights)

If you want to correlate the variables "gender" and "weight", you will need to use something other than a standard correlation test - e.g. a Point-biserial correlation coefficient.

You could also do a correlation test between the paired groups of males and females by subsetting the data appropriately (the vectors would need to be equal length). This, however would not likely be logical based on how I understand the structure of your data. Nonetheless, here is how to do that:

ChickWeight_filt <- ChickWeight[ChickWeight$Diet %in% c(1,2) & ChickWeight$Time %in% c(0,2) & ChickWeight$Chick %in% c(1:10,21:30),]

m_weights_filt <- ChickWeight_filt$weight[ChickWeight_filt$Diet == 1]
f_weights_filt <- ChickWeight_filt$weight[ChickWeight_filt $Diet == 2]

cor.test(x = as.numeric(m_weights_filt),y = as.numeric(f_weights_filt))

If you have follow questions around statistics as a result of this, you might be best to ask here: https://stats.stackexchange.com/


问:
Finding cropped and scaled similar image
Given several large original images and a small image which is cropped and isotropic-scaled from one of large images, the task is to find where the small image comes from.

cropping usually occur at the center of large image

but exact crop boundary is unknown

the size of small image is about 200x200

again, exact size of small image is unknown

if the size of cropped area is (width, height), the size of small image must be (width * k, height * k), where k < 1.0

I've read some related topics in SO and tried methods like ORB / color histograms, however the accuracy is not acceptable. Would you please give me some advice? Is there any efficient algorithm to deal with this problem? Thank you very much.

答:
The wording you are looking for is template matching, as you want to scan the original image and look for the origin of the cropped and scaled one.

The OpenCV tutorial has an extensive explaination for it


问:
call a php function from jquery
I'm trying to figure out the best way to do this...I am using JQuery to submit data to a PHP function, which sends back data from the DB as JSON, which is working. The thing is, on success, I want the JQuery to execute a PHP function...and I'd rather not have to make yet another AJAX call on top of the first AJAX success - especially since the php function is something I've already used elsewhere on my page. This is my code:

JQUERY:

```<code>$.ajax({
    type: "POST",
    url: post_url,
    success: function(group) //we're calling the response json array 'tree'
    {
        //WANT TO CALL THE PHP FUNCTION HERE
    } //end success
 }); //end AJAX
</code>```

PHP:

```<code><?php
foreach($groups as $group){
    echo '<option value="' . $group->id . '">' . $group->group_name . '</option>';
}
?>
</code>```

答:
You have to be aware that you're dealing with two paradigms here, the first one is server-side logic (PHP) and the second one is client-side logic (JavaScript).

Unfortunately there is no way to call PHP from JS from the client without performing an AJAX call and rendering the content you want to show. However, you could prepare the result and set the body of the AJAX response with your requested HTML string.

If this is not possible, I suggest to look at the diverse number of JS frameworks that will provide helpers to generate options for select fields.

Title: call a php function from jquery

Body:
I'm trying to figure out the best way to do this...I am using JQuery to submit data to a PHP function, which sends back data from the DB as JSON, which is working. The thing is, on success, I want the JQuery to execute a PHP function...and I'd rather not have to make yet another AJAX call on top of the first AJAX success - especially since the php function is something I've already used elsewhere on my page. This is my code:

JQUERY:

$.ajax({
    type: "POST",
    url: post_url,
    success: function(group) //we're calling the response json array 'tree'
    {
        //WANT TO CALL THE PHP FUNCTION HERE
    } //end success
 }); //end AJAX

PHP:

<?php
foreach($groups as $group){
    echo '<option value="' . $group->id . '">' . $group->group_name . '</option>';
}
?>


问:
Flutter : 'onError' is deprecated on runZoned function
I got this error message when I using newest Flutter v 1.17.1 and Dart 2.8.2 version on main.dart file,

'onError' is deprecated and shouldn't be used. Use runZonedGuarded instead.
  Try replacing the use of the deprecated member with the replacement.

and this is the code,

```<code>  runZoned<Future<Null>>(() async {
    runApp(MyApp());
  }, onError: (error, stackTrace) async {
    await FlutterCrashlytics().reportCrash(error, stackTrace, forceCrash: false);
  });
}
</code>```

Any solution to get rid of this error message?

答:
You can do this:</p>

```<code>runZonedGuarded(() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}, (Object error, StackTrace stack) async {
  await FlutterCrashlytics().reportCrash(error, stackTrace, forceCrash: false);
});

</code>```

Body:
I got this error message when I using newest Flutter v 1.17.1 and Dart 2.8.2 version on main.dart file,

'onError' is deprecated and shouldn't be used. Use runZonedGuarded instead.
  Try replacing the use of the deprecated member with the replacement.

and this is the code,

  runZoned<Future<Null>>(() async {
    runApp(MyApp());
  }, onError: (error, stackTrace) async {
    await FlutterCrashlytics().reportCrash(error, stackTrace, forceCrash: false);
  });
}

Any solution to get rid of this error message?

Body:
You can do this:

runZonedGuarded(() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}, (Object error, StackTrace stack) async {
  await FlutterCrashlytics().reportCrash(error, stackTrace, forceCrash: false);
});


问:
Universal URL does not work when build is archived
I think I implemented universal URL correctly and it is working fine when I launch the app directly from the Xcode but if I am archiving the build and sharing it via tesflight or diawi I am not able to open the app using URL scheme.</p>

答:
Make sure your Associated Domains are in both entitlement files: "Debug" and "Release".
In my case all domains were listed in Entitlement-Debug.plist file but the Entitlement-Release.plist was empty.
After adding them manually to the 'Release' file - app installed via TestFlight started working with Universal Links.

Select All and Add your domain like this.

Make sure you have both release and debug entitlements.


问:
R logistic regression extracting coefficients in a loop: error with setting up loop
I'm trying to build a logistic regression model with 3 predictors, and I have a list of IDs for each predictor like below. (using mtcars dataset as an example)

```<code>var1 <- c("mpg", "cyl", "disp")
var2 <- c("mpg", "hp", "wt")
var3 <- c("drat", "wt", "gear", "carb")
</code>```

I want to build multiple regression models with each of these IDs used. am is a fixed variable that I want to predict, so each of my model would look like:

```<code>mod1 <- glm(am ~ mpg + mpg + drat, data=mtcars, ...)
mod2 <- glm(am ~ mpg + mpg + wt, data=mtcars, ...)
mod3 <- glm(am ~ mpg + mpg + gear, data=mtcars, ...)
...
mod5 <- glm(am ~ mpg + hp + drat, data=mtcars, ...)
...
mod9 <- glm(am ~ mpg + wt + drat, data=mtcars, ...)
...
mod36 <- glm(am ~ disp + wt + carb, data=mtcars, ...)
</code>```

So in this case it would be 3*3*4 = 36 models total. I'm trying to use apply like below.

```<code>coefs_mat <- expand.grid(var1, var2, var3)
mods = apply(coefs_mat, 1, function(row) {
    glm(as.formula(am ~ row[1] + row[2] + row[3]), data = mtcars,
family = "binomial",control=list(maxit=20))
})
</code>```

(+ Edit: coefs_mat looks like below:

```<code>>coefs_mat
  var1    var2    var3
1 mpg     mpg     drat
2 cyl     mpg     drat
3 disp    mpg     drat
4 mpg     hp      drat
...
36 disp   wt      carb
</code>```

This gives the following error: "object of type 'closure' is not subsettable".

I searched for other Stackoverflow posts that had similar problems, and tried this instead:

```<code>mods = apply(coefs_mat, 1, function(row) {
  glm(as.formula(paste("am~", row[1] + row[2] + row[3])), data = mtcars,
family = "binomial",control=list(maxit=20))
})
</code>```

But this gave another error: "Error in row[1] + row[2] : non-numeric argument to binary operator". What's causing these errors in my code?

答:
I solved this by using sprintf.

```<code>var1 <- c("mpg", "cyl", "disp")
var2 <- c("mpg", "hp", "wt")
var3 <- c("drat", "wt", "gear", "carb")
coefs_mat <- expand.grid(var1, var2, var3)
vars_comb <- apply(coefs_mat, 1, function(x){paste(sort(x), collapse = '+')})
formula_vec <- sprintf("am ~ %s", vars_comb)

glm_res <- lapply(formula_vec, function(x)   {
  fit1 <- glm(x, data = mtcars, family = binomial("logit"))
  return(fit1)
})
</code>```

Body:
I'm trying to build a logistic regression model with 3 predictors, and I have a list of IDs for each predictor like below. (using mtcars dataset as an example)

var1 <- c("mpg", "cyl", "disp")
var2 <- c("mpg", "hp", "wt")
var3 <- c("drat", "wt", "gear", "carb")

I want to build multiple regression models with each of these IDs used. am is a fixed variable that I want to predict, so each of my model would look like:

mod1 <- glm(am ~ mpg + mpg + drat, data=mtcars, ...)
mod2 <- glm(am ~ mpg + mpg + wt, data=mtcars, ...)
mod3 <- glm(am ~ mpg + mpg + gear, data=mtcars, ...)
...
mod5 <- glm(am ~ mpg + hp + drat, data=mtcars, ...)
...
mod9 <- glm(am ~ mpg + wt + drat, data=mtcars, ...)
...
mod36 <- glm(am ~ disp + wt + carb, data=mtcars, ...)

So in this case it would be 3*3*4 = 36 models total. I'm trying to use apply like below.

coefs_mat <- expand.grid(var1, var2, var3)
mods = apply(coefs_mat, 1, function(row) {
    glm(as.formula(am ~ row[1] + row[2] + row[3]), data = mtcars,
family = "binomial",control=list(maxit=20))
})

(+ Edit: coefs_mat looks like below:

>coefs_mat
  var1    var2    var3
1 mpg     mpg     drat
2 cyl     mpg     drat
3 disp    mpg     drat
4 mpg     hp      drat
...
36 disp   wt      carb

This gives the following error: "object of type 'closure' is not subsettable".

I searched for other Stackoverflow posts that had similar problems, and tried this instead:

mods = apply(coefs_mat, 1, function(row) {
  glm(as.formula(paste("am~", row[1] + row[2] + row[3])), data = mtcars,
family = "binomial",control=list(maxit=20))
})

But this gave another error: "Error in row[1] + row[2] : non-numeric argument to binary operator". What's causing these errors in my code?

Body:
I solved this by using sprintf.

var1 <- c("mpg", "cyl", "disp")
var2 <- c("mpg", "hp", "wt")
var3 <- c("drat", "wt", "gear", "carb")
coefs_mat <- expand.grid(var1, var2, var3)
vars_comb <- apply(coefs_mat, 1, function(x){paste(sort(x), collapse = '+')})
formula_vec <- sprintf("am ~ %s", vars_comb)

glm_res <- lapply(formula_vec, function(x)   {
  fit1 <- glm(x, data = mtcars, family = binomial("logit"))
  return(fit1)
})


答:
@Jose Perhaps not as sound mathematically (in terms of the clustering) but (generally) a better measure of great circle distances (Vincenty's formulae). And ~8 times faster to achieve (what I think is your desired result) - (just using your sample data). </p>

```<code># Order the dataframe by Lon and Lat: ordered_df => data.frame
ordered_df <-
  df %>%
  arrange(., Longitude, Latitude)

# Scalar valued at how many clusters we are expecting => integer vector
k = 3

# Matrix of co-ordinates: coordinates => matrix
coordinates <-
  ordered_df %>%
  select(Longitude, Latitude) %>%
  as.matrix()

# Generate great circle distances between points and Long-Lat Matrix: d => data.frame
d <- data.frame(Dist = c(0, distVincentyEllipsoid(coordinates)))

# Segment the distances into groups: cluster => factor
d$Cluster <- factor(cumsum(d$Dist > (quantile(d$Dist, 1/k))) + 1)

# Merge with base data: clustered_df => data.frame
clustered_df <- cbind(ordered_df, d)
</code>```

<p>Libraries and sample data: </p>

```<code>library(geosphere)
library(dplyr)

df <- structure(list(Industries=c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19),
Latitude = c(-23.8, -23.8, -23.9, -23.9, -23.9,  -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9),
Longitude = c(-49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.7,-49.7, -49.7, -49.7, -49.7, -49.6, -49.6, -49.6, -49.6)),
class = "data.frame", row.names = c(NA, -19L))
start_time <- Sys.time()
</code>```

Title: Distance calculation optimization in R

Body:
I would like to know if there is any way to optimize the distance calculation process below. I left a small example below, however I am working with a spreadsheet with more than 6000 rows, and it takes considerable time to calculate the variable d. It would be possible to somehow adjust this to have the same results, but in an optimized way.

library(rdist)
library(tictoc)
library(geosphere)

time<-tic()

df<-structure(list(Industries=c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19), Latitude = c(-23.8, -23.8, -23.9, -23.9, -23.9,  -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9,
+ + -23.9, -23.9, -23.9, -23.9, -23.9), Longitude = c(-49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.7,
+ + -49.7, -49.7, -49.7, -49.7, -49.6, -49.6, -49.6, -49.6)), class = "data.frame", row.names = c(NA, -19L))

k=3
#clusters
coordinates<-df[c("Latitude","Longitude")]
d<-as.dist(distm(coordinates[,2:1]))
fit.average<-hclust(d,method="average")
clusters<-cutree(fit.average, k)
nclusters<-matrix(table(clusters))
df$cluster <- clusters

time<-toc()

1.54 sec elapsed

d
          1        2        3        4        5        6        7        8
2      0.00
3  11075.61 11075.61
4  11075.61 11075.61     0.00
5  11075.61 11075.61     0.00     0.00
6  11075.61 11075.61     0.00     0.00     0.00
7  11075.61 11075.61     0.00     0.00     0.00     0.00
8  11075.61 11075.61     0.00     0.00     0.00     0.00     0.00
9  11075.61 11075.61     0.00     0.00     0.00     0.00     0.00     0.00
10 11075.61 11075.61     0.00     0.00     0.00     0.00     0.00     0.00
11 15048.01 15048.01 10183.02 10183.02 10183.02 10183.02 10183.02 10183.02
12 15048.01 15048.01 10183.02 10183.02 10183.02 10183.02 10183.02 10183.02
13 15048.01 15048.01 10183.02 10183.02 10183.02 10183.02 10183.02 10183.02
14 15048.01 15048.01 10183.02 10183.02 10183.02 10183.02 10183.02 10183.02
15 15048.01 15048.01 10183.02 10183.02 10183.02 10183.02 10183.02 10183.02
16 11075.61 11075.61     0.00     0.00     0.00     0.00     0.00     0.00
17 11075.61 11075.61     0.00     0.00     0.00     0.00     0.00     0.00
18 11075.61 11075.61     0.00     0.00     0.00     0.00     0.00     0.00
19 11075.61 11075.61     0.00     0.00     0.00     0.00     0.00     0.00
          9       10       11       12       13       14       15       16
2
3
4
5
6
7
8
9
10     0.00
11 10183.02 10183.02
12 10183.02 10183.02     0.00
13 10183.02 10183.02     0.00     0.00
14 10183.02 10183.02     0.00     0.00     0.00
15 10183.02 10183.02     0.00     0.00     0.00     0.00
16     0.00     0.00 10183.02 10183.02 10183.02 10183.02 10183.02
17     0.00     0.00 10183.02 10183.02 10183.02 10183.02 10183.02     0.00
18     0.00     0.00 10183.02 10183.02 10183.02 10183.02 10183.02     0.00
19     0.00     0.00 10183.02 10183.02 10183.02 10183.02 10183.02     0.00
         17       18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18     0.00
19     0.00     0.00

Comparation

> df$cluster <- clusters
> df
   Industries Latitude Longitude cluster
1           1    -23.8     -49.6       1
2           2    -23.8     -49.6       1
3           3    -23.9     -49.6       2
4           4    -23.9     -49.6       2
5           5    -23.9     -49.6       2
6           6    -23.9     -49.6       2
7           7    -23.9     -49.6       2
8           8    -23.9     -49.6       2
9           9    -23.9     -49.6       2
10         10    -23.9     -49.6       2
11         11    -23.9     -49.7       3
12         12    -23.9     -49.7       3
13         13    -23.9     -49.7       3
14         14    -23.9     -49.7       3
15         15    -23.9     -49.7       3
16         16    -23.9     -49.6       2
17         17    -23.9     -49.6       2
18         18    -23.9     -49.6       2
19         19    -23.9     -49.6       2

> clustered_df
   Industries Latitude Longitude cluster     Dist Cluster
1          11    -23.9     -49.7       3     0.00       1
2          12    -23.9     -49.7       3     0.00       1
3          13    -23.9     -49.7       3     0.00       1
4          14    -23.9     -49.7       3     0.00       1
5          15    -23.9     -49.7       3     0.00       1
6           3    -23.9     -49.6       2 10183.02       2
7           4    -23.9     -49.6       2     0.00       2
8           5    -23.9     -49.6       2     0.00       2
9           6    -23.9     -49.6       2     0.00       2
10          7    -23.9     -49.6       2     0.00       2
11          8    -23.9     -49.6       2     0.00       2
12          9    -23.9     -49.6       2     0.00       2
13         10    -23.9     -49.6       2     0.00       2
14         16    -23.9     -49.6       2     0.00       2
15         17    -23.9     -49.6       2     0.00       2
16         18    -23.9     -49.6       2     0.00       2
17         19    -23.9     -49.6       2     0.00       2
18          1    -23.8     -49.6       1 11075.61       3
19          2    -23.8     -49.6       1     0.00       3

Body:
@Jose Perhaps not as sound mathematically (in terms of the clustering) but (generally) a better measure of great circle distances (Vincenty's formulae). And ~8 times faster to achieve (what I think is your desired result) - (just using your sample data).

# Order the dataframe by Lon and Lat: ordered_df => data.frame
ordered_df <-
  df %>%
  arrange(., Longitude, Latitude)

# Scalar valued at how many clusters we are expecting => integer vector
k = 3

# Matrix of co-ordinates: coordinates => matrix
coordinates <-
  ordered_df %>%
  select(Longitude, Latitude) %>%
  as.matrix()

# Generate great circle distances between points and Long-Lat Matrix: d => data.frame
d <- data.frame(Dist = c(0, distVincentyEllipsoid(coordinates)))

# Segment the distances into groups: cluster => factor
d$Cluster <- factor(cumsum(d$Dist > (quantile(d$Dist, 1/k))) + 1)

# Merge with base data: clustered_df => data.frame
clustered_df <- cbind(ordered_df, d)

Libraries and sample data:

library(geosphere)
library(dplyr)

df <- structure(list(Industries=c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19),
Latitude = c(-23.8, -23.8, -23.9, -23.9, -23.9,  -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9),
Longitude = c(-49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.7,-49.7, -49.7, -49.7, -49.7, -49.6, -49.6, -49.6, -49.6)),
class = "data.frame", row.names = c(NA, -19L))
start_time <- Sys.time()


问:
How does filter affect LEFT JOIN in sql
I'm trying to understand why the following query only returns one row in spite of LEFT JOIN

with t1(day_partition, entity_id, feature_1) AS (values
  ('2020-05-15', 'id_1', 'x'),
  ('2020-05-15', 'id_2', 'y')
),

t2(day_partition, entity_id, feature_2) AS (values
  ('2020-05-15', 'id_1', 1)
)

SELECT
  t1.day_partition AS day_partition_1,
  t2.day_partition AS day_partition_2,
  t1.entity_id AS entity_id_1,
  t2.entity_id AS entity_id_2
FROM
  t1
LEFT JOIN
  t2
ON
  t1.entity_id = t2.entity_id
WHERE
  t2.day_partition = '2020-05-15'
;
```

<p>returns</p>

``` day_partition_1 | day_partition_2 | entity_id_1 | entity_id_2
-----------------+-----------------+-------------+-------------
 2020-05-15      | 2020-05-15      | o1          | o1
```

<p>However, removing the filter of </p>

```WHERE
  t2.day_partition = '2020-05-15'
```

<p>will return </p>

``` day_partition_1 | day_partition_2 | entity_id_1 | entity_id_2
-----------------+-----------------+-------------+-------------
 2020-05-15      | 2020-05-15      | id_1        | id_1
 2020-05-15      | NULL            | id_2        | NULL
```

I find such behavior unintuitive and what's the rule behind it?

答:
If you put the condition in the join it works as you expect

```<code>SELECT
  t1.day_partition AS day_partition_1,
  t2.day_partition AS day_partition_2,
  t1.entity_id AS entity_id_1,
  t2.entity_id AS entity_id_2
FROM
  t1
LEFT JOIN
  t2
ON
  t1.entity_id = t2.entity_id AND t2.day_partition = '2020-05-15'
</code>```

The query parser does not know what you are thinking. If you filter the data in a  where clause it affects all records and not just the records of the joined table.

Title: How does filter affect LEFT JOIN in sql

Body:
I'm trying to understand why the following query only returns one row in spite of LEFT JOIN

with t1(day_partition, entity_id, feature_1) AS (values
  ('2020-05-15', 'id_1', 'x'),
  ('2020-05-15', 'id_2', 'y')
),

t2(day_partition, entity_id, feature_2) AS (values
  ('2020-05-15', 'id_1', 1)
)

SELECT
  t1.day_partition AS day_partition_1,
  t2.day_partition AS day_partition_2,
  t1.entity_id AS entity_id_1,
  t2.entity_id AS entity_id_2
FROM
  t1
LEFT JOIN
  t2
ON
  t1.entity_id = t2.entity_id
WHERE
  t2.day_partition = '2020-05-15'
;

returns

 day_partition_1 | day_partition_2 | entity_id_1 | entity_id_2
-----------------+-----------------+-------------+-------------
 2020-05-15      | 2020-05-15      | o1          | o1

However, removing the filter of

WHERE
  t2.day_partition = '2020-05-15'

will return

 day_partition_1 | day_partition_2 | entity_id_1 | entity_id_2
-----------------+-----------------+-------------+-------------
 2020-05-15      | 2020-05-15      | id_1        | id_1
 2020-05-15      | NULL            | id_2        | NULL

I find such behavior unintuitive and what's the rule behind it?

Body:
If you put the condition in the join it works as you expect

SELECT
  t1.day_partition AS day_partition_1,
  t2.day_partition AS day_partition_2,
  t1.entity_id AS entity_id_1,
  t2.entity_id AS entity_id_2
FROM
  t1
LEFT JOIN
  t2
ON
  t1.entity_id = t2.entity_id AND t2.day_partition = '2020-05-15'

The query parser does not know what you are thinking. If you filter the data in a  where clause it affects all records and not just the records of the joined table.


问:
How to automate this process?
It involves rewriting .htm to .txt (output file)

then using a parser (stanford grammar parser) (output file)

for all the files in a directory.

MY QUESTION: I would like to get all the files in the directory, without doing it manually, and find a way to run the parser, without having to type it into the Terminal for each file.

Here is my code:

```<code>#!/usr/bin/perl
use strict;
use warnings;
use HTML::FormatText;
use HTML::TreeBuilder;

my $tree = HTML::TreeBuilder->new->parse_file("chpt15Intro.htm");

use HTML::FormatText;

my $formatter = HTML::FormatText->new(leftmargin => 0, rightmargin => 1000);
   #print $formatter->format($tree); is replaced by push
push (my @files, $formatter->format($tree));
foreach my $files (@files) {
    $files =~ s/^\s+//mg;
    open MYFILE, ">ch15Intro.txt";
    select MYFILE;
    print $files;
}
</code>```

In the Terminal, after getting the html file converted, I write:

```<code>script parsedch15Intro.txt ./lexparser.csh ch15Intro.txt
</code>```

to save the output of the parser. This step still needs automation.

I'm a beginner so thanks for any advice.

答:
You can pass multiple files via the command line using globbing, which the shell will expand.

```<code>./lexparser *.html
</code>```

All file names ending in '.html' are then available in @ARGV. If your script is to take only file names as arguments, simply loop over @ARGV to get each input file name, processing the input file in the loop body. For example:

```<code>for my $in (@ARGV) {
    my $out = $in;
    $out =~ s/(\.html?)?$/.txt/;
    ...
}
</code>```

If you want your script to take additional options (such as to set the extension for the output files, or to set a prefix or suffix for output files), process @ARGV before processing the files. You can write your own option processor or use one of the Getopt modules.

Note: an extension of '.csh' indicates a C shell script. For Perl, use '.pl' if you want to use an extension at all (it's usually unnecessary, as the shebang line carries information as to the script type).

Title: How to automate this process?

Body:
It involves rewriting .htm to .txt (output file)

then using a parser (stanford grammar parser) (output file)

for all the files in a directory.

MY QUESTION: I would like to get all the files in the directory, without doing it manually, and find a way to run the parser, without having to type it into the Terminal for each file.

Here is my code:

#!/usr/bin/perl
use strict;
use warnings;
use HTML::FormatText;
use HTML::TreeBuilder;

my $tree = HTML::TreeBuilder->new->parse_file("chpt15Intro.htm");

use HTML::FormatText;

my $formatter = HTML::FormatText->new(leftmargin => 0, rightmargin => 1000);
   #print $formatter->format($tree); is replaced by push
push (my @files, $formatter->format($tree));
foreach my $files (@files) {
    $files =~ s/^\s+//mg;
    open MYFILE, ">ch15Intro.txt";
    select MYFILE;
    print $files;
}

In the Terminal, after getting the html file converted, I write:

script parsedch15Intro.txt ./lexparser.csh ch15Intro.txt

to save the output of the parser. This step still needs automation.

I'm a beginner so thanks for any advice.

Body:
You can pass multiple files via the command line using globbing, which the shell will expand.

./lexparser *.html

All file names ending in '.html' are then available in @ARGV. If your script is to take only file names as arguments, simply loop over @ARGV to get each input file name, processing the input file in the loop body. For example:

for my $in (@ARGV) {
    my $out = $in;
    $out =~ s/(\.html?)?$/.txt/;
    ...
}

If you want your script to take additional options (such as to set the extension for the output files, or to set a prefix or suffix for output files), process @ARGV before processing the files. You can write your own option processor or use one of the Getopt modules.

Note: an extension of '.csh' indicates a C shell script. For Perl, use '.pl' if you want to use an extension at all (it's usually unnecessary, as the shebang line carries information as to the script type).


答:
This is by design. Conditions in the where clause are mandatory so putting there a condition on the left joined table ends up evicting rows where the left join came back empty. Basically, this turns the left join to an inner join.

You need to put all predicates that relate to columns coming from the left joined table in the on clause of the join:

```<code>FROM t1
LEFT JOIN t2
    ON t1.entity_id = t2.entity_id
    AND t2.day_partition = '2020-05-15'
</code>```

By looking at your resultset, I tend to think that you actually wanted a condition on t1:

```<code>FROM t1
LEFT JOIN t2
    ON t1.entity_id = t2.entity_id
WHERE t1.day_partition = '2020-05-15'
</code>```

Title: How does filter affect LEFT JOIN in sql

Body:
This is by design. Conditions in the where clause are mandatory so putting there a condition on the left joined table ends up evicting rows where the left join came back empty. Basically, this turns the left join to an inner join.

You need to put all predicates that relate to columns coming from the left joined table in the on clause of the join:

FROM t1
LEFT JOIN t2
    ON t1.entity_id = t2.entity_id
    AND t2.day_partition = '2020-05-15'

By looking at your resultset, I tend to think that you actually wanted a condition on t1:

FROM t1
LEFT JOIN t2
    ON t1.entity_id = t2.entity_id
WHERE t1.day_partition = '2020-05-15'


问:
how to set multiple Font Styles when checked Combobox in c#
I'd like to font style and font size in Combobox. When I selected font size after selected font style then, I select font style in Combobox again it did not work.

How can I solve it?

```<code>private void FontBox_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        RichTextBox.SelectionFont = new Font(FontBox.Text, RichTextBox.Font.Size);
    }
    catch { }
}

private void font_sizeBox_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        RichTextBox.SelectionFont = new Font(RichTextBox.Font.FontFamily,
            float.Parse(font_sizeBox.SelectedItem.ToString()));
    }
    catch { }
}
</code>```

答:
Try setting like this:</p>

```<code>richTextBox1.SelectAll();
richTextBox1.SelectionFont = newFont;
</code>```

Body:
I'd like to font style and font size in Combobox. When I selected font size after selected font style then, I select font style in Combobox again it did not work.

How can I solve it?

private void FontBox_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        RichTextBox.SelectionFont = new Font(FontBox.Text, RichTextBox.Font.Size);
    }
    catch { }
}

private void font_sizeBox_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        RichTextBox.SelectionFont = new Font(RichTextBox.Font.FontFamily,
            float.Parse(font_sizeBox.SelectedItem.ToString()));
    }
    catch { }
}

Body:
Try setting like this:

richTextBox1.SelectAll();
richTextBox1.SelectionFont = newFont;


问:
How to convert items in a 0-d numpy array?
So say I have a 0-d array like this:

```<code>a = [3.0, 0.0, 3.0, 0.0, 5.0]
</code>```

for each item in this array, I want to convert it back to a certain string value depending on the number. So for 0.0, I want to return 'no'. For 3.0, I want to return 'maybe'. And for 5.0, I want to return 'yes'. So it would look like this:

```<code>a = ['maybe', 'no', 'maybe', 'no', 'yes']
</code>```

my problem is when I try to write a for loop to convert each item, I don't think I can use enumerate since all of the items are held in a 0-d array. I'm not sure how else I can go about updating this type of array.

答:
Are you looking for this:

```<code>a = np.array([3.0, 0.0, 3.0, 0.0, 5.0])
dictionary = {0:'no',3:'maybe',5:'yes'}
[dictionary[i] for i in a]
</code>```

output:

```<code>['maybe', 'no', 'maybe', 'no', 'yes']
</code>```

Body:
So say I have a 0-d array like this:

a = [3.0, 0.0, 3.0, 0.0, 5.0]

for each item in this array, I want to convert it back to a certain string value depending on the number. So for 0.0, I want to return 'no'. For 3.0, I want to return 'maybe'. And for 5.0, I want to return 'yes'. So it would look like this:

a = ['maybe', 'no', 'maybe', 'no', 'yes']

my problem is when I try to write a for loop to convert each item, I don't think I can use enumerate since all of the items are held in a 0-d array. I'm not sure how else I can go about updating this type of array.

Body:
Are you looking for this:

a = np.array([3.0, 0.0, 3.0, 0.0, 5.0])
dictionary = {0:'no',3:'maybe',5:'yes'}
[dictionary[i] for i in a]

output:

['maybe', 'no', 'maybe', 'no', 'yes']


问:
XML comments file could not be found - Swagger
This is certainly one of those that drives you nuts. As the title indicates all I'm simply trying to do is display comments pulled from an xml file using swagger.

I appear to have taken all steps according to the swagger documentation but to no avail. Hopefully you kind folk can point me in the right direction.

Steps Taken:

Ensured file exists:

Configured SwaggerConfig.cs

I've tried changing the path too: @"bin/....xml"

Nothing seems to work.

**The Error "Could not find file": **

Can anyone point me in the right direction please?

Regards,

答:
I just wanted to put an answer to this question to further explain why those codes didn't work for Tez (and didn't work for me either).

The code in question is:

```<code>var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
</code>```

For this to work, your swagger documentation configuration must be written in the "startup.cs" or in a .cs file within the same project as the controller.

Also, you must ensure that your XML file is being generated. So, right-click on your project, go to properties, go to build, scroll down to the "output" section, and check the "XML documentation file" option. (These steps are for Visual Studio 2019).

XML files are usually named "your-project-name".xml by default.

```<code>$"{Assembly.GetExecutingAssembly().GetName().Name}.xml"
</code>```

Thus, this line of code ensures that the name of the xml file in your swagger configuration will be: "your-project-name".xml, where your controller documentation sits.

In my case, I had my swagger configuration in an extension method in class library, so that line of code produced the xml file name: "class-library-project-name".xml, when it should have been "controller-resident-project-name".xml.

The solution, like Tez suggested, is to manually set the XML file name, since you already know what it is.

Another solution would be to configure swagger in the startup.cs, which is usually in the same project as your controllers.

Hope this helps.

Body:
I just wanted to put an answer to this question to further explain why those codes didn't work for Tez (and didn't work for me either).

The code in question is:

var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

For this to work, your swagger documentation configuration must be written in the "startup.cs" or in a .cs file within the same project as the controller.

Also, you must ensure that your XML file is being generated. So, right-click on your project, go to properties, go to build, scroll down to the "output" section, and check the "XML documentation file" option. (These steps are for Visual Studio 2019).

XML files are usually named "your-project-name".xml by default.

$"{Assembly.GetExecutingAssembly().GetName().Name}.xml"

Thus, this line of code ensures that the name of the xml file in your swagger configuration will be: "your-project-name".xml, where your controller documentation sits.

In my case, I had my swagger configuration in an extension method in class library, so that line of code produced the xml file name: "class-library-project-name".xml, when it should have been "controller-resident-project-name".xml.

The solution, like Tez suggested, is to manually set the XML file name, since you already know what it is.

Another solution would be to configure swagger in the startup.cs, which is usually in the same project as your controllers.

Hope this helps.


问:
Google spreadsheet api Request had insufficient authentication scopes
I'm making an script to read data from google spreadsheet using the following script on nodejs:

```<code>var url = oauth2Client.generateAuthUrl({
    access_type:     'offline',
    approval_prompt: 'force',
    scope: [
      'https://www.googleapis.com/auth/analytics.readonly',
      'https://www.googleapis.com/auth/drive',
      'https://www.googleapis.com/auth/spreadsheets'
    ]
});
global.googleapis = { expiry_date: 0 };
google.options({ auth: oauth2Client });
var sheets    = google.sheets('v4');
sheets.spreadsheets.get({ spreadsheetId: 'id'}, function(err, data) {
    res.send(err, data);
});
</code>```

But on every get request i'm getting this error:

```<code>Request had insufficient authentication scopes.
</code>```

I checked the Google developers console to enable the Google Drive API and it's enabled, so I dont really know what could it be.

答:
Also please check the installed version of googleapis in your workspace, because the latest version (51) does not support for Node 8. So you need downgrade its version.
https://github.com/googleapis/google-api-nodejs-client/releases</p>

Body:
I'm making an script to read data from google spreadsheet using the following script on nodejs:

var url = oauth2Client.generateAuthUrl({
    access_type:     'offline',
    approval_prompt: 'force',
    scope: [
      'https://www.googleapis.com/auth/analytics.readonly',
      'https://www.googleapis.com/auth/drive',
      'https://www.googleapis.com/auth/spreadsheets'
    ]
});
global.googleapis = { expiry_date: 0 };
google.options({ auth: oauth2Client });
var sheets    = google.sheets('v4');
sheets.spreadsheets.get({ spreadsheetId: 'id'}, function(err, data) {
    res.send(err, data);
});

But on every get request i'm getting this error:

Request had insufficient authentication scopes.

I checked the Google developers console to enable the Google Drive API and it's enabled, so I dont really know what could it be.


问:
How to map a MySQL char(n) column to an instance variable using a JPA/Hibernate annotation?
I encounter a JPA/Hibernate mapping problem on a column "language" in a MySQL table whose type is char(7). In my entity, the code generated for the field is:

```<code>    private String language;
</code>```

this causes the following exception at runtime:

```<code>        ... 43 more
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: prosvetaPersistenceUnit] Unable to build EntityManagerFactory
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:911)
    at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:74)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:225)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:308)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
    ... 58 more
Caused by: org.hibernate.HibernateException: Wrong column type in joo16_dev.jos_categories for column language. Found: char, expected: varchar(255)
    at org.hibernate.mapping.Table.validateColumns(Table.java:283)
    at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:1313)
    at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:139)
    at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:378)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1842)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:902)
    ... 63 more
</code>```

Thanks in advance !

JP

答:
Try this:

```<code>@Column(name="language",columnDefinition="char(7)")
</code>```

see if that works.

Body:
I encounter a JPA/Hibernate mapping problem on a column "language" in a MySQL table whose type is char(7). In my entity, the code generated for the field is:

    private String language;

this causes the following exception at runtime:

        ... 43 more
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: prosvetaPersistenceUnit] Unable to build EntityManagerFactory
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:911)
    at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:74)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:225)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:308)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
    ... 58 more
Caused by: org.hibernate.HibernateException: Wrong column type in joo16_dev.jos_categories for column language. Found: char, expected: varchar(255)
    at org.hibernate.mapping.Table.validateColumns(Table.java:283)
    at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:1313)
    at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:139)
    at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:378)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1842)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:902)
    ... 63 more

Thanks in advance !

JP

Body:
Try this:

@Column(name="language",columnDefinition="char(7)")

see if that works.


问:
Can't plot ggplot2 objects created with R 3.x into R 4.x imported from a RDS file
I exported a list with some ggplot2 objects into a .RDS file, generated from a R 3.6.1 session. Then, tried importing it into a R 4.0.0 session and got the following error:

```<code>Error in identicalUnits(x) :
  old version of unit class is no longer allowed
</code>```

I can read and import these plots into an R object, but CAN'T plot. They actually have all the data within (data, layers, scales mapping...) but ggplot2 is not plotting them.

Is there any way around it? Have any of you encountered with this issue? Would ggplot2have plans to update the library so we can import older version plots? Hope you can help me find a solution, or at least a patch. Thanks!

答:
Saving ggplot2 objects into .Rds files is generally discouraged, because there is absolutely no guarantee that they will still work if either ggplot2 or (in this case) R is upgraded to the next release, even if it is minor release. ggplot2 objects contain large amounts of executable code (closures) as well as internal data structures, and these generally get out of sync whenever we generate a plot with one ggplot2 version and then try to print with another.

Another problem with saving a ggplot2 object to .Rds is that the entire R environment is saved as well, so that your .Rds file may blow up if you happen to have a large amount of data loaded into your session.

The only two safe approaches to retaining plots across versions are to 1. save your raw data and code that generates the plot or 2. save the plot output as .png, .pdf, etc.

Body:
I exported a list with some ggplot2 objects into a .RDS file, generated from a R 3.6.1 session. Then, tried importing it into a R 4.0.0 session and got the following error:

Error in identicalUnits(x) :
  old version of unit class is no longer allowed

I can read and import these plots into an R object, but CAN'T plot. They actually have all the data within (data, layers, scales mapping...) but ggplot2 is not plotting them.

Is there any way around it? Have any of you encountered with this issue? Would ggplot2have plans to update the library so we can import older version plots? Hope you can help me find a solution, or at least a patch. Thanks!


问:
Keras LSTM Dtype in MatMul not the same
So, I'm coding a LSTM model to find the next number in a sequence. But when I fit the model I get this error,

```<code>TypeError: Input 'b' of 'MatMul' Op has type float32 that does not match type int64 of argument 'a'.
</code>```

I don't understand this question because Ive checked and all of the data and labels are dtype int64.

Here is my code:

```<code>import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, LSTM
import random
import numpy as np

def makeData(total, types=5):
    #PATTERNS:
    #1)going up by 1
    #2)going up by 2
    #3)muliply by 3
    #4)multiple by 2
    #5)square number
    NumPer = int(total/types)
    Labels = []
    Data = []
    print(NumPer)
    for type in range(types):
        for i in range(NumPer):
            preData = []
            if type == 0:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x+1)
                preData.append(x+2)
                Labels.append([x+3])
            if type == 1:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x+2)
                preData.append(x+4)
                Labels.append([x+6])
            if type == 2:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x*3)
                preData.append(x*9)
                Labels.append([x*27])
            if type == 3:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x*2)
                preData.append(x*4)
                Labels.append([x*8])
            if type == 4:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x*x)
                preData.append((x*x)*(x*x))
                Labels.append([(x*x)*(x*x)*((x*x)*(x*x))])
        Data.append(preData)
    return np.array(Data), np.array(Labels)

x, y = makeData(5)

def MakeRNN():
    model = Sequential()
    model.add(LSTM(3, activation='tanh'))
    model.add(Dense(9, activation='relu'))
    model.add(LSTM(9, activation='tanh'))
    model.add(Dense(36, activation='relu'))
    model.add(Dense(1, activation='relu'))
    model.compile(optimizer='Adam', loss="mse", metrics=['accuracy'])
    return model
Model = MakeRNN()
print(x.shape)
x = x.reshape(-1,1,3)
print(y[0].dtype)
print(x.shape)
Model.fit(x,y, epochs=20)

print(Model.predict([[1,2,3]]))
</code>```

I don't understand this, I would appreciate any help from you guys. I don't know too much in the field of keras.

答:
Following code worked for me. Just made some tweaks to the x, y from makeData to convert them to floats. Also, the argument passed to predict needs to be 3 dimensional (at present you have a 2d argument) and it needs to be a float. Also need to add return sequences = True at first LSTM because it still has another LSTM after it.
Also, your model is a little bit strange. Keras expects the inputs to a sequential model to be of form (batch_size, timesteps, input_dim). You have timesteps = 1 and hence no sequence really. But that is a separate thing about what you want to do. As for getting the code to run, above tweaks worked.</p>

```<code>import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, LSTM
import random
import numpy as np

def makeData(total, types=5):
    #PATTERNS:
    #1)going up by 1
    #2)going up by 2
    #3)muliply by 3
    #4)multiple by 2
    #5)square number
    NumPer = int(total/types)
    Labels = []
    Data = []
    print(NumPer)
    for type in range(types):
        for i in range(NumPer):
            preData = []
            if type == 0:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x+1)
                preData.append(x+2)
                Labels.append([x+3])
            if type == 1:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x+2)
                preData.append(x+4)
                Labels.append([x+6])
            if type == 2:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x*3)
                preData.append(x*9)
                Labels.append([x*27])
            if type == 3:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x*2)
                preData.append(x*4)
                Labels.append([x*8])
            if type == 4:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x*x)
                preData.append((x*x)*(x*x))
                Labels.append([(x*x)*(x*x)*((x*x)*(x*x))])
        Data.append(preData)
    return np.array(Data), np.array(Labels)

x, y = makeData(5)
x = x.astype(float)
y = y.astype(float)

def MakeRNN():
    model = Sequential()
    model.add(LSTM(3, activation='tanh', return_sequences=True))
    model.add(Dense(9, activation='relu'))
    model.add(LSTM(9, activation='tanh'))
    model.add(Dense(36, activation='relu'))
    model.add(Dense(1, activation='relu'))
    model.compile(optimizer='Adam', loss="mse", metrics=['accuracy'])
    return model
Model = MakeRNN()
print(x.shape)
x = x.reshape(-1,1,3)
print(y[0].dtype)
print(x.shape)
Model.fit(x,y, epochs=20)

print(Model.predict(np.array([[[1.0,2.0,3.0]]])))
</code>```

Title: Keras LSTM Dtype in MatMul not the same

Body:
So, I'm coding a LSTM model to find the next number in a sequence. But when I fit the model I get this error,

TypeError: Input 'b' of 'MatMul' Op has type float32 that does not match type int64 of argument 'a'.

I don't understand this question because Ive checked and all of the data and labels are dtype int64.

Here is my code:

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, LSTM
import random
import numpy as np

def makeData(total, types=5):
    #PATTERNS:
    #1)going up by 1
    #2)going up by 2
    #3)muliply by 3
    #4)multiple by 2
    #5)square number
    NumPer = int(total/types)
    Labels = []
    Data = []
    print(NumPer)
    for type in range(types):
        for i in range(NumPer):
            preData = []
            if type == 0:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x+1)
                preData.append(x+2)
                Labels.append([x+3])
            if type == 1:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x+2)
                preData.append(x+4)
                Labels.append([x+6])
            if type == 2:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x*3)
                preData.append(x*9)
                Labels.append([x*27])
            if type == 3:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x*2)
                preData.append(x*4)
                Labels.append([x*8])
            if type == 4:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x*x)
                preData.append((x*x)*(x*x))
                Labels.append([(x*x)*(x*x)*((x*x)*(x*x))])
        Data.append(preData)
    return np.array(Data), np.array(Labels)

x, y = makeData(5)

def MakeRNN():
    model = Sequential()
    model.add(LSTM(3, activation='tanh'))
    model.add(Dense(9, activation='relu'))
    model.add(LSTM(9, activation='tanh'))
    model.add(Dense(36, activation='relu'))
    model.add(Dense(1, activation='relu'))
    model.compile(optimizer='Adam', loss="mse", metrics=['accuracy'])
    return model
Model = MakeRNN()
print(x.shape)
x = x.reshape(-1,1,3)
print(y[0].dtype)
print(x.shape)
Model.fit(x,y, epochs=20)

print(Model.predict([[1,2,3]]))

I don't understand this, I would appreciate any help from you guys. I don't know too much in the field of keras.

Body:
Following code worked for me. Just made some tweaks to the x, y from makeData to convert them to floats. Also, the argument passed to predict needs to be 3 dimensional (at present you have a 2d argument) and it needs to be a float. Also need to add return sequences = True at first LSTM because it still has another LSTM after it.
Also, your model is a little bit strange. Keras expects the inputs to a sequential model to be of form (batch_size, timesteps, input_dim). You have timesteps = 1 and hence no sequence really. But that is a separate thing about what you want to do. As for getting the code to run, above tweaks worked.

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, LSTM
import random
import numpy as np

def makeData(total, types=5):
    #PATTERNS:
    #1)going up by 1
    #2)going up by 2
    #3)muliply by 3
    #4)multiple by 2
    #5)square number
    NumPer = int(total/types)
    Labels = []
    Data = []
    print(NumPer)
    for type in range(types):
        for i in range(NumPer):
            preData = []
            if type == 0:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x+1)
                preData.append(x+2)
                Labels.append([x+3])
            if type == 1:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x+2)
                preData.append(x+4)
                Labels.append([x+6])
            if type == 2:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x*3)
                preData.append(x*9)
                Labels.append([x*27])
            if type == 3:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x*2)
                preData.append(x*4)
                Labels.append([x*8])
            if type == 4:
                x = random.random()*100
                x = round(x)
                preData.append(x)
                preData.append(x*x)
                preData.append((x*x)*(x*x))
                Labels.append([(x*x)*(x*x)*((x*x)*(x*x))])
        Data.append(preData)
    return np.array(Data), np.array(Labels)

x, y = makeData(5)
x = x.astype(float)
y = y.astype(float)

def MakeRNN():
    model = Sequential()
    model.add(LSTM(3, activation='tanh', return_sequences=True))
    model.add(Dense(9, activation='relu'))
    model.add(LSTM(9, activation='tanh'))
    model.add(Dense(36, activation='relu'))
    model.add(Dense(1, activation='relu'))
    model.compile(optimizer='Adam', loss="mse", metrics=['accuracy'])
    return model
Model = MakeRNN()
print(x.shape)
x = x.reshape(-1,1,3)
print(y[0].dtype)
print(x.shape)
Model.fit(x,y, epochs=20)

print(Model.predict(np.array([[[1.0,2.0,3.0]]])))


问:
How to get, change or clear a django-autocomplete-light field value with javascript
I'm using django-autocomplete-light and want to add action buttons do update/delete choices. So, I don't understand clearly how I can update/delete value and trigger change specific field.

Is there a clear documentation about that somewhere ?

答:
I don't think this solution is complete, but this is what I've been doing for programmatically selecting an option for Select2QuerySetViews:

```<code>$('#select2-<field_id>-container').val(<object_key>).html(<object_str>).trigger('change')
</code>```

So to get this to work you need:

field_id: ID of the input element

object_key: primary key of the selected model

object_str: string representation of the model (whatever is returned by __str__).

I know this doesn't fully answer your question, but I'm hoping there's some value.  There wasn't much documentation on how to do this either.  Would love if someone could improve on this.

Body:
I don't think this solution is complete, but this is what I've been doing for programmatically selecting an option for Select2QuerySetViews:

$('#select2-<field_id>-container').val(<object_key>).html(<object_str>).trigger('change')

So to get this to work you need:

field_id: ID of the input element

object_key: primary key of the selected model

object_str: string representation of the model (whatever is returned by __str__).

I know this doesn't fully answer your question, but I'm hoping there's some value.  There wasn't much documentation on how to do this either.  Would love if someone could improve on this.


问:
Receiving commandline input while listening for connections in Python
I am trying to write a program that has clients connect to it while the server is still able to send commands to all of the clients. I am using the "Twisted" solution. How can I go about this? Here is the code I have so far (I understand that Twisted already uses non-blocking sockets):</p>

```<code>import threading
print 'threading.'

def dock():
   try:
       from twisted.internet.protocol import Factory, Protocol
       from twisted.internet import reactor
       import currentTime
       print '[*]Imports succesful.'
   except:
       print '[/]Imports failed.'

   #Define the class for the protocol
   class Master(Protocol):
       command = raw_input('> ')
       def connectionMade(self):
           print 'Slave connected.'
           print currentTime.getTime() #Print current time
           #self.transport.write("Hello")

       def connectionLost(self, reason):
           print 'Lost.'
   #Assemble it in a "factory"

   class MasterFactory(Factory):
       protocol = Master

   reactor.listenTCP(8800, MasterFactory())

   #Run it all
   reactor.run()

def commandline():
   raw_input('>')

threading.Thread(target=dock()).start()
threading.Thread(target=commandline()).start()
</code>```

答:
Since you're already using twisted, you should also use it for the console part, instead of using raw_input in a thread.

Twisted's event loop can monitor any file descriptor for changes, including the standard input, so you can get event-based callbacks on a new line entered -- It works asynchronously without need for threads.

I've found this example of a interactive console in a twisted application, maybe you can use it.

Body:
I am trying to write a program that has clients connect to it while the server is still able to send commands to all of the clients. I am using the "Twisted" solution. How can I go about this? Here is the code I have so far (I understand that Twisted already uses non-blocking sockets):

import threading
print 'threading.'

def dock():
   try:
       from twisted.internet.protocol import Factory, Protocol
       from twisted.internet import reactor
       import currentTime
       print '[*]Imports succesful.'
   except:
       print '[/]Imports failed.'

   #Define the class for the protocol
   class Master(Protocol):
       command = raw_input('> ')
       def connectionMade(self):
           print 'Slave connected.'
           print currentTime.getTime() #Print current time
           #self.transport.write("Hello")

       def connectionLost(self, reason):
           print 'Lost.'
   #Assemble it in a "factory"

   class MasterFactory(Factory):
       protocol = Master

   reactor.listenTCP(8800, MasterFactory())

   #Run it all
   reactor.run()

def commandline():
   raw_input('>')

threading.Thread(target=dock()).start()
threading.Thread(target=commandline()).start()


问:
TypeError: forward() takes 1 positional argument but 2 were given

class DeConv2d(nn.Module):
    def __init__(self, in_channel, out_channel, kernel_size, stride, padding, dilation):
        super().__init__()

        self.up = nn.Upsample(scale_factor=2, mode='nearest')
        self.conv = nn.Conv2d(in_channel, out_channel, kernel_size=kernel_size, \
                              stride=stride, padding=padding, dilation=dilation)

    def forward(self, x):

        output = self.up(x)
        output = self.conv(output)

        return output

class EncoderDecoder(nn.Module):
    def __init__(self, pretrained_net, n_class):
        super().__init__()
        self.n_class = n_class
        self.pretrained_net = pretrained_net
        self.relu = nn.ReLU(inplace=True)

        self.deconv1 = DeConv2d(512, 512, kernel_size=3, stride=1, padding=1, dilation=1)
        self.bn1 = nn.BatchNorm2d(512)

        self.deconv2 = DeConv2d(512, 256, kernel_size=3, stride=1, padding=1, dilation=1)
        self.bn2 = nn.BatchNorm2d(256)

        self.deconv3 = DeConv2d(256, 128, kernel_size=3, stride=1, padding=1, dilation=1)
        self.bn3 = nn.BatchNorm2d(128)

        self.deconv4 = DeConv2d(128, 64, kernel_size=3, stride=1, padding=1, dilation=1)
        self.bn4 = nn.BatchNorm2d(64)

        self.classifier = nn.Conv2d(64, n_class, kernel_size=1)

    def forward(self, x):

        output=self.pretrained_net.layers(x)

        output=self.relu(self.deconv1(output))
        output=self.bn1(output)

        output=self.relu(self.deconv2(output))
        output=self.bn2(output)

        output=self.relu(self.deconv3(output))
        output=self.bn3(output)

        output=self.relu(self.deconv4(output))
        output=self.bn4(output)

        output=self.classifier(output)

        return output
```

this is my code and I don't know why the type error exist . Does somebody know how to fix these problems?

答:
When you create a class, and define a function with self args within the class, self is autofilled with the class.Ex:

class item():# create a random class
 self.var = 0
 def fun(self,x):
  self.var +=x
n = item()
```

<p>And you can try add:</p>

```n.fun(3)
print(n.var)
```

returns 3

self argument is autofilled with class itself

Body:
class DeConv2d(nn.Module):
    def __init__(self, in_channel, out_channel, kernel_size, stride, padding, dilation):
        super().__init__()

        self.up = nn.Upsample(scale_factor=2, mode='nearest')
        self.conv = nn.Conv2d(in_channel, out_channel, kernel_size=kernel_size, \
                              stride=stride, padding=padding, dilation=dilation)

    def forward(self, x):

        output = self.up(x)
        output = self.conv(output)

        return output

class EncoderDecoder(nn.Module):
    def __init__(self, pretrained_net, n_class):
        super().__init__()
        self.n_class = n_class
        self.pretrained_net = pretrained_net
        self.relu = nn.ReLU(inplace=True)

        self.deconv1 = DeConv2d(512, 512, kernel_size=3, stride=1, padding=1, dilation=1)
        self.bn1 = nn.BatchNorm2d(512)

        self.deconv2 = DeConv2d(512, 256, kernel_size=3, stride=1, padding=1, dilation=1)
        self.bn2 = nn.BatchNorm2d(256)

        self.deconv3 = DeConv2d(256, 128, kernel_size=3, stride=1, padding=1, dilation=1)
        self.bn3 = nn.BatchNorm2d(128)

        self.deconv4 = DeConv2d(128, 64, kernel_size=3, stride=1, padding=1, dilation=1)
        self.bn4 = nn.BatchNorm2d(64)

        self.classifier = nn.Conv2d(64, n_class, kernel_size=1)

    def forward(self, x):

        output=self.pretrained_net.layers(x)

        output=self.relu(self.deconv1(output))
        output=self.bn1(output)

        output=self.relu(self.deconv2(output))
        output=self.bn2(output)

        output=self.relu(self.deconv3(output))
        output=self.bn3(output)

        output=self.relu(self.deconv4(output))
        output=self.bn4(output)

        output=self.classifier(output)

        return output

this is my code and I don't know why the type error exist . Does somebody know how to fix these problems?

Body:
When you create a class, and define a function with self args within the class, self is autofilled with the class.Ex:

class item():# create a random class
 self.var = 0
 def fun(self,x):
  self.var +=x
n = item()

And you can try add:

n.fun(3)
print(n.var)

returns 3

self argument is autofilled with class itself


问:
How to add multiple rows in ngFor table dynamically in edit mode in angular 6
I have an ngFor table in which i can add a single row in edit mode, which has some select boxes in it.

I am able to edit, cancel and save the data into the database which is mysql.

The question is that i need to add more than one row dynamically in the table in edit mode and save them all in one go.
Actually it is a project for my office, so i can't share any code.
but i'm using

```<code>myArray.splice(0,0,newObject);
myArray = [...myArray]
</code>```

to add a new row into the table.
How can i add multiple rows using the same having its individual cancel button.

答:
Stackblitz demo

You can work with a FormArray to do that. Basically, each row of your table will be an entry in your FormArray:

<form [formGroup]="_form" novalidate>

              <input matInput
                     formControlName="name"
                     placeholder="Name"
                     required>

              <input matInput
                     formControlName="surname"
                     placeholder="Surname"
                     required>

              <select formControlName="gender">
                <option [ngValue]="null">GENDER</option>
                <option *ngFor="let g of _genders" [ngValue]="g">
                  {{g}}
                </option>
              </select>

              <button (click)="_removeRow(i)" type="button">
                Remove
              </button>

              <button type="button" (click)="_addRow()">
                New Row
              </button>

</form>
```

<p>Notice that the controls in form array are also <code>FormGroup</code>'s instead of simple controls. The overall <code>_form</code> can be declared as:</p>

<pre class="lang-js prettyprint-override"><code>this._form = this._formBuilder.group({
  data: this._formBuilder.array([])
});
</code>```

And you can add a FormGroup to the FormArray by doing:

const formArray: FormArray = this._form.get('data') as FormArray;

const form = this._fb.group({
  name: ['', Validators.required],
  surname: ['', Validators.required],
  gender: [null, Validators.required]
});

formArray.push(form);
```

<p>You can remove a row by removing it from the formArray:</p>

<pre class="lang-js prettyprint-override"><code>const formArray: FormArray = this._form.get('data') as FormArray;
formArray.removeAt(index);
</code>```

Body:
I have an ngFor table in which i can add a single row in edit mode, which has some select boxes in it.

I am able to edit, cancel and save the data into the database which is mysql.

The question is that i need to add more than one row dynamically in the table in edit mode and save them all in one go.
Actually it is a project for my office, so i can't share any code.
but i'm using

myArray.splice(0,0,newObject);
myArray = [...myArray]

to add a new row into the table.
How can i add multiple rows using the same having its individual cancel button.

Body:
Stackblitz demo

You can work with a FormArray to do that. Basically, each row of your table will be an entry in your FormArray:

<form [formGroup]="_form" novalidate>
    <table>
        <tbody formArrayName="data">
          <tr *ngFor="let array of _form.get('data').controls; index as i"
              [formGroupName]="i">
            <td>
              <input matInput
                     formControlName="name"
                     placeholder="Name"
                     required>
            </td>
            <td>
              <input matInput
                     formControlName="surname"
                     placeholder="Surname"
                     required>
            </td>
            <td>
              <select formControlName="gender">
                <option [ngValue]="null">GENDER</option>
                <option *ngFor="let g of _genders" [ngValue]="g">
                  {{g}}
                </option>
              </select>
            </td>
            <td>
              <button (click)="_removeRow(i)" type="button">
                Remove
              </button>
            </td>
          </tr>
        </tbody>
        <tbody>
          <tr>
            <td>
              <button type="button" (click)="_addRow()">
                New Row
              </button>
            </td>
          </tr>
        </tbody>
    </table>
</form>

Notice that the controls in form array are also FormGroup's instead of simple controls. The overall _form can be declared as:

this._form = this._formBuilder.group({
  data: this._formBuilder.array([])
});

And you can add a FormGroup to the FormArray by doing:

const formArray: FormArray = this._form.get('data') as FormArray;

const form = this._fb.group({
  name: ['', Validators.required],
  surname: ['', Validators.required],
  gender: [null, Validators.required]
});

formArray.push(form);

You can remove a row by removing it from the formArray:

const formArray: FormArray = this._form.get('data') as FormArray;
formArray.removeAt(index);


问:
How to use Scala DataFrameReader option method
The Scala DataFrameReader has a function "option" which has the following signature:

```<code> def  option(key: String, value: String): DataFrameReader
   // Adds an input option for the underlying data source.
</code>```

So what is an "input option" for the underlying data source, can someone share an example here on how to use this function?

答:
```<code>sparkSession.read.option("header",true).parquet(fileKey)
</code>```

In above code snippet, Header=True means : keep column headers.

Body:
The Scala DataFrameReader has a function "option" which has the following signature:

 def  option(key: String, value: String): DataFrameReader
   // Adds an input option for the underlying data source.

So what is an "input option" for the underlying data source, can someone share an example here on how to use this function?

Body:
sparkSession.read.option("header",true).parquet(fileKey)

In above code snippet, Header=True means : keep column headers.