问:
R how to calculate the most cases?
```<code>df <- read.csv ('https://raw.githubusercontent.com/ulklc/covid1-timeseries/master/countryReport/raw/rawReport.csv',
                stringsAsFactors = FALSE)
</code>```

Using this dataset, how can I find the number of patients in the 5 countries with the most cases?

Then, how can I draw the number of patients as line graph?

答:
To find the countries with most patients

```<code>library(tidyverse)

df %>%
  group_by(countryName) %>%
  summarise(total = max(confirmed)) %>%
  arrange(desc(total)) %>%
  top_n(5) -> countries5

countries5
## A tibble: 5 x 2
#  countryName      total
#  <chr>            <int>
#1 United States  1768116
#2 Brazil          438812
#3 Russia          379051
#4 Spain           284986
#5 United Kingdom  269127
</code>```

To plot their confirmed cases evolution.

```<code>countries5 %>%
  left_join(df, by = 'countryName') %>%
  select(countryCode, confirmed, day) %>%
  mutate(day = as.Date(day)) %>%
  filter(confirmed > 0) %>%
  ggplot(aes(day, confirmed, color = countryCode)) +
  geom_line()
</code>```

Title: R how to calculate the most cases?

Body:
df <- read.csv ('https://raw.githubusercontent.com/ulklc/covid1-timeseries/master/countryReport/raw/rawReport.csv',
                stringsAsFactors = FALSE)

Using this dataset, how can I find the number of patients in the 5 countries with the most cases?

Then, how can I draw the number of patients as line graph?

Body:
To find the countries with most patients

library(tidyverse)

df %>%
  group_by(countryName) %>%
  summarise(total = max(confirmed)) %>%
  arrange(desc(total)) %>%
  top_n(5) -> countries5

countries5
## A tibble: 5 x 2
#  countryName      total
#  <chr>            <int>
#1 United States  1768116
#2 Brazil          438812
#3 Russia          379051
#4 Spain           284986
#5 United Kingdom  269127

To plot their confirmed cases evolution.

countries5 %>%
  left_join(df, by = 'countryName') %>%
  select(countryCode, confirmed, day) %>%
  mutate(day = as.Date(day)) %>%
  filter(confirmed > 0) %>%
  ggplot(aes(day, confirmed, color = countryCode)) +
  geom_line()


来源: stackexchange

问:
What should be change in the "gender" part of the coding I have done below?
In the code below keeps on looping where entering 1 will lead in the void main() function and inside it, there is "gender" information. However, the gender output always got skipped over right after I type the date.

The "Enter your gender(Male/Female): " part got skipped

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void entry() {
    FILE *fpointer;
    char name[20], gender[20], op, option;
    int visit_ID, phone_number, service_needed, change_service, date;
    float service_fee, payment_made, changes, change_service_fee;

    printf("\n\nEnter information:\n");
    printf("\nEnter name: ");
    scanf("%s", name);
    printf("\n\nEnter your ID number(Number only): ");
    scanf("%d", &visit_ID);
    printf("\n\nEnter today date in dd-mm-yy: ");
    scanf("%d", &date);
    printf("\n\nEnter your gender(Male/Female): ");
    scanf("%s", &gender);
    printf("\n\nEnter your phone number: ");
    scanf("%d", &phone_number);
    printf("\n\nDone registered\n\n");

    if ((fpointer = fopen("visitdetails.txt", "a")) == NULL) {
        perror("Write");
        exit(1);
    }
    fprintf(fpointer, "Visit ID = %d", visit_ID);
    fprintf(fpointer, "\nCustomer name = %s", name);
    fprintf(fpointer, "\nLast visit date : %d", date);
    fprintf(fpointer, "\nLast Service type repaired: %d", service_needed);
    fscanf(fpointer, "%d", service_needed);
    fprintf(fpointer, "\nLast Service fee: %.2f", service_fee);
    fprintf(fpointer, "\nLast payment: %.2f", payment_made);
    printf("\n\nRecord Written Successfully\n\n!!!");
    fclose(fpointer);
}

void Repair() {
    char name[20], gender[20], op, option;
    int visit_ID, phone_number, service_needed, date;
    float service_fee, payment_made, changes, change_service_fee;
    FILE *Welcome;

    Welcome = fopen("visitdetails.txt", "r");
    printf("\nWhich service type do you need(1-8)? ");
    scanf("%d", &service_needed);

    switch (service_needed) {
      case 1:
        printf("\nThe cost of it will be 30RM for Normal and 50RM for Urgent(type the cost): ");
        scanf("%f", &service_fee);
        break;

      case 2:
        printf("\nThe cost of it will be 40RM for Normal and 70RM for Urgent(type the cost): ");
        scanf("%f", &service_fee);
        break;

      case 3:
        printf("\nThe cost of it will be 330RM for Normal and 430RM for Urgent(type the cost): ");
        scanf("%f", &service_fee);
        break;

      case 4:
        printf("\nThe cost of it will be 160RM for Normal and 200RM for Urgent(type the cost): ");
        scanf("%f", &service_fee);
        break;

      case 5:
        printf("\nThe cost of it will be 180RM for Normal and 210RM for Urgent(type the cost): ");
        scanf("%f", &service_fee);
        break;

      case 6:
        printf("\nThe cost of it will be 50RM for Normal and 80RM for Urgent(type the cost): ", service_fee);
        scanf("%f", &service_fee);
        break;

      case 7:
        printf("\nThe cost of it will be 100RM for Normal and 150RM for Urgent(type the cost): ", service_fee);
        scanf("%f", &service_fee);
        break;

      case 8:
        printf("\nThe cost of it will be 50RM for Normal and 75RM for Urgent(type the cost): ", service_fee);
        scanf("%f", &service_fee);
        break;

      default:
        printf("Invalid option");
    }

    printf("\n\nPayment: ", payment_made);
    scanf("%f", &payment_made);

    if (payment_made > service_fee) {
        changes = payment_made - service_fee;
        printf("\nHere is your changes :%.2f\n", changes);
    }
    fclose(Welcome);
}

void Viewing_Store() {
    FILE *view;
    view = fopen("visitdetails.txt", "r");

    printf("No |    Service Type                                    | Needed Days | Service Fee | \n");
    printf("                                                                      |Normal|Urgent|\n");
    printf("1. | Remove virus,Malware, or Spyware                   |      2      | 30RM | 50RM |\n");
    printf("2. | Troubleshot and fix computer running slow          |      2      | 40RM | 70RM |\n");
    printf("3. | Laptop Screen Replacement                          |      3      | 330RM| 430RM|\n");
    printf("4. | Laptop Keyboard Replacement                        |      2      | 160RM| 200RM|\n");
    printf("5. | Laptop Battery Replacement                         |      1      | 180RM| 210RM|\n");
    printf("6. | Operating System Format and Installation           |      2      | 50RM | 80RM |\n");
    printf("7. | Data Backup and Recovery                           |      2      | 100RM| 150RM|\n");
    printf("8. | Internet Connectivity issues                       |      1      | 50RM | 75RM |\n");

    fclose(view);
}

void change_type() {
    FILE *change;
    char name[20], gender[20], op, option;
    int visit_ID, phone_number, service_needed, change_service, date;
    float service_fee, payment_made, changes, change_service_fee;

    change = fopen("visitdetails.txt", "r");
    printf("\nAre you sure you want to change the service type into(Y/N) : ", op);
    scanf("%s", &op);
    if (op == 'Y') {
        printf("\nWhat service type do you want to change into(1-8)? ", change_service);
        scanf("%d", &change_service);
        switch (change_service) {
          case 1:
            printf("\nThe cost of it will be 30RM for Normal and 50RM for Urgent(type the cost): ", change_service_fee);
            scanf("%f", &change_service_fee);
            break;

          case 2:
            printf("\nThe cost of it will be 40RM for Normal and 70RM for Urgent(type the cost): ", change_service_fee);
            scanf("%f", &change_service_fee);
            break;

          case 3:
            printf("\nThe cost of it will be 330RM for Normal and 430RM for Urgent(type the cost): ", change_service_fee);
            scanf("%f", &change_service_fee);
            break;

          case 4:
            printf("\nThe cost of it will be 160RM for Normal and 200RM for Urgent(type the cost): ", change_service_fee);
            scanf("%f", &change_service_fee);
            break;

          case 5:
            printf("\nThe cost of it will be 180RM for Normal and 210RM for Urgent(type the cost): ", change_service_fee);
            scanf("%f", &change_service_fee);
            break;

          case 6:
            printf("\nThe cost of it will be 50RM for Normal and 80RM for Urgent(type the cost): ", change_service_fee);
            scanf("%f", &change_service_fee);
            break;

          case 7:
            printf("\nThe cost of it will be 100RM for Normal and 150RM for Urgent(type the cost): ", change_service_fee);
            scanf("%f", &change_service_fee);
            break;

          case 8:
            printf("\nThe cost of it will be 50RM for Normal and 75RM for Urgent(type the cost): ", change_service_fee);
            scanf("%f", &change_service_fee);
            break;

          default:
            printf("Invalid option");
        }
    } else
    if (op == 'N') {
        printf("\nThe final price will be : %.2f", service_fee);
    }

    printf("\n\nPayment: ", payment_made);
    scanf("%f", &payment_made);

    if (payment_made > service_fee) {
        changes = payment_made - service_fee;
        printf("\nHere is your changes :%.2f\n", changes);
    } else
    if (payment_made > change_service_fee) {
        changes = payment_made - change_service_fee;
        printf("\nHere is your changes: %.2f\n", changes);
    } else
    if (payment_made == service_fee) {
        changes = payment_made - service_fee;
        printf("\nHere is your changes %f\n", changes);
    } else
    if (payment_made == change_service_fee) {
        changes = payment_made - change_service_fee;
        printf("\nHere is your changes: %f\n", changes);
    } else {
        printf("Error");
    }

    fprintf(change, "\n\nChanging service type into: %d", change_service);
    fprintf(change, "\nThe price of this service type is: %f", change_service_fee);
    fprintf(change,"\nPayment: %.2f", payment_made);
    fclose(change);
}

void any_visit(char anv[]) {
    FILE *anyvisit;
    char name[200], gender[20];
    int visit_ID, phone_number, service_needed, change_service, date, set;
    float service_fee, payment_made, changes, change_service_fee;

    anyvisit = fopen("visitdetails.txt","r");
    while (fscanf(any_visit, "%s %d %d %s %d %d\n", name, visit_ID, date, gender, phone_number, payment_made) != EOF) {
        set = strcmp(date, anv);
        if (set == 0) {
            printf("Visit_ID is %d", visit_ID);
            printf("\nName : %s", name);
            printf("\nGender is %s", gender);
            printf("\nPhone number is %d", phone_number);
            printf("\nPayment : %.2f", payment_made);
        }
    }
    fclose(anyvisit);
}

void search(char cnm[]) {
    FILE *search;
    char name[200], gender[20];
    int visit_ID, phone_number, service_needed, change_service, date, tes;
    float service_fee, payment_made, changes, change_service_fee;

    search = fopen("visitdetails.txt","r");
    while (fscanf(search, "%s %d %d %s %d %d\n", name, visit_ID, date, gender, phone_number, payment_made) != EOF) {
        tes = strcmp(name, cnm);
        if (tes == 0) {
            printf("Visit_ID is %d", visit_ID);
            printf("Date of visit is %d", date);
            printf("\nGender is %s", gender);
            printf("\nPhone number is %d", phone_number);
            printf("\nPayment: %d", date);
        }
    }
    fclose(search);
}

void main() {
    char name[200], gender[20], op, option, ch, cnm[30], anv[30];
    int visit_ID, phone_number, service_needed, change_service, date;
    float service_fee, payment_made, changes, change_service_fee;

    printf("*****Welcome to the Computer center*****\n");
    printf("\nBefore entering the store and have your equipment repair, it is best to view the store\n");
    do {
        printf("\nPress '1' to enter and have your data store");
        printf("\nPress '2' to View the store");
        printf("\nPress '3' to have your equipment being repaired");
        printf("\nPress '4' if you want to change your repair type");
        printf("\nPress '5' if you want to Search");
        printf("\nPress '6' if you want to search payment and unpaid balance by any visit");
        printf("\nPress '0' to exit");
        printf("\nEnter your choice : ");
        scanf("%d", &ch);
        switch(ch) {
          case 1:
            entry();
            break;
          case 2:
            Viewing_Store();
            break;
          case 3:
            Repair();
            break;
          case 4:
            change_type();
            break;
          case 5:
            printf("Enter your name: ");
            scanf("%s", &cnm);
            search(cnm);
            break;
          case 6:
            printf("Enter the date you visit: ");
            scanf("%d", &anv);
            any_visit(anv);
            break;
          case 0:
            exit(0);
          default:
            printf("\nInvalid Entry!!! ");
        }
    } while (ch != 0);
}
```

答:
As you mentioned above, We cannot give Gender.
Since you used int datatype for Storing the date, but you asked to give in dd-mm-yy format.

*To prove that give any "number" of int type in this prompt Enter today date in dd-mm-yy: and You can see that the program prompts for the  Gender.*

we cannot store dd-mm-yy this  format in int type.

so you can do in another ways

To store date as Char array  OR

To store day,month,year in individual int variables  OR

To use Struct datatype

ContentLicense: CC BY-SA 4.0


问:
AgGrid crashes on re-render in React application
I have a React + Typescript application that displays data using AgGrid. The data is fetched from a server and then fed to AgGrid, and we have multiple options that the user can interact with that could potentially change the data displayed, such as Filters, paging, and some other custom stuff.

The data that is displayed is first fetched and then displayed in full. For example, we fetch 25 rows and display all of them, we are not using any of AgGrid's paging features.

If a user makes a change to one of the parameters and the data doesn't change (for example, adding a filter which captures every single item already displayed), the data will be re-fetched, and then fed to AgGrid again, however this will cause AgGrid to crash.

This only happens when the data doesn't change.

The error that is occuring is the following:

```<code>The above error occurred in the <AgGridReact> component:
    in AgGridReact (at ag-collections/index.tsx:250)
    in div (at ag-collections/index.tsx:240)
    in div (created by ForwardRef(Paper))
    in ForwardRef(Paper) (created by WithStyles(ForwardRef(Paper)))
    in WithStyles(ForwardRef(Paper)) (at ag-collections/index.tsx:225)
    in main (at main/index.tsx:59)
    in div (at main/index.tsx:36)
    in Component (created by WithStyles(Component))
    in WithStyles(Component) (at ag-collections/index.tsx:218)
    in TableAg (created by Context.Consumer)
    in Connect(TableAg) (created by Connect(TableAg))
    in Connect(TableAg) (created by Context.Consumer)
    in withRouter(Connect(TableAg)) (created by WithStyles(withRouter(Connect(TableAg))))
    in WithStyles(withRouter(Connect(TableAg))) (created by Context.Consumer)
    in Route (at routes.tsx:20)
    in Switch (at routes.tsx:16)
    in Routes (at app.tsx:50)
    in ThemeProvider (at app.tsx:48)
    in Route (created by QueryParamProvider)
    in QueryParamProvider (at app.tsx:47)
    in Provider (at app.tsx:46)
    in App (at src/index.tsx:8)
    in Router (created by HashRouter)
    in HashRouter (at src/index.tsx:7)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit <link removed> to learn more about error boundaries. index.js:1437
TypeError: can't define property "areEquivPropertyTracking": Array is not extensible
changeDetectionService.js:147
TypeError: can't define property "areEquivPropertyTracking": Array is not extensible
</code>```

The line in question in changeDetectionService.js is:

      if (newA) {
        a.areEquivPropertyTracking = []; // LINE 147
      } else if (a.areEquivPropertyTracking.some(function (other) {
        return other === b;
      })) return true;

      if (newB) {
        b.areEquivPropertyTracking = [];
      } else if (b.areEquivPropertyTracking.some(function (other) {
        return other === a;
      })) {
        return true;
      }

```

As far as I can tell, they are trying to create a new item on the object a, but this is being forbidden.

If I need to provide anything else I can try to do so. How can I go about fixing this?

答:
If the data that is being provided is immutable, then you won't be able to perform a deep check as this attempts to extend the objects provided.

There are, however, multiple data change detection strategies that can be used.

I solved this issue by adding the following to the AgGridReact component:

import { ChangeDetectionStrategyType } from 'ag-grid-react/lib/changeDetectionService'
...
<AgGridReact
rowDataChangeDetectionStrategy={ChangeDetectionStrategyType.IdentityCheck}
...
/>
```

which will be sufficient.

I was lead to this by this github answer by @benhodeda, which says:

hi :)
  I had a similar problem when I've migrated our state object to use immer instead of immutableJS .
  We bind the state to AgGridReact's rowData prop, and when we filter the data (server-side filtering) the app was crash while doing change detection. I added deltaRowDataMode prop alongside with getRowNodeId={row => row.id} on AgGridReact component.

you can read more here: https://www.ag-grid.com/javascript-grid-data-update/

Body:
I have a React + Typescript application that displays data using AgGrid. The data is fetched from a server and then fed to AgGrid, and we have multiple options that the user can interact with that could potentially change the data displayed, such as Filters, paging, and some other custom stuff.

The data that is displayed is first fetched and then displayed in full. For example, we fetch 25 rows and display all of them, we are not using any of AgGrid's paging features.

If a user makes a change to one of the parameters and the data doesn't change (for example, adding a filter which captures every single item already displayed), the data will be re-fetched, and then fed to AgGrid again, however this will cause AgGrid to crash.

This only happens when the data doesn't change.

The error that is occuring is the following:

The above error occurred in the <AgGridReact> component:
    in AgGridReact (at ag-collections/index.tsx:250)
    in div (at ag-collections/index.tsx:240)
    in div (created by ForwardRef(Paper))
    in ForwardRef(Paper) (created by WithStyles(ForwardRef(Paper)))
    in WithStyles(ForwardRef(Paper)) (at ag-collections/index.tsx:225)
    in main (at main/index.tsx:59)
    in div (at main/index.tsx:36)
    in Component (created by WithStyles(Component))
    in WithStyles(Component) (at ag-collections/index.tsx:218)
    in TableAg (created by Context.Consumer)
    in Connect(TableAg) (created by Connect(TableAg))
    in Connect(TableAg) (created by Context.Consumer)
    in withRouter(Connect(TableAg)) (created by WithStyles(withRouter(Connect(TableAg))))
    in WithStyles(withRouter(Connect(TableAg))) (created by Context.Consumer)
    in Route (at routes.tsx:20)
    in Switch (at routes.tsx:16)
    in Routes (at app.tsx:50)
    in ThemeProvider (at app.tsx:48)
    in Route (created by QueryParamProvider)
    in QueryParamProvider (at app.tsx:47)
    in Provider (at app.tsx:46)
    in App (at src/index.tsx:8)
    in Router (created by HashRouter)
    in HashRouter (at src/index.tsx:7)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit <link removed> to learn more about error boundaries. index.js:1437
TypeError: can't define property "areEquivPropertyTracking": Array is not extensible
changeDetectionService.js:147
TypeError: can't define property "areEquivPropertyTracking": Array is not extensible

The line in question in changeDetectionService.js is:

      if (newA) {
        a.areEquivPropertyTracking = []; // LINE 147
      } else if (a.areEquivPropertyTracking.some(function (other) {
        return other === b;
      })) return true;

      if (newB) {
        b.areEquivPropertyTracking = [];
      } else if (b.areEquivPropertyTracking.some(function (other) {
        return other === a;
      })) {
        return true;
      }

As far as I can tell, they are trying to create a new item on the object a, but this is being forbidden.

If I need to provide anything else I can try to do so. How can I go about fixing this?

Body:
If the data that is being provided is immutable, then you won't be able to perform a deep check as this attempts to extend the objects provided.

There are, however, multiple data change detection strategies that can be used.

I solved this issue by adding the following to the AgGridReact component:

import { ChangeDetectionStrategyType } from 'ag-grid-react/lib/changeDetectionService'
...
<AgGridReact
rowDataChangeDetectionStrategy={ChangeDetectionStrategyType.IdentityCheck}
...
/>

which will be sufficient.

I was lead to this by this github answer by @benhodeda, which says:

hi :)
  I had a similar problem when I've migrated our state object to use immer instead of immutableJS .
  We bind the state to AgGridReact's rowData prop, and when we filter the data (server-side filtering) the app was crash while doing change detection. I added deltaRowDataMode prop alongside with getRowNodeId={row => row.id} on AgGridReact component.

you can read more here: https://www.ag-grid.com/javascript-grid-data-update/


问:
TortoiseGit modified sign (icon overlay) is not updating
I have made a small change in some code but TortoiseGit shows it as modified (red exclamation sign) although I have committed, pulled, pushed, but it stays. What should I do here? I have not seen this issue before.</p>

答:
Not sure if this is relevant.

Looks like TortoiseGit has cache issues with file/folder cases.

In my case since the folder case was not correct with the once expected, the icons' overlay were not showing up

ContentLicense: CC BY-SA 3.0


问:
Not able to run the project in flutter
I am trying to build a flutter project, I am getting this error repeatedly as per the below error log.

How should I resolve it??

```<code>> Compiler message:
> ../../../Documents/flutter/packages/flutter/lib/src/cupertino/page_scaffold.dart:116:31:
> Error: The getter 'navigationBar' isn't defined for the class
> '_CupertinoPageScaffoldState'.
>  - '_CupertinoPageScaffoldState' is from 'package:flutter/src/cupertino/page_scaffold.dart'
> ('../../../Documents/flutter/packages/flutter/lib/src/cupertino/page_scaffold.dart').
> Try correcting the name to the name of an existing getter, or defining
> a getter or field named 'navigationBar'.
>       final fullObstruction = navigationBar.shouldFullyObstruct(context) == null ||
> navigationBar.shouldFullyObstruct(context);
>                               ^^^^^^^^^^^^^
</code>```

答:
import the following library in your route.</p>

```<code>import 'package:flutter/cupertino.dart';
</code>```

Title: Not able to run the project in flutter

Body:
I am trying to build a flutter project, I am getting this error repeatedly as per the below error log.

How should I resolve it??

> Compiler message:
> ../../../Documents/flutter/packages/flutter/lib/src/cupertino/page_scaffold.dart:116:31:
> Error: The getter 'navigationBar' isn't defined for the class
> '_CupertinoPageScaffoldState'.
>  - '_CupertinoPageScaffoldState' is from 'package:flutter/src/cupertino/page_scaffold.dart'
> ('../../../Documents/flutter/packages/flutter/lib/src/cupertino/page_scaffold.dart').
> Try correcting the name to the name of an existing getter, or defining
> a getter or field named 'navigationBar'.
>       final fullObstruction = navigationBar.shouldFullyObstruct(context) == null ||
> navigationBar.shouldFullyObstruct(context);
>                               ^^^^^^^^^^^^^

Body:
import the following library in your route.

import 'package:flutter/cupertino.dart';


问:
How to re-render every time state changes with API call limit?
Edit: People from FUTURE: check out this video -

https://www.youtube.com/watch?v=FyxFSkh2wug
and the article provided by Leonardo.

I have a searchbar component and a stockchart component that are both children of the Parent component. I want to re-render the stockchart every time a key is entered in the search bar. I am new to react so please bear with my code.

I tried a shouldComponentUpdate and it made too many API calls. In the CorrectRender function, I tried to return the StockChart everytime ticker changed but it didn't work.

I've tried my best to describe the methods I wrote, please feel free to ask any questions.

This is the Parent component, I'm calling this inside App.js

```<code>import React, { Component } from 'react'
import StockChart from './StockChart';
import SearchBar from './SearchBar';

// Renders stockChart when value is entered
// I tried to re-render by using a current and previousTicker symbols but it didn't work.

function CorrectRender(props, oldtick) {
    const ticker = props.props;
    console.log("props", props)
    const previousTicker = props.oldtick;
    if (ticker.length > 0 && previousTicker !== ticker) {
        return <div>
            <p>{ticker}</p>
            <StockChart stockSymbol = {ticker} previousTicker={previousTicker}/>
        </div>
    }
    return null;
    }

export class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            stockSymbol: '',
            previousTicker: ''
        }
        this.callbackFunction = this.callbackFunction.bind(this);
    }

    shaveData(value) {
        let value1 = value.split(`,`);
        value = value1[0];
        this.setState({
            stockSymbol: value,
        });
    }

    callbackFunction(sS)  {
        this.setState({ previousTicker: this.state.stockSymbol});
        this.shaveData(sS);
    };

    render() {
        return (
            <div>
                <SearchBar parentCallback = {this.callbackFunction}/>
                <CorrectRender props={this.state.stockSymbol} oldtick={this.state.previousTicker}/>
            </div>
        )
    }
}

export default Parent;
</code>```

This is the SEARCHBAR component.

```<code>import React, { Component } from 'react';
import './SearchBar.css';

export class SearchBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            search: ' ',
            tickerList: [],
        }
    }

    // Get a list of tickers from an API, this is not the api call that is being overused
    // I want the data to show to the user as "Ticker, Company name" which is what the second (.then) is doing
    fetchTickers(stockSymbol) {
        const pointer = this;
        let arr = [];
        console.log(stockSymbol);
        let url = `https://ticker-2e1ica8b9.now.sh/keyword/${stockSymbol}`;

        fetch(url)
            .then( function(response) {
                return response.json();
            })
            .then ( function(data) {
                for (var key in data) {
                    arr.push(data[key]['symbol'] + ", "+ data[key]['name'])
                };

                pointer.setState({
                    tickerList: arr
                })
            }

            )
    }

    // this is for handling keys in the search bar and rendering new results based on the
    critera
    textChange = (e) => {
        const value = e.target.value;
        let arr = [];
        if (value.length > 0) {
            const regex = new RegExp(`^${value}`, 'i');
            this.fetchTickers(value);
            arr = this.state.tickerList.sort().filter(tick => regex.test(tick));
        }
        this.setState({
            tickerList: arr,
            search: value
        });
    }

    // This will be called when an option is chosen by user
    tickerChosen(value) {
        let value1 = value.split(`,`);
        value = value1[0];
        this.setState({
            search: value,
            tickerList: []
        });

    };

    // list of suggestions on user side based on criteria
    tickerSuggestions () {
        const { tickerList } = this.state;
        if (tickerList.length === 0) {
            return null;
        }
        return (
            <ul>
                {tickerList.map((ticker) => <li key={ticker} onClick={() =>  {this.props.parentCallback(ticker); this.tickerChosen(ticker);} }>{ticker}</li>)}
            </ul>
        )
    };

    render() {
        const { search } = this.state;
        return (
            <div className= 'SearchBar'>
                <input value = { search } onChange={this.textChange} type='text' />
                {this.tickerSuggestions()}

            </div>
        )
    }
}

export default SearchBar
</code>```

This is the StockChart component.

```<code>import React, { Component } from 'react';
import Plot from 'react-plotly.js';

class StockChart extends Component {
    constructor(props) {
        super(props);
        this.state = {
            stockXValues: [],
            stockYValues: [],
            stockSymbol: '',

        }
}

componentDidMount() {
    this.fetchStock();
}

fetchStock() {
    const pointer = this;
    const symbol = this.props.stockSymbol;

    const API_KEY = `X`;
    let API_Call = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=${symbol}&outputsize=compact&apikey=${API_KEY}`;

    let StockXValuesFunc = [];
    let StockYValuesFunc = [];

    fetch(API_Call)
        .then(
            function(response) {
                return response.json();
            }
        )
        .then(
            function(data) {
                console.log(data);

                for (var key in data['Time Series (Daily)']) {
                    StockXValuesFunc.push(key);
                    StockYValuesFunc.push(data['Time Series (Daily)']
                    [key]['4. close']);
                }
                pointer.setState({
                    stockXValues: StockXValuesFunc,
                    stockYValues: StockYValuesFunc,
                });

            }
        )

}
render() {
  return (
    <div>
        <h2>{this.props.stockSymbol}</h2>
        <Plot
            data={[
            {
                x: this.state.stockXValues,
                y: this.state.stockYValues,
                type: 'scatter',
                mode: 'lines+markers',
                marker: {color: 'red'},
            },
            ]}
            layout={ {width: 720, height: 440, title: 'Closing Price over the last 100 days'} }
        />
    </div>
  )
 }
}
</code>```

Export default StockChart;

答:
Here you can find a good explanation on how to throttle and avoid doing so many API calls:
Improve your react app performance by using throttling and debouncing</p>

Body:
Edit: People from FUTURE: check out this video -

https://www.youtube.com/watch?v=FyxFSkh2wug
and the article provided by Leonardo.

I have a searchbar component and a stockchart component that are both children of the Parent component. I want to re-render the stockchart every time a key is entered in the search bar. I am new to react so please bear with my code.

I tried a shouldComponentUpdate and it made too many API calls. In the CorrectRender function, I tried to return the StockChart everytime ticker changed but it didn't work.

I've tried my best to describe the methods I wrote, please feel free to ask any questions.

This is the Parent component, I'm calling this inside App.js

import React, { Component } from 'react'
import StockChart from './StockChart';
import SearchBar from './SearchBar';

// Renders stockChart when value is entered
// I tried to re-render by using a current and previousTicker symbols but it didn't work.

function CorrectRender(props, oldtick) {
    const ticker = props.props;
    console.log("props", props)
    const previousTicker = props.oldtick;
    if (ticker.length > 0 && previousTicker !== ticker) {
        return

{ticker}

            <StockChart stockSymbol = {ticker} previousTicker={previousTicker}/>

    }
    return null;
    }

export class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            stockSymbol: '',
            previousTicker: ''
        }
        this.callbackFunction = this.callbackFunction.bind(this);
    }

    shaveData(value) {
        let value1 = value.split(`,`);
        value = value1[0];
        this.setState({
            stockSymbol: value,
        });
    }

    callbackFunction(sS)  {
        this.setState({ previousTicker: this.state.stockSymbol});
        this.shaveData(sS);
    };

    render() {
        return (

                <SearchBar parentCallback = {this.callbackFunction}/>
                <CorrectRender props={this.state.stockSymbol} oldtick={this.state.previousTicker}/>

        )
    }
}

export default Parent;

This is the SEARCHBAR component.

import React, { Component } from 'react';
import './SearchBar.css';

export class SearchBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            search: ' ',
            tickerList: [],
        }
    }

    // Get a list of tickers from an API, this is not the api call that is being overused
    // I want the data to show to the user as "Ticker, Company name" which is what the second (.then) is doing
    fetchTickers(stockSymbol) {
        const pointer = this;
        let arr = [];
        console.log(stockSymbol);
        let url = `https://ticker-2e1ica8b9.now.sh/keyword/${stockSymbol}`;

        fetch(url)
            .then( function(response) {
                return response.json();
            })
            .then ( function(data) {
                for (var key in data) {
                    arr.push(data[key]['symbol'] + ", "+ data[key]['name'])
                };

                pointer.setState({
                    tickerList: arr
                })
            }

            )
    }

    // this is for handling keys in the search bar and rendering new results based on the
    critera
    textChange = (e) => {
        const value = e.target.value;
        let arr = [];
        if (value.length > 0) {
            const regex = new RegExp(`^${value}`, 'i');
            this.fetchTickers(value);
            arr = this.state.tickerList.sort().filter(tick => regex.test(tick));
        }
        this.setState({
            tickerList: arr,
            search: value
        });
    }

    // This will be called when an option is chosen by user
    tickerChosen(value) {
        let value1 = value.split(`,`);
        value = value1[0];
        this.setState({
            search: value,
            tickerList: []
        });

    };

    // list of suggestions on user side based on criteria
    tickerSuggestions () {
        const { tickerList } = this.state;
        if (tickerList.length === 0) {
            return null;
        }
        return (

                {tickerList.map((ticker) =>
  {this.props.parentCallback(ticker); this.tickerChosen(ticker);} }>{ticker}
)}

        )
    };

    render() {
        const { search } = this.state;
        return (

                <input value = { search } onChange={this.textChange} type='text' />
                {this.tickerSuggestions()}

        )
    }
}

export default SearchBar

This is the StockChart component.

import React, { Component } from 'react';
import Plot from 'react-plotly.js';

class StockChart extends Component {
    constructor(props) {
        super(props);
        this.state = {
            stockXValues: [],
            stockYValues: [],
            stockSymbol: '',

        }
}

componentDidMount() {
    this.fetchStock();
}

fetchStock() {
    const pointer = this;
    const symbol = this.props.stockSymbol;

    const API_KEY = `X`;
    let API_Call = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=${symbol}&outputsize=compact&apikey=${API_KEY}`;

    let StockXValuesFunc = [];
    let StockYValuesFunc = [];

    fetch(API_Call)
        .then(
            function(response) {
                return response.json();
            }
        )
        .then(
            function(data) {
                console.log(data);

                for (var key in data['Time Series (Daily)']) {
                    StockXValuesFunc.push(key);
                    StockYValuesFunc.push(data['Time Series (Daily)']
                    [key]['4. close']);
                }
                pointer.setState({
                    stockXValues: StockXValuesFunc,
                    stockYValues: StockYValuesFunc,
                });

            }
        )

}
render() {
  return (

{this.props.stockSymbol}

        <Plot
            data={[
            {
                x: this.state.stockXValues,
                y: this.state.stockYValues,
                type: 'scatter',
                mode: 'lines+markers',
                marker: {color: 'red'},
            },
            ]}
            layout={ {width: 720, height: 440, title: 'Closing Price over the last 100 days'} }
        />

  )
 }
}

Export default StockChart;


问:
Not able to assign data value returned from api to class variable in Angular 8
I am calling api to get data on ngOnInit. However I am not able to assign the data class variable.
Below is the related code

```<code>  tasks: Task[];

  ngOnInit() {

    this.apiService.getTasks()
      .subscribe( data => {
        Object.keys(data).map((index) => {
          this.tasks.push(data[index]);
       });
      });

  }
</code>```

I get error saying 'TypeError: Cannot read property 'push' of undefined' for statement

```<code>this.tasks.push(data[index]);
</code>```

But the tasks is already defined as array.

Can anyone help me here, the scope really confuses me

答:
Map will return a new array so no need of pushing inside map. Hence Your code should be </p>

```<code>this.apiService.getTasks()
      .subscribe( data => {
        this.tasks = Object.keys(data).map((index) => {
         return data[index];
         });
      });
</code>```

Body:
I am calling api to get data on ngOnInit. However I am not able to assign the data class variable.
Below is the related code

  tasks: Task[];

  ngOnInit() {

    this.apiService.getTasks()
      .subscribe( data => {
        Object.keys(data).map((index) => {
          this.tasks.push(data[index]);
       });
      });

  }

I get error saying 'TypeError: Cannot read property 'push' of undefined' for statement

this.tasks.push(data[index]);

But the tasks is already defined as array.

Can anyone help me here, the scope really confuses me

Body:
Map will return a new array so no need of pushing inside map. Hence Your code should be

this.apiService.getTasks()
      .subscribe( data => {
        this.tasks = Object.keys(data).map((index) => {
         return data[index];
         });
      });


问:
Robot_framework UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 42: invalid continuation byte
I am using RED ( Robotframework in Eclipse )

My Testcase is run OK

Now it not work again

It have a error : UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 42: invalid continuation byte

I dont know why it happen
Can you help me

Thank you

```<code>     *** setting ***
Library    SeleniumLibrary

*** Variables***
${Ecran_Name}         New_Ecran_is_ABC
${URL}  http://cd.blueway.fr:20321/BWDesignerFaces/login.jsf
${Credentials}   Nam  Son  Cyrille
&{Login_by_id_Pass}     Username=admin    Password=admin

***Keyword***

LoginPageBlueway
    [Tags]    Login
    [Documentation]    Login Page
    Open Browser    http://cd.blueway.fr:20321/BWDesignerFaces/login.jsf    Chrome
    Click Element    id=loginForm:username
    Input Text    id=loginForm:username    admin
    Click Element    id=loginForm:password
    Input Password    id=loginForm:password    Password
    #Input Password    id=loginForm:password    &{Login_by_id_Pass}[Password]
    Click Element    xpath=//button/span
    Maximize Browser Window
</code>```

Note *: I guess it relative to Font : Language

Font : Liste déroulante

I used font : French laguage

I use font : English is OK

My file UTF8 is look like :

```<code>    import codecs

### Codec APIs

encode = codecs.utf_8_encode

def decode(input, errors='strict'):
    return codecs.utf_8_decode(input, errors, True)

class IncrementalEncoder(codecs.IncrementalEncoder):
    def encode(self, input, final=False):
        return codecs.utf_8_encode(input, self.errors)[0]

class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
    _buffer_decode = codecs.utf_8_decode

class StreamWriter(codecs.StreamWriter):
    encode = codecs.utf_8_encode

class StreamReader(codecs.StreamReader):
    decode = codecs.utf_8_decode

### encodings module API

def getregentry():
    return codecs.CodecInfo(
        name='utf-8',
        encode=encode,
        decode=decode,
        incrementalencoder=IncrementalEncoder,
        incrementaldecoder=IncrementalDecoder,
        streamreader=StreamReader,
        streamwriter=StreamWriter,
    )
</code>```

答:
Eclipse :

Window/ Preferences/ Workspace

Text file encoding = UTF8

Check all Testcase again :

Look at special character

Modify Font again

Testcase will run

Body:
I am using RED ( Robotframework in Eclipse )

My Testcase is run OK

Now it not work again

It have a error : UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 42: invalid continuation byte

I dont know why it happen
Can you help me

Thank you

     *** setting ***
Library    SeleniumLibrary

*** Variables***
${Ecran_Name}         New_Ecran_is_ABC
${URL}  http://cd.blueway.fr:20321/BWDesignerFaces/login.jsf
${Credentials}   Nam  Son  Cyrille
&{Login_by_id_Pass}     Username=admin    Password=admin

***Keyword***

LoginPageBlueway
    [Tags]    Login
    [Documentation]    Login Page
    Open Browser    http://cd.blueway.fr:20321/BWDesignerFaces/login.jsf    Chrome
    Click Element    id=loginForm:username
    Input Text    id=loginForm:username    admin
    Click Element    id=loginForm:password
    Input Password    id=loginForm:password    Password
    #Input Password    id=loginForm:password    &{Login_by_id_Pass}[Password]
    Click Element    xpath=//button/span
    Maximize Browser Window

Note *: I guess it relative to Font : Language

Font : Liste déroulante

I used font : French laguage

I use font : English is OK

My file UTF8 is look like :

    import codecs

### Codec APIs

encode = codecs.utf_8_encode

def decode(input, errors='strict'):
    return codecs.utf_8_decode(input, errors, True)

class IncrementalEncoder(codecs.IncrementalEncoder):
    def encode(self, input, final=False):
        return codecs.utf_8_encode(input, self.errors)[0]

class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
    _buffer_decode = codecs.utf_8_decode

class StreamWriter(codecs.StreamWriter):
    encode = codecs.utf_8_encode

class StreamReader(codecs.StreamReader):
    decode = codecs.utf_8_decode

### encodings module API

def getregentry():
    return codecs.CodecInfo(
        name='utf-8',
        encode=encode,
        decode=decode,
        incrementalencoder=IncrementalEncoder,
        incrementaldecoder=IncrementalDecoder,
        streamreader=StreamReader,
        streamwriter=StreamWriter,
    )


问:
Covert datetime64[ns, UTC] to datetime64 python
I have a column with datetime UTC date

```<code>2020-01-01 00:00:00+00:00
</code>```

Can someone help me to convert it to just datetime64 for eg:

```<code>2020-01-01
</code>```

答:
if you use pandas (this seems to be the case) you can change it like that: </p>

```<code>df.dates.apply(lambda x: x.date()) # where dates is your datetime column
</code>```

Body:
I have a column with datetime UTC date

2020-01-01 00:00:00+00:00

Can someone help me to convert it to just datetime64 for eg:

2020-01-01

Body:
if you use pandas (this seems to be the case) you can change it like that:

df.dates.apply(lambda x: x.date()) # where dates is your datetime column


问:
Fit content in to flex direction column
Im trying to fit content into a div with a flex.
Works perfectly into a flex-direction:row; (Standar) but isen´t work into a flex-direction:column;
In "column" just overflow my div, do not resize the elements inside.

How can i do to resize elemetns to fit into a div with out know cuantity of elemnts?

https://codepen.io/nandordena/pen/jObjJNw

HTML

```<code><body>
<div class="column">
  <div>
    <video src="https://www.w3schools.com/tags/movie.ogg">
  </div>
  <div>
    <video src="https://www.w3schools.com/tags/movie.ogg">
  </div>
  <div>
    <video src="https://www.w3schools.com/tags/movie.ogg">
  </div>
</div>

<div class="row">
  <div>
    <video src="https://www.w3schools.com/tags/movie.ogg">
  </div>
  <div>
    <video src="https://www.w3schools.com/tags/movie.ogg">
  </div>
  <div>
    <video src="https://www.w3schools.com/tags/movie.ogg">
  </div>
</div>
</body>
</code>```

CSS

```<code>div{
  border:solid 1px #f00;
  margin:1px;
  flex:1;
}
body{
  border:solid 1px #00f;
  pading:1px;
  display:flex;
  height: 500px;
  width: 500px;
}
.row{
  display:flex;
  flex-direction:row;
}
.column{
  display: flex;
  flex-direction:column;
}
video {
  max-height:100%;
  max-width:100%;
}
</code>```

答: Probably the easiest (not sure if a correct way), to let column grow and don't let it shrink. You can achieve this by adding flex: 1 0 auto; to your wrapper (.row > div)

Title: Fit content in to flex direction column

Body:
Im trying to fit content into a div with a flex.
Works perfectly into a flex-direction:row; (Standar) but isen´t work into a flex-direction:column;
In "column" just overflow my div, do not resize the elements inside.

How can i do to resize elemetns to fit into a div with out know cuantity of elemnts?

https://codepen.io/nandordena/pen/jObjJNw

HTML

    <video src="https://www.w3schools.com/tags/movie.ogg">

    <video src="https://www.w3schools.com/tags/movie.ogg">

    <video src="https://www.w3schools.com/tags/movie.ogg">

    <video src="https://www.w3schools.com/tags/movie.ogg">

    <video src="https://www.w3schools.com/tags/movie.ogg">

    <video src="https://www.w3schools.com/tags/movie.ogg">

CSS

div{
  border:solid 1px #f00;
  margin:1px;
  flex:1;
}
body{
  border:solid 1px #00f;
  pading:1px;
  display:flex;
  height: 500px;
  width: 500px;
}
.row{
  display:flex;
  flex-direction:row;
}
.column{
  display: flex;
  flex-direction:column;
}
video {
  max-height:100%;
  max-width:100%;
}


问:
jQuery: Change highlight fade-to color?
Is it possible to change the color that the jQuery highlight effect fade's to?

Right now it starts the highlight at yellow, then fades to white and then fades out.

I ultimately what to highlight the background color with yellow, then just fade to transparent.

答:
Below is the highlight effect source code in jQuery UI 1.8.9. Doesn't look like it should fade to white... it should fade from yellow (#ffff99 or the color option you pass in) to the original background color, which is cached in the variable animation. Are you using 1.8.9?

```<code>/*
 * jQuery UI Effects Highlight 1.8.9
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Highlight
 *
 * Depends:
 *  jquery.effects.core.js
 */
(function( $, undefined ) {

$.effects.highlight = function(o) {
    return this.queue(function() {
        var elem = $(this),
            props = ['backgroundImage', 'backgroundColor', 'opacity'],
            mode = $.effects.setMode(elem, o.options.mode || 'show'),
            animation = {
                backgroundColor: elem.css('backgroundColor')
            };

        if (mode == 'hide') {
            animation.opacity = 0;
        }

        $.effects.save(elem, props);
        elem
            .show()
            .css({
                backgroundImage: 'none',
                backgroundColor: o.options.color || '#ffff99'
            })
            .animate(animation, {
                queue: false,
                duration: o.duration,
                easing: o.options.easing,
                complete: function() {
                    (mode == 'hide' && elem.hide());
                    $.effects.restore(elem, props);
                    (mode == 'show' && !$.support.opacity && this.style.removeAttribute('filter'));
                    (o.callback && o.callback.apply(this, arguments));
                    elem.dequeue();
                }
            });
    });
};
</code>```

Title: jQuery: Change highlight fade-to color?

Body:
Below is the highlight effect source code in jQuery UI 1.8.9. Doesn't look like it should fade to white... it should fade from yellow (#ffff99 or the color option you pass in) to the original background color, which is cached in the variable animation. Are you using 1.8.9?

/*
 * jQuery UI Effects Highlight 1.8.9
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Highlight
 *
 * Depends:
 *  jquery.effects.core.js
 */
(function( $, undefined ) {

$.effects.highlight = function(o) {
    return this.queue(function() {
        var elem = $(this),
            props = ['backgroundImage', 'backgroundColor', 'opacity'],
            mode = $.effects.setMode(elem, o.options.mode || 'show'),
            animation = {
                backgroundColor: elem.css('backgroundColor')
            };

        if (mode == 'hide') {
            animation.opacity = 0;
        }

        $.effects.save(elem, props);
        elem
            .show()
            .css({
                backgroundImage: 'none',
                backgroundColor: o.options.color || '#ffff99'
            })
            .animate(animation, {
                queue: false,
                duration: o.duration,
                easing: o.options.easing,
                complete: function() {
                    (mode == 'hide' && elem.hide());
                    $.effects.restore(elem, props);
                    (mode == 'show' && !$.support.opacity && this.style.removeAttribute('filter'));
                    (o.callback && o.callback.apply(this, arguments));
                    elem.dequeue();
                }
            });
    });
};


问:
jQuery scroll to element and then click it
I'm currently trying to make jQuery scroll to an element (in this case an accordion item) and then I want it to be automatically opened (clicked). So far I can successfully scroll to the item via jquery animate, but I can't seem to figure out how to click it AFTER the animate function has completed. This is my code so far:

```<code>$([document.documentElement, document.body]).animate({
            scrollTop: $("#"+ articleID +"").offset().top
        }, 800).then(function(){
            $("div[id='"+ articleID +"']").click();
        });
</code>```

Variables are being defined as function arguments, but the rest of the function is not relevant to the issue.

The code above successfully scrolls to the desired element, but won't click it afterwards. Any ideas how to approach this issue?

答:
.then() is a promise chain. Since animate() will not return a promise, so it won't work as expected. If you want to perform an action after a certain animation took place, you should pass the complete callback function to it.

So your final code should be something like this:

```<code>$([document.documentElement, document.body]).animate({// The selector should be $(document.documentElement) otherwise it will trigger the click event twice.
  scrollTop: $("#" + articleID + "").offset().top
}, 800, function() {
  $("div[id='" + articleID + "']").click();
});
</code>```

NOTE: As @freedomn-m pointed out, there should be only one selector for passing through the animate() function. So you should replace $([document.documentElement, document.body]) with $(document.documentElement).

Body:
I'm currently trying to make jQuery scroll to an element (in this case an accordion item) and then I want it to be automatically opened (clicked). So far I can successfully scroll to the item via jquery animate, but I can't seem to figure out how to click it AFTER the animate function has completed. This is my code so far:

$([document.documentElement, document.body]).animate({
            scrollTop: $("#"+ articleID +"").offset().top
        }, 800).then(function(){
            $("div[id='"+ articleID +"']").click();
        });

Variables are being defined as function arguments, but the rest of the function is not relevant to the issue.

The code above successfully scrolls to the desired element, but won't click it afterwards. Any ideas how to approach this issue?

Body:
.then() is a promise chain. Since animate() will not return a promise, so it won't work as expected. If you want to perform an action after a certain animation took place, you should pass the complete callback function to it.

So your final code should be something like this:

$([document.documentElement, document.body]).animate({// The selector should be $(document.documentElement) otherwise it will trigger the click event twice.
  scrollTop: $("#" + articleID + "").offset().top
}, 800, function() {
  $("div[id='" + articleID + "']").click();
});

NOTE: As @freedomn-m pointed out, there should be only one selector for passing through the animate() function. So you should replace $([document.documentElement, document.body]) with $(document.documentElement).


问:
VS2013: fatal error C1001: An internal error has occurred in the compiler
The code is quite simple:

```<code>int main(void){
    return 0;
}
</code>```

and the compile error goes:

```<code>1>------ Build started: Project: Project1, Configuration: Debug Win32 ------
1>  Source.cpp
1>c:\userdata\zdck\documents\visual studio 2013\projects\project1\project1\source.cpp : fatal error C1001: An internal error has occurred in the compiler.
1>  (compiler file 'f:\dd\vctools\compiler\cxxfe\sl\p1\c\p0io.c', line 2807)
1>   To work around this problem, try simplifying or changing the program near the locations listed above.
1>  Please choose the Technical Support command on the Visual C++
1>   Help menu, or open the Technical Support help file for more information
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
</code>```

I have no driver F but there comes an error in f:\dd\vctools\compiler\cxxfe\sl\p1\c\p0io.c??

Believe in me that I have checked dozens of posts with title "C1001 blah blah..." here and there but no one works for me.

My VS: V2013 Version 12.0.40629.00 Update 5
My OS: win 10, 64 bit

答:
The error C1001 related to compiler file p0io.c is mainly caused by enabling Use Unicode UTF-8 for worldwide language supportin Region Settings. You could see the link about the concrete reason. You could click Time &Language -> Region-> Additional date, time, &regional settings-> Region-> Administrative->Change system locale and turn off UTF-8.

enter image description here

If the error couldn’t be fixed, I suggest that you could update your VS version to VS2019.

Body:
The code is quite simple:

int main(void){
    return 0;
}

and the compile error goes:

1>------ Build started: Project: Project1, Configuration: Debug Win32 ------
1>  Source.cpp
1>c:\userdata\zdck\documents\visual studio 2013\projects\project1\project1\source.cpp : fatal error C1001: An internal error has occurred in the compiler.
1>  (compiler file 'f:\dd\vctools\compiler\cxxfe\sl\p1\c\p0io.c', line 2807)
1>   To work around this problem, try simplifying or changing the program near the locations listed above.
1>  Please choose the Technical Support command on the Visual C++
1>   Help menu, or open the Technical Support help file for more information
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

I have no driver F but there comes an error in f:\dd\vctools\compiler\cxxfe\sl\p1\c\p0io.c??

Believe in me that I have checked dozens of posts with title "C1001 blah blah..." here and there but no one works for me.

My VS: V2013 Version 12.0.40629.00 Update 5
My OS: win 10, 64 bit


问:
showing only data from machines which do not show up in another query
I have a fairly typical show CPU usage query

100 - (avg by (instance) (irate(wmi_cpu_time_total{mode="idle"}[2m])) * 100) > 80

which results in data which looks a bit like this:

```<code>{instance="opus143.domain.com:9182"} 94.07140535559513
{instance="opus162.domain.com:9182"} 90.00755315803018
{instance="opus163.domain.com:9182"} 85.48084077380952
</code>```

but I would like to query only for values for machines which don't appear in another list

opus_local_slaves_count > 0

```<code>opus_local_slaves_count{instance="opus143.domain.com:5100",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{instance="opus143.domain.com:5110",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{instance="opus145.domain.com:5100",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{instance="opus145.domain.com:5110",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{instance="opus146.domain.com:5100",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{instance="opus146.domain.com:5110",job="opus-live",runname="SimV3.1a"} 54
</code>```

I think I've been able to get part of the way there using label_replace to give me the host in each case

(label_replace((100 - (avg by (instance) (irate(wmi_cpu_time_total{mode="idle"}[2m])) * 100) > 80), "host", "$1","instance","(.*?)[.].*"))

```<code>{host="opus143",instance="opus143.domain.com:9182"} 94.07140535559513
{host="opus162",instance="opus162.domain.com:9182"} 90.00755315803018
{host="opus163",instance="opus163.domain.com:9182"} 85.48084077380952
</code>```

label_replace((opus_local_slaves_count > 0), "host", "$1","instance","(.*?)[.].*")

```<code>opus_local_slaves_count{host="opus143",instance="opus143.domain.com:5100",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{host="opus143",instance="opus143.domain.com:5110",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{host="opus145",instance="opus145.domain.com:5100",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{host="opus145",instance="opus145.domain.com:5110",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{host="opus146",instance="opus146.domain.com:5100",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{host="opus146",instance="opus146.domain.com:5110",job="opus-live",runname="SimV3.1a"} 54
</code>```

But now I am really stuck trying to exclude hosts in the second list, from the first. Is this even possible in PromQL? In SQL it would be a simple NOT IN subquery

UPDATE: For context, what I'm trying to achieve is to be able to alert for high-CPU on servers, except servers in the second list, which should have high-CPU utilisation. Maybe there's a better way?

答:
Solved it!

For anyone who finds this looking to do something similar... The saliant keyword is UNLESS!

I first simplified things by creating recording rules:

```<code>groups:
- name: custom_rules
  rules:
  - record: wmi_cpu_time_total_instance
    expr: 100 - (avg by (instance) (irate(wmi_cpu_time_total{mode="idle"}[2m])) * 100)
  - record: wmi_cpu_time_total_instance_host
    expr: label_replace(wmi_cpu_time_total_instance, "host", "$1", "instance","(.*?)[.].*")
  - record: opus_local_slaves_count_instance_host
    expr: label_replace(opus_local_slaves_count, "host", "$1", "instance","(.*?)[.].*")
</code>```

which encapsulated much of the complexity in calculating and adding the host label, and I then found this blog (thank you Chris Siebenmann) https://utcc.utoronto.ca/~cks/space/blog/sysadmin/PrometheusFindUnpairedMetrics which pointed me at the UNLESS keyword so I could write the simple query

wmi_cpu_time_total_instance_host unless on(host) (opus_local_slaves_count_instance_host > 0)

which gives a list of hosts which don't have the opus_local_slaves_count label, or for which the opus_local_slaves_count = 0

Voila!

Body:
I have a fairly typical show CPU usage query

100 - (avg by (instance) (irate(wmi_cpu_time_total{mode="idle"}[2m])) * 100) > 80

which results in data which looks a bit like this:

{instance="opus143.domain.com:9182"} 94.07140535559513
{instance="opus162.domain.com:9182"} 90.00755315803018
{instance="opus163.domain.com:9182"} 85.48084077380952

but I would like to query only for values for machines which don't appear in another list

opus_local_slaves_count > 0

opus_local_slaves_count{instance="opus143.domain.com:5100",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{instance="opus143.domain.com:5110",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{instance="opus145.domain.com:5100",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{instance="opus145.domain.com:5110",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{instance="opus146.domain.com:5100",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{instance="opus146.domain.com:5110",job="opus-live",runname="SimV3.1a"} 54

I think I've been able to get part of the way there using label_replace to give me the host in each case

(label_replace((100 - (avg by (instance) (irate(wmi_cpu_time_total{mode="idle"}[2m])) * 100) > 80), "host", "$1","instance","(.*?)[.].*"))

{host="opus143",instance="opus143.domain.com:9182"} 94.07140535559513
{host="opus162",instance="opus162.domain.com:9182"} 90.00755315803018
{host="opus163",instance="opus163.domain.com:9182"} 85.48084077380952

label_replace((opus_local_slaves_count > 0), "host", "$1","instance","(.*?)[.].*")

opus_local_slaves_count{host="opus143",instance="opus143.domain.com:5100",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{host="opus143",instance="opus143.domain.com:5110",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{host="opus145",instance="opus145.domain.com:5100",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{host="opus145",instance="opus145.domain.com:5110",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{host="opus146",instance="opus146.domain.com:5100",job="opus-live",runname="SimV3.1a"} 54
opus_local_slaves_count{host="opus146",instance="opus146.domain.com:5110",job="opus-live",runname="SimV3.1a"} 54

But now I am really stuck trying to exclude hosts in the second list, from the first. Is this even possible in PromQL? In SQL it would be a simple NOT IN subquery

UPDATE: For context, what I'm trying to achieve is to be able to alert for high-CPU on servers, except servers in the second list, which should have high-CPU utilisation. Maybe there's a better way?

Body:
Solved it!

For anyone who finds this looking to do something similar... The saliant keyword is UNLESS!

I first simplified things by creating recording rules:

groups:
- name: custom_rules
  rules:
  - record: wmi_cpu_time_total_instance
    expr: 100 - (avg by (instance) (irate(wmi_cpu_time_total{mode="idle"}[2m])) * 100)
  - record: wmi_cpu_time_total_instance_host
    expr: label_replace(wmi_cpu_time_total_instance, "host", "$1", "instance","(.*?)[.].*")
  - record: opus_local_slaves_count_instance_host
    expr: label_replace(opus_local_slaves_count, "host", "$1", "instance","(.*?)[.].*")

which encapsulated much of the complexity in calculating and adding the host label, and I then found this blog (thank you Chris Siebenmann) https://utcc.utoronto.ca/~cks/space/blog/sysadmin/PrometheusFindUnpairedMetrics which pointed me at the UNLESS keyword so I could write the simple query

wmi_cpu_time_total_instance_host unless on(host) (opus_local_slaves_count_instance_host > 0)

which gives a list of hosts which don't have the opus_local_slaves_count label, or for which the opus_local_slaves_count = 0

Voila!


问:
Centre of mass row-wise in a dataframe and multiply each column by different mass
I'm trying to calculate the centre of mass of 20 objects, where each object has it's own different mass.

These objects are represented in a dataframe cm_x, and their associated masses in a list. Below I show an example of just 3 of those 20 objects, for the sake of saving space. Each object has an x, y, z coordinate, but I'll just show the x and then I can apply the same technique to the rest. Below is the head of the dataframe.

```<code>bar_head_x  bar_hip_centre_x    bar_left_ankle_x
0   -203.3502   -195.4573   -293.262
1   -203.4280   -195.4720   -293.251
2   -203.4954   -195.4675   -293.248
3   -203.5022   -195.9193   -293.219
4   -203.5014   -195.9092   -293.328

m_head = 0.081
m_hipc = 0.139
m_lank = 0.0465
m = [m_head,m_hipc,m_lank]
</code>```

I saw in another similar question, someone has suggested this method, however this doesn't incorporate the masses, and that is where I'm having an issue:

```<code>def series_sum(pd_series):
    return np.sum(np.dot(pd_series.values, np.asarray(range(1, len(pd_series)+1)))/np.sum(pd_series))

cm_x.apply(series_sum, axis=1)
</code>```

Basically I want for each row, to have an associated centre of mass, using the formula for centre of mass which is sum(x_i * m_i) / sum(m_i).

The desired result would be a new column in the dataframe like so:

```<code>cm_x
0   -214.92
1   ...
2   ...
3   ...
4   ...
</code>```

Any help?

Body:
I'm trying to calculate the centre of mass of 20 objects, where each object has it's own different mass.

These objects are represented in a dataframe cm_x, and their associated masses in a list. Below I show an example of just 3 of those 20 objects, for the sake of saving space. Each object has an x, y, z coordinate, but I'll just show the x and then I can apply the same technique to the rest. Below is the head of the dataframe.

bar_head_x  bar_hip_centre_x    bar_left_ankle_x
0   -203.3502   -195.4573   -293.262
1   -203.4280   -195.4720   -293.251
2   -203.4954   -195.4675   -293.248
3   -203.5022   -195.9193   -293.219
4   -203.5014   -195.9092   -293.328

m_head = 0.081
m_hipc = 0.139
m_lank = 0.0465
m = [m_head,m_hipc,m_lank]

I saw in another similar question, someone has suggested this method, however this doesn't incorporate the masses, and that is where I'm having an issue:

def series_sum(pd_series):
    return np.sum(np.dot(pd_series.values, np.asarray(range(1, len(pd_series)+1)))/np.sum(pd_series))

cm_x.apply(series_sum, axis=1)

Basically I want for each row, to have an associated centre of mass, using the formula for centre of mass which is sum(x_i * m_i) / sum(m_i).

The desired result would be a new column in the dataframe like so:

cm_x
0   -214.92
1   ...
2   ...
3   ...
4   ...

Any help?

Body:
Use DataFrame.dot and divide by sum of list m:

s = df.dot(m).div(sum(m))
print (s)
0      -214.921628
1      -214.951023
2      -214.968638
3      -215.201292
4      -215.214800
7441   -245.078910
7442   -244.943961
7443   -244.806606
7444   -244.665285
7445   -244.533503
dtype: float64

If need DataFrame add Series.to_frame:

df1 = df.dot(m).div(sum(m)).to_frame('cm_x')
print (df1)
            cm_x
0    -214.921628
1    -214.951023
2    -214.968638
3    -215.201292
4    -215.214800
7441 -245.078910
7442 -244.943961
7443 -244.806606
7444 -244.665285
7445 -244.533503


问:
Java: How do you enforce a class type parameter to be the same as generic type specified in a generic method?
I created a NotificationManager class, which let's you register a generic listener to some generic notification service. In the NotificationManager class I have a generic method for registering a listener with a service:

```<code>public static <E> void registerNotify(Class<E> type, INotificationListener<E> listener) {
    @SuppressWarnings("unchecked")
    INotificationService<E> service = (INotificationService<E>) NotificationServiceFactory.get(type);
    service.registerNotificationListener(listener);
}
</code>```

So, for some INotificationListener of a particular type I'd like to force the user, when calling this method, to specify the same type as the listener. The type maps to all the INotificationListeners of the same type, however this method doesn't enforce what I'm trying to enforce. For example, I could call:

```<code>INotificationListener<Location> locationListener = this;
NotificationManager.registerNotify(String.class, locationListener);
</code>```

and the code compiles fine. What I thought this would enforce is the following:

```<code>INotificationListener<Location> locationListener = this;
NotificationManager.registerNotify(Location.class, locationListener);
</code>```

Any ideas on how to accomplish this?

Update:

Sorry for the mixup, the above does in fact work. The method in the same class which does not work is actually the following:

```<code>public static <E> void broadcastNotify(Class<E> type, E data)
    {
        @SuppressWarnings("unchecked")
        INotificationService<E> service = (INotificationService<E>) NotificationServiceFactory.get(type);
        service.notifyListeners(data);
    }
</code>```

And calling:

```<code>Location location = new Location();
NotificationManager.broadcastNotify(Object.class, location);
</code>```

Does not cause a compilation error, which is what I would like it to do.

答:
I figured this out. I changed the signature of:

```<code>public static <E> void broadcastNotify(Class<E> type, E data)
</code>```

to:

```<code>public static <E> void broadcastNotify(Class<E> type, INotification<E> data)
</code>```

where INotification is some interface that wraps the data I'm trying to return in the notification. This enforces that the class type must exactly match the notification type so that the underlying map that maps the notifications sends the messages to the registered listeners correctly without worry of programmer error.

Body:
I created a NotificationManager class, which let's you register a generic listener to some generic notification service. In the NotificationManager class I have a generic method for registering a listener with a service:

public static <E> void registerNotify(Class<E> type, INotificationListener<E> listener) {
    @SuppressWarnings("unchecked")
    INotificationService<E> service = (INotificationService<E>) NotificationServiceFactory.get(type);
    service.registerNotificationListener(listener);
}

So, for some INotificationListener of a particular type I'd like to force the user, when calling this method, to specify the same type as the listener. The type maps to all the INotificationListeners of the same type, however this method doesn't enforce what I'm trying to enforce. For example, I could call:

INotificationListener<Location> locationListener = this;
NotificationManager.registerNotify(String.class, locationListener);

and the code compiles fine. What I thought this would enforce is the following:

INotificationListener<Location> locationListener = this;
NotificationManager.registerNotify(Location.class, locationListener);

Any ideas on how to accomplish this?

Update:

Sorry for the mixup, the above does in fact work. The method in the same class which does not work is actually the following:

public static <E> void broadcastNotify(Class<E> type, E data)
    {
        @SuppressWarnings("unchecked")
        INotificationService<E> service = (INotificationService<E>) NotificationServiceFactory.get(type);
        service.notifyListeners(data);
    }

And calling:

Location location = new Location();
NotificationManager.broadcastNotify(Object.class, location);

Does not cause a compilation error, which is what I would like it to do.

Body:
I figured this out. I changed the signature of:

public static <E> void broadcastNotify(Class<E> type, E data)

to:

public static <E> void broadcastNotify(Class<E> type, INotification<E> data)

where INotification is some interface that wraps the data I'm trying to return in the notification. This enforces that the class type must exactly match the notification type so that the underlying map that maps the notifications sends the messages to the registered listeners correctly without worry of programmer error.


问:
Change Google colab language setting
How to change Colab interface from French to English? I can not find this setting. this is my problem. The interface:

答: hl parameter is used to set the page language. Add ?hl=en at the end of the URL of the page.</p>

Title: Change Google colab language setting


问:
How to Create a Pig Latin Job in Azure HDInsight Cluster
I just created a free account to Azure and created a hadoop cluster on HDInsight. However, it dose not in anyway show how to launch a Pig client and create pig latin job and run it?</p>

答:
Unfortunately, you cannot use Ambari UI to run pig latin jobs.

Note: To process data using Pig, will need to open an SSH console that is connected to your cluster and then run the pig latin using local mode or mapreduce mode:

If you are using a Windows client computer:

In the Microsoft Azure portal, on the HDInsight Cluster blade for your HDInsight cluster, click  Secure Shell, and then in the Secure Shell blade, in the Hostname list, note the Host name for your cluster (which should be your_cluster_name-ssh.azurehdinsight.net).

Open PuTTY, and in the Session page, enter the host name into the Host Name box. Then under Connection type, select SSH and click Open. If a security warning that the host certificate cannot be verified is displayed, click Yes to continue.

When prompted, enter the SSH username and password you specified when provisioning the cluster (not the cluster login username).

If you are using a Mac OS X or Linux client computer:

In the Microsoft Azure portal, on the HDInsight Cluster blade for your HDInsight cluster, click Secure Shell, and then in the Secure Shell blade, in the Hostname list, select the hostname for your cluster. then copy the ssh command that is displayed, which should resemble the following command – you will use this to connect to the head node.
ssh sshuser@your_cluster_name-ssh.azurehdinsight.net

Open a new terminal session, and paste the ssh command, specifying your SSH user name (not the cluster login username).

If you are prompted to connect even though the certificate can’t be verified, enter yes.

When prompted, enter the password for the SSH username.

Once you connected to your cluster, to run pig latin as shown:

You can execute Pig Latin statements:

Using grunt shell or command line

In mapreduce mode or local mode

Either interactively or in batch

Reference: Pig Manual


问:
Cannot specify constructor arguments in declaration in C Sharp
This is the Question I am trying to solve in C Sharp.

I am getting an error:

Error Expected ; or = (cannot specify constructor arguments in declaration)

Can anyone help me to solve this or guide me to solve this?

```<code>namespace program
{
    public class Integer
    {
        private int intvar;
        public Integer()
        {
            intvar = 0;
        }
        public Integer(int x)
        {
            intvar = x;
        }
        public void display()
        {
            Console.Write(intvar);
            Console.Write("\n");
        }
        public void add(Integer x, Integer y)
        {
            intvar = x.intvar + y.intvar;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Integer a(5),b(45);
            Integer c;
            c.add(a,b);
            c.display();
            Console.ReadLine();
        }
    }
}
</code>```

答:
To create a new instance of a type, you have to invoke one of the constructors of that type using the new operator. For example:</p>

```<code>    class Program
    {
        static void Main(string[] args)
        {
            var a = new Integer(5);
            var b = new Integer(45);
            var c = new Integer(); //result instance
            c.add(a, b);
            c.display();
            Console.ReadLine();
        }
    }
</code>```

Body:
This is the Question I am trying to solve in C Sharp.

I am getting an error:

Error Expected ; or = (cannot specify constructor arguments in declaration)

Can anyone help me to solve this or guide me to solve this?

namespace program
{
    public class Integer
    {
        private int intvar;
        public Integer()
        {
            intvar = 0;
        }
        public Integer(int x)
        {
            intvar = x;
        }
        public void display()
        {
            Console.Write(intvar);
            Console.Write("\n");
        }
        public void add(Integer x, Integer y)
        {
            intvar = x.intvar + y.intvar;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Integer a(5),b(45);
            Integer c;
            c.add(a,b);
            c.display();
            Console.ReadLine();
        }
    }
}

Body:
To create a new instance of a type, you have to invoke one of the constructors of that type using the new operator. For example:

    class Program
    {
        static void Main(string[] args)
        {
            var a = new Integer(5);
            var b = new Integer(45);
            var c = new Integer(); //result instance
            c.add(a, b);
            c.display();
            Console.ReadLine();
        }
    }


问:
Datatables plugin
Is there any tutorial of how to use DataTables plugin with asp.net mvc(especially server side code)? Thanks</p>

答: See http://www.codeproject.com/KB/aspnet/JQuery-DataTables-MVC.aspx You have description and demo code.</p>

ContentLicense: CC BY-SA 2.5

Title: Datatables plugin


问:
How respond in HTML and JSON with Rails?
I have

(Home Controller)

```<code>    def default

        users = Users.all

        respond_to do |format|

            format.html
            format.json { render json: users}

        end

     end
</code>```

and

(view)

```<code>axios({
        method: 'get',
        url: '/home',
        headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }
        }).then(response => console.log(response))

</code>```

with the json headers but I get

```<code>ActionController::UnknownFormat (LoginController#default is missing a template for this request format and variant.

request.formats: ["application/json"]
request.variant: []):
</code>```

with the http error 406 (Not Acceptable)

Thank you for your help :)

Edit :

I find the problem, in fact my Rails took my request as '/homehome' I don't know why ? I change '/home' to '' in the axios url parameter and it's work now, but I still not understand what is happening ??

I have also in my web console this message

```<code>A cookie associated with a cross-site resource at http://youtube.com/ was set
without the `SameSite` attribute. A future release of Chrome will only deliver
cookies with cross-site requests if they are set with `SameSite=None` and
`Secure`. You can review cookies in developer tools under
Application>Storage>Cookies and see more details at
https://www.chromestatus.com/feature/5088147346030592 and
https://www.chromestatus.com/feature/5633521622188032.

</code>```

答: Has you ever try this config responseType: 'json', // default for axios, for detail you can read in the axios document.

Body:
I have

(Home Controller)

    def default

        users = Users.all

        respond_to do |format|

            format.html
            format.json { render json: users}

        end

     end

and

(view)

axios({
        method: 'get',
        url: '/home',
        headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }
        }).then(response => console.log(response))

with the json headers but I get

ActionController::UnknownFormat (LoginController#default is missing a template for this request format and variant.

request.formats: ["application/json"]
request.variant: []):

with the http error 406 (Not Acceptable)

Thank you for your help :)

Edit :

I find the problem, in fact my Rails took my request as '/homehome' I don't know why ? I change '/home' to '' in the axios url parameter and it's work now, but I still not understand what is happening ??

I have also in my web console this message

A cookie associated with a cross-site resource at http://youtube.com/ was set
without the `SameSite` attribute. A future release of Chrome will only deliver
cookies with cross-site requests if they are set with `SameSite=None` and
`Secure`. You can review cookies in developer tools under
Application>Storage>Cookies and see more details at
https://www.chromestatus.com/feature/5088147346030592 and
https://www.chromestatus.com/feature/5633521622188032.


问:
How to launch electron app from a node.js script on mac?
I have a simple electron app I want to run on multiple platforms.  I launch the app from a git hook.  I have multiple platform specific packages of the app published to npm.  The windows path is working great.  Here is my windows commit-msg hook script (which runs my electron apps .exe, works great):

```<code>#!/usr/bin/env node

var child_process = require('child_process');
const cFile = process.argv[2];

child_process.exec(`"C:\\users\\myuser\\nodejs\\node_modules\\azure-devops-work-items-win\\dist\\win\\azure-devops-work-items.exe" --repoPath=C:\\\\project\\.git\\hooks --commitFile=${cFile}`, (error, stdout, stderr) => {
    if (error !== null) {
        console.log(error);
        process.exit(1);
    }
});
</code>```

On mac I install this git hook script (which doesn't work).

```<code>#!/usr/bin/env node

var child_process = require('child_process');
const cFile = process.argv[2];

child_process.exec(`"/usr/local/lib/node_modules/azure-devops-work-items-mac/dist/mac/azure-devops-work-items.app" --repoPath=/Users/meeusen/appdev/.git/hooks --commitFile=${cFile}`, (error, stdout, stderr) => {
    if (error !== null) {
        console.log(error);
        process.exit(1);
    }
});
</code>```

When the mac hook runs it errors with this message:

```<code>MeeusenMacBookPro:appdev meeusen$ git commit . -m"."
Error: Command failed: "/usr/local/lib/node_modules/azure-devops-work-items-mac/dist/mac/azure-devops-work-items.app" --repoPath=/Users/meeusen/appdev/.git/hooks --commitFile=.git/COMMIT_EDITMSG
/bin/sh: /usr/local/lib/node_modules/azure-devops-work-items-mac/dist/mac/azure-devops-work-items.app: is a directory

    at ChildProcess.exithandler (child_process.js:303:12)
    at ChildProcess.emit (events.js:315:20)
    at maybeClose (internal/child_process.js:1021:16)
    at Socket.<anonymous> (internal/child_process.js:443:11)
    at Socket.emit (events.js:315:20)
    at Pipe.<anonymous> (net.js:674:12) {
  killed: false,
  code: 126,
  signal: null,
  cmd: '"/usr/local/lib/node_modules/azure-devops-work-items-mac/dist/mac/azure-devops-work-items.app" --repoPath=/Users/meeusen/appdev/.git/hooks --commitFile=.git/COMMIT_EDITMSG'
}
</code>```

It looks like I might be trying to launch this electron app wrong on the mac.  I'm a windows guy and am not sure if I'm going about this the right way.  What I want is to bundle my app with electron and then launch the platform specific binary via a nodejs script.  Should I be trying to launch the .app file?  Is there a better file that I should be trying to launch on mac?

I'm packaging my electron app with electron-builder -mwl.

My repo is here

答:
from the command line you can start *.app with open Like:

open /usr/local/lib/node_modules/azure-devops-work-items-mac/dist/mac/azure-devops-work-items.app

if you want to use command line switches, you can add an --args <actual arguments> but it wont print anything in the cli. Since your script might rely on that, then there is a file inside .app than can be run and it will behave more like a unix command. Most likely in your script it will look like:

/usr/local/lib/node_modules/azure-devops-work-items-mac/dist/mac/azure-devops-work-items.app/Contents/MacOS/azure-devops-work-items" --repoPath=/Users/meeusen/appdev/.git/hooks --commitFile=${cFile}

Body:
I have a simple electron app I want to run on multiple platforms.  I launch the app from a git hook.  I have multiple platform specific packages of the app published to npm.  The windows path is working great.  Here is my windows commit-msg hook script (which runs my electron apps .exe, works great):

#!/usr/bin/env node

var child_process = require('child_process');
const cFile = process.argv[2];

child_process.exec(`"C:\\users\\myuser\\nodejs\\node_modules\\azure-devops-work-items-win\\dist\\win\\azure-devops-work-items.exe" --repoPath=C:\\\\project\\.git\\hooks --commitFile=${cFile}`, (error, stdout, stderr) => {
    if (error !== null) {
        console.log(error);
        process.exit(1);
    }
});

On mac I install this git hook script (which doesn't work).

#!/usr/bin/env node

var child_process = require('child_process');
const cFile = process.argv[2];

child_process.exec(`"/usr/local/lib/node_modules/azure-devops-work-items-mac/dist/mac/azure-devops-work-items.app" --repoPath=/Users/meeusen/appdev/.git/hooks --commitFile=${cFile}`, (error, stdout, stderr) => {
    if (error !== null) {
        console.log(error);
        process.exit(1);
    }
});

When the mac hook runs it errors with this message:

MeeusenMacBookPro:appdev meeusen$ git commit . -m"."
Error: Command failed: "/usr/local/lib/node_modules/azure-devops-work-items-mac/dist/mac/azure-devops-work-items.app" --repoPath=/Users/meeusen/appdev/.git/hooks --commitFile=.git/COMMIT_EDITMSG
/bin/sh: /usr/local/lib/node_modules/azure-devops-work-items-mac/dist/mac/azure-devops-work-items.app: is a directory

    at ChildProcess.exithandler (child_process.js:303:12)
    at ChildProcess.emit (events.js:315:20)
    at maybeClose (internal/child_process.js:1021:16)
    at Socket.<anonymous> (internal/child_process.js:443:11)
    at Socket.emit (events.js:315:20)
    at Pipe.<anonymous> (net.js:674:12) {
  killed: false,
  code: 126,
  signal: null,
  cmd: '"/usr/local/lib/node_modules/azure-devops-work-items-mac/dist/mac/azure-devops-work-items.app" --repoPath=/Users/meeusen/appdev/.git/hooks --commitFile=.git/COMMIT_EDITMSG'
}

It looks like I might be trying to launch this electron app wrong on the mac.  I'm a windows guy and am not sure if I'm going about this the right way.  What I want is to bundle my app with electron and then launch the platform specific binary via a nodejs script.  Should I be trying to launch the .app file?  Is there a better file that I should be trying to launch on mac?

I'm packaging my electron app with electron-builder -mwl.

My repo is here


问:
Function-wide exception handling in c++ - is it a bad style?
There is a try-catch thing about functions, which I think sometimes may be quite useful:

```<code>bool function()
try
{
    //do something
}
catch(exception_type & t)
{
   //do something
}
</code>```

So the first part of the question: is this style considered bad in general case?

And the concrete example I used this approach in:

We had project with quite a lot of code in c and c++. And there we had custom exception types (not std::exception derived). I needed to integrate XML library and cast all exception to our types. So, basically, the last step was to catch all exceptions from XML library and convert them.

Function before:

```<code>bool readEntity(...)
{
   while(...)
   {
      if(...)
      {
         //lot's of code...
      }
   }
}
</code>```

after:

```<code>bool readEntity(...)
try
{
   while(...)
   {
      if(...)
      {
         //lot's of code...
      }
   }
}
catch(XMLBaseException & ex)
{
    //create our exception and throw
}
</code>```

My thoughts went something like this: I clearly state my intentions to convert all exception derived from one type into custom type AND we keep our screen without horizontal scroll bar (cause horizontal scroll bars are bad).

Well, I actually was quite criticized for this approach as for non-clear one during code review.

So I'd like to hear you thoughts.

UPDATE: just to be clear: refactoring the function wasn't an option. And actually it was good written one.

答: That function is supposed to return a bool so you can return a true or false but if the function were to fail and the bool was used for something other than success flag(which is bad practice unless pure c) it should throw to signal the caller it didn't work.</p>

Body:
There is a try-catch thing about functions, which I think sometimes may be quite useful:

bool function()
try
{
    //do something
}
catch(exception_type & t)
{
   //do something
}

So the first part of the question: is this style considered bad in general case?

And the concrete example I used this approach in:

We had project with quite a lot of code in c and c++. And there we had custom exception types (not std::exception derived). I needed to integrate XML library and cast all exception to our types. So, basically, the last step was to catch all exceptions from XML library and convert them.

Function before:

bool readEntity(...)
{
   while(...)
   {
      if(...)
      {
         //lot's of code...
      }
   }
}

after:

bool readEntity(...)
try
{
   while(...)
   {
      if(...)
      {
         //lot's of code...
      }
   }
}
catch(XMLBaseException & ex)
{
    //create our exception and throw
}

My thoughts went something like this: I clearly state my intentions to convert all exception derived from one type into custom type AND we keep our screen without horizontal scroll bar (cause horizontal scroll bars are bad).

Well, I actually was quite criticized for this approach as for non-clear one during code review.

So I'd like to hear you thoughts.

UPDATE: just to be clear: refactoring the function wasn't an option. And actually it was good written one.

OwnerDisplayName: Ctrl Alt D-1337

LastEditorDisplayName: Ctrl Alt D-1337


问:
count elements after DOM change
so currently using ajax with JQuery .post to return a form populate with some values. What I am trying to do is basically identify if the content contains checkboxes using:

```<code>var count = $('#form').find('checkbox').length;
alert(count);
</code>```

however even when it does contain checkboxes the output is 0. So do I have the syntax wrong or is it something to do with the fact the checkboxes weren't in the original DOM?

many thanks,

答:
There is no tag checkbox, you will need to use the :checkbox docs selector

```<code>$('#form').find(':checkbox').length;
</code>```

or the more verbose

```<code>$('#form').find('input[type="checkbox"]').length;
</code>```

Title: count elements after DOM change

Body:
so currently using ajax with JQuery .post to return a form populate with some values. What I am trying to do is basically identify if the content contains checkboxes using:

var count = $('#form').find('checkbox').length;
alert(count);

however even when it does contain checkboxes the output is 0. So do I have the syntax wrong or is it something to do with the fact the checkboxes weren't in the original DOM?

many thanks,

Body:
There is no tag checkbox, you will need to use the :checkbox docs selector

$('#form').find(':checkbox').length;

or the more verbose

$('#form').find('input[type="checkbox"]').length;


答:
Grid can do the trick

.grd {
  display: grid;
  grid-template-columns: auto;
  grid-template-rows: 50px;
}

.item1 {
  background-color: blue;
  width: 120px;
  grid-row: 1;
}

.item2 {
  background-color: pink;
  width: 1fr;
  grid-row: 1;
}

.item3 {
  background-color: red;
  width: 20px;
  grid-row: 1;
}

.item4 {
  background-color: darkblue;
  width: 1fr;
  grid-row: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grd">
  <div class="item1">One</div>
  <div class="item2">Two</div>
  <div class="item3">Three</div>
  <div class="item4">Four</div>
</div></code>```

Title: Fit content in to flex direction column

Body:
Im trying to fit content into a div with a flex.
Works perfectly into a flex-direction:row; (Standar) but isen´t work into a flex-direction:column;
In "column" just overflow my div, do not resize the elements inside.

How can i do to resize elemetns to fit into a div with out know cuantity of elemnts?

https://codepen.io/nandordena/pen/jObjJNw

HTML

    <video src="https://www.w3schools.com/tags/movie.ogg">

    <video src="https://www.w3schools.com/tags/movie.ogg">

    <video src="https://www.w3schools.com/tags/movie.ogg">

    <video src="https://www.w3schools.com/tags/movie.ogg">

    <video src="https://www.w3schools.com/tags/movie.ogg">

    <video src="https://www.w3schools.com/tags/movie.ogg">

CSS

div{
  border:solid 1px #f00;
  margin:1px;
  flex:1;
}
body{
  border:solid 1px #00f;
  pading:1px;
  display:flex;
  height: 500px;
  width: 500px;
}
.row{
  display:flex;
  flex-direction:row;
}
.column{
  display: flex;
  flex-direction:column;
}
video {
  max-height:100%;
  max-width:100%;
}

Body:
Grid can do the trick

.grd {
  display: grid;
  grid-template-columns: auto;
  grid-template-rows: 50px;
}

.item1 {
  background-color: blue;
  width: 120px;
  grid-row: 1;
}

.item2 {
  background-color: pink;
  width: 1fr;
  grid-row: 1;
}

.item3 {
  background-color: red;
  width: 20px;
  grid-row: 1;
}

.item4 {
  background-color: darkblue;
  width: 1fr;
  grid-row: 1;
}

<div class="grd">
  <div class="item1">One</div>
  <div class="item2">Two</div>
  <div class="item3">Three</div>
  <div class="item4">Four</div>
</div>