问:
Pandas - groupby result as table
I'm new to pandas and plotly and am currently working on a small analysis project looking at my Netflix data.

I'm trying to display a table of my top 10 films (by max. duration watched). I have:

top10 = df.groupby(['Film Title'])['Duration'].sum().nlargest(10)

and

```<code>table = go.Figure(data=[go.Table(
    header=dict(values=('Title', 'Total Time Watched'),
                fill_color='#66c5cc',
                align='left'),
    cells=dict(values=['', top10],
               align='left'),
)])
table.update_layout(title_text="Top 10 Series through the Years", title_x=0.5)
</code>```

This results in a table that looks like this:

result table

I can't find a way to also get the titles of the films connected to the "top 10" list to be able to insert that into the "values" in "cells". The "top 10" list only displays the duration. I tried changing the index of "top10", and to create a list, but I can't find an answer. It's probably something very simple, but I'm new to programming, so, no idea where the error is :/

Appreciate your help! Thank you in advance :)

答:
you're putting blank values '' in your cell values, you need to fill it with the values you want, in this case it's your groupby index: top10.index

```<code>table = go.Figure(data=[go.Table(
    header=dict(values=('Title', 'Total Time Watched'),
                fill_color='#66c5cc',
                align='left'),
    cells=dict(values=[top10.index, top10],
               align='left'),
)])
table.update_layout(title_text="Top 10 Series through the Years", title_x=0.5)
</code>```

Title: Pandas - groupby result as table

Body:
I'm new to pandas and plotly and am currently working on a small analysis project looking at my Netflix data.

I'm trying to display a table of my top 10 films (by max. duration watched). I have:

top10 = df.groupby(['Film Title'])['Duration'].sum().nlargest(10)

and

table = go.Figure(data=[go.Table(
    header=dict(values=('Title', 'Total Time Watched'),
                fill_color='#66c5cc',
                align='left'),
    cells=dict(values=['', top10],
               align='left'),
)])
table.update_layout(title_text="Top 10 Series through the Years", title_x=0.5)

This results in a table that looks like this:

result table

I can't find a way to also get the titles of the films connected to the "top 10" list to be able to insert that into the "values" in "cells". The "top 10" list only displays the duration. I tried changing the index of "top10", and to create a list, but I can't find an answer. It's probably something very simple, but I'm new to programming, so, no idea where the error is :/

Appreciate your help! Thank you in advance :)

Body:
you're putting blank values '' in your cell values, you need to fill it with the values you want, in this case it's your groupby index: top10.index

table = go.Figure(data=[go.Table(
    header=dict(values=('Title', 'Total Time Watched'),
                fill_color='#66c5cc',
                align='left'),
    cells=dict(values=[top10.index, top10],
               align='left'),
)])
table.update_layout(title_text="Top 10 Series through the Years", title_x=0.5)


来源: stackexchange

问:
Error when connect database continuously
When I am querying from database in continuous looping, after some time
I get an error :

An exception has been raised that is likely due to a transient
  failure. If you are connecting to a SQL Azure database consider using SqlAzureExecutionStrategy.

Normally it is working fine.

答:
I configured the the project to run in the development mode. But for some unknown reason, it always runs in the production mode.

So that means it uses the  ConnectionStrings from
appsettings.Production.json file. Because the ConnectionStrings in this file points to the production server and the production server is not reachable this error is genereted. Temporary rename this file
and use the appsettings.Development.json it will solve it.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Help me my first test
I have created a Hello World program and I am new to C#, My program will print 100 words like that as follow

```<code>public static void Main(/*I forgot arguments*/)
{
   string []s=new string [100];
   foreach(string ss in s)
   {
      ss="Hello World";
      Console.WriteLine("{0}\n",ss);
   }
}
</code>```

Could you show me  step-by-step how to create a test for this program ? Does it need one ? I don't have an image of how testers do the test. Sorry I am stupid.

I think I have tried my best, no one ever find I find it unworthy to me not to get any help ? I don't need the class because I forgot the class long ago after the accident.

答:
Why would you need a test for this? What would you be testing for? Instead of how to test the code I'd be looking at how you can make it better.

Have a look at the Main below.

```<code>public static void Main(/*I forgot arguments*/)
{
    for(var i = 0; i < 100; i++)
    {
        Console.WriteLine("Hello World");
    }
}
</code>```

Note, you don't use the array you create so there is no need to create it. Use a for loop when you know exactly how many times you need to loop. Also, there is no to format your string if you are not concating it with other strings.

Title: Help me my first test

Body:
I have created a Hello World program and I am new to C#, My program will print 100 words like that as follow

public static void Main(/*I forgot arguments*/)
{
   string []s=new string [100];
   foreach(string ss in s)
   {
      ss="Hello World";
      Console.WriteLine("{0}\n",ss);
   }
}

Could you show me  step-by-step how to create a test for this program ? Does it need one ? I don't have an image of how testers do the test. Sorry I am stupid.

I think I have tried my best, no one ever find I find it unworthy to me not to get any help ? I don't need the class because I forgot the class long ago after the accident.

Body:
Why would you need a test for this? What would you be testing for? Instead of how to test the code I'd be looking at how you can make it better.

Have a look at the Main below.

public static void Main(/*I forgot arguments*/)
{
    for(var i = 0; i < 100; i++)
    {
        Console.WriteLine("Hello World");
    }
}

Note, you don't use the array you create so there is no need to create it. Use a for loop when you know exactly how many times you need to loop. Also, there is no to format your string if you are not concating it with other strings.


问:
curl.h no such file or directory
I installed curl this command (i use Ubuntu):

```<code>sudo apt-get install curl
</code>```

When I test simple program using g++ test.cpp

```<code>#include <stdio.h>
#include <curl/curl.h>

int main(void)
{
  CURL *curl;
  CURLcode res;

  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");

    /* Perform the request, res will get the return code */
    res = curl_easy_perform(curl);
    /* Check for errors */
    if(res != CURLE_OK)
      fprintf(stderr, "curl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));

    /* always cleanup */
    curl_easy_cleanup(curl);
  }
  return 0;
}
</code>```

g++ shows me:

```<code>fatal error: curl/curl.h: No such file or directory
compilation terminated.
</code>```

Can anyone help me?

答:
For those of view who stumbled on this post after a Google of "R curl curl.h no such file or directory" (first link), who are on Windows, and want to install curl in R, the solution is pretty simple and fast.

Launch Rtools Bash from the Rtools folder in the Windows all app menu.

Throw pacman -Syuv in the command line to make sure you're up-to-date.

pacman -S mingw-w64-x86_64-curl fixes the problem. You can now go back to R and install curl without any issues. No more curl.h missing errors.

Title: curl.h no such file or directory

Body:
I installed curl this command (i use Ubuntu):

sudo apt-get install curl

When I test simple program using g++ test.cpp

#include <stdio.h>
#include <curl/curl.h>

int main(void)
{
  CURL *curl;
  CURLcode res;

  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");

    /* Perform the request, res will get the return code */
    res = curl_easy_perform(curl);
    /* Check for errors */
    if(res != CURLE_OK)
      fprintf(stderr, "curl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));

    /* always cleanup */
    curl_easy_cleanup(curl);
  }
  return 0;
}

g++ shows me:

fatal error: curl/curl.h: No such file or directory
compilation terminated.

Can anyone help me?


问:
Cannot read properties of undefined (reading 'top') happens on every page except homepage
I currently get a jQuery error that is driving me crazy.

"Cannot read properties of undefined (reading 'top')"

I implemented a simple scroll to anchor function.

```<code>    $('html,body').animate({
        scrollTop: $("#scroll").offset().top
      },
      'fast');
  });
</code>```

Code is working fine on the homepage.
But on all other pages it is returning the error below

"Cannot read properties of undefined (reading 'top')"

It is driving me crazy. All help is appreciated :)

答:
That's probably because the element that matches the #scroll selector does not exist on those pages that threw the error. When that happens, $('#scroll').offset() returned undefined, and you cannot access top from undefined.

To fix this, you will probably need to ensure the element exists before attempting to invoke the logic:

```<code>const $scroll = $('#scroll');

if ($scroll.length) {
    $('html,body').animate({
        scrollTop: $scroll.offset().top
    }, 'fast');
}
</code>```

Body:
I currently get a jQuery error that is driving me crazy.

"Cannot read properties of undefined (reading 'top')"

I implemented a simple scroll to anchor function.

    $('html,body').animate({
        scrollTop: $("#scroll").offset().top
      },
      'fast');
  });

Code is working fine on the homepage.
But on all other pages it is returning the error below

"Cannot read properties of undefined (reading 'top')"

It is driving me crazy. All help is appreciated :)

Body:
That's probably because the element that matches the #scroll selector does not exist on those pages that threw the error. When that happens, $('#scroll').offset() returned undefined, and you cannot access top from undefined.

To fix this, you will probably need to ensure the element exists before attempting to invoke the logic:

const $scroll = $('#scroll');

if ($scroll.length) {
    $('html,body').animate({
        scrollTop: $scroll.offset().top
    }, 'fast');
}


问:
Should we enclose filename with encodeURIComponent in Javascript?
I'm accepting files to be uploaded to my site. So, is it a safe practice to encodeURIComponent the filename? Or should I use escape()? OR is it necessary at all?</p>

答:
You should never use escape for anything (unless forced to because you're sending information to something that will use unescape [which it shouldn't]).

Whether you need to use encodeURIComponent depends entirely on whether you're going to use the filename directly as a URI component¹. If you are, yes, you should use it. If you aren't, no, you probably shouldn't.

¹ for instance, as a query string parameter when you're creating the query string manually rather than via URLSearchParams (which is generally better practice)


问:
Node.js Unable to send multiple csv in an archive folder
I'have currently a problem to create and to send an archive from a node.js server.

In fact, i succeeded create an archive with 5 csv files on the archive but when i send the archive to my React Application and when i unzip this archive i'have got just one file ....

I have checked (local) the archive created by the server and there are 5 files instead of one when i unzip the folder send to the React Application.

My http response :

```<code>import { Parser } from "json2csv";
import archiver from "archiver";
import fs from "fs";
import path from "path";

const output = fs.createWriteStream(`csv/${campaign.title}.zip`, 'utf-8');

const archive = archiver("zip", {
zlib: { level: 9 }, // Sets the compression level.
});

output.on("close", function () {
console.log(archive.pointer() + " total bytes");
console.log("archiver has been finalized and the output file descriptor has closed.");
});

output.on("end", function () {
console.log("Data has been drained");
});

archive.on("warning", function (err) {
if (err.code === "ENOENT") {
    // log warning
} else {
    // throw error
    throw err;
}});

archive.on("error", function (err) {
throw err;
});

archive.pipe(output);

d.map(items => {
let file = items;
archive.append(file, { name: file });
});

archive.pipe(res)

archive.finalize();

res.setHeader('application/zip')

res.setHeader("Content-Disposition", `attachment; filename=${campaign.title}.zip`);

res.status(200).send(archive);
</code>```

答:
What is content of mystical d? You use archiver incorrectly I think:

your code:

```<code>d.map(items => {
let file = items;
archive.append(file, { name: file });
});
</code>```

but documentation say:
https://www.archiverjs.com/docs/archiver#append

```<code>append(source, data) → {this}
</code>```

Appends an input source (text string, buffer, or stream) to the instance.

When the instance has received, processed, and emitted the input, the entry event is fired.

Parameters

```<code>source - Buffer | Stream | String - The input source.
data - Object - The entry data.
</code>```

Check content and use of d - you need data and filename for use in append

EDIT:

Don't use Array.map like Array.forEach, it's Anti-pattern: Is performing a mapping operation without using returned value an antipattern?

Body:
I'have currently a problem to create and to send an archive from a node.js server.

In fact, i succeeded create an archive with 5 csv files on the archive but when i send the archive to my React Application and when i unzip this archive i'have got just one file ....

I have checked (local) the archive created by the server and there are 5 files instead of one when i unzip the folder send to the React Application.

My http response :

import { Parser } from "json2csv";
import archiver from "archiver";
import fs from "fs";
import path from "path";

const output = fs.createWriteStream(`csv/${campaign.title}.zip`, 'utf-8');

const archive = archiver("zip", {
zlib: { level: 9 }, // Sets the compression level.
});

output.on("close", function () {
console.log(archive.pointer() + " total bytes");
console.log("archiver has been finalized and the output file descriptor has closed.");
});

output.on("end", function () {
console.log("Data has been drained");
});

archive.on("warning", function (err) {
if (err.code === "ENOENT") {
    // log warning
} else {
    // throw error
    throw err;
}});

archive.on("error", function (err) {
throw err;
});

archive.pipe(output);

d.map(items => {
let file = items;
archive.append(file, { name: file });
});

archive.pipe(res)

archive.finalize();

res.setHeader('application/zip')

res.setHeader("Content-Disposition", `attachment; filename=${campaign.title}.zip`);

res.status(200).send(archive);

Body:
What is content of mystical d? You use archiver incorrectly I think:

your code:

d.map(items => {
let file = items;
archive.append(file, { name: file });
});

but documentation say:
https://www.archiverjs.com/docs/archiver#append

append(source, data) → {this}

Appends an input source (text string, buffer, or stream) to the instance.

When the instance has received, processed, and emitted the input, the entry event is fired.

Parameters

source - Buffer | Stream | String - The input source.
data - Object - The entry data.

Check content and use of d - you need data and filename for use in append

EDIT:

Don't use Array.map like Array.forEach, it's Anti-pattern: Is performing a mapping operation without using returned value an antipattern?


问:
On 0 row in jqgrid how can we replace Page 1 of NaN to something else?
if the jqgrid has no rows at some time, it shows Page 1 of NaN what is Nan here? can't we change it to something more appropriate like Page 0 of 0 or something better?

my jqgrid code

```<code>var grid = jQuery("#list1");

                grid.jqGrid({

                  datastr : xml,
                  datatype: 'xmlstring',
                  colNames:['cfgId','Name', 'Host', 'Description','Product', 'Type', 'Last Updated Time','Last Updated By','',''],
                  colModel:[
                      {name:'cfgId',index:'cfgId', width:90, align:"left", hidden:true},
                      {name:'cfgName',index:'cfgName', width:90, align:"left", formatter: 'showlink', formatoptions:
                                                                                {
                                                                                baseLinkUrl:'javascript:',
                                                                                showAction: "goToViewAllPage('",
                                                                                addParam: "');"

                                                                                }},
                      {name:'hostname',index:'hostname', width:90, align:"left"},
                      {name:'cfgDesc',index:'cfgDesc', width:90, align:"left"},
                      {name:'productId',index:'productId', width:60, align:"left"},
                      {name:'cfgType',index:'cfgType', width:60, align:"left"},
                      {name:'updateDate',index:'updateDate',sorttype:'Date', width:120, align:"left"},
                      {name:'emailAddress',index:'emailAddress', width:120, align:"left"},
                      {name:'absolutePath',index:'absolutePath', width:90, align:"left", hidden:true},
                      {name:'fileName',index:'fileName', width:90, align:"left", hidden:true},
                  ],
                  pager : '#gridpager',
                  rowNum:10,
                  rowList:[10,50,100],
                  scrollOffset:0,
                  height: 'auto',
                  emptyrecords: 'No configurations loaded',
                  autowidth:true,
                  viewrecords: true,
                  gridview: true,
                  multiselect: true,
                  xmlReader: {
                      root : "list",
                      row: "Response",
                      userdata: "userdata",
                      repeatitems: false
                  },
                  loadComplete: function () {
                        var count = grid.getGridParam();
                        var ts = grid[0];
                        if (ts.p.reccount === 0) {
                            grid.hide();
                            emptyMsgDiv.show();
                        } else {
                            grid.show();
                            emptyMsgDiv.hide();
                        }
                    },
                  onSelectRow: function(id,status){
                      var rowData = jQuery(this).getRowData(id);
                      configid = rowData['cfgId'];
                      configname=rowData['cfgName'];
                      configdesc=rowData['cfgDesc'];
                      configenv=rowData['cfgType'];
                      absolutepath=rowData['absolutePath'];

                      /*filename=rowData['fileName'];
                      updatedate=rowData['updateDate'];
                      absolutepath=rowData['absolutePath'];*/
                      updateproductid=rowData['productId'];

                      $('#cfgid').removeAttr('disabled');
                      document.getElementById("cfgid").value=configid;
                      document.getElementById("cfgname").value=configname;
                      document.getElementById("cfgdesc").value=configdesc;

                      var element = document.getElementById('cfgenv');
                      if(configenv=="Production")
                          element.value = "Production";
                      else if(configenv=="Development")
                          element.value="Development";
                      else
                          element.value="Test/QA";
                      rowChecked=1;
                      currentrow=id;
                      }

                });
                grid.jqGrid('navGrid','#gridpager',{edit:false,add:false,del:false});
                jQuery("#m1").click( function() {
                    var s;
                    s = grid.jqGrid('getGridParam','selarrrow');
                    alert(s);
                });
                var myGrid = $("#list1");
                $("#cb_"+myGrid[0].id).hide();
                // place div with empty message insde of bdiv
                emptyMsgDiv.insertAfter(grid.parent());

         }
</code>```

My Xml

```<code><Response>
<isSuccess>true</isSuccess>
<operation>viewall</operation>
<message>No configurations were found for this project</message>
</Response>
</code>```

答:
It's the same problem which was described here, but with XML data.

In the line the variable rn will be declared, but it will be not assigned it any value. The first assignment of the value rn = parseInt(ts.p.rowNum,10); will be here inside of if(gxml && gl) which is false in your case. So the statement

```<code>ts.p.lastpage = Math.ceil(gl/ rn);
</code>```

produce NaN value.

To fix the bug you can modify the line 1086 of the jquery.jqGrid.src.js of the jqGrid 4.1.2 from

```<code>var gl = gxml.length, j=0, grpdata={}, rn;
</code>```

to

```<code>var gl = gxml.length, j=0, grpdata={}, rn = parseInt(ts.p.rowNum,10);
</code>```

The line 1088 which contains the same assignment can be removed.

How you can see in the demo (compare with your same code used original jquery.jqGrid.src.js) the changes fix the problem.

Body:
if the jqgrid has no rows at some time, it shows Page 1 of NaN what is Nan here? can't we change it to something more appropriate like Page 0 of 0 or something better?

my jqgrid code

var grid = jQuery("#list1");

                grid.jqGrid({

                  datastr : xml,
                  datatype: 'xmlstring',
                  colNames:['cfgId','Name', 'Host', 'Description','Product', 'Type', 'Last Updated Time','Last Updated By','',''],
                  colModel:[
                      {name:'cfgId',index:'cfgId', width:90, align:"left", hidden:true},
                      {name:'cfgName',index:'cfgName', width:90, align:"left", formatter: 'showlink', formatoptions:
                                                                                {
                                                                                baseLinkUrl:'javascript:',
                                                                                showAction: "goToViewAllPage('",
                                                                                addParam: "');"

                                                                                }},
                      {name:'hostname',index:'hostname', width:90, align:"left"},
                      {name:'cfgDesc',index:'cfgDesc', width:90, align:"left"},
                      {name:'productId',index:'productId', width:60, align:"left"},
                      {name:'cfgType',index:'cfgType', width:60, align:"left"},
                      {name:'updateDate',index:'updateDate',sorttype:'Date', width:120, align:"left"},
                      {name:'emailAddress',index:'emailAddress', width:120, align:"left"},
                      {name:'absolutePath',index:'absolutePath', width:90, align:"left", hidden:true},
                      {name:'fileName',index:'fileName', width:90, align:"left", hidden:true},
                  ],
                  pager : '#gridpager',
                  rowNum:10,
                  rowList:[10,50,100],
                  scrollOffset:0,
                  height: 'auto',
                  emptyrecords: 'No configurations loaded',
                  autowidth:true,
                  viewrecords: true,
                  gridview: true,
                  multiselect: true,
                  xmlReader: {
                      root : "list",
                      row: "Response",
                      userdata: "userdata",
                      repeatitems: false
                  },
                  loadComplete: function () {
                        var count = grid.getGridParam();
                        var ts = grid[0];
                        if (ts.p.reccount === 0) {
                            grid.hide();
                            emptyMsgDiv.show();
                        } else {
                            grid.show();
                            emptyMsgDiv.hide();
                        }
                    },
                  onSelectRow: function(id,status){
                      var rowData = jQuery(this).getRowData(id);
                      configid = rowData['cfgId'];
                      configname=rowData['cfgName'];
                      configdesc=rowData['cfgDesc'];
                      configenv=rowData['cfgType'];
                      absolutepath=rowData['absolutePath'];

                      /*filename=rowData['fileName'];
                      updatedate=rowData['updateDate'];
                      absolutepath=rowData['absolutePath'];*/
                      updateproductid=rowData['productId'];

                      $('#cfgid').removeAttr('disabled');
                      document.getElementById("cfgid").value=configid;
                      document.getElementById("cfgname").value=configname;
                      document.getElementById("cfgdesc").value=configdesc;

                      var element = document.getElementById('cfgenv');
                      if(configenv=="Production")
                          element.value = "Production";
                      else if(configenv=="Development")
                          element.value="Development";
                      else
                          element.value="Test/QA";
                      rowChecked=1;
                      currentrow=id;
                      }

                });
                grid.jqGrid('navGrid','#gridpager',{edit:false,add:false,del:false});
                jQuery("#m1").click( function() {
                    var s;
                    s = grid.jqGrid('getGridParam','selarrrow');
                    alert(s);
                });
                var myGrid = $("#list1");
                $("#cb_"+myGrid[0].id).hide();
                // place div with empty message insde of bdiv
                emptyMsgDiv.insertAfter(grid.parent());

         }

My Xml

<Response>
<isSuccess>true</isSuccess>
<operation>viewall</operation>
<message>No configurations were found for this project</message>
</Response>

Body:
It's the same problem which was described here, but with XML data.

In the line the variable rn will be declared, but it will be not assigned it any value. The first assignment of the value rn = parseInt(ts.p.rowNum,10); will be here inside of if(gxml && gl) which is false in your case. So the statement

ts.p.lastpage = Math.ceil(gl/ rn);

produce NaN value.

To fix the bug you can modify the line 1086 of the jquery.jqGrid.src.js of the jqGrid 4.1.2 from

var gl = gxml.length, j=0, grpdata={}, rn;

to

var gl = gxml.length, j=0, grpdata={}, rn = parseInt(ts.p.rowNum,10);

The line 1088 which contains the same assignment can be removed.

How you can see in the demo (compare with your same code used original jquery.jqGrid.src.js) the changes fix the problem.


问:
Error : RuntimeException at DisplayListCanvas.throwIfCannotDraw
My application work very well on nougat emulator and many devices, but i found this exception in google play crash reporter, I don't know why it happened, The exception causes with nougat devices ++ only.

the exception :

```<code>   java.lang.RuntimeException:
  at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:260)
  at android.graphics.Canvas.drawBitmap(Canvas.java:1420)
  at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:545)
  at android.view.View.getDrawableRenderNode(View.java:18591)
  at android.view.View.drawBackground(View.java:18527)
  at android.view.View.draw(View.java:18315)
  at android.view.View.updateDisplayListIfDirty(View.java:17302)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty(View.java:17297)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty(View.java:17297)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty(View.java:17297)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty(View.java:17297)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.draw(View.java:18327)
  at com.android.internal.policy.DecorView.draw(DecorView.java:919)
  at android.view.View.updateDisplayListIfDirty(View.java:17302)
  at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:692)
  at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:698)
  at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:806)
  at android.view.ViewRootImpl.draw(ViewRootImpl.java:3135)
  at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2931)
  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2523)
  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1522)
  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7098)
  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:927)
  at android.view.Choreographer.doCallbacks(Choreographer.java:702)
  at android.view.Choreographer.doFrame(Choreographer.java:638)
  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:913)
  at android.os.Handler.handleCallback(Handler.java:751)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:154)
  at android.app.ActivityThread.main(ActivityThread.java:6682)
  at java.lang.reflect.Method.invoke(Native Method:0)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
</code>```

What this error could be?

CAUTION: all drawable i used is less than 1MB.

答: To anyone who still needs an answer to this question(as I did two days ago) the answer is simple: Resize all your images that are above 1024 x 1024 to 1024 x 1024, for example I had an image with something like 1080 x 850, that 1080 is a problem and would thus need to be resized and scaled down to 1024 and if you use a photo editing tool, when scaling it will automatically set the correct width / length to your image</p>

Body:
My application work very well on nougat emulator and many devices, but i found this exception in google play crash reporter, I don't know why it happened, The exception causes with nougat devices ++ only.

the exception :

   java.lang.RuntimeException:
  at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:260)
  at android.graphics.Canvas.drawBitmap(Canvas.java:1420)
  at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:545)
  at android.view.View.getDrawableRenderNode(View.java:18591)
  at android.view.View.drawBackground(View.java:18527)
  at android.view.View.draw(View.java:18315)
  at android.view.View.updateDisplayListIfDirty(View.java:17302)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty(View.java:17297)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty(View.java:17297)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty(View.java:17297)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty(View.java:17297)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.draw(View.java:18327)
  at com.android.internal.policy.DecorView.draw(DecorView.java:919)
  at android.view.View.updateDisplayListIfDirty(View.java:17302)
  at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:692)
  at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:698)
  at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:806)
  at android.view.ViewRootImpl.draw(ViewRootImpl.java:3135)
  at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2931)
  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2523)
  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1522)
  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7098)
  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:927)
  at android.view.Choreographer.doCallbacks(Choreographer.java:702)
  at android.view.Choreographer.doFrame(Choreographer.java:638)
  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:913)
  at android.os.Handler.handleCallback(Handler.java:751)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:154)
  at android.app.ActivityThread.main(ActivityThread.java:6682)
  at java.lang.reflect.Method.invoke(Native Method:0)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

What this error could be?

CAUTION: all drawable i used is less than 1MB.


答:
encodeURIComponent takes a string and escapes it to make it safe to insert into a URI, typically used for query string data.

If you are inserting a string into a URI then you can use it, but should probably use URLSearchParams to construct the whole query string instead.

If you aren't inserting a string into a URI then you probably should not use it.

escape is deprecated and should not be used. It doesn't work property with Unicode.

Considerations for accepting files are typically more along the lines of "Will this accidentally overwrite an existing file?" and "Are the characters in this filename allowed by my filesystem?".

Some people prefer to generate a completely new file name (e.g. with a guid library) to ensure it is safe. You could store the original name in a database (at which point your escaping should be handled by parametrised queries).

Title: Should we enclose filename with encodeURIComponent in Javascript?

Body: I'm accepting files to be uploaded to my site. So, is it a safe practice to encodeURIComponent the filename? Or should I use escape()? OR is it necessary at all?


问:
poor pyspark query performance
I'm trying to migrate from a single node pure python/pandas workflow to a parallel workflow using spark cluster because i'm running into performance and OOM issues as the dataset is getting larger and larger. As a PoC, i've been trying to convert one part of my code which I think is best case for spark because the entire thing is pandas aggregates and very little of python just for collecting the data and writing to a db at the end.

This is what the code currently does: aggregates values for each userid for each month, in pseudo code:

```<code>
dates_to_process = [LIST OF DATES(FIRST OF MONTH. eg: 1/1/2010:00:00:00.0000) GOING BACK SEVERAL YEARS]
for uid, df in datafame.groupby('userid'):
      for start_date in dates_to_process:
          end_date = last_of_month(start_date) // this will be 31/1/2010:23:59:59.9999)
          current_month = df[df['date'] >= start_date & df['date'] <= end_date]
          // here run a bunch of queries like
          val1 = df[col1].sum()
          val2 = df[(col2) == "somestring"][col3].sum()
          val3 = df.groupby(col4).mean(col5)
          val4 = df[df[col6] <= end_date][col7].value_counts()
          // and so on. maybe 200 - 250 such calculations
          // collect the values and put it in new dataframe which gets written to db at the end

</code>```

I tried doing it in pyspark, but it turned out I need to call count() and collect() way too often and probably more often than recommended. And it takes maybe 3 minutes per userid (about 1500 unique userids) in a 3 million row dataframe.

Is there a better way of doing this or is spark not the right tool for this kind of job? I tried running on a local cluster of 2 other machines and the performance didn't improve all that much.

答:
Based on your code snippet , you should look at Pandas UDF and here, which would also allow you to reuse your existing native pandas code snippets as well.

Introducing a loop like that does not provide much gains in Spark , stick to native functions which are optimised

A typical example of Pandas UDF is as below -

Here I m trying to find out similar names utilising applyInPandas as an example

Primarily you need to supply the output schema after your custom pandas function returns

Data Preparation

```<code>df1 = sql.createDataFrame([
 ["Luc Krier"],
 ["Jeanny Thorn"],
 [ "Teddy E Beecher"],
 ["Philippe Schauss"],
 ["Meindert I Tholen"],
 ["John I Muller"]
]).toDF("name")

df2 = sql.createDataFrame([
 ["J. Thorn"],
 ["Ben Weller"],
 [ "L. Krier"],
 ["J.M. Thorn"],
 ["Liam Muller"],
 ["Meindert Tholen"]
]).toDF("name")

df1 = df1.withColumn('id',F.lit(1))
df2 = df2.withColumn('id',F.lit(1))

combined_df = df1.join(df2
                      ,df1['id'] == df2['id']
                      ).select(df1['name'],df2['name'].alias('name_proxy'))

combined_df.filter(F.col('name') == 'Luc Krier').show()

+---------+---------------+
|     name|     name_proxy|
+---------+---------------+
|Luc Krier|       J. Thorn|
|Luc Krier|     Ben Weller|
|Luc Krier|       L. Krier|
|Luc Krier|     J.M. Thorn|
|Luc Krier|    Liam Muller|
|Luc Krier|Meindert Tholen|
+---------+---------------+
</code>```

Pandas UDF

```<code>schema = StructType([
           StructField('name', StringType(), True),
           StructField('name_proxy', StringType(), True),
           StructField('match', BooleanType(), True)
 ])

def whos_who_match(inp_df,match_columns):

    inp_df['match'] = inp_df[match_columns].apply(lambda x : who.match(x[0],x[1]),axis=1)

    return inp_df

partial_func = partial(whos_who_match,match_columns=['name','name_proxy'])

combined_df = combined_df.groupby('name').applyInPandas(partial_func,schema)

combined_df.filter(F.col('match') == True).show()

+-----------------+---------------+-----+
|             name|     name_proxy|match|
+-----------------+---------------+-----+
|Meindert I Tholen|Meindert Tholen| true|
|     Jeanny Thorn|       J. Thorn| true|
|        Luc Krier|       L. Krier| true|
+-----------------+---------------+-----+
</code>```

Title: poor pyspark query performance

Body:
I'm trying to migrate from a single node pure python/pandas workflow to a parallel workflow using spark cluster because i'm running into performance and OOM issues as the dataset is getting larger and larger. As a PoC, i've been trying to convert one part of my code which I think is best case for spark because the entire thing is pandas aggregates and very little of python just for collecting the data and writing to a db at the end.

This is what the code currently does: aggregates values for each userid for each month, in pseudo code:

dates_to_process = [LIST OF DATES(FIRST OF MONTH. eg: 1/1/2010:00:00:00.0000) GOING BACK SEVERAL YEARS]
for uid, df in datafame.groupby('userid'):
      for start_date in dates_to_process:
          end_date = last_of_month(start_date) // this will be 31/1/2010:23:59:59.9999)
          current_month = df[df['date'] >= start_date & df['date'] <= end_date]
          // here run a bunch of queries like
          val1 = df[col1].sum()
          val2 = df[(col2) == "somestring"][col3].sum()
          val3 = df.groupby(col4).mean(col5)
          val4 = df[df[col6] <= end_date][col7].value_counts()
          // and so on. maybe 200 - 250 such calculations
          // collect the values and put it in new dataframe which gets written to db at the end

I tried doing it in pyspark, but it turned out I need to call count() and collect() way too often and probably more often than recommended. And it takes maybe 3 minutes per userid (about 1500 unique userids) in a 3 million row dataframe.

Is there a better way of doing this or is spark not the right tool for this kind of job? I tried running on a local cluster of 2 other machines and the performance didn't improve all that much.

Body:
Based on your code snippet , you should look at Pandas UDF and here, which would also allow you to reuse your existing native pandas code snippets as well.

Introducing a loop like that does not provide much gains in Spark , stick to native functions which are optimised

A typical example of Pandas UDF is as below -

Here I m trying to find out similar names utilising applyInPandas as an example

Primarily you need to supply the output schema after your custom pandas function returns

Data Preparation

df1 = sql.createDataFrame([
 ["Luc Krier"],
 ["Jeanny Thorn"],
 [ "Teddy E Beecher"],
 ["Philippe Schauss"],
 ["Meindert I Tholen"],
 ["John I Muller"]
]).toDF("name")

df2 = sql.createDataFrame([
 ["J. Thorn"],
 ["Ben Weller"],
 [ "L. Krier"],
 ["J.M. Thorn"],
 ["Liam Muller"],
 ["Meindert Tholen"]
]).toDF("name")

df1 = df1.withColumn('id',F.lit(1))
df2 = df2.withColumn('id',F.lit(1))

combined_df = df1.join(df2
                      ,df1['id'] == df2['id']
                      ).select(df1['name'],df2['name'].alias('name_proxy'))

combined_df.filter(F.col('name') == 'Luc Krier').show()

+---------+---------------+
|     name|     name_proxy|
+---------+---------------+
|Luc Krier|       J. Thorn|
|Luc Krier|     Ben Weller|
|Luc Krier|       L. Krier|
|Luc Krier|     J.M. Thorn|
|Luc Krier|    Liam Muller|
|Luc Krier|Meindert Tholen|
+---------+---------------+

Pandas UDF

schema = StructType([
           StructField('name', StringType(), True),
           StructField('name_proxy', StringType(), True),
           StructField('match', BooleanType(), True)
 ])

def whos_who_match(inp_df,match_columns):

    inp_df['match'] = inp_df[match_columns].apply(lambda x : who.match(x[0],x[1]),axis=1)

    return inp_df

partial_func = partial(whos_who_match,match_columns=['name','name_proxy'])

combined_df = combined_df.groupby('name').applyInPandas(partial_func,schema)

combined_df.filter(F.col('match') == True).show()

+-----------------+---------------+-----+
|             name|     name_proxy|match|
+-----------------+---------------+-----+
|Meindert I Tholen|Meindert Tholen| true|
|     Jeanny Thorn|       J. Thorn| true|
|        Luc Krier|       L. Krier| true|
+-----------------+---------------+-----+


问:
auto adjust text size to fit a button Android
Is there a way to auto adjust the text size of a button to be the biggest it can be while stayinh one line, and still fit in the button?</p>

答:
Have a look at Autosizing TextViews (provides support to API level 14).

For example

```<code><Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:text="Some text"
    app:autoSizeTextType="uniform" />
</code>```

The key property here is app:autoSizeTextType

Body:
Have a look at Autosizing TextViews (provides support to API level 14).

For example

<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:text="Some text"
    app:autoSizeTextType="uniform" />

The key property here is app:autoSizeTextType


问:
ER modelling tool for Snowflake
From snowflake documentation it seems that there is an ER application that will allow connecting to the dwh to create diagrams - https://www.snowflake.com/blog/support-multiple-data-modeling-approaches-with-snowflake/.

Does anyone know what tool is used in the article?
Can you recommend alternative ER tool for modelling purposes?

答:
Another tool with CI/CD tools I came accross:

https://sqldbm.com/Home/

Title: ER modelling tool for Snowflake


问:
Cant hit breakpoint in web api controller
When i try to debug this code :

```<code> // POST: api/Events
    [HttpPost]
    public async Task<IActionResult> PostEvent([FromBody] object savedEvent)
    {

        Event addedEvent = JsonConvert.DeserializeObject<Event>(savedEvent.ToString());

        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
</code>```

Cant hit  this line :

```<code>   Event addedEvent = JsonConvert.DeserializeObject<Event>(savedEvent.ToString());
</code>```

Debuger reacts like i hit continue but code past doesnt execute. Im really confused. Thanks for your help.

答:
Wow, I finally solved it. In my case it was incorrectly registered service in DI, just for example:

```<code>services.AddScoped<AccountService>();  << 'Fixed my problem'
services.AddScoped<NI.JwtBearerAuth.IAccountService, AccountService>(); << 'Confused me, thought I had already registered it, but as you see, this is other implementation'
</code>```

After that I was able to hit breakpoint in controller. So, my controller wasn't registered because of this service.

Body:
When i try to debug this code :

 // POST: api/Events
    [HttpPost]
    public async Task<IActionResult> PostEvent([FromBody] object savedEvent)
    {

        Event addedEvent = JsonConvert.DeserializeObject<Event>(savedEvent.ToString());

        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

Cant hit  this line :

   Event addedEvent = JsonConvert.DeserializeObject<Event>(savedEvent.ToString());

Debuger reacts like i hit continue but code past doesnt execute. Im really confused. Thanks for your help.

Body:
Wow, I finally solved it. In my case it was incorrectly registered service in DI, just for example:

services.AddScoped<AccountService>();  << 'Fixed my problem'
services.AddScoped<NI.JwtBearerAuth.IAccountService, AccountService>(); << 'Confused me, thought I had already registered it, but as you see, this is other implementation'

After that I was able to hit breakpoint in controller. So, my controller wasn't registered because of this service.


问:
Why my "new Question" button is not changing the question when i click the button?
So the idea is when you click the button, you should see new question. But its not working and i don't know why :( Help!</p>
```<code>  const Trivia = () => {
      const [question, setQuestion] = React.useState();

      React.useEffect(() => {

             fetch('https://opentdb.com/api.php?amount=1')
            .then(response => response.json())
            .then(data => {
             setQuestion(data.results[0].question);

             });
      }, [] )

      return(
      <div>
            <p>{question}</p>

            <button onClick={() => }> New Question</button>
      </div>

      );
  };

  ReactDOM.render(<Trivia />, document.getElementById("root"));
</script>
</code>```

答:
So if you want to refetch a new question from your API when you click the button, I suggest you to export your API call into a function like that :

```<code>    const fetchQuestion = () => {
    fetch("https://opentdb.com/api.php?amount=1")
      .then((response) => response.json())
      .then((data) => {
        setQuestion(data.results[0].question);
      });
  };
</code>```

Then you can call it whenever you want, and your code should be like this :

```<code>const Trivia = () => {
  const [question, setQuestion] = React.useState();

  const fetchQuestion = () => {
    fetch("https://opentdb.com/api.php?amount=1")
      .then((response) => response.json())
      .then((data) => {
        setQuestion(data.results[0].question);
      });
  };

  React.useEffect(() => {
    fetchQuestion();
  }, []);

  return (
    <div>
      <p>{question}</p>

      <button onClick={fetchQuestion}>New Question</button>
    </div>
  );
};

ReactDOM.render(<Trivia />, document.getElementById("root"));
</script>
</code>```

Body:
So the idea is when you click the button, you should see new question. But its not working and i don't know why :( Help!

  const Trivia = () => {
      const [question, setQuestion] = React.useState();

      React.useEffect(() => {

             fetch('https://opentdb.com/api.php?amount=1')
            .then(response => response.json())
            .then(data => {
             setQuestion(data.results[0].question);

             });
      }, [] )

      return(

{question}

            <button onClick={() => }> New Question</button>

      );
  };

  ReactDOM.render(<Trivia />, document.getElementById("root"));
</script>

Body:
So if you want to refetch a new question from your API when you click the button, I suggest you to export your API call into a function like that :

    const fetchQuestion = () => {
    fetch("https://opentdb.com/api.php?amount=1")
      .then((response) => response.json())
      .then((data) => {
        setQuestion(data.results[0].question);
      });
  };

Then you can call it whenever you want, and your code should be like this :

const Trivia = () => {
  const [question, setQuestion] = React.useState();

  const fetchQuestion = () => {
    fetch("https://opentdb.com/api.php?amount=1")
      .then((response) => response.json())
      .then((data) => {
        setQuestion(data.results[0].question);
      });
  };

  React.useEffect(() => {
    fetchQuestion();
  }, []);

  return (
    <div>
      <p>{question}</p>

      <button onClick={fetchQuestion}>New Question</button>
    </div>
  );
};

ReactDOM.render(<Trivia />, document.getElementById("root"));
</script>


问:
Comparing two numpy arrays with different lengths line-wise
I am trying to compare all to all elements of two different lenght arrays. Lets say I have an array:

```<code>A = np.array([[15,25,22],[200,200,20]])
</code>```

And second array is an array I want to compare with:

```<code>B = np.array([[150., 350.],
 [250., 450.],
 [150., 350.],
 [400., 600.],
 [400., 600.],
 [650., 850.],
 [550., 750.],
 [650., 850.]])
</code>```

What I need is to compare all the elements on index 0 of all arrays in A (A[:, 0]) with all elements on index 0 in all arrays in array B (B[:, 0]).

If A is just a simple array such as A=[25,40,25], then it is simply done as:

```<code>smaller = np.array(A[0] > B[:, 0]).astype('int')
</code>```

I thought I can transform it to 2d comparison such that

```<code>smaller = np.array(A[:, 0] > B[:, 0]).astype('int')
</code>```

This is not working, error is clear, ValueError: operands could not be broadcast together with shapes (2,) (8,). I understand that this way I cannot compare it but I was not able to find the way how to do so.

My desired output would look like this:

```<code>[[False, False, False, False, False, False, False, False],
 [True, False, True, False, False, False, False, False]]
</code>```

答:
This is what I can have</p>
```<code>np.array([A[i,0] > B[:, 0] for i in range(A.shape[0])])
</code>```

Body:
I am trying to compare all to all elements of two different lenght arrays. Lets say I have an array:

A = np.array([[15,25,22],[200,200,20]])

And second array is an array I want to compare with:

B = np.array([[150., 350.],
 [250., 450.],
 [150., 350.],
 [400., 600.],
 [400., 600.],
 [650., 850.],
 [550., 750.],
 [650., 850.]])

What I need is to compare all the elements on index 0 of all arrays in A (A[:, 0]) with all elements on index 0 in all arrays in array B (B[:, 0]).

If A is just a simple array such as A=[25,40,25], then it is simply done as:

smaller = np.array(A[0] > B[:, 0]).astype('int')

I thought I can transform it to 2d comparison such that

smaller = np.array(A[:, 0] > B[:, 0]).astype('int')

This is not working, error is clear, ValueError: operands could not be broadcast together with shapes (2,) (8,). I understand that this way I cannot compare it but I was not able to find the way how to do so.

My desired output would look like this:

[[False, False, False, False, False, False, False, False],
 [True, False, True, False, False, False, False, False]]

Body:
This is what I can have

np.array([A[i,0] > B[:, 0] for i in range(A.shape[0])])


问:
Different ways to create an empty list
I want to create an empty list and append some values inside this list. So far I know that if I want to create and empty list I can do it either like this:

```<code>list1 = []
</code>```

or like this:

```<code>list1 = list()
</code>```

(My apologies if there is another way that currently I don't know)

My question at this point is if there is a difference between those two ways to create a list; in terms of efficiency for example.

Thank you in advance for your help.

答:
I Don't Think it makes any difference, I can not see why you need to declare a new list using the constructor.

list1 = [] and list1 = list() are the same as I know.

If you have literal values you should use the literal notation list1= ['a', 'b', 'c']
I don't even think it's possible to create a list with some values using the constructor.

The constructor main usage is when we want to convert a Map, Set or 'tuple' into a list

For example:

```<code>my_tuple = ('a', 'b', 'c')
my_list = list(my_tuple)
</code>```

Title: Different ways to create an empty list

Body:
I want to create an empty list and append some values inside this list. So far I know that if I want to create and empty list I can do it either like this:

list1 = []

or like this:

list1 = list()

(My apologies if there is another way that currently I don't know)

My question at this point is if there is a difference between those two ways to create a list; in terms of efficiency for example.

Thank you in advance for your help.

Body:
I Don't Think it makes any difference, I can not see why you need to declare a new list using the constructor.

list1 = [] and list1 = list() are the same as I know.

If you have literal values you should use the literal notation list1= ['a', 'b', 'c']
I don't even think it's possible to create a list with some values using the constructor.

The constructor main usage is when we want to convert a Map, Set or 'tuple' into a list

For example:

my_tuple = ('a', 'b', 'c')
my_list = list(my_tuple)


问:
dump_coverage.cc:48] Check failed: (java_agent_class) != nullptr
I am trying to calculate code coverage of instrumented class files on an Android virtual device using libdumpcoverage.so. A 64-bit file has been copied to /system/lib64/ & jacocoagent.jar is available under /system/frameworks/.

In dump process according to the link, I am getting following error in adb logs

```<code>dump_coverage.cc:48] Check failed: (java_agent_class) != nullptr
</code>```

I tried to check this with JaCoCo team. they told me check with Android developers.

答:
I set following variables before AOSP build & i got coverage dump after executing steps mentioned in link.</p>
```<code> export EMMA_INSTRUMENT_FRAMEWORK=true
 export EMMA_INSTRUMENT=true
 export LOCAL_EMMA_INSTRUMENT=true
</code>```

Body:
I am trying to calculate code coverage of instrumented class files on an Android virtual device using libdumpcoverage.so. A 64-bit file has been copied to /system/lib64/ & jacocoagent.jar is available under /system/frameworks/.

In dump process according to the link, I am getting following error in adb logs

dump_coverage.cc:48] Check failed: (java_agent_class) != nullptr

I tried to check this with JaCoCo team. they told me check with Android developers.

Body:
I set following variables before AOSP build & i got coverage dump after executing steps mentioned in link.

 export EMMA_INSTRUMENT_FRAMEWORK=true
 export EMMA_INSTRUMENT=true
 export LOCAL_EMMA_INSTRUMENT=true


问:
What is the significance of the 'x-phone' styling rule for sencha touch?
Here is the css I am reading:

```<code> .card {
        font-size: 72px;
        padding: 80px 40px;
    }

    .x-phone .card {
        padding: 15px;
        font-size: 36px;
    }
</code>```

What is the significance of x-phone? I am guessing, and this is a pure guess, that the css is saying, for the case a mobile device is detected, overide the .card styling class rule with .x-phone .card styling rule?

Is that correct? I searched the sencha touch api and google with no answer.

Thanks

答:
If you look at body-tag's classes and change User Agent strings, you can see that it will change the class between x-desktop, x-phone and x-tablet.

So yes, it will override .card's styles when on phone.

Body:
Here is the css I am reading:

 .card {
        font-size: 72px;
        padding: 80px 40px;
    }

    .x-phone .card {
        padding: 15px;
        font-size: 36px;
    }

What is the significance of x-phone? I am guessing, and this is a pure guess, that the css is saying, for the case a mobile device is detected, overide the .card styling class rule with .x-phone .card styling rule?

Is that correct? I searched the sencha touch api and google with no answer.

Thanks


问:
React Native Community DateTimePicker value.getTime is undefined
Hey guys I have few questions regarding the community version of the RN DateTimePicker (https://github.com/react-native-datetimepicker/datetimepicker#value-required)

First of all my Code:

State:

```<code>activityDate: todaysDate, (just a JS new Date())
showDatePicker: false
</code>```

Toggle Function:

```<code>  showDatePickerHandler = () => {
    this.setState({
      showDatePicker: !this.state.showDatePicker
    })
  }
</code>```

DateTimePicker Code:

```<code>   <Button onPress={this.showDatePickerHandler} title="Open"/>
    <>
    { this.state.showDatePicker && (
    <DateTimePicker
      // style={{width: "60%"}}
      value={this.state.activityDate}
      placeholderText="Pick your Date"
      onChange={(event, date) => {
        this.resetSOFT()
        this.setState({
          // activityDate: date,
          activityDate: Moment(date).format("YYYY-MM-DD"),
          checked: false,
         }
        )
      }}
    />
    )}
    </>
</code>```

Here is what I am experiencing:

When I open the DatePicker and then chose a date and press Ok (or cancel) my App reloads with this error: TypeError: value.getTime is not a function. (In 'value.getTime()', 'value.getTime' is undefined) - value is set to new Date() so thats weird

is there a way to set a Format to the whole DateTimePicker Component? something like format = "YYYY-MM-DD" and then it should use this format for the date

I was using: https://github.com/xgfe/react-native-datepicker before which had some good formating functions and an easy way to handle dates - but since its buggy on IOS and has no maintainer I wanted to switch..

Edit:
On my first Press it looks good I am getting a Date but when I open it again it crashes the app and reloads it.. how can I safely close the Picker? is it enought to setState of showDatePicker to false in the onChange?

答:
You can only set a new Date() type as the value of DateTimePicker component.

You can show the date in required format in another component like below.

```<code>  <>
    {this.state.showDatePicker && (
      <DateTimePicker
        style={{height: 0}}
        value={this.state.activityDate}
        placeholderText="Pick your Date"
        onChange={(event, date) => {
          this.resetSOFT()
          this.setState({
            activityDate: date,
            checked: false,
            showDatePicker: false
          })
       }}
      />
    )}
    <TouchableOpacity style={{padding:20, width:'80%', alignItems:'center', justifyContent:'center'}} onPress={()=>showDatePickerHandler()}>
      <Text>{Moment(date).format("YYYY-MM-DD")}</Text>
    </TouchableOpacity>
  </>
</code>```

Body:
Hey guys I have few questions regarding the community version of the RN DateTimePicker (https://github.com/react-native-datetimepicker/datetimepicker#value-required)

First of all my Code:

State:

activityDate: todaysDate, (just a JS new Date())
showDatePicker: false

Toggle Function:

  showDatePickerHandler = () => {
    this.setState({
      showDatePicker: !this.state.showDatePicker
    })
  }

DateTimePicker Code:

   <Button onPress={this.showDatePickerHandler} title="Open"/>
    <>
    { this.state.showDatePicker && (
    <DateTimePicker
      // style={{width: "60%"}}
      value={this.state.activityDate}
      placeholderText="Pick your Date"
      onChange={(event, date) => {
        this.resetSOFT()
        this.setState({
          // activityDate: date,
          activityDate: Moment(date).format("YYYY-MM-DD"),
          checked: false,
         }
        )
      }}
    />
    )}
    </>

Here is what I am experiencing:

When I open the DatePicker and then chose a date and press Ok (or cancel) my App reloads with this error: TypeError: value.getTime is not a function. (In 'value.getTime()', 'value.getTime' is undefined) - value is set to new Date() so thats weird

is there a way to set a Format to the whole DateTimePicker Component? something like format = "YYYY-MM-DD" and then it should use this format for the date

I was using: https://github.com/xgfe/react-native-datepicker before which had some good formating functions and an easy way to handle dates - but since its buggy on IOS and has no maintainer I wanted to switch..

Edit:
On my first Press it looks good I am getting a Date but when I open it again it crashes the app and reloads it.. how can I safely close the Picker? is it enought to setState of showDatePicker to false in the onChange?

Body:
You can only set a new Date() type as the value of DateTimePicker component.

You can show the date in required format in another component like below.

  <>
    {this.state.showDatePicker && (
      <DateTimePicker
        style={{height: 0}}
        value={this.state.activityDate}
        placeholderText="Pick your Date"
        onChange={(event, date) => {
          this.resetSOFT()
          this.setState({
            activityDate: date,
            checked: false,
            showDatePicker: false
          })
       }}
      />
    )}
    <TouchableOpacity style={{padding:20, width:'80%', alignItems:'center', justifyContent:'center'}} onPress={()=>showDatePickerHandler()}>
      <Text>{Moment(date).format("YYYY-MM-DD")}</Text>
    </TouchableOpacity>
  </>


问:
loop through array of objects and get all object values as a single string
I have an array of object

```<code> const arr = [
  { id: 1, value: "Apple" },
  { id: 1, value: "Orange" },
  { id: 1, value: "Pine Apple" },
  { id: 1, value: "Banana" },
];
</code>```

I want to loop through this array and get all the fruit names as a single string every fruit will separated with comma. But don't know how to do that. Does anybody help me to do this?

答:
You can use map and join like this

const arr = [
  { id: 1, value: "Apple" },
  { id: 1, value: "Orange" },
  { id: 1, value: "Pine Apple" },
  { id: 1, value: "Banana" },
];
const result = arr.map(({ value }) => value).join(', ')
console.log(result)```

Body:
I have an array of object

 const arr = [
  { id: 1, value: "Apple" },
  { id: 1, value: "Orange" },
  { id: 1, value: "Pine Apple" },
  { id: 1, value: "Banana" },
];

I want to loop through this array and get all the fruit names as a single string every fruit will separated with comma. But don't know how to do that. Does anybody help me to do this?


问:
Router does not navigate to targeted component
I have a function that redirects a user to a page Orders if the user's state is complete, and to a HOME page if the user's state is not complete.

The Orders page has a GuardService that implements canActivate, and the HOME page does not have any guards.

I have some users with the R_ORDERS right and in a complete state who are not navigating at all. (ie they are neither routed to the Orders page nor the HOME page).

I can see that the HTTP requests retrieving the user's right is called but they are stuck in that page.

Is my issue related to this post ?
enter link description here

or to this article
enter link description here

Also, I have tried to add logs when the observable has completed but in that case, the log is never displayed in the console.

return this.getList().subscribe((e) => {
        const right = new List(e).FirstOrDefault(
          (d) => d.code == securizedPath.keyCode
        )?.type;
        if (!right) return resolve("OFF");
        return resolve(right);
      },
        (error) => {
          console.log("Right store threw an error");
          console.log(error);
        },
        () => {
          console.log("Right list completed")
        }
);
```
<p>thanks for your help</p>
<pre class="lang-js prettyprint-override"><code>async redirectTo() {
  this.loading = true;
  this.userState = await this.stateService.getToPromise(this.userId);

  if (this.userState.isComplete) {
     this.orderService.init();
     this.router.navigate([RouteNames.ORDERS]);
     this.loading = false;
     return;
  }

  this.router.navigate([RouteNames.HOME]);
  return;

}
</code>```

The RouteNames.ORDERS has the following guard:

@Injectable({
  providedIn: "root",
})
export class GuardService implements CanActivate {
  constructor(
    private router: Router,
    private rightService: UserRightService
  ) {}
  canActivate(
    route: import("@angular/router").ActivatedRouteSnapshot,
    state: import("@angular/router").RouterStateSnapshot
  ):
    | boolean
    | import("@angular/router").UrlTree
    | import("rxjs").Observable<boolean | import("@angular/router").UrlTree>
    | Promise<boolean | import("@angular/router").UrlTree> {
    return this.test(route);
  }
  async test(route: ActivatedRouteSnapshot) {
    const right = await this.rightService.isRouteAllowed(route.url[0].path);
    if (right == "OFF") {
      this.router.navigate([RouteNames.FEATURE_UNAUTHORIZED]);
      return false;
    } else if (right != "ON") {
      this.router.navigate([RouteNames.FEATURE_UNAUTHORIZED]);
      return false;
    }
    return true;
  }

}
```
<p>Code for the <code>UserRightService</code> is</p>
<pre class="lang-js prettyprint-override"><code> isRouteAllowed(route: string): Promise<Right> {

    const securizedPath = new List(this.securizedPaths).FirstOrDefault(
      (e) => e.name == route
    );
    return new Promise((resolve) => {
      return this.getList().subscribe((e) => {
        const right = new List(e).FirstOrDefault(
          (d) => d.code == securizedPath.keyCode
        )?.type;
        if (!right) return resolve("OFF");
        return resolve(right);
      });
    });
  }
</code>```

securizedPaths is defined as below
typescript[{ name: RouteNames.ORDERS, keyCode: "R_ORDERS" }, // other value ]

and getList is

 getList() {
    this.subjectList = new ReplaySubject<T[]>();
    this.load();
    return this.subjectList;
 }

protected load() {
      return this.getService()
        .getAll()
        .then((e) => {
          this.subjectList.next(e);
        })
        .catch((e) => {
          this.subjectList.next([]);
          this.subjectList = null;
        });
  }

// Code for this.getService().getAll()
  async getAll(id?: any, parameter?: any): Promise<Array<T>> {
    let urlParameters;
    ({ urlParameters, parameter } = this.createParameters(parameter, id));
    return this.http
      .get(this.url + (urlParameters ? "?" + urlParameters : ""))
      .toPromise<Array<T>>();
  }
```

答:
I am NOT* sure whether i understand your problem completely but based on reading i see something which i would like to propose you. I see some issue in GuardService

```<code>@Injectable({
    providedIn: "root",
})

export class GuardService implements CanActivate {
    constructor(
        private router: Router,
        private rightService: UserRightService
    ) { }

    canActivate(
        route: import("@angular/router").ActivatedRouteSnapshot,
        state: import("@angular/router").RouterStateSnapshot
    ): Promise<boolean> {

        let resolver: (value: boolean | PromiseLike<boolean>) => void;

        const promise = new Promise<boolean>((resolve) => {
            resolver = resolve;
        });
        this.test(route, resolver);
        return resolver;
    }

    async test(route: ActivatedRouteSnapshot, resolver: (value: boolean | PromiseLike<boolean>)) {
        const right = await this.rightService.isRouteAllowed(route.url[0].path);
        if (right == "OFF") {
            this.router.navigate([RouteNames.FEATURE_UNAUTHORIZED]);
            return resolver(false);
        } else if (right != "ON") {
            this.router.navigate([RouteNames.FEATURE_UNAUTHORIZED]);
            return resolver(false);
        }
        return resolver(true);
    }
}
</code>```

See code I have highlighted in bold.

I guess you must return a promise which will resolved in test method based on what value will be received in response.

My proposal is totally based some assumption which helped me to fix an issue in past where CanActivte method of the Gurad wanted to return a value asynchronously.

Body:
I have a function that redirects a user to a page Orders if the user's state is complete, and to a HOME page if the user's state is not complete.

The Orders page has a GuardService that implements canActivate, and the HOME page does not have any guards.

I have some users with the R_ORDERS right and in a complete state who are not navigating at all. (ie they are neither routed to the Orders page nor the HOME page).

I can see that the HTTP requests retrieving the user's right is called but they are stuck in that page.

Is my issue related to this post ?
enter link description here

or to this article
enter link description here

Also, I have tried to add logs when the observable has completed but in that case, the log is never displayed in the console.

return this.getList().subscribe((e) => {
        const right = new List(e).FirstOrDefault(
          (d) => d.code == securizedPath.keyCode
        )?.type;
        if (!right) return resolve("OFF");
        return resolve(right);
      },
        (error) => {
          console.log("Right store threw an error");
          console.log(error);
        },
        () => {
          console.log("Right list completed")
        }
);

thanks for your help

async redirectTo() {
  this.loading = true;
  this.userState = await this.stateService.getToPromise(this.userId);

  if (this.userState.isComplete) {
     this.orderService.init();
     this.router.navigate([RouteNames.ORDERS]);
     this.loading = false;
     return;
  }

  this.router.navigate([RouteNames.HOME]);
  return;

}

The RouteNames.ORDERS has the following guard:

@Injectable({
  providedIn: "root",
})
export class GuardService implements CanActivate {
  constructor(
    private router: Router,
    private rightService: UserRightService
  ) {}
  canActivate(
    route: import("@angular/router").ActivatedRouteSnapshot,
    state: import("@angular/router").RouterStateSnapshot
  ):
    | boolean
    | import("@angular/router").UrlTree
    | import("rxjs").Observable<boolean | import("@angular/router").UrlTree>
    | Promise<boolean | import("@angular/router").UrlTree> {
    return this.test(route);
  }
  async test(route: ActivatedRouteSnapshot) {
    const right = await this.rightService.isRouteAllowed(route.url[0].path);
    if (right == "OFF") {
      this.router.navigate([RouteNames.FEATURE_UNAUTHORIZED]);
      return false;
    } else if (right != "ON") {
      this.router.navigate([RouteNames.FEATURE_UNAUTHORIZED]);
      return false;
    }
    return true;
  }

}

Code for the UserRightService is

 isRouteAllowed(route: string): Promise<Right> {

    const securizedPath = new List(this.securizedPaths).FirstOrDefault(
      (e) => e.name == route
    );
    return new Promise((resolve) => {
      return this.getList().subscribe((e) => {
        const right = new List(e).FirstOrDefault(
          (d) => d.code == securizedPath.keyCode
        )?.type;
        if (!right) return resolve("OFF");
        return resolve(right);
      });
    });
  }

securizedPaths is defined as below
typescript[{ name: RouteNames.ORDERS, keyCode: "R_ORDERS" }, // other value ]

and getList is

 getList() {
    this.subjectList = new ReplaySubject<T[]>();
    this.load();
    return this.subjectList;
 }

protected load() {
      return this.getService()
        .getAll()
        .then((e) => {
          this.subjectList.next(e);
        })
        .catch((e) => {
          this.subjectList.next([]);
          this.subjectList = null;
        });
  }

// Code for this.getService().getAll()
  async getAll(id?: any, parameter?: any): Promise<Array<T>> {
    let urlParameters;
    ({ urlParameters, parameter } = this.createParameters(parameter, id));
    return this.http
      .get(this.url + (urlParameters ? "?" + urlParameters : ""))
      .toPromise<Array<T>>();
  }

Body:
I am NOT* sure whether i understand your problem completely but based on reading i see something which i would like to propose you. I see some issue in GuardService

@Injectable({
    providedIn: "root",
})

export class GuardService implements CanActivate {
    constructor(
        private router: Router,
        private rightService: UserRightService
    ) { }

    canActivate(
        route: import("@angular/router").ActivatedRouteSnapshot,
        state: import("@angular/router").RouterStateSnapshot
    ): Promise<boolean> {

        let resolver: (value: boolean | PromiseLike<boolean>) => void;

        const promise = new Promise<boolean>((resolve) => {
            resolver = resolve;
        });
        this.test(route, resolver);
        return resolver;
    }

    async test(route: ActivatedRouteSnapshot, resolver: (value: boolean | PromiseLike<boolean>)) {
        const right = await this.rightService.isRouteAllowed(route.url[0].path);
        if (right == "OFF") {
            this.router.navigate([RouteNames.FEATURE_UNAUTHORIZED]);
            return resolver(false);
        } else if (right != "ON") {
            this.router.navigate([RouteNames.FEATURE_UNAUTHORIZED]);
            return resolver(false);
        }
        return resolver(true);
    }
}

See code I have highlighted in bold.

I guess you must return a promise which will resolved in test method based on what value will be received in response.

My proposal is totally based some assumption which helped me to fix an issue in past where CanActivte method of the Gurad wanted to return a value asynchronously.


问:
JVector Map disable dragging/movement on touch devices
I used JVectorMap (http://jvectormap.com/maps/world/europe/) to create a map of europe. But I don't want that you can drag or move the map.

The map is based on jQuery. I get it for desktop computers but on touch devices I can drag and move the map. How can I disable this drag/move for this map?

Please, who can help me with this?

答:
This may be a late answer, but you can disable the zoom feature by setting the panOnDrag: false and zoomOnScroll: false.

I just haven't found how to disable the touch for mobile. I will update if found a way to do that.


问:
xcode 13.2 landscape design for storyboard in swift
can anyone help me how to design landscape UI design in iphone and ipad for xcode 13. previously xcode versions we have an option like Vary for Traits directly. in current version no option for vary for traits.</p>

答: You can add constraints variations here:


问:
How to get the procedure's call stack in code
I'm using Delphi 5. I want to get in code, all the calling procedure's call stack. For example:

procedure main (line 17) > function F1 (line 34) > function F2 (line 2)

MadExcept does exactly that, but only when it handles an exception. I want to get it when I'm asking. I need it for a log.

Is there a way to get that infomation, by MadExcept, or by another way?

答: What I remember from my old Delphi 5 days is that MemCheck also is able to read the call stack from within a procedure call. It may require to set very specific compiler and linker options in the project properties.</p>


问:
JMS Topic Creation in JBoss 5 AS
In Jboss 4, when I deployed an ear with an MDB for a topic that had not been specified in the deployment descriptors, the server would automatically create the topic (after posting a warning saying that topic didn't exist).

In Jboss 5, it doesn't seem to automatically create the topics anymore (errors out instead). Is there a configuration option somewhere that would allow automatic topic creation?

答:
From the JBoss community forums -- This JIRA was added in 5AS.

Unfortunately it looks like there is no way to implement createDestination globally in the standardjboss.xml descriptor -- You have to add a custom jboss.xml descriptor to the ear deploying the mdb.

```<code><jboss xsi:schemaLocation="http://www.jboss.com/xml/ns/javaee
 http://www.jboss.org/j2ee/schema/jboss_5_0.xsd" version="3.0">
    <enterprise-beans>
       <message-driven>
          <ejb-name>MessageDriven</ejb-name>
          <create-destination>true</create-destination>
       </message-driven>
    </enterprise-beans>
</jboss>
</code>```

OwnerDisplayName: Mark

ContentLicense: CC BY-SA 2.5

Title: JMS Topic Creation in JBoss 5 AS

Body:
From the JBoss community forums -- This JIRA was added in 5AS.

Unfortunately it looks like there is no way to implement createDestination globally in the standardjboss.xml descriptor -- You have to add a custom jboss.xml descriptor to the ear deploying the mdb.

<jboss xsi:schemaLocation="http://www.jboss.com/xml/ns/javaee
 http://www.jboss.org/j2ee/schema/jboss_5_0.xsd" version="3.0">
    <enterprise-beans>
       <message-driven>
          <ejb-name>MessageDriven</ejb-name>
          <create-destination>true</create-destination>
       </message-driven>
    </enterprise-beans>
</jboss>


问:
Where to implement business calculations on a query using Clean architecture
We are re-building our core application trying to use clean architecture and CQRS.
Projects have all been set up.

Currently this is all working

Domain layer currently holds complex models ie. models that simply map to the results from a stored proc.

```<code>namespace UHNM.myHotelCore.Domain.Entities.floor
{
public class FloorCx
{
    public int      FloorId      { get; set; }
    public int      x            { get; set; }
    public int      y            { get; set; }
    public string   FloorCode    { get; set; }
    public string   Floor        { get; set; }
}
</code>```

}

This is all working.  We now want to introduce calculations.

We use generally use automapper in our query handler in the application layer to map our complexmodel to our returned DTO.

```<code>var floors = _autoMapper.Map<List<FloorDTO>>(_floor.GetFloors(request.FloorId));
</code>```

Our return model from the API looks like this :-

```<code>namespace UHNM.myHotelCore.Application.CQRS.Queries.Floor.DTO
{
public class Floor
{
    public int      FloorId      { get; set; }
    public decimal  Average      { get; set; }
    public string   FloorCode    { get; set; }
    public string   Floor        { get; set; }
}
</code>```

}

Where average is calculated based on x and y from the complex model.
Using clean architecture, where is generally the best place for these calculations to go? and at what point are they called?

Would they sit within FloorCx?

```<code> public class FloorCx
{
    public int      FloorId      { get; set; }
    public int      x            { get; set; }
    public int      y            { get; set; }
    public string   FloorCode    { get; set; }
    public string   Floor        { get; set; }

Public decimalCalculateAverage(int x, int y)
{
//Calculation goes here
}
  }
</code>```

Create a separate class for the calculations?
Or even a separate project for business logic?

答:
From what I understand, your FloorCx is placed in Domain layer. The current shape of that class is a pure anemic model, which is an anti pattern in DDD world.

Not sure if your intention is to follow DDD principles as well, but if it is, then you could introduce repositories that return your FloorCx data models, which then you map to your real business objects. Such business objects should have business behavior, so having calculations inside is a way to go as long as the calculations can be self-contained, meaning they rely on object's internal properties, or accept primitive types (to reduce coupling between your domain model and other resources). When the calculations require more information from the outside world, you can create business services that do them.

Also, in DDD world, AutoMapper and similar solutions are often discouraged, also because your domain objects should not have public setters on their properties, but rather expose constructors or static factory methods that control what is initialized and how, ensuring object's internal consistency.

Having that said, I would create FloorCxDataModel that represents objects fetched from your repository (which abstracts away the stored procedure call and transformations), which then is mapped to a FloorCx business model that exposes methods for calculations and other business behavior. If those calculations depend on external information, for simple types that should work too, but for more complex input parameters I would create a FloorCxCalculationService that resides in Domain layer and does necessary calculations for you.

In the end, you map that business object to your FloorDto (which contains only data, no additional behavior) and return it from your API. In my view, that DTO should also have read-only public properties and have constructor/static factory method that does initialization.

Body:
We are re-building our core application trying to use clean architecture and CQRS.
Projects have all been set up.

Currently this is all working

Domain layer currently holds complex models ie. models that simply map to the results from a stored proc.

namespace UHNM.myHotelCore.Domain.Entities.floor
{
public class FloorCx
{
    public int      FloorId      { get; set; }
    public int      x            { get; set; }
    public int      y            { get; set; }
    public string   FloorCode    { get; set; }
    public string   Floor        { get; set; }
}

}

This is all working.  We now want to introduce calculations.

We use generally use automapper in our query handler in the application layer to map our complexmodel to our returned DTO.

var floors = _autoMapper.Map<List<FloorDTO>>(_floor.GetFloors(request.FloorId));

Our return model from the API looks like this :-

namespace UHNM.myHotelCore.Application.CQRS.Queries.Floor.DTO
{
public class Floor
{
    public int      FloorId      { get; set; }
    public decimal  Average      { get; set; }
    public string   FloorCode    { get; set; }
    public string   Floor        { get; set; }
}

}

Where average is calculated based on x and y from the complex model.
Using clean architecture, where is generally the best place for these calculations to go? and at what point are they called?

Would they sit within FloorCx?

 public class FloorCx
{
    public int      FloorId      { get; set; }
    public int      x            { get; set; }
    public int      y            { get; set; }
    public string   FloorCode    { get; set; }
    public string   Floor        { get; set; }

Public decimalCalculateAverage(int x, int y)
{
//Calculation goes here
}
  }

Create a separate class for the calculations?
Or even a separate project for business logic?


问:
How to skip a line every two lines starting by skipping the first line?
Here's my code : ls -lt | sed -n 'p;n'

That code makes me skip from a line to another when listing file names but doesn't start by skipping the first one, how to make that happen?

Here's an exemple without my code to skip to make it clear:

And here's an exemple of when I use the skip code:

答:
You can use sed's ~ operator: first~step</p>
```<code>$ seq 1 10 | sed -n '1~2p'
1
3
5
7
9
</code>```
```<code>$ seq 1 10 | sed -n '2~2p'
2
4
6
8
10
</code>```

Body:
You can use sed's ~ operator: first~step

$ seq 1 10 | sed -n '1~2p'
1
3
5
7
9

$ seq 1 10 | sed -n '2~2p'
2
4
6
8
10


答:
```<code>const fruitNames = arr.map(fruit => fruit.value).toString();
</code>```

Title: loop through array of objects and get all object values as a single string


问:
serialization of xml file in VB.net
I have Following data structure

```<code>Public Class MeasData
Public Number As Integer
Public Amp As Single
Public Fall As Single
Public Width As Single
Public setPRF As Integer
Public Volt As Single
Public setWidth As Single
</code>```

Serializer Class Code

```<code>Public Class TestDataSerializer
Public PulsTestData As New List(Of PulserMeasData)
Private PulsTestDataSorted As New SortedList(Of Integer, PulserMeasData)

Public Sub AddPulsTestData(ByVal ChaNum As Integer,
                           ByVal PAmp As Single,
                            ByVal PFallTime As Single,
                            ByVal PWidth As Single,
                            ByVal setPrf As Integer,
                            ByVal setVoltage As Single,
                            ByVal setPulswidth As Single)

    Dim Data As New PulserMeasData(ChaNum, PAmp, PFallTime, PWidth, setPrf, setVoltage, setPulswidth)

    If PulsTestDataSorted.ContainsKey(ChaNum) Then
        PulsTestDataSorted(ChaNum) = Data
    Else
        PulsTestDataSorted.Add(ChaNum, Data)
    End If
    PulsTestData = PulsTestDataSorted.Values.ToList ' XML Serializer can not handle SortedLists
    Dim serializer As New XMLSerializer(GetType(List(Of PulserMeasData)))
    Using file As System.IO.FileStream = System.IO.File.Open("obj.xml", IO.FileMode.OpenOrCreate, IO.FileAccess.Write)
        serializer.Serialize(file, PulsTestData)
    End Using
End Sub
</code>```

End Class

I Want to Generate XML from the above Data Strucuture with different values of set width prf and voltage

答:
Try following :

```<code>Imports System.Xml
Imports System.Xml.Serialization
Module Module1
    Const INPUT_FILENAME As String = "c:\temp\test.xml"
    Const OUTPUT_FILENAME As String = "c:\temp\test1.xml"
    Sub Main()
        'read data
        Dim reader As XmlReader = XmlReader.Create(INPUT_FILENAME)
        Dim serializer As XmlSerializer = New XmlSerializer(GetType(PulserMeasDataPA))
        Dim PulserMeasDataPA As PulserMeasDataPA = serializer.Deserialize(reader)

        Dim writer As XmlWriter = XmlWriter.Create(OUTPUT_FILENAME)

        serializer.Serialize(writer, PulserMeasDataPA)

        Dim PulsTestData As New List(Of PulserMeasData)
        Dim PulsTestDataSorted As New SortedList(Of Integer, PulserMeasData)

        Dim newPulseData As New PulserMeasDataPA()
        Dim newListData As New List(Of TestData)
        newPulseData.TestData = newListData

        For Each PD In PulsTestDataSorted.GroupBy(Function(x) x.Key)
            Dim newTestData As New TestData()
            newListData.Add(newTestData)
            newTestData.PortNumber = PD.Key

            newTestData.MeasureValues = New List(Of MeasureValues)

            For Each testData In PD
                Dim newValues As New MeasureValues
                newTestData.MeasureValues.Add(newValues)

                newValues.Amplitude = testData.Value.Amplitude

            Next
        Next

    End Sub

End Module

Public Class PulserMeasData
    Public ChannelNumber As Integer
    Public Amplitude As Single
    Public Fall As Single
    Public Width As Single
    Public setPRF As Integer
    Public setVoltage As Single
    Public setWidth As Single
End Class

Public Class PulserMeasDataPA
    <XmlElement()>
    Public TestData As List(Of TestData)
End Class
Public Class TestData
    Public PortNumber As Integer
    <XmlArray("Measurement")>
    <XmlArrayItem("MeasureValues")>
    Public MeasureValues As List(Of MeasureValues)
End Class
Public Class MeasureValues
    Public Amplitude As String
    Public Fall As String
    Public Width As String
    Public setWidth As Decimal
    Public PRF As Decimal
    Public Volt As Decimal
End Class
</code>```

Here is the XML file I used

```<code><?xml version="1.0" encoding="utf-8" ?>
<PulserMeasDataPA>
  <TestData>
    <PortNumber>1</PortNumber>
    <Measurement>
      <MeasureValues>
        <Amplitude></Amplitude>
        <Fall></Fall>
        <Width></Width>
        <setWidth>
          40</setWidth>
          <PRF>
            1000</PRF>
            <Volt>
              100</Volt>
            </MeasureValues>
      <MeasureValues>
        <Amplitude></Amplitude>
        <Fall></Fall>
        <Width></Width>
        <setWidth>
          100</setWidth>
          <PRF>
            1000</PRF>
            <Volt>
              100</Volt>
            </MeasureValues>
      <MeasureValues>
        <Amplitude></Amplitude>
        <Fall></Fall>
        <Width></Width>
        <setWidth>
          40</setWidth>
          <PRF>
            5000</PRF>
            <Volt>
              50</Volt>
            </MeasureValues>
      <MeasureValues>
        <Amplitude></Amplitude>
        <Fall></Fall>
        <Width></Width>
        <setWidth>
          100</setWidth>
          <PRF>
            5000</PRF>
            <Volt>
              50</Volt>
            </MeasureValues>
    </Measurement>
  </TestData>
  <TestData>
    <PortNumber>2</PortNumber>
    <Measurement>
      <MeasureValues>
        <Amplitude></Amplitude>
        <Fall></Fall>
        <Width></Width>
        <setWidth>
          40</setWidth>
          <PRF>
            1000</PRF>
            <Volt>
              100</Volt>
            </MeasureValues>
      <MeasureValues>
        <Amplitude></Amplitude>
        <Fall></Fall>
        <Width></Width>
        <setWidth>
          100</setWidth>
          <PRF>
            1000</PRF>
            <Volt>
              100</Volt>
            </MeasureValues>
      <MeasureValues>
        <Amplitude></Amplitude>
        <Fall></Fall>
        <Width></Width>
        <setWidth>
          40</setWidth>
          <PRF>
            5000</PRF>
            <Volt>
              50</Volt>
            </MeasureValues>
      <MeasureValues>
        <Amplitude></Amplitude>
        <Fall></Fall>
        <Width></Width>
        <setWidth>
          100</setWidth>
          <PRF>
            5000</PRF>
            <Volt>
              50</Volt>
            </MeasureValues>
    </Measurement>
  </TestData>
</PulserMeasDataPA>
</code>```

Title: serialization of xml file in VB.net

Body:
I have Following data structure

Public Class MeasData
Public Number As Integer
Public Amp As Single
Public Fall As Single
Public Width As Single
Public setPRF As Integer
Public Volt As Single
Public setWidth As Single

Serializer Class Code

Public Class TestDataSerializer
Public PulsTestData As New List(Of PulserMeasData)
Private PulsTestDataSorted As New SortedList(Of Integer, PulserMeasData)

Public Sub AddPulsTestData(ByVal ChaNum As Integer,
                           ByVal PAmp As Single,
                            ByVal PFallTime As Single,
                            ByVal PWidth As Single,
                            ByVal setPrf As Integer,
                            ByVal setVoltage As Single,
                            ByVal setPulswidth As Single)

    Dim Data As New PulserMeasData(ChaNum, PAmp, PFallTime, PWidth, setPrf, setVoltage, setPulswidth)

    If PulsTestDataSorted.ContainsKey(ChaNum) Then
        PulsTestDataSorted(ChaNum) = Data
    Else
        PulsTestDataSorted.Add(ChaNum, Data)
    End If
    PulsTestData = PulsTestDataSorted.Values.ToList ' XML Serializer can not handle SortedLists
    Dim serializer As New XMLSerializer(GetType(List(Of PulserMeasData)))
    Using file As System.IO.FileStream = System.IO.File.Open("obj.xml", IO.FileMode.OpenOrCreate, IO.FileAccess.Write)
        serializer.Serialize(file, PulsTestData)
    End Using
End Sub

End Class

I Want to Generate XML from the above Data Strucuture with different values of set width prf and voltage

Body:
Try following :

Imports System.Xml
Imports System.Xml.Serialization
Module Module1
    Const INPUT_FILENAME As String = "c:\temp\test.xml"
    Const OUTPUT_FILENAME As String = "c:\temp\test1.xml"
    Sub Main()
        'read data
        Dim reader As XmlReader = XmlReader.Create(INPUT_FILENAME)
        Dim serializer As XmlSerializer = New XmlSerializer(GetType(PulserMeasDataPA))
        Dim PulserMeasDataPA As PulserMeasDataPA = serializer.Deserialize(reader)

        Dim writer As XmlWriter = XmlWriter.Create(OUTPUT_FILENAME)

        serializer.Serialize(writer, PulserMeasDataPA)

        Dim PulsTestData As New List(Of PulserMeasData)
        Dim PulsTestDataSorted As New SortedList(Of Integer, PulserMeasData)

        Dim newPulseData As New PulserMeasDataPA()
        Dim newListData As New List(Of TestData)
        newPulseData.TestData = newListData

        For Each PD In PulsTestDataSorted.GroupBy(Function(x) x.Key)
            Dim newTestData As New TestData()
            newListData.Add(newTestData)
            newTestData.PortNumber = PD.Key

            newTestData.MeasureValues = New List(Of MeasureValues)

            For Each testData In PD
                Dim newValues As New MeasureValues
                newTestData.MeasureValues.Add(newValues)

                newValues.Amplitude = testData.Value.Amplitude

            Next
        Next

    End Sub

End Module

Public Class PulserMeasData
    Public ChannelNumber As Integer
    Public Amplitude As Single
    Public Fall As Single
    Public Width As Single
    Public setPRF As Integer
    Public setVoltage As Single
    Public setWidth As Single
End Class

Public Class PulserMeasDataPA
    <XmlElement()>
    Public TestData As List(Of TestData)
End Class
Public Class TestData
    Public PortNumber As Integer
    <XmlArray("Measurement")>
    <XmlArrayItem("MeasureValues")>
    Public MeasureValues As List(Of MeasureValues)
End Class
Public Class MeasureValues
    Public Amplitude As String
    Public Fall As String
    Public Width As String
    Public setWidth As Decimal
    Public PRF As Decimal
    Public Volt As Decimal
End Class

Here is the XML file I used

<?xml version="1.0" encoding="utf-8" ?>
<PulserMeasDataPA>
  <TestData>
    <PortNumber>1</PortNumber>
    <Measurement>
      <MeasureValues>
        <Amplitude></Amplitude>
        <Fall></Fall>
        <Width></Width>
        <setWidth>
          40</setWidth>
          <PRF>
            1000</PRF>
            <Volt>
              100</Volt>
            </MeasureValues>
      <MeasureValues>
        <Amplitude></Amplitude>
        <Fall></Fall>
        <Width></Width>
        <setWidth>
          100</setWidth>
          <PRF>
            1000</PRF>
            <Volt>
              100</Volt>
            </MeasureValues>
      <MeasureValues>
        <Amplitude></Amplitude>
        <Fall></Fall>
        <Width></Width>
        <setWidth>
          40</setWidth>
          <PRF>
            5000</PRF>
            <Volt>
              50</Volt>
            </MeasureValues>
      <MeasureValues>
        <Amplitude></Amplitude>
        <Fall></Fall>
        <Width></Width>
        <setWidth>
          100</setWidth>
          <PRF>
            5000</PRF>
            <Volt>
              50</Volt>
            </MeasureValues>
    </Measurement>
  </TestData>
  <TestData>
    <PortNumber>2</PortNumber>
    <Measurement>
      <MeasureValues>
        <Amplitude></Amplitude>
        <Fall></Fall>
        <Width></Width>
        <setWidth>
          40</setWidth>
          <PRF>
            1000</PRF>
            <Volt>
              100</Volt>
            </MeasureValues>
      <MeasureValues>
        <Amplitude></Amplitude>
        <Fall></Fall>
        <Width></Width>
        <setWidth>
          100</setWidth>
          <PRF>
            1000</PRF>
            <Volt>
              100</Volt>
            </MeasureValues>
      <MeasureValues>
        <Amplitude></Amplitude>
        <Fall></Fall>
        <Width></Width>
        <setWidth>
          40</setWidth>
          <PRF>
            5000</PRF>
            <Volt>
              50</Volt>
            </MeasureValues>
      <MeasureValues>
        <Amplitude></Amplitude>
        <Fall></Fall>
        <Width></Width>
        <setWidth>
          100</setWidth>
          <PRF>
            5000</PRF>
            <Volt>
              50</Volt>
            </MeasureValues>
    </Measurement>
  </TestData>
</PulserMeasDataPA>