问:
Dash download in-memory generated file on button click: How to give filename?
I generate an in-memory Excel file via pd.ExcelWriter and BytesIO for a click event in my Python3.8 dash app.

Everything works as it should be. When I download my file I get this popup message asking me if I would like to continue to download/open the generated file. However, the popup message shows this (I guess base64 encoded) string (or path?), e.g. ...ydaHdjhgk328AAAAnxsAA== and after downloading the download gets a (randomly assigned?) set of characters as the filename (e.g. ZySzsdn1.xlsx).

How can I adjust this so it would display and assign the filename to something like download.xlsx? My guess is that is has something to do with the base64 encoded href.

The function to generate the excel file:

```<code>def write_product_file():
    output = BytesIO()
    writer = pd.ExcelWriter(output, engine="xlsxwriter")
    upload_df = pd.DataFrame()
    upload_df.to_excel(writer, index=False, sheet_name="sheet1")
    writer.save()
    return output
</code>```

The button in my Dash application:

```<code>html.Div(
  id="select-upload-form",
  style={"width": "100%"},
  children=[
    dbc.Button(
      "Download the upload form",
      id="download-excel",
      color="secondary",
      external_link="true",
      target="",
      href="",
    ),
  ],
),
</code>```

And finally my callback:

```<code>@app.callback(
    [
        Output("download-excel", "href"),
        Output("download-excel", "color"),
        Output("download-excel", "target"),
    ],
    [Input("download-excel", "n_clicks")],
)
def download_template_file(n_clicks):
    if n_clicks:
        excelfile = write_product_file()
        excelfile.seek(0)
        media_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        data = base64.b64encode(excelfile.read()).decode("utf-8")
        href_data = f"data:{media_type};base64,{data}"
        return href_data, "success", href_data,
    else:
        return None, "secondary", None

</code>```

答:
You could use the Download component from the dash-extensions package,

```<code>pip install dash-extensions == 0.0.18
</code>```

The syntax is simpler, and it has a filename argument. Here is a small example,

```<code>import dash
import dash_html_components as html
import numpy as np
import pandas as pd

from dash.dependencies import Output, Input
from dash_extensions import Download
from dash_extensions.snippets import send_bytes

# Generate some example data.
data = np.column_stack((np.arange(10), np.arange(10) * 2))
df = pd.DataFrame(columns=["a column", "another column"], data=data)
# Create app.
app = dash.Dash(prevent_initial_callbacks=True)
app.layout = html.Div([html.Button("Download xlsx", id="btn"), Download(id="download")])

@app.callback(Output("download", "data"), [Input("btn", "n_clicks")])
def generate_xlsx(n_nlicks):

    def to_xlsx(bytes_io):
        xslx_writer = pd.ExcelWriter(bytes_io, engine="xlsxwriter")
        df.to_excel(xslx_writer, index=False, sheet_name="sheet1")
        xslx_writer.save()

    return send_bytes(to_xlsx, "some_name.xlsx")

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

Disclaimer: I am the author of the dash-extensions package.

Body:
I generate an in-memory Excel file via pd.ExcelWriter and BytesIO for a click event in my Python3.8 dash app.

Everything works as it should be. When I download my file I get this popup message asking me if I would like to continue to download/open the generated file. However, the popup message shows this (I guess base64 encoded) string (or path?), e.g. ...ydaHdjhgk328AAAAnxsAA== and after downloading the download gets a (randomly assigned?) set of characters as the filename (e.g. ZySzsdn1.xlsx).

How can I adjust this so it would display and assign the filename to something like download.xlsx? My guess is that is has something to do with the base64 encoded href.

The function to generate the excel file:

def write_product_file():
    output = BytesIO()
    writer = pd.ExcelWriter(output, engine="xlsxwriter")
    upload_df = pd.DataFrame()
    upload_df.to_excel(writer, index=False, sheet_name="sheet1")
    writer.save()
    return output

The button in my Dash application:

html.Div(
  id="select-upload-form",
  style={"width": "100%"},
  children=[
    dbc.Button(
      "Download the upload form",
      id="download-excel",
      color="secondary",
      external_link="true",
      target="",
      href="",
    ),
  ],
),

And finally my callback:

@app.callback(
    [
        Output("download-excel", "href"),
        Output("download-excel", "color"),
        Output("download-excel", "target"),
    ],
    [Input("download-excel", "n_clicks")],
)
def download_template_file(n_clicks):
    if n_clicks:
        excelfile = write_product_file()
        excelfile.seek(0)
        media_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        data = base64.b64encode(excelfile.read()).decode("utf-8")
        href_data = f"data:{media_type};base64,{data}"
        return href_data, "success", href_data,
    else:
        return None, "secondary", None

Body:
You could use the Download component from the dash-extensions package,

pip install dash-extensions == 0.0.18

The syntax is simpler, and it has a filename argument. Here is a small example,

import dash
import dash_html_components as html
import numpy as np
import pandas as pd

from dash.dependencies import Output, Input
from dash_extensions import Download
from dash_extensions.snippets import send_bytes

# Generate some example data.
data = np.column_stack((np.arange(10), np.arange(10) * 2))
df = pd.DataFrame(columns=["a column", "another column"], data=data)
# Create app.
app = dash.Dash(prevent_initial_callbacks=True)
app.layout = html.Div([html.Button("Download xlsx", id="btn"), Download(id="download")])

@app.callback(Output("download", "data"), [Input("btn", "n_clicks")])
def generate_xlsx(n_nlicks):

    def to_xlsx(bytes_io):
        xslx_writer = pd.ExcelWriter(bytes_io, engine="xlsxwriter")
        df.to_excel(xslx_writer, index=False, sheet_name="sheet1")
        xslx_writer.save()

    return send_bytes(to_xlsx, "some_name.xlsx")

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

Disclaimer: I am the author of the dash-extensions package.


来源: stackexchange

问:
Test cross browser in the same test case using protractor
I need to test a chat app and the way i want to test is open one instance of chrome and another instance of firefox and send messages between both. From what I found I can open two browser sessions but they are for the same application and use multi-capabilities for testing all the test cases cross-platform. Has anyone attempted this?
Thanks in advance.

Edit:
So I added this to my protractor configuration i have tried with to test the same test case on multiple browsers

```<code>  multicapabilities:[
    {
       browserName: 'chrome'
    },
    {
       browserName: 'firefox'
    }
  ]
</code>```

I added this and I was able to run the same test case on multiple browsers independently.

Since I needed a test case run on multiple browsers. I found that we could use browser.forkNewDriverInstance(). This allowed me to launch multiple windows of the same browsers. This enabled me test more scenarios. And now I need to be able to test mutiple browsers(firefox, chrome) in the same test case.

Please let me know if any more information needs to be provided.

答:
After searching more stackoverflow pages and github issues. I found this article https://github.com/angular/protractor/issues/4962. That tells me how to start chrome and firefox together in the same test case. and the code i used is below: </p>

```<code>describe('Video Tests', () => {
    let ffBrowser: ProtractorBrowser;

    beforeAll(async () => {
        ffBrowser = await protractor.browser.forkNewDriverInstance().ready;
        (await ffBrowser.getProcessedConfig()).capabilities = {
          'browserName': 'firefox',
          'marionette': true,
          'moz:firefoxOptions': {
            'prefs': {
              'media.navigator.streams.fake': true,
              'media.navigator.permission.disabled': true
            }
          }
        } // new caps goes here;
        ffBrowser = await ffBrowser.restart();
    });

    it('testing cross browser', async () => {
      await browser.get(browser.baseUrl);
      await ffBrowser.get(browser.baseUrl);
      await browser.sleep(5000);
    });

    afterEach(async () => {
      // Assert that there are no errors emitted from the browser
      const logs = await browser.manage().logs().get(logging.Type.BROWSER);
      expect(logs).not.toContain(jasmine.objectContaining({
        level: logging.Level.SEVERE
      } as logging.Entry));
    });
  });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to test a chat app and the way i want to test is open one instance of chrome and another instance of firefox and send messages between both. From what I found I can open two browser sessions but they are for the same application and use multi-capabilities for testing all the test cases cross-platform. Has anyone attempted this?
Thanks in advance.

Edit:
So I added this to my protractor configuration i have tried with to test the same test case on multiple browsers

  multicapabilities:[
    {
       browserName: 'chrome'
    },
    {
       browserName: 'firefox'
    }
  ]

I added this and I was able to run the same test case on multiple browsers independently.

Since I needed a test case run on multiple browsers. I found that we could use browser.forkNewDriverInstance(). This allowed me to launch multiple windows of the same browsers. This enabled me test more scenarios. And now I need to be able to test mutiple browsers(firefox, chrome) in the same test case.

Please let me know if any more information needs to be provided.

Body:
After searching more stackoverflow pages and github issues. I found this article https://github.com/angular/protractor/issues/4962. That tells me how to start chrome and firefox together in the same test case. and the code i used is below:

describe('Video Tests', () => {
    let ffBrowser: ProtractorBrowser;

    beforeAll(async () => {
        ffBrowser = await protractor.browser.forkNewDriverInstance().ready;
        (await ffBrowser.getProcessedConfig()).capabilities = {
          'browserName': 'firefox',
          'marionette': true,
          'moz:firefoxOptions': {
            'prefs': {
              'media.navigator.streams.fake': true,
              'media.navigator.permission.disabled': true
            }
          }
        } // new caps goes here;
        ffBrowser = await ffBrowser.restart();
    });

    it('testing cross browser', async () => {
      await browser.get(browser.baseUrl);
      await ffBrowser.get(browser.baseUrl);
      await browser.sleep(5000);
    });

    afterEach(async () => {
      // Assert that there are no errors emitted from the browser
      const logs = await browser.manage().logs().get(logging.Type.BROWSER);
      expect(logs).not.toContain(jasmine.objectContaining({
        level: logging.Level.SEVERE
      } as logging.Entry));
    });
  });


问:
What is the Method for Database CleanUp in SQlite?
As what i experience using Sqlite for my Small Applications i always use sqliteadmin to use its database cleanup function to removes unnecessary data on my database.

Now i want to create a Method in my Application which do the same way as sqliteadmin  CleanUp.

How to do this?

Thanks in Regards

答:
```<code>using (SQLiteCommand command = m_connection.CreateCommand())
{
    command.CommandText = "vacuum;";
    command.ExecuteNonQuery();
}
</code>```

here is the exact answer on how to execute vacuum.

ContentLicense: CC BY-SA 3.0

Body:
using (SQLiteCommand command = m_connection.CreateCommand())
{
    command.CommandText = "vacuum;";
    command.ExecuteNonQuery();
}

here is the exact answer on how to execute vacuum.


问:
how to provide multiprocessing.process unique variblables
I have a list containing ID Number's, I want to implement every unique ID Number in an API call for each Multiprocessor whilst running the same corresponding functions, implementing the same conditional statements to each processor etc. I have tried to make sense of it but there is not a lot online about this procedure.

I thought to use a for loop but I don't want every processor running this for loop picking up every item in a list. I just need each item to be associated to each processor.

I was thinking something like this:

```<code>from multiprocessing import process
import requests, json

ID_NUMBERS = ["ID 1", "ID 2", "ID 3".... ETC]
BASE_URL = "www.api.com"
KEY = {"KEY": "12345"}

a = 0

for x in ID_NUMBERS:
    def[a]():
        while Active_live_data == True:
            # continuously loops over, requesting data from the website
            unique_api_call = "{}/livedata[{}]".format(BASE_URL, x)
            request_it = requests.get(unique_api_call, headers=KEY)
            show_it = (json.loads(request_it.content))

            #some extra conditional code...

        a += 1

processes = []
b = 0

for _ in range(len(ID_NUMBERS))
    p = multiprocessing.Process(target = b)
    p.start()
    processes.append(p)
    b += 1

</code>```

Any help would be greatly appreciated!

Kindest regards,

Andrew

答:
You can use the map function:

```<code>import multiprocessing as mp
num_cores = mp.cpu_count()
pool = mp.Pool(processes=num_cores)
results = pool.map(your_function, list_of_IDs)
</code>```

This will execute the function your_function, each time with a different item from the list list_of_IDs, and the values returned by your_function will be stored in a list of values (results).

Body:
I have a list containing ID Number's, I want to implement every unique ID Number in an API call for each Multiprocessor whilst running the same corresponding functions, implementing the same conditional statements to each processor etc. I have tried to make sense of it but there is not a lot online about this procedure.

I thought to use a for loop but I don't want every processor running this for loop picking up every item in a list. I just need each item to be associated to each processor.

I was thinking something like this:

from multiprocessing import process
import requests, json

ID_NUMBERS = ["ID 1", "ID 2", "ID 3".... ETC]
BASE_URL = "www.api.com"
KEY = {"KEY": "12345"}

a = 0

for x in ID_NUMBERS:
    def[a]():
        while Active_live_data == True:
            # continuously loops over, requesting data from the website
            unique_api_call = "{}/livedata[{}]".format(BASE_URL, x)
            request_it = requests.get(unique_api_call, headers=KEY)
            show_it = (json.loads(request_it.content))

            #some extra conditional code...

        a += 1

processes = []
b = 0

for _ in range(len(ID_NUMBERS))
    p = multiprocessing.Process(target = b)
    p.start()
    processes.append(p)
    b += 1

Any help would be greatly appreciated!

Kindest regards,

Andrew

Body:
You can use the map function:

import multiprocessing as mp
num_cores = mp.cpu_count()
pool = mp.Pool(processes=num_cores)
results = pool.map(your_function, list_of_IDs)

This will execute the function your_function, each time with a different item from the list list_of_IDs, and the values returned by your_function will be stored in a list of values (results).


问:
history.back() doesn't work in firefox and internet explorer but it work in google chrome
I encountered an anomaly by adding a button back to the previous page on JSP:
indeed when I click on the button the values of the fields that i filled will be lost
this behavior is detected on firefoxe and internet explorer,
on the other hand everything works well on chrome when I click on the button the values that I filled are displayed correctly.
can you help me on this point knowing that i tried the code below:

<button type="button" name="back" onCLick="history.back()">Retour</button>

<button type="button" name="back" onCLick="window.history.go(-1)">Retour</button>

<button type="button" name="back" onClick="goBack()">Retour</button>

function goBack() {
    window.history.back();
}

-below the current code:

```<code><button type="button" name="back" onclick="history.back()">Retour</button>
</code>```

Wainting for your help.

答:
Problem resolved :

The server is sending "no-store" with the page, so Firefox does not store the form after you leave the page :

```<code>HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Cache-Control", "public"); // HTTP 1.1
httpResponse.setHeader("Pragma", "public"); // HTTP 1.0
httpResponse.setDateHeader("Expires", Long.MAX_VALUE); // Proxies.
</code>```

Body:
I encountered an anomaly by adding a button back to the previous page on JSP:
indeed when I click on the button the values of the fields that i filled will be lost
this behavior is detected on firefoxe and internet explorer,
on the other hand everything works well on chrome when I click on the button the values that I filled are displayed correctly.
can you help me on this point knowing that i tried the code below:

<button type="button" name="back" onCLick="history.back()">Retour</button>

<button type="button" name="back" onCLick="window.history.go(-1)">Retour</button>

<button type="button" name="back" onClick="goBack()">Retour</button>

function goBack() {
    window.history.back();
}

-below the current code:

<button type="button" name="back" onclick="history.back()">Retour</button>

Wainting for your help.

Body:
Problem resolved :

The server is sending "no-store" with the page, so Firefox does not store the form after you leave the page :

HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Cache-Control", "public"); // HTTP 1.1
httpResponse.setHeader("Pragma", "public"); // HTTP 1.0
httpResponse.setDateHeader("Expires", Long.MAX_VALUE); // Proxies.


问:
Can we use RabbitMQ and Mediatr together using masstransit?
I created a microservice application that microservices using MassTransit and RabbitMQ for communication.

Each microservice developed using clean architecture, so we have MediatR inside each microservice.

Is it possible to use MassTransit for inside communication as well? so I can use the same signature for all services and when I want to expose a service to be used inter-microservice, it will be doable with ease.
So MediatR used for intra-communication and RabbitMQ used for inter-communication, and whole universe is on MassTransit system.

[Update] My question is how we can configure consumers so some can be used for inside communication (via MediatR) and some can be used for external communication (via RabbitMQ) and easily change them from inside to outside.

[Update2] for example here is my MassTransit registration:

```<code>services.AddMassTransit(x =>
        {
            x.AddConsumers(Assembly.GetExecutingAssembly());

            x.AddBus(provider =>
                Bus.Factory.CreateUsingRabbitMq(cfg =>
                {
                    cfg.Host(new Uri(config.RabbitMQ.Address), h =>
                    {
                        h.Username(config.RabbitMQ.Username);
                        h.Password(config.RabbitMQ.Password);
                    });

                    cfg.ReceiveEndpoint("my-queue", ep => { ep.ConfigureConsumers(provider); });
                }));

            x.AddMediator((provider, cfg) => { cfg.ConfigureConsumers(provider); });
        });
</code>```

How can I differ in internal communication and external communication? in other words, how can I register some consumers to MediatR and some to RabbitMQ?

答:
They can be used together, and MassTransit has its own Mediator implementation as well so you can write your handlers once and use them either via the mediator or via a durable transport such as RabbitMQ.

There are videos available that take you through the capabilities, starting with mediator and moving to RabbitMQ.

Body:
I created a microservice application that microservices using MassTransit and RabbitMQ for communication.

Each microservice developed using clean architecture, so we have MediatR inside each microservice.

Is it possible to use MassTransit for inside communication as well? so I can use the same signature for all services and when I want to expose a service to be used inter-microservice, it will be doable with ease.
So MediatR used for intra-communication and RabbitMQ used for inter-communication, and whole universe is on MassTransit system.

[Update] My question is how we can configure consumers so some can be used for inside communication (via MediatR) and some can be used for external communication (via RabbitMQ) and easily change them from inside to outside.

[Update2] for example here is my MassTransit registration:

services.AddMassTransit(x =>
        {
            x.AddConsumers(Assembly.GetExecutingAssembly());

            x.AddBus(provider =>
                Bus.Factory.CreateUsingRabbitMq(cfg =>
                {
                    cfg.Host(new Uri(config.RabbitMQ.Address), h =>
                    {
                        h.Username(config.RabbitMQ.Username);
                        h.Password(config.RabbitMQ.Password);
                    });

                    cfg.ReceiveEndpoint("my-queue", ep => { ep.ConfigureConsumers(provider); });
                }));

            x.AddMediator((provider, cfg) => { cfg.ConfigureConsumers(provider); });
        });

How can I differ in internal communication and external communication? in other words, how can I register some consumers to MediatR and some to RabbitMQ?


问:
How to forecast the column value based on its previous value in Python
I have a dataframe with 3,000,000 IDs. Each ID has the month range from 2015-01-01
t0 2018-12-01. Each ID has column "A" and "B" with numeric values. I need to create a new column "C:.

For each ID, when Date == '2015-01-01' which is the first month for that ID, column C value equal to exp(column_A value).
 For the next month (Date == '2015-02-01'), column C value equal to exp(log(column_C_value in previous month) + column_B_value at this month), so here is exp(log(column C @ 2015-01-01) + column_B @ 2015-02-01). Each of the following months has the same pattern until it reaches 2018-12-01.

In Python, I can setup the loop for each ID and for each row/month, such as:
for ID in range(xxx):
    for month in range(xxxx):

However, such calculation takes long time. Can anyone tell me a faster way to do this calculation? Very appreciated for your help!

答:
Consider that
(1) exp(x+y) == exp(x)*exp(y).
And
(2) exp(log(x)) == x.

So exp(log(c1) + b2) == c1 * exp(b2).
The next value simplifies to c1 * exp(b2) * exp(b3), and so on.

That means, you have to multiply all exp(b) values, which can be turned
into adding all(b)-s and then applying exp() to the result.

And don't forget to multiply it with a1, the initial value.

a1 * exp(b2 * b3 * ...)


问:
For loop to merge pandas dataframe with common columns
I have 25 data frames, each of them have 7 ascending dates(as rows) and between 570-600 airport names as columns. The big problem is that, since the dataframes store the number of ascensions each airport has each day, the weeks that certain airports are inactive results in the dataframes having different orders and quantities of like and unlike airport names. All of the column names will appear in alphabetical order in each dataframe, but the absence of just one airport column from the dataframe messes up the entire alignment of the master dataframe.

I have tried merge, concat, join, update...this problem is really complicated and my end goal is to have a master dataframe with all exisiting alphabetically ordered airports as columns, and ongoing rows as the dates ascend and time passes.

I think I have to make a for loop to do this:
1. No data can be lost
2. It needs to merge dataframes by column so that if the column name of the second data frame is the same as the column of the first, the new data will be added below that column without repeating the column name again.
3.If the column name of the second is different than the column name of the first, I want the column to be added as a new column (hopefully in alphabetical order).
4.If the second dataframe does not have a column that the first one does have, I want it to say NAN for that airport.

In sum, the major parts I want the for loop to do is add data under identical columns(even though the dataframes have the columns out of order), add columns that weren't previously there, fill in NANs where airports are missing, and make sure that the column names only appear as the 0 row. Sorry, it is so hard to explain.

Here are two simple dataframe examples that I want the for loop to be able to merge

```<code>df1 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
                    columns=['Airport1', 'Airport3', 'Airport4'])
df1.index.name='Dates'
df1.index=['11/01','11/02','11/03']
df2 = pd.DataFrame(np.array([[2, 4, 6], [8, 10, 12], [14, 16, 18]]),
                    columns=['Airport1', 'Airport2', 'Airport3'])
df2.index.name='Dates'
df2.index=['11/04','11/05','11/06']
display(df1,df2)

Dates **Airport1** **Airport3** **Airport4**
11/01   1.            2.          3.
11/02   4.            5.          6.
11/03   7.            8.          9.

Dates **Airport1** **Airport2** **Airport3**
11/04   2.           4.           6
11/05   8.           10.          12
11/06   14.          16.          18
</code>```

The result I would want the for loop to have is:

```<code>Dates **Airport1** **Airport2** **Airport3** **Airport4**
11/01   1.              NAN.         2.           3
11/02.  4.              NAN.         5.           6
11/03.  7.              NAN.         8.           9
11/04.  2.               4.          6.          NAN
11/05.  8.              10.          12.         NAN
11/06.  14.             16.          18.         NAN
</code>```

Another note is that I have 25 data frames to merge and counting, so I would like the for loop to be able to take in infinite dataframes. Thanks so much in advance!!!

答:
IIUC, You can try pd.concat along with df.sort_index:

```<code>df = pd.concat([df1, df2]).sort_index(axis=1)
</code>```

In case of more than two dataframes, Use:

```<code>from functools import reduce

dfs = [df1, df2] # list of all dataframes that need's to be combined
df = reduce(lambda d1, d2: pd.concat([d1, d2]), dfs).sort_index(axis=1)
</code>```

Result:

```<code># print(df)

       Airport1  Airport2  Airport3  Airport4
11/01         1       NaN         2       3.0
11/02         4       NaN         5       6.0
11/03         7       NaN         8       9.0
11/04         2       4.0         6       NaN
11/05         8      10.0        12       NaN
11/06        14      16.0        18       NaN
</code>```

Body:
I have 25 data frames, each of them have 7 ascending dates(as rows) and between 570-600 airport names as columns. The big problem is that, since the dataframes store the number of ascensions each airport has each day, the weeks that certain airports are inactive results in the dataframes having different orders and quantities of like and unlike airport names. All of the column names will appear in alphabetical order in each dataframe, but the absence of just one airport column from the dataframe messes up the entire alignment of the master dataframe.

I have tried merge, concat, join, update...this problem is really complicated and my end goal is to have a master dataframe with all exisiting alphabetically ordered airports as columns, and ongoing rows as the dates ascend and time passes.

I think I have to make a for loop to do this:
1. No data can be lost
2. It needs to merge dataframes by column so that if the column name of the second data frame is the same as the column of the first, the new data will be added below that column without repeating the column name again.
3.If the column name of the second is different than the column name of the first, I want the column to be added as a new column (hopefully in alphabetical order).
4.If the second dataframe does not have a column that the first one does have, I want it to say NAN for that airport.

In sum, the major parts I want the for loop to do is add data under identical columns(even though the dataframes have the columns out of order), add columns that weren't previously there, fill in NANs where airports are missing, and make sure that the column names only appear as the 0 row. Sorry, it is so hard to explain.

Here are two simple dataframe examples that I want the for loop to be able to merge

df1 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
                    columns=['Airport1', 'Airport3', 'Airport4'])
df1.index.name='Dates'
df1.index=['11/01','11/02','11/03']
df2 = pd.DataFrame(np.array([[2, 4, 6], [8, 10, 12], [14, 16, 18]]),
                    columns=['Airport1', 'Airport2', 'Airport3'])
df2.index.name='Dates'
df2.index=['11/04','11/05','11/06']
display(df1,df2)

Dates **Airport1** **Airport3** **Airport4**
11/01   1.            2.          3.
11/02   4.            5.          6.
11/03   7.            8.          9.

Dates **Airport1** **Airport2** **Airport3**
11/04   2.           4.           6
11/05   8.           10.          12
11/06   14.          16.          18

The result I would want the for loop to have is:

Dates **Airport1** **Airport2** **Airport3** **Airport4**
11/01   1.              NAN.         2.           3
11/02.  4.              NAN.         5.           6
11/03.  7.              NAN.         8.           9
11/04.  2.               4.          6.          NAN
11/05.  8.              10.          12.         NAN
11/06.  14.             16.          18.         NAN

Another note is that I have 25 data frames to merge and counting, so I would like the for loop to be able to take in infinite dataframes. Thanks so much in advance!!!

Body:
IIUC, You can try pd.concat along with df.sort_index:

df = pd.concat([df1, df2]).sort_index(axis=1)

In case of more than two dataframes, Use:

from functools import reduce

dfs = [df1, df2] # list of all dataframes that need's to be combined
df = reduce(lambda d1, d2: pd.concat([d1, d2]), dfs).sort_index(axis=1)

Result:

# print(df)

       Airport1  Airport2  Airport3  Airport4
11/01         1       NaN         2       3.0
11/02         4       NaN         5       6.0
11/03         7       NaN         8       9.0
11/04         2       4.0         6       NaN
11/05         8      10.0        12       NaN
11/06        14      16.0        18       NaN


问:
Validating elements of a 2D array
My code for making sure an element isn't over 100 or less than 0 is:

boolean test = true;
for (int i = 0; i < inArray.length; i++) {
    for (int j = 0; j < inArray[0].length; j++) {
        if (inArray[i][j] <= 1 && inArray[i][j] >= 100) {
            test = false;
        }
    }
}
return test;
```
<p>Except no matter what the input is the answer is always <code>true</code></p>
<p>My input <code>array</code> is</p>
```{12, 1331, 23, 5, 1, 3},
{22, 23, 231, 21312, 1, 3},
{23, 31, 343, 3432, 1, 3},
{42, 12, 5454, 1212, 3, 9}
```

test should = false if I input this no?

College rules mean I cannot use break; or return anywhere other than the end of the sub module.

答:
Update your for loop condition to i < inArray.length && test and j < inArray[0].length && test which would force your loop to end once an invalid nos is found
and your if condition to inArray[i][j] <= 1 ||  inArray[i][j] >= 100

```<code>boolean test = true

        for(int i = 0; i < inArray.length && test; i++){
            for(int j = 0; j < inArray[0].length && test; j++){
                if(inArray[i][j] <= 1 ||  inArray[i][j] >= 100){
                    test = false;
                }
            }
        }

        return test;
</code>```

you can also skip a if block by,

```<code>boolean test = true

        for(int i = 0; i < inArray.length && test; i++){
            for(int j = 0; j < inArray[0].length && test; j++){
                test = (1 < inArray[i][j]  && inArray[i][j] < 100)
            }
        }

        return test;
</code>```

Title: Validating elements of a 2D array

Body:
My code for making sure an element isn't over 100 or less than 0 is:

boolean test = true;
for (int i = 0; i < inArray.length; i++) {
    for (int j = 0; j < inArray[0].length; j++) {
        if (inArray[i][j] <= 1 && inArray[i][j] >= 100) {
            test = false;
        }
    }
}
return test;

Except no matter what the input is the answer is always true

My input array is

{12, 1331, 23, 5, 1, 3},
{22, 23, 231, 21312, 1, 3},
{23, 31, 343, 3432, 1, 3},
{42, 12, 5454, 1212, 3, 9}

test should = false if I input this no?

College rules mean I cannot use break; or return anywhere other than the end of the sub module.

Body:
Update your for loop condition to i < inArray.length && test and j < inArray[0].length && test which would force your loop to end once an invalid nos is found
and your if condition to inArray[i][j] <= 1 ||  inArray[i][j] >= 100

boolean test = true

        for(int i = 0; i < inArray.length && test; i++){
            for(int j = 0; j < inArray[0].length && test; j++){
                if(inArray[i][j] <= 1 ||  inArray[i][j] >= 100){
                    test = false;
                }
            }
        }

        return test;

you can also skip a if block by,

boolean test = true

        for(int i = 0; i < inArray.length && test; i++){
            for(int j = 0; j < inArray[0].length && test; j++){
                test = (1 < inArray[i][j]  && inArray[i][j] < 100)
            }
        }

        return test;


问:
heroku: set SSL certificates on Free Plan?
I would like to set some SSL certificates for one app I have on heroku (a simple application based on nodeJS + Vue).

I know if I upgrade to the Hobby Plan (7$ for month) I can have it automatically.

But for now it would too much money for a test application, so I am wondering if I can achieve some similar goal also with a Free Plan.

so:
Is it possible to set SSL certificate for an app on Heroku JUST with the Free Plan?
Maybe in a complicated/tricky way via CLI?

From the Heroku pages and documentation it looks not possible.
But I have to ask :)

答:
If you are using

1]free heroku,

You can't use 1)free ssl or 2)paid ssl

2]paid heroku

1)you get free ssl 2)you can use paid ssl also

Solution
1]get paid heroku
2]move to netlify or other alternatives


问:
What's the purpose of named hierarchical loggers?
According to this example http://tutorials.jenkov.com/java-logging/logger-hierarchy.html

we have three loggers "com", "com.jenkov" and "com.jenkov.web". Why these has to be in hierarchy, what's the advantage of rolling up the messages ?

答:
Why these has to be in hierarchy...?

Inheritance.  Per Java™ Logging Overview - 1.3 Loggers:

In particular, a logger may inherit:

Logging level. If a Logger's level is set to be null then the Logger will use an effective Level that will be obtained by walking up the parent tree and using the first non-null Level.
  Handlers. By default a Logger will log any output messages to its parent's handlers, and so on recursively up the tree.
  Resource bundle names. If a logger has a null resource bundle name, then it will inherit any resource bundle name defined for its parent, and so on recursively up the tree.

Using the package deceleration in Java which allows you to either listen, turn off, or sift logging for class, package, or even an organisational 3rd party lib.  It also means you don't have to write a configuration file with hundreds of logger names to disable all logging.  Setting the root adjusts all children for you in one line.  Since you have a tree structure you can recursively apply that logic to the child loggers to disable a specific library or a logical program module.

In the tutorial it is explained:

Logger.getLogger("com.jenkov.web") has only one parent and that is the root logger.  Looks like this: "" <- "com.jenkov.web"

However, Logger logger  = Logger.getLogger("");
Logger logger1 = Logger.getLogger("com");
Logger logger2 = Logger.getLogger("com.jenkov");
Logger logger3 = Logger.getLogger("com.jenkov.web");

forces the LogManager to create a different hierarchy which looks like this:
"" <- "com." <- "com.jenkov." <- "com.jenkov.web"

Adding code like this is not required in log4j but is required in JUL if you want to modify the hierarchy so you can control it at runtime.  Also loggers should be pinned in memory to avoid garbage collection if you need to do this trick.

...what's the advantage of rolling up the messages ?

I assume you mean sending messages to parent loggers???  It enables the configuration to sift log records into specific Handlers and sharing common handler settings.  For instance, in a development environment configuration you might want to send all output to the console by attaching to the root and then only send to the FileHandler for a specific package.  The advantage with the logger tree is that you don't have to attach a second ConsoleHandler to the specific package to see console output.


问:
Show tooltip arrow at top of icon which is align end of text in TextView
I have a TextView in which i am setting text dynamically(text length is not fixed ) and end of the text there is a icon,So My question is I want to show tooltip like tooltip arrow should be at top of info icon , as shown in attached image

答:
You can follow this way

XML File

```<code><androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/clMain"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent">

    <ImageView
        android:id="@+id/ivDone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:src="@drawable/ic_done_black_24dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/tvShipInBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="Ship in Box($10 Extra per box)"
        android:textColor="#E83535"
        app:layout_constraintBottom_toBottomOf="@id/ivDone"
        app:layout_constraintStart_toEndOf="@id/ivDone" />

    <ImageView
        android:id="@+id/ivInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:src="@drawable/ic_info_black_24dp"
        app:layout_constraintBottom_toBottomOf="@id/ivDone"
        app:layout_constraintStart_toEndOf="@id/tvShipInBox" />

</androidx.constraintlayout.widget.ConstraintLayout>

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/clToolTip"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginBottom="8dp"
    android:background="@drawable/ic_tooltip_bg"
    app:layout_constraintBottom_toTopOf="@id/clMain"
    app:layout_constraintHeight_percent="0.075"

    app:layout_constraintStart_toStartOf="@id/clMain"
    app:layout_constraintWidth_percent="0.65">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginHorizontal="8dp"
        android:alpha="0.87"
        android:text="A box increases an items volumetric weight and costs more."
        android:textColor="#000000"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent="0.6"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Java File

```<code>public class MainActivity extends AppCompatActivity {

    ImageView ivInfo;
    ConstraintLayout clToolTip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ivInfo = findViewById(R.id.ivInfo);
        clToolTip = findViewById(R.id.clToolTip);
        ivInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ivInfo.setVisibility(View.INVISIBLE);
                ivInfo.postDelayed(new Runnable() {
                    public void run() {
                        clToolTip.setVisibility(View.VISIBLE);
                    }
                }, 7000);
            }
        });
    }
}
</code>```

Body:
You can follow this way

XML File

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/clMain"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent">

    <ImageView
        android:id="@+id/ivDone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:src="@drawable/ic_done_black_24dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/tvShipInBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="Ship in Box($10 Extra per box)"
        android:textColor="#E83535"
        app:layout_constraintBottom_toBottomOf="@id/ivDone"
        app:layout_constraintStart_toEndOf="@id/ivDone" />

    <ImageView
        android:id="@+id/ivInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:src="@drawable/ic_info_black_24dp"
        app:layout_constraintBottom_toBottomOf="@id/ivDone"
        app:layout_constraintStart_toEndOf="@id/tvShipInBox" />

</androidx.constraintlayout.widget.ConstraintLayout>

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/clToolTip"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginBottom="8dp"
    android:background="@drawable/ic_tooltip_bg"
    app:layout_constraintBottom_toTopOf="@id/clMain"
    app:layout_constraintHeight_percent="0.075"

    app:layout_constraintStart_toStartOf="@id/clMain"
    app:layout_constraintWidth_percent="0.65">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginHorizontal="8dp"
        android:alpha="0.87"
        android:text="A box increases an items volumetric weight and costs more."
        android:textColor="#000000"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent="0.6"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Java File

public class MainActivity extends AppCompatActivity {

    ImageView ivInfo;
    ConstraintLayout clToolTip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ivInfo = findViewById(R.id.ivInfo);
        clToolTip = findViewById(R.id.clToolTip);
        ivInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ivInfo.setVisibility(View.INVISIBLE);
                ivInfo.postDelayed(new Runnable() {
                    public void run() {
                        clToolTip.setVisibility(View.VISIBLE);
                    }
                }, 7000);
            }
        });
    }
}


问:
Unknown URL content://downloads/my_downloads
I'm using Download Manger to download some multimedia files and categorize them. I'm also using Crashlytics and this is an error I frequently get on different devices and versions of Android:

```<code>java.lang.IllegalArgumentException: Unknown URL content://downloads/my_downloads
   at android.content.ContentResolver.insert(ContentResolver.java:862)
   at android.app.DownloadManager.enqueue(DownloadManager.java:1252)
   at com.myapp.LessonFragment$DownloadClickListener.onClick(SourceFile:570)
   at android.view.View.performClick(View.java:4262)
   at android.view.View$PerformClick.run(View.java:17351)
   at android.os.Handler.handleCallback(Handler.java:615)
   at android.os.Handler.dispatchMessage(Handler.java:92)
   at android.os.Looper.loop(Looper.java:137)
   at android.app.ActivityThread.main(ActivityThread.java:4921)
   at java.lang.reflect.Method.invokeNative(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:511)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
   at dalvik.system.NativeStart.main(NativeStart.java)
</code>```

You can see my codes below:

private class DownloadClickListener implements View.OnClickListener {
    @Override
    public void onClick(View view) {
        // Check if download manager available before request
        if (!DownloadHelper.isDownloadManagerAvailable(getActivity())) {
            // Build custom alert dialog
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage(R.string.download_manager_disabled);
            builder.setCancelable(false);
            builder.setPositiveButton(R.string.ok, (dialog, which) -> {
                dialog.dismiss();
            });
            // Create and display alert dialog
            AlertDialog dialog = builder.create();
            dialog.show();
            return;
        }

        // Display short toast on download clicked
        Toast.makeText(getActivity(), R.string.lesson_download_start, Toast.LENGTH_SHORT).show();

        // Get attach from view tag
        Attache attache = (Attache) view.getTag();

        // Get lesson using lesson id
        Lesson lesson = new Select().from(Lesson.class)
                .where(Condition.column("id").is(attache.getLessonId()))
                .querySingle();

        // Set file name from url and attache name
        Uri uri = Uri.parse(attache.getFile());
        String fileName = attache.getName() + '.'
                + MimeTypeMap.getFileExtensionFromUrl(attache.getFile());

        // Check if path directory not exist and create it
        String filePath = Environment.getExternalStorageDirectory() + "/myapp/" + lesson.getTitle() + "/";
        File path = new File(filePath);
        if (!path.exists() || !path.isDirectory()) {
            if (!path.mkdirs()) {
                Timber.e("Could not create path directory.");
            }
        }

        // Check if file exist and then delete it
        File file = new File(filePath, fileName);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                Timber.v("%s just deleted.", fileName);
            }
        }

        // Create download manager request using url
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setTitle(attache.getName());
        request.setDestinationInExternalPublicDir("/myapp/" + lesson.getTitle(), fileName);

        // Using DownloadManager for download attache file
        DownloadManager manager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
        manager.enqueue(request);
    }
}
```

答:
I have encountered the exception java.lang.IllegalArgumentException: Unknown URI: content://downloads/public_downloads/7505 in getting the doucument from the downloads. This solution worked for me.

```<code>else if (isDownloadsDocument(uri)) {
            String fileName = getFilePath(context, uri);
            if (fileName != null) {
                return Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
            }

            String id = DocumentsContract.getDocumentId(uri);
            if (id.startsWith("raw:")) {
                id = id.replaceFirst("raw:", "");
                File file = new File(id);
                if (file.exists())
                    return id;
            }

            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            return getDataColumn(context, contentUri, null, null);
        }
</code>```

This the method used to get the filepath

```<code>   public static String getFilePath(Context context, Uri uri) {

    Cursor cursor = null;
    final String[] projection = {
            MediaStore.MediaColumns.DISPLAY_NAME
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, null, null,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}
</code>```

Body:
I'm using Download Manger to download some multimedia files and categorize them. I'm also using Crashlytics and this is an error I frequently get on different devices and versions of Android:

java.lang.IllegalArgumentException: Unknown URL content://downloads/my_downloads
   at android.content.ContentResolver.insert(ContentResolver.java:862)
   at android.app.DownloadManager.enqueue(DownloadManager.java:1252)
   at com.myapp.LessonFragment$DownloadClickListener.onClick(SourceFile:570)
   at android.view.View.performClick(View.java:4262)
   at android.view.View$PerformClick.run(View.java:17351)
   at android.os.Handler.handleCallback(Handler.java:615)
   at android.os.Handler.dispatchMessage(Handler.java:92)
   at android.os.Looper.loop(Looper.java:137)
   at android.app.ActivityThread.main(ActivityThread.java:4921)
   at java.lang.reflect.Method.invokeNative(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:511)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
   at dalvik.system.NativeStart.main(NativeStart.java)

You can see my codes below:

private class DownloadClickListener implements View.OnClickListener {
    @Override
    public void onClick(View view) {
        // Check if download manager available before request
        if (!DownloadHelper.isDownloadManagerAvailable(getActivity())) {
            // Build custom alert dialog
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage(R.string.download_manager_disabled);
            builder.setCancelable(false);
            builder.setPositiveButton(R.string.ok, (dialog, which) -> {
                dialog.dismiss();
            });
            // Create and display alert dialog
            AlertDialog dialog = builder.create();
            dialog.show();
            return;
        }

        // Display short toast on download clicked
        Toast.makeText(getActivity(), R.string.lesson_download_start, Toast.LENGTH_SHORT).show();

        // Get attach from view tag
        Attache attache = (Attache) view.getTag();

        // Get lesson using lesson id
        Lesson lesson = new Select().from(Lesson.class)
                .where(Condition.column("id").is(attache.getLessonId()))
                .querySingle();

        // Set file name from url and attache name
        Uri uri = Uri.parse(attache.getFile());
        String fileName = attache.getName() + '.'
                + MimeTypeMap.getFileExtensionFromUrl(attache.getFile());

        // Check if path directory not exist and create it
        String filePath = Environment.getExternalStorageDirectory() + "/myapp/" + lesson.getTitle() + "/";
        File path = new File(filePath);
        if (!path.exists() || !path.isDirectory()) {
            if (!path.mkdirs()) {
                Timber.e("Could not create path directory.");
            }
        }

        // Check if file exist and then delete it
        File file = new File(filePath, fileName);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                Timber.v("%s just deleted.", fileName);
            }
        }

        // Create download manager request using url
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setTitle(attache.getName());
        request.setDestinationInExternalPublicDir("/myapp/" + lesson.getTitle(), fileName);

        // Using DownloadManager for download attache file
        DownloadManager manager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
        manager.enqueue(request);
    }
}

Body:
I have encountered the exception java.lang.IllegalArgumentException: Unknown URI: content://downloads/public_downloads/7505 in getting the doucument from the downloads. This solution worked for me.

else if (isDownloadsDocument(uri)) {
            String fileName = getFilePath(context, uri);
            if (fileName != null) {
                return Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
            }

            String id = DocumentsContract.getDocumentId(uri);
            if (id.startsWith("raw:")) {
                id = id.replaceFirst("raw:", "");
                File file = new File(id);
                if (file.exists())
                    return id;
            }

            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            return getDataColumn(context, contentUri, null, null);
        }

This the method used to get the filepath

   public static String getFilePath(Context context, Uri uri) {

    Cursor cursor = null;
    final String[] projection = {
            MediaStore.MediaColumns.DISPLAY_NAME
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, null, null,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


问:
what is the use of ! sign in some ruby methods

Possible Duplicate:

  Why are exclamation marks used in Ruby methods?

Hi All,

In ruby/rails I have seen some methods ended up with ! sign like

```<code>before_filter :authenticated!
</code>```

just wonder what does mean by authenticated!, '!' sign

thanks in advance

cheers

sameera

答:
Exclamation marks are used by convention in instance methods just to denote that the method is going to modify the instance itself.

While

```<code>mystring.gsub(..)
</code>```

won't modify mystring,

```<code>mystring.gsub!(..)
</code>```

will.

Body:
Possible Duplicate:

  Why are exclamation marks used in Ruby methods?

Hi All,

In ruby/rails I have seen some methods ended up with ! sign like

before_filter :authenticated!

just wonder what does mean by authenticated!, '!' sign

thanks in advance

cheers

sameera

Body:
Exclamation marks are used by convention in instance methods just to denote that the method is going to modify the instance itself.

While

mystring.gsub(..)

won't modify mystring,

mystring.gsub!(..)

will.


问:
Assign src as the txt file content by JavaScript
I have a file, name: 1.txt

In that .txt file I have a URL in the first line: https://example.com/logo.png

In this HTML code:

```<code><img id= 'summer' src=''>
</code>```

I want to assign the URL of that file as src by JavaScript. How can I do that? Any good idea?

I tried the following JavaScript code (But, it doesn't work):

const response = await fetch('1.txt');
const data = await response.text();
console.log(data);
$("#summer").attr('src', console.log(data));```

Thanks in advance!

答:
The return value of console.log() is always undefined

If you want to use the value of data as your attribute, then use the value of data and not of console.log(data)!

Body:
I have a file, name: 1.txt

In that .txt file I have a URL in the first line: https://example.com/logo.png

In this HTML code:

I want to assign the URL of that file as src by JavaScript. How can I do that? Any good idea?

I tried the following JavaScript code (But, it doesn't work):

const response = await fetch('1.txt');
const data = await response.text();
console.log(data);
$("#summer").attr('src', console.log(data));

Thanks in advance!


问:
Powershell or batch file help required with script for setting up a scheduled task
So we are all aware of this screen below

Windows Nag Screen - Click here to view image

I have multiple computers on a newwork that require to be rebooted in the middle of the night, they are supposed to be playing a video on them every reboot and it loops on a system.

this pop up nag screen keeps appearing on random systems and I need to remote into them and disable by pressing SKIP for now.

I have some questions

when you press Skip for now - will this screen pop up AGAIN at some stage?

can I run a batch file to kill this process and will it then come up again once I reboot the system?

can Powershell be run and remotely press the "skip for now" button on any machines if this screen exists on any of them? so I can set it up as a scheduled task or something after each reboot?

答:
Never seen this, but maybe

How to disable "Get even more out of Windows" on Windows 10

helps?

If not, you could try using "SendKeys": Supposed you could press Alt + "s" for "Skip for now" use this:

```<code>[System.Windows.Forms.SendKeys]::SendWait("%s")
</code>```

Body:
Never seen this, but maybe

How to disable "Get even more out of Windows" on Windows 10

helps?

If not, you could try using "SendKeys": Supposed you could press Alt + "s" for "Skip for now" use this:

[System.Windows.Forms.SendKeys]::SendWait("%s")


问:
How can I make part of the text in the Entry bold and change its background color?
I am creating a Tkinter-based GUI, and it has an Entry widget. I want to make a part of its text bold and change its background color. But I can't figure out how can I do that. If I use the Text widget I can just use tags but it looks like they can't be used with Entry widget:

This code is using the Text widget:

```<code>import tkinter as tk
from tkinter.font import Font

root = tk.Tk()
text = tk.Text(root, font=Font(size=12))
text.insert("1.0", "I want THIS PART to be bold and have red background")
text.tag_configure("bold-and-red", font=Font(size=12, weight="bold"), background="red")
text.tag_add("bold-and-red", "1.7", "1.16")
text.pack()
root.mainloop()
</code>```

Everything works fine (the Text widget is shown and "THIS PART" is bold and has a red background)

And this code is using the Entry widget:

```<code>import tkinter as tk
from tkinter.font import Font

root = tk.Tk()
entry = tk.Entry(root, font=Font(size=12))
entry.insert(0, "I want THIS PART to be bold and have red background")
entry.tag_configure("bold-and-red", font=Font(size=12, weight="bold"), background="red")
entry.tag_add("bold-and-red", 7, 16)
entry.pack()
root.mainloop()
</code>```

I just get the error:

AttributeError: 'Entry' object has no attribute 'tag_configure'

Is there a way to do what I want for Entry widget?

答:
How can I make part of the text in the Entry bold and change its background color? ... If I use the Text widget I can just use tags but it looks like they can't be used with Entry widget:

You are correct: you can't change the appearance of only some of the characters in an entry widget, other than through the selection mechanism.

If you want to change the appearance of only certain characters, you will need to use a one-line Text widget instead.

Body:
I am creating a Tkinter-based GUI, and it has an Entry widget. I want to make a part of its text bold and change its background color. But I can't figure out how can I do that. If I use the Text widget I can just use tags but it looks like they can't be used with Entry widget:

This code is using the Text widget:

import tkinter as tk
from tkinter.font import Font

root = tk.Tk()
text = tk.Text(root, font=Font(size=12))
text.insert("1.0", "I want THIS PART to be bold and have red background")
text.tag_configure("bold-and-red", font=Font(size=12, weight="bold"), background="red")
text.tag_add("bold-and-red", "1.7", "1.16")
text.pack()
root.mainloop()

Everything works fine (the Text widget is shown and "THIS PART" is bold and has a red background)

And this code is using the Entry widget:

import tkinter as tk
from tkinter.font import Font

root = tk.Tk()
entry = tk.Entry(root, font=Font(size=12))
entry.insert(0, "I want THIS PART to be bold and have red background")
entry.tag_configure("bold-and-red", font=Font(size=12, weight="bold"), background="red")
entry.tag_add("bold-and-red", 7, 16)
entry.pack()
root.mainloop()

I just get the error:

AttributeError: 'Entry' object has no attribute 'tag_configure'

Is there a way to do what I want for Entry widget?


问:
How to properly declare a self-referencing template type?
How do I declare a templated type that refers to itself?

```<code>template <class T = Animal> class Animal
{
public:
    T getChild ();
}
</code>```

With this, I get a compiler error concerning a missing type specifier. I tried to forward-declare Animal, without success.

I am trying to impose a type constraint. A Lion can only have a Lion as a child, a Bear has a Bear, and so on.

EDIT

I'll post part of the actual class. It is a template for classes that can appear in a linked list:

```<code>template <class T = Linked<T> > class Linked
{
private:
    T* m_prev;
    T* m_next;
}
</code>```

I want to enforce that the class can only point to object of the same class (or a subclass).

答:
The usual way to do something like a linked list is:

```<code>template <class T> class Linked
{
private:
    Linked<T>* m_prev;
    Linked<T>* m_next;
}
</code>```

Does this work for you, and if not, what are you trying to accomplish that can't be done this way?

Body:
How do I declare a templated type that refers to itself?

template <class T = Animal> class Animal
{
public:
    T getChild ();
}

With this, I get a compiler error concerning a missing type specifier. I tried to forward-declare Animal, without success.

I am trying to impose a type constraint. A Lion can only have a Lion as a child, a Bear has a Bear, and so on.

EDIT

I'll post part of the actual class. It is a template for classes that can appear in a linked list:

template <class T = Linked<T> > class Linked
{
private:
    T* m_prev;
    T* m_next;
}

I want to enforce that the class can only point to object of the same class (or a subclass).

Body:
The usual way to do something like a linked list is:

template <class T> class Linked
{
private:
    Linked<T>* m_prev;
    Linked<T>* m_next;
}

Does this work for you, and if not, what are you trying to accomplish that can't be done this way?


问:
VS Code "step into" debugger configuration
When I debug my C++ project in VS Code and toggle a breakpoint, The "step into" option redirecting me to external files/libraries, but I want to step only into my code.

I tried to add "justMyCode": true option in launch.js file, but it says this property is not allowed.

What can I do to go only through source code?

答:
One thing could be done for this issue. I actually tested my own test program:

```<code>std::vector<std::string> name;

std::cout << "Enter a name: ";
std::getline(std::cin, name);

nameList.push_back(name); // BREAKPOINT
</code>```

When we select Step Into in the breakpoint execution, it redirects into the definition of the function where it's actually defined, it's not going to debug only for your file in this case.

Step Into Type:

Rather, you must use Step Over since it doesn't tries to find the function definitions and you would able to debug your content straightforwardly.

Step Over Type:

The Step Into will certainly redirect you into the function definition wherever it's defined, if you want to know the declaration and other things about the related function, it's good opportunity to use Step Into. But in case you just want to debug the line only and not considering to go in depth and don't want to get jumped into another file, you must use Step Over.

If you want to know more about Step Into and Step Over, you can go through this Stack Overflow thread. I've found this helpful too.

Body:
One thing could be done for this issue. I actually tested my own test program:

std::vector<std::string> name;

std::cout << "Enter a name: ";
std::getline(std::cin, name);

nameList.push_back(name); // BREAKPOINT

When we select Step Into in the breakpoint execution, it redirects into the definition of the function where it's actually defined, it's not going to debug only for your file in this case.

Step Into Type:

Rather, you must use Step Over since it doesn't tries to find the function definitions and you would able to debug your content straightforwardly.

Step Over Type:

The Step Into will certainly redirect you into the function definition wherever it's defined, if you want to know the declaration and other things about the related function, it's good opportunity to use Step Into. But in case you just want to debug the line only and not considering to go in depth and don't want to get jumped into another file, you must use Step Over.

If you want to know more about Step Into and Step Over, you can go through this Stack Overflow thread. I've found this helpful too.


问:
pyspark bind issue cannot generate the SPARK UI
I am facing an issue with pyspark while running this in local mode. And the tricky thing is when I open cmd and run pyspark it creates a session and then if I open the localhost:4040 I can see the UI. But, if I run some program from pycharm I am not able to access the UI (localhost:4040) also the URL is not generated.

And in other case when I have the pyspark shell open in parallel with pycharm program and if I run the same program in pycharm I will get a warning saying cannot bind port 4040 so attempting 4041. which is a bit understandable as shell has occupied port 4040 so it is attempting 4041. So, ideally 4041 should be allocated but that is not the case. As the documentation says it attempts 16 times, to get the next free port number available, I have not been allocated with any. So, then if I see the services running currently on my PC, I could see none of them are using those ports.

Please help me with this.

答:
The warning "port 4040 is unaviable, attempting 4041" and forawrd..., is occures probably, because you open a a lot of SparkContext without close them.(SparkContext#close).

You can change the port if you want by the parameter spark.ui.port in configuration.

For your first issue, can you provide logs please of the running spark app? maybe you are running a fast program that close the web ui fast enough before you enter?


问:
Reusable way to assign a bi-directional record to another
I am using the UVVM AXI-Stream VVC. It defines the AxiStream interface as a record type, shortened in this question for brevity.

So, given this record type that contains signals going in both directions

```<code>  type t_axistream_if is record
    tdata  : std_logic_vector;  -- Going in
    tvalid : std_logic;         -- Going in
    tready : std_logic;         -- Going out
  end record;
</code>```

I want a re-usable method that can reorder the bytes in tdata and connect two instances of this record to each other.

This is the functionality that I am looking for. The following VHDL is functional:

```<code>   -- dutInput and axisMasterIf are constrained instances of the record.
   dutInput.tData      <= reverseBytes(axisMasterIf.tData);
   dutInput.tValid     <= axisMasterIf.tValid;
   axisMasterIf.tReady <= dutInput.tReady;
</code>```

What i want is something like this (because the record is much larger):

```<code>   dutInput            <= reverse(axisMasterIf);
   axisMasterIf.tReady <= dutInput.tReady;
   -- or using a procedure
   -- reverse(axisMasterIf, dutInput)
</code>```

When using procedures it doesn't seem like the signals are continuously assigned. When using functions i struggle with not assigning dutInput.tReady.

Here is a few, non-working, attempts:

```<code>   -- If I set outIf <= reverse(inIf) this function will drive the
   -- TReady-signal and I will get U due to multiple drivers.
   -- When I  set TReady as open, it just doesn't compile.
   function reverse(inIf : t_axistream_if) return t_axistream_if is
   begin
      return (
         tData  => reverseBytes(inIf.tData),
         tValid => inIf.tValid,
         tReady => open -- This doesn't compile.
      );
   end function;

   -- This compiles, but the signals don't seem to become continually assigned when the procedure is called from within a process.
   procedure reverse(
      signal inIf  : inout t_axistream_if;
      signal outIf : inout t_axistream_if
   ) is
   begin
      outIf.tData  <= reverseBytes(inIf.tData);
      outIf.tValid <= inIf.tValid;

      inIf.tReady <= outIf.tReady;
   end procedure;
</code>```

The code does not need to be synthesizable. I'm using VHDL2008.

答:
With respect to this block:

```<code>   -- This compiles, but the signals don't seem to become continually assigned when the procedure is called from within a process.
   procedure reverse(
      signal inIf  : inout t_axistream_if;
      signal outIf : inout t_axistream_if
   ) is
   begin
      outIf.tData  <= reverseBytes(inIf.tData);
      outIf.tValid <= inIf.tValid;

      inIf.tReady <= outIf.tReady;
   end procedure;
</code>```

... specifically:

... but the signals don't seem to become continually assigned when the procedure is called from within a process

All assignments in a (clocked) process turn into flip-flops.  Using your procedure reverse in a process will change the timing of the signals by adding an extra clock cycle of delay.  This is the expected behaviour.

However, that is likely not what you want.  You will want to use the procedure outside any process to ensure it is pass-through without any delay.

Body:
I am using the UVVM AXI-Stream VVC. It defines the AxiStream interface as a record type, shortened in this question for brevity.

So, given this record type that contains signals going in both directions

  type t_axistream_if is record
    tdata  : std_logic_vector;  -- Going in
    tvalid : std_logic;         -- Going in
    tready : std_logic;         -- Going out
  end record;

I want a re-usable method that can reorder the bytes in tdata and connect two instances of this record to each other.

This is the functionality that I am looking for. The following VHDL is functional:

   -- dutInput and axisMasterIf are constrained instances of the record.
   dutInput.tData      <= reverseBytes(axisMasterIf.tData);
   dutInput.tValid     <= axisMasterIf.tValid;
   axisMasterIf.tReady <= dutInput.tReady;

What i want is something like this (because the record is much larger):

   dutInput            <= reverse(axisMasterIf);
   axisMasterIf.tReady <= dutInput.tReady;
   -- or using a procedure
   -- reverse(axisMasterIf, dutInput)

When using procedures it doesn't seem like the signals are continuously assigned. When using functions i struggle with not assigning dutInput.tReady.

Here is a few, non-working, attempts:

   -- If I set outIf <= reverse(inIf) this function will drive the
   -- TReady-signal and I will get U due to multiple drivers.
   -- When I  set TReady as open, it just doesn't compile.
   function reverse(inIf : t_axistream_if) return t_axistream_if is
   begin
      return (
         tData  => reverseBytes(inIf.tData),
         tValid => inIf.tValid,
         tReady => open -- This doesn't compile.
      );
   end function;

   -- This compiles, but the signals don't seem to become continually assigned when the procedure is called from within a process.
   procedure reverse(
      signal inIf  : inout t_axistream_if;
      signal outIf : inout t_axistream_if
   ) is
   begin
      outIf.tData  <= reverseBytes(inIf.tData);
      outIf.tValid <= inIf.tValid;

      inIf.tReady <= outIf.tReady;
   end procedure;

The code does not need to be synthesizable. I'm using VHDL2008.

Body:
With respect to this block:

   -- This compiles, but the signals don't seem to become continually assigned when the procedure is called from within a process.
   procedure reverse(
      signal inIf  : inout t_axistream_if;
      signal outIf : inout t_axistream_if
   ) is
   begin
      outIf.tData  <= reverseBytes(inIf.tData);
      outIf.tValid <= inIf.tValid;

      inIf.tReady <= outIf.tReady;
   end procedure;

... specifically:

... but the signals don't seem to become continually assigned when the procedure is called from within a process

All assignments in a (clocked) process turn into flip-flops.  Using your procedure reverse in a process will change the timing of the signals by adding an extra clock cycle of delay.  This is the expected behaviour.

However, that is likely not what you want.  You will want to use the procedure outside any process to ensure it is pass-through without any delay.


问:
max value is not working for the EditorFor field in Razor
I have components and parts, both work and function the same but the 'Max' and 'Min' values aren't working for my editorFor's for my parts but they are working for my components?

Here is my code for my view page

```<code>    <h4><u><b>Component(s) Included</b></u></h4>
    <table class="table">
        <tr>
            <th>
                Actual Qty Received
            </th>
            <th>Date</th>
            <th>Notes</th>
        </tr>

        <tr>
            @if (Model.Components != null)
            {
                var orderedcomps = Model.dynamicComp_qty != null ? (int)Model.dynamicComp_qty : (int)Model.comp_qty;
                int receivedcomps = Model.actual_comp_qty != null ? (int)Model.actual_comp_qty : 0;
                var compremain = orderedcomps - receivedcomps;

                <td>
                    @Model.Components.ComponentIDLink
                </td>
                <td>
                    @Html.DisplayFor(model => model.Components.Name)
                </td>
                <td>
                    @compremain
                </td>
                <td>
                    @if (disableInput)
                    {
                        @Html.EditorFor(model => model.actual_comp_qty, new { htmlAttributes = new { @disabled = "true" } })
                    }
                    else
                    {
                        if (compremain < 0)
                        {
                            @Html.EditorFor(model => model.actual_comp_qty, new { htmlAttributes = new { @Value = 0, max = 0, min = compremain, onchange = "updateRows(this," + Model.Components.ID + ")" } })
                        }
                        else {
                        @Html.EditorFor(model => model.actual_comp_qty, new { htmlAttributes = new { @Value = 0, max = compremain, min = 0, onchange = "updateRows(this," + Model.Components.ID + ")" } })
                        }

                    }
                </td>
                <td></td>
            }
        </tr>
    </table>
    <h4><u><b>Part(s) Included</b></u></h4>
    <table class="table">
        <tr>
            <th>
                Actual Qty Received
            </th>
            <th>Date</th>
            <th>Notes</th>
        </tr>

        <tr>
            @if (Model.Parts != null)
            {
                var orderedparts = Model.dynamicPart_qty != null ? (int)Model.dynamicPart_qty : (int)Model.part_qty;
                int receivedparts = Model.actual_part_qty != null ? (int)Model.actual_part_qty : 0;
                var partremain = orderedparts - receivedparts;

                <td>
                    @if (disableInput)
                    {
                        @Html.EditorFor(model => model.actual_part_qty, new { htmlAttributes = new { @disabled = "true" } })
                    }
                    else
                    {
                        if (partremain < 0)
                        {
                            @Html.EditorFor(model => model.actual_part_qty, new { htmlAttributes = new { @Value = 0, max = 0, min = partremain, onchange = "updateRows(this," + Model.Parts.ID + ")" } })
                        }
                        else
                        {
                            @Html.EditorFor(model => model.actual_part_qty, new { htmlAttributes = new { @Value = 0, max = partremain, min = partremain, onchange = "updateRows(this," + Model.Parts.ID + ")" } })
                        }

                    }
                </td>
            }
        </tr>
</code>```

I have verified that partremain has a value and I even changed it to a number for testing purposes but it still doesn't work. It was working a few days ago and nothing has changed in code to have it not work but the validation isn't.

This seems like an Visual Studio Glitch but I'm not too sure how to fix it

Here is the rendered html

UI

The component only lets me enter 0-5

but I can enter any qty I want for the part

答:
Update:

Fixed by changing my editorFor to look like this

```<code> @Html.EditorFor(model => model.actual_part_qty, new { htmlAttributes = new { type = "number", max = partremain, min = 0, step = 1, onchange = "updateRows(this," + Model.Parts.ID + ")" } })

</code>```

Body:
I have components and parts, both work and function the same but the 'Max' and 'Min' values aren't working for my editorFor's for my parts but they are working for my components?

Here is my code for my view page

Component(s) Included

                Actual Qty Received

            Date
            Notes

            @if (Model.Components != null)
            {
                var orderedcomps = Model.dynamicComp_qty != null ? (int)Model.dynamicComp_qty : (int)Model.comp_qty;
                int receivedcomps = Model.actual_comp_qty != null ? (int)Model.actual_comp_qty : 0;
                var compremain = orderedcomps - receivedcomps;

                    @Model.Components.ComponentIDLink

                    @Html.DisplayFor(model => model.Components.Name)

                    @compremain

                    @if (disableInput)
                    {
                        @Html.EditorFor(model => model.actual_comp_qty, new { htmlAttributes = new { @disabled = "true" } })
                    }
                    else
                    {
                        if (compremain < 0)
                        {
                            @Html.EditorFor(model => model.actual_comp_qty, new { htmlAttributes = new { @Value = 0, max = 0, min = compremain, onchange = "updateRows(this," + Model.Components.ID + ")" } })
                        }
                        else {
                        @Html.EditorFor(model => model.actual_comp_qty, new { htmlAttributes = new { @Value = 0, max = compremain, min = 0, onchange = "updateRows(this," + Model.Components.ID + ")" } })
                        }

                    }

            }

Part(s) Included

                Actual Qty Received

            Date
            Notes

            @if (Model.Parts != null)
            {
                var orderedparts = Model.dynamicPart_qty != null ? (int)Model.dynamicPart_qty : (int)Model.part_qty;
                int receivedparts = Model.actual_part_qty != null ? (int)Model.actual_part_qty : 0;
                var partremain = orderedparts - receivedparts;

                    @if (disableInput)
                    {
                        @Html.EditorFor(model => model.actual_part_qty, new { htmlAttributes = new { @disabled = "true" } })
                    }
                    else
                    {
                        if (partremain < 0)
                        {
                            @Html.EditorFor(model => model.actual_part_qty, new { htmlAttributes = new { @Value = 0, max = 0, min = partremain, onchange = "updateRows(this," + Model.Parts.ID + ")" } })
                        }
                        else
                        {
                            @Html.EditorFor(model => model.actual_part_qty, new { htmlAttributes = new { @Value = 0, max = partremain, min = partremain, onchange = "updateRows(this," + Model.Parts.ID + ")" } })
                        }

                    }

            }

I have verified that partremain has a value and I even changed it to a number for testing purposes but it still doesn't work. It was working a few days ago and nothing has changed in code to have it not work but the validation isn't.

This seems like an Visual Studio Glitch but I'm not too sure how to fix it

Here is the rendered html

UI

The component only lets me enter 0-5

but I can enter any qty I want for the part

Body:
Update:

Fixed by changing my editorFor to look like this

 @Html.EditorFor(model => model.actual_part_qty, new { htmlAttributes = new { type = "number", max = partremain, min = 0, step = 1, onchange = "updateRows(this," + Model.Parts.ID + ")" } })


问:
Chartjs-plugin: How to add a different color to each label?
I have a piechart made with chartjs. I then added a label on each pie thanks to chart-js plugin. Sometimes, the pie background is a bit light, so my white text is not visible enough. I've made a function that check the contrast and color it to black in such a case.

But when applied to chartjs-plugin's label color property, the function runs only once, and keep the same color for all label. How to apply a different color to each label based on its background?

Here is the code:

 plugins: {
                datalabels: {
                  color: function(ctx: any) {
                    [...Array(ctx.dataset.data.length)].map((_, i) => {
                      return transformColor(ctx.dataset.backgroundColor[i]);
                    });
                  },```

Thanks!

EDIT:

here is the rendering of my current piechart:

答:
you need to provide backgroundColor: [] in Pie Chart for background color. Here is the complete example:

```<code>import React from "react";
import {makeStyles} from "@material-ui/core/styles";
import {Pie} from "react-chartjs-2";

const useStyles = makeStyles(theme => ({
    chart: {
        marginLeft: theme.spacing(2)
    }
}));

export default function PieChartExample(props) {
    const classes = useStyles();
    const [data, setdata] = React.useState({
        labels: ["type1", "type2", "type3", "type4"],
        datasets: [
            {
                label: "No. of registrations made",
                backgroundColor: [
                    "#3e95cd",
                    "#8e5ea2",
                    "#3cba9f",
                    "#e8c3b9",
                    "#c45850"
                ],
                barThickness: 80,
                data: [50, 100, 75, 20, 0]
            }
        ]
    });

    const getChartData = canvas => {
        return data;
    };
    return (
        <React.Fragment>
            <div
                className={classes.chart}
                style={{position: "relative", width: 900, height: 450}}
            >
                <Pie
                    options={{
                        responsive: true,
                        maintainAspectRatio: true,
                        legend: {display: true},
                        title: {
                            display: true,
                            text: "Title for the graph"
                        }
                    }}
                    onElementsClick={(e) => { console.log(e, 'e')}}
                    data={getChartData}
                />
            </div>
        </React.Fragment>
    );
}
</code>```

Body:
I have a piechart made with chartjs. I then added a label on each pie thanks to chart-js plugin. Sometimes, the pie background is a bit light, so my white text is not visible enough. I've made a function that check the contrast and color it to black in such a case.

But when applied to chartjs-plugin's label color property, the function runs only once, and keep the same color for all label. How to apply a different color to each label based on its background?

Here is the code:

 plugins: {
                datalabels: {
                  color: function(ctx: any) {
                    [...Array(ctx.dataset.data.length)].map((_, i) => {
                      return transformColor(ctx.dataset.backgroundColor[i]);
                    });
                  },

Thanks!

EDIT:

here is the rendering of my current piechart:

Body:
you need to provide backgroundColor: [] in Pie Chart for background color. Here is the complete example:

import React from "react";
import {makeStyles} from "@material-ui/core/styles";
import {Pie} from "react-chartjs-2";

const useStyles = makeStyles(theme => ({
    chart: {
        marginLeft: theme.spacing(2)
    }
}));

export default function PieChartExample(props) {
    const classes = useStyles();
    const [data, setdata] = React.useState({
        labels: ["type1", "type2", "type3", "type4"],
        datasets: [
            {
                label: "No. of registrations made",
                backgroundColor: [
                    "#3e95cd",
                    "#8e5ea2",
                    "#3cba9f",
                    "#e8c3b9",
                    "#c45850"
                ],
                barThickness: 80,
                data: [50, 100, 75, 20, 0]
            }
        ]
    });

    const getChartData = canvas => {
        return data;
    };
    return (
        <React.Fragment>
            <div
                className={classes.chart}
                style={{position: "relative", width: 900, height: 450}}
            >
                <Pie
                    options={{
                        responsive: true,
                        maintainAspectRatio: true,
                        legend: {display: true},
                        title: {
                            display: true,
                            text: "Title for the graph"
                        }
                    }}
                    onElementsClick={(e) => { console.log(e, 'e')}}
                    data={getChartData}
                />
            </div>
        </React.Fragment>
    );
}


问:
Angular - boolean value doesn't change
I'm facing issue with my app.
I'm trying to create a list of checkboxes, when the checkbox is clicked the value should be true and when clicked again the value should be false. Simple.

Here is my html

```<code>  <li *ngFor="let checkbox of checkboxSelect">
      <div class="checkbox-style">
          <input type="checkbox" name ="{{checkbox.inputName}}"
                [checked]="checkbox.name"
                (change)="checkbox.name= !checkbox.name"/>
             <div class="state">
                 <label>{{checkbox.label}}</label>
             </div>
      </div>
  </li>
</code>```

Here is my component.ts

```<code>showFirstName = true;
showLastName = true;

checkboxSelect: any[] = [{
        label: 'First name',
        name: this.showFirstName,
        inputName: 'showFirstName'
    }, {
        label: 'Last name',
        name: this.showLastName,
        inputName: 'showLastName'

    },
];
</code>```

Everything is working except my 'name' value doesn't change to true/false when clicked.

On the other hand when I put that straight to html without *ngFor it's working

```<code>  <li>
      <div class="checkbox-style">
          <input type="checkbox" name = "firstName"
                [checked]="showFirstName"
                (change)="showFirstName = !showFirstName"/>
             <div class="state">
                 <label>First Name</label>
             </div>
      </div>
  </li>
</code>```

I wasn't so clear, my goal is to display divs depend on true/false

```<code> <div *ngIf="showFirstName" scope="col">First name</div>
<div *ngIf="showLastName" scope="col">Second name</div>
</code>```

But it doesn't change at all.

Does anyone have an idea what's wrong with my code?

答:
Based on your comment, you are trying to use variables showFirstName and showLastName that aren't modified by the event handler to show/hide strings First Name and Last Name. To make the value binding persist between two variables, you could make them objects. Objects are usually passed by reference in Javascript. Try the following

Controller

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  showFirstName = { status: true };
  showLastName = { status: true };

  checkboxSelect: any[] = [{
    label: 'First name',
    name: this.showFirstName,
    inputName: 'showFirstName'
  }, {
    label: 'Last name',
    name: this.showLastName,
    inputName: 'showLastName'

  }, ];

  checkStatus() {
    console.log(this.checkboxSelect[0].name, this.checkboxSelect[1].name);
  }
}
```

<p>Template</p>

<pre class="lang-html prettyprint-override"><code><li *ngFor="let checkbox of checkboxSelect">
  <div class="checkbox-style">
    <input type="checkbox" name="{{checkbox.inputName}}" [checked]="checkbox.name.status"
      (change)="checkbox.name.status = !checkbox.name.status; checkStatus()" />
    <div class="state">
      <label>{{checkbox.label}}</label>
    </div>
  </div>
</li>

<table>
  <th *ngIf="showFirstName.status" scope="col">First Name</th>
  <th *ngIf="showLastName.status" scope="col">Last Name</th>
</table>
</code>```

Note: Using object reference to control the state of variables could get very tangled later in development. Better way would be to think of a different structure.

Working example: Stackblitz

Title: Angular - boolean value doesn't change

Body:
I'm facing issue with my app.
I'm trying to create a list of checkboxes, when the checkbox is clicked the value should be true and when clicked again the value should be false. Simple.

Here is my html

          <input type="checkbox" name ="{{checkbox.inputName}}"
                [checked]="checkbox.name"
                (change)="checkbox.name= !checkbox.name"/>

                 {{checkbox.label}}

Here is my component.ts

showFirstName = true;
showLastName = true;

checkboxSelect: any[] = [{
        label: 'First name',
        name: this.showFirstName,
        inputName: 'showFirstName'
    }, {
        label: 'Last name',
        name: this.showLastName,
        inputName: 'showLastName'

    },
];

Everything is working except my 'name' value doesn't change to true/false when clicked.

On the other hand when I put that straight to html without *ngFor it's working

          <input type="checkbox" name = "firstName"
                [checked]="showFirstName"
                (change)="showFirstName = !showFirstName"/>

                 First Name

I wasn't so clear, my goal is to display divs depend on true/false

First name

Second name

But it doesn't change at all.

Does anyone have an idea what's wrong with my code?

Body:
Based on your comment, you are trying to use variables showFirstName and showLastName that aren't modified by the event handler to show/hide strings First Name and Last Name. To make the value binding persist between two variables, you could make them objects. Objects are usually passed by reference in Javascript. Try the following

Controller

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  showFirstName = { status: true };
  showLastName = { status: true };

  checkboxSelect: any[] = [{
    label: 'First name',
    name: this.showFirstName,
    inputName: 'showFirstName'
  }, {
    label: 'Last name',
    name: this.showLastName,
    inputName: 'showLastName'

  }, ];

  checkStatus() {
    console.log(this.checkboxSelect[0].name, this.checkboxSelect[1].name);
  }
}

Template

<li *ngFor="let checkbox of checkboxSelect">
  <div class="checkbox-style">
    <input type="checkbox" name="{{checkbox.inputName}}" [checked]="checkbox.name.status"
      (change)="checkbox.name.status = !checkbox.name.status; checkStatus()" />
    <div class="state">
      <label>{{checkbox.label}}</label>
    </div>
  </div>
</li>

<table>
  <th *ngIf="showFirstName.status" scope="col">First Name</th>
  <th *ngIf="showLastName.status" scope="col">Last Name</th>
</table>

Note: Using object reference to control the state of variables could get very tangled later in development. Better way would be to think of a different structure.

Working example: Stackblitz