问:
How can I search through an Excel sheet in a C# GUI?
I have this code

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

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

        private void cboSheet_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataTable dt = tableCollection[cboSheet.SelectedItem.ToString()];
            dataGridView1.DataSource = dt;
        }

        DataTableCollection tableCollection;

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            using(OpenFileDialog openFileDialog=new OpenFileDialog() { Filter="Excel|*.xls|Excel|*.xlsx" })
            {
                if(openFileDialog.ShowDialog()==DialogResult.OK)
                {
                    txtFilename.Text = openFileDialog.FileName;
                    using(var stream=File.Open(openFileDialog.FileName, FileMode.Open, FileAccess.Read))
                    {
                        using (IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream))
                        {
                            DataSet result = reader.AsDataSet(new ExcelDataSetConfiguration()
                            {
                                ConfigureDataTable=(_)=>new ExcelDataTableConfiguration() { UseHeaderRow=true }
                            });
                            tableCollection = result.Tables;
                            cboSheet.Items.Clear();
                            foreach (DataTable table in tableCollection)
                                cboSheet.Items.Add(table.TableName);
                        }
                    }
                }
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
</code>```

The code makes a GUI in .NET framework and it lets you upload an .xls or .xlsx, the Excel file will be shown as a DataGrid view. I implemented a new textbox ( the textBox1_TextChanged(object sender, EventArgs e) method), and based on the user's input, I want to it to display only the rows that correspond with the input. How am I supposed to do that? Thanks in advance!

答:
You have 3 options for working with office formats:

if you only need to support the new formats (.xslx) you can use the OpenXML SDK, any of the wrappers people wrote for it. Or even the ZipArchive and XMLReader classes. It is well known and easily processed

If you need to support the old format as well (.xls) you have to use the (t)rusty Office COM interop. That one has the usualy issues of COM interop, plus some unique problems. Like requiring a Interactive Session due to poor design choices.

For any given problem, any given file format, any given GUI technology there might be another way. But those are far and few in between

My standing advice is to use the OpenXML way and learn to live without the old formats altogether. They are way more trouble to support then it is worth.

Body:
I have this code

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

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

        private void cboSheet_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataTable dt = tableCollection[cboSheet.SelectedItem.ToString()];
            dataGridView1.DataSource = dt;
        }

        DataTableCollection tableCollection;

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            using(OpenFileDialog openFileDialog=new OpenFileDialog() { Filter="Excel|*.xls|Excel|*.xlsx" })
            {
                if(openFileDialog.ShowDialog()==DialogResult.OK)
                {
                    txtFilename.Text = openFileDialog.FileName;
                    using(var stream=File.Open(openFileDialog.FileName, FileMode.Open, FileAccess.Read))
                    {
                        using (IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream))
                        {
                            DataSet result = reader.AsDataSet(new ExcelDataSetConfiguration()
                            {
                                ConfigureDataTable=(_)=>new ExcelDataTableConfiguration() { UseHeaderRow=true }
                            });
                            tableCollection = result.Tables;
                            cboSheet.Items.Clear();
                            foreach (DataTable table in tableCollection)
                                cboSheet.Items.Add(table.TableName);
                        }
                    }
                }
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}

The code makes a GUI in .NET framework and it lets you upload an .xls or .xlsx, the Excel file will be shown as a DataGrid view. I implemented a new textbox ( the textBox1_TextChanged(object sender, EventArgs e) method), and based on the user's input, I want to it to display only the rows that correspond with the input. How am I supposed to do that? Thanks in advance!


来源: stackexchange

问:
How to work around maximum execution time when uploading to S3 Bucket?
I am using the S3-for-Google-Apps-Script library to export full attachments from Gmail to an S3 bucket. I changed the S3 code to upload the actual content of the attachment rather than an encoded string, as detailed in this post.

However, when attempting to upload an attachment approximately > 5 MB, apps script throws the following error: "Maximum Execution Time Exceeded". I used timestamps to measure the difference in time to ensure that the time issue occurred in the s3.putObject(bucket,objectKey,file) function.

It might be also helpful to note that for a file barely over the limit, it still gets uploaded to my s3 bucket, but apps script returns that the execution time has been exceeded (30 seconds) to the user, disrupting user flow.

Reproducible Example

This is basically a simple button that scrapes a current email for all attachments, if they are pdf's then it calls the export function. and it exports those attachments to our s3 instance. the problem is that when the file > 5mb, it throws the error:

"exportHandler exceeded execution time"

If you're trying to reproduce this be aware that you need to copy an instance of s3 for gas and initialize that as a separate library in apps script with the changes made here.

In order to link the libraries, go to file>libraries, and add the respective library id, version, and development mode in the google apps script console. You'll also need to save your AWS access key and secret key in your property service cache, as detailed in the library documentation.

An initial button that triggers an export of a single attachment on the current Gmail thread:

```<code>export default function testButton() {
  const Card = CardService.newCardBuilder();
  const exportButtonSection = CardService.newCardSection();
  const exportWidget = CardService.newTextButton()
    .setText('Export File')
    .setOnClickAction(CardService.newAction().setFunctionName('exportHandler'));
  exportButtonSection.addWidget(exportWidget);
  Card.addSection(exportButtonSection);
  return Card.build();
}
</code>```

Export an attachment to a specified s3 bucket. Note that S3Modified is an instance of the s3 for google apps script that is modified in accordance to the post outlined above, it's a separate Apps Script file, s3.putObject is where it takes a long time to process an attachment (this is where the error occurs I think).

credentials initialize your s3 awsAccessKey and awsBucket, and can be stored in PropertiesService.

```<code>function exportAttachment(attachment) {
  const fileName = attachment.getName();
  const timestamp = Date.now();
  const credentials = PropertiesService.getScriptProperties().getProperties();
  const s3 = S3Modified.getInstance(credentials.awsAccessKeyId, credentials.awsSecretAccessKey);
  s3.putObject(credentials.awsBucket, fileName, attachment, { logRequests: true });
  const timestamp2 = Date.now();
  Logger.log('difference: ', timestamp2 - timestamp);
}
</code>```

This gets all the attachments that are PDFs in the current email message, this function is pretty much the same as the one on the apps script site for handling Gmail attachments, this specifically looks for pdf's though (not a requirement for the code):

```<code>function getAttachments(event) {
  const gmailAccessToken = event.gmail.accessToken;
  const messageIdVal = event.gmail.messageId;

  GmailApp.setCurrentMessageAccessToken(gmailAccessToken);
  const mailMessage = GmailApp.getMessageById(messageIdVal);

  const thread = mailMessage.getThread();
  const messages = thread.getMessages();
  const filteredAttachments = [];
  for (let i = 0; i < messages.length; i += 1) {
    const allAttachments = messages[i].getAttachments();
    for (let j = 0; j < allAttachments.length; j += 1) {
      if (allAttachments[j].getContentType() === 'application/pdf') {
        filteredAttachments.push(allAttachments[j]);
      }
    }
  }
  return filteredAttachments;
}

</code>```

the global handler that gets attachments and exports them to the s3 bucket when the button is clicked:

```<code>function exportHandler(event) {
  const currAttachment = getAttachments(event).flat()[0];
  exportAttachment(currAttachment);
}
global.export = exportHandler;
</code>```

To be absolutely clear, the bulk of the time is being processed in the second code sample (exportAttachment), since that is where the object is being put into the s3 application.

The timestamps help log how much time that function takes, test it with a 300kb file, you'll get 2 seconds, 4mb 20 seconds, >5mb approx 30 seconds. This part contributes the most to the max execution time.

So this is what leads me to my question, why do I get the maximum execution time exceeded error and how can I fix it? Here are my two thoughts on potential solutions:

Why does the execution limit occur? The quotas say that the runtime limit for a custom function is 30 seconds, and the runtime limit for the script is 6 minutes.

After some research, I only found custom function mentions in the context of AddOns in Google Sheets, but the function where I'm getting the error is a global function (so that it can be recognized by a callback) in my script. Is there a way to change it to not be recognized as a custom function so that I'm not limited to the 30-second execution limit?

Now, how can I work around this execution limit? Is this an issue with the recommendation to modify the S3 library in this post? Essentially, the modification suggests that we export the actual bytes of the attachment rather than the encoded string.

This definitely increases the load that Apps Script has to handle which is why it increases the execution time required. How can I work around this issue? Is there a way to change the S3 library to improve processing speed?

答:
Regarding the first question

From https://developers.google.com/gsuite/add-ons/concepts/actions#callback_functions

Warning: The Apps Script Card service limits callback functions to a maximum of 30 seconds of execution time. If the execution takes longer than that, your add-on UI may not update its card display properly in response to the Action.

Regarding the second question

On the answer to Google Apps Script Async function execution on Server side it's suggested a "hack": Use an "open link" action to call something that can run asynchronously the task that will requiere a long time to run.

Related

How to use HtmlService in Gmail add-on using App Script

Handling Gmail Addon Timeouts

Can't serve HTML on the Google Apps Script callback page in a GMail add-on

Answer to rev 1.

Regarding the first question

In Google Apps Script, a custom function is a function to be used in a Google Sheets formula. There is no way not extend this limit. Reference https://developers.google.com/app-script/guides/sheets/functions

onOpen and onEdit simple triggers has also a 30 seconds execution time limit. Reference https://developers.google.com/apps-script/guides/triggers

Functions being executed from the Google Apps Script editor, a custom menu, an image that has assigned the function, installable triggers, client side code, Google Apps Script API has an execution time limit of 6 minutes for regular Google accounts (like those that have a @gmail.com email address) by the other hand G Suite accounts have a 30 minutes limit.

ContentLicense: CC BY-SA 4.0

Body:
I am using the S3-for-Google-Apps-Script library to export full attachments from Gmail to an S3 bucket. I changed the S3 code to upload the actual content of the attachment rather than an encoded string, as detailed in this post.

However, when attempting to upload an attachment approximately > 5 MB, apps script throws the following error: "Maximum Execution Time Exceeded". I used timestamps to measure the difference in time to ensure that the time issue occurred in the s3.putObject(bucket,objectKey,file) function.

It might be also helpful to note that for a file barely over the limit, it still gets uploaded to my s3 bucket, but apps script returns that the execution time has been exceeded (30 seconds) to the user, disrupting user flow.

Reproducible Example

This is basically a simple button that scrapes a current email for all attachments, if they are pdf's then it calls the export function. and it exports those attachments to our s3 instance. the problem is that when the file > 5mb, it throws the error:

"exportHandler exceeded execution time"

If you're trying to reproduce this be aware that you need to copy an instance of s3 for gas and initialize that as a separate library in apps script with the changes made here.

In order to link the libraries, go to file>libraries, and add the respective library id, version, and development mode in the google apps script console. You'll also need to save your AWS access key and secret key in your property service cache, as detailed in the library documentation.

An initial button that triggers an export of a single attachment on the current Gmail thread:

export default function testButton() {
  const Card = CardService.newCardBuilder();
  const exportButtonSection = CardService.newCardSection();
  const exportWidget = CardService.newTextButton()
    .setText('Export File')
    .setOnClickAction(CardService.newAction().setFunctionName('exportHandler'));
  exportButtonSection.addWidget(exportWidget);
  Card.addSection(exportButtonSection);
  return Card.build();
}

Export an attachment to a specified s3 bucket. Note that S3Modified is an instance of the s3 for google apps script that is modified in accordance to the post outlined above, it's a separate Apps Script file, s3.putObject is where it takes a long time to process an attachment (this is where the error occurs I think).

credentials initialize your s3 awsAccessKey and awsBucket, and can be stored in PropertiesService.

function exportAttachment(attachment) {
  const fileName = attachment.getName();
  const timestamp = Date.now();
  const credentials = PropertiesService.getScriptProperties().getProperties();
  const s3 = S3Modified.getInstance(credentials.awsAccessKeyId, credentials.awsSecretAccessKey);
  s3.putObject(credentials.awsBucket, fileName, attachment, { logRequests: true });
  const timestamp2 = Date.now();
  Logger.log('difference: ', timestamp2 - timestamp);
}

This gets all the attachments that are PDFs in the current email message, this function is pretty much the same as the one on the apps script site for handling Gmail attachments, this specifically looks for pdf's though (not a requirement for the code):

function getAttachments(event) {
  const gmailAccessToken = event.gmail.accessToken;
  const messageIdVal = event.gmail.messageId;

  GmailApp.setCurrentMessageAccessToken(gmailAccessToken);
  const mailMessage = GmailApp.getMessageById(messageIdVal);

  const thread = mailMessage.getThread();
  const messages = thread.getMessages();
  const filteredAttachments = [];
  for (let i = 0; i < messages.length; i += 1) {
    const allAttachments = messages[i].getAttachments();
    for (let j = 0; j < allAttachments.length; j += 1) {
      if (allAttachments[j].getContentType() === 'application/pdf') {
        filteredAttachments.push(allAttachments[j]);
      }
    }
  }
  return filteredAttachments;
}

the global handler that gets attachments and exports them to the s3 bucket when the button is clicked:

function exportHandler(event) {
  const currAttachment = getAttachments(event).flat()[0];
  exportAttachment(currAttachment);
}
global.export = exportHandler;

To be absolutely clear, the bulk of the time is being processed in the second code sample (exportAttachment), since that is where the object is being put into the s3 application.

The timestamps help log how much time that function takes, test it with a 300kb file, you'll get 2 seconds, 4mb 20 seconds, >5mb approx 30 seconds. This part contributes the most to the max execution time.

So this is what leads me to my question, why do I get the maximum execution time exceeded error and how can I fix it? Here are my two thoughts on potential solutions:

Why does the execution limit occur? The quotas say that the runtime limit for a custom function is 30 seconds, and the runtime limit for the script is 6 minutes.

After some research, I only found custom function mentions in the context of AddOns in Google Sheets, but the function where I'm getting the error is a global function (so that it can be recognized by a callback) in my script. Is there a way to change it to not be recognized as a custom function so that I'm not limited to the 30-second execution limit?

Now, how can I work around this execution limit? Is this an issue with the recommendation to modify the S3 library in this post? Essentially, the modification suggests that we export the actual bytes of the attachment rather than the encoded string.

This definitely increases the load that Apps Script has to handle which is why it increases the execution time required. How can I work around this issue? Is there a way to change the S3 library to improve processing speed?


问:
Not able to get output of select query
I am executing a simple select query on my trial instance of snowflake.
select * from schema_migrations;

I am getting the following error:
SQL compilation error: Object 'SCHEMA_MIGRATIONS' does not exist or not authorized.

The correct role, database and schema have been selected in the top right corner of the query box.
Attaching a screenshot.

The same select query is working for a different table in the same db, schema.

Note that this table (schema_migrations) was created via golang code using snowflake library for golang.

答:
Snowflake's object identifiers are case-sensitive. Your table created from Go has been created with a double-quoted table name identifier, and thus appears as lower-case in your screenshot.

Therefore, to query it, you must explicitly specify a lower-case name:

SELECT * FROM UTIL_DB.PUBLIC."schema_migrations";
```

Unquoted identifier names are treated as upper-case and will not match identifiers that were double-quoted. Quoting the relevant documentation portions that speak of this:

When an identifier is unquoted, it is stored and resolved in uppercase.

When an identifier is double-quoted, it is stored and resolved exactly as entered, including case.

And,

If an object is created using a double-quoted identifier, when referenced in a query or any other SQL statement, the identifier must be specified exactly as created, including the double quotes.

Failure to include the quotes might result in an Object does not exist error (or similar type of error).

Title: Not able to get output of select query

Body:
Snowflake's object identifiers are case-sensitive. Your table created from Go has been created with a double-quoted table name identifier, and thus appears as lower-case in your screenshot.

Therefore, to query it, you must explicitly specify a lower-case name:

SELECT * FROM UTIL_DB.PUBLIC."schema_migrations";

Unquoted identifier names are treated as upper-case and will not match identifiers that were double-quoted. Quoting the relevant documentation portions that speak of this:

When an identifier is unquoted, it is stored and resolved in uppercase.

When an identifier is double-quoted, it is stored and resolved exactly as entered, including case.

And,

If an object is created using a double-quoted identifier, when referenced in a query or any other SQL statement, the identifier must be specified exactly as created, including the double quotes.

Failure to include the quotes might result in an Object does not exist error (or similar type of error).


问:
Running two functions in parallel and passing the parameter returned by one function as argument to the other in python
I have implemented a sampler and a clock. I want to run the sampler and clock in parallel and at the same time I want the sampler to return it's end time to clock so that clock runs for that much time. These two functions are in some other module and it is being called from other module.

code for clock:

```<code>def clock_generator(self, freq, end_time):

    time_period = 1 / (freq)
    clock = 0
    while time.time<end_time:
        clock = 1
        time.sleep(((time_period) / 2))
        clock = 0
        time.sleep(((time_period) / 2))
</code>```

code for sampler:

```<code> def data_sample(self, path, result_file_name, time_index, formatted_data, time_period):

    start_time = time.time()

    """perform few operations"""

    end_time = time.time()
    return end_time
</code>```

答:
Following the clarification above "I want to run both data sampler and clock concurrently but I want the clock to run only till the data sampler is running hence, I want to send the end time from data sampler to the clock":

There's better ways to do this than running another process in parallel (depending on why you need the clock in a different function). Here's one way:

```<code>from time import time, sleep

class Clock:

  def __init__(self, freq):
    self.period = 1./freq

  def start(self):
    self.start = time()
    return self.start

  def getElapsed(self):
    return time() - self.start

  def getTick(self):
    elapsed = self.getElapsed();
    return int((elapsed/self.period) % 2)    # feel free to negate this condition

  def stop(self):
    self.end = time()
    return self.end

def data_sample():

    clock = Clock(5)
    print(clock.start())

    """perform few operations"""    # can call clock.getTick() here

    end = clock.stop()
    print(end)
    return end

data_sample()
</code>```

Body:
I have implemented a sampler and a clock. I want to run the sampler and clock in parallel and at the same time I want the sampler to return it's end time to clock so that clock runs for that much time. These two functions are in some other module and it is being called from other module.

code for clock:

def clock_generator(self, freq, end_time):

    time_period = 1 / (freq)
    clock = 0
    while time.time<end_time:
        clock = 1
        time.sleep(((time_period) / 2))
        clock = 0
        time.sleep(((time_period) / 2))

code for sampler:

 def data_sample(self, path, result_file_name, time_index, formatted_data, time_period):

    start_time = time.time()

    """perform few operations"""

    end_time = time.time()
    return end_time

Body:
Following the clarification above "I want to run both data sampler and clock concurrently but I want the clock to run only till the data sampler is running hence, I want to send the end time from data sampler to the clock":

There's better ways to do this than running another process in parallel (depending on why you need the clock in a different function). Here's one way:

from time import time, sleep

class Clock:

  def __init__(self, freq):
    self.period = 1./freq

  def start(self):
    self.start = time()
    return self.start

  def getElapsed(self):
    return time() - self.start

  def getTick(self):
    elapsed = self.getElapsed();
    return int((elapsed/self.period) % 2)    # feel free to negate this condition

  def stop(self):
    self.end = time()
    return self.end

def data_sample():

    clock = Clock(5)
    print(clock.start())

    """perform few operations"""    # can call clock.getTick() here

    end = clock.stop()
    print(end)
    return end

data_sample()


问:
Detecting Valid URLs

Possible Duplicate:

  Java HTTP getResponseCode returns 200 for non-existent URL

Hello, my goal is to build an application that determines the validity of HTML links, however in my following code :

```<code>try
{
 // create the HttpURLConnection
 URL url = new URL("http://www.thisurldoesnotexist");
 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 System.out.println("Response code is " + connection.getResponseCode());
}
</code>```

the nonsense URL is resolving to an IP address, which I did not expect, and the code returns the product : "Response code is 200"

It seems my approach to distinguishing between actual and non-existent pages is flawed. Does anyone know if I am applying the wrong tools toward determining the validity of web pages . . . i.e., is there a better way to differentiate between existent and non-existent web pages . . . thanks so much,

答:
You could:

Resolve the IP from the host of the page

Try to connect to port 80 on the resolved IP using plain sockets

This however will add complexity since you will need to make a simple GET request through the socket. Then validate the response so you're sure that its actually a HTTP server running on port 80.

NMap might be able to help you here.

ContentLicense: CC BY-SA 3.0

Title: Detecting Valid URLs

Body:
Possible Duplicate:

  Java HTTP getResponseCode returns 200 for non-existent URL

Hello, my goal is to build an application that determines the validity of HTML links, however in my following code :

try
{
 // create the HttpURLConnection
 URL url = new URL("http://www.thisurldoesnotexist");
 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 System.out.println("Response code is " + connection.getResponseCode());
}

the nonsense URL is resolving to an IP address, which I did not expect, and the code returns the product : "Response code is 200"

It seems my approach to distinguishing between actual and non-existent pages is flawed. Does anyone know if I am applying the wrong tools toward determining the validity of web pages . . . i.e., is there a better way to differentiate between existent and non-existent web pages . . . thanks so much,


问:
Flask peewee AttributeError: 'ModelSelect' object has no attribute '_meta'
I have a very simple setup, a model and api file in a pipenv flask environment. I'm currently using peewee and been facing an issue with getting all results from a datatable. I've done this before in python and works fine however not sure what in Flask I'm doing wrong. Here is my model

```<code>from peewee import *
import peewee as pw

db = pw.MySQLDatabase('xxxxx', host="localhost", port=3306, user='xxx',
password="xxxxx")

class HomeCarousel(Model):
   icon = pw.CharField(100)
   header = pw.CharField(50)
   text = pw.CharField(100)
   class Meta:
      database = db
</code>```

and here is my api file

```<code>from flask import Flask, g
from flask import jsonify, make_response
from playhouse.shortcuts import model_to_dict
from peewee import *
import peewee as pw
from models import *
from flask_cors import CORS

app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}})

@app.route('/')
def index():
   items = HomeCarousel.select()
   items = model_to_dict(items)
   return items

if __name__ == '__main__':
    app.run()
</code>```

Now the issue is that when I do items = HomeCarousel.select() I get an error "AttributeError: 'ModelSelect' object has no attribute '_meta'"

If I select only one record, everything works just fine.  items = HomeCarousel.get()

Does anyone know what I'm doing wrong here?

Thanks

答:
The model_to_dict expects an object instance.  You're passing it a ModelSelect.  You need to iterate over the objects returned in your ModelSelect:</p>

```<code>@app.route('/')
def index():
   items = HomeCarousel.select()
   items = [model_to_dict(item) for item in items]
   return items
</code>```

Body:
I have a very simple setup, a model and api file in a pipenv flask environment. I'm currently using peewee and been facing an issue with getting all results from a datatable. I've done this before in python and works fine however not sure what in Flask I'm doing wrong. Here is my model

from peewee import *
import peewee as pw

db = pw.MySQLDatabase('xxxxx', host="localhost", port=3306, user='xxx',
password="xxxxx")

class HomeCarousel(Model):
   icon = pw.CharField(100)
   header = pw.CharField(50)
   text = pw.CharField(100)
   class Meta:
      database = db

and here is my api file

from flask import Flask, g
from flask import jsonify, make_response
from playhouse.shortcuts import model_to_dict
from peewee import *
import peewee as pw
from models import *
from flask_cors import CORS

app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}})

@app.route('/')
def index():
   items = HomeCarousel.select()
   items = model_to_dict(items)
   return items

if __name__ == '__main__':
    app.run()

Now the issue is that when I do items = HomeCarousel.select() I get an error "AttributeError: 'ModelSelect' object has no attribute '_meta'"

If I select only one record, everything works just fine.  items = HomeCarousel.get()

Does anyone know what I'm doing wrong here?

Thanks

Body:
The model_to_dict expects an object instance.  You're passing it a ModelSelect.  You need to iterate over the objects returned in your ModelSelect:

@app.route('/')
def index():
   items = HomeCarousel.select()
   items = [model_to_dict(item) for item in items]
   return items


问:
Highchart - Angular 9: How to export all charts into single pdf?
I am configuring Highchart in my application and exporting individual chart by using "exporting" API (importing ExportingModule) successfully.
But not able to find any way to export all the charts in the page on single click (say, exportAll button on top of the page)
I've already imported following highchart modules in my application:

```<code>import ExportingModule from 'highcharts/modules/exporting';
import DownloadingModule from 'highcharts/modules/export-data.js';

ExportingModule(Highcharts);
DownloadingModule(Highcharts);
</code>```

Rendering charts by passing id and chart options:

```<code>Highcharts.chart(this.chartId, this.optiondata)
</code>```

Is there a way/API to export all charts in single pdf?

答:
The answer to your question you can find in the Highcharts FAQ.

https://www.highcharts.com/docs/getting-started/frequently-asked-questions#can-i-export-multiple-charts-to-the-same-image-or-pdf

Body:
I am configuring Highchart in my application and exporting individual chart by using "exporting" API (importing ExportingModule) successfully.
But not able to find any way to export all the charts in the page on single click (say, exportAll button on top of the page)
I've already imported following highchart modules in my application:

import ExportingModule from 'highcharts/modules/exporting';
import DownloadingModule from 'highcharts/modules/export-data.js';

ExportingModule(Highcharts);
DownloadingModule(Highcharts);

Rendering charts by passing id and chart options:

Highcharts.chart(this.chartId, this.optiondata)

Is there a way/API to export all charts in single pdf?


问:
Zend_Date tooooooooo slow, real slow
This is my code:

```<code>$frontendOptions = array('lifeTime' => 10);
$backendOptions = array('cacheDir' => '../tmp/');

$cache = Zend_Cache::factory(   'Core',
                                'File',
                                $frontendOptions,
                                $backendOptions);

$cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);

$locale = new Zend_Locale('es_ES');
Zend_Registry::set('Zend_Locale', $locale);
Zend_Locale::setCache($cache);

$date = new Zend_Date('11-03-2010');
</code>```

The script slows down when I try to create the Zend_Date object.

I'm using Zend 1.11.5 on MAMP (Mac / Snow Leopard).

Does anyone have any idea how can I speed up this?

答:
Problem is your cache lifetime is really low. Zend_Date uses Zend_Locale, that parses some XMLs (not very small ones), which takes lots and lots of time. Create special cache instance with extremely long lifetime (or better tie it to a files' modified time) and set that to both Zend_Date and Zend_Locale. That should speedup things dramatically. But it's not a good idea to use Zend_Date for say... echoing date in orders list. You can use

```<code>date('d.m.Y', strtotime($timeFromDb))
</code>```

You should use Zend_Date when doing date calculations or other advanced things with dates. Not for simple choing, unless you need abbility to echo it practically in any locale :)

Title: Zend_Date tooooooooo slow, real slow

Body:
This is my code:

$frontendOptions = array('lifeTime' => 10);
$backendOptions = array('cacheDir' => '../tmp/');

$cache = Zend_Cache::factory(   'Core',
                                'File',
                                $frontendOptions,
                                $backendOptions);

$cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);

$locale = new Zend_Locale('es_ES');
Zend_Registry::set('Zend_Locale', $locale);
Zend_Locale::setCache($cache);

$date = new Zend_Date('11-03-2010');

The script slows down when I try to create the Zend_Date object.

I'm using Zend 1.11.5 on MAMP (Mac / Snow Leopard).

Does anyone have any idea how can I speed up this?

Body:
Problem is your cache lifetime is really low. Zend_Date uses Zend_Locale, that parses some XMLs (not very small ones), which takes lots and lots of time. Create special cache instance with extremely long lifetime (or better tie it to a files' modified time) and set that to both Zend_Date and Zend_Locale. That should speedup things dramatically. But it's not a good idea to use Zend_Date for say... echoing date in orders list. You can use

date('d.m.Y', strtotime($timeFromDb))

You should use Zend_Date when doing date calculations or other advanced things with dates. Not for simple choing, unless you need abbility to echo it practically in any locale :)


问:
Find the lists that share common values
My question is closely related to the following topic.
I have a number of lists and I want to find the lists that share common values. All lists have the same size. The total number of lists is variable and can increase. Minimum number of lists is 2

```<code>a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
c = [9, 10, 11, 1]
</code>```

The expected output is:

```<code>[a, c]
</code>```

Ideally, I also want the fastest method. Thanks in advance,

答:
If you want the ['a', 'c'] output for n named lists, you could save them in a dict and use any to check if they intersect while looping through them:

```<code>lists = {
    "a" : [1, 2, 3, 4],
    "b" : [5, 6, 7, 8],
    "c" : [9, 10, 11, 1]
}
res = []
for l in lists:
    for l2 in lists:
        if l is not l2:
            if any(i in lists[l] for i in lists[l2]):
                res.append(l)
                break;
print(res)

OUT: ['a', 'c']
</code>```

Title: Find the lists that share common values

Body:
My question is closely related to the following topic.
I have a number of lists and I want to find the lists that share common values. All lists have the same size. The total number of lists is variable and can increase. Minimum number of lists is 2

a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
c = [9, 10, 11, 1]

The expected output is:

[a, c]

Ideally, I also want the fastest method. Thanks in advance,

Body:
If you want the ['a', 'c'] output for n named lists, you could save them in a dict and use any to check if they intersect while looping through them:

lists = {
    "a" : [1, 2, 3, 4],
    "b" : [5, 6, 7, 8],
    "c" : [9, 10, 11, 1]
}
res = []
for l in lists:
    for l2 in lists:
        if l is not l2:
            if any(i in lists[l] for i in lists[l2]):
                res.append(l)
                break;
print(res)

OUT: ['a', 'c']


问:
Why for gcc 'UNIX' and 'unix' macros are not the same thing?
I have a weird problem with gcc in Ubuntu Mate.

I need to write a golang program which uses a third-party C library, but i'v run a problem.

When I try to connect the third-party library in this code:

```<code>package main

// #cgo CFLAGS: -I /opt/cprocsp/include/interfaces/
// #cgo CFLAGS: -I /opt/cprocsp/include/
// #cgo CFLAGS: -I /opt/cprocsp/include/cpcsp/
// #include <stddef.h>
// #include "wincspc.h"
// #include "wincspc_int.h"
import "C"

func main() {
  var CSPConfig C.CPC_CONFIG
  C.CPCGetDefaultConfig(&CSPConfig, nil)
  CSPConfig.logConfig.name = string(C.MODNAME)
}
</code>```

I get a compile error:

```<code>In file included from /opt/cprocsp/include/cpcsp/wincspc.h:28:0,
                 from ./gost.go:7:
/opt/cprocsp/include/cpcsp/WinCryptEx.h:35:10: fatal error: wincrypt.h: No such file or directory
 #include <wincrypt.h>
          ^~~~~~~~~~~~
compilation terminated.
</code>```

I didn't know what this error meant. Next I decided to open WinCryptEx.h and I found these lines there:

```<code>#if defined UNIX || defined CSP_LITE
#include "CSP_WinCrypt.h"
#else // UNIX
#include <wincrypt.h>
#endif // UNIX
</code>```

So I realized that the compiler runs else statement (but I want it runs if statement because my OS is Linux). To confirm the problem I decided to write a C sample.

```<code>#if defined UNIX
#include "CSP_WinCrypt.h"
#else
#include <wincrypt.h>
#endif

int main()
{
    printf("Hello world");
}
</code>```

When I try to run this sample, I get the same error.
But then I decided to try to run the next code:

```<code>#if defined unix
#include "CSP_WinCrypt.h"
#else
#include <wincrypt.h>
#endif

int main()
{
    printf("Hello world");
}
</code>```

And it works fine!! The compiler runs if statement as I need.
I don't understand why.

I can't change the third-party library. So I need the compiler work correctly with 'UNIX' macro.

Does anyone have a solution? Thanks in advance.

答:
This query to a popular Internet search engine brings only a single page matching the word "unix" in the proper context: it's this page on system-specific macros.

That page hints at two things:

GCC does not guarantee that UNIX macro is defined.

The unix macro is described as being "common" but nothing is
stated about the fact it has to be present:

However, historically system-specific macros have had names with no special prefix; for instance, it is common to find unix defined on Unix systems. For all such macros, GCC provides a parallel macro with two underscores added at the beginning and the end. If unix is defined, __unix__ will be defined too.

In either case, identifiers in C are case-sensitive, and so are the symbols handled by its preprocessor, so unix and UNIX are two unrelated symbols.

In your case, I would supposedly reverse the logic and test for Windows, not the other way.

There, the symbol _WIN32 should be defined by both MinGW and MSVC.

Body:
I have a weird problem with gcc in Ubuntu Mate.

I need to write a golang program which uses a third-party C library, but i'v run a problem.

When I try to connect the third-party library in this code:

package main

// #cgo CFLAGS: -I /opt/cprocsp/include/interfaces/
// #cgo CFLAGS: -I /opt/cprocsp/include/
// #cgo CFLAGS: -I /opt/cprocsp/include/cpcsp/
// #include <stddef.h>
// #include "wincspc.h"
// #include "wincspc_int.h"
import "C"

func main() {
  var CSPConfig C.CPC_CONFIG
  C.CPCGetDefaultConfig(&CSPConfig, nil)
  CSPConfig.logConfig.name = string(C.MODNAME)
}

I get a compile error:

In file included from /opt/cprocsp/include/cpcsp/wincspc.h:28:0,
                 from ./gost.go:7:
/opt/cprocsp/include/cpcsp/WinCryptEx.h:35:10: fatal error: wincrypt.h: No such file or directory
 #include <wincrypt.h>
          ^~~~~~~~~~~~
compilation terminated.

I didn't know what this error meant. Next I decided to open WinCryptEx.h and I found these lines there:

#if defined UNIX || defined CSP_LITE
#include "CSP_WinCrypt.h"
#else // UNIX
#include <wincrypt.h>
#endif // UNIX

So I realized that the compiler runs else statement (but I want it runs if statement because my OS is Linux). To confirm the problem I decided to write a C sample.

#if defined UNIX
#include "CSP_WinCrypt.h"
#else
#include <wincrypt.h>
#endif

int main()
{
    printf("Hello world");
}

When I try to run this sample, I get the same error.
But then I decided to try to run the next code:

#if defined unix
#include "CSP_WinCrypt.h"
#else
#include <wincrypt.h>
#endif

int main()
{
    printf("Hello world");
}

And it works fine!! The compiler runs if statement as I need.
I don't understand why.

I can't change the third-party library. So I need the compiler work correctly with 'UNIX' macro.

Does anyone have a solution? Thanks in advance.


问:
Why wrong function was linked by the linker?
I am very confused about the following situation:

I have Linux project (which is written in c) that uses a static library A to get an executable. In this static library A there is a c code which calls sem_init from  Linux include. There is include to semaphore.h in the .c file, the file compiled using GCC without warnings. I use ld linker.

Everything was fine until I have added unintentionally a new module(which compiled to the static library B) to the project. New code has a function with the same name (sem_init) but a different signature. Code from A does not include .h file from B that defines the new sem_init().

Now, after the addition of library B to the compilation, I saw that instead of sem_init from semaphore.h, the new sem_init was called from library B.

I know that calling functions with the same name is an awful idea, but within a large project, it can happen unintentionally.

The question: why did this happen??? Why linker has chosen the new sem_init??? Why I did not get a multiple definition linkage error?

答:
When the linker is linking static libraries it looks there for undefined symbols only and if it finds a definition, then it links it in and resolves the symbol. sem_init happens to come from B which is linked before -lc (the GNU C standard library which also implements POSIX sem_init) is linked, and hence the linker picks up sem_init from B and then never looks for sem_init again, this is why you don't get multiple symbol definition error.

B library probably doesn't intend to implement POSIX sem_init with a different parameter list. It probably needs to mark its sem_init as static so that it is not visible to other translation units. And/or use a completely different name for it.


问:
Vaadin java Class will not start
I took a class for login into a web application from this forum for testing.

I use the Vaadin designer for making a single page webapplication. A User should login and will transfer to the site which I've created with the designer. At the moment there is no Java connection for the Webapp and my only goal is to transfer from log in to the MainView page.

Today I tried it again and it doesn't work anymore.  I've done nothing on the Java side only expanded the designer file.

```<code>package com.example;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.login.AbstractLogin;
import com.vaadin.flow.component.login.LoginForm;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.PWA;
import com.vaadin.flow.server.VaadinSession;

import java.util.Objects;
import java.util.Optional;

/**
 * The main view contains a button and a click listener.
 */
@Route ( "" )
@PWA ( name = "Project Base for Vaadin", shortName = "Project Base" )
public class MainView extends VerticalLayout
{

    public MainView ( )
    {
        this.display();
    }

    private void display ( )
    {
        if ( Objects.isNull( VaadinSession.getCurrent().getAttribute( User.class ) ) )
        {
            this.removeAll();
            this.add( this.makeLoginForm() );
        } else
        { // Else we have a User, so must be authenticated.
            this.removeAll();
            this.add( new MyContentView() );
        }
    }

    private LoginForm makeLoginForm ( )
    {
        Authenticator authenticator = new Authenticator();
        LoginForm component = new LoginForm();
        component.addLoginListener( ( AbstractLogin.LoginEvent loginEvent ) -> {
            Optional < User > user = authenticator.authenticate( loginEvent.getUsername() , loginEvent.getPassword() );
            if ( user.isPresent() )
            {
                VaadinSession.getCurrent().setAttribute( User.class , user.get() );
                this.display();
            } else
            {
                component.setError( true );
            }
        } );
        return component;
    }
</code>```
```<code>package com.example;

import com.vaadin.flow.component.accordion.Accordion;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.datepicker.DatePicker;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.polymertemplate.Id;
import com.vaadin.flow.templatemodel.TemplateModel;
import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.polymertemplate.PolymerTemplate;

/**
 * A Designer generated component for the my-content-view template.
 *
 * Designer will add and remove fields with @Id mappings but
 * does not overwrite or otherwise change this file.
 */
@Tag("my-content-view")
@JsModule("./my-content-view.js")
public class MyContentView extends PolymerTemplate<MyContentView.MyContentViewModel> {

    @Id("vaadinAccordion")
    private Accordion vaadinAccordion;
    @Id("label")
    private Label label;
    @Id("label1")
    private Label label1;
    @Id("birthday")
    private DatePicker birthday;
    @Id("vaadinButton")
    private Button vaadinButton;

    /**
     * Creates a new MyContentView.
     */
    public MyContentView() {
        // You can initialize any data required for the connected UI components here.
    }

    /**
     * This model binds properties between MyContentView and my-content-view
     */
    public interface MyContentViewModel extends TemplateModel {
        // Add setters and getters for template properties here.
    }
}
</code>```

This is the error Massage after login and update the site

```<code>There was an exception while trying to navigate to '' with the exception message 'Error creating bean with name 'com.example.MainView': Instantiation of bean failed;
nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.MainView]: Constructor threw exception;
nested exception is java.lang.IllegalStateException: There is no element with id='vaadinAccordion' in the template file './my-content-view.js'. Cannot map it using @Id'
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.example.MainView': Instantiation of bean failed;
nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.MainView]: Constructor threw exception;
nested exception is java.lang.IllegalStateException: There is no element with id='vaadinAccordion' in the template file './my-content-view.js'. Cannot map it using @Id
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1320)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:307)
    at com.vaadin.flow.spring.SpringInstantiator.getOrCreate(SpringInstantiator.java:117)
    at com.vaadin.flow.di.Instantiator.createRouteTarget(Instantiator.java:160)
    at com.vaadin.flow.router.internal.AbstractNavigationStateRenderer.lambda$getRouteTarget$1(AbstractNavigationStateRenderer.java:133)
    at java.base/java.util.Optional.orElseGet(Optional.java:369)
    at com.vaadin.flow.router.internal.AbstractNavigationStateRenderer.getRouteTarget(AbstractNavigationStateRenderer.java:132)
    at com.vaadin.flow.router.internal.AbstractNavigationStateRenderer.sendBeforeEnterEventAndPopulateChain(AbstractNavigationStateRenderer.java:498)
    at com.vaadin.flow.router.internal.AbstractNavigationStateRenderer.createChainIfEmptyAndExecuteBeforeEnterNavigation(AbstractNavigationStateRenderer.java:477)
    at com.vaadin.flow.router.internal.AbstractNavigationStateRenderer.handle(AbstractNavigationStateRenderer.java:228)
    at com.vaadin.flow.router.Router.handleNavigation(Router.java:249)
    at com.vaadin.flow.router.Router.navigate(Router.java:220)
    at com.vaadin.flow.router.Router.navigate(Router.java:186)
    at com.vaadin.flow.router.Router.initializeUI(Router.java:93)
    at com.vaadin.flow.server.BootstrapHandler.createAndInitUI(BootstrapHandler.java:1516)
    at com.vaadin.flow.server.BootstrapHandler.synchronizedHandleRequest(BootstrapHandler.java:472)
    at com.vaadin.flow.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:40)
    at com.vaadin.flow.server.VaadinService.handleRequest(VaadinService.java:1545)
    at com.vaadin.flow.server.VaadinServlet.service(VaadinServlet.java:247)
    at com.vaadin.flow.spring.SpringServlet.service(SpringServlet.java:120)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:352)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
    at org.springframework.web.servlet.mvc.ServletForwardingController.handleRequestInternal(ServletForwardingController.java:141)
    at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:177)
    at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:52)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1579)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.MainView]: Constructor threw exception; nested exception is java.lang.IllegalStateException: There is no element with id='vaadinAccordion' in the template file './my-content-view.js'. Cannot map it using @Id
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:213)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1312)
    ... 72 more
Caused by: java.lang.IllegalStateException: There is no element with id='vaadinAccordion' in the template file './my-content-view.js'. Cannot map it using @Id
    at com.vaadin.flow.component.polymertemplate.IdCollector.collectedInjectedId(IdCollector.java:106)
    at com.vaadin.flow.component.polymertemplate.IdCollector.lambda$collectInjectedIds$1(IdCollector.java:78)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
    at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at com.vaadin.flow.component.polymertemplate.IdCollector.collectInjectedIds(IdCollector.java:78)
    at com.vaadin.flow.component.polymertemplate.IdCollector.collectInjectedIds(IdCollector.java:67)
    at com.vaadin.flow.component.polymertemplate.TemplateDataAnalyzer.parseTemplate(TemplateDataAnalyzer.java:215)
    at com.vaadin.flow.component.polymertemplate.TemplateInitializer.<init>(TemplateInitializer.java:91)
    at com.vaadin.flow.component.polymertemplate.PolymerTemplate.<init>(PolymerTemplate.java:88)
    at com.vaadin.flow.component.polymertemplate.PolymerTemplate.<init>(PolymerTemplate.java:103)
    at com.example.MyContentView.<init>(MyContentView.java:38)
    at com.example.MainView.display(MainView.java:38)
    at com.example.MainView.<init>(MainView.java:26)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:200)
    ... 74 more
</code>```
```<code>import {html, PolymerElement} from '@polymer/polymer/polymer-element.js';
import '@vaadin/vaadin-button/src/vaadin-button.js';
import '@vaadin/vaadin-charts/src/vaadin-chart.js';
import '@vaadin/vaadin-ordered-layout/src/vaadin-vertical-layout.js';
import '@vaadin/vaadin-ordered-layout/src/vaadin-horizontal-layout.js';
import '@vaadin/vaadin-date-picker/src/vaadin-date-picker.js';
import '@vaadin/vaadin-accordion/src/vaadin-accordion.js';

class MyContentView extends PolymerElement {

    static get template() {
        return html`
<style include="shared-styles">
                :host {
                    display: block;
                    height: 100%;
                }
            </style>
<vaadin-horizontal-layout style="width: 100%; height: 100%;">
 <vaadin-vertical-layout class="sidebar" style="flex-basis: calc(7*var(--lumo-size-s)); flex-shrink: 0; background-color: var(--lumo-contrast-5pct);">
  <vaadin-vertical-layout theme="spacing" style="flex-grow: 1; align-self: stretch;">
   <vaadin-vertical-layout theme="spacing" style="flex-grow: 1; align-self: stretch;">
    <vaadin-button>
      Button
    </vaadin-button>
   </vaadin-vertical-layout>
   <vaadin-vertical-layout theme="spacing" style="flex-grow: 1; align-self: stretch;">
    <vaadin-button theme="primary">
      Primary
    </vaadin-button>
   </vaadin-vertical-layout>
  </vaadin-vertical-layout>
  <vaadin-vertical-layout theme="spacing" style="flex-grow: 1; align-self: stretch;">
   <vaadin-button id="vaadinButton">
     Button
   </vaadin-button>
   <vaadin-accordion></vaadin-accordion>
  </vaadin-vertical-layout>
 </vaadin-vertical-layout>
 <vaadin-vertical-layout class="content" style="flex-grow: 1; flex-shrink: 1; flex-basis: auto;">
  <vaadin-vertical-layout theme="spacing" style="align-self: stretch; height: 20%;">
   <vaadin-chart type="pie" title="Browser market shares in January, 2018" tooltip="">
    <vaadin-chart-series title="Brands" values="[["Chrome",61.41],["Internet Explorer",11.84],["Firefox",10.85],["Edge",4.67],["Safari",4.18],["Sogou Explorer",1.64],["Opera",1.6],["QQ",1.2],["Other",2.61]]"></vaadin-chart-series>
   </vaadin-chart>
  </vaadin-vertical-layout>
  <vaadin-vertical-layout theme="spacing" style="align-self: stretch; flex-grow: 1;">
   <vaadin-horizontal-layout theme="spacing" style="flex-grow: 1; height: 100%; align-self: stretch;">
    <vaadin-vertical-layout theme="spacing" style="width: 30%;">
     <vaadin-vertical-layout theme="margin" style="height: 50%; align-self: stretch; width: 100%; padding: var(--lumo-space-m);">
      <label id="label1">Neuigkeiten - Letzter Monat</label>
     </vaadin-vertical-layout>
     <vaadin-vertical-layout theme="margin" style="height: 50%; align-self: stretch; flex-grow: 0; width: 100%; padding: var(--lumo-space-m);"></vaadin-vertical-layout>
    </vaadin-vertical-layout>
    <vaadin-vertical-layout theme="spacing" style="width: 100%;">
     <vaadin-vertical-layout style="width: 100%; height: 50%;">
      <label id="label">Meine Kurse</label>
     </vaadin-vertical-layout>
     <vaadin-vertical-layout style="width: 100%; height: 50%;"></vaadin-vertical-layout>
    </vaadin-vertical-layout>
    <vaadin-vertical-layout theme="spacing" style="width: 30%;">
     <vaadin-vertical-layout theme="spacing" style="width: 100%; height: 50%; padding: var(--lumo-space-m);">
      <label>Mail</label>
     </vaadin-vertical-layout>
     <vaadin-vertical-layout theme="spacing" style="width: 100%; height: 50%; padding: var(--lumo-space-m);">
      <vaadin-date-picker label="Datum" placeholder="Pick a date" id="birthday">
        Datum
      </vaadin-date-picker>
     </vaadin-vertical-layout>
    </vaadin-vertical-layout>
   </vaadin-horizontal-layout>
  </vaadin-vertical-layout>
 </vaadin-vertical-layout>
</vaadin-horizontal-layout>
`;
    }

    static get is() {
        return 'my-content-view';
    }

    static get properties() {
        return {
            // Declare your properties here.
        };
    }
}

customElements.define(MyContentView.is, MyContentView);
</code>```

答:
As the error states:

```<code>There is no element with id='vaadinAccordion' in the template file
</code>```

The "HTML" of the design file contains an accordion tag, but no
id-attribute:

<vaadin-accordion></vaadin-accordion>
```

Title: Vaadin java Class will not start

Body:
I took a class for login into a web application from this forum for testing.

I use the Vaadin designer for making a single page webapplication. A User should login and will transfer to the site which I've created with the designer. At the moment there is no Java connection for the Webapp and my only goal is to transfer from log in to the MainView page.

Today I tried it again and it doesn't work anymore.  I've done nothing on the Java side only expanded the designer file.

package com.example;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.login.AbstractLogin;
import com.vaadin.flow.component.login.LoginForm;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.PWA;
import com.vaadin.flow.server.VaadinSession;

import java.util.Objects;
import java.util.Optional;

/**
 * The main view contains a button and a click listener.
 */
@Route ( "" )
@PWA ( name = "Project Base for Vaadin", shortName = "Project Base" )
public class MainView extends VerticalLayout
{

    public MainView ( )
    {
        this.display();
    }

    private void display ( )
    {
        if ( Objects.isNull( VaadinSession.getCurrent().getAttribute( User.class ) ) )
        {
            this.removeAll();
            this.add( this.makeLoginForm() );
        } else
        { // Else we have a User, so must be authenticated.
            this.removeAll();
            this.add( new MyContentView() );
        }
    }

    private LoginForm makeLoginForm ( )
    {
        Authenticator authenticator = new Authenticator();
        LoginForm component = new LoginForm();
        component.addLoginListener( ( AbstractLogin.LoginEvent loginEvent ) -> {
            Optional < User > user = authenticator.authenticate( loginEvent.getUsername() , loginEvent.getPassword() );
            if ( user.isPresent() )
            {
                VaadinSession.getCurrent().setAttribute( User.class , user.get() );
                this.display();
            } else
            {
                component.setError( true );
            }
        } );
        return component;
    }

package com.example;

import com.vaadin.flow.component.accordion.Accordion;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.datepicker.DatePicker;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.polymertemplate.Id;
import com.vaadin.flow.templatemodel.TemplateModel;
import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.polymertemplate.PolymerTemplate;

/**
 * A Designer generated component for the my-content-view template.
 *
 * Designer will add and remove fields with @Id mappings but
 * does not overwrite or otherwise change this file.
 */
@Tag("my-content-view")
@JsModule("./my-content-view.js")
public class MyContentView extends PolymerTemplate<MyContentView.MyContentViewModel> {

    @Id("vaadinAccordion")
    private Accordion vaadinAccordion;
    @Id("label")
    private Label label;
    @Id("label1")
    private Label label1;
    @Id("birthday")
    private DatePicker birthday;
    @Id("vaadinButton")
    private Button vaadinButton;

    /**
     * Creates a new MyContentView.
     */
    public MyContentView() {
        // You can initialize any data required for the connected UI components here.
    }

    /**
     * This model binds properties between MyContentView and my-content-view
     */
    public interface MyContentViewModel extends TemplateModel {
        // Add setters and getters for template properties here.
    }
}

This is the error Massage after login and update the site

There was an exception while trying to navigate to '' with the exception message 'Error creating bean with name 'com.example.MainView': Instantiation of bean failed;
nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.MainView]: Constructor threw exception;
nested exception is java.lang.IllegalStateException: There is no element with id='vaadinAccordion' in the template file './my-content-view.js'. Cannot map it using @Id'
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.example.MainView': Instantiation of bean failed;
nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.MainView]: Constructor threw exception;
nested exception is java.lang.IllegalStateException: There is no element with id='vaadinAccordion' in the template file './my-content-view.js'. Cannot map it using @Id
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1320)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:307)
    at com.vaadin.flow.spring.SpringInstantiator.getOrCreate(SpringInstantiator.java:117)
    at com.vaadin.flow.di.Instantiator.createRouteTarget(Instantiator.java:160)
    at com.vaadin.flow.router.internal.AbstractNavigationStateRenderer.lambda$getRouteTarget$1(AbstractNavigationStateRenderer.java:133)
    at java.base/java.util.Optional.orElseGet(Optional.java:369)
    at com.vaadin.flow.router.internal.AbstractNavigationStateRenderer.getRouteTarget(AbstractNavigationStateRenderer.java:132)
    at com.vaadin.flow.router.internal.AbstractNavigationStateRenderer.sendBeforeEnterEventAndPopulateChain(AbstractNavigationStateRenderer.java:498)
    at com.vaadin.flow.router.internal.AbstractNavigationStateRenderer.createChainIfEmptyAndExecuteBeforeEnterNavigation(AbstractNavigationStateRenderer.java:477)
    at com.vaadin.flow.router.internal.AbstractNavigationStateRenderer.handle(AbstractNavigationStateRenderer.java:228)
    at com.vaadin.flow.router.Router.handleNavigation(Router.java:249)
    at com.vaadin.flow.router.Router.navigate(Router.java:220)
    at com.vaadin.flow.router.Router.navigate(Router.java:186)
    at com.vaadin.flow.router.Router.initializeUI(Router.java:93)
    at com.vaadin.flow.server.BootstrapHandler.createAndInitUI(BootstrapHandler.java:1516)
    at com.vaadin.flow.server.BootstrapHandler.synchronizedHandleRequest(BootstrapHandler.java:472)
    at com.vaadin.flow.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:40)
    at com.vaadin.flow.server.VaadinService.handleRequest(VaadinService.java:1545)
    at com.vaadin.flow.server.VaadinServlet.service(VaadinServlet.java:247)
    at com.vaadin.flow.spring.SpringServlet.service(SpringServlet.java:120)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:352)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
    at org.springframework.web.servlet.mvc.ServletForwardingController.handleRequestInternal(ServletForwardingController.java:141)
    at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:177)
    at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:52)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1579)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.MainView]: Constructor threw exception; nested exception is java.lang.IllegalStateException: There is no element with id='vaadinAccordion' in the template file './my-content-view.js'. Cannot map it using @Id
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:213)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1312)
    ... 72 more
Caused by: java.lang.IllegalStateException: There is no element with id='vaadinAccordion' in the template file './my-content-view.js'. Cannot map it using @Id
    at com.vaadin.flow.component.polymertemplate.IdCollector.collectedInjectedId(IdCollector.java:106)
    at com.vaadin.flow.component.polymertemplate.IdCollector.lambda$collectInjectedIds$1(IdCollector.java:78)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
    at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at com.vaadin.flow.component.polymertemplate.IdCollector.collectInjectedIds(IdCollector.java:78)
    at com.vaadin.flow.component.polymertemplate.IdCollector.collectInjectedIds(IdCollector.java:67)
    at com.vaadin.flow.component.polymertemplate.TemplateDataAnalyzer.parseTemplate(TemplateDataAnalyzer.java:215)
    at com.vaadin.flow.component.polymertemplate.TemplateInitializer.<init>(TemplateInitializer.java:91)
    at com.vaadin.flow.component.polymertemplate.PolymerTemplate.<init>(PolymerTemplate.java:88)
    at com.vaadin.flow.component.polymertemplate.PolymerTemplate.<init>(PolymerTemplate.java:103)
    at com.example.MyContentView.<init>(MyContentView.java:38)
    at com.example.MainView.display(MainView.java:38)
    at com.example.MainView.<init>(MainView.java:26)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:200)
    ... 74 more

import {html, PolymerElement} from '@polymer/polymer/polymer-element.js';
import '@vaadin/vaadin-button/src/vaadin-button.js';
import '@vaadin/vaadin-charts/src/vaadin-chart.js';
import '@vaadin/vaadin-ordered-layout/src/vaadin-vertical-layout.js';
import '@vaadin/vaadin-ordered-layout/src/vaadin-horizontal-layout.js';
import '@vaadin/vaadin-date-picker/src/vaadin-date-picker.js';
import '@vaadin/vaadin-accordion/src/vaadin-accordion.js';

class MyContentView extends PolymerElement {

    static get template() {
        return html`

<vaadin-horizontal-layout style="width: 100%; height: 100%;">
 <vaadin-vertical-layout class="sidebar" style="flex-basis: calc(7*var(--lumo-size-s)); flex-shrink: 0; background-color: var(--lumo-contrast-5pct);">
  <vaadin-vertical-layout theme="spacing" style="flex-grow: 1; align-self: stretch;">
   <vaadin-vertical-layout theme="spacing" style="flex-grow: 1; align-self: stretch;">
    <vaadin-button>
      Button
    </vaadin-button>
   </vaadin-vertical-layout>
   <vaadin-vertical-layout theme="spacing" style="flex-grow: 1; align-self: stretch;">
    <vaadin-button theme="primary">
      Primary
    </vaadin-button>
   </vaadin-vertical-layout>
  </vaadin-vertical-layout>
  <vaadin-vertical-layout theme="spacing" style="flex-grow: 1; align-self: stretch;">
   <vaadin-button id="vaadinButton">
     Button
   </vaadin-button>
   <vaadin-accordion></vaadin-accordion>
  </vaadin-vertical-layout>
 </vaadin-vertical-layout>
 <vaadin-vertical-layout class="content" style="flex-grow: 1; flex-shrink: 1; flex-basis: auto;">
  <vaadin-vertical-layout theme="spacing" style="align-self: stretch; height: 20%;">
   <vaadin-chart type="pie" title="Browser market shares in January, 2018" tooltip="">
    <vaadin-chart-series title="Brands" values="[["Chrome",61.41],["Internet Explorer",11.84],["Firefox",10.85],["Edge",4.67],["Safari",4.18],["Sogou Explorer",1.64],["Opera",1.6],["QQ",1.2],["Other",2.61]]"></vaadin-chart-series>
   </vaadin-chart>
  </vaadin-vertical-layout>
  <vaadin-vertical-layout theme="spacing" style="align-self: stretch; flex-grow: 1;">
   <vaadin-horizontal-layout theme="spacing" style="flex-grow: 1; height: 100%; align-self: stretch;">
    <vaadin-vertical-layout theme="spacing" style="width: 30%;">
     <vaadin-vertical-layout theme="margin" style="height: 50%; align-self: stretch; width: 100%; padding: var(--lumo-space-m);">
      Neuigkeiten - Letzter Monat
     </vaadin-vertical-layout>
     <vaadin-vertical-layout theme="margin" style="height: 50%; align-self: stretch; flex-grow: 0; width: 100%; padding: var(--lumo-space-m);"></vaadin-vertical-layout>
    </vaadin-vertical-layout>
    <vaadin-vertical-layout theme="spacing" style="width: 100%;">
     <vaadin-vertical-layout style="width: 100%; height: 50%;">
      Meine Kurse
     </vaadin-vertical-layout>
     <vaadin-vertical-layout style="width: 100%; height: 50%;"></vaadin-vertical-layout>
    </vaadin-vertical-layout>
    <vaadin-vertical-layout theme="spacing" style="width: 30%;">
     <vaadin-vertical-layout theme="spacing" style="width: 100%; height: 50%; padding: var(--lumo-space-m);">
      Mail
     </vaadin-vertical-layout>
     <vaadin-vertical-layout theme="spacing" style="width: 100%; height: 50%; padding: var(--lumo-space-m);">
      <vaadin-date-picker label="Datum" placeholder="Pick a date" id="birthday">
        Datum
      </vaadin-date-picker>
     </vaadin-vertical-layout>
    </vaadin-vertical-layout>
   </vaadin-horizontal-layout>
  </vaadin-vertical-layout>
 </vaadin-vertical-layout>
</vaadin-horizontal-layout>
`;
    }

    static get is() {
        return 'my-content-view';
    }

    static get properties() {
        return {
            // Declare your properties here.
        };
    }
}

customElements.define(MyContentView.is, MyContentView);

Body:
As the error states:

There is no element with id='vaadinAccordion' in the template file

The "HTML" of the design file contains an accordion tag, but no
id-attribute:

<vaadin-accordion></vaadin-accordion>


问:
how to create a windows environment in linux
I am trying to run windows software in fedora OS. There option of dual booting. But is there a way of creating a virtual environment, like we create environment for various python project, in which we can run .exe files and use microsoft office softwares (word, excel, etc.)? It's a weird question, but I searched the internet but not able to find it out.</p>

答:
yes, you can easily do so with the help of VmWare or VrtualBox, or any other similar applications.With a virtual machine application like VMware, you can run another operating system inside your current operating system.
It's running an OS inside another OS,also, you can store and run multiple OS (not simultaneously though) with the hep of these virtual machines. </p>


问:
pubDate to unixtime in javascript
Does anyone have a function which can covert an RSS feeds pubDate to a unix timestamp? I tired using a javascript version of strtotime() but it never worked correctly.</p>

答:
```<code>var pubDate = "Sun, 27 Mar 2011 20:17:21 +0100";

var date = new Date(pubDate);
var timestamp = Math.round(date.getTime()/1000);

alert(timestamp);
</code>```

http://jsfiddle.net/VDwVB/1/

Title: pubDate to unixtime in javascript

Body:
var pubDate = "Sun, 27 Mar 2011 20:17:21 +0100";

var date = new Date(pubDate);
var timestamp = Math.round(date.getTime()/1000);

alert(timestamp);

http://jsfiddle.net/VDwVB/1/


问:
Do while loop in class c++
I am having a problem,more of a personal confusion,with a part of my code.You see the point is after asking the question about name amount weight given by n by user it should ask "add more?" and if replied Y or y it should either ask again for how many products do you want or just add 1 more.

```<code>class Class
{
public:
    char ask;
    vector <string> names;
    vector <int> amounts;
    vector <float> weights;
    string name;
    int amount, n;
    float weight;
    void market()
    {
        cout << "Give the number of products you want to get at Market : " << endl;
        cin >> n;
    }

void get()
{
    for (int i = 0; i < n; i++)
            {
                do
                {
                cout << "Give product name,amount and weight : " << endl;
                cin >> name >> amount >> weight;
                cout << endl;
                names.push_back(name);
                amounts.push_back(amount);
                weights.push_back(weight);
                }
                cout << "Add more? (Y/n): "; // add more? Go on if yes...
                cin >> ask;

            }while (ask == 'Y' || ask == 'y');

        }
};
</code>```

It is all in a class that i later put in main,is there any way to make it work that way?

答:
Apart from some syntax(improper bracketing) error in your code, there's some logic error that I can see. This is probably how you are looking for your get() function to be :

```<code>void get()
{
    for (int i = 0; i < n; i++){
        cout << "Give product name,amount and weight : " << endl;
        cin >> name >> amount >> weight;
        cout << endl;
        names.push_back(name);
        amounts.push_back(amount);
        weights.push_back(weight);
    }
    cout << "Add more? (Y/n): "; // add more? Go on if yes...
    cin >> ask;
    while (ask == 'Y' || ask == 'y'){
        cout << "Give product name,amount and weight : " << endl;
        cin >> name >> amount >> weight;
        cout << endl;
        names.push_back(name);
        amounts.push_back(amount);
        weights.push_back(weight);
        cout << "Add more? (Y/n): "; // add more? Go on if yes...
        cin >> ask;
    }
}
</code>```

The above code will first take n inputs from the user and then asks the user if wants to input more number of items. The while() loop will keep running until the user enters Y or y as the input.

Hope this solves your issue !

Title: Do while loop in class c++

Body:
I am having a problem,more of a personal confusion,with a part of my code.You see the point is after asking the question about name amount weight given by n by user it should ask "add more?" and if replied Y or y it should either ask again for how many products do you want or just add 1 more.

class Class
{
public:
    char ask;
    vector <string> names;
    vector <int> amounts;
    vector <float> weights;
    string name;
    int amount, n;
    float weight;
    void market()
    {
        cout << "Give the number of products you want to get at Market : " << endl;
        cin >> n;
    }

void get()
{
    for (int i = 0; i < n; i++)
            {
                do
                {
                cout << "Give product name,amount and weight : " << endl;
                cin >> name >> amount >> weight;
                cout << endl;
                names.push_back(name);
                amounts.push_back(amount);
                weights.push_back(weight);
                }
                cout << "Add more? (Y/n): "; // add more? Go on if yes...
                cin >> ask;

            }while (ask == 'Y' || ask == 'y');

        }
};

It is all in a class that i later put in main,is there any way to make it work that way?

Body:
Apart from some syntax(improper bracketing) error in your code, there's some logic error that I can see. This is probably how you are looking for your get() function to be :

void get()
{
    for (int i = 0; i < n; i++){
        cout << "Give product name,amount and weight : " << endl;
        cin >> name >> amount >> weight;
        cout << endl;
        names.push_back(name);
        amounts.push_back(amount);
        weights.push_back(weight);
    }
    cout << "Add more? (Y/n): "; // add more? Go on if yes...
    cin >> ask;
    while (ask == 'Y' || ask == 'y'){
        cout << "Give product name,amount and weight : " << endl;
        cin >> name >> amount >> weight;
        cout << endl;
        names.push_back(name);
        amounts.push_back(amount);
        weights.push_back(weight);
        cout << "Add more? (Y/n): "; // add more? Go on if yes...
        cin >> ask;
    }
}

The above code will first take n inputs from the user and then asks the user if wants to input more number of items. The while() loop will keep running until the user enters Y or y as the input.

Hope this solves your issue !


问:
frontend & backend development of an application containing "image processing" and "user authentication" steps
I am planning to build a mobile application (android and iOS), but I am confused. my idea is simple:
user takes a photo using her/his mobile phone, the photo is sent to the server, server checks if the user has registered or not (user authentication), if he/she is a registered user, his/her photo would be processed (some image processing steps) and finally the processed image would be sent back to user's mobile.

I know I should have a frontend and a backend. what programming languages should I use? I have googled a lot but yet no success. someone suggested using Laravel for user authentication but I am not sure if Laravel could handle the image processing steps as well.

Any help is appreciated.

答:
Being unaware of your experience and preference of programming language, I recommend to start with the Django framework, which is based on Python and receives a growing interest after its release in 2005. Probably the most famous project using Django is Instagram, whose core functionality is close to what you are after.

A good example project for you to start with can be found here:

https://github.com/axelpale/minimal-django-file-upload-example


问:
One hot encoding for sales prediction and kernel died
I am trying to forecast sales in daily basis and have a dataset 858935x15 features. Before feeding features to model, I want to make one hot encoding for categorical features. The product related features color, product_id, brand_id, category_id and subcategory_id are provided by int64 format and have below unique values;

------count of unique values -------

productid     -> 19359

color         -> 2243

categoryid    -> 101

brandid       -> 868

subcategoryid -> 103

If I made one-hot encode for these features, kernel is dying and the dataset becomes 17.5GB O.O

I guess, the problem is unique value count of product_id, do I strictly need to perform encoding for categorical features or can I leave them as they are especially for product_id?

答:
I can divide your question into two parts.

How to prevent the kernel from dying.

It dies when the storage limit is exceeded. It definitely does as you produce almost 20000 new columns. Based on my humble experience I can say one-hot encoding will be a very rude technique for the features color and brandid as well, as 1000 new features blows out your data significantly. I suggest you using algorithms, which can perfectly deal with categorical features: tree-based algorithms, such as Random Forest (please refer sklearn implementation) or Gradient Boosting methods.
(please refer LightGBM library)

Other ways to deal with categorical features.

If you insist on using linear or neural-based models, there is an amazing technique called mean encoding. You group the observations by each unique value of the feature and substitute the feature values with the mean values of target variable for each group. This technique does lose some information, containing in the feature, however, it does not require the swell of your dataset. This article explains the profits of using this approach.

Hope it helps.


问:
cdh quickstart 6.3.2 download link
Currently cloudera has stopped cloudera manager express and also unable to download cdh latest version.

cdh 6.3.2 is last open source version. I looking for its VM for virtualbox download link.

Anybody has cdh 6.3.2, please share it.

答: CDH 5.14 is available to download. Download link - https://community.cloudera.com/t5/Support-Questions/Cloudera-Quickstart-VM-Download/td-p/291225</p>

Title: cdh quickstart 6.3.2 download link


问:
Unable to encode csv to UTF-8
I am importing a csv and want to encode it to UTF-8 as some columns appear like this:

```<code>Comentario                                                                     Fecha      Mes   `Estaci\xf3n` Hotel        Marca
  <chr>                                                                          <date>     <chr> <chr>         <chr>        <chr>
1 "No todas las instalaciones del hotel se pudieron usar, estaban cerradas sin ~ 2020-02-01 feb.  "Invierno"    Sol Arona T~ Sol
2 "Me he ido con un buen sabor de boca, y ganas de volver. Me ha sorprendido to~ 2019-11-01 nov.  "Oto\xf1o"    Sol Arona T~ Sol
3 "Hotel normalito. Est\xe1 un poco viejo. Las habitaciones no tienen aire acon~ 2019-09-01 sep.  "Verano"      Sol Arona T~ Sol
</code>```

I have tried the following:

```<code>df<- read.csv("SolArona.csv",  sep=",", encoding = "UTF-8")
</code>```

But this returns Error in read_csv("SolArona.csv", sep = ",", encoding = "UTF-8") :
  unused arguments (sep = ",", encoding = "UTF-8"). So, I have also tried doing the Encoding of each column:

```<code>df <-read_csv("SolArona.csv")
Encoding(df$Comentario)<-"UTF-8"
Encoding (df$Estaci\xf3n)<-"UTF-8"
</code>```

Thanks very much in advance!

答:
Try this, insert another encoding if nescessary</p>

```<code>library(readr)
df<- read_csv("SolArona.csv",",",locale = locale(encoding = "UTF-8"))
</code>```

Title: Unable to encode csv to UTF-8

Body:
I am importing a csv and want to encode it to UTF-8 as some columns appear like this:

Comentario                                                                     Fecha      Mes   `Estaci\xf3n` Hotel        Marca
  <chr>                                                                          <date>     <chr> <chr>         <chr>        <chr>
1 "No todas las instalaciones del hotel se pudieron usar, estaban cerradas sin ~ 2020-02-01 feb.  "Invierno"    Sol Arona T~ Sol
2 "Me he ido con un buen sabor de boca, y ganas de volver. Me ha sorprendido to~ 2019-11-01 nov.  "Oto\xf1o"    Sol Arona T~ Sol
3 "Hotel normalito. Est\xe1 un poco viejo. Las habitaciones no tienen aire acon~ 2019-09-01 sep.  "Verano"      Sol Arona T~ Sol

I have tried the following:

df<- read.csv("SolArona.csv",  sep=",", encoding = "UTF-8")

But this returns Error in read_csv("SolArona.csv", sep = ",", encoding = "UTF-8") :
  unused arguments (sep = ",", encoding = "UTF-8"). So, I have also tried doing the Encoding of each column:

df <-read_csv("SolArona.csv")
Encoding(df$Comentario)<-"UTF-8"
Encoding (df$Estaci\xf3n)<-"UTF-8"

Thanks very much in advance!

Body:
Try this, insert another encoding if nescessary

library(readr)
df<- read_csv("SolArona.csv",",",locale = locale(encoding = "UTF-8"))