问:
Add custom rules for parsing quarters to SUTime
I'm following the official instructions for adding custom SUTime rules for fiscal year quarters (stuff like Q1, Q2, Q3 and Q4).

I used the default defs.sutime.txt and english.sutime.txt as templates for my own rule files.

After appending the following code to my defs.sutime.txt

```<code>  // Financial Quarters
  FYQ1 = {
      type: QUARTER_OF_YEAR,
      label: "FYQ1",
      value: TimeWithRange(TimeRange(IsoDate(ANY,10,1), IsoDate(ANY,12,31), QUARTER))
  }
  FYQ2 = {
      type: QUARTER_OF_YEAR,
      label: "FYQ2",
      value: TimeWithRange(TimeRange(IsoDate(ANY,1,1), IsoDate(ANY,3,31), QUARTER))
  }
  FYQ3 = {
      type: QUARTER_OF_YEAR,
      label: "FYQ3",
      value: TimeWithRange(TimeRange(IsoDate(ANY,4,1), IsoDate(ANY,6,30), QUARTER))
  }
  FYQ4 = {
      type: QUARTER_OF_YEAR,
      label: "FYQ4",
      value: TimeWithRange(TimeRange(IsoDate(ANY,7,1), IsoDate(ANY,9,30), QUARTER))
  }
</code>```

and appending the following code to my english.sutime.txt

```<code>  # Financial Quarters
  FISCAL_YEAR_QUARTER_MAP = {
    "Q1": FYQ1,
    "Q2": FYQ2,
    "Q3": FYQ3,
    "Q4": FYQ4
  }
  FISCAL_YEAR_QUARTER_YEAR_OFFSETS_MAP = {
    "Q1": 1,
    "Q2": 0,
    "Q3": 0,
    "Q4": 0
  }
  $FiscalYearQuarterTerm = CreateRegex(Keys(FISCAL_YEAR_QUARTER_MAP))

  {
    matchWithResults: TRUE,
    pattern: ((/$FiscalYearQuarterTerm/) (FY)? (/(FY)?([0-9]{4})/)),
    result:  TemporalCompose(INTERSECT, IsoDate(Subtract({type: "NUMBER", value: $$3.matchResults[0].word.group(2)}, FISCAL_YEAR_QUARTER_YEAR_OFFSETS_MAP[$1[0].word]), ANY, ANY), FISCAL_YEAR_QUARTER_MAP[$1[0].word])
  }

  {
    pattern: ((/$FiscalYearQuarterTerm/)),
    result: FISCAL_YEAR_QUARTER_MAP[$1[0].word]
  }
</code>```

I'm still unable to correctly parse stuff like "Q1 2020".

How can I properly add rules for parsing fiscal year quarters (e.g. "Q1")?

Here's my full code:

```<code>import java.util.List;
import java.util.Properties;

import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.pipeline.*;
import edu.stanford.nlp.time.*;
import edu.stanford.nlp.util.CoreMap;

public class SUTimeSoExample {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.setProperty("sutime.includeRange", "true");
        props.setProperty("sutime.markTimeRanges", "true");
        props.setProperty("sutime.rules", "./defs.sutime.txt,./english.sutime.txt");

        AnnotationPipeline pipeline = new AnnotationPipeline();
        pipeline.addAnnotator(new TokenizerAnnotator(false));
        pipeline.addAnnotator(new WordsToSentencesAnnotator(false));
        pipeline.addAnnotator(new POSTaggerAnnotator(false));
        pipeline.addAnnotator(new TimeAnnotator("sutime", props));

        String input = "Stuff for Q1 2020";

        Annotation annotation = new Annotation(input);
        annotation.set(CoreAnnotations.DocDateAnnotation.class, "2020-06-01");
        pipeline.annotate(annotation);
        System.out.println(annotation.get(CoreAnnotations.TextAnnotation.class));
        List<CoreMap> timexAnnsAll = annotation.get(TimeAnnotations.TimexAnnotations.class);
        for (CoreMap cm : timexAnnsAll) {
            System.out.println(cm // match
                    + " --> " + cm.get(TimeExpression.Annotation.class).getTemporal() // parsed value
            );
        }
    }
}
</code>```

Note that I deleted the deafult defs.sutime.txt and english.sutime.txt files from the stanford corenlp models JAR in order to avoid this issue.

答:
There is a Java code example here:

https://stanfordnlp.github.io/CoreNLP/sutime.html

It should work if you follow that example, mainly building your pipeline in this manner:

```<code>props.setProperty("annotators", "tokenize,ssplit,pos,lemma,ner");
props.setProperty("ner.docDate.usePresent", "true");
// this will shut off the statistical models if you only want to run SUTime only
props.setProperty("ner.rulesOnly", "true");
// add your sutime properties as in your example
...
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
</code>```

and make sure to use version 4.0.0.

You can set ner.rulesOnly to true if you just want to run SUTime without running the statistical models.

You can use one of several properties for ner.docDate or just set the document date in the annotation before running.

Body:
I'm following the official instructions for adding custom SUTime rules for fiscal year quarters (stuff like Q1, Q2, Q3 and Q4).

I used the default defs.sutime.txt and english.sutime.txt as templates for my own rule files.

After appending the following code to my defs.sutime.txt

  // Financial Quarters
  FYQ1 = {
      type: QUARTER_OF_YEAR,
      label: "FYQ1",
      value: TimeWithRange(TimeRange(IsoDate(ANY,10,1), IsoDate(ANY,12,31), QUARTER))
  }
  FYQ2 = {
      type: QUARTER_OF_YEAR,
      label: "FYQ2",
      value: TimeWithRange(TimeRange(IsoDate(ANY,1,1), IsoDate(ANY,3,31), QUARTER))
  }
  FYQ3 = {
      type: QUARTER_OF_YEAR,
      label: "FYQ3",
      value: TimeWithRange(TimeRange(IsoDate(ANY,4,1), IsoDate(ANY,6,30), QUARTER))
  }
  FYQ4 = {
      type: QUARTER_OF_YEAR,
      label: "FYQ4",
      value: TimeWithRange(TimeRange(IsoDate(ANY,7,1), IsoDate(ANY,9,30), QUARTER))
  }

and appending the following code to my english.sutime.txt

  # Financial Quarters
  FISCAL_YEAR_QUARTER_MAP = {
    "Q1": FYQ1,
    "Q2": FYQ2,
    "Q3": FYQ3,
    "Q4": FYQ4
  }
  FISCAL_YEAR_QUARTER_YEAR_OFFSETS_MAP = {
    "Q1": 1,
    "Q2": 0,
    "Q3": 0,
    "Q4": 0
  }
  $FiscalYearQuarterTerm = CreateRegex(Keys(FISCAL_YEAR_QUARTER_MAP))

  {
    matchWithResults: TRUE,
    pattern: ((/$FiscalYearQuarterTerm/) (FY)? (/(FY)?([0-9]{4})/)),
    result:  TemporalCompose(INTERSECT, IsoDate(Subtract({type: "NUMBER", value: $$3.matchResults[0].word.group(2)}, FISCAL_YEAR_QUARTER_YEAR_OFFSETS_MAP[$1[0].word]), ANY, ANY), FISCAL_YEAR_QUARTER_MAP[$1[0].word])
  }

  {
    pattern: ((/$FiscalYearQuarterTerm/)),
    result: FISCAL_YEAR_QUARTER_MAP[$1[0].word]
  }

I'm still unable to correctly parse stuff like "Q1 2020".

How can I properly add rules for parsing fiscal year quarters (e.g. "Q1")?

Here's my full code:

import java.util.List;
import java.util.Properties;

import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.pipeline.*;
import edu.stanford.nlp.time.*;
import edu.stanford.nlp.util.CoreMap;

public class SUTimeSoExample {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.setProperty("sutime.includeRange", "true");
        props.setProperty("sutime.markTimeRanges", "true");
        props.setProperty("sutime.rules", "./defs.sutime.txt,./english.sutime.txt");

        AnnotationPipeline pipeline = new AnnotationPipeline();
        pipeline.addAnnotator(new TokenizerAnnotator(false));
        pipeline.addAnnotator(new WordsToSentencesAnnotator(false));
        pipeline.addAnnotator(new POSTaggerAnnotator(false));
        pipeline.addAnnotator(new TimeAnnotator("sutime", props));

        String input = "Stuff for Q1 2020";

        Annotation annotation = new Annotation(input);
        annotation.set(CoreAnnotations.DocDateAnnotation.class, "2020-06-01");
        pipeline.annotate(annotation);
        System.out.println(annotation.get(CoreAnnotations.TextAnnotation.class));
        List<CoreMap> timexAnnsAll = annotation.get(TimeAnnotations.TimexAnnotations.class);
        for (CoreMap cm : timexAnnsAll) {
            System.out.println(cm // match
                    + " --> " + cm.get(TimeExpression.Annotation.class).getTemporal() // parsed value
            );
        }
    }
}

Note that I deleted the deafult defs.sutime.txt and english.sutime.txt files from the stanford corenlp models JAR in order to avoid this issue.

Body:
There is a Java code example here:

https://stanfordnlp.github.io/CoreNLP/sutime.html

It should work if you follow that example, mainly building your pipeline in this manner:

props.setProperty("annotators", "tokenize,ssplit,pos,lemma,ner");
props.setProperty("ner.docDate.usePresent", "true");
// this will shut off the statistical models if you only want to run SUTime only
props.setProperty("ner.rulesOnly", "true");
// add your sutime properties as in your example
...
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);

and make sure to use version 4.0.0.

You can set ner.rulesOnly to true if you just want to run SUTime without running the statistical models.

You can use one of several properties for ner.docDate or just set the document date in the annotation before running.


来源: stackexchange

问:
How to implement deep copy or clone of an object that has circular references?
I have such hierarchy:

```<code>class Sphere;
class Cube;
class SpherePair;

class Entity {};

class Cube : public Entity {
public:
  list<Sphere*> spheres_;
};

class Sphere : public Entity {
public:
  Cube       *cube;
  SpherePair *spherepair;
};

class SpherePair : public Entity {
public:
  Sphere *first;
  Sphere *second;
};
</code>```

What I want is to make a clone of Cube object and all the objects connected to it (Sphere, SpherePair, Cube).

Cube has Spheres inside, each Sphere is a half of SpherePair object. SpherePair points to Spheres which are in separate Cubes or in one same Cube.

This is needed for proper Undo functionality.

I would also like to have a map of old and cloned entities:

```<code>std::map<Entity*, Entity*> old_new;
</code>```

Added: Before these circular references I had a simple clone functionality:

```<code>class Entity {
 public:
  virtual Entity* clone() = 0;
}
</code>```

It was used in such a scheme:

```<code>std::vector<Entity*> selected_objects_;

void move(const vec3f &offset) {
  document->beginUndo();

  for(int i = 0; i < selected_objects_.size(); ++i) {
    Entity *cloned = selected_objects_[i]->clone();

    cloned->move(offset);

    selected_objects_[i]->setDeleted(true);
    document->pushToUndo(selected_objects_[i]);
    document->addEntity(cloned);
  }

  document->endUndo();
}
</code>```

答:
As for your general question: regard the structure as a graph with in-memory objects as vertices and pointers as edges. Walk the structure in a depth-first manner. Keep a map, initially empty, of addresses of nodes in the old structure to addresses of nodes in the new structure, by shallow-copying the structure and setting the pointers one-by-one. Stop recursion every time you encounter a substructure whose address has already been seen (is in the map).

However...

This is needed for proper Undo functionality.

I'm not sure I get your point, but you don't need circular references for undo. Use a circular buffer instead (which is really just a flat array with a few flags and pointers) and use structure sharing, if possible, to keep the memory requirements down.

If you meant you need the deep copy for undo, then I still recommend you consider some kind of "flat" graph representation for your objects. Pointer structures are great for trees and DAGs, but very confusing when used for general graphs.

ContentLicense: CC BY-SA 3.0

Body:
I have such hierarchy:

class Sphere;
class Cube;
class SpherePair;

class Entity {};

class Cube : public Entity {
public:
  list<Sphere*> spheres_;
};

class Sphere : public Entity {
public:
  Cube       *cube;
  SpherePair *spherepair;
};

class SpherePair : public Entity {
public:
  Sphere *first;
  Sphere *second;
};

What I want is to make a clone of Cube object and all the objects connected to it (Sphere, SpherePair, Cube).

Cube has Spheres inside, each Sphere is a half of SpherePair object. SpherePair points to Spheres which are in separate Cubes or in one same Cube.

This is needed for proper Undo functionality.

I would also like to have a map of old and cloned entities:

std::map<Entity*, Entity*> old_new;

Added: Before these circular references I had a simple clone functionality:

class Entity {
 public:
  virtual Entity* clone() = 0;
}

It was used in such a scheme:

std::vector<Entity*> selected_objects_;

void move(const vec3f &offset) {
  document->beginUndo();

  for(int i = 0; i < selected_objects_.size(); ++i) {
    Entity *cloned = selected_objects_[i]->clone();

    cloned->move(offset);

    selected_objects_[i]->setDeleted(true);
    document->pushToUndo(selected_objects_[i]);
    document->addEntity(cloned);
  }

  document->endUndo();
}


问:
Is there a way to adjust only the bottom padding of a chart's title in Chart.js?
Based on the documentation, the padding property of the title in Chart.js adjusts both the top and bottom paddings. However, I'd like to adjust only the bottom padding.

I've tried using a padding object:

```<code>title:{
    display: true,
    text:'Population of cities in California',
    padding:{
        left:0,
        right:0,
        bottom:30,
        top:0
    }
}
</code>```

But this is probably not supported, because it just messed everything up and made the chart not even visible.
I've searched the documentation and googled a bit to see if this has been asked somewhere already, but I couldn't find any solutions.

Is there a built-in way to do this within Chart.js? If not, what would be the simplest workaround?

答:
title.padding takes the number of pixels to add above and below the title text.

There exists a workaround to add padding at the bottom of the chart title only. The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterDraw hook to draw the title yourself directly on the canvas using CanvasRenderingContext2D.fillText().

```<code>plugins: [{
  afterDraw: chart => {
    var ctx = chart.chart.ctx;
    ctx.save();
    ctx.textAlign = 'center';
    ctx.font = "18px Arial";
    ctx.fillStyle = "gray";
    ctx.fillText('My Title', chart.chart.width / 2, 20);
    ctx.restore();
  }
}],
</code>```

Together with this, you'll have to define top padding for your chart. This determines the space between your title and the chart (the title bottom padding basicaly).

```<code>layout: {
  padding: {
    top: 80
  }
},
</code>```

Please have a look at below code that shows how it could look like.

new Chart(document.getElementById('myChart'), {
  type: 'bar',
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      ctx.save();
      ctx.textAlign = 'center';
      ctx.font = "18px Arial";
      ctx.fillStyle = "gray";
      ctx.fillText('My Title', chart.chart.width / 2, 20);
      ctx.restore();
    }
  }],
  data: {
    labels: ['A', 'B', 'C', 'D'],
    datasets: [{
      data: [10, 12, 8, 6],
      backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 205, 86, 0.2)', 'rgba(75, 192, 192, 0.2)'],
      borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)'],
      borderWidth: 1
    }]
  },
  options: {
    layout: {
      padding: {
        top: 80
      }
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas></code>```

ContentLicense: CC BY-SA 4.0

Body:
Based on the documentation, the padding property of the title in Chart.js adjusts both the top and bottom paddings. However, I'd like to adjust only the bottom padding.

I've tried using a padding object:

title:{
    display: true,
    text:'Population of cities in California',
    padding:{
        left:0,
        right:0,
        bottom:30,
        top:0
    }
}

But this is probably not supported, because it just messed everything up and made the chart not even visible.
I've searched the documentation and googled a bit to see if this has been asked somewhere already, but I couldn't find any solutions.

Is there a built-in way to do this within Chart.js? If not, what would be the simplest workaround?

Body:
title.padding takes the number of pixels to add above and below the title text.

There exists a workaround to add padding at the bottom of the chart title only. The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterDraw hook to draw the title yourself directly on the canvas using CanvasRenderingContext2D.fillText().

plugins: [{
  afterDraw: chart => {
    var ctx = chart.chart.ctx;
    ctx.save();
    ctx.textAlign = 'center';
    ctx.font = "18px Arial";
    ctx.fillStyle = "gray";
    ctx.fillText('My Title', chart.chart.width / 2, 20);
    ctx.restore();
  }
}],

Together with this, you'll have to define top padding for your chart. This determines the space between your title and the chart (the title bottom padding basicaly).

layout: {
  padding: {
    top: 80
  }
},

Please have a look at below code that shows how it could look like.

new Chart(document.getElementById('myChart'), {
  type: 'bar',
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      ctx.save();
      ctx.textAlign = 'center';
      ctx.font = "18px Arial";
      ctx.fillStyle = "gray";
      ctx.fillText('My Title', chart.chart.width / 2, 20);
      ctx.restore();
    }
  }],
  data: {
    labels: ['A', 'B', 'C', 'D'],
    datasets: [{
      data: [10, 12, 8, 6],
      backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 205, 86, 0.2)', 'rgba(75, 192, 192, 0.2)'],
      borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)'],
      borderWidth: 1
    }]
  },
  options: {
    layout: {
      padding: {
        top: 80
      }
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>


问:
how can I successfuly sanitise taken photo in ionic 4 using capacitor plugin
ionic 4 capacitor camera plugin after taking a picture and then sanitizing but still getting this error:

SafeValue must use [property]=binding: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/4UHuRXhpZgAATU0AKgAAAAgABgEaAAUAAAABAAAAVgEbAAUAAAABAAAAXgEoAAMAAAABAAIAAAITAAMAAAABAAEAAIdpAAQAAAABAAAIcuocAAcAAAgMAAAAZgAAEOQAAAEsAAAAAQAAASwAAAABHOoAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA....

here is my method in .ts file:

```<code>import { Component, OnInit } from '@angular/core';
import { Plugins, CameraResultType, CameraSource} from '@capacitor/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

const { Camera } = Plugins;

  constructor(
    public sanitizer: DomSanitizer
  ) { }

 async takePicture() {

  const image = await Camera.getPhoto({
    quality: 100,
    allowEditing: false,
    resultType: CameraResultType.DataUrl,
    source: CameraSource.Camera
  });

  this.takenImg = this.sanitizer.bypassSecurityTrustResourceUrl(image.dataUrl);

}
</code>```

and in .html file:
    <ion-item>
            Camera
          </ion-item>
          <ion-item>
            <ion-img [src]="takenImg" alt=""></ion-img>
          </ion-item>

答:
I use a standard  tag for this rather than the <ion-img> tag and I don't need to sanitize:

```

Body:
ionic 4 capacitor camera plugin after taking a picture and then sanitizing but still getting this error:

SafeValue must use [property]=binding: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/4UHuRXhpZgAATU0AKgAAAAgABgEaAAUAAAABAAAAVgEbAAUAAAABAAAAXgEoAAMAAAABAAIAAAITAAMAAAABAAEAAIdpAAQAAAABAAAIcuocAAcAAAgMAAAAZgAAEOQAAAEsAAAAAQAAASwAAAABHOoAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA....

here is my method in .ts file:

import { Component, OnInit } from '@angular/core';
import { Plugins, CameraResultType, CameraSource} from '@capacitor/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

const { Camera } = Plugins;

  constructor(
    public sanitizer: DomSanitizer
  ) { }

 async takePicture() {

  const image = await Camera.getPhoto({
    quality: 100,
    allowEditing: false,
    resultType: CameraResultType.DataUrl,
    source: CameraSource.Camera
  });

  this.takenImg = this.sanitizer.bypassSecurityTrustResourceUrl(image.dataUrl);

}

and in .html file:
    <ion-item>
            Camera
          </ion-item>
          <ion-item>
            <ion-img [src]="takenImg" alt=""></ion-img>
          </ion-item>

Body:
I use a standard <img> tag for this rather than the <ion-img> tag and I don't need to sanitize:

<img [src]="image.dataUrl"/>


问:
How do I check if there are any extra columns in my pandas csv?
Currently I am trying to check a csv file if there are certain columns (whether they exist) and also to find out if there are any extra columns (that should not be there) in a certain csv file.

I have put all the required columns into a list and check the list against the columns in the file.

```<code>list = ['column 1', 'column 2' , 'column 3']
for column in list:
    if column not in list:
        /execute  action
</code>```

However, I am unable to find out if any extra columns already exist .
For example csv file has 4 columns, and 3 of them is checked against the list.

How do I get the last column to be displayed or shown?

Thanks in advance!

答:
Lets say you have a setup like this, for example:</p>

```<code>import pandas as pd
list = ['column 1', 'column 2' , 'column 3']

csv_file = pd.read_csv('csv_file_here')
for col in csv_file.columns:
    if col not in list:
        print(col) # The extra column
</code>```

Body:
Currently I am trying to check a csv file if there are certain columns (whether they exist) and also to find out if there are any extra columns (that should not be there) in a certain csv file.

I have put all the required columns into a list and check the list against the columns in the file.

list = ['column 1', 'column 2' , 'column 3']
for column in list:
    if column not in list:
        /execute  action

However, I am unable to find out if any extra columns already exist .
For example csv file has 4 columns, and 3 of them is checked against the list.

How do I get the last column to be displayed or shown?

Thanks in advance!

Body:
Lets say you have a setup like this, for example:

import pandas as pd
list = ['column 1', 'column 2' , 'column 3']

csv_file = pd.read_csv('csv_file_here')
for col in csv_file.columns:
    if col not in list:
        print(col) # The extra column


问:
ng build message "ERROR in Cannot read property 'toLowerCase' of undefined"
I am using an Azure DevOps YAML pipeline to build/deploy my Angular 9 application.  The YAML contains a Powershell script to build it as follows

```<code>- powershell: |
    $angularBuildConfiguration = "MyBuildConfig";

    write-host "ng-build start";
    ng build --prod --aot --configuration $angularBuildConfiguration;
    write-host "ng-build end";

  workingDirectory: '$(Build.SourcesDirectory)\...'
  displayName: 'Build app - Angular app'
</code>```

The above goes through the Angular build and at the end returns the message "ERROR in Cannot read property 'toLowerCase' of undefined".

I have verified that the workingDirectory and angularBuildConfiguration parameters have the values intended - I have also replaced them with hardcoded values and get the same result.  If I run the Powershell script above on the build server (where the YAML script actually runs on), in the folder intended the build fails with the same error message, however if I build with the same script on my local machine it builds successfully

I don't know whether it is a ng build issue, or whether there is something within my Angular 9 project that causes the error - there is no 'associated' file that is flagged that accompanies the error message

Does anyone have any ideas ?

答:
This was really random - the toLowerCase message wasn't referring to any javascript/typescript code - it must be an internal message.  The only way I could pinpoint where the issue was by process of elimination - i.e. taking out webpages a batch at a time until I got a clean prod compile - then worked back including one by one to get to the culprit.

There was a style that was causing the issue - we replaced the following

```<code>.gridlines-left {
  border: 1px solid #c0c0c0;
  border-right-width: 0;
  border-top-width: 0;
  border-bottom-width: 0;
}
</code>```

...with

```<code>.gridlines-left {
  border: 1px solid #c0c0c0;
  border-right-style: none;
  border-top-style: none;
  border-bottom-style: none;
}
</code>```

...and the compile ran successfully.  I still have no idea how/why as we had plenty of other styles very similar and used the same strategy of setting border-right/left/bottom/top-width: 0 - it may have had something to do with how we combined css classes - certain styles may conflict with others come compile time - who knows, but all works well now and haven't had the problem since

Body:
I am using an Azure DevOps YAML pipeline to build/deploy my Angular 9 application.  The YAML contains a Powershell script to build it as follows

- powershell: |
    $angularBuildConfiguration = "MyBuildConfig";

    write-host "ng-build start";
    ng build --prod --aot --configuration $angularBuildConfiguration;
    write-host "ng-build end";

  workingDirectory: '$(Build.SourcesDirectory)\...'
  displayName: 'Build app - Angular app'

The above goes through the Angular build and at the end returns the message "ERROR in Cannot read property 'toLowerCase' of undefined".

I have verified that the workingDirectory and angularBuildConfiguration parameters have the values intended - I have also replaced them with hardcoded values and get the same result.  If I run the Powershell script above on the build server (where the YAML script actually runs on), in the folder intended the build fails with the same error message, however if I build with the same script on my local machine it builds successfully

I don't know whether it is a ng build issue, or whether there is something within my Angular 9 project that causes the error - there is no 'associated' file that is flagged that accompanies the error message

Does anyone have any ideas ?

Body:
This was really random - the toLowerCase message wasn't referring to any javascript/typescript code - it must be an internal message.  The only way I could pinpoint where the issue was by process of elimination - i.e. taking out webpages a batch at a time until I got a clean prod compile - then worked back including one by one to get to the culprit.

There was a style that was causing the issue - we replaced the following

.gridlines-left {
  border: 1px solid #c0c0c0;
  border-right-width: 0;
  border-top-width: 0;
  border-bottom-width: 0;
}

...with

.gridlines-left {
  border: 1px solid #c0c0c0;
  border-right-style: none;
  border-top-style: none;
  border-bottom-style: none;
}

...and the compile ran successfully.  I still have no idea how/why as we had plenty of other styles very similar and used the same strategy of setting border-right/left/bottom/top-width: 0 - it may have had something to do with how we combined css classes - certain styles may conflict with others come compile time - who knows, but all works well now and haven't had the problem since


问:
How do I send a timed notification on React Native
I don't need a server or anything, but basically I want to do a scheduled notification locally.

I tried using react-native-push-notification but it says I need firebase?

I just want to schedule a notification when the app is opened for a certain time

答:
If you want to use only local notification with react-native-push-notification and avoid using firebase, refer to this part of readme:screenshot of readme

Don't worry about IOS, this library won't be used there


问:
Looping over Array of objects and returning random object value - JavaScript
I am trying to loop over an array of objects and display a random quote from the data, so far my code returns undefined. Any idea's why?

Code so far..

```<code>const quotesToUse = [{
    quote: "This was the biggest quote ever - Array Object",
    author: "Derek Bullshido",
  },
  {
    quote: "Hey hows it going - Array Object",
    author: "Paul Frank",
  },
  {
    quote: "Why can I say that - Array Object",
    author: "Derek Paul",
  },
]

function randomQuotes() {
    for (var i = 0; i < 1; i += 1 )  {
    const randomQuote = quotesToUse[i][Math.floor(Math.random() * quotesToUse[i].quote.length)];
    document.getElementById("container").appendChild(text).append(randomQuote);
}
</code>```

I am trying to display the quote (String) randomly.

答:
You can do this more readably with rando.js. Just don't forget to add the script tag to the head of your HTML document if you want to use this code.

const quotesToUse = [
  {quote: "This was the biggest quote ever - Array Object", author: "Derek Bullshido"},
  {quote: "Hey hows it going - Array Object", author: "Paul Frank"},
  {quote: "Why can I say that - Array Object", author: "Derek Paul"},
];

var randomValueFromArray = rando(quotesToUse).value;
console.log(randomValueFromArray.quote);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://randojs.com/1.0.0.js"></script></code>```

Body:
I am trying to loop over an array of objects and display a random quote from the data, so far my code returns undefined. Any idea's why?

Code so far..

const quotesToUse = [{
    quote: "This was the biggest quote ever - Array Object",
    author: "Derek Bullshido",
  },
  {
    quote: "Hey hows it going - Array Object",
    author: "Paul Frank",
  },
  {
    quote: "Why can I say that - Array Object",
    author: "Derek Paul",
  },
]

function randomQuotes() {
    for (var i = 0; i < 1; i += 1 )  {
    const randomQuote = quotesToUse[i][Math.floor(Math.random() * quotesToUse[i].quote.length)];
    document.getElementById("container").appendChild(text).append(randomQuote);
}

I am trying to display the quote (String) randomly.

Body:
You can do this more readably with rando.js. Just don't forget to add the script tag to the head of your HTML document if you want to use this code.

const quotesToUse = [
  {quote: "This was the biggest quote ever - Array Object", author: "Derek Bullshido"},
  {quote: "Hey hows it going - Array Object", author: "Paul Frank"},
  {quote: "Why can I say that - Array Object", author: "Derek Paul"},
];

var randomValueFromArray = rando(quotesToUse).value;
console.log(randomValueFromArray.quote);

<script src="https://randojs.com/1.0.0.js"></script>


问:
How can I change the rootnode of any treestore at runtime?
How can I change the rootNode of my treestore at runtime?

Following is my current tree store:

```<code>Ext.define('rt.store.userinproject', {
    extend: 'Ext.data.TreeStore',
    folderSort: true,
    sorters: [{
        property: 'text',
        direction: 'ASC'
    }],
    root: {
        expanded: true,
        text: "",
        user: "",
        status: "",
        children: [{
            text: "Project 1",
            pid: 1,
            expanded: true,
            children: [{
                text: "Department 1",
                did: 1,
                cls: "folder",
                children: [{
                    text: "User 1",
                    uid: 1,
                    leaf: true
                }, {
                    text: "User 2",
                    uid: 2,
                    leaf: true
                }, {
                    text: "User 3",
                    uid: 3,
                    leaf: true
                }, {
                    text: "User 4",
                    uid: 4,
                    leaf: true
                }, {
                    text: "User 5",
                    uid: 5,
                    leaf: true
                }]
            }, {
                text: "Department 2",
                did: 2,
                cls: "folder",
                children: [{
                    text: "User 6",
                    uid: 6,
                    leaf: true
                }, {
                    text: "User 7",
                    uid: 7,
                    leaf: true
                }, {
                    text: "User 8",
                    uid: 8,
                    leaf: true
                }, {
                    text: "User 9",
                    uid: 9,
                    leaf: true
                }, {
                    text: "User 10",
                    uid: 10,
                    leaf: true
                }]
            }, {
                text: "Department 3",
                did: 3,
                cls: "folder",
                children: [{
                    text: "User 11",
                    uid: 11,
                    leaf: true
                }, {
                    text: "User 12",
                    uid: 12,
                    leaf: true
                }, {
                    text: "User 13",
                    uid: 13,
                    leaf: true
                }, {
                    text: "User 14",
                    uid: 14,
                    leaf: true
                }, {
                    text: "User 15",
                    uid: 15,
                    leaf: true
                }]
            }]
        }, {
            text: "Project 2",
            pid: 2,
            expanded: true,
            children: [{
                text: "Department 1",
                did: 1,
                cls: "folder",
                children: [{
                    text: "User 1",
                    uid: 1,
                    leaf: true
                }, {
                    text: "User 2",
                    uid: 2,
                    leaf: true
                }, {
                    text: "User 3",
                    uid: 3,
                    leaf: true
                }, {
                    text: "User 4",
                    uid: 4,
                    leaf: true
                }, {
                    text: "User 5",
                    uid: 5,
                    leaf: true
                }]
            }, {
                text: "Department 2",
                did: 2,
                cls: "folder",
                children: [{
                    text: "User 16",
                    uid: 16,
                    leaf: true
                }, {
                    text: "User 17",
                    uid: 17,
                    leaf: true
                }, {
                    text: "User 18",
                    uid: 18,
                    leaf: true
                }, {
                    text: "User 19",
                    uid: 19,
                    leaf: true
                }, {
                    text: "User 20",
                    uid: 20,
                    leaf: true
                }]
            }, {
                text: "Department 3",
                did: 3,
                cls: "folder",
                children: [{
                    text: "User 21",
                    uid: 21,
                    leaf: true
                }, {
                    text: "User 22",
                    uid: 22,
                    leaf: true
                }, {
                    text: "User 23",
                    uid: 23,
                    leaf: true
                }, {
                    text: "User 24",
                    uid: 24,
                    leaf: true
                }, {
                    text: "User 25",
                    uid: 25,
                    leaf: true
                }]
            }]
        }]
    }
});
</code>```

Currently I am able to show whole tree from root Node in my treepanel.

Now in store above I want to make "Project 1" as my root node when user click on project 1
and "project 2" as my root node when user click on project 2.

Is this possible? If so, how? Let me know if you need anything from me.

答:
1. If you are trying to modify some part of the existing root first you need to get hold of the root node. You can get hold of your root node using getRootNode() available with your TreeStore. example:

```<code> var node = treeObject.getStore().getRootNode();
</code>```

Now, to modify the data, you can make use of data property. For example, if you need to change the root node's text, you can:

```<code>node.data.text = 'New Root';   // You can access any other property of your node's data model the same way
</code>```

2. If you need to replace the entire node you can make use of the setRootNode() which is also available with your TreeStore. You will have to pass the appropriate data model used for your TreeStore.

Since, you are trying to replace your root, you definitly need to use setRootNode(). Here is an example code replacing the root:

```<code>//your tree click handler...
itemclick : function(view,rec,it,inx,ev) {

    var root = view.getTreeStore().getRootNode();
    var newRoot = root.getChildAt(inx).copy('xx',true);
    view.getTreeStore().setRootNode(newRoot);
}
</code>```

Ideally, this code should work. but there is a small bug in copy() that causes to break this code. A temporary solution (I would not recommend modifying library files) is available at the forum (refer the above link).

Another way would be to code your own copy code like:

```<code>var root = view.getTreeStore().getRootNode();
var newRoot = root.getChildAt(inx);
view.getTreeStore().setRootNode(newRoot);
// for each child in newRoot, create child for the newly assigned root.
</code>```

Body:
How can I change the rootNode of my treestore at runtime?

Following is my current tree store:

Ext.define('rt.store.userinproject', {
    extend: 'Ext.data.TreeStore',
    folderSort: true,
    sorters: [{
        property: 'text',
        direction: 'ASC'
    }],
    root: {
        expanded: true,
        text: "",
        user: "",
        status: "",
        children: [{
            text: "Project 1",
            pid: 1,
            expanded: true,
            children: [{
                text: "Department 1",
                did: 1,
                cls: "folder",
                children: [{
                    text: "User 1",
                    uid: 1,
                    leaf: true
                }, {
                    text: "User 2",
                    uid: 2,
                    leaf: true
                }, {
                    text: "User 3",
                    uid: 3,
                    leaf: true
                }, {
                    text: "User 4",
                    uid: 4,
                    leaf: true
                }, {
                    text: "User 5",
                    uid: 5,
                    leaf: true
                }]
            }, {
                text: "Department 2",
                did: 2,
                cls: "folder",
                children: [{
                    text: "User 6",
                    uid: 6,
                    leaf: true
                }, {
                    text: "User 7",
                    uid: 7,
                    leaf: true
                }, {
                    text: "User 8",
                    uid: 8,
                    leaf: true
                }, {
                    text: "User 9",
                    uid: 9,
                    leaf: true
                }, {
                    text: "User 10",
                    uid: 10,
                    leaf: true
                }]
            }, {
                text: "Department 3",
                did: 3,
                cls: "folder",
                children: [{
                    text: "User 11",
                    uid: 11,
                    leaf: true
                }, {
                    text: "User 12",
                    uid: 12,
                    leaf: true
                }, {
                    text: "User 13",
                    uid: 13,
                    leaf: true
                }, {
                    text: "User 14",
                    uid: 14,
                    leaf: true
                }, {
                    text: "User 15",
                    uid: 15,
                    leaf: true
                }]
            }]
        }, {
            text: "Project 2",
            pid: 2,
            expanded: true,
            children: [{
                text: "Department 1",
                did: 1,
                cls: "folder",
                children: [{
                    text: "User 1",
                    uid: 1,
                    leaf: true
                }, {
                    text: "User 2",
                    uid: 2,
                    leaf: true
                }, {
                    text: "User 3",
                    uid: 3,
                    leaf: true
                }, {
                    text: "User 4",
                    uid: 4,
                    leaf: true
                }, {
                    text: "User 5",
                    uid: 5,
                    leaf: true
                }]
            }, {
                text: "Department 2",
                did: 2,
                cls: "folder",
                children: [{
                    text: "User 16",
                    uid: 16,
                    leaf: true
                }, {
                    text: "User 17",
                    uid: 17,
                    leaf: true
                }, {
                    text: "User 18",
                    uid: 18,
                    leaf: true
                }, {
                    text: "User 19",
                    uid: 19,
                    leaf: true
                }, {
                    text: "User 20",
                    uid: 20,
                    leaf: true
                }]
            }, {
                text: "Department 3",
                did: 3,
                cls: "folder",
                children: [{
                    text: "User 21",
                    uid: 21,
                    leaf: true
                }, {
                    text: "User 22",
                    uid: 22,
                    leaf: true
                }, {
                    text: "User 23",
                    uid: 23,
                    leaf: true
                }, {
                    text: "User 24",
                    uid: 24,
                    leaf: true
                }, {
                    text: "User 25",
                    uid: 25,
                    leaf: true
                }]
            }]
        }]
    }
});

Currently I am able to show whole tree from root Node in my treepanel.

Now in store above I want to make "Project 1" as my root node when user click on project 1
and "project 2" as my root node when user click on project 2.

Is this possible? If so, how? Let me know if you need anything from me.

Body:
1. If you are trying to modify some part of the existing root first you need to get hold of the root node. You can get hold of your root node using getRootNode() available with your TreeStore. example:

 var node = treeObject.getStore().getRootNode();

Now, to modify the data, you can make use of data property. For example, if you need to change the root node's text, you can:

node.data.text = 'New Root';   // You can access any other property of your node's data model the same way

2. If you need to replace the entire node you can make use of the setRootNode() which is also available with your TreeStore. You will have to pass the appropriate data model used for your TreeStore.

Since, you are trying to replace your root, you definitly need to use setRootNode(). Here is an example code replacing the root:

//your tree click handler...
itemclick : function(view,rec,it,inx,ev) {

    var root = view.getTreeStore().getRootNode();
    var newRoot = root.getChildAt(inx).copy('xx',true);
    view.getTreeStore().setRootNode(newRoot);
}

Ideally, this code should work. but there is a small bug in copy() that causes to break this code. A temporary solution (I would not recommend modifying library files) is available at the forum (refer the above link).

Another way would be to code your own copy code like:

var root = view.getTreeStore().getRootNode();
var newRoot = root.getChildAt(inx);
view.getTreeStore().setRootNode(newRoot);
// for each child in newRoot, create child for the newly assigned root.


问:
Error while starting apache2 server in ubuntu
systemctl start apache2.service

Getting this error:-

Job for apache2.service failed because the control process exited with error code.
See "systemctl status apache2.service" and "journalctl -xe" for details.

Logs of systemctl status apache2.service

```<code>● apache2.service - The Apache HTTP Server
   Loaded: loaded (/lib/systemd/system/apache2.service; disabled; vendor preset: enabled)
  Drop-In: /lib/systemd/system/apache2.service.d
           └─apache2-systemd.conf
   Active: failed (Result: exit-code) since Tue 2020-06-02 08:24:55 IST; 49s ago
  Process: 9759 ExecStart=/usr/sbin/apachectl start (code=exited, status=127)

Jun 02 08:24:55 GS-4996 systemd[1]: Starting The Apache HTTP Server...
Jun 02 08:24:55 GS-4996 apachectl[9759]: /usr/sbin/apachectl: 174: /usr/sbin/apachectl: /usr/sbin/apache2: not found
Jun 02 08:24:55 GS-4996 apachectl[9759]: Action 'start' failed.
Jun 02 08:24:55 GS-4996 apachectl[9759]: The Apache error log may have more information.
Jun 02 08:24:55 GS-4996 systemd[1]: apache2.service: Control process exited, code=exited status=127
Jun 02 08:24:55 GS-4996 systemd[1]: apache2.service: Failed with result 'exit-code'.
Jun 02 08:24:55 GS-4996 systemd[1]: Failed to start The Apache HTTP Server.
</code>```

答:
Looks like the apache2 file is not available on server.
/usr/sbin/apache2 is provided by apache2-bin. apache2-bin is a dependency of the apache2 package, so apache2 will not work properly without it. Open the terminal and type:</p>

```<code>sudo apt install --reinstall apache2-bin
sudo service apache2 start
</code>```

Body:
systemctl start apache2.service

Getting this error:-

Job for apache2.service failed because the control process exited with error code.
See "systemctl status apache2.service" and "journalctl -xe" for details.

Logs of systemctl status apache2.service

● apache2.service - The Apache HTTP Server
   Loaded: loaded (/lib/systemd/system/apache2.service; disabled; vendor preset: enabled)
  Drop-In: /lib/systemd/system/apache2.service.d
           └─apache2-systemd.conf
   Active: failed (Result: exit-code) since Tue 2020-06-02 08:24:55 IST; 49s ago
  Process: 9759 ExecStart=/usr/sbin/apachectl start (code=exited, status=127)

Jun 02 08:24:55 GS-4996 systemd[1]: Starting The Apache HTTP Server...
Jun 02 08:24:55 GS-4996 apachectl[9759]: /usr/sbin/apachectl: 174: /usr/sbin/apachectl: /usr/sbin/apache2: not found
Jun 02 08:24:55 GS-4996 apachectl[9759]: Action 'start' failed.
Jun 02 08:24:55 GS-4996 apachectl[9759]: The Apache error log may have more information.
Jun 02 08:24:55 GS-4996 systemd[1]: apache2.service: Control process exited, code=exited status=127
Jun 02 08:24:55 GS-4996 systemd[1]: apache2.service: Failed with result 'exit-code'.
Jun 02 08:24:55 GS-4996 systemd[1]: Failed to start The Apache HTTP Server.

Body:
Looks like the apache2 file is not available on server.
/usr/sbin/apache2 is provided by apache2-bin. apache2-bin is a dependency of the apache2 package, so apache2 will not work properly without it. Open the terminal and type:

sudo apt install --reinstall apache2-bin
sudo service apache2 start


问:
JavaScript: get and set URL hash parameters?
How do you get and set URL hash parameters in pure JavaScript?

For example, I'd like to use parameters like this: myurl.com/#from=2012-01-05&to=2013-01-01

And I'd like to be able to get and set the from and to parameters in the above.

I'm happy to use the HTML5 history API if that's the best way of doing things.

答:
As for getting parameters... how about this solution:

```<code>var myUrl = new URL(window.location.href.replace(/#/g,"?"));
var param_value = myUrl.searchParams.get("param_name");
</code>```

Wish u luck!

Body:
As for getting parameters... how about this solution:

var myUrl = new URL(window.location.href.replace(/#/g,"?"));
var param_value = myUrl.searchParams.get("param_name");

Wish u luck!


问:
Is there a better solution to R CMD javareconf -e?
I am currently working on a project that aims to offer an application either for vanilla using - by running just the implemented features and algorithms - and also easy to extend in order to help another researchers with a "just plug your extra code here" architecture.

I'm using Electron Python-backended that in turn also communicates with R using the rpy2 library.
The problem is that one of the R libraries my Python code needs to load, uses rJava, and the only way I found to make the syntax rpackages.importr('rJava') work, was, before running the Python script, export some R/Java variables (I think it does that) with the command R CMD javareconf -e, then it works fine on Ubuntu.

I briefly tested this solution also on Windows and it didn't work. So I want to know how can I solve it, if there is another way.

In the Linux scenario, do you think running the npm start (for the whole Electron app) preceded by the R CMD command would work? Isn't there a better solution for this?

I also was thinking about using a Docker container, but I fear this would make it harder for another researchers plug their code into the App (if an external library was needed, for example).

The error without using R CMD javareconf -e is this:

```<code>...............
  File "/usr/local/lib/python3.7/dist-packages/rpy2/robjects/packages.py", line 483, in importr
    env = _get_namespace(name)
  File "/usr/local/lib/python3.7/dist-packages/rpy2/rinterface_lib/conversion.py", line 40, in _
    cdata = function(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/rpy2/rinterface.py", line 791, in __call__
    raise embedded.RRuntimeError(_rinterface._geterrmessage())
rpy2.rinterface_lib.embedded.RRuntimeError: Error: .onLoad failed in loadNamespace() for 'rJava', details:
  call: dyn.load(file, DLLpath = DLLpath, ...)
  error: unable to load shared object '/home/thispc/R/x86_64-pc-linux-gnu-library/3.6/rJava/libs/rJava.so':
  libjvm.so: cannot open shared object file: No such file or directory
</code>```

I already tried ~$sudo R CMD javareconf

答:
R seems to be installed in an unconventional location. May the linker cannot find it. Does setting the environment variables as suggested in the output of the following command help ? </p>

```<code>python -m rpy2.situation LD_LIBRARY_PATH
</code>```

Body:
I am currently working on a project that aims to offer an application either for vanilla using - by running just the implemented features and algorithms - and also easy to extend in order to help another researchers with a "just plug your extra code here" architecture.

I'm using Electron Python-backended that in turn also communicates with R using the rpy2 library.
The problem is that one of the R libraries my Python code needs to load, uses rJava, and the only way I found to make the syntax rpackages.importr('rJava') work, was, before running the Python script, export some R/Java variables (I think it does that) with the command R CMD javareconf -e, then it works fine on Ubuntu.

I briefly tested this solution also on Windows and it didn't work. So I want to know how can I solve it, if there is another way.

In the Linux scenario, do you think running the npm start (for the whole Electron app) preceded by the R CMD command would work? Isn't there a better solution for this?

I also was thinking about using a Docker container, but I fear this would make it harder for another researchers plug their code into the App (if an external library was needed, for example).

The error without using R CMD javareconf -e is this:

...............
  File "/usr/local/lib/python3.7/dist-packages/rpy2/robjects/packages.py", line 483, in importr
    env = _get_namespace(name)
  File "/usr/local/lib/python3.7/dist-packages/rpy2/rinterface_lib/conversion.py", line 40, in _
    cdata = function(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/rpy2/rinterface.py", line 791, in __call__
    raise embedded.RRuntimeError(_rinterface._geterrmessage())
rpy2.rinterface_lib.embedded.RRuntimeError: Error: .onLoad failed in loadNamespace() for 'rJava', details:
  call: dyn.load(file, DLLpath = DLLpath, ...)
  error: unable to load shared object '/home/thispc/R/x86_64-pc-linux-gnu-library/3.6/rJava/libs/rJava.so':
  libjvm.so: cannot open shared object file: No such file or directory

I already tried ~$sudo R CMD javareconf

Body:
R seems to be installed in an unconventional location. May the linker cannot find it. Does setting the environment variables as suggested in the output of the following command help ?

python -m rpy2.situation LD_LIBRARY_PATH


问:
How to automate this process?
It involves rewriting .htm to .txt (output file)

then using a parser (stanford grammar parser) (output file)

for all the files in a directory.

MY QUESTION: I would like to get all the files in the directory, without doing it manually, and find a way to run the parser, without having to type it into the Terminal for each file.

Here is my code:

```<code>#!/usr/bin/perl
use strict;
use warnings;
use HTML::FormatText;
use HTML::TreeBuilder;

my $tree = HTML::TreeBuilder->new->parse_file("chpt15Intro.htm");

use HTML::FormatText;

my $formatter = HTML::FormatText->new(leftmargin => 0, rightmargin => 1000);
   #print $formatter->format($tree); is replaced by push
push (my @files, $formatter->format($tree));
foreach my $files (@files) {
    $files =~ s/^\s+//mg;
    open MYFILE, ">ch15Intro.txt";
    select MYFILE;
    print $files;
}
</code>```

In the Terminal, after getting the html file converted, I write:

```<code>script parsedch15Intro.txt ./lexparser.csh ch15Intro.txt
</code>```

to save the output of the parser. This step still needs automation.

I'm a beginner so thanks for any advice.

答:
Not a perl solution, but you can do it as a one-liner with this shell pipeline,

assuming

you have the text-only browser lynx installed (is it available on the mac?)

and there is a sh Shell on your system:

ls -1 mydir/*.html | xargs -i sh -c "lynx -dump '{}' > '{}.txt'"

this creates a bunch of *.html.txt files in the same directory. And the text might be not formatted according to your requirements

Title: How to automate this process?

Body:
It involves rewriting .htm to .txt (output file)

then using a parser (stanford grammar parser) (output file)

for all the files in a directory.

MY QUESTION: I would like to get all the files in the directory, without doing it manually, and find a way to run the parser, without having to type it into the Terminal for each file.

Here is my code:

#!/usr/bin/perl
use strict;
use warnings;
use HTML::FormatText;
use HTML::TreeBuilder;

my $tree = HTML::TreeBuilder->new->parse_file("chpt15Intro.htm");

use HTML::FormatText;

my $formatter = HTML::FormatText->new(leftmargin => 0, rightmargin => 1000);
   #print $formatter->format($tree); is replaced by push
push (my @files, $formatter->format($tree));
foreach my $files (@files) {
    $files =~ s/^\s+//mg;
    open MYFILE, ">ch15Intro.txt";
    select MYFILE;
    print $files;
}

In the Terminal, after getting the html file converted, I write:

script parsedch15Intro.txt ./lexparser.csh ch15Intro.txt

to save the output of the parser. This step still needs automation.

I'm a beginner so thanks for any advice.


问:
Scraping similarly named tables using rvest
I'm trying to scrape tables of data from different pages on fbref.com using rvest. I've been able to scrape the data from one page using:

```<code>library(rvest)
URL <- "https://fbref.com/en/squads/822bd0ba/Liverpool"
WS <- read_html(URL)
passStats <- WS %>% rvest::html_nodes(xpath = '//*[(@id = "ks_sched_all")]') %>% rvest::html_table() %>% data.frame()
</code>```

but when I try to apply it to multiple pages using a for loop I have a problem as not all of the pages use the same id for the table. Some are "ks_sched_all" but others are "ks_sched_(4-digit number)". Is there any way to just extract any table on the page with an id starting with: "ks_sched_"?

答:
You can add table to your XPath expression and (). Code could be :

```<code>library(rvest)
URL <- "https://fbref.com/en/squads/822bd0ba/Liverpool"
WS <- read_html(URL)

results=list()
i=1

for (tables in 1:length(html_nodes(x = WS,xpath = "//table[starts-with(@id,'ks_sched_')]"))) {
path=paste0('(//table[starts-with(@id,"ks_sched_")])[',i,']')
results[[i]] <- WS %>% html_nodes(xpath = path) %>% html_table() %>% data.frame()
i=i+1
}
</code>```

We use a for loop, get the number of tables with length, generate a new XPath each time with paste0 and store the results in a list.

Output : list of 7 dataframes

Body:
I'm trying to scrape tables of data from different pages on fbref.com using rvest. I've been able to scrape the data from one page using:

library(rvest)
URL <- "https://fbref.com/en/squads/822bd0ba/Liverpool"
WS <- read_html(URL)
passStats <- WS %>% rvest::html_nodes(xpath = '//*[(@id = "ks_sched_all")]') %>% rvest::html_table() %>% data.frame()

but when I try to apply it to multiple pages using a for loop I have a problem as not all of the pages use the same id for the table. Some are "ks_sched_all" but others are "ks_sched_(4-digit number)". Is there any way to just extract any table on the page with an id starting with: "ks_sched_"?

Body:
You can add table to your XPath expression and (). Code could be :

library(rvest)
URL <- "https://fbref.com/en/squads/822bd0ba/Liverpool"
WS <- read_html(URL)

results=list()
i=1

for (tables in 1:length(html_nodes(x = WS,xpath = "//table[starts-with(@id,'ks_sched_')]"))) {
path=paste0('(//table[starts-with(@id,"ks_sched_")])[',i,']')
results[[i]] <- WS %>% html_nodes(xpath = path) %>% html_table() %>% data.frame()
i=i+1
}

We use a for loop, get the number of tables with length, generate a new XPath each time with paste0 and store the results in a list.

Output : list of 7 dataframes


问:
Replace multiple strings and numbers from multiple columns with NaN in Pandas
If I have a following dataframe, I would like to clean data by replacing multiple strings and numbers into NaNs: ie. 68, Tardeo Road and 0 from state, 567 from dept, and #ERROR! and 123 from phonenumber:

```<code>   id                                state                          dept  \
0   1                            Abu Dhabi                   {Marketing}
1   2                                   MO                       {Other}
2   3                      68, Tardeo Road           {"Human Resources"}
3   4  National Capital Territory of Delhi           {"Human Resources"}
4   5                        Aargau Canton                   {Marketing}
5   6                        Aargau Canton                           567
6  18                                   NB  {"Finance & Administration"}
7  19                                    0                       {Sales}
8  20                            Abu Dhabi           {"Human Resources"}
9  21                               Aargau  {"Finance & Administration"}

   phonenumber
0          123
1   5635888000
2  18006708450
3      #ERROR!
4  12032722596
5  18003928343
6          NaN
7      #ERROR!
8          NaN
9          NaN
</code>```

I have tried the following code:

Solution 1:

```<code>mask = (df.state == '0') | (df.state == '68, Tardeo Road')
df.loc[mask, ['state']] = np.nan
</code>```

Solution 2:

```<code>df.loc[(df.state == '68, Tardeo Road') | (df.state == 0), 'state'] = np.nan
</code>```

Solution 3:

```<code>df.loc[df.state == '0', 'state'] = np.nan
df.loc[df.state == '68, Tardeo Road', 'state'] = np.nan
</code>```

All of them works, but if I apply them to multiple columns, it's a little bit long.

Just wondering if it's possible to make it more concise and efficient? By using str.replace for example. Thanks.

答:
You can do a replace:

```<code>df = df.replace({'state':['68, Tardeo Road','0'],
                 'dept':['567'],
                 'phonenumber':['#ERROR!','123']}, np.nan)
</code>```

Output:

```<code>      id                                state                          dept    phonenumber
--  ----  -----------------------------------  ----------------------------  -------------
0   1     Abu Dhabi                            {Marketing}                             nan
1   2     MO                                   {Other}                          5635888000
2   3     nan                                  {"Human Resources"}             18006708450
3   4     National Capital Territory of Delhi  {"Human Resources"}                     nan
4   5     Aargau Canton                        {Marketing}                     12032722596
5   6     Aargau Canton                        nan                             18003928343
6   18    NB                                   {"Finance & Administration"}            nan
7   19    nan                                  {Sales}                                 nan
8   20    Abu Dhabi                            {"Human Resources"}                     nan
9   21    Aargau                               {"Finance & Administration"}            nan
</code>```

Body:
If I have a following dataframe, I would like to clean data by replacing multiple strings and numbers into NaNs: ie. 68, Tardeo Road and 0 from state, 567 from dept, and #ERROR! and 123 from phonenumber:

   id                                state                          dept  \
0   1                            Abu Dhabi                   {Marketing}
1   2                                   MO                       {Other}
2   3                      68, Tardeo Road           {"Human Resources"}
3   4  National Capital Territory of Delhi           {"Human Resources"}
4   5                        Aargau Canton                   {Marketing}
5   6                        Aargau Canton                           567
6  18                                   NB  {"Finance & Administration"}
7  19                                    0                       {Sales}
8  20                            Abu Dhabi           {"Human Resources"}
9  21                               Aargau  {"Finance & Administration"}

   phonenumber
0          123
1   5635888000
2  18006708450
3      #ERROR!
4  12032722596
5  18003928343
6          NaN
7      #ERROR!
8          NaN
9          NaN

I have tried the following code:

Solution 1:

mask = (df.state == '0') | (df.state == '68, Tardeo Road')
df.loc[mask, ['state']] = np.nan

Solution 2:

df.loc[(df.state == '68, Tardeo Road') | (df.state == 0), 'state'] = np.nan

Solution 3:

df.loc[df.state == '0', 'state'] = np.nan
df.loc[df.state == '68, Tardeo Road', 'state'] = np.nan

All of them works, but if I apply them to multiple columns, it's a little bit long.

Just wondering if it's possible to make it more concise and efficient? By using str.replace for example. Thanks.

Body:
You can do a replace:

df = df.replace({'state':['68, Tardeo Road','0'],
                 'dept':['567'],
                 'phonenumber':['#ERROR!','123']}, np.nan)

Output:

      id                                state                          dept    phonenumber
--  ----  -----------------------------------  ----------------------------  -------------
0   1     Abu Dhabi                            {Marketing}                             nan
1   2     MO                                   {Other}                          5635888000
2   3     nan                                  {"Human Resources"}             18006708450
3   4     National Capital Territory of Delhi  {"Human Resources"}                     nan
4   5     Aargau Canton                        {Marketing}                     12032722596
5   6     Aargau Canton                        nan                             18003928343
6   18    NB                                   {"Finance & Administration"}            nan
7   19    nan                                  {Sales}                                 nan
8   20    Abu Dhabi                            {"Human Resources"}                     nan
9   21    Aargau                               {"Finance & Administration"}            nan


问:
How to split arrays based on space in NodeJS?
My array looks like:

```<code>[P1 Apple, P2 Mango, P2.1 Pluto, P3.1.1 Earth... P10 Red, P10.1 Blue, P10.1.1 Copper]
</code>```

I want to split these based on the space between the elements. For example,

```<code>In "P1 Apple" - "P1" will be the key, "Apple" will be the value
</code>```

I have to build a tree structure based on the key value. If the key has a whole number (P1, P2, P3, ... P10) then it has to be the child of a root node. I have the root node show up in the visualization already. How can I get this done?

My current code looks like this:

```<code>filteredSources.forEach(src => {
        console.log("src is " + src)
        let key = src.substring(0, src.indexOf(' '));
        let keyPair = key.split(',');
        console.log("keyPair is " + keyPair + "length is " + keyPair.length)
        for (let i = keyPair.length - 1; i >= 0; i--) {
            if (i == 0) {
                filteredSources.push({ name: src, key: key, parent: 'Target' });
                console.log("filteredSources is " + filteredSources)
            } else {
                let parentKey = [];
                Object.assign(parentKey, keyPair);
                console.log("parentKey on Object.assign is " + parentKey)
                parentKey.splice(i, 1);
                console.log("parentKey after splice("+i + ",1) is " + parentKey)
                filteredSources.push({ name: src, key: key, parent: parentKey.join('.') });
                console.log("filteredSources is " + filteredSources)
            }
        }
    });
</code>```

答:
Note: your original sample data had missing nodes in the tree hierarchy, which I've filled in manually.

Additional Note: d3 has functions for parsing CSV data directly that is already in a hierarchical form.

I've transformed the data into the form {id, parentId, name} where P3.1.1 will emit {id: "P3.1.1", parentId: "P3.1", name: "Earth"}.  This can be fed to d3.stratify that will build the hierarchy for you (since d3-tree rendering is your ultimate goal).  I also added a {id: "P", name: "Target"} for the root node.

d3-stratify:

https://github.com/d3/d3-hierarchy/blob/master/README.md#stratify

demo

Trim off [ ] and split on ,, then use RegEx to capture node's path id, node's parent's path's id (which is just the path excluding the last .[n], and the name.

https://regex101.com/r/TvLfQ3/1 to see the regex in action

Finally use .map to transform to {id, parentId, name} shape.

You could use a recursive function to build a tree, but since you're using d3 you can just let d3-stratify do the work for you.

data = `[P1 Apple, P2 Mango, P2.1 Pluto, P3.1.1 Earth, P10 Red, P10.1 Blue, P10.1.1 Copper, P3 PewPewPew, P3.1 Chopper, P3.2 Twenty, P3.1.2 Two]`
.slice(1,-1).split(', ')
.map(x=>x.match(/^((.*?)(?:\.)?(?:\d*)?) (.*)$/).slice(1))
.map(([id, parentId, name])=>({id, parentId, name}))

data.push({id: 'P', name:'Target'})

console.log(data)```

Body:
My array looks like:

[P1 Apple, P2 Mango, P2.1 Pluto, P3.1.1 Earth... P10 Red, P10.1 Blue, P10.1.1 Copper]

I want to split these based on the space between the elements. For example,

In "P1 Apple" - "P1" will be the key, "Apple" will be the value

I have to build a tree structure based on the key value. If the key has a whole number (P1, P2, P3, ... P10) then it has to be the child of a root node. I have the root node show up in the visualization already. How can I get this done?

My current code looks like this:

filteredSources.forEach(src => {
        console.log("src is " + src)
        let key = src.substring(0, src.indexOf(' '));
        let keyPair = key.split(',');
        console.log("keyPair is " + keyPair + "length is " + keyPair.length)
        for (let i = keyPair.length - 1; i >= 0; i--) {
            if (i == 0) {
                filteredSources.push({ name: src, key: key, parent: 'Target' });
                console.log("filteredSources is " + filteredSources)
            } else {
                let parentKey = [];
                Object.assign(parentKey, keyPair);
                console.log("parentKey on Object.assign is " + parentKey)
                parentKey.splice(i, 1);
                console.log("parentKey after splice("+i + ",1) is " + parentKey)
                filteredSources.push({ name: src, key: key, parent: parentKey.join('.') });
                console.log("filteredSources is " + filteredSources)
            }
        }
    });


问:
How to detect Facebook Like button pressed and trigger event?
Here is the example:

http://www.facebook.com/UEvents?v=app_4949752878&ref=ts

These guys get people to click on Like button (in Step 1) first before letting the user download the video in Step 2.

Interestingly, the Like button was detected and the page refreshed to show the blurred out image in Step 2 so user can click through to download.

And it seems to remember that I click on Like (when I reload the page) so the Like button does not show any more and it just only shows Step 2.

What is their trick of the trade?

答:
Actually information if user is page fan or not exists in signed request. Since you need firstly to decode signed request like it is here:

```<code> $signed_request = $_REQUEST["signed_request"];
 list($encoded_sig, $payload) = explode('.', $signed_request, 2);
 $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
</code>```

And after that access page liked variable:

```<code>$pageLiked = $data['page']['liked'];
</code>```

Now FB is on the way of deprecating FBML so don't consider <fb:visible-to-connection> as something that will work for a long base.

ContentLicense: CC BY-SA 2.5

Body:
Actually information if user is page fan or not exists in signed request. Since you need firstly to decode signed request like it is here:

 $signed_request = $_REQUEST["signed_request"];
 list($encoded_sig, $payload) = explode('.', $signed_request, 2);
 $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);

And after that access page liked variable:

$pageLiked = $data['page']['liked'];

Now FB is on the way of deprecating FBML so don't consider <fb:visible-to-connection> as something that will work for a long base.


问:
NET Core web.api sudden memory peak after dozen of calls
I have a web.api in .net core 3.1 that continually receives byte array data. I have noticed that after a dozen of calls, the memory suddenly increases with +100Mb.

As you can see in the GIF, the memory increases steadily as the calls are being handled. And then at 155Mb, the memory increases to 296Mb

I have created a repo: https://github.com/puppetSpace/MemoryIssue
This contains a client project, that calls the API continually.
And the web.api project, that gets the byte array from the body and waits 500ms (simulate work).
I just want to know a couple of things:
- Is someone else also getting this result?
- Is this normal behavior? like it's reserving memory? Or it's just because of debbuging?

I tried to use a profiler, but I can't figure out what causes the sudden increase.

答:
This should be related to your MemoryStream. After executing the MemoryStream, you need to release it, otherwise it will always occupy memory.

And because the await you are currently using is an asynchronous operation, you do not need to use await Task.Delay(500); to delay.

Modify your api code as follows：

```<code>  public async Task<IActionResult> Post()
    {
        var ms = new MemoryStream();
        await Request.Body.CopyToAsync(ms).ContinueWith(x => ms.Dispose());
        return NoContent();
    }
</code>```

Body:
This should be related to your MemoryStream. After executing the MemoryStream, you need to release it, otherwise it will always occupy memory.

And because the await you are currently using is an asynchronous operation, you do not need to use await Task.Delay(500); to delay.

Modify your api code as follows：

  public async Task<IActionResult> Post()
    {
        var ms = new MemoryStream();
        await Request.Body.CopyToAsync(ms).ContinueWith(x => ms.Dispose());
        return NoContent();
    }


问:
How to get the first line of span in php?
I am looking for a way to get each line of a span tag in php.
I have attempted to use explode and strpos but I can't get these to work.

I have a line of markup that is formatted like this:

```<code><span>
LINE 1
<br/>
9.00am
<br/>
Description: this can be quite a long piece of text.
</span>
</code>```

I need to have seperate variables for each line that I can reference later, these need to have the full contents of that line, but only that line.

How can I extract each line into a seperate variable without knowing the length of the individual lines?

There are 3 lines in text that I am interested in so ideally the end result will be:

```<code>$line1 = "LINE 1"
$line2 = "9.00am"
$line3 = "Description: this can be quite a long piece of text"
</code>```

答:
You don't want to use explode or strpos on HTML. Use a parser so the elements are correctly read, then you can use a regex on the nodevalue and its rendered content to get each line:

```<code><?php
$html = '<span>
LINE 1
<br/>
9.00am
<br/>
Description: this can be quite a long piece of text.
</span>';
$dom = new domdocument();
$dom->loadhtml($html);
$spans = $dom->getelementsbytagname('span');
foreach($spans as $span){
    $lines = preg_split('/\v+/', $span->nodeValue, -1, PREG_SPLIT_NO_EMPTY);
    print_r($lines);
}
</code>```

Output:

```<code>Array
(
    [0] => LINE 1
    [1] => 9.00am
    [2] => Description: this can be quite a long piece of text.
)
</code>```

This answer presumes Description doesn't have new lines in it. If it does you will need to alter the pattern. Currently it splits on at least one vertical space (aka a new line).

Body:
I am looking for a way to get each line of a span tag in php.
I have attempted to use explode and strpos but I can't get these to work.

I have a line of markup that is formatted like this:

LINE 1

9.00am

Description: this can be quite a long piece of text.

I need to have seperate variables for each line that I can reference later, these need to have the full contents of that line, but only that line.

How can I extract each line into a seperate variable without knowing the length of the individual lines?

There are 3 lines in text that I am interested in so ideally the end result will be:

$line1 = "LINE 1"
$line2 = "9.00am"
$line3 = "Description: this can be quite a long piece of text"

Body:
You don't want to use explode or strpos on HTML. Use a parser so the elements are correctly read, then you can use a regex on the nodevalue and its rendered content to get each line:

<?php
$html = '<span>
LINE 1
<br/>
9.00am
<br/>
Description: this can be quite a long piece of text.
</span>';
$dom = new domdocument();
$dom->loadhtml($html);
$spans = $dom->getelementsbytagname('span');
foreach($spans as $span){
    $lines = preg_split('/\v+/', $span->nodeValue, -1, PREG_SPLIT_NO_EMPTY);
    print_r($lines);
}

Output:

Array
(
    [0] => LINE 1
    [1] => 9.00am
    [2] => Description: this can be quite a long piece of text.
)

This answer presumes Description doesn't have new lines in it. If it does you will need to alter the pattern. Currently it splits on at least one vertical space (aka a new line).


问:
Problem connecting to RDS from EC2 instance: Is the server running on host/accepting TCP/IP connections on port 5432?
I have personal AWS EC2 server and I'm using ssh into this server. I installed PostgreSQL on the EC2 instance, cerated a PostgreSQL RDS, and trying to connect to the RDS from EC2 CLI. I get following error:

Is the server running on host "db-xxxx.us-east-2.rds.amazonaws.com" and accepting
    TCP/IP connections on port 5432?

I have:
 - change RDS to publicly accessible
 - added listen_addresses = '*' to postgres.conf
 - added 0.0.0.0/0 md5 to pg_hba.conf

```<code>  # IPv4 local connections:
  host    all             all             0.0.0.0/0            md5
</code>```

ensured both EC2 and RDS have same security group

added security-group-for-inbound-nfs-xx to RDS

enabled IAM authorization on RDS

output of "service postgresql status" shows postgres is running and listening on the port 5432

Redirecting to /bin/systemctl status postgresql.service
● postgresql.service - PostgreSQL database server
   Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2020-06-03 04:28:54 UTC; 20min ago
  Process: 3065 ExecStartPre=/usr/libexec/postgresql-check-db-dir %N (code=exited, status=0/SUCCESS)
 Main PID: 3070 (postmaster)
   CGroup: /system.slice/postgresql.service
           ├─3070 /usr/bin/postmaster -D /var/lib/pgsql/data
           ├─3084 postgres: logger process

           ├─3089 postgres: checkpointer process

           ├─3090 postgres: writer process

           ├─3091 postgres: wal writer process

           ├─3092 postgres: autovacuum launcher process

           ├─3093 postgres: stats collector process

           └─3094 postgres: bgworker: logical replication launcher

I see postgres is running and listning on the port 5432.

postmaster[3070]: 2020-06-03 04:28:54.168 UTC [3070] LOG:  listening on IPv4 address "0.0.0.0", port 5432
Jun 03 04:28:54 ip-172-xx-xx-xx9.us-east-2.compute.internal postmaster[3070]: 2020-06-03 04:28:54.168 UTC [3070] LOG:  listening on IPv6 address "::", port 5432
Jun 03 04:28:54 ip-172-xx-xx-xx9.us-east-2.compute.internal postmaster[3070]: 2020-06-03 04:28:54.169 UTC [3070] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
Jun 03 04:28:54 ip-172-xx-xx-xx.us-east-2.compute.internal postmaster[3070]: 2020-06-03 04:28:54.171 UTC [3070] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432"
Jun 03 04:28:54 ip-xx-xx-xx.us-east-2.compute.internal postmaster[3070]: 2020-06-03 04:28:54.198 UTC [3070] LOG:  redirecting log output to logging collector process
Jun 03 04:28:54 ip-xx-xx-xx.us-east-2.compute.internal postmaster[3070]: 2020-06-03 04:28:54.198 UTC [3070] HINT:  Future log output will appear in directory "log".
Jun 03 04:28:54 ip-172-31-36-109.us-east-2.compute.internal systemd[1]: Started PostgreSQL database server.

I have verified everything provided here:

https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ConnectToPostgreSQLInstance.html

https://aws.amazon.com/premiumsupport/knowledge-center/rds-connectivity-instance-subnet-vpc/

What am I missing? Thanks for the help.

答:
Well, RDS will tell you the endpoint of your PSQL, and the default port would be 5432 right. But I suggest you do the double-check if the endpoint you connected is the same with the RDS dashboard.

https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ConnectToPostgreSQLInstance.html

Body:
I have personal AWS EC2 server and I'm using ssh into this server. I installed PostgreSQL on the EC2 instance, cerated a PostgreSQL RDS, and trying to connect to the RDS from EC2 CLI. I get following error:

Is the server running on host "db-xxxx.us-east-2.rds.amazonaws.com" and accepting
    TCP/IP connections on port 5432?

I have:
 - change RDS to publicly accessible
 - added listen_addresses = '*' to postgres.conf
 - added 0.0.0.0/0 md5 to pg_hba.conf

  # IPv4 local connections:
  host    all             all             0.0.0.0/0            md5

ensured both EC2 and RDS have same security group

added security-group-for-inbound-nfs-xx to RDS

enabled IAM authorization on RDS

output of "service postgresql status" shows postgres is running and listening on the port 5432

Redirecting to /bin/systemctl status postgresql.service
● postgresql.service - PostgreSQL database server
   Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2020-06-03 04:28:54 UTC; 20min ago
  Process: 3065 ExecStartPre=/usr/libexec/postgresql-check-db-dir %N (code=exited, status=0/SUCCESS)
 Main PID: 3070 (postmaster)
   CGroup: /system.slice/postgresql.service
           ├─3070 /usr/bin/postmaster -D /var/lib/pgsql/data
           ├─3084 postgres: logger process

           ├─3089 postgres: checkpointer process

           ├─3090 postgres: writer process

           ├─3091 postgres: wal writer process

           ├─3092 postgres: autovacuum launcher process

           ├─3093 postgres: stats collector process

           └─3094 postgres: bgworker: logical replication launcher

I see postgres is running and listning on the port 5432.

postmaster[3070]: 2020-06-03 04:28:54.168 UTC [3070] LOG:  listening on IPv4 address "0.0.0.0", port 5432
Jun 03 04:28:54 ip-172-xx-xx-xx9.us-east-2.compute.internal postmaster[3070]: 2020-06-03 04:28:54.168 UTC [3070] LOG:  listening on IPv6 address "::", port 5432
Jun 03 04:28:54 ip-172-xx-xx-xx9.us-east-2.compute.internal postmaster[3070]: 2020-06-03 04:28:54.169 UTC [3070] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
Jun 03 04:28:54 ip-172-xx-xx-xx.us-east-2.compute.internal postmaster[3070]: 2020-06-03 04:28:54.171 UTC [3070] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432"
Jun 03 04:28:54 ip-xx-xx-xx.us-east-2.compute.internal postmaster[3070]: 2020-06-03 04:28:54.198 UTC [3070] LOG:  redirecting log output to logging collector process
Jun 03 04:28:54 ip-xx-xx-xx.us-east-2.compute.internal postmaster[3070]: 2020-06-03 04:28:54.198 UTC [3070] HINT:  Future log output will appear in directory "log".
Jun 03 04:28:54 ip-172-31-36-109.us-east-2.compute.internal systemd[1]: Started PostgreSQL database server.

I have verified everything provided here:

https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ConnectToPostgreSQLInstance.html

https://aws.amazon.com/premiumsupport/knowledge-center/rds-connectivity-instance-subnet-vpc/

What am I missing? Thanks for the help.