问:
Renaming object properties in an array of objects
I have the following structure:

```<code>const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        }
    ]
};
</code>```

I am wanting to re-name all instances of InvoiceNumber to CreditNoteNumber to give me the following:

```<code>const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        }
    ]
};
</code>```

I have tried various things like the following for example:

```<code>var changed = data.invoices.map(function(item) {
    return {
        ...data.invoices,
        CreditNoteNumber: item.InvoiceNumber
    };
});
</code>```

However the spread pushes CreditNoteNumber outside the object.

答:
the best option is to create a new object with the property item.CreditNoteNumber
and use a for each loop to iterate and reassign the values to the new object.

once the new object is created, assign the new object to the original object
data.invoices.

```<code>const data = {invoices: [{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"},{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"}]};

var newInvoices = [];

data.invoices.forEach((item) => {
 let invoice = {};
     invoice.Date = item.Date;
     invoice.CreditNoteNumber = item.InvoiceNumber;

  newInvoice.push(invoice);
});

data.invoices = newInvoices;

console.log(data.invoices);
</code>```

Body:
I have the following structure:

const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        }
    ]
};

I am wanting to re-name all instances of InvoiceNumber to CreditNoteNumber to give me the following:

const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        }
    ]
};

I have tried various things like the following for example:

var changed = data.invoices.map(function(item) {
    return {
        ...data.invoices,
        CreditNoteNumber: item.InvoiceNumber
    };
});

However the spread pushes CreditNoteNumber outside the object.

Body:
the best option is to create a new object with the property item.CreditNoteNumber
and use a for each loop to iterate and reassign the values to the new object.

once the new object is created, assign the new object to the original object
data.invoices.

const data = {invoices: [{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"},{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"}]};

var newInvoices = [];

data.invoices.forEach((item) => {
 let invoice = {};
     invoice.Date = item.Date;
     invoice.CreditNoteNumber = item.InvoiceNumber;

  newInvoice.push(invoice);
});

data.invoices = newInvoices;

console.log(data.invoices);


来源: stackexchange

问:
Material-UI Divider adds a scrollbar on the right hand side of the screen, when I remove it from the component, no ScrollBar
Is there any way to remove the scrollbar, it is being added whenever I add the divider to my Home, right below the menu. </p>

<p>Here is the code </p>

```<code>    return (
      <Box className={classes.root}>
        <Grid item xs={12}>
          <Header />
        </Grid>
        <Divider flexItem={true} className={classes.headerDivider}/>
        <Grid item xs={12}>
          {body}
        </Grid>
        <Grid item xs={12}>
          <Footer/>
        </Grid>
      </Box>
    );
  }
}
</code>```

答:
Add css to hide horizontal scroll</p>

```<code>.some-box-class {
  overflow-x: hidden;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is there any way to remove the scrollbar, it is being added whenever I add the divider to my Home, right below the menu.

Here is the code

    return (
      <Box className={classes.root}>
        <Grid item xs={12}>

        </Grid>
        <Divider flexItem={true} className={classes.headerDivider}/>
        <Grid item xs={12}>
          {body}
        </Grid>
        <Grid item xs={12}>

        </Grid>
      </Box>
    );
  }
}

Body:
Add css to hide horizontal scroll

.some-box-class {
  overflow-x: hidden;
}


问:
Simple Traefik reverse proxy configuration
I'm starting up Traefik version 2.1.4 with the following configuration:

```<code>defaultEntryPoints:
  - http

entryPoints:
  hole-1:
    address: ':663'

frontends:
  hole-frontend-1:
    backend: hole-backend-1
    entrypoints:
      - hole-1

backends:
  hole-backend-1:
    servers:
      hole-server-1:
        url: 'http://11.23.24.1:3000'
        weight: 10
</code>```

When I hit the http://11.23.24.1:663 I'm hit with the Traefik page 404 pages not found. When I go to http://11.23.24.1:3000 in the browser, it works, it displays the page.

I can't seem to figure out how to set up a reverse proxy in Traefik to point http://11.23.24.1:663 to http://11.23.24.1:3000.

I tried this, but I get the error

2020/02/18 11:39:43 command traefik.exe error: no valid configuration found in file: C:\config\traefik.yaml

```<code>http:
  routers:
    hole-router-1:
      rule: "Host(`11.23.24.1`) && PathPrefix(`/`)"
      service: hole-service

services:
  hole-service:
    loadBalancer:
      servers:
        - url: http://11.23.24.1:3000
</code>```

答:
C:\config\traefik\traefik.yaml:

```<code>entryPoints:
  hole-1:
    address: ":661"

providers:
  file:
    filename: C:\config\traefik\dynamic.yaml
</code>```

C:\config\traefik\dynamic.yaml:

```<code>http:
  routers:
    hole-router-1:
      rule: "Path(`/`)"
      entryPoints:
        - hole-1
      service: hole-service

  services:
    hole-service:
      loadBalancer:
        servers:
          - url: http://10.23.24.10:3000
</code>```

I started Traefik with: traefik.exe --configFile=C:/config/traefik/traefik.yaml

Body:
I'm starting up Traefik version 2.1.4 with the following configuration:

defaultEntryPoints:
  - http

entryPoints:
  hole-1:
    address: ':663'

frontends:
  hole-frontend-1:
    backend: hole-backend-1
    entrypoints:
      - hole-1

backends:
  hole-backend-1:
    servers:
      hole-server-1:
        url: 'http://11.23.24.1:3000'
        weight: 10

When I hit the http://11.23.24.1:663 I'm hit with the Traefik page 404 pages not found. When I go to http://11.23.24.1:3000 in the browser, it works, it displays the page.

I can't seem to figure out how to set up a reverse proxy in Traefik to point http://11.23.24.1:663 to http://11.23.24.1:3000.

I tried this, but I get the error

2020/02/18 11:39:43 command traefik.exe error: no valid configuration found in file: C:\config\traefik.yaml

http:
  routers:
    hole-router-1:
      rule: "Host(`11.23.24.1`) && PathPrefix(`/`)"
      service: hole-service

services:
  hole-service:
    loadBalancer:
      servers:
        - url: http://11.23.24.1:3000

Body:
C:\config\traefik\traefik.yaml:

entryPoints:
  hole-1:
    address: ":661"

providers:
  file:
    filename: C:\config\traefik\dynamic.yaml

C:\config\traefik\dynamic.yaml:

http:
  routers:
    hole-router-1:
      rule: "Path(`/`)"
      entryPoints:
        - hole-1
      service: hole-service

  services:
    hole-service:
      loadBalancer:
        servers:
          - url: http://10.23.24.10:3000

I started Traefik with: traefik.exe --configFile=C:/config/traefik/traefik.yaml


问:
java network event listener
Now, I want to implement an event listener to make network request to async like Object-c or Js.
I wanna to got the HeaderReceived evnent, How much bytes downloaded(means progress),got response event.
How can I do that?</p>

答: look at AsyncHttpClient. It's a good framework written by Jean-François Arcand (which has largely contributed to the Glassfish Application Server by writing large parts of the Grizzly web server)</p>

ContentLicense: CC BY-SA 3.0

Title: java network event listener


问:
Chrome 80: Pause script execution (F8) does not work when DevTools is not focused
since Chrome 80 I cannot pause the script execution when the focus is on the website I'm developing. This is extremely inconvenient e.g. when debugging hover effects.

Does anyone else experience this issue or has more information about it? Maybe a feature flag deep inside the browser settings?

Update

This was fixed in Chrome 83.

答:
Until it is fixed, you can use the following in your app:</p>

```<code>document.addEventListener('keydown', function (e) {
    if (e.keyCode == 119) { // F8
        debugger;
    }
}, {
    capture: true
});
</code>```

Body:
Until it is fixed, you can use the following in your app:

document.addEventListener('keydown', function (e) {
    if (e.keyCode == 119) { // F8
        debugger;
    }
}, {
    capture: true
});


问:
Convert argb to string
Which method allows convert ARGB to string as 'int, int, int'? Example. The $Main background color is set as a string '0, 100, 200'. Return $Main.BackColor gives ARGB but not string '0, 100, 200':

```<code>$Main  = [System.Windows.Forms.Form] @{
    BackColor = '0, 100, 200'
}

$Main.BackColor
--------------
R             : 0
G             : 100
B             : 200
A             : 255
IsKnownColor  : False
IsEmpty       : False
IsNamedColor  : False
IsSystemColor : False
Name          : ff0064c8
</code>```

The To.String() method returns the result Color [A=255, R=0, G=100, B=200]
. This is not what is expected.

At the moment I am doing this:

```<code> ('R', 'G', 'B').ForEach({ $Main.BackColor.$_ }) -join ', '

--------------
0, 100, 200
</code>```

However, I hope that there are special methods for converting as ARGB to string, as string to ARGB. What are these methods? Thanks

答:
As far as I know there is no custom string format in System.Drawing.Color. You need custom conversion. You can use your method or any other. I would use custom expression and string interpolation:

```<code>$c = [System.Drawing.Color]'0, 100, 200'

#simulate array
$c,$c | select @{N="Color";E={"$($_.R), $($_.G), $($_.B)"}}
</code>```

Result:

```<code>Color
-----
0, 100, 200
0, 100, 200
</code>```

Title: Convert argb to string

Body:
Which method allows convert ARGB to string as 'int, int, int'? Example. The $Main background color is set as a string '0, 100, 200'. Return $Main.BackColor gives ARGB but not string '0, 100, 200':

$Main  = [System.Windows.Forms.Form] @{
    BackColor = '0, 100, 200'
}

$Main.BackColor
--------------
R             : 0
G             : 100
B             : 200
A             : 255
IsKnownColor  : False
IsEmpty       : False
IsNamedColor  : False
IsSystemColor : False
Name          : ff0064c8

The To.String() method returns the result Color [A=255, R=0, G=100, B=200]
. This is not what is expected.

At the moment I am doing this:

 ('R', 'G', 'B').ForEach({ $Main.BackColor.$_ }) -join ', '

--------------
0, 100, 200

However, I hope that there are special methods for converting as ARGB to string, as string to ARGB. What are these methods? Thanks

Body:
As far as I know there is no custom string format in System.Drawing.Color. You need custom conversion. You can use your method or any other. I would use custom expression and string interpolation:

$c = [System.Drawing.Color]'0, 100, 200'

#simulate array
$c,$c | select @{N="Color";E={"$($_.R), $($_.G), $($_.B)"}}

Result:

Color
-----
0, 100, 200
0, 100, 200


问:
How to sum data from multiple rows, based on a condition in Teradata?
I am trying to sum the data, based on two columns, where the values in 2 of the rows are equal.
This is the table I have:

```<code>Country   | System     | Money
 AAA      | A          | 10
 AAA      | A          | 200
 AAA      | B          | 60
 BBB      | B          | 600
 BBB      | A          | 150
 BBB      | B          | 140
</code>```

This is what I want to achieve:

```<code>Country   | System     | Money  | SystemSum
 AAA      | A          | 10     |  210
 AAA      | A          | 200    |  210
 AAA      | B          | 60     |  60
 BBB      | B          | 600    |  740
 BBB      | A          | 150    |  150
 BBB      | B          | 140    |  740
</code>```

This is what I have tried:

```<code>SUM(Money) OVER (ORDER BY Country, System ROWS UNBOUNDED PRECEDING)
</code>```

but it returns the values cumulatively. How to do it correctly?

答:
You can do a group

```<code>select a.Country, a.System, a.Money, SystemSum
from tbl a inner join
(
    select Country, System,
    SUM(Money) as SystemSum
    from tbl
    group by Country, System
) b on a.Country = b.Country and a.System = b.System
</code>```

The window function used with ROWS UNBOUNDED PRECEDING will sum cumulatively all preceeding values of Money, hence the result you were having before

Body:
I am trying to sum the data, based on two columns, where the values in 2 of the rows are equal.
This is the table I have:

Country   | System     | Money
 AAA      | A          | 10
 AAA      | A          | 200
 AAA      | B          | 60
 BBB      | B          | 600
 BBB      | A          | 150
 BBB      | B          | 140

This is what I want to achieve:

Country   | System     | Money  | SystemSum
 AAA      | A          | 10     |  210
 AAA      | A          | 200    |  210
 AAA      | B          | 60     |  60
 BBB      | B          | 600    |  740
 BBB      | A          | 150    |  150
 BBB      | B          | 140    |  740

This is what I have tried:

SUM(Money) OVER (ORDER BY Country, System ROWS UNBOUNDED PRECEDING)

but it returns the values cumulatively. How to do it correctly?

Body:
You can do a group

select a.Country, a.System, a.Money, SystemSum
from tbl a inner join
(
    select Country, System,
    SUM(Money) as SystemSum
    from tbl
    group by Country, System
) b on a.Country = b.Country and a.System = b.System

The window function used with ROWS UNBOUNDED PRECEDING will sum cumulatively all preceeding values of Money, hence the result you were having before


问:
Possible bug in bookdown when compiling to PDF. Images get cut by the margins
When I compile my Bookdown books for pdf output I get figures cut by the left and right margins. This does not happen if I generate them with ggsave() myself and then add them with knitter::include_graphics().

```<code>    ---
    output:
      pdf_document: default
      html_document: default
    ---

    # Example
    ```{r example, message=FALSE}
    require(tidyverse)
    ggplot(data=iris, aes(x=Sepal.Length, y=Sepal.Width))+geom_point()
    ```
</code>```

I execute `bookdown::render("index.Rmd", output_format=pdf_book(keep_tex=TRUE))

I get this image as output (in main_files/figure-latex)

Is this a bug or is it just me? How can I solve it? I do not like very much the idea of ggsave() + knitr::include_image(), but it is the only workaround I got so far.

Extra information about my system

```<code>> xfun::session_info('bookdown')
R version 3.6.2 (2019-12-12)
Platform: x86_64-suse-linux-gnu (64-bit)
Running under: openSUSE Leap 15.1, RStudio 1.2.5019

Locale:
  LC_CTYPE=es_ES.UTF-8       LC_NUMERIC=C               LC_TIME=es_ES.UTF-8
  LC_COLLATE=es_ES.UTF-8     LC_MONETARY=es_ES.UTF-8    LC_MESSAGES=es_ES.UTF-8
  LC_PAPER=es_ES.UTF-8       LC_NAME=C                  LC_ADDRESS=C
  LC_TELEPHONE=C             LC_MEASUREMENT=es_ES.UTF-8 LC_IDENTIFICATION=C

Package version:
  base64enc_0.1.3 bookdown_0.17   digest_0.6.18   evaluate_0.14   glue_1.3.1
  graphics_3.6.2  grDevices_3.6.2 highr_0.3       htmltools_0.4.0 jsonlite_1.6
  knitr_1.28      magrittr_1.5    markdown_1.1    methods_3.6.2   mime_0.8
  Rcpp_1.0.3      rlang_0.4.4     rmarkdown_2.1   stats_3.6.2     stringi_1.2.4
  stringr_1.4.0   tinytex_0.18    tools_3.6.2     utils_3.6.2     xfun_0.8
  yaml_2.2.0
</code>```

答:
If you take a look at the fig_crop argument on the help page ?rmarkdown::pdf_document, you will see that figure files will be cropped by default if pdfcrop is available. You can turn this feature off via:

```<code>output:
  pdf_document:
    fig_crop: false
</code>```

Body:
When I compile my Bookdown books for pdf output I get figures cut by the left and right margins. This does not happen if I generate them with ggsave() myself and then add them with knitter::include_graphics().

    ---
    output:
      pdf_document: default
      html_document: default
    ---

    # Example
    ```{r example, message=FALSE}
    require(tidyverse)
    ggplot(data=iris, aes(x=Sepal.Length, y=Sepal.Width))+geom_point()
    ```

I execute `bookdown::render("index.Rmd", output_format=pdf_book(keep_tex=TRUE))

I get this image as output (in main_files/figure-latex)

Is this a bug or is it just me? How can I solve it? I do not like very much the idea of ggsave() + knitr::include_image(), but it is the only workaround I got so far.

Extra information about my system

> xfun::session_info('bookdown')
R version 3.6.2 (2019-12-12)
Platform: x86_64-suse-linux-gnu (64-bit)
Running under: openSUSE Leap 15.1, RStudio 1.2.5019

Locale:
  LC_CTYPE=es_ES.UTF-8       LC_NUMERIC=C               LC_TIME=es_ES.UTF-8
  LC_COLLATE=es_ES.UTF-8     LC_MONETARY=es_ES.UTF-8    LC_MESSAGES=es_ES.UTF-8
  LC_PAPER=es_ES.UTF-8       LC_NAME=C                  LC_ADDRESS=C
  LC_TELEPHONE=C             LC_MEASUREMENT=es_ES.UTF-8 LC_IDENTIFICATION=C

Package version:
  base64enc_0.1.3 bookdown_0.17   digest_0.6.18   evaluate_0.14   glue_1.3.1
  graphics_3.6.2  grDevices_3.6.2 highr_0.3       htmltools_0.4.0 jsonlite_1.6
  knitr_1.28      magrittr_1.5    markdown_1.1    methods_3.6.2   mime_0.8
  Rcpp_1.0.3      rlang_0.4.4     rmarkdown_2.1   stats_3.6.2     stringi_1.2.4
  stringr_1.4.0   tinytex_0.18    tools_3.6.2     utils_3.6.2     xfun_0.8
  yaml_2.2.0

Body:
If you take a look at the fig_crop argument on the help page ?rmarkdown::pdf_document, you will see that figure files will be cropped by default if pdfcrop is available. You can turn this feature off via:

output:
  pdf_document:
    fig_crop: false


问:
Adding the value parts of multiple HashMap into a new one
I have three HashMap<String, Integer> where some keys may be present in two/three Maps.

I'm looking for a new HashMap that will combine all three in a new one where the value part will be a simple summation of all the values (where key is same).

I did that with merge() method,

```<code>Map<String, Integer> combine = new HashMap<>(map1);

map2.forEach((k, v) -> combine.merge(k, v, Integer::sum));
map3.forEach((k, v) -> combine.merge(k, v, Integer::sum));
</code>```

Wondering, How can I do it using Stream and/or Collection classes?

答:
I suppose:

```<code>Map<String, Integer> combine = Stream.of(map1, map2, map3)
    .map(Map::entrySet)
    .flatMap(Set::stream)
    .collect(toMap(Entry::getKey, Entry::getValue, Math::addExact));
</code>```

This does have the advantage of not modifying any of the maps. You approach would be a problem if map1 happens to be an unmodifiable map.

In general, avoid modification for achieving results that don’t require it, especially when such a side effect is unexpected.

Body:
I have three HashMap<String, Integer> where some keys may be present in two/three Maps.

I'm looking for a new HashMap that will combine all three in a new one where the value part will be a simple summation of all the values (where key is same).

I did that with merge() method,

Map<String, Integer> combine = new HashMap<>(map1);

map2.forEach((k, v) -> combine.merge(k, v, Integer::sum));
map3.forEach((k, v) -> combine.merge(k, v, Integer::sum));

Wondering, How can I do it using Stream and/or Collection classes?

Body:
I suppose:

Map<String, Integer> combine = Stream.of(map1, map2, map3)
    .map(Map::entrySet)
    .flatMap(Set::stream)
    .collect(toMap(Entry::getKey, Entry::getValue, Math::addExact));

This does have the advantage of not modifying any of the maps. You approach would be a problem if map1 happens to be an unmodifiable map.

In general, avoid modification for achieving results that don’t require it, especially when such a side effect is unexpected.


问:
Fuzzy Match columns of Different Dataframe
Background

I have 2 data frames which has no common key to which I can merge them. Both df have a column that contains "entity name". One df contains 8000+ entities and the other close to 2000 entities.

Sample Data:

```<code>vendor_df=
     Name of Vendor                             City         State  ZIP
     FREDDIE LEES AMERICAN GOURMET SAUCE       St. Louis    MO     63101
     CITYARCHRIVER 2015 FOUNDATION             St. Louis    MO     63102
     GLAXOSMITHKLINE CONSUMER HEALTHCARE       St. Louis    MO     63102
     LACKEY SHEET METAL                        St. Louis    MO     63102

regulator_df =
     Name of Entity                    Committies
     LACKEY SHEET METAL                 Private
     PRIMUS STERILIZER COMPANY LLC      Private
     HELGET GAS PRODUCTS INC            Autonomous
     ORTHOQUEST LLC                     Governmant
</code>```

Problem Stmt:

I have to fuzzy match the entities of these two(Name of vendor & Name of Entity) columns and get a score. So, need to know if 1st value of dataframe 1(vendor_df) is matching with any of the 2000 entities of dataframe2(regulator_df).

StackOverflow Links I checked:

fuzzy match between 2 columns (Python)

create new column in dataframe using fuzzywuzzy

Apply fuzzy matching across a dataframe column and save results in a new column

Code

```<code>import pandas as pd
from fuzzywuzzy import fuzz
from fuzzywuzzy import process

vendor_df = pd.read_excel('C:\\Users\\40101584\\Desktop\\AUS CUB AML\\Vendors_Sheet.xlsx', sheet_name=0)

regulator_df = pd.read_excel('C:\\Users\\40101584\\Desktop\\AUS CUB AML\\Regulated_Vendors_Sheet.xlsx', sheet_name=0)

compare = pd.MultiIndex.from_product([vendor_df['Name of vendor'],
                                      regulator_df['Name of Entity']]).to_series()

def metrics(tup):
    return pd.Series([fuzz.ratio(*tup),
                      fuzz.token_sort_ratio(*tup)],
                     ['ratio', 'token'])

#compare.apply(metrics) -- Either this works or the below line

result = compare.apply(metrics).unstack().idxmax().unstack(0)
</code>```

Problems with Above Code:

The code works if the two dataframes are small but it is taking forever when I give the complete dataset. Above code is taken from 3rd link.

Any solution if the same thing can work fast or can work with large dataset?

UPDATE 1

Can the above code be made faster if we pass or hard-code a score say 80 which will filter series/dataframe only with fuzzyscore > 80 ?

答:
in my case also i need to look for only above 80. i modified your code as per my use case.hope it helps.</p>

```<code>compare = compare.apply(metrics)
compare_80=compare[(compare['ratio'] >80) & (compare['token'] >80)]
</code>```

Body:
Background

I have 2 data frames which has no common key to which I can merge them. Both df have a column that contains "entity name". One df contains 8000+ entities and the other close to 2000 entities.

Sample Data:

vendor_df=
     Name of Vendor                             City         State  ZIP
     FREDDIE LEES AMERICAN GOURMET SAUCE       St. Louis    MO     63101
     CITYARCHRIVER 2015 FOUNDATION             St. Louis    MO     63102
     GLAXOSMITHKLINE CONSUMER HEALTHCARE       St. Louis    MO     63102
     LACKEY SHEET METAL                        St. Louis    MO     63102

regulator_df =
     Name of Entity                    Committies
     LACKEY SHEET METAL                 Private
     PRIMUS STERILIZER COMPANY LLC      Private
     HELGET GAS PRODUCTS INC            Autonomous
     ORTHOQUEST LLC                     Governmant

Problem Stmt:

I have to fuzzy match the entities of these two(Name of vendor & Name of Entity) columns and get a score. So, need to know if 1st value of dataframe 1(vendor_df) is matching with any of the 2000 entities of dataframe2(regulator_df).

StackOverflow Links I checked:

fuzzy match between 2 columns (Python)

create new column in dataframe using fuzzywuzzy

Apply fuzzy matching across a dataframe column and save results in a new column

Code

import pandas as pd
from fuzzywuzzy import fuzz
from fuzzywuzzy import process

vendor_df = pd.read_excel('C:\\Users\\40101584\\Desktop\\AUS CUB AML\\Vendors_Sheet.xlsx', sheet_name=0)

regulator_df = pd.read_excel('C:\\Users\\40101584\\Desktop\\AUS CUB AML\\Regulated_Vendors_Sheet.xlsx', sheet_name=0)

compare = pd.MultiIndex.from_product([vendor_df['Name of vendor'],
                                      regulator_df['Name of Entity']]).to_series()

def metrics(tup):
    return pd.Series([fuzz.ratio(*tup),
                      fuzz.token_sort_ratio(*tup)],
                     ['ratio', 'token'])

#compare.apply(metrics) -- Either this works or the below line

result = compare.apply(metrics).unstack().idxmax().unstack(0)

Problems with Above Code:

The code works if the two dataframes are small but it is taking forever when I give the complete dataset. Above code is taken from 3rd link.

Any solution if the same thing can work fast or can work with large dataset?

UPDATE 1

Can the above code be made faster if we pass or hard-code a score say 80 which will filter series/dataframe only with fuzzyscore > 80 ?

Body:
in my case also i need to look for only above 80. i modified your code as per my use case.hope it helps.

compare = compare.apply(metrics)
compare_80=compare[(compare['ratio'] >80) & (compare['token'] >80)]


问:
Spring Kafka Unit Tests Triggers the listener, but the method cannot get the message using consumer.poll
We are using spring-kafka-test-2.2.8-RELEASE.
When I use the template to send the message, it triggers the listener correctly, but I can't get the message content in the consumer.poll. If i instantiate the KafkaTemplate without "wiring" it in a class attribute and Instantiate it based on a producer factory, it sends the message, but does not trigger the @KafkaListener, only work if I setup a Message Listener inside the @Test Method. I need to trigger the kafka listener and realize which Topic will be called next("sucess" topic when executed without errors, and "errorTopic" the listener throws an Exception) and the message content.</p>

```<code>    @RunWith(SpringRunner.class)
    @SpringBootTest
    @EmbeddedKafka(partitions = 1, topics = { "tp-in-gco-mao-notasfiscais" })
    public class InvoicingServiceTest {

         @Autowired
         private NFKafkaListener nfKafkaListener;

         @ClassRule
         public static EmbeddedKafkaRule broker = new EmbeddedKafkaRule(1, false, "tp-in-gco-mao-
         notasfiscais");

         @Value("${" + EmbeddedKafkaBroker.SPRING_EMBEDDED_KAFKA_BROKERS + "}")
         private String brokerAddresses;

         @Autowired
         private KafkaTemplate<Object, Object> template;

         @BeforeClass
         public static void setup() {
                System.setProperty(EmbeddedKafkaBroker.BROKER_LIST_PROPERTY,
              "spring.kafka.bootstrap-servers");
         }

         @Test
         public void testTemplate() throws Exception {
               NFServiceTest nfServiceTest = spy(new NFServiceTest());

               nfKafkaListener.setNfServiceClient(nfServiceTest);
               Map<String, Object> consumerProps =  KafkaTestUtils.consumerProps("teste9", "false", broker.getEmbeddedKafka());
               consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
               consumerProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
               consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, InvoiceDeserializer.class);
               consumerProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");

               DefaultKafkaConsumerFactory<Integer, Object> cf = new DefaultKafkaConsumerFactory<Integer, Object>(
            consumerProps);

           Consumer<Integer, Object> consumer = cf.createConsumer();

           broker.getEmbeddedKafka().consumeFromAnEmbeddedTopic(consumer, "tp-in-gco-mao-notasfiscais");

           ZfifNfMao zf = new ZfifNfMao();
           zf.setItItensnf(new Zfietb011());

           Zfietb011 zfietb011 = new Zfietb011();
           Zfie011 zfie011 = new Zfie011();
           zfie011.setMatkl("TESTE");
           zfietb011.getItem().add(zfie011);
           zf.setItItensnf(zfietb011);

           template.send("tp-in-gco-mao-notasfiscais", zf);
           List<ConsumerRecord<Integer, Object>> received = new ArrayList<>();
           int n = 0;
           while (received.size() < 1 && n++ < 10) {
                ConsumerRecords<Integer, Object> records1 = consumer.poll(Duration.ofSeconds(10));
                //records1  is always empty
                if (!records1.isEmpty()) {
                    records1.forEach(rec -> received.add(rec));
                }
           }

           assertThat(received).extracting(rec -> {
               ZfifNfMao zfifNfMaoRdesponse = (ZfifNfMao) rec.value();
               return zfifNfMaoRdesponse.getItItensnf().getItem().get(0).getMatkl();
            }).contains("TESTE");
            broker.getEmbeddedKafka().getKafkaServers().forEach(b -> b.shutdown());
            broker.getEmbeddedKafka().getKafkaServers().forEach(b -> b.awaitShutdown());
            consumer.close();
        }

        public static class NFServiceTest implements INFServiceClient {
            CountDownLatch latch = new CountDownLatch(1);

            @Override
            public ZfifNfMaoResponse enviarSap(ZfifNfMao zfifNfMao) {
                ZfifNfMaoResponse zfifNfMaoResponse = new ZfifNfMaoResponse();
                zfifNfMaoResponse.setItItensnf(new Zfietb011());

                Zfietb011 zfietb011 = new Zfietb011();
                Zfie011 zfie011 = new Zfie011();
                zfie011.setMatkl("TESTE");
                zfietb011.getItem().add(zfie011);
                zfifNfMaoResponse.setItItensnf(zfietb011);
                return zfifNfMaoResponse;
            }
        }
    }
</code>```

答:
You have two brokers; one created by @EmbeddedKafka and one created by the @ClassRule.

Use one or the other; preferably the @EmbeddedKafka and simply @Autowired the broker instance.

I am guessing the consumers are listening to different brokers; you can confirm that by looking at the INFO logs put out by the consumer config.

Body:
We are using spring-kafka-test-2.2.8-RELEASE.
When I use the template to send the message, it triggers the listener correctly, but I can't get the message content in the consumer.poll. If i instantiate the KafkaTemplate without "wiring" it in a class attribute and Instantiate it based on a producer factory, it sends the message, but does not trigger the @KafkaListener, only work if I setup a Message Listener inside the @Test Method. I need to trigger the kafka listener and realize which Topic will be called next("sucess" topic when executed without errors, and "errorTopic" the listener throws an Exception) and the message content.

    @RunWith(SpringRunner.class)
    @SpringBootTest
    @EmbeddedKafka(partitions = 1, topics = { "tp-in-gco-mao-notasfiscais" })
    public class InvoicingServiceTest {

         @Autowired
         private NFKafkaListener nfKafkaListener;

         @ClassRule
         public static EmbeddedKafkaRule broker = new EmbeddedKafkaRule(1, false, "tp-in-gco-mao-
         notasfiscais");

         @Value("${" + EmbeddedKafkaBroker.SPRING_EMBEDDED_KAFKA_BROKERS + "}")
         private String brokerAddresses;

         @Autowired
         private KafkaTemplate<Object, Object> template;

         @BeforeClass
         public static void setup() {
                System.setProperty(EmbeddedKafkaBroker.BROKER_LIST_PROPERTY,
              "spring.kafka.bootstrap-servers");
         }

         @Test
         public void testTemplate() throws Exception {
               NFServiceTest nfServiceTest = spy(new NFServiceTest());

               nfKafkaListener.setNfServiceClient(nfServiceTest);
               Map<String, Object> consumerProps =  KafkaTestUtils.consumerProps("teste9", "false", broker.getEmbeddedKafka());
               consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
               consumerProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
               consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, InvoiceDeserializer.class);
               consumerProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");

               DefaultKafkaConsumerFactory<Integer, Object> cf = new DefaultKafkaConsumerFactory<Integer, Object>(
            consumerProps);

           Consumer<Integer, Object> consumer = cf.createConsumer();

           broker.getEmbeddedKafka().consumeFromAnEmbeddedTopic(consumer, "tp-in-gco-mao-notasfiscais");

           ZfifNfMao zf = new ZfifNfMao();
           zf.setItItensnf(new Zfietb011());

           Zfietb011 zfietb011 = new Zfietb011();
           Zfie011 zfie011 = new Zfie011();
           zfie011.setMatkl("TESTE");
           zfietb011.getItem().add(zfie011);
           zf.setItItensnf(zfietb011);

           template.send("tp-in-gco-mao-notasfiscais", zf);
           List<ConsumerRecord<Integer, Object>> received = new ArrayList<>();
           int n = 0;
           while (received.size() < 1 && n++ < 10) {
                ConsumerRecords<Integer, Object> records1 = consumer.poll(Duration.ofSeconds(10));
                //records1  is always empty
                if (!records1.isEmpty()) {
                    records1.forEach(rec -> received.add(rec));
                }
           }

           assertThat(received).extracting(rec -> {
               ZfifNfMao zfifNfMaoRdesponse = (ZfifNfMao) rec.value();
               return zfifNfMaoRdesponse.getItItensnf().getItem().get(0).getMatkl();
            }).contains("TESTE");
            broker.getEmbeddedKafka().getKafkaServers().forEach(b -> b.shutdown());
            broker.getEmbeddedKafka().getKafkaServers().forEach(b -> b.awaitShutdown());
            consumer.close();
        }

        public static class NFServiceTest implements INFServiceClient {
            CountDownLatch latch = new CountDownLatch(1);

            @Override
            public ZfifNfMaoResponse enviarSap(ZfifNfMao zfifNfMao) {
                ZfifNfMaoResponse zfifNfMaoResponse = new ZfifNfMaoResponse();
                zfifNfMaoResponse.setItItensnf(new Zfietb011());

                Zfietb011 zfietb011 = new Zfietb011();
                Zfie011 zfie011 = new Zfie011();
                zfie011.setMatkl("TESTE");
                zfietb011.getItem().add(zfie011);
                zfifNfMaoResponse.setItItensnf(zfietb011);
                return zfifNfMaoResponse;
            }
        }
    }


问:
jQuery UI How to Open a Dialog, append to a div not the body
I'm using this simple modal dialog example here:
http://jqueryui.com/demos/dialog/modal-form.html

When the page loads, jQuery removes the dialog's div from the DOM. When the button is clicked to open the dialog, jQuery appends the dialog's div to the end of the body element.

I want to append it to a certain div, not the body. The reason is I have a large form on the page, and in the dialog is a single file input (no seperate form). I want to keep my file input in the dialog, within the same form as the rest of the fields on the page (which aren't in the dialog).

Is it possible to append the dialog to a given div or element?

答:
Just tackled this myself yesterday. The way I solved it was to insert an empty div at the bottom of the form (

) then when closing the dialogue, move it's contents into that div.
In my case, the code was something like this:

```<code>        // Setup up dialogue box that contains some form fields:
        $j("#myDialogue").dialog({
            autoOpen: false,
            height: 300,
            width: 350,
            modal: true,
            buttons: {
                "Submit": function() {
                    // Move to main form so fields get included:
                    $j(this).parent().prependTo($j("#bottomOfForm"));
                    // Submit the main form:
                    $j('#mainForm').submit();
                },
                Cancel: function() {
                    $j(this).dialog( "close" );
                }
            }
        });
</code>```

Body:
Just tackled this myself yesterday. The way I solved it was to insert an empty div at the bottom of the form (<div id="bottomOfForm"></div>) then when closing the dialogue, move it's contents into that div.
In my case, the code was something like this:

        // Setup up dialogue box that contains some form fields:
        $j("#myDialogue").dialog({
            autoOpen: false,
            height: 300,
            width: 350,
            modal: true,
            buttons: {
                "Submit": function() {
                    // Move to main form so fields get included:
                    $j(this).parent().prependTo($j("#bottomOfForm"));
                    // Submit the main form:
                    $j('#mainForm').submit();
                },
                Cancel: function() {
                    $j(this).dialog( "close" );
                }
            }
        });


问:
Why page not working after putting valid user check?
i want to protect a page with a user script and after putting this 4 lines of code, login system works, but i received many Undefined index and Undefined offset errors and any class.

it's like that Require_once and include not working at same.

Image of the error:

```<code><?php
  define("_WOJO", true);
  require_once("../../init.php");
  if (!Membership::is_valid([1]))
  Url::redirect(SITEURL);// back to login screen when not valid user
?>

// begin of code when valid user (1)

<?php

define("FLG_CFG", TRUE);
include("inc/config.php");

##################################################
# page configuration
$page['title'] = 'Nog te factureren';
##################################################
# table
$sql['table'] = 'woningopdrachten';
//$sql['joins'][] = 'JOIN company ON company.id_company = user.id_company';
# fields array(column, alias, asc/desc, type, responsive, hidden)
$sql['fields'][] = array('woningopdrachten.id', 'id');
$sql['fields'][] = array('woningopdrachten.makelaar', 'makelaarr', true);
$sql['fields'][] = array('woningopdrachten.adres', 'adres', true);
$sql['fields'][] = array('woningopdrachten.plaats', 'plaats', true);
$sql['fields'][] = array('woningopdrachten.pakket', 'pakket', true);
$sql['fields'][] = array('woningopdrachten.datum', 'datum', true);
//$sql['fields'][] = array('woningopdrachten.status', 'status', true);
//

//$sql['fields'][] = array('woningopdrachten.id', 'view');
//$sql['fields'][] = array('woningopdrachten.id', 'afsluiten');
//$sql['fields'][] = array('woningopdrachten.id', 'datumaanpas');
//$sql['fields'][] = array('woningopdrachten.id', 'delete');

# extras
$sql['groupby'] = false;
$sql['new'] = false;
# delete handler
check_delete();
##################################################
# header
include('div/header.php');
# table
# Filter op (laat enkel opdrachten zien waarvan nog een bon gemaakt moet worden#
//$sql['filters'][] = array('woningopdrachten.status = :woningopdrachten.status', ':woningopdrachten.status', 2, PDO::PARAM_INT);
$sql['filters'][] = array('woningopdrachten.status LIKE :status', ':status', "%factureren%", PDO::PARAM_STR);
grid($sql);
# footer
include('div/footer.php');
</code>```

答:
It's hard to say specifically without looking at the other files, but there shouldn't be any issue caused by using multiple requires/includes on the same page.

Where you are getting the undefined index/offset errors, you can use something like var_dump() https://www.php.net/manual/en/function.var-dump.php or print_r() https://www.php.net/manual/en/function.print-r.php to get more information about those variables and see what is contained in them vs. what you are expecting to be there.

Body:
i want to protect a page with a user script and after putting this 4 lines of code, login system works, but i received many Undefined index and Undefined offset errors and any class.

it's like that Require_once and include not working at same.

Image of the error:

<?php
  define("_WOJO", true);
  require_once("../../init.php");
  if (!Membership::is_valid([1]))
  Url::redirect(SITEURL);// back to login screen when not valid user
?>

// begin of code when valid user (1)

<?php

define("FLG_CFG", TRUE);
include("inc/config.php");

##################################################
# page configuration
$page['title'] = 'Nog te factureren';
##################################################
# table
$sql['table'] = 'woningopdrachten';
//$sql['joins'][] = 'JOIN company ON company.id_company = user.id_company';
# fields array(column, alias, asc/desc, type, responsive, hidden)
$sql['fields'][] = array('woningopdrachten.id', 'id');
$sql['fields'][] = array('woningopdrachten.makelaar', 'makelaarr', true);
$sql['fields'][] = array('woningopdrachten.adres', 'adres', true);
$sql['fields'][] = array('woningopdrachten.plaats', 'plaats', true);
$sql['fields'][] = array('woningopdrachten.pakket', 'pakket', true);
$sql['fields'][] = array('woningopdrachten.datum', 'datum', true);
//$sql['fields'][] = array('woningopdrachten.status', 'status', true);
//

//$sql['fields'][] = array('woningopdrachten.id', 'view');
//$sql['fields'][] = array('woningopdrachten.id', 'afsluiten');
//$sql['fields'][] = array('woningopdrachten.id', 'datumaanpas');
//$sql['fields'][] = array('woningopdrachten.id', 'delete');

# extras
$sql['groupby'] = false;
$sql['new'] = false;
# delete handler
check_delete();
##################################################
# header
include('div/header.php');
# table
# Filter op (laat enkel opdrachten zien waarvan nog een bon gemaakt moet worden#
//$sql['filters'][] = array('woningopdrachten.status = :woningopdrachten.status', ':woningopdrachten.status', 2, PDO::PARAM_INT);
$sql['filters'][] = array('woningopdrachten.status LIKE :status', ':status', "%factureren%", PDO::PARAM_STR);
grid($sql);
# footer
include('div/footer.php');


问:
"Key is invalid" message on GitHub
I have generated SSH keys for a new server installation according to the procedure outlined here. However, when I copy the contents of id_rsa.pub to my keys list on GitHub, I get the error message "Key is invalid. Ensure you've copied the file correctly."

The generated key is valid, and I am copying it exactly as is (all in one line with no whitespace at the beginning/end).

Anybody have an idea what could be going on?

答:
To Copy the entire content of id_rsa.pub to clipboard:

Run >  pbcopy  ~/.ssh/id_rsa.pub

Title: "Key is invalid" message on GitHub


问:
C# Linq using arrays inside where
I would like to output all values in the filename array and filter them out through the Where Instruction. I tried to loop it. The problem is, the values are displayed twice.

```<code>var files = from file in Directory.EnumerateFiles(Path, "*.TXT", SearchOption.AllDirectories)
            from line in File.ReadLines(file)
            where line.Contains(Filename[i])
            select new
            {
                File = file,
                Line = line
            };
foreach (var line in files)
{
    Console.WriteLine($"{line.Line}");
}
</code>```

Is there a Problem with my logic or am i Using Linq wrong ?

答:
After question is edited:

Use this code to get existing files:

```<code>var txtPath = Path.Combine(dirPath, txtFileName);
var txtLines = File.ReadAllLines(txtPath).ToList();
var filesFound = from file in Directory.EnumerateFiles(dirPath, "*.DST", SearchOption.AllDirectories)
                 where txtLines.Contains(Path.GetFileName(file))
                 select new
                 {
                     File = file,
                     Line = Path.GetFileName(file)
                 };

foreach (var line in filesFound)
    Console.WriteLine($"{line.Line}");
</code>```

Use this code to get missing file(name)s:

```<code>var existingFiles = filesFound.Select(s => s.Line).ToList();
var missingFiles = txtLines.Except(existingFiles);
</code>```

Or:

```<code>var txtPath = Path.Combine(dirPath, txtFileName);
var txtLines = File.ReadAllLines(txtPath).ToList();
var filesMissing = txtLines.Except(from file in Directory.EnumerateFiles(dirPath, "*.DST", SearchOption.AllDirectories)
                                   where txtLines.Contains(Path.GetFileName(file))
                                   select Path.GetFileName(file));

foreach (var line in filesMissing)
    Console.WriteLine(line);
</code>```

The 2nd has at least twice better performance. Especially if you don't need filePath at all --> since missing files don't have one.

For Original question:

Maybe you have the duplication because either there is 2 file in your foder but you are using the same filename for check or there is 2 line in your file, that matches with the filename.

What is more important to answer your question is:

Do you want to filter out files that has its own name within, or do you want to get all files only once when they have their own name within?

You chose the former, so the solution:

```<code>var files = from file in Directory.EnumerateFiles(path, "*.TXT", SearchOption.AllDirectories)
            from line in File.ReadLines(file)
            where !line.Contains(System.IO.Path.GetFileName(file))  //note the exclamation mark, this is how you filter
            select new
            {
                File = file,
                Line = line
            };

foreach (var line in files)
    Console.WriteLine($"{line.Line}");
</code>```

You probably noticed that you don't need the array.

Title: C# Linq using arrays inside where

Body:
I would like to output all values in the filename array and filter them out through the Where Instruction. I tried to loop it. The problem is, the values are displayed twice.

var files = from file in Directory.EnumerateFiles(Path, "*.TXT", SearchOption.AllDirectories)
            from line in File.ReadLines(file)
            where line.Contains(Filename[i])
            select new
            {
                File = file,
                Line = line
            };
foreach (var line in files)
{
    Console.WriteLine($"{line.Line}");
}

Is there a Problem with my logic or am i Using Linq wrong ?

Body:
After question is edited:

Use this code to get existing files:

var txtPath = Path.Combine(dirPath, txtFileName);
var txtLines = File.ReadAllLines(txtPath).ToList();
var filesFound = from file in Directory.EnumerateFiles(dirPath, "*.DST", SearchOption.AllDirectories)
                 where txtLines.Contains(Path.GetFileName(file))
                 select new
                 {
                     File = file,
                     Line = Path.GetFileName(file)
                 };

foreach (var line in filesFound)
    Console.WriteLine($"{line.Line}");

Use this code to get missing file(name)s:

var existingFiles = filesFound.Select(s => s.Line).ToList();
var missingFiles = txtLines.Except(existingFiles);

Or:

var txtPath = Path.Combine(dirPath, txtFileName);
var txtLines = File.ReadAllLines(txtPath).ToList();
var filesMissing = txtLines.Except(from file in Directory.EnumerateFiles(dirPath, "*.DST", SearchOption.AllDirectories)
                                   where txtLines.Contains(Path.GetFileName(file))
                                   select Path.GetFileName(file));

foreach (var line in filesMissing)
    Console.WriteLine(line);

The 2nd has at least twice better performance. Especially if you don't need filePath at all --> since missing files don't have one.

For Original question:

Maybe you have the duplication because either there is 2 file in your foder but you are using the same filename for check or there is 2 line in your file, that matches with the filename.

What is more important to answer your question is:

Do you want to filter out files that has its own name within, or do you want to get all files only once when they have their own name within?

You chose the former, so the solution:

var files = from file in Directory.EnumerateFiles(path, "*.TXT", SearchOption.AllDirectories)
            from line in File.ReadLines(file)
            where !line.Contains(System.IO.Path.GetFileName(file))  //note the exclamation mark, this is how you filter
            select new
            {
                File = file,
                Line = line
            };

foreach (var line in files)
    Console.WriteLine($"{line.Line}");

You probably noticed that you don't need the array.


问:
How to avoid use of crawler in aws glue
AWS glue crawler has cost associated with it, how to avoid us of the crawler in aws glue.

Is there any way we can avoid the use of crawler and infer schema from any other option, so that cost can be reduced.

答:
You can use Athena to create tables in Glue catalog, but to do so you need to know the schema of the file or you can get the DDL from the existing table created by running SHOW CREATE TABLE
 in Athena and then you can modified the DDL statement according to your schema.

DDL queries are free in Athena and incurs no charges.

One other way of doing it is by issuing a Glue create table API call. Please refer to this for python syntax.

Title: How to avoid use of crawler in aws glue

Body:
You can use Athena to create tables in Glue catalog, but to do so you need to know the schema of the file or you can get the DDL from the existing table created by running SHOW CREATE TABLE <table-name> in Athena and then you can modified the DDL statement according to your schema.

DDL queries are free in Athena and incurs no charges.

One other way of doing it is by issuing a Glue create table API call. Please refer to this for python syntax.


问:
How to open a different activity on recyclerView item onclick
i am using a recyclerView to show my listitems in the navigation drawer.I have implemented the onclickListener but i have been stuck on how to open a different activity when items are clicked. All my items do on item click as of now as per the code is to display a toast with the item position.

I would appreciate the help.

AdapterClass.java

public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {
    private LayoutInflater inflater;
    private Context context;
List<Information>data= Collections.emptyList();
    public AdapterClass(Context context,List<Information>data){
        this.context=context;

        inflater= LayoutInflater.from(context);
        this.data=data;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       View view= inflater.inflate(R.layout.custom_row,parent,false);
        MyViewHolder holder=new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Information current=data.get(position);
        holder.title.setText(current.title);
        holder.icon.setImageResource(current.iconId);

    }

    @Override
    public int getItemCount() {
        return data.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        TextView title;
        ImageView icon;

        public MyViewHolder(View itemView) {
            super(itemView);
            title=(TextView)itemView.findViewById(R.id.listText);
           icon=(ImageView)itemView.findViewById(R.id.listIcon);
            itemView.setClickable(true);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {

            Toast.makeText(context,"The Item Clicked is: "+getPosition(),Toast.LENGTH_SHORT).show();
        }
    };
}```
</div>
</div>
</p>

```Log  cat error after implementing Konrad's solution

    02-27 15:24:52.833: D/AndroidRuntime(1630): --------- beginning of crash
02-27 15:24:52.834: E/AndroidRuntime(1630): FATAL EXCEPTION: main
02-27 15:24:52.834: E/AndroidRuntime(1630): Process: com.snappy.stevekamau.snappy, PID: 1630
02-27 15:24:52.834: E/AndroidRuntime(1630): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.snappy.stevekamau.snappy/com.snappy.stevekamau.snappy.YourActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.access$800(ActivityThread.java:144)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.os.Looper.loop(Looper.java:135)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.main(ActivityThread.java:5221)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at java.lang.reflect.Method.invoke(Native Method)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at java.lang.reflect.Method.invoke(Method.java:372)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
02-27 15:24:52.834: E/AndroidRuntime(1630): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.internal.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:95)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.internal.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:88)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.internal.app.ToolbarActionBar.<init>(ToolbarActionBar.java:84)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.app.ActionBarActivityDelegateBase.setSupportActionBar(ActionBarActivityDelegateBase.java:175)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.app.ActionBarActivity.setSupportActionBar(ActionBarActivity.java:92)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at com.snappy.stevekamau.snappy.YourActivity.onCreate(YourActivity.java:18)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.Activity.performCreate(Activity.java:5933)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
02-27 15:24:52.834: E/AndroidRuntime(1630):     ... 10 more
02-27 15:24:52.839: W/ActivityManager(464):   Force finishing activity com.snappy.stevekamau.snappy/.YourActivity
02-27 15:24:52.841: W/ActivityManager(464):   Force finishing activity com.snappy.stevekamau.snappy/.MainActivity
```

答:
This question has been asked long ago but none of the answers above helped me out, though Milad Moosavi`s answer was very close.
To open a new activity from a certain position on the recycler view, the following code may help:</p>

```<code>
    @Override
    public void onBindViewHolder(@NonNull TripViewHolder holder, int position) {
        Trip currentTrip = trips.get(position);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(), EditTrip.class);
                v.getContext().startActivity(intent);
            }
        });

        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Intent intent = new Intent(v.getContext(), ReadTripActivity.class);
                v.getContext().startActivity(intent);

                return false;
            }
        });
    }
</code>```

Body:
i am using a recyclerView to show my listitems in the navigation drawer.I have implemented the onclickListener but i have been stuck on how to open a different activity when items are clicked. All my items do on item click as of now as per the code is to display a toast with the item position.

I would appreciate the help.

AdapterClass.java

public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {
    private LayoutInflater inflater;
    private Context context;
List<Information>data= Collections.emptyList();
    public AdapterClass(Context context,List<Information>data){
        this.context=context;

        inflater= LayoutInflater.from(context);
        this.data=data;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       View view= inflater.inflate(R.layout.custom_row,parent,false);
        MyViewHolder holder=new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Information current=data.get(position);
        holder.title.setText(current.title);
        holder.icon.setImageResource(current.iconId);

    }

    @Override
    public int getItemCount() {
        return data.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        TextView title;
        ImageView icon;

        public MyViewHolder(View itemView) {
            super(itemView);
            title=(TextView)itemView.findViewById(R.id.listText);
           icon=(ImageView)itemView.findViewById(R.id.listIcon);
            itemView.setClickable(true);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {

            Toast.makeText(context,"The Item Clicked is: "+getPosition(),Toast.LENGTH_SHORT).show();
        }
    };
}

Log  cat error after implementing Konrad's solution

    02-27 15:24:52.833: D/AndroidRuntime(1630): --------- beginning of crash
02-27 15:24:52.834: E/AndroidRuntime(1630): FATAL EXCEPTION: main
02-27 15:24:52.834: E/AndroidRuntime(1630): Process: com.snappy.stevekamau.snappy, PID: 1630
02-27 15:24:52.834: E/AndroidRuntime(1630): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.snappy.stevekamau.snappy/com.snappy.stevekamau.snappy.YourActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.access$800(ActivityThread.java:144)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.os.Looper.loop(Looper.java:135)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.main(ActivityThread.java:5221)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at java.lang.reflect.Method.invoke(Native Method)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at java.lang.reflect.Method.invoke(Method.java:372)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
02-27 15:24:52.834: E/AndroidRuntime(1630): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.internal.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:95)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.internal.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:88)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.internal.app.ToolbarActionBar.<init>(ToolbarActionBar.java:84)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.app.ActionBarActivityDelegateBase.setSupportActionBar(ActionBarActivityDelegateBase.java:175)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.app.ActionBarActivity.setSupportActionBar(ActionBarActivity.java:92)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at com.snappy.stevekamau.snappy.YourActivity.onCreate(YourActivity.java:18)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.Activity.performCreate(Activity.java:5933)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
02-27 15:24:52.834: E/AndroidRuntime(1630):     ... 10 more
02-27 15:24:52.839: W/ActivityManager(464):   Force finishing activity com.snappy.stevekamau.snappy/.YourActivity
02-27 15:24:52.841: W/ActivityManager(464):   Force finishing activity com.snappy.stevekamau.snappy/.MainActivity

Body:
This question has been asked long ago but none of the answers above helped me out, though Milad Moosavi`s answer was very close.
To open a new activity from a certain position on the recycler view, the following code may help:

    @Override
    public void onBindViewHolder(@NonNull TripViewHolder holder, int position) {
        Trip currentTrip = trips.get(position);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(), EditTrip.class);
                v.getContext().startActivity(intent);
            }
        });

        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Intent intent = new Intent(v.getContext(), ReadTripActivity.class);
                v.getContext().startActivity(intent);

                return false;
            }
        });
    }


问:
The creation of bundle by webpack might be a problem to download
I was learning how Webpack works. As I found out one of the webpack's benefits is that out of several files webpack creates one bundle. I know the benefit of the creation of bundle is that instead of making several HTTP requests and with bundle we make only one request which does not stress the web server. The question is How can a bundle be useful since the bundle can weigh much in terms of size and which can take long time to download? That is, one combined file can be, say, big in size and it will take longer to download rather than to download several small files. I am just confused about this</p>

答: According to my research, even if initially our JS bundle have big size, there is something called "tree shaking" which removes all of the unnecessary code from the bundle. So, the bundle will ultimately contain only the code we need. For more info https://www.sitepoint.com/beginners-guide-webpack-module-bundling/</p>


答:
You can do a window sum, but you need to remove the rows clause: since you specified rows unbounded preceding, the query only considers the preceding rows, while you want to sum over the entire partition:

```<code>select
    t.*,
    sum(money) over(partition by country, system) systemsum
from mytable as t
</code>```

Side note: specifying preceding rows without an order by does not really make sense - with this syntax, you get an undefined set of rows being considered within the partition.

Title: How to sum data from multiple rows, based on a condition in Teradata?

Body:
You can do a window sum, but you need to remove the rows clause: since you specified rows unbounded preceding, the query only considers the preceding rows, while you want to sum over the entire partition:

select
    t.*,
    sum(money) over(partition by country, system) systemsum
from mytable as t

Side note: specifying preceding rows without an order by does not really make sense - with this syntax, you get an undefined set of rows being considered within the partition.


问:
Need Clarification on error Android Development with Visual Studio
I am trying to learn more about developing apps on Android by following this guide.

When I attempt to run the blank Cordova project I get an error, regardless if I turn deploy ON or OFF.

With deploy OFF I get the error(s):

Unable to get launched browser process for your app.

With deploy ON I get the error(s):

```<code>assert.js:90

AssertionError: missing path

at Function.Module.runMain (module.js:441:10)

at Function.Module._load (module.js:300:12)

at Module.load (module.js:343:32)

at Module.require (module.js:351:3)

at Module._compile (module.js:409:26)

at node.js:968:3

at Object.<anonymous> (C:\ProgramData\Microsoft\VisualStudio\MDA\f6dfaae9\taco-toolset-6.3.1\simulate.js:15:13)
Description

at Object.Module._extensions..js (module.js:416:10)

at require (internal/module.js:12:17)

at startup (node.js:139:18)

Node process unexpectedly exited while waiting for property 'appUrl'.

throw new assert.AssertionError(
</code>```

As I am fairly new to Android development and Visual Studio, any help would be appreciated.

I have installed Google Chrome.

答:
I recently came across the same problem. Through command lines bellow I discovered that the configuration of one plugin was wrong

```<code>cordova clean android
</code>```

and

```<code>cordova build android
</code>```

I hope to help someone in the same situation.

Body:
I am trying to learn more about developing apps on Android by following this guide.

When I attempt to run the blank Cordova project I get an error, regardless if I turn deploy ON or OFF.

With deploy OFF I get the error(s):

Unable to get launched browser process for your app.

With deploy ON I get the error(s):

assert.js:90

AssertionError: missing path

at Function.Module.runMain (module.js:441:10)

at Function.Module._load (module.js:300:12)

at Module.load (module.js:343:32)

at Module.require (module.js:351:3)

at Module._compile (module.js:409:26)

at node.js:968:3

at Object.<anonymous> (C:\ProgramData\Microsoft\VisualStudio\MDA\f6dfaae9\taco-toolset-6.3.1\simulate.js:15:13)
Description

at Object.Module._extensions..js (module.js:416:10)

at require (internal/module.js:12:17)

at startup (node.js:139:18)

Node process unexpectedly exited while waiting for property 'appUrl'.

throw new assert.AssertionError(

As I am fairly new to Android development and Visual Studio, any help would be appreciated.

I have installed Google Chrome.

Body:
I recently came across the same problem. Through command lines bellow I discovered that the configuration of one plugin was wrong

cordova clean android

and

cordova build android

I hope to help someone in the same situation.


问:
Plotting y values of an arc
I am trying to plot the segment of a circle (2D) as an arc in matplotlib.  I have written a class which will provide the maths for the segment such as chord length, height of arc etc.  I wish to plot the x y values between (0,0) and (0, chord length).

I am currently representing the X values as numpy linspace array (0, chordLength, 200).  I am a bit stumped as to how to plot the y values as a similar linspace array so that I can plot these points using matplotlib.  The idea behind this is to display the curvature of the earth between two points of a known arc length (great circle distance).  I have been reading around sine cosine etc however outside of using cookie cutter formulas for my geometry calculations, I am somewhat lost as to how to apply it to gain my y values.

First, the circle class

import numpy as np

class Circle:

    def __init__(self,radiusOfCircle,lengthOfArc):
        self.radius = radiusOfCircle
        self.circumference = 2 * np.pi * self.radius
        self.diameter = self.radius * 2
        self.arcLength = lengthOfArc
        self.degrees = self.calcDegrees()
        self.radians = self.calcRadians()
        self.chordLength = self.calcChordLength()
        self.sagitta = self.calcSagitta()
        self.segmentArea = self.calcSegmentArea()
        self.arcHeight = self.calcArcHeight()

    #Setters and getters for the Circle class (TODO: setters)
    def getRadius(self):
        return self.radius

    def getCircumference(self):
        return self.circumference

    def getDiameter(self):
        return self.diameter

    def getArcLength(self):
        return self.arcLength

    def getRadians(self):
        return self.radians

    def getDegrees(self):
        return self.degrees

    def getChordLength(self):
        return self.chordLength

    def getSagitta(self):
        return self.sagitta

    def getSegmentArea(self):
        return self.segmentArea

    def getArcHeight(self):
        return self.arcHeight

    #Define Circle class methods

    #Calculate the central angle, in degrees, by using the arcLength
    def calcDegrees(self):
        self.degrees = (self.arcLength / (np.pi * self.diameter)) * 360 #Gives angle in degrees at centre of the circle between the two points (beginning and end points of arcLength)
        return self.degrees

    #Calculate the central angle in radians, between two points on the circle
    def calcRadians(self):#Where theta is the angle between both points at the centre of the circle
        self.radians = np.radians(self.degrees) # Convert degrees to radians to work with ChordLength formula
        return self.radians

    #Returns the chord lengths of the arc, taking theta (angle in radians) as it's argument
    #The chord is the horizontal line which separates the arc segment from the rest of the circle
    def calcChordLength(self):
        self.chordLength = 2*self.radius*np.sin(self.radians/2) #formula works for theta (radians) only, not degrees #confirmed using http://www.ambrsoft.com/TrigoCalc/Sphere/Arc_.htm
        return self.chordLength

    #Calculates the length of arc, taking theta (angle in radians) as its argument.
    def calcArcLength(self):
        self.arcLength = (self.degrees/360)*self.diameter*np.pi #confirmed using http://www.ambrsoft.com/TrigoCalc/Sphere/Arc_.htm
        return self.arcLength

    #Calculates the sagitta of the arc segment.  The sagitta is the horizontal line which extends from the bottom
    #of the circle to the chord of the segment
    def calcSagitta(self):
        self.sagitta = self.radius - (np.sqrt((self.radius**2)-((self.chordLength/2)**2))) #Confirmed correct against online calculator https://www.liutaiomottola.com/formulae/sag.htm
        return self.sagitta

    #Calculates the area of the circular segment/arc).
    def calcSegmentArea(self):
        self.segmentArea = (self.radians - np.sin(self.radians) / 2) * self.radius**2
        return self.segmentArea

    #Calculate the height of the arc
    #Radius - sagitta of the segment
    def calcArcHeight(self):
        self.arcHeight = self.radius - self.sagitta
        return self.arcHeight
```

<p>I have not progressed very far with the main program as one of the first tasks im aiming to do is create the y values.   This is what I have so far - </p>

<pre class="lang-py prettyprint-override"><code>from circle import Circle
import numpy as np
import matplotlib.pyplot as plt

def main():
    #define centre point

    #Circle(radius,arc length)
    c1 = Circle(3440.065,35) #Nautical miles radius with 35Nm arc length
    chordLength = c1.getChordLength()
    arcHeight = c1.getArcHeight()

    centerX = chordLength/2
    centerY = 0

if __name__ == "__main__":
    main()
</code>```

For context, I wish to use this 'arc' to add elevation data to, akin to - https://link.ui.com/#.  I hope to simulate increased curvature over distance which I can use for rough line of sight analysis.

However, first step is getting the y values.

答:
Here is the final solution, I'm not 100% about the maths and how it all works but if anyone is struggling with the same problem - I hope this helps.

The circle class can be found in the original question, located below. Find attached the final code which provides me with what I was after - simulating the curvature of the earth on a graph based upon the arc length (great circle distance).

Big thank you to all who took the time to answer me and help me along my way.

```<code>from circle import Circle
import numpy as np
import matplotlib.pyplot as plt

def calcStartAngle(startY,centreY,startX,centreX):
    startAngle = np.arctan2(startY-centreY, startX-centreX)
    return startAngle

def calcEndAngle(endY,centreY,endX,centreX):
    endAngle = np.arctan2(endY-centreY, endX-centreX)
    return endAngle

def main():
    distance = 200
    radius = 3440.065

#create circle object
c1 = Circle(radius,distance)
angle = c1.getDegrees()
xc = c1.getXc()
yc = c1.getYc()

#set start and end points
x1,y1 = 0,0
x2,y2 = distance,0

#get start and end angles
startAngle = calcStartAngle(y1,yc,x1,xc)
endAngle = calcEndAngle(y2,yc,x2,xc)
angleList = np.linspace(startAngle,endAngle,distance)
x_values = np.linspace(x1,x2,distance)
y_valuesList = []

for i in range(len(x_values)):
    y = radius*np.sin(angleList[i]) - c1.getArcHeight()
    y_valuesList.append(y)

#Create numpy array to hold y values
y_values = np.array(y_valuesList)

plt.ylim(0,50)
plt.plot(x_values,y_values)
plt.show()

if __name__ == "__main__":
     main()
</code>```

Here is an example of the finished product -

Title: Plotting y values of an arc

Body:
I am trying to plot the segment of a circle (2D) as an arc in matplotlib.  I have written a class which will provide the maths for the segment such as chord length, height of arc etc.  I wish to plot the x y values between (0,0) and (0, chord length).

I am currently representing the X values as numpy linspace array (0, chordLength, 200).  I am a bit stumped as to how to plot the y values as a similar linspace array so that I can plot these points using matplotlib.  The idea behind this is to display the curvature of the earth between two points of a known arc length (great circle distance).  I have been reading around sine cosine etc however outside of using cookie cutter formulas for my geometry calculations, I am somewhat lost as to how to apply it to gain my y values.

First, the circle class

import numpy as np

class Circle:

    def __init__(self,radiusOfCircle,lengthOfArc):
        self.radius = radiusOfCircle
        self.circumference = 2 * np.pi * self.radius
        self.diameter = self.radius * 2
        self.arcLength = lengthOfArc
        self.degrees = self.calcDegrees()
        self.radians = self.calcRadians()
        self.chordLength = self.calcChordLength()
        self.sagitta = self.calcSagitta()
        self.segmentArea = self.calcSegmentArea()
        self.arcHeight = self.calcArcHeight()

    #Setters and getters for the Circle class (TODO: setters)
    def getRadius(self):
        return self.radius

    def getCircumference(self):
        return self.circumference

    def getDiameter(self):
        return self.diameter

    def getArcLength(self):
        return self.arcLength

    def getRadians(self):
        return self.radians

    def getDegrees(self):
        return self.degrees

    def getChordLength(self):
        return self.chordLength

    def getSagitta(self):
        return self.sagitta

    def getSegmentArea(self):
        return self.segmentArea

    def getArcHeight(self):
        return self.arcHeight

    #Define Circle class methods

    #Calculate the central angle, in degrees, by using the arcLength
    def calcDegrees(self):
        self.degrees = (self.arcLength / (np.pi * self.diameter)) * 360 #Gives angle in degrees at centre of the circle between the two points (beginning and end points of arcLength)
        return self.degrees

    #Calculate the central angle in radians, between two points on the circle
    def calcRadians(self):#Where theta is the angle between both points at the centre of the circle
        self.radians = np.radians(self.degrees) # Convert degrees to radians to work with ChordLength formula
        return self.radians

    #Returns the chord lengths of the arc, taking theta (angle in radians) as it's argument
    #The chord is the horizontal line which separates the arc segment from the rest of the circle
    def calcChordLength(self):
        self.chordLength = 2*self.radius*np.sin(self.radians/2) #formula works for theta (radians) only, not degrees #confirmed using http://www.ambrsoft.com/TrigoCalc/Sphere/Arc_.htm
        return self.chordLength

    #Calculates the length of arc, taking theta (angle in radians) as its argument.
    def calcArcLength(self):
        self.arcLength = (self.degrees/360)*self.diameter*np.pi #confirmed using http://www.ambrsoft.com/TrigoCalc/Sphere/Arc_.htm
        return self.arcLength

    #Calculates the sagitta of the arc segment.  The sagitta is the horizontal line which extends from the bottom
    #of the circle to the chord of the segment
    def calcSagitta(self):
        self.sagitta = self.radius - (np.sqrt((self.radius**2)-((self.chordLength/2)**2))) #Confirmed correct against online calculator https://www.liutaiomottola.com/formulae/sag.htm
        return self.sagitta

    #Calculates the area of the circular segment/arc).
    def calcSegmentArea(self):
        self.segmentArea = (self.radians - np.sin(self.radians) / 2) * self.radius**2
        return self.segmentArea

    #Calculate the height of the arc
    #Radius - sagitta of the segment
    def calcArcHeight(self):
        self.arcHeight = self.radius - self.sagitta
        return self.arcHeight

I have not progressed very far with the main program as one of the first tasks im aiming to do is create the y values.   This is what I have so far -

from circle import Circle
import numpy as np
import matplotlib.pyplot as plt

def main():
    #define centre point

    #Circle(radius,arc length)
    c1 = Circle(3440.065,35) #Nautical miles radius with 35Nm arc length
    chordLength = c1.getChordLength()
    arcHeight = c1.getArcHeight()

    centerX = chordLength/2
    centerY = 0

if __name__ == "__main__":
    main()

For context, I wish to use this 'arc' to add elevation data to, akin to - https://link.ui.com/#.  I hope to simulate increased curvature over distance which I can use for rough line of sight analysis.

However, first step is getting the y values.

Body:
Here is the final solution, I'm not 100% about the maths and how it all works but if anyone is struggling with the same problem - I hope this helps.

The circle class can be found in the original question, located below. Find attached the final code which provides me with what I was after - simulating the curvature of the earth on a graph based upon the arc length (great circle distance).

Big thank you to all who took the time to answer me and help me along my way.

from circle import Circle
import numpy as np
import matplotlib.pyplot as plt

def calcStartAngle(startY,centreY,startX,centreX):
    startAngle = np.arctan2(startY-centreY, startX-centreX)
    return startAngle

def calcEndAngle(endY,centreY,endX,centreX):
    endAngle = np.arctan2(endY-centreY, endX-centreX)
    return endAngle

def main():
    distance = 200
    radius = 3440.065

#create circle object
c1 = Circle(radius,distance)
angle = c1.getDegrees()
xc = c1.getXc()
yc = c1.getYc()

#set start and end points
x1,y1 = 0,0
x2,y2 = distance,0

#get start and end angles
startAngle = calcStartAngle(y1,yc,x1,xc)
endAngle = calcEndAngle(y2,yc,x2,xc)
angleList = np.linspace(startAngle,endAngle,distance)
x_values = np.linspace(x1,x2,distance)
y_valuesList = []

for i in range(len(x_values)):
    y = radius*np.sin(angleList[i]) - c1.getArcHeight()
    y_valuesList.append(y)

#Create numpy array to hold y values
y_values = np.array(y_valuesList)

plt.ylim(0,50)
plt.plot(x_values,y_values)
plt.show()

if __name__ == "__main__":
     main()

Here is an example of the finished product -


问:
fsolve for function with exp
I'm trying to solve a nonlinear equation with Python and Scipy, heres the simple input:

```<code>from numpy import exp
from scipy.optimize import fsolve

def func(x):
    return 5*x*(2*x-1+exp(2*x))-5

x0 = fsolve(func,0)

print(x0)
</code>```

However executing the function leads to RuntimeWarning: overflow encountered in exp message.
Using Matlab and fzero with the same function works fine and returns 0.4385 for the root.

How can I solve this?

答:
using 0 as a starting estimate causes some problems
you can use any arbitary value and if you want to start from zero use something like 1e-6

```<code>from numpy import exp
from scipy.optimize import fsolve

def func(x):
    return 5*x*(2*x-1+exp(2*x))-5

x0 = fsolve(func,1e-6)

print(x0)
</code>```

yields

```<code>[0.43848533]
</code>```

Title: fsolve for function with exp

Body:
I'm trying to solve a nonlinear equation with Python and Scipy, heres the simple input:

from numpy import exp
from scipy.optimize import fsolve

def func(x):
    return 5*x*(2*x-1+exp(2*x))-5

x0 = fsolve(func,0)

print(x0)

However executing the function leads to RuntimeWarning: overflow encountered in exp message.
Using Matlab and fzero with the same function works fine and returns 0.4385 for the root.

How can I solve this?

Body:
using 0 as a starting estimate causes some problems
you can use any arbitary value and if you want to start from zero use something like 1e-6

from numpy import exp
from scipy.optimize import fsolve

def func(x):
    return 5*x*(2*x-1+exp(2*x))-5

x0 = fsolve(func,1e-6)

print(x0)

yields

[0.43848533]


问:
Ensure spyOnProperty creates configurable properties with Object.defineProperty
In an upgrade to Angular 9 (from 8.1) and Typescript 3.7 (from <3.6), I have encountered an issue with spyOnProperty

My service looks like:

```<code>class Backend {
  public get baseURL(): string {
    return 'http://baseurl.com/';
  }
}
</code>```

My test that worked before the upgrade would spyOnProperty

```<code>spyOnProperty(backend, 'baseURL', 'get').and.returnValue('http://new');
</code>```

However, I am now getting this error:

```<code>Error: <spyOnProperty> : baseURL is not declared configurable
Usage: spyOnProperty(<object>, <propName>, [accessType])
</code>```

I know that I need to Object.defineProperty as configurable: true, as when stepping through Jasmine I see it fails at:

```<code>if (!descriptor.configurable) {
  throw new Error(
    getErrorMsg(propertyName + ' is not declared configurable')
  );
}
</code>```

And descriptor is created by descriptor = Object.getOwnPropertyDescriptor(proto, methodName);

So in Javascript I would want to:

```<code>Object.defineProperty(backend.prototpye, 'baseURL', {value: 'http://new', configurable: true});
</code>```

To ensure that this property could be spied on.

However, my question is how do I apply the same configurable with Typescript. I have tried to run Object.defineProperty again but I get an error defineproperty Cannot redefine property, which makes sense as to why the check is there in the first place.

I tried using the suggested configurable decorator defined here:

```<code>function configurable(value: boolean) {
    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        descriptor.configurable = value;
    };
}
</code>```

But this does not work, also to note that when I put a breakpoint inside the above method, the descriptor.configurable is actually already set to true before assigning the value. So I am not sure what is actually causing the original error in the tests.

答:
I missed some additional information about creating my tests. To create an instance of the injected services I am using, ts-mockito to create an instance() of each class.

I think it was this call to instance() that was creating properties as not configurable.

Effectively:

```<code>service = new Service(instance(new Backend));
</code>```

Changed to:

```<code>service = new Service(new Backend);
</code>```

Resolves the issue

Body:
In an upgrade to Angular 9 (from 8.1) and Typescript 3.7 (from <3.6), I have encountered an issue with spyOnProperty

My service looks like:

class Backend {
  public get baseURL(): string {
    return 'http://baseurl.com/';
  }
}

My test that worked before the upgrade would spyOnProperty

spyOnProperty(backend, 'baseURL', 'get').and.returnValue('http://new');

However, I am now getting this error:

Error: <spyOnProperty> : baseURL is not declared configurable
Usage: spyOnProperty(<object>, <propName>, [accessType])

I know that I need to Object.defineProperty as configurable: true, as when stepping through Jasmine I see it fails at:

if (!descriptor.configurable) {
  throw new Error(
    getErrorMsg(propertyName + ' is not declared configurable')
  );
}

And descriptor is created by descriptor = Object.getOwnPropertyDescriptor(proto, methodName);

So in Javascript I would want to:

Object.defineProperty(backend.prototpye, 'baseURL', {value: 'http://new', configurable: true});

To ensure that this property could be spied on.

However, my question is how do I apply the same configurable with Typescript. I have tried to run Object.defineProperty again but I get an error defineproperty Cannot redefine property, which makes sense as to why the check is there in the first place.

I tried using the suggested configurable decorator defined here:

function configurable(value: boolean) {
    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        descriptor.configurable = value;
    };
}

But this does not work, also to note that when I put a breakpoint inside the above method, the descriptor.configurable is actually already set to true before assigning the value. So I am not sure what is actually causing the original error in the tests.

Body:
I missed some additional information about creating my tests. To create an instance of the injected services I am using, ts-mockito to create an instance() of each class.

I think it was this call to instance() that was creating properties as not configurable.

Effectively:

service = new Service(instance(new Backend));

Changed to:

service = new Service(new Backend);

Resolves the issue