问:
Flutter :how to call function in statelesswidget?
I want to show a list of data with list view and JSON. This code in a file with stateless widget. And this page opened after login. When I try in stateful widget, the code RUN normally. In stateless widget, when I debug it, the code didn't call function getData(). But directly went to

```<code>Widget build(BuildContext context) {
     return new Scaffold( ...
</code>```

Here is complete code :

```<code>class frmClass extends StatelessWidget{
  List<dynamic> dta;
  get setState => null;

  Future<String> getData() async {
      var uri ='https://xxxx.com/class';
      var map = new Map<String, dynamic>();
      map["username"] = "abc";
      map["password"] = "1234";

      http.Response response = await http.post(
        uri,
        body: jsonEncode(map),
      );

      Map<String,dynamic> mp = jsonDecode(utf8.decode(response.bodyBytes));
      this.setState(() {
        dta = mp["data"];
        debugPrint(dta.toString());
      });

    }

  @override
  void initState(){
    this.getData();
  }

  @override
  Widget build(BuildContext context) {

     return new Scaffold(
       appBar: new AppBar(
           backgroundColor:Colors.transparent,
           elevation: 0.0,
           iconTheme: new IconThemeData(color: Color(0xFF18D191))),
       body: new ListView.builder(
           itemCount: dta == null ? 0 : dta.length,
           itemBuilder: (BuildContext context, int index){
             return new Card(
               child: new Text(dta[index]["className"]),
             );
           }
       ),
     );
  }
}
</code>```

How can I fix it?

答:
You can use a FutureBuilder to call getData() into build() method of StatelessWidget:

https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

But, this will fire getData() every time your statelessWidget is rebuild.

Another way is to use reactive programing architecture (like Bloc, rxdart, etc..).

Depends on what do you want, fire getData() every time or just once (or when your conditions are true/false).

Body:
I want to show a list of data with list view and JSON. This code in a file with stateless widget. And this page opened after login. When I try in stateful widget, the code RUN normally. In stateless widget, when I debug it, the code didn't call function getData(). But directly went to

Widget build(BuildContext context) {
     return new Scaffold( ...

Here is complete code :

class frmClass extends StatelessWidget{
  List<dynamic> dta;
  get setState => null;

  Future<String> getData() async {
      var uri ='https://xxxx.com/class';
      var map = new Map<String, dynamic>();
      map["username"] = "abc";
      map["password"] = "1234";

      http.Response response = await http.post(
        uri,
        body: jsonEncode(map),
      );

      Map<String,dynamic> mp = jsonDecode(utf8.decode(response.bodyBytes));
      this.setState(() {
        dta = mp["data"];
        debugPrint(dta.toString());
      });

    }

  @override
  void initState(){
    this.getData();
  }

  @override
  Widget build(BuildContext context) {

     return new Scaffold(
       appBar: new AppBar(
           backgroundColor:Colors.transparent,
           elevation: 0.0,
           iconTheme: new IconThemeData(color: Color(0xFF18D191))),
       body: new ListView.builder(
           itemCount: dta == null ? 0 : dta.length,
           itemBuilder: (BuildContext context, int index){
             return new Card(
               child: new Text(dta[index]["className"]),
             );
           }
       ),
     );
  }
}

How can I fix it?


来源: stackexchange

问:
Opengl proper lighting problem
I have written the following program to display a teapot on a table in a room with 2side walls and a floor.

```<code>#include <stdio.h>
#include <glut.h>

void wall1(float thickness)
{
    glPushMatrix();
    glTranslatef(100,100,0);
    glRotatef(90,1,0,0);
    glScalef(thickness,1,1);
    glutSolidCube(100);
    glPopMatrix();
}
void wall2(float thickness)
{
    glPushMatrix();
    glTranslatef(150,100,-50);
    glScalef(1,1,thickness);
    glutSolidCube(100);
    glPopMatrix();
}
void floor(float thickness)
{
    glPushMatrix();
    glTranslatef(150,50,0);
    glScalef(1,thickness,1);
    glutSolidCube(100);
    glPopMatrix();
}
void leg(float thickness)
{
    glPushMatrix();
    glScalef(thickness,.5,thickness);
    glutSolidCube(100);
    glPopMatrix();
}
void tableTop(float thickess)
{
    glPushMatrix();
    glTranslatef(150,100,0);
    glScalef(.5,thickess,.5);
    glutSolidCube(100);
    glPopMatrix();
}
void table()
{
    tableTop(.05);

    glPushMatrix();
    glTranslatef(125,75,-25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(175,75,-25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(175,75,25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(125,75,25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(150,110,0);
    glScalef(.1,.1,.1);
    glutSolidTeapot(100);
    glPopMatrix();
}
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    float pos[] = {200,200,0};
    float dif[] = {.3,.3,.3,3};
    float spe[] = {1,1,1,1};
    float amb[] = {1,1,1,0};
    glLightfv(GL_LIGHT0,GL_POSITION,pos);
    glLightfv(GL_LIGHT0,GL_DIFFUSE,dif);
    glLightfv(GL_LIGHT0,GL_AMBIENT,amb);
    glLightfv(GL_LIGHT0,GL_SPECULAR,spe);

    glTranslatef(50,50,0);
    glRotatef(30,1,0,0);
    glRotatef(-30,0,1,0);
    wall1(.05);
    wall2(.05);
    floor(0.05);
    table();

    glFlush();
}
void reshape(int w,int h)
{
    glViewport(0,0,w,h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0,400,0,400,-400,400);
    glMatrixMode(GL_MODELVIEW);
}

void main(int argc,char** argv)
{
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH);
    glutInitWindowPosition(100,100);
    glutInitWindowSize(400,400);
    glutCreateWindow("woot");
    glClearColor(1,1,1,1);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);

    glShadeModel(GL_SMOOTH);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutMainLoop();
}
</code>```

The problem with this is my lighting part is not working as expected. Its not illuminating evenly all my objects... What am i missing? This making even the teapot hard to sea.
My lighting part is in display function.

答: If you want to evenly light all objects, only use ambient lighting.</p>

ContentLicense: CC BY-SA 3.0

Title: Opengl proper lighting problem

Body:
I have written the following program to display a teapot on a table in a room with 2side walls and a floor.

#include <stdio.h>
#include <glut.h>

void wall1(float thickness)
{
    glPushMatrix();
    glTranslatef(100,100,0);
    glRotatef(90,1,0,0);
    glScalef(thickness,1,1);
    glutSolidCube(100);
    glPopMatrix();
}
void wall2(float thickness)
{
    glPushMatrix();
    glTranslatef(150,100,-50);
    glScalef(1,1,thickness);
    glutSolidCube(100);
    glPopMatrix();
}
void floor(float thickness)
{
    glPushMatrix();
    glTranslatef(150,50,0);
    glScalef(1,thickness,1);
    glutSolidCube(100);
    glPopMatrix();
}
void leg(float thickness)
{
    glPushMatrix();
    glScalef(thickness,.5,thickness);
    glutSolidCube(100);
    glPopMatrix();
}
void tableTop(float thickess)
{
    glPushMatrix();
    glTranslatef(150,100,0);
    glScalef(.5,thickess,.5);
    glutSolidCube(100);
    glPopMatrix();
}
void table()
{
    tableTop(.05);

    glPushMatrix();
    glTranslatef(125,75,-25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(175,75,-25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(175,75,25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(125,75,25);
    leg(.05);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(150,110,0);
    glScalef(.1,.1,.1);
    glutSolidTeapot(100);
    glPopMatrix();
}
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    float pos[] = {200,200,0};
    float dif[] = {.3,.3,.3,3};
    float spe[] = {1,1,1,1};
    float amb[] = {1,1,1,0};
    glLightfv(GL_LIGHT0,GL_POSITION,pos);
    glLightfv(GL_LIGHT0,GL_DIFFUSE,dif);
    glLightfv(GL_LIGHT0,GL_AMBIENT,amb);
    glLightfv(GL_LIGHT0,GL_SPECULAR,spe);

    glTranslatef(50,50,0);
    glRotatef(30,1,0,0);
    glRotatef(-30,0,1,0);
    wall1(.05);
    wall2(.05);
    floor(0.05);
    table();

    glFlush();
}
void reshape(int w,int h)
{
    glViewport(0,0,w,h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0,400,0,400,-400,400);
    glMatrixMode(GL_MODELVIEW);
}

void main(int argc,char** argv)
{
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH);
    glutInitWindowPosition(100,100);
    glutInitWindowSize(400,400);
    glutCreateWindow("woot");
    glClearColor(1,1,1,1);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);

    glShadeModel(GL_SMOOTH);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutMainLoop();
}

The problem with this is my lighting part is not working as expected. Its not illuminating evenly all my objects... What am i missing? This making even the teapot hard to sea.
My lighting part is in display function.


问:
Python3: Can use other than 'self' as a 1st parameter of methods?
Can this code

```<code>class Point:
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def __str__(self):
        return "Point({},{})".format(self.x,self.y)
p=Point(3,5)
print(p)
</code>```

be modified to following code?

```<code>class Point:
    def __init__(p,x,y):
        p.x=x
        p.y=y
    def __str__(p):
        return "Point({},{})".format(p.x, p.y)
p=Point(3,5)
print(p)
</code>```

It seems to be worked in this case. But it is so naive case. I wonder using other than 'self' will cause some problem in some situations.

答: The first argument is the reference to the bound variable or object. Its convention to use self but anything else will also work. check the doc here.</p>

ContentLicense: CC BY-SA 4.0

Body:
Can this code

class Point:
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def __str__(self):
        return "Point({},{})".format(self.x,self.y)
p=Point(3,5)
print(p)

be modified to following code?

class Point:
    def __init__(p,x,y):
        p.x=x
        p.y=y
    def __str__(p):
        return "Point({},{})".format(p.x, p.y)
p=Point(3,5)
print(p)

It seems to be worked in this case. But it is so naive case. I wonder using other than 'self' will cause some problem in some situations.


问:
PHP: How to check if image file exists?
I need to see if a specific image exists on my cdn.

I've tried the following and it doesn't work:

```<code>if (file_exists(http://www.example.com/images/$filename)) {
    echo "The file exists";
} else {
    echo "The file does not exist";
}
</code>```

Even if the image exists or doesn't exist, it always says "The file exists". I'm not sure why its not working...

答:
```<code>if(@getimagesize($image_path)){
 ...}
</code>```

Is working for me.

Title: PHP: How to check if image file exists?

Body:
I need to see if a specific image exists on my cdn.

I've tried the following and it doesn't work:

if (file_exists(http://www.example.com/images/$filename)) {
    echo "The file exists";
} else {
    echo "The file does not exist";
}

Even if the image exists or doesn't exist, it always says "The file exists". I'm not sure why its not working...

Body:
if(@getimagesize($image_path)){
 ...}

Is working for me.


问:
How to create a python script that handles an input string or an input file?
I would like to make a python script that can either process a string fed into the command line

python my_script.py "Hello World"

or a set of strings inside a file (e.g. input_file.txt)

python my_script.py -i input_file.txt

Is there a way to do this via argparse? So far I can handle input files, but I don't know how to add the option of just processing a string fed directly in the command line.

答:
make argparse accept one positional argument (filename or string) and one flag (-i). If the flag is present, treat the argument as a file. Take a look at argparse tutorial for more info. I've modified the example to fit your needs.

```<code>import argparse
parser = argparse.ArgumentParser()
parser.add_argument("inp", help="input string or input file")
parser.add_argument("-i", "--treat-as-file", action="store_true",
                    help="reads from file if specified")
args = parser.parse_args()

if args.treat_as_file:
    print("Treating {} as input file".format(args.inp))
else:
    print("Treating {} as the input".format(args.inp))
</code>```

Output:

```<code>/tmp $ python test.py abcde
Treating abcde as the input
/tmp $ python test.py -i abcde
Treating abcde as input file
</code>```

Body:
make argparse accept one positional argument (filename or string) and one flag (-i). If the flag is present, treat the argument as a file. Take a look at argparse tutorial for more info. I've modified the example to fit your needs.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("inp", help="input string or input file")
parser.add_argument("-i", "--treat-as-file", action="store_true",
                    help="reads from file if specified")
args = parser.parse_args()

if args.treat_as_file:
    print("Treating {} as input file".format(args.inp))
else:
    print("Treating {} as the input".format(args.inp))

Output:

/tmp $ python test.py abcde
Treating abcde as the input
/tmp $ python test.py -i abcde
Treating abcde as input file


问:
Use setIndexedTypes or setTypeMetadata methods on CacheConfiguration to enable. Ignite Error
I am trying out the simple person example for a read through cache. Set up basic table and here is my code that i am trying to run

```<code> IgniteConfiguration cfg = new IgniteConfiguration();
        cfg.setClientMode(true);
        cfg.setPeerClassLoadingEnabled(true);

        // Create store factory.
        CacheJdbcPojoStoreFactory storeFactory = new CacheJdbcPojoStoreFactory();
        storeFactory.setDataSourceBean("dataSource");

        CacheConfiguration sampleCache = CacheConfig.cache("sampleCache", storeFactory);
        sampleCache.setIndexedTypes(PersonKey.class,Person.class);
        cfg.setCacheConfiguration(sampleCache);

        Ignition.start("default-config1.xml");
        Ignite ignite=Ignition.ignite();

        IgniteCache<IncappconfigKey,INCAppConfig> cache =ignite.getOrCreateCache("sampleCache");
        cache.loadCache(null);

        SqlQuery  sqlQuery=new SqlQuery(Person.class,"id=?");
        cache.query(sqlQuery.setArgs(1l));
</code>```

Am setting the index type still am getting the above error. Can some one please help. Stuck on this for some time now.

All the CacheConfig and other classes are auto generated by the import tool.

答:
You did not pass in the configuration into Ignite. Just start Ignition with the IgniteConfiguration object you have initialized.

In short, it should be

IgniteConfiguration cfg = new IgniteConfiguration();
        ...
        ...
Ignition.start(cfg);
        ...
```

Body:
I am trying out the simple person example for a read through cache. Set up basic table and here is my code that i am trying to run

 IgniteConfiguration cfg = new IgniteConfiguration();
        cfg.setClientMode(true);
        cfg.setPeerClassLoadingEnabled(true);

        // Create store factory.
        CacheJdbcPojoStoreFactory storeFactory = new CacheJdbcPojoStoreFactory();
        storeFactory.setDataSourceBean("dataSource");

        CacheConfiguration sampleCache = CacheConfig.cache("sampleCache", storeFactory);
        sampleCache.setIndexedTypes(PersonKey.class,Person.class);
        cfg.setCacheConfiguration(sampleCache);

        Ignition.start("default-config1.xml");
        Ignite ignite=Ignition.ignite();

        IgniteCache<IncappconfigKey,INCAppConfig> cache =ignite.getOrCreateCache("sampleCache");
        cache.loadCache(null);

        SqlQuery  sqlQuery=new SqlQuery(Person.class,"id=?");
        cache.query(sqlQuery.setArgs(1l));

Am setting the index type still am getting the above error. Can some one please help. Stuck on this for some time now.

All the CacheConfig and other classes are auto generated by the import tool.


问:
Finding values in postgres array (some must be in, some must not be in at the same query)
I have a ids integer[]

And, I want to find rows which contain 1 but must not contains 2, 3, 4

but [1] OR [1, 5] OR [1, 6, 7] <- this data is OK. [2,3,4] is not.

So I tried this way

```<code>SELECT *
FROM table_test
WHERE 1 = ANY(ids) AND 2 <> ANY(ids)  AND 3 <> ANY(ids)  AND 4 <> ANY(ids)
</code>```

but it returns 1 = ANY(ids) part

```<code>[1 2 3]
[1 3 4]
[1]
[1 5]
[1 6 7]
</code>```

I want this data

```<code>[1]
[1 5]
[1 6 7]
</code>```

How can I solve this problem?

Thanks  a lot!

答:
You should use ALL together with <>.

The expression 2 <> ANY(ids) is true if at least one element is not equal to 2 - which is always the case because you require at least one element to be 1 (which is not 2) with the first condition.

```<code>SELECT *
FROM table_test
WHERE 1 = ANY(ids)
  AND 2 <> ALL(ids)
  AND 3 <> ALL(ids)
  AND 4 <> ALL(ids)
</code>```

another option is to use the overlaps operator && ("have elements in common") and negate it:

```<code>SELECT *
FROM table_test
WHERE 1 = ANY(ids)
  AND NOT ids && array[3,4,5]
</code>```

Body:
I have a ids integer[]

And, I want to find rows which contain 1 but must not contains 2, 3, 4

but [1] OR [1, 5] OR [1, 6, 7] <- this data is OK. [2,3,4] is not.

So I tried this way

SELECT *
FROM table_test
WHERE 1 = ANY(ids) AND 2 <> ANY(ids)  AND 3 <> ANY(ids)  AND 4 <> ANY(ids)

but it returns 1 = ANY(ids) part

[1 2 3]
[1 3 4]
[1]
[1 5]
[1 6 7]

I want this data

[1]
[1 5]
[1 6 7]

How can I solve this problem?

Thanks  a lot!

Body:
You should use ALL together with <>.

The expression 2 <> ANY(ids) is true if at least one element is not equal to 2 - which is always the case because you require at least one element to be 1 (which is not 2) with the first condition.

SELECT *
FROM table_test
WHERE 1 = ANY(ids)
  AND 2 <> ALL(ids)
  AND 3 <> ALL(ids)
  AND 4 <> ALL(ids)

another option is to use the overlaps operator && ("have elements in common") and negate it:

SELECT *
FROM table_test
WHERE 1 = ANY(ids)
  AND NOT ids && array[3,4,5]


问:
How can we capture change events of LayersControl component?
For example, when changing the base layer (radio buttons) or toggling an overlay on/off (checkboxes), how can we capture the change events in order to update other aspects of state in an application. Thanks in advance, open to any type of solution. Pseudo-code:</p>

```<code><Map>
    <LayersControl position='topright' change={this.handleLayerControlsChange}>
        <BaseLayer checked name='Map 1'>
            <TileLayer url={map1} />
        </BaseLayer>
        <BaseLayer checked name='Map 2'>
            <TileLayer url={map2} />
        </BaseLayer>
        <Overlay name='Overlay 1'>
            <LayerGroup>
                <GeoJSON data={overlayData1} />
            </LayerGroup>
        </Overlay>
        <Overlay name='Overlay 2'>
            <LayerGroup>
                <GeoJSON data={overlayData2} />
            </LayerGroup>
        </Overlay>
    </LayersControl>
</Map>
</code>```

答:
Of course... hours and hours and it's only after posting a question that the solution is found. The map has a whenReady event (which I was already using it just wasn't in the pseudo-code) which upon looking at the Leaflet Docs on the Map Events there's a baselayerchange that can be used. Pseudo-code, that maybe helps someone else at some point:

```<code>baseLayerChange = event => {
    console.log('baseLayerChange event', event);
}

whenReadyHandler = event => {
    const { target } = event;
    target.on('baselayerchange', this.baseLayerChange);
}

<Map whenReady={this.whenReadyHandler}>
    <LayersControl position='topright' change={this.handleLayerControlsChange}>
        <BaseLayer checked name='Map 1'>
            <TileLayer url={map1} />
        </BaseLayer>
        <BaseLayer checked name='Map 2'>
            <TileLayer url={map2} />
        </BaseLayer>
        <Overlay name='Overlay 1'>
            <LayerGroup>
                <GeoJSON data={overlayData1} />
            </LayerGroup>
        </Overlay>
        <Overlay name='Overlay 2'>
            <LayerGroup>
                <GeoJSON data={overlayData2} />
            </LayerGroup>
        </Overlay>
    </LayersControl>
</Map>
</code>```

Body:
For example, when changing the base layer (radio buttons) or toggling an overlay on/off (checkboxes), how can we capture the change events in order to update other aspects of state in an application. Thanks in advance, open to any type of solution. Pseudo-code:

<Map>
    <LayersControl position='topright' change={this.handleLayerControlsChange}>
        <BaseLayer checked name='Map 1'>
            <TileLayer url={map1} />
        </BaseLayer>
        <BaseLayer checked name='Map 2'>
            <TileLayer url={map2} />
        </BaseLayer>
        <Overlay name='Overlay 1'>
            <LayerGroup>
                <GeoJSON data={overlayData1} />
            </LayerGroup>
        </Overlay>
        <Overlay name='Overlay 2'>
            <LayerGroup>
                <GeoJSON data={overlayData2} />
            </LayerGroup>
        </Overlay>
    </LayersControl>
</Map>

Body:
Of course... hours and hours and it's only after posting a question that the solution is found. The map has a whenReady event (which I was already using it just wasn't in the pseudo-code) which upon looking at the Leaflet Docs on the Map Events there's a baselayerchange that can be used. Pseudo-code, that maybe helps someone else at some point:

baseLayerChange = event => {
    console.log('baseLayerChange event', event);
}

whenReadyHandler = event => {
    const { target } = event;
    target.on('baselayerchange', this.baseLayerChange);
}

<Map whenReady={this.whenReadyHandler}>
    <LayersControl position='topright' change={this.handleLayerControlsChange}>
        <BaseLayer checked name='Map 1'>
            <TileLayer url={map1} />
        </BaseLayer>
        <BaseLayer checked name='Map 2'>
            <TileLayer url={map2} />
        </BaseLayer>
        <Overlay name='Overlay 1'>
            <LayerGroup>
                <GeoJSON data={overlayData1} />
            </LayerGroup>
        </Overlay>
        <Overlay name='Overlay 2'>
            <LayerGroup>
                <GeoJSON data={overlayData2} />
            </LayerGroup>
        </Overlay>
    </LayersControl>
</Map>


问:
Logic Apps "Get file Content" Sharepoint connector timed out for files over 20MB
As the topic implies, my logic app having a Get File Content from a sharepoint connector,which was working fine for all the files less than 20 MB. For the files greater than 20 MB getting timeout after 4 retries by giving the 500 Internal Server Error

I couldn't able to find this type of size limitations in the documentations.

I tried to use the chunks options but its only for upload not for retrieve

Some Other findings :

A file with 17 MB got succeeded at the second retry, however for files more than 20 MB it always getting failed even after 4 retries.

RAW Output:

```<code>{
  "error": {
    "code": 500,
    "source": "logic-apis-northeurope.azure-apim.net",
    "clientRequestId": "3a0bf64d-2b82-4aef-92ba-ff8b101e44bb",
    "message": "BadGateway",
    "innerError": {
      "status": 500,
      "message": "Request timed out. Try again later.\r\nclientRequestId: 3a0bf64d-2b82-4aef-92ba-ff8b101e44bb\r\nserviceRequestId: e0ce569f-96aa-d08b-1c7e-20a6ccf358c3",
      "source": "https://xxxxx",
      "errors": []
    }
  }
}
</code>```

P.S I'm using on-prem sharepoint, i.e gateway is already using. However no timeout logs in the gateway,which makes me to eliminate the issue is not from gateway and from logic app

答:
We can see logic app supports get data from sharepoint according to the on-premises data gateway in this document.

Then click limits on their payload size, we can see the limits of it.

Although the document above doesn't mention the limit of 20 MB for the data response, but I think when you request the data of 17 MB, it beyond exceed the limit. So it got succeeded at the second retry but not success at the first time.

Body:
As the topic implies, my logic app having a Get File Content from a sharepoint connector,which was working fine for all the files less than 20 MB. For the files greater than 20 MB getting timeout after 4 retries by giving the 500 Internal Server Error

I couldn't able to find this type of size limitations in the documentations.

I tried to use the chunks options but its only for upload not for retrieve

Some Other findings :

A file with 17 MB got succeeded at the second retry, however for files more than 20 MB it always getting failed even after 4 retries.

RAW Output:

{
  "error": {
    "code": 500,
    "source": "logic-apis-northeurope.azure-apim.net",
    "clientRequestId": "3a0bf64d-2b82-4aef-92ba-ff8b101e44bb",
    "message": "BadGateway",
    "innerError": {
      "status": 500,
      "message": "Request timed out. Try again later.\r\nclientRequestId: 3a0bf64d-2b82-4aef-92ba-ff8b101e44bb\r\nserviceRequestId: e0ce569f-96aa-d08b-1c7e-20a6ccf358c3",
      "source": "https://xxxxx",
      "errors": []
    }
  }
}

P.S I'm using on-prem sharepoint, i.e gateway is already using. However no timeout logs in the gateway,which makes me to eliminate the issue is not from gateway and from logic app


问:
Why is NAT causing problems for server running on the home network?

NAT has enjoyed widespread deployment in recent years. But NAT is not without detractors. First, one might argue that, port numbers are meant to be used for
  addressing processes, not for addressing hosts. This violation can indeed cause problems for servers running on the home network, since, as we have seen in Chapter 2, server processes wait for incoming requests at well-known port numbers and peers in a P2P protocol need to accept incoming connections when acting as servers.

From Kurose & Ross, Computer networking: a top down approach, 7th. p.375.

答:
I don't know how much you know NAT, so I'll first give a short introduction.

NAT, network address translation, comes from the shortage of IPV4 addresses, and it builds a safe way for home users like firewall.

There are four types of NAT used now, full cone NAT, restricted NAT, port restricted NAT, symmetric NAT, you can google them for detail differencees.

Let's look at what will happen when we build server behind a NAT router.

If you don't do NAT traversal, then the clients can not access to server if only the server access to them first.

Then if you do the NAT traversal. For some types it can work, but for others it can't.

What's more, if you're successful to open the door, then all the clients/attackers can connect to the server without any check. So you lose the safe security of NAT, then you need to build it by yoursel. Then, why do you need the NAT?

In a word, NAT causes many problems for server on the home network, and they are not needed.


问:
Angular HTTP Request Interception - execution order for priming data
I have AuthenticationService code implemented as an Angular Service that contains a method below. Its purpose is to extract user profile information from RESTfull API end-point. This method must complete before any request is made to the remote server.

```<code>  getUserProfile(): Observable<UserProfileModel> {
    const url = `${this.roleUrl}profile`;
    return this.http
      .get<UserProfileModel>(url, constants.httpOptions)
      .pipe(
        map(user => {
        if (user.roles && user.roles.length) {
          user.selectedRoleTypeName = user.roles[0].name;
          user.selectedRoleID = user.roles[0].id;
          user.selectedRoleTypeID = user.roles[0].roleTypeId;
        }

        localStorage.setItem('user', JSON.stringify(user));
        this.userSubject.next(user);
        return user;
        }),
        );
  }
</code>```

getUserProfile() method above is called by an Angular component in following manner:

```<code>  getCurrentUserProfile() {
    let currentUser: any;
    const subscription: Subscription = this.authenticationService.getUserProfile().subscribe((response: UserProfileModel) => {
      if (response) {

        currentUser = JSON.parse(localStorage.getItem('user'));
        this.currentUserName = currentUser.name || '';
        if (currentUser.roles && currentUser.roles.length) {
          this.currentUserRoles = currentUser.roles;
          this.selectedRoleTypeName = this.currentUserRoles[0].name; // Role name
        }
      }
      subscription.unsubscribe();
    });
  }
</code>```

I have Angular HTTP Interceptor code that should include roleid request header when the Browser local storage is set by the getUserProfile() method above.

Snippet of the Interceptor code is below:

```<code>  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    console.log('HttpRoleIdInterceptor - start');

    const user: UserProfileModel = JSON.parse(localStorage.getItem('user'));
    const selectedRoleID = user.selectedRoleID;
    const reqWithRoleID = req.clone({
      setHeaders: {
        roleid: `${selectedRoleID}`
      }
    });
    return next.handle(reqWithRoleID);
  }
</code>```

Currently, the issue is that I get the following error in the Interceptor code:
"Cannot read property 'selectedRoleID of null".

It seems that get user profile() doesn't set the local storage just in time for Interceptor to read data from local storage.

I'm really confused!

答:
There is many ways to exclude calls from interceptor but this one is my favourite.

You can use a custom header in your getUserProfile(). Then check after it in interceptor.

example :

```<code>  getUserProfile(): Observable<UserProfileModel> {
  const headers = new HttpHeaders().set(SkipInterceptor, '');

    const url = `${this.roleUrl}profile`;
    return this.http
      .get<UserProfileModel>(url, {headers})
      .pipe(
        map(user => {
        if (user.roles && user.roles.length) {
          user.selectedRoleTypeName = user.roles[0].name;
          user.selectedRoleID = user.roles[0].id;
          user.selectedRoleTypeID = user.roles[0].roleTypeId;
        }

        localStorage.setItem('user', JSON.stringify(user));
        this.userSubject.next(user);
        return user;
        }),
        );
  }
</code>```

In the interceptor:

```<code>export const SkipInterceptor= 'X-Skip-Interceptor';

@Injectable()
export class SkippableInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.headers.has(SkipInterceptor)) {
      const headers = req.headers.delete(SkipInterceptor);
      return next.handle(req.clone({ headers }));
    }

    ...  // intercept
  }
</code>```

}

EDIT: I saw that you had constans.httpOptions add the header in there.

Body:
I have AuthenticationService code implemented as an Angular Service that contains a method below. Its purpose is to extract user profile information from RESTfull API end-point. This method must complete before any request is made to the remote server.

  getUserProfile(): Observable<UserProfileModel> {
    const url = `${this.roleUrl}profile`;
    return this.http
      .get<UserProfileModel>(url, constants.httpOptions)
      .pipe(
        map(user => {
        if (user.roles && user.roles.length) {
          user.selectedRoleTypeName = user.roles[0].name;
          user.selectedRoleID = user.roles[0].id;
          user.selectedRoleTypeID = user.roles[0].roleTypeId;
        }

        localStorage.setItem('user', JSON.stringify(user));
        this.userSubject.next(user);
        return user;
        }),
        );
  }

getUserProfile() method above is called by an Angular component in following manner:

  getCurrentUserProfile() {
    let currentUser: any;
    const subscription: Subscription = this.authenticationService.getUserProfile().subscribe((response: UserProfileModel) => {
      if (response) {

        currentUser = JSON.parse(localStorage.getItem('user'));
        this.currentUserName = currentUser.name || '';
        if (currentUser.roles && currentUser.roles.length) {
          this.currentUserRoles = currentUser.roles;
          this.selectedRoleTypeName = this.currentUserRoles[0].name; // Role name
        }
      }
      subscription.unsubscribe();
    });
  }

I have Angular HTTP Interceptor code that should include roleid request header when the Browser local storage is set by the getUserProfile() method above.

Snippet of the Interceptor code is below:

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    console.log('HttpRoleIdInterceptor - start');

    const user: UserProfileModel = JSON.parse(localStorage.getItem('user'));
    const selectedRoleID = user.selectedRoleID;
    const reqWithRoleID = req.clone({
      setHeaders: {
        roleid: `${selectedRoleID}`
      }
    });
    return next.handle(reqWithRoleID);
  }

Currently, the issue is that I get the following error in the Interceptor code:
"Cannot read property 'selectedRoleID of null".

It seems that get user profile() doesn't set the local storage just in time for Interceptor to read data from local storage.

I'm really confused!

Body:
There is many ways to exclude calls from interceptor but this one is my favourite.

You can use a custom header in your getUserProfile(). Then check after it in interceptor.

example :

  getUserProfile(): Observable<UserProfileModel> {
  const headers = new HttpHeaders().set(SkipInterceptor, '');

    const url = `${this.roleUrl}profile`;
    return this.http
      .get<UserProfileModel>(url, {headers})
      .pipe(
        map(user => {
        if (user.roles && user.roles.length) {
          user.selectedRoleTypeName = user.roles[0].name;
          user.selectedRoleID = user.roles[0].id;
          user.selectedRoleTypeID = user.roles[0].roleTypeId;
        }

        localStorage.setItem('user', JSON.stringify(user));
        this.userSubject.next(user);
        return user;
        }),
        );
  }

In the interceptor:

export const SkipInterceptor= 'X-Skip-Interceptor';

@Injectable()
export class SkippableInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.headers.has(SkipInterceptor)) {
      const headers = req.headers.delete(SkipInterceptor);
      return next.handle(req.clone({ headers }));
    }

    ...  // intercept
  }

}

EDIT: I saw that you had constans.httpOptions add the header in there.


问:
In python how to update a value in CSV file which have more than 5K rows?
I'm a beginner to python, is there any way I can update the csv file while reading and writing in the same file, or is there any alternate way to do this. All the suggestions are welcomed.

NOTE: I have a CSV file with records 5k and above.

What I want to do is read the csv file line by line and if the value of msg_sent is False then update it to True

Here is the code snippet which I've tried but it is adding an new line at the end of CSV file instead of updating it,

```<code>with open('subscribers.csv', 'r+') as subscribers_csv:
reader = csv.DictReader(subscribers_csv)
writer = csv.DictWriter(subscribers_csv,
                        delimiter=",",
                        lineterminator="\n",
                        fieldnames=['user_id', 'name', 'msg_sent'])
    for subscriber in reader:
        if subscriber['msg_sent'] == 'False':
            subscriber_row = {'user_id': subscriber['user_id'],
                              'name': subscriber['name'],
                              'msg_sent': True}
            writer.writerow(subscriber_row)
</code>```

答:
As per my comment above - use pandas.

If you want to update all rows with msg_sent==False to True just use df.loc[~df.msg_sent, 'msg_sent'] = True or even shorter df.msg_sent = True as there are only 2 possibilities True and False.

If you want to only write back rows that were False and set their msg_sent value to True use df = df.loc[~df.msg_sent].assign(msg_sent=True)

Complete example (for case 2):

```<code>import pandas as pd
df = pd.read_csv('subscribers.csv')
df = df.loc[~df.msg_sent].assign(msg_sent=True)
df.to_csv('subscribers.csv')
</code>```

Body:
I'm a beginner to python, is there any way I can update the csv file while reading and writing in the same file, or is there any alternate way to do this. All the suggestions are welcomed.

NOTE: I have a CSV file with records 5k and above.

What I want to do is read the csv file line by line and if the value of msg_sent is False then update it to True

Here is the code snippet which I've tried but it is adding an new line at the end of CSV file instead of updating it,

with open('subscribers.csv', 'r+') as subscribers_csv:
reader = csv.DictReader(subscribers_csv)
writer = csv.DictWriter(subscribers_csv,
                        delimiter=",",
                        lineterminator="\n",
                        fieldnames=['user_id', 'name', 'msg_sent'])
    for subscriber in reader:
        if subscriber['msg_sent'] == 'False':
            subscriber_row = {'user_id': subscriber['user_id'],
                              'name': subscriber['name'],
                              'msg_sent': True}
            writer.writerow(subscriber_row)

Body:
As per my comment above - use pandas.

If you want to update all rows with msg_sent==False to True just use df.loc[~df.msg_sent, 'msg_sent'] = True or even shorter df.msg_sent = True as there are only 2 possibilities True and False.

If you want to only write back rows that were False and set their msg_sent value to True use df = df.loc[~df.msg_sent].assign(msg_sent=True)

Complete example (for case 2):

import pandas as pd
df = pd.read_csv('subscribers.csv')
df = df.loc[~df.msg_sent].assign(msg_sent=True)
df.to_csv('subscribers.csv')


问:
Automating the install of GFortran and Python3
I'd like to write a bash script that will be executed on new users' linux machines. The script should make sure the machine is ready to compile and run several fortran and python scripts. My intent was to check for GCC and subsequently check for gfortran in GCC and then use homebrew to install the gfortran formula if not present. Similarly with python, I would use pip to install python3 if python isn't up to date. </p>

<p>I would like some advice before I begin. What are some best practices for checking for programs and installing them through a behind the scenes bash script? What are things to be careful for? I realize this question is vague but literally any advice is greatly appreciated. </p>

答:
A possible different approach to consider.

If the packages that you want are available for installation via the standard package manager for the Linux distribution that you are using, you could build a metapackage which, when installed, will force the installation of all of the components.  (A metapackage is one which does not directly contain any software itself but which lists a number of dependencies that the package manager will need to satisfy when installing it.)

If you also set up a repository on an http server containing your metapackage, and configure the package manager on the clients to point to it, then if you later decide to update the list of packages contained in your standard software suite across all the client machines, all you need to do is to publish a new version of your metapackage to the repository, and have the client machines rerun their operating system's software updater.  For the individual software components listed in the metapackage, the software update will pick up any updates to these in the ordinary way, provided that the dependency information in the metapackage does not specify an exact version (you could make the metapackage depend on >= some version number).

This is from experience where this approach has worked well in setting up and maintaining a common software platform across a large number of machines (including nodes of a compute cluster) -- although in cases where the required software components are not available in standard package repositories, it is then necessary to build a package for it locally and publish that to your repository; this can then be added as a requirement in your metapackage.

The above is in general terms, but taking the specific example on which this experience is based, if the client machines are running CentOS, then you would create a meta-RPM with dependencies on packages in standard repositories (e.g. base and EPEL) plus any other RPMs that you need to build locally, publish it to the repository on the http server and use createrepo to construct the necessary repository metadata, and create a config file in /etc/yum.repo.d on the clients to point to your repository and run yum install <your_meta_package>.  Any subsequent yum update on the clients will pick up any changes that you push to your repository.  The http server itself is simply serving static content, so does not need special configuration.

For Ubuntu etc, you could do similarly but with deb packages and APT.

One thing worth mentioning is that the above is aimed at a rather homogeneous environment, where the same operating system is in use on all the client machines.  If you want to cater for a more heterogeneous environment, then an alternative approach would be to use conda.  You could similarly maintain a conda channel containing a metapackage.

Body:
I'd like to write a bash script that will be executed on new users' linux machines. The script should make sure the machine is ready to compile and run several fortran and python scripts. My intent was to check for GCC and subsequently check for gfortran in GCC and then use homebrew to install the gfortran formula if not present. Similarly with python, I would use pip to install python3 if python isn't up to date.

I would like some advice before I begin. What are some best practices for checking for programs and installing them through a behind the scenes bash script? What are things to be careful for? I realize this question is vague but literally any advice is greatly appreciated.


问:
how to write circe decoder/encoder for abstract class
I need to write decoder/encoder for akka.http.scaladsl.model.HttpHeader

```<code>abstract class HttpHeader extends jm.HttpHeader with ToStringRenderable {
  def name: String
  def value: String
  def lowercaseName: String
  def is(nameInLowerCase: String): Boolean = lowercaseName == nameInLowerCase
  def isNot(nameInLowerCase: String): Boolean = lowercaseName != nameInLowerCase
}
</code>```

i've tried to use derive encode and decode, but it didn't work

```<code>implicit val jsonDecoder: Decoder[HttpHeader] = deriveDecoder[HttpHeader]
implicit val jsonEncoder: Encoder[HttpHeader] = deriveEncoder[HttpHeader]
</code>```

just getting an error could not find Lazy implicit value of type io.circe.generic.decoding.DerivedDecoder[akka.http.scaladsl.model.HttpHeader]

答:
Circe's generic derivation (deriveDecoder, etc.) only works for types that it recognizes as "algebraic data types" (which in Scala means case classes and sealed hierarchies of case classes).

You can definitely use Circe with types like your HttpHeader, but you'll have to be a little more explicit about how you want them encoded. Part of the reason for this is that there are many possible ways you could encode values of this type—e.g. do you want derived properties like the lowercaseName value included in the serialisation?

Here's one possible way to write instances for this type:

```<code>import io.circe.{Decoder, Encoder}

abstract class HttpHeader {
  def name: String
  def value: String
  def lowercaseName: String
  def is(nameInLowerCase: String): Boolean = lowercaseName == nameInLowerCase
  def isNot(nameInLowerCase: String): Boolean = lowercaseName != nameInLowerCase
}

implicit val decodeHttpHeader: Decoder[HttpHeader] =
  Decoder.forProduct2("name", "value") {
    (n: String, v: String) => new HttpHeader {
      val name = n
      val value = v
      def lowercaseName = v.toLowerCase
    }
  }

implicit val encodeHttpHeader: Encoder[HttpHeader] =
  Encoder.forProduct2("name", "value") { header =>
    (header.name, header.value)
  }
</code>```

Which works like this:

```<code>scala> import io.circe.syntax._, io.circe.jawn.decode
import io.circe.syntax._
import io.circe.jawn.decode

scala> decode[HttpHeader]("""{ "name": "ABC", "value": "XYZ" }""")
res0: Either[io.circe.Error,HttpHeader] = Right($anon$1@dcd9c89b)

scala> res0.map(_.asJson)
res1: scala.util.Either[io.circe.Error,io.circe.Json] =
Right({
  "name" : "ABC",
  "value" : "XYZ"
})
</code>```

You could also get lower-level, building up the instances using flatMap or other combinators directly, but most of the time in situations like this forProductN is what you want.

Body:
I need to write decoder/encoder for akka.http.scaladsl.model.HttpHeader

abstract class HttpHeader extends jm.HttpHeader with ToStringRenderable {
  def name: String
  def value: String
  def lowercaseName: String
  def is(nameInLowerCase: String): Boolean = lowercaseName == nameInLowerCase
  def isNot(nameInLowerCase: String): Boolean = lowercaseName != nameInLowerCase
}

i've tried to use derive encode and decode, but it didn't work

implicit val jsonDecoder: Decoder[HttpHeader] = deriveDecoder[HttpHeader]
implicit val jsonEncoder: Encoder[HttpHeader] = deriveEncoder[HttpHeader]

just getting an error could not find Lazy implicit value of type io.circe.generic.decoding.DerivedDecoder[akka.http.scaladsl.model.HttpHeader]

Body:
Circe's generic derivation (deriveDecoder, etc.) only works for types that it recognizes as "algebraic data types" (which in Scala means case classes and sealed hierarchies of case classes).

You can definitely use Circe with types like your HttpHeader, but you'll have to be a little more explicit about how you want them encoded. Part of the reason for this is that there are many possible ways you could encode values of this type—e.g. do you want derived properties like the lowercaseName value included in the serialisation?

Here's one possible way to write instances for this type:

import io.circe.{Decoder, Encoder}

abstract class HttpHeader {
  def name: String
  def value: String
  def lowercaseName: String
  def is(nameInLowerCase: String): Boolean = lowercaseName == nameInLowerCase
  def isNot(nameInLowerCase: String): Boolean = lowercaseName != nameInLowerCase
}

implicit val decodeHttpHeader: Decoder[HttpHeader] =
  Decoder.forProduct2("name", "value") {
    (n: String, v: String) => new HttpHeader {
      val name = n
      val value = v
      def lowercaseName = v.toLowerCase
    }
  }

implicit val encodeHttpHeader: Encoder[HttpHeader] =
  Encoder.forProduct2("name", "value") { header =>
    (header.name, header.value)
  }

Which works like this:

scala> import io.circe.syntax._, io.circe.jawn.decode
import io.circe.syntax._
import io.circe.jawn.decode

scala> decode[HttpHeader]("""{ "name": "ABC", "value": "XYZ" }""")
res0: Either[io.circe.Error,HttpHeader] = Right($anon$1@dcd9c89b)

scala> res0.map(_.asJson)
res1: scala.util.Either[io.circe.Error,io.circe.Json] =
Right({
  "name" : "ABC",
  "value" : "XYZ"
})

You could also get lower-level, building up the instances using flatMap or other combinators directly, but most of the time in situations like this forProductN is what you want.


问:
What is the different between encode and encription?
I am using windows form and mysql.

I am very confuse about different between encode and encription?.

encode also change the string value. and decode is give back the string.

In my program,...

userid - mcs
password - mcs

i want to store these strings in mysql database. but not a same string, for security purpose.

What is secure way to store these datas.

encode and encription which is best for this requirement.

thanks in advance.

i googled for the different but till i am not clear!. any one pls tell me  the different between encode and encription?. For my requrement what i use?.

Before leave this question just vist my downvote question in Click here

答:
Always google gives the best answer, by quick search.. Very neat with example explanation here.

http://www.blesta.com/2009/07/26/encoding-vs-encryption/

http://www.perlmonks.org/index.pl?node_id=66249

Don't get confused, encoding is not encryption

http://www.di-mgt.com.au/encode_encrypt.html


问:
Is there any other way so that i can get rid of this problem as my page.click() function is not working
I am trying to scrape OLX cars data but I'm unable to click on load more .

Both code are not working

await page.click('#container > main > div > section > div > div > div:nth-child(7) > div._3etsg > div > div.JbJAl > button')
await page.evaluate(()=>document.querySelector('#container > main > div > section > div > div > div:nth-child(7) > div._3etsg > div > div.JbJAl > button').click())```

答:
There is some error with your selector, this code is working for me on https://www.olx.in

```<code>await page.click("#container > main > div > section > div > div > div > div.JbJAl > button");
</code>```

Can you check if this works?

Body:
There is some error with your selector, this code is working for me on https://www.olx.in

await page.click("#container > main > div > section > div > div > div > div.JbJAl > button");

Can you check if this works?


问:
Unable to produce desired UI output for Chartjs tooltips
I have the following scenario:
x-axes: String date
y-axes: Integers

2 data sets

When i hover over a particular data point, i want to display the following:

```<code>Data collected as of 2020-06-02
33,600
33,000
Diff: 600
</code>```

Here is what i get instead:

```<code>Data collected as of undefined
33,600
33,000
Diff: NaN
</code>```

Here is my tooltip callbacks code:

```<code>tooltips: {
    mode: 'index',
    intersect: false,
    callbacks: {
      title: function(toolTipItem, data) {
        return "Data points collected as of " + toolTipItem.xLabel;
        // return "Data points collected as of " + data.labels[toolTipItem.index];  // this did not work either
      },
      label: function(toolTipItem, data) {
        if (toolTipItem.datasetIndex === 0) {
          return toolTipItem.yLabel.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ',');
        } else if (toolTipItem.datasetIndex === 1) {
          return toolTipItem.yLabel.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ',');
        }
      },
      labelColor: function(toolTipItem, data){
        if (toolTipItem.datasetIndex === 0) {
          return {
            borderColor: 'rgba(196, 196, 196, 1)'
          };
        } else if (toolTipItem.datasetIndex === 1) {
          return {
            borderColor: 'rgba(127, 231, 106, 1)'
          };
        }
      },
      footer: function(toolTipItems, data) {
        let diff = 0;
        diff = parseInt(data.datasets[0].data[toolTipItems.index]) - parseInt(data.datasets[1].data[toolTipItems.index]);
        return 'Diff: ' + diff;
        // return 'Diff: ' + diff.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ',');  // this did not work either
      }
    }
  },
</code>```

I have followed the sample here:
Sample tooltip callback use case from chartjs

Having said that, would like to know why in the documentation: chartjs docs
Sometimes the argument is ToolTipItem[] and sometimes it is ToolTipItem. Am i missing something?

Thanks.

答:
I figured out where I went wrong and what caused the confusion.

Under the label/labelColor attribute, I merely had to perform an equal check on toolTipItem.datasetIndex. This lead me to believe that I could call the attributes directly. However, when it came to any other attributes (i tried title, footer, afterBody),  toolTipItem.datasetIndex did not exist and when i printed out the keys of the toolTipItem, i got [0, 1]. Upon further expansion of what the values of toolTipItem[0] and toolTipItem[1], i discovered a list of attributes which i was looking for (i.e. index, x/yLabel..).

This ultimately helped me solved the issue. So all i needed to do was:

```<code>...
return "Data points collected as of " + toolTipItem[0].xLabel
...
</code>```

for the title property and:

```<code>...
    diff = parseInt(data.datasets[0].data[toolTipItems[0].index]) - parseInt(data.datasets[1].data[toolTipItems[1].index]);
...
</code>```

I am still not sure how come label & labelColor still could function if I did not specify the index for toolTipItem, but whatever the case is/was it is solved now. If someone could point out if i have a bug waiting to happen, it will be greatly appreciated.

Body:
I have the following scenario:
x-axes: String date
y-axes: Integers

2 data sets

When i hover over a particular data point, i want to display the following:

Data collected as of 2020-06-02
33,600
33,000
Diff: 600

Here is what i get instead:

Data collected as of undefined
33,600
33,000
Diff: NaN

Here is my tooltip callbacks code:

tooltips: {
    mode: 'index',
    intersect: false,
    callbacks: {
      title: function(toolTipItem, data) {
        return "Data points collected as of " + toolTipItem.xLabel;
        // return "Data points collected as of " + data.labels[toolTipItem.index];  // this did not work either
      },
      label: function(toolTipItem, data) {
        if (toolTipItem.datasetIndex === 0) {
          return toolTipItem.yLabel.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ',');
        } else if (toolTipItem.datasetIndex === 1) {
          return toolTipItem.yLabel.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ',');
        }
      },
      labelColor: function(toolTipItem, data){
        if (toolTipItem.datasetIndex === 0) {
          return {
            borderColor: 'rgba(196, 196, 196, 1)'
          };
        } else if (toolTipItem.datasetIndex === 1) {
          return {
            borderColor: 'rgba(127, 231, 106, 1)'
          };
        }
      },
      footer: function(toolTipItems, data) {
        let diff = 0;
        diff = parseInt(data.datasets[0].data[toolTipItems.index]) - parseInt(data.datasets[1].data[toolTipItems.index]);
        return 'Diff: ' + diff;
        // return 'Diff: ' + diff.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ',');  // this did not work either
      }
    }
  },

I have followed the sample here:
Sample tooltip callback use case from chartjs

Having said that, would like to know why in the documentation: chartjs docs
Sometimes the argument is ToolTipItem[] and sometimes it is ToolTipItem. Am i missing something?

Thanks.

Body:
I figured out where I went wrong and what caused the confusion.

Under the label/labelColor attribute, I merely had to perform an equal check on toolTipItem.datasetIndex. This lead me to believe that I could call the attributes directly. However, when it came to any other attributes (i tried title, footer, afterBody),  toolTipItem.datasetIndex did not exist and when i printed out the keys of the toolTipItem, i got [0, 1]. Upon further expansion of what the values of toolTipItem[0] and toolTipItem[1], i discovered a list of attributes which i was looking for (i.e. index, x/yLabel..).

This ultimately helped me solved the issue. So all i needed to do was:

...
return "Data points collected as of " + toolTipItem[0].xLabel
...

for the title property and:

...
    diff = parseInt(data.datasets[0].data[toolTipItems[0].index]) - parseInt(data.datasets[1].data[toolTipItems[1].index]);
...

I am still not sure how come label & labelColor still could function if I did not specify the index for toolTipItem, but whatever the case is/was it is solved now. If someone could point out if i have a bug waiting to happen, it will be greatly appreciated.


问:
Add client ip to graylog output with Gelf.Extensions.Logging package
I am using the Gelf.Extensions.Logging package to send log info to graylog from an asp.net core 3 website, and I would like additional fields like current user name, client ip, user agent.

In startup.cs, I have the following, but I don't know how to add the data to AdditionalFields that I want - I'm not even sure that this would be the right place, as I can't see how to inject the http context at this early stage.

```<code>public static IHostBuilder CreateHostBuilder(string[] args) =>
  Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
      webBuilder.UseStartup<Startup>()
        .ConfigureLogging((context, builder) => builder.AddGelf(options =>
        {
          options.AdditionalFields["machine_name"] = Environment.MachineName;
          options.AdditionalFields["environment_name"] = context.HostingEnvironment.EnvironmentName;

          options.AdditionalFields["app_version"] = Assembly.GetEntryAssembly()?.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
        }));
    });
</code>```

My appsettings.json is like so:

```<code>{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Information",
      "System": "Warning"
    },
    "GELF": {
      "Host": "graylog",
      "Port": 12202,
      "Protocol": "HTTP",
      "LogSource": "DataEntry",
      "LogLevel": {
        "Default": "Information",
        "Microsoft": "Information",
        "System": "Warning"
      }
    }
  },
  "AllowedHosts": "*",
   /* snip */
}
</code>```

答:
It turns out the recommended approach here it to use a middleware like this example to add information about the current request as fields:</p>

```<code>public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        // Register the middleware like so:
        app.UseAppEnvironmentInfo();
    }
}

public static class RequestAppEnvironmentInfoMiddlewareExtensions
{
    public static IApplicationBuilder UseAppEnvironmentInfo(
        this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<AppEnvironmentInfoMiddleware>();
    }
}

public class AppEnvironmentInfoMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly ILogger<AppEnvironmentInfoMiddleware> _logger;

    public AppEnvironmentInfoMiddleware(RequestDelegate next,
        IHttpContextAccessor httpContextAccessor, ILogger<AppEnvironmentInfoMiddleware> logger)
    {
        _next = next;
        _httpContextAccessor = httpContextAccessor;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        using (_logger.BeginScope(("machine_name", Environment.MachineName)))
        using (_logger.BeginScope(("environment_name", context.HostingEnvironment.EnvironmentName)))
        using (_logger.BeginScope(("app_version", Assembly.GetEntryAssembly()?.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion)))
        {
            await _next.Invoke(context);
        }
    }
}
</code>```

Body:
I am using the Gelf.Extensions.Logging package to send log info to graylog from an asp.net core 3 website, and I would like additional fields like current user name, client ip, user agent.

In startup.cs, I have the following, but I don't know how to add the data to AdditionalFields that I want - I'm not even sure that this would be the right place, as I can't see how to inject the http context at this early stage.

public static IHostBuilder CreateHostBuilder(string[] args) =>
  Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
      webBuilder.UseStartup<Startup>()
        .ConfigureLogging((context, builder) => builder.AddGelf(options =>
        {
          options.AdditionalFields["machine_name"] = Environment.MachineName;
          options.AdditionalFields["environment_name"] = context.HostingEnvironment.EnvironmentName;

          options.AdditionalFields["app_version"] = Assembly.GetEntryAssembly()?.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
        }));
    });

My appsettings.json is like so:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Information",
      "System": "Warning"
    },
    "GELF": {
      "Host": "graylog",
      "Port": 12202,
      "Protocol": "HTTP",
      "LogSource": "DataEntry",
      "LogLevel": {
        "Default": "Information",
        "Microsoft": "Information",
        "System": "Warning"
      }
    }
  },
  "AllowedHosts": "*",
   /* snip */
}

Body:
It turns out the recommended approach here it to use a middleware like this example to add information about the current request as fields:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        // Register the middleware like so:
        app.UseAppEnvironmentInfo();
    }
}

public static class RequestAppEnvironmentInfoMiddlewareExtensions
{
    public static IApplicationBuilder UseAppEnvironmentInfo(
        this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<AppEnvironmentInfoMiddleware>();
    }
}

public class AppEnvironmentInfoMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly ILogger<AppEnvironmentInfoMiddleware> _logger;

    public AppEnvironmentInfoMiddleware(RequestDelegate next,
        IHttpContextAccessor httpContextAccessor, ILogger<AppEnvironmentInfoMiddleware> logger)
    {
        _next = next;
        _httpContextAccessor = httpContextAccessor;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        using (_logger.BeginScope(("machine_name", Environment.MachineName)))
        using (_logger.BeginScope(("environment_name", context.HostingEnvironment.EnvironmentName)))
        using (_logger.BeginScope(("app_version", Assembly.GetEntryAssembly()?.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion)))
        {
            await _next.Invoke(context);
        }
    }
}


问:
How can I connect to multiple databases from a Blazor .NET Core project?
How do I connect to multiple database instances from a Blazor WebAssembly project, where I have also added the ASP.NET Core hosted?

My thought was to initiate the DBContexts into the `Startup.cs`` (from Blazor.Server Application which has a reference to Blazor.Client Application):

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<DatabaseContext>(options =>
            options.UseSqlite(
                "connection string holder ..."));
}
```

like this but I want to let the user choose in my View if they want to do a test run of the App where the SQLite database instance will be created. The regular run will be an instance to SQL Server database. How can I do this in the ConfigureServices method?

Right now I am building the DBContexts classes, are these effected too?

The controllers are not done yet, are ASP.NET Core MVC controllers the right choice?

答:
You can implement that using 2 DB contexts, one interface and a service choosing the context from data sent in API requests:

DB context interface

public interface IDatabaseContext
{
// add all DbSet declaration here
}
```

<p><strong>db context</strong></p>

```public class DatabaseContext : IDatabaseContext
{
// db context implementation
}
```

<p><strong>Test db context</strong></p>

<pre class="lang-cs prettyprint-override"><code>public class TestDatabaseContext: DatabaseContext
{
// add your constructor
}
</code>```

DbContext resolver service

public class DbContextResolver
{
    public bool IsTest { get; set; }
```

<p><strong>Server side DI setup</strong></p>

<pre class="lang-cs prettyprint-override"><code>services.AddDbContext<DatabaseContext>(options =>
            options.UseSqlServer(
                "SqlServer connection string holder ..."))
        .AddDbContext<TestDatabaseContext>(options =>
            options.UseSqlite(
                "Sqlite connection string holder ..."))
        .AddScoped<DbContextResolver>())
        .AddScoped<IDatabaseContext>(p =>
        {
            var resolver = p.GetRequiredService<DbContextResolver>();
            if (resolver.IsTest)
            {
                retrun p.GetRequiredService<TestDatabaseContext>();
            }
            return p.GetRequiredService<DatabaseContext>();
        }));
</code>```

Select the DB Context from request

public void Configure(IApplicationBuilder app)
{
     app.Use((context, next) =>
     {
          var resolver = context.RequestServices.GetRequiredService<DbContextResolver>();
          resolver.IsTest = context.Request.Query.ContainsKey("test"); // here the context is choosed by query string but you can choose to send an header instead
          return next();
     }
}
```

<p><strong>use the chosen DB context in controller or a service</strong></p>

<pre class="lang-cs prettyprint-override"><code>public class MyController : Controller
{
     public MyController(IDatabaseContext context)
...
}
</code>```

Body:
How do I connect to multiple database instances from a Blazor WebAssembly project, where I have also added the ASP.NET Core hosted?

My thought was to initiate the DBContexts into the `Startup.cs`` (from Blazor.Server Application which has a reference to Blazor.Client Application):

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<DatabaseContext>(options =>
            options.UseSqlite(
                "connection string holder ..."));
}

like this but I want to let the user choose in my View if they want to do a test run of the App where the SQLite database instance will be created. The regular run will be an instance to SQL Server database. How can I do this in the ConfigureServices method?

Right now I am building the DBContexts classes, are these effected too?

The controllers are not done yet, are ASP.NET Core MVC controllers the right choice?

Body:
You can implement that using 2 DB contexts, one interface and a service choosing the context from data sent in API requests:

DB context interface

public interface IDatabaseContext
{
// add all DbSet declaration here
}

db context

public class DatabaseContext : IDatabaseContext
{
// db context implementation
}

Test db context

public class TestDatabaseContext: DatabaseContext
{
// add your constructor
}

DbContext resolver service

public class DbContextResolver
{
    public bool IsTest { get; set; }

Server side DI setup

services.AddDbContext<DatabaseContext>(options =>
            options.UseSqlServer(
                "SqlServer connection string holder ..."))
        .AddDbContext<TestDatabaseContext>(options =>
            options.UseSqlite(
                "Sqlite connection string holder ..."))
        .AddScoped<DbContextResolver>())
        .AddScoped<IDatabaseContext>(p =>
        {
            var resolver = p.GetRequiredService<DbContextResolver>();
            if (resolver.IsTest)
            {
                retrun p.GetRequiredService<TestDatabaseContext>();
            }
            return p.GetRequiredService<DatabaseContext>();
        }));

Select the DB Context from request

public void Configure(IApplicationBuilder app)
{
     app.Use((context, next) =>
     {
          var resolver = context.RequestServices.GetRequiredService<DbContextResolver>();
          resolver.IsTest = context.Request.Query.ContainsKey("test"); // here the context is choosed by query string but you can choose to send an header instead
          return next();
     }
}

use the chosen DB context in controller or a service

public class MyController : Controller
{
     public MyController(IDatabaseContext context)
...
}


问:
Unable to connect with container at address /0.0.0.0:9000
My container of play/scala application starts at [info] p.c.s.AkkaHttpServer - Listening for HTTP on /0.0.0.0:9000. But I am unable to connect to it from the browser. I am running the container on my windows machine after having build the image using Docker for Windows

The Dockerfile is

```<code>FROM openjdk:8
WORKDIR deploy
COPY target/universal/myapp-1.0.zip .

COPY conf/logback_dev.xml ./logback.xml
COPY conf/application_dev.conf ./application.conf
RUN unzip myapp-1.0.zip
RUN chmod +x myapp-1.0/bin/myapp
EXPOSE 9000
ENTRYPOINT myapp-1.0/bin/myapp -Dplay.http.secret.key=changemeplease -Dlogger.file=/deploy/logback.xml -Dconfig.file=/deploy/application.conf
</code>```

I am starting the container as docker run myApp -p 9000:9000 -network="host" and also tried docker run myApp -p 9000:9000 -network="host"

UPDATE

this is interesting.
If I specify image name before port then the application isn't reachable

```<code>docker run  myApp -p 9000:9000
</code>```

In docker container ps -a, I see (no mapping of localhost:9000 to 9000)

```<code>C:\Users\manuc>docker container ps -a
CONTAINER ID        IMAGE                     COMMAND                  CREATED             STATUS              PORTS                NAMES
4d16547cd96d        myApp   "/bin/sh -c 'myApp…"   10 seconds ago      Up 9 seconds        9000/tcp, 9042/tcp   ecstatic_bell
</code>```

but if I specify port before image name, then the application is reachable

```<code>docker run  -p 9000:9000 myApp
</code>```

In docker container ps -a, I see mapping of localhost:9000 -> 9000

```<code>C:\Users\manuc>docker container ps -a
CONTAINER ID        IMAGE                     COMMAND                  CREATED             STATUS              PORTS                              NAMES
24b571cc0057        myApp   "/bin/sh -c 'MyApp…"   39 seconds ago      Up 38 seconds       0.0.0.0:9000->9000/tcp, 9042/tcp   silly_yalow
</code>```

答:
Things to do when your container is not behaving like you want:

Check if your application is running in your computer.

After you run your container, check if it is healthy with docker ps. If it is not healthy, the problem is usually in your application.

Ensure it is running without errors, check logs with docker logs <container-id>. If logs are ok, problem is usually in the container network configuration.

Ensure you can access your application with docker exec -it <container-id> bash. And try to access port with curl or wget. If it is not reachable problem can be in iptables, firewall, or your application.

If you can ensure all the steps above working as expected. The problem is in docker network configuration.

Docker network host only works in linux, not mac and windows. You can run container with docker run -p 9000:9000 myapp. Checkout documentation: https://docs.docker.com/network/host/#:~:text=The%20host%20networking%20driver%20only,the%20docker%20service%20create%20command.

General form of the docker run command is docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...] as you can see in documentation. You need to specify port options before image name.

Body:
My container of play/scala application starts at [info] p.c.s.AkkaHttpServer - Listening for HTTP on /0.0.0.0:9000. But I am unable to connect to it from the browser. I am running the container on my windows machine after having build the image using Docker for Windows

The Dockerfile is

FROM openjdk:8
WORKDIR deploy
COPY target/universal/myapp-1.0.zip .

COPY conf/logback_dev.xml ./logback.xml
COPY conf/application_dev.conf ./application.conf
RUN unzip myapp-1.0.zip
RUN chmod +x myapp-1.0/bin/myapp
EXPOSE 9000
ENTRYPOINT myapp-1.0/bin/myapp -Dplay.http.secret.key=changemeplease -Dlogger.file=/deploy/logback.xml -Dconfig.file=/deploy/application.conf

I am starting the container as docker run myApp -p 9000:9000 -network="host" and also tried docker run myApp -p 9000:9000 -network="host"

UPDATE

this is interesting.
If I specify image name before port then the application isn't reachable

docker run  myApp -p 9000:9000

In docker container ps -a, I see (no mapping of localhost:9000 to 9000)

C:\Users\manuc>docker container ps -a
CONTAINER ID        IMAGE                     COMMAND                  CREATED             STATUS              PORTS                NAMES
4d16547cd96d        myApp   "/bin/sh -c 'myApp…"   10 seconds ago      Up 9 seconds        9000/tcp, 9042/tcp   ecstatic_bell

but if I specify port before image name, then the application is reachable

docker run  -p 9000:9000 myApp

In docker container ps -a, I see mapping of localhost:9000 -> 9000

C:\Users\manuc>docker container ps -a
CONTAINER ID        IMAGE                     COMMAND                  CREATED             STATUS              PORTS                              NAMES
24b571cc0057        myApp   "/bin/sh -c 'MyApp…"   39 seconds ago      Up 38 seconds       0.0.0.0:9000->9000/tcp, 9042/tcp   silly_yalow


问:
How to remove stop words using nltk or python
I have a dataset from which I would like to remove stop words.

I used NLTK to get a list of stop words:

```<code>from nltk.corpus import stopwords

stopwords.words('english')
</code>```

Exactly how do I compare the data to the list of stop words, and thus remove the stop words from the data?

答:
In case your data are stored as a Pandas DataFrame, you can use remove_stopwords from textero that use the NLTK stopwords list by default.

import pandas as pd
import texthero as hero
df['text_without_stopwords'] = hero.remove_stopwords(df['text'])
```

Body:
I have a dataset from which I would like to remove stop words.

I used NLTK to get a list of stop words:

from nltk.corpus import stopwords

stopwords.words('english')

Exactly how do I compare the data to the list of stop words, and thus remove the stop words from the data?


问:
Certbot - DNS problem: NXDOMAIN looking up A for xxx - check that a DNS records exists for this
So I tried to run the following

```<code>sudo certbot certonly --nginx --dry-run -d subdomain.domain.com -d www.subdomain.domain.com
</code>```

That gave me a DNS problem, however, it worked when running

```<code>sudo certbot certonly --nginx --dry-run -d subdomain.domain.com
</code>```

Am I missing something in my DNS records?

I have sucessfully run

```<code>sudo certbot certonly --nginx --dry-run -d domain.com -d www.domain.com
</code>```

Do I need to make a specific DNS record for the ´´www´´ part if I use subdomains?

Edit
Result of running ´´dig subdomain.domain.com´´

```<code>; <<>> DiG 9.11.5-P4-5.1ubuntu2.1-Ubuntu <<>> subdomain.domain.co.uk
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 45932
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 65494
;; QUESTION SECTION:
;subdomain.domain.co.uk.           IN      A

;; ANSWER SECTION:
subdomain.domain.co.uk.    1800    IN      A       xxx.yyy.aa.dd

;; Query time: 88 msec
;; SERVER: 127.0.0.53#53(127.0.0.53)
;; WHEN: Fri Feb 07 11:24:26 UTC 2020
;; MSG SIZE  rcvd: 64
</code>```

答:
Adding proper answer from the question:

Create an type A entry with the host "www.subdomain" and you're good

I'd add to wait anywhere between 5 minutes to an hour for the record to take effect and for certbot to be able to see it, from my experience.

Body:
So I tried to run the following

sudo certbot certonly --nginx --dry-run -d subdomain.domain.com -d www.subdomain.domain.com

That gave me a DNS problem, however, it worked when running

sudo certbot certonly --nginx --dry-run -d subdomain.domain.com

Am I missing something in my DNS records?

I have sucessfully run

sudo certbot certonly --nginx --dry-run -d domain.com -d www.domain.com

Do I need to make a specific DNS record for the ´´www´´ part if I use subdomains?

Edit
Result of running ´´dig subdomain.domain.com´´

; <<>> DiG 9.11.5-P4-5.1ubuntu2.1-Ubuntu <<>> subdomain.domain.co.uk
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 45932
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 65494
;; QUESTION SECTION:
;subdomain.domain.co.uk.           IN      A

;; ANSWER SECTION:
subdomain.domain.co.uk.    1800    IN      A       xxx.yyy.aa.dd

;; Query time: 88 msec
;; SERVER: 127.0.0.53#53(127.0.0.53)
;; WHEN: Fri Feb 07 11:24:26 UTC 2020
;; MSG SIZE  rcvd: 64


问:
wrapper | OpenSCManager failed - Access is denied. (0x5)
I am trying to install Archiva on windows 8.1 pro (64 bit) and I am continuously getting the same error as below

wrapper  | OpenSCManager failed - Access is denied. (0x5).

I logged in as administrator only. But still I am getting the same error. Most of the answers for the same problem I am seeing it for VISTA and 7 etc.. But not for Windows8.1 Pro (64 bit)

答:
Click on Start

Click All Programs

Click on Accessories

Right click on Command Prompt icon

Click Properties

Click on the Shortcut tab on the top

Click the Advanced button at the bottom

Click on the check box that says:

Run as Administrator

Click OK

Go to the folder having the batch file

Enter the command which was giving

Access denied

error

It will execute successfully.


问:
Persist selected item on ASP.Net custom control
I have built the following custom control that I have built and I set the selected value when a bullet list item is clicked.

My problem is that I need to set the css class (SetSelected()) after postback, but it always picks up the previous entry in the viewstate rather than picking up the new value.

I don't think I should be using PageLoad for setting the CSS class but am unsure where best to do this.

Can anyone help please?

```<code>[DefaultProperty("SelectedValue"),
ToolboxData("<{0}:GlossaryList runat=\"server\" />")]
public class GlossaryList : WebControl
{
    const string MANAGEDMETADATASERVICE = "Managed Metadata Service";
    const string TOYOTA = "Toyota";

    BulletedList _bulletList = new BulletedList();

    public String SelectedText
    {
        get
        {
            object selectedText = ViewState["SelectedText"];
            return (selectedText == null) ? String.Empty : (string)selectedText;
        }
        set
        {
            ViewState["SelectedText"] = value;
        }
    }

    public String SelectedValue
    {
        get
        {
            object selectedValue = ViewState["SelectedValue"];
            return (selectedValue == null) ? String.Empty : (string)selectedValue;
        }
        set
        {
            ViewState["SelectedValue"] = value;
        }
    }

    protected override void OnInit(EventArgs e)
    {
        CreateBulletedList();

        base.OnInit(e);
    }

    protected override void OnLoad(EventArgs e)
    {
        if (this.Page.IsPostBack)
        {
            SetSelected();
        }

        base.OnLoad(e);
    }

    private void SetSelected()
    {
        //if(this.Controls != null && this.Controls.Count > 0)
        //{
        //    foreach (ListItem listItem in ((BulletedList)this.Controls[0]).Items)
        //    {
        //        if (listItem.Value == SelectedValue)
        //        {
        //            listItem.Attributes.Add("class", "active");
        //        }
        //    }
        //}
    }

    protected void CreateBulletedList()
    {
        _bulletList.Click += new BulletedListEventHandler(BulletListItem_Click);
        _bulletList.DisplayMode = BulletedListDisplayMode.LinkButton;
        _bulletList.CssClass = "letter-selector";

        for (char c = 'A'; c <= 'Z'; c++)
        {
            ListItem listItem = new ListItem();

            listItem.Text = c.ToString();
            listItem.Value = c.ToString();

            if (SelectedValue == c.ToString())
            {
                listItem.Attributes.Add("class", "active");
            }

            _bulletList.Items.Add(listItem);
        }

        if (!this.Page.IsPostBack)
        {
            _bulletList.Items[0].Selected = true;
            _bulletList.Items[0].Attributes.Add("class", "active");
        }

        this.Controls.Add(_bulletList);
    }

    private void BulletListItem_Click(object sender, BulletedListEventArgs e)
    {
        SelectedValue = SelectedText = _bulletList.Items[e.Index].Value;

        SetActive(e.Index);
    }

    private void SetActive(int index)
    {
        if (this.Controls != null && ((BulletedList)this.Controls[0]).Items.Count > 0)
        {
            foreach (ListItem listItem in ((BulletedList)this.Controls[0]).Items)
            {
                listItem.Attributes.Clear();
            }
        }

        ((BulletedList)this.Controls[0]).Items[index].Attributes.Add("class", "active");
    }
}
</code>```

答:
Add following code:

```<code>protected override void CreateChildControls()
{
    Controls.Clear();
    CreateBulletedList();
}

public override ControlCollection Controls
{
    get
    {
        EnsureChildControls();
        return base.Controls;
    }
}

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    EnsureChildControls();
}
</code>```

Change the SetSelected method:

```<code>private void SetSelected()
{
        foreach (ListItem listItem in _bulletList.Items)
        {
            if (listItem.Value == SelectedValue)
            {
                listItem.Attributes.Add("class", "active");
            }
        }

}
</code>```

Body:
I have built the following custom control that I have built and I set the selected value when a bullet list item is clicked.

My problem is that I need to set the css class (SetSelected()) after postback, but it always picks up the previous entry in the viewstate rather than picking up the new value.

I don't think I should be using PageLoad for setting the CSS class but am unsure where best to do this.

Can anyone help please?

[DefaultProperty("SelectedValue"),
ToolboxData("<{0}:GlossaryList runat=\"server\" />")]
public class GlossaryList : WebControl
{
    const string MANAGEDMETADATASERVICE = "Managed Metadata Service";
    const string TOYOTA = "Toyota";

    BulletedList _bulletList = new BulletedList();

    public String SelectedText
    {
        get
        {
            object selectedText = ViewState["SelectedText"];
            return (selectedText == null) ? String.Empty : (string)selectedText;
        }
        set
        {
            ViewState["SelectedText"] = value;
        }
    }

    public String SelectedValue
    {
        get
        {
            object selectedValue = ViewState["SelectedValue"];
            return (selectedValue == null) ? String.Empty : (string)selectedValue;
        }
        set
        {
            ViewState["SelectedValue"] = value;
        }
    }

    protected override void OnInit(EventArgs e)
    {
        CreateBulletedList();

        base.OnInit(e);
    }

    protected override void OnLoad(EventArgs e)
    {
        if (this.Page.IsPostBack)
        {
            SetSelected();
        }

        base.OnLoad(e);
    }

    private void SetSelected()
    {
        //if(this.Controls != null && this.Controls.Count > 0)
        //{
        //    foreach (ListItem listItem in ((BulletedList)this.Controls[0]).Items)
        //    {
        //        if (listItem.Value == SelectedValue)
        //        {
        //            listItem.Attributes.Add("class", "active");
        //        }
        //    }
        //}
    }

    protected void CreateBulletedList()
    {
        _bulletList.Click += new BulletedListEventHandler(BulletListItem_Click);
        _bulletList.DisplayMode = BulletedListDisplayMode.LinkButton;
        _bulletList.CssClass = "letter-selector";

        for (char c = 'A'; c <= 'Z'; c++)
        {
            ListItem listItem = new ListItem();

            listItem.Text = c.ToString();
            listItem.Value = c.ToString();

            if (SelectedValue == c.ToString())
            {
                listItem.Attributes.Add("class", "active");
            }

            _bulletList.Items.Add(listItem);
        }

        if (!this.Page.IsPostBack)
        {
            _bulletList.Items[0].Selected = true;
            _bulletList.Items[0].Attributes.Add("class", "active");
        }

        this.Controls.Add(_bulletList);
    }

    private void BulletListItem_Click(object sender, BulletedListEventArgs e)
    {
        SelectedValue = SelectedText = _bulletList.Items[e.Index].Value;

        SetActive(e.Index);
    }

    private void SetActive(int index)
    {
        if (this.Controls != null && ((BulletedList)this.Controls[0]).Items.Count > 0)
        {
            foreach (ListItem listItem in ((BulletedList)this.Controls[0]).Items)
            {
                listItem.Attributes.Clear();
            }
        }

        ((BulletedList)this.Controls[0]).Items[index].Attributes.Add("class", "active");
    }
}

Body:
Add following code:

protected override void CreateChildControls()
{
    Controls.Clear();
    CreateBulletedList();
}

public override ControlCollection Controls
{
    get
    {
        EnsureChildControls();
        return base.Controls;
    }
}

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    EnsureChildControls();
}

Change the SetSelected method:

private void SetSelected()
{
        foreach (ListItem listItem in _bulletList.Items)
        {
            if (listItem.Value == SelectedValue)
            {
                listItem.Attributes.Add("class", "active");
            }
        }

}