问:
SQLAlchemy \ GeoAlchemy support of PostGIS geometry data types
In an ORM I would expect to be able to do this:

```<code>session.add(Lake("hello",Polygon([(0,0),(1,0),(1,1)])))
lake = session.get(Lake).first()
assert isinstance(lake.geometry, Polygon)
assert isinstance(lake.geometry.get_exterior_ring().get_points()[0], Point)
print(lake.geometry.get_exterior_ring().get_points()[0].x)
</code>```

Instead the only way I see to access the Points of my lake is through a rather complex monster of code:

```<code>ring = func.ST_ExteriorRing(func.ST_GeomFromWKB(Lake.geometry))
node_count = func.ST_NPoints(ring)
node_series = func.generate_series(1, node_count)
node_n = func.ST_PointN(ring, node_series)
node_n_x = func.ST_X(node_n)
node_n_y = func.ST_Y(node_n)
rows = session.query(Lake, node_n_x, node_n_y).all()
lake_coasts = {}
for row in rows:
    lake = row[0]
    if not lake in lake_coasts:
        lake_coasts[lake] = []
    lake_coast = lake_coasts[lake]
    lake_coast.append((row[1], row[2]))
for lake in lake_coasts:
    lake_coast = lake_coasts[lake]
    print("Lake #{0}: \"{1}\" has its coasts at {2}"
          .format(lake.id, lake.name, lake_coast))
</code>```

and while this loop gets me the coordinates I want, I'm lost figuring out how to implement some Lake.get_coast() that returns this instance's coast.

Also I gave up on implementing the same for ""Lake""s with MULTIPOLYGONs as the nesting to get down to the points was too much for postgis (at least that's how I read the Error message)

I'm new to postgis, gis, python and sqla but in two days of googling I could not find anything that looks like an ORM within SQL-Alchemy 2 but only some SQL-helper functions (postgis) to parse the WKB but only within the database. Do I need some additional framework? I saw gdal, ogr, fiona but I feel like looking in the wrong direction. Is there some open source project using SQL-Alchemy2 with a nice structure? Entities, DAOs, whatever? How do you actually use this monster beyond this minimalist example?

答:
You may use GeoAlchemy2 and Shapely:</p>
```<code>    from geoalchemy2 import Geography
    from geoalchemy2.shape import from_shape
    from shapely.geometry import Polygon, Point, shape
    from sqlalchemy import create_engine, Column, Integer, func
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import scoped_session
    from sqlalchemy.orm import sessionmaker

    Base = declarative_base()
    db_session = scoped_session(sessionmaker())
    db_session.configure(bind=create_engine(connection_string))

    """
    create table polygon (
        id serial not null primary key,
        polygon geography(POLYGON) not null
    );
    """

    class TablePolygon(Base):
        __tablename__ = 'polygon'

        id = Column(Integer, primary_key=True)
        polygon = Column(Geography('POLYGON'), nullable=False)

    db_session.add(
        TablePolygon(
            id=1,
            polygon=from_shape(
                Polygon([
                    [-74.0133476, 40.7013069], [-73.9776421, 40.7121134], [-74.012661, 40.7230482],
                    [-74.0133476, 40.7013069]
                ])
            )
        )
    )

    geojson = """{"coordinates": [[[-73.9597893,40.8024021],[-73.9846802,40.7668997],[-73.9726639,40.7623468],[-73.9460564,40.7969415],[-73.9597893,40.8024021]]],"type": "Polygon"}"""

    db_session.add(
        TablePolygon(
            id=2,
            polygon=from_shape(
                shape(json.loads(geojson))
            )
        )
    )

    def find_polygon_id(point: Point):
        return db_session.query(
            TablePolygon.id
        ).filter(
            func.ST_Intersects(TablePolygon.polygon, from_shape(point))
        ).scalar()

    print(find_polygon_id(Point(-73.9822769, 40.7564925)))  # prints "None"
    print(find_polygon_id(Point(-73.9625359, 40.7858887)))  # prints "2"
    print(find_polygon_id(Point(-74.0059662, 40.7138058)))  # prints "1"
</code>```

Body:
In an ORM I would expect to be able to do this:

session.add(Lake("hello",Polygon([(0,0),(1,0),(1,1)])))
lake = session.get(Lake).first()
assert isinstance(lake.geometry, Polygon)
assert isinstance(lake.geometry.get_exterior_ring().get_points()[0], Point)
print(lake.geometry.get_exterior_ring().get_points()[0].x)

Instead the only way I see to access the Points of my lake is through a rather complex monster of code:

ring = func.ST_ExteriorRing(func.ST_GeomFromWKB(Lake.geometry))
node_count = func.ST_NPoints(ring)
node_series = func.generate_series(1, node_count)
node_n = func.ST_PointN(ring, node_series)
node_n_x = func.ST_X(node_n)
node_n_y = func.ST_Y(node_n)
rows = session.query(Lake, node_n_x, node_n_y).all()
lake_coasts = {}
for row in rows:
    lake = row[0]
    if not lake in lake_coasts:
        lake_coasts[lake] = []
    lake_coast = lake_coasts[lake]
    lake_coast.append((row[1], row[2]))
for lake in lake_coasts:
    lake_coast = lake_coasts[lake]
    print("Lake #{0}: \"{1}\" has its coasts at {2}"
          .format(lake.id, lake.name, lake_coast))

and while this loop gets me the coordinates I want, I'm lost figuring out how to implement some Lake.get_coast() that returns this instance's coast.

Also I gave up on implementing the same for ""Lake""s with MULTIPOLYGONs as the nesting to get down to the points was too much for postgis (at least that's how I read the Error message)

I'm new to postgis, gis, python and sqla but in two days of googling I could not find anything that looks like an ORM within SQL-Alchemy 2 but only some SQL-helper functions (postgis) to parse the WKB but only within the database. Do I need some additional framework? I saw gdal, ogr, fiona but I feel like looking in the wrong direction. Is there some open source project using SQL-Alchemy2 with a nice structure? Entities, DAOs, whatever? How do you actually use this monster beyond this minimalist example?

Body:
You may use GeoAlchemy2 and Shapely:

    from geoalchemy2 import Geography
    from geoalchemy2.shape import from_shape
    from shapely.geometry import Polygon, Point, shape
    from sqlalchemy import create_engine, Column, Integer, func
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import scoped_session
    from sqlalchemy.orm import sessionmaker

    Base = declarative_base()
    db_session = scoped_session(sessionmaker())
    db_session.configure(bind=create_engine(connection_string))

    """
    create table polygon (
        id serial not null primary key,
        polygon geography(POLYGON) not null
    );
    """

    class TablePolygon(Base):
        __tablename__ = 'polygon'

        id = Column(Integer, primary_key=True)
        polygon = Column(Geography('POLYGON'), nullable=False)

    db_session.add(
        TablePolygon(
            id=1,
            polygon=from_shape(
                Polygon([
                    [-74.0133476, 40.7013069], [-73.9776421, 40.7121134], [-74.012661, 40.7230482],
                    [-74.0133476, 40.7013069]
                ])
            )
        )
    )

    geojson = """{"coordinates": [[[-73.9597893,40.8024021],[-73.9846802,40.7668997],[-73.9726639,40.7623468],[-73.9460564,40.7969415],[-73.9597893,40.8024021]]],"type": "Polygon"}"""

    db_session.add(
        TablePolygon(
            id=2,
            polygon=from_shape(
                shape(json.loads(geojson))
            )
        )
    )

    def find_polygon_id(point: Point):
        return db_session.query(
            TablePolygon.id
        ).filter(
            func.ST_Intersects(TablePolygon.polygon, from_shape(point))
        ).scalar()

    print(find_polygon_id(Point(-73.9822769, 40.7564925)))  # prints "None"
    print(find_polygon_id(Point(-73.9625359, 40.7858887)))  # prints "2"
    print(find_polygon_id(Point(-74.0059662, 40.7138058)))  # prints "1"


来源: stackexchange

问:
How do I give a name to a primary key constraint?
I have (another) question about indexing.

I use the following code:

```<code>CREATE TABLE [dbo].[PnrDetails1](
        [OId] [int] IDENTITY(1,1) NOT NULL ,
    [file_name] [varchar](256) NOT NULL,
    [gds_id] [int] NOT NULL,
    [pnr_locator] [varchar](15) NOT NULL,
    [first_cust_name] [varchar](50) NOT NULL,
    [ticket_number] [varchar](20) NOT NULL,
    [full_price] [decimal](18, 0) NOT NULL,
    [currency_desc] [varchar](4) NOT NULL,
    [user_name] [varchar](50) NOT NULL,
    [save_time] [datetime] NOT NULL,
    [update_time] [datetime] NOT NULL,
    [clerk_id] [int] NOT NULL,
    [isUpdated] [bit] NOT NULL,
    [isDeleted] [bit] NOT NULL,
    [pnr_file_id] [int] NOT NULL
) ON [PRIMARY]

ALTER TABLE [dbo].[PnrDetails1] ADD PRIMARY KEY CLUSTERED
(
[OId] ASC
)ON [PRIMARY]
</code>```

this is actually a script sql server 2008 created for me,
but when I look at the object explorer I see an ugly name for the index (something like PK_PnrDetai_CB394B1958F2C25C). How can I change it? If so?

答:
While I agree with @marc_s that you should always declare these names up front, I disagree that you have to drop and re-create:</p>

```<code>EXEC sp_rename 'PK_PnrDetai_CB394B1958F2C25C', 'my_new_shiny_name', OBJECT;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have (another) question about indexing.

I use the following code:

CREATE TABLE [dbo].[PnrDetails1](
        [OId] [int] IDENTITY(1,1) NOT NULL ,
    [file_name] [varchar](256) NOT NULL,
    [gds_id] [int] NOT NULL,
    [pnr_locator] [varchar](15) NOT NULL,
    [first_cust_name] [varchar](50) NOT NULL,
    [ticket_number] [varchar](20) NOT NULL,
    [full_price] [decimal](18, 0) NOT NULL,
    [currency_desc] [varchar](4) NOT NULL,
    [user_name] [varchar](50) NOT NULL,
    [save_time] [datetime] NOT NULL,
    [update_time] [datetime] NOT NULL,
    [clerk_id] [int] NOT NULL,
    [isUpdated] [bit] NOT NULL,
    [isDeleted] [bit] NOT NULL,
    [pnr_file_id] [int] NOT NULL
) ON [PRIMARY]

ALTER TABLE [dbo].[PnrDetails1] ADD PRIMARY KEY CLUSTERED
(
[OId] ASC
)ON [PRIMARY]

this is actually a script sql server 2008 created for me,
but when I look at the object explorer I see an ugly name for the index (something like PK_PnrDetai_CB394B1958F2C25C). How can I change it? If so?

Body:
While I agree with @marc_s that you should always declare these names up front, I disagree that you have to drop and re-create:

EXEC sp_rename 'PK_PnrDetai_CB394B1958F2C25C', 'my_new_shiny_name', OBJECT;


问:
How to make a specific rectangle flutter
I want to make shape like the one below and write on it in my flutter app

How can I make it?

答:
you can use ClipPath

```<code> class _BottomBarState extends State<BottomBar> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child: ClipPath(
        clipper: MyCustomClipper(),
        child: Container(
          width: 300,
          height: 50,
          color: Colors.red,
          alignment: Alignment.center,
          child:const Text("Your Text"),
        ),
      ),
    ));
  }
}

class MyCustomClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    final path = Path();

    path.lineTo(size.width, 0);
    path.lineTo(size.width - 50, 25);
    path.lineTo(size.width, size.height);
    path.lineTo(0, size.height);

    return path;
  }

  @override
  bool shouldReclip(MyCustomClipper oldClipper) => false;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
you can use ClipPath

 class _BottomBarState extends State<BottomBar> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child: ClipPath(
        clipper: MyCustomClipper(),
        child: Container(
          width: 300,
          height: 50,
          color: Colors.red,
          alignment: Alignment.center,
          child:const Text("Your Text"),
        ),
      ),
    ));
  }
}

class MyCustomClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    final path = Path();

    path.lineTo(size.width, 0);
    path.lineTo(size.width - 50, 25);
    path.lineTo(size.width, size.height);
    path.lineTo(0, size.height);

    return path;
  }

  @override
  bool shouldReclip(MyCustomClipper oldClipper) => false;
}


问:
Trying to find an object with a key in a nested array in javascript
I'm trying to pass a key to a recursive function and find and return that object with that key.

This is the array that I like to search into

```<code>const treeData = [
  {
    title: 'parent 1',
    key: '0-0',
    children: [
      {
        title: 'parent 1-0',
        key: '0-0-0',
        disabled: true,
        children: [
          {
            title: 'leafffff',
            key: '0-0-0-0',
            disableCheckbox: true,
          },
          {
            title: 'leaf',
            key: '0-0-0-1',
          },
        ],
      },
    ],
  },
];
</code>```

And this is my current function

```<code>function findNode(x, key) {
    if (x.key === key)
        return x
    else if (Array.isArray(x)) {
        return x.map(item => {
            const r = findNode(item, key)
            if (r) return r
            if (item.children)
                return findNode(item.children, key)
        })
    }
}
</code>```

Live example:

const treeData = [ { title: 'parent 1', key: '0-0', children: [ { title: 'parent 1-0', key: '0-0-0', disabled: true, children: [ { title: 'leafffff', key: '0-0-0-0', disableCheckbox: true, }, { title: 'leaf', key: '0-0-0-1', }, ], }, ], }, ];
function findNode(x, key) {
  if (x.key === key)
    return x
  else if (Array.isArray(x)) {
    return x.map(item => {
      const r = findNode(item, key)
      if (r) return r
      if (item.children)
        return findNode(item.children, key)
    })
  }
}

const node = findNode(treeData, '0-0-0-1')
console.log(node)```

Using this function I can find the result but is not in the current format. I like to get a single object but gives me nested array with that object in the most nested child

答:
You could iterate the array and exit early on find, either by finding the node directly or by finding it by iterating the children.

const
    find = (key, array = []) => {
        let node;
        array.some(object => node = object.key === key
            ? object
            : find(key, object.children)
        );
        return node;
    }
    data = [{ title: 'parent 1', key: '0-0', children: [{ title: 'parent 1-0', key: '0-0-0', disabled: true, children: [{ title: 'leafffff', key: '0-0-0-0', disableCheckbox: true }, { title: 'leaf', key: '0-0-0-1' }] }] }];

console.log(find('0-0', data));
console.log(find('0-0-0', data));
console.log(find('0-0-0-0', data));
console.log(find('0-0-0-1', data));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I'm trying to pass a key to a recursive function and find and return that object with that key.

This is the array that I like to search into

const treeData = [
  {
    title: 'parent 1',
    key: '0-0',
    children: [
      {
        title: 'parent 1-0',
        key: '0-0-0',
        disabled: true,
        children: [
          {
            title: 'leafffff',
            key: '0-0-0-0',
            disableCheckbox: true,
          },
          {
            title: 'leaf',
            key: '0-0-0-1',
          },
        ],
      },
    ],
  },
];

And this is my current function

function findNode(x, key) {
    if (x.key === key)
        return x
    else if (Array.isArray(x)) {
        return x.map(item => {
            const r = findNode(item, key)
            if (r) return r
            if (item.children)
                return findNode(item.children, key)
        })
    }
}

Live example:

const treeData = [ { title: 'parent 1', key: '0-0', children: [ { title: 'parent 1-0', key: '0-0-0', disabled: true, children: [ { title: 'leafffff', key: '0-0-0-0', disableCheckbox: true, }, { title: 'leaf', key: '0-0-0-1', }, ], }, ], }, ];
function findNode(x, key) {
  if (x.key === key)
    return x
  else if (Array.isArray(x)) {
    return x.map(item => {
      const r = findNode(item, key)
      if (r) return r
      if (item.children)
        return findNode(item.children, key)
    })
  }
}

const node = findNode(treeData, '0-0-0-1')
console.log(node)

Using this function I can find the result but is not in the current format. I like to get a single object but gives me nested array with that object in the most nested child

Body:
You could iterate the array and exit early on find, either by finding the node directly or by finding it by iterating the children.

const
    find = (key, array = []) => {
        let node;
        array.some(object => node = object.key === key
            ? object
            : find(key, object.children)
        );
        return node;
    }
    data = [{ title: 'parent 1', key: '0-0', children: [{ title: 'parent 1-0', key: '0-0-0', disabled: true, children: [{ title: 'leafffff', key: '0-0-0-0', disableCheckbox: true }, { title: 'leaf', key: '0-0-0-1' }] }] }];

console.log(find('0-0', data));
console.log(find('0-0-0', data));
console.log(find('0-0-0-0', data));
console.log(find('0-0-0-1', data));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
find named entities from tokenized sentences in SPACY v2.0
I am trying to do:

Tokenize sentences from text

Compute Named Entities for each word present in sentence

This is what I have done so far:

```<code>nlp = spacy.load('en')
sentence = "Germany and U.S.A are popular countries. I am going to gym tonight"
sentence = nlp(sentence)
tokenized_sentences = []
for sent in sentence.sents:
        tokenized_sentences.append(sent)
for s in tokenized_sentences:
        labels = [ent.label_ for ent in s.ents]
        entities = [ent.text for ent in s.ents]
</code>```

Error:

```<code>    labels = [ent.label_ for ent in s.ents]
    AttributeError: 'spacy.tokens.span.Span' object has no attribute 'ents'
</code>```

Is there any alternative way to find named entities of tokenized sentence?

Thanks in advance

答:
ents works only with doc (spacy.tokens.doc.Doc), if you use doc=nlp(text)

sent is of type spacy.tokens.span.Span which has no ents method.

Convert it to text and use nlp() again.

```<code>print([(ent.text, ent.label_) for ent in nlp(sent.text).ents])
</code>```

Body:
I am trying to do:

Tokenize sentences from text

Compute Named Entities for each word present in sentence

This is what I have done so far:

nlp = spacy.load('en')
sentence = "Germany and U.S.A are popular countries. I am going to gym tonight"
sentence = nlp(sentence)
tokenized_sentences = []
for sent in sentence.sents:
        tokenized_sentences.append(sent)
for s in tokenized_sentences:
        labels = [ent.label_ for ent in s.ents]
        entities = [ent.text for ent in s.ents]

Error:

    labels = [ent.label_ for ent in s.ents]
    AttributeError: 'spacy.tokens.span.Span' object has no attribute 'ents'

Is there any alternative way to find named entities of tokenized sentence?

Thanks in advance

Body:
ents works only with doc (spacy.tokens.doc.Doc), if you use doc=nlp(text)

sent is of type spacy.tokens.span.Span which has no ents method.

Convert it to text and use nlp() again.

print([(ent.text, ent.label_) for ent in nlp(sent.text).ents])


问:
Use AWS CLI to list certain managed policies
I'm trying to list AWS (managed) policies related to CodeCommit using AWS CLI.

I found aws list-policies but it doesn't seem to have a way to filter. It just returns ALL the policies.

I would like to return the same as if I was using the console

AWSCodeCommitFullAccess

AWSCodeCommitPowerUser

AWSCodeCommitReadOnly

Anyone knows the proper way to do this? Thanks!

答:
when run commands to list anything in aws and then grep it with target information. as shown in below command.

```<code>aws iam list-policies --profile binsysmh  |grep -i commit
</code>```

here you will also get arn for target policies which will help for next aws cli tasks.

Note: this trick is only validate in Linux based terminal.

Body:
when run commands to list anything in aws and then grep it with target information. as shown in below command.

aws iam list-policies --profile binsysmh  |grep -i commit

here you will also get arn for target policies which will help for next aws cli tasks.

Note: this trick is only validate in Linux based terminal.


问:
c++ const convert

Possible Duplicate:

  why isnt it legal to convert (pointer to pointer to non-const) to a (pointer to pointer to a const)

I have a function:

```<code>bool isCirclePolygonIntersection(const Point*, const int*, const Point*,
                                 const Point**, const int*);
</code>```

and I'm trying to call it like this:

```<code>isCirclePolygonIntersection(p, &r, poly_coord, poly, &poly_size)
</code>```

where poly defined like this:

```<code>Point** poly = new Point*[poly_size];
</code>```

and there is a compiler error when I'm trying to compile it:

```<code>error C2664: 'isCirclePolygonIntersection' : cannot convert parameter 4 from 'Point **' to 'const Point **'
1>          Conversion loses qualifiers
</code>```

from what I've learned is that you cannot give const argument to function when a function expects a non const argument, but it's fine otherwise.
Does anyone knows what is the problem??
Thanks.

答: You're correct; you can implicitly convert a T * to a const T *.  However, you cannot implicitly convert a T ** to a const T **.  See this from the C FAQ: http://c-faq.com/ansi/constmismatch.html.

Title: c++ const convert

Body:
Possible Duplicate:

  why isnt it legal to convert (pointer to pointer to non-const) to a (pointer to pointer to a const)

I have a function:

bool isCirclePolygonIntersection(const Point*, const int*, const Point*,
                                 const Point**, const int*);

and I'm trying to call it like this:

isCirclePolygonIntersection(p, &r, poly_coord, poly, &poly_size)

where poly defined like this:

Point** poly = new Point*[poly_size];

and there is a compiler error when I'm trying to compile it:

error C2664: 'isCirclePolygonIntersection' : cannot convert parameter 4 from 'Point **' to 'const Point **'
1>          Conversion loses qualifiers

from what I've learned is that you cannot give const argument to function when a function expects a non const argument, but it's fine otherwise.
Does anyone knows what is the problem??
Thanks.


问:
VBA : Can child sub inherit properties from its parent sub
I am creating an Excel macro that populated as template PowerPoint slide deck with some charts from the workbook.

The act of copy and pasting a chart from Excel to PowerPoint takes a lot of lines of code, so I am trying to move this into a subroutine that I call from the main routine, to keep everything modular.  The below illustrates what I am trying to do.

To me, the only arguments that should vary for each call of the PasteChart subroutine is the name of the chart I am copying across (eg Figure1, Figure2, etc) and the placeholder position on the slide (2, 3, etc).  The slide number I want to define before calling the routines as I need to do other things to the slide as well.

To me, the arguments wb, pptApp, ppt, SlideNumber should be inherited from the main routine so that I don't have to keep passing them to the PasteChart subroutine.  Ie, these 4 arguments are going to be the same for all calls of the PasteChart subroutine.

But if I don't pass them as I have below, my macro won't work.

Is there a way to more elegantly structure the below subroutine?  Or in other words, how can I get the PasteChart subroutine to inherit the arguments wb, pptApp, ppt, SlideNumber from the main routine?

Parent Subroutine

```<code>Sub CreateSlideDeck()

    Set wb = ActiveWorkbook()

    Set pptApp = CreateObject("PowerPoint.Application")
    Set ppt = pptApp.Presentations.Open("D:\Template\Template.pptx", untitled:=msoTrue)

    SlideNumber = 3

    Call PasteChart("Figure1", 2, wb, pptApp, ppt, SlideNumber)
    Call PasteChart("Figure2", 3, wb, pptApp, ppt, SlideNumber)

End Sub
</code>```

Child Subroutine

```<code>Sub PasteChart(ChartName, Position, wb, pptApp, ppt, SlideNumber)

    wb.Sheets("Charts").ChartObjects(ChartName).Activate
    ActiveChart.ChartArea.Copy

    pptApp.Activate
    ppt.Slides(SlideNumber).Select
    ppt.Slides(SlideNumber).Shapes.Placeholders(Position).Select
    ppt.Windows(1).view.Paste

End Sub
</code>```

答:
This is untested but you can create them as global variables within the module.

```<code>Dim wb As Workbook
Dim pptApp As Object
Dim ppt As Object
Dim SlideNumber As Long

Sub CreateSlideDeck()
    Set wb = ActiveWorkbook()

    Set pptApp = CreateObject("PowerPoint.Application")
    Set ppt = pptApp.Presentations.Open("D:\Template\Template.pptx", untitled:=msoTrue)

    SlideNumber = 3

    Call PasteChart("Figure1", 2)
    Call PasteChart("Figure2", 3)
End Sub

Sub PasteChart(ByVal ChartName As String, ByVal Position As Long)
    wb.Sheets("Charts").ChartObjects(ChartName).Activate
    ActiveChart.ChartArea.Copy

    pptApp.Activate
    ppt.Slides(SlideNumber).Select
    ppt.Slides(SlideNumber).Shapes.Placeholders(Position).Select
    ppt.Windows(1).View.Paste
End Sub
</code>```

Would I do that?  Probably not but each to their own and if you have a use case and it works for you then so be it.

Body:
I am creating an Excel macro that populated as template PowerPoint slide deck with some charts from the workbook.

The act of copy and pasting a chart from Excel to PowerPoint takes a lot of lines of code, so I am trying to move this into a subroutine that I call from the main routine, to keep everything modular.  The below illustrates what I am trying to do.

To me, the only arguments that should vary for each call of the PasteChart subroutine is the name of the chart I am copying across (eg Figure1, Figure2, etc) and the placeholder position on the slide (2, 3, etc).  The slide number I want to define before calling the routines as I need to do other things to the slide as well.

To me, the arguments wb, pptApp, ppt, SlideNumber should be inherited from the main routine so that I don't have to keep passing them to the PasteChart subroutine.  Ie, these 4 arguments are going to be the same for all calls of the PasteChart subroutine.

But if I don't pass them as I have below, my macro won't work.

Is there a way to more elegantly structure the below subroutine?  Or in other words, how can I get the PasteChart subroutine to inherit the arguments wb, pptApp, ppt, SlideNumber from the main routine?

Parent Subroutine

Sub CreateSlideDeck()

    Set wb = ActiveWorkbook()

    Set pptApp = CreateObject("PowerPoint.Application")
    Set ppt = pptApp.Presentations.Open("D:\Template\Template.pptx", untitled:=msoTrue)

    SlideNumber = 3

    Call PasteChart("Figure1", 2, wb, pptApp, ppt, SlideNumber)
    Call PasteChart("Figure2", 3, wb, pptApp, ppt, SlideNumber)

End Sub

Child Subroutine

Sub PasteChart(ChartName, Position, wb, pptApp, ppt, SlideNumber)

    wb.Sheets("Charts").ChartObjects(ChartName).Activate
    ActiveChart.ChartArea.Copy

    pptApp.Activate
    ppt.Slides(SlideNumber).Select
    ppt.Slides(SlideNumber).Shapes.Placeholders(Position).Select
    ppt.Windows(1).view.Paste

End Sub

Body:
This is untested but you can create them as global variables within the module.

Dim wb As Workbook
Dim pptApp As Object
Dim ppt As Object
Dim SlideNumber As Long

Sub CreateSlideDeck()
    Set wb = ActiveWorkbook()

    Set pptApp = CreateObject("PowerPoint.Application")
    Set ppt = pptApp.Presentations.Open("D:\Template\Template.pptx", untitled:=msoTrue)

    SlideNumber = 3

    Call PasteChart("Figure1", 2)
    Call PasteChart("Figure2", 3)
End Sub

Sub PasteChart(ByVal ChartName As String, ByVal Position As Long)
    wb.Sheets("Charts").ChartObjects(ChartName).Activate
    ActiveChart.ChartArea.Copy

    pptApp.Activate
    ppt.Slides(SlideNumber).Select
    ppt.Slides(SlideNumber).Shapes.Placeholders(Position).Select
    ppt.Windows(1).View.Paste
End Sub

Would I do that?  Probably not but each to their own and if you have a use case and it works for you then so be it.


问:
How to handle QDialogButtonBox RestoreDefaults button
In Qt Designer I created a dialog box that has a QDialogButtonBox with OK, Cancel, and "Restore Defaults" buttons in it. It took a while, but I figured out how to setup the signals/slots in my implementation file with:

```<code>QPushButton* resetButton = m_ui.buttonBox->button(QDialogButtonBox::RestoreDefaults);
connect(resetButton, SIGNAL(clicked()), this, SLOT(resetDefaultsPressed()));
</code>```

My question is this: Is there a way to setup the signals/slots in QtDesigner like you can with the OK and Cancel buttons? I haven't been able to find a signal called RestoreDefaults or similar... The method I have works, but it would be nice if all the signal/slot setup was together in the .h file that uic generates.

答:
I've done it by adding

```<code><connection>
 <sender>buttonBox</sender>
 <signal>clicked(button)</signal>
 <receiver>OptionsWindow</receiver>
 <slot>clicked(button)</slot>
</connection>
</code>```

to my OptionsWindow.ui <connections> section, and then in code it is:

```<code>void OptionsWindow::clicked(QAbstractButton* button)
{
    if (mUi->buttonBox->buttonRole(button) == QDialogButtonBox::ButtonRole::ResetRole)
    {
        mOptionsData = OptionsData();
        mSavedOptionsData = mOptionsData;
        updateUi();
    }
}
</code>```

as a slot.

Body:
In Qt Designer I created a dialog box that has a QDialogButtonBox with OK, Cancel, and "Restore Defaults" buttons in it. It took a while, but I figured out how to setup the signals/slots in my implementation file with:

QPushButton* resetButton = m_ui.buttonBox->button(QDialogButtonBox::RestoreDefaults);
connect(resetButton, SIGNAL(clicked()), this, SLOT(resetDefaultsPressed()));

My question is this: Is there a way to setup the signals/slots in QtDesigner like you can with the OK and Cancel buttons? I haven't been able to find a signal called RestoreDefaults or similar... The method I have works, but it would be nice if all the signal/slot setup was together in the .h file that uic generates.

Body:
I've done it by adding

<connection>
 <sender>buttonBox</sender>
 <signal>clicked(button)</signal>
 <receiver>OptionsWindow</receiver>
 <slot>clicked(button)</slot>
</connection>

to my OptionsWindow.ui <connections> section, and then in code it is:

void OptionsWindow::clicked(QAbstractButton* button)
{
    if (mUi->buttonBox->buttonRole(button) == QDialogButtonBox::ButtonRole::ResetRole)
    {
        mOptionsData = OptionsData();
        mSavedOptionsData = mOptionsData;
        updateUi();
    }
}

as a slot.


问:
Google map crash with jetpack compose library
I am trying to add google maps to my app following this document - https://developers.google.com/maps/documentation/android-sdk/maps-compose

The problem is when I set is isMyLocationEnabled = true I got this error, I want to display myLocation button, when it is to false it is working

```<code>    Process: com.example.tryingtofixgooglemap, PID: 12872
    java.lang.SecurityException: my location requires permission ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION
        at com.google.maps.api.android.lib6.impl.bi.c(:com.google.android.gms.dynamite_mapsdynamite@201817052@20.18.17 (040700-0):27)
        at com.google.android.gms.maps.internal.i.a(:com.google.android.gms.dynamite_mapsdynamite@201817052@20.18.17 (040700-0):138)
        at cy.onTransact(:com.google.android.gms.dynamite_mapsdynamite@201817052@20.18.17 (040700-0):4)
        at android.os.Binder.transact(Binder.java:1043)
...
...
</code>```

I got both permissions in my manifest file

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.tryingtofixgooglemap">
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.TryingToFixGoogleMap">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="{api_key}" />
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.TryingToFixGoogleMap">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

And this is my build.gradle

```<code>    implementation 'androidx.core:core-ktx:1.7.0'
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
    implementation 'androidx.activity:activity-compose:1.3.1'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
    implementation "com.google.maps.android:maps-compose:1.0.0"
    implementation "com.google.android.gms:play-services-maps:18.0.2"
    implementation 'com.google.android.gms:play-services-location:19.0.1'
</code>```

And my code in compose scope

```<code>var uiSettings by remember { mutableStateOf(
                            MapUiSettings(
                                zoomControlsEnabled = false,
                            )
                        )
                    }
                    var properties by remember { mutableStateOf(
                            MapProperties(
                            isMyLocationEnabled = true
                            )
                        )
                    }
                    Box(Modifier.fillMaxSize()) {
                        GoogleMap(
                            modifier = Modifier.matchParentSize(),
                            properties = properties,
                            uiSettings = uiSettings
                        ){

                        }

                    }
</code>```

答:
you can make use of google's accompanist library to check for run time permission with jetpack compose

```<code>implementation "com.google.accompanist:accompanist-permissions:<version>"
</code>```

Declare Permission State

```<code>val permissionState = rememberPermissionState(
    permission = Manifest.permission.ACCESS_FINE_LOCATION,
)
</code>```

On Tap of a button or a lifecycle event you can request run time permissions

```<code>Button(onClick = { state.launchPermissionRequest() }) {
    Text("Request Permission")
}
</code>```

Listen for the permission result from permissionState flow

```<code>if (permissionState.hasPermission) {
    // do something
}
</code>```

ref: https://google.github.io/accompanist/permissions/

Body:
I am trying to add google maps to my app following this document - https://developers.google.com/maps/documentation/android-sdk/maps-compose

The problem is when I set is isMyLocationEnabled = true I got this error, I want to display myLocation button, when it is to false it is working

    Process: com.example.tryingtofixgooglemap, PID: 12872
    java.lang.SecurityException: my location requires permission ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION
        at com.google.maps.api.android.lib6.impl.bi.c(:com.google.android.gms.dynamite_mapsdynamite@201817052@20.18.17 (040700-0):27)
        at com.google.android.gms.maps.internal.i.a(:com.google.android.gms.dynamite_mapsdynamite@201817052@20.18.17 (040700-0):138)
        at cy.onTransact(:com.google.android.gms.dynamite_mapsdynamite@201817052@20.18.17 (040700-0):4)
        at android.os.Binder.transact(Binder.java:1043)
...
...

I got both permissions in my manifest file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.tryingtofixgooglemap">
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.TryingToFixGoogleMap">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="{api_key}" />
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.TryingToFixGoogleMap">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

And this is my build.gradle

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
    implementation 'androidx.activity:activity-compose:1.3.1'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
    implementation "com.google.maps.android:maps-compose:1.0.0"
    implementation "com.google.android.gms:play-services-maps:18.0.2"
    implementation 'com.google.android.gms:play-services-location:19.0.1'

And my code in compose scope

var uiSettings by remember { mutableStateOf(
                            MapUiSettings(
                                zoomControlsEnabled = false,
                            )
                        )
                    }
                    var properties by remember { mutableStateOf(
                            MapProperties(
                            isMyLocationEnabled = true
                            )
                        )
                    }
                    Box(Modifier.fillMaxSize()) {
                        GoogleMap(
                            modifier = Modifier.matchParentSize(),
                            properties = properties,
                            uiSettings = uiSettings
                        ){

                        }

                    }

Body:
you can make use of google's accompanist library to check for run time permission with jetpack compose

implementation "com.google.accompanist:accompanist-permissions:<version>"

Declare Permission State

val permissionState = rememberPermissionState(
    permission = Manifest.permission.ACCESS_FINE_LOCATION,
)

On Tap of a button or a lifecycle event you can request run time permissions

Button(onClick = { state.launchPermissionRequest() }) {
    Text("Request Permission")
}

Listen for the permission result from permissionState flow

if (permissionState.hasPermission) {
    // do something
}

ref: https://google.github.io/accompanist/permissions/


问:
Python: How to make machine learning predictions run faster in production?
I have created a machine learning model in scikit-learn which I need to deploy in production with live data. The features look like this for example:

```<code>  date          event_id  user_id     feature1    feature2    featureX...
  2017-01-27    100       5555        1.23        2           2.99
  2017-01-27    100       4444        2.55        5           3.16
  2017-01-27    100       3333        0.45        3           1.69
  2017-01-27    105       1212        3.96        4           0.0
  2017-01-27    105       2424        1.55        2           5.56
  2017-01-27    105       3636        0.87        4           10.28
</code>```

So, there are different events each day. Before the event starts I basically store this in a dataframe by pulling them from a database and calculate the predictions using the pickled scikit model as:

```<code>df_X = df.drop(['date', 'event_id', 'user_id'], axis=1)
loaded_model = joblib.load("model.joblib.dat")
prediction = loaded_model.predict_proba(df_X)
</code>```

Then I match the prediction back to df and send as an output to an API or file as needed.

When the events starts the featureX is constantly updated that I get from an API. To do the updating I'm using the loop that goes through each event_id and user_id and update df with the new featureX value, recalculate and send to the output again.

For that I'm doing something like this:

```<code># get list of unique event ids
events = set(df['event_id'].tolist())

try:
    while True:
        start = time.time()
        for event in events:
            featureX = request.get(API_URL + event)
            featureX_json = featureX.json()

            for user in featureX_json['users']:
                df.loc[df.user_id == user['user_id'],
                       'featureX'] = user['featureX']

        df_X = df.drop(['date', 'event_id', 'user_id'], axis=1)
        df['prediction'] = loaded_model.predict_proba(df_X)

        # send to API or write to file

        end = time.time()
        print('recalculation time {} secs'.format(end - start))

except KeyboardInterrupt:
    print('exiting !')
</code>```

This works fine for me but the whole prediction update takes around 4 secs in the server and I need it to be under 1 sec. I'm trying to figure out what I could change in the while loop to get the speedup I need?

A sample of the json has been added upon request for event_id = 100 the URL http://myapi/api/event_users/<event_id>:

```<code>{
    "count": 3,
    "users": [
        {
            "user_id": 4444,
            "featureY": 34,
            "featureX": 4.49,
            "created": "2017-01-17T13:00:09.065498Z"
        },
        {
            "user_id": 3333,
            "featureY": 22,
            "featureX": 1.09,
            "created": "2017-01-17T13:00:09.065498Z"
        },
         {
            "user_id": 5555,
            "featureY": 58,
            "featureX": 9.54,
            "created": "2017-01-17T13:00:09.065498Z"
        }
    ]
}
</code>```

答:
You can try using accelerated implementations of algorithms - such as scikit-learn-intelex - https://github.com/intel/scikit-learn-intelex.  This is a free software AI accelerator that brings over 10-100X acceleration across a variety of applications.

This library will provide great performance improvements for both training and predictions.

Example of speedup that you can achieve

First install package

pip install scikit-learn-intelex
```
<p>And then add in your python script</p>
<pre class="lang-py prettyprint-override"><code>from sklearnex import patch_sklearn
patch_sklearn()
</code>```

Body:
I have created a machine learning model in scikit-learn which I need to deploy in production with live data. The features look like this for example:

  date          event_id  user_id     feature1    feature2    featureX...
  2017-01-27    100       5555        1.23        2           2.99
  2017-01-27    100       4444        2.55        5           3.16
  2017-01-27    100       3333        0.45        3           1.69
  2017-01-27    105       1212        3.96        4           0.0
  2017-01-27    105       2424        1.55        2           5.56
  2017-01-27    105       3636        0.87        4           10.28

So, there are different events each day. Before the event starts I basically store this in a dataframe by pulling them from a database and calculate the predictions using the pickled scikit model as:

df_X = df.drop(['date', 'event_id', 'user_id'], axis=1)
loaded_model = joblib.load("model.joblib.dat")
prediction = loaded_model.predict_proba(df_X)

Then I match the prediction back to df and send as an output to an API or file as needed.

When the events starts the featureX is constantly updated that I get from an API. To do the updating I'm using the loop that goes through each event_id and user_id and update df with the new featureX value, recalculate and send to the output again.

For that I'm doing something like this:

# get list of unique event ids
events = set(df['event_id'].tolist())

try:
    while True:
        start = time.time()
        for event in events:
            featureX = request.get(API_URL + event)
            featureX_json = featureX.json()

            for user in featureX_json['users']:
                df.loc[df.user_id == user['user_id'],
                       'featureX'] = user['featureX']

        df_X = df.drop(['date', 'event_id', 'user_id'], axis=1)
        df['prediction'] = loaded_model.predict_proba(df_X)

        # send to API or write to file

        end = time.time()
        print('recalculation time {} secs'.format(end - start))

except KeyboardInterrupt:
    print('exiting !')

This works fine for me but the whole prediction update takes around 4 secs in the server and I need it to be under 1 sec. I'm trying to figure out what I could change in the while loop to get the speedup I need?

A sample of the json has been added upon request for event_id = 100 the URL http://myapi/api/event_users/<event_id>:

{
    "count": 3,
    "users": [
        {
            "user_id": 4444,
            "featureY": 34,
            "featureX": 4.49,
            "created": "2017-01-17T13:00:09.065498Z"
        },
        {
            "user_id": 3333,
            "featureY": 22,
            "featureX": 1.09,
            "created": "2017-01-17T13:00:09.065498Z"
        },
         {
            "user_id": 5555,
            "featureY": 58,
            "featureX": 9.54,
            "created": "2017-01-17T13:00:09.065498Z"
        }
    ]
}

Body:
You can try using accelerated implementations of algorithms - such as scikit-learn-intelex - https://github.com/intel/scikit-learn-intelex.  This is a free software AI accelerator that brings over 10-100X acceleration across a variety of applications.

This library will provide great performance improvements for both training and predictions.

Example of speedup that you can achieve

First install package

pip install scikit-learn-intelex

And then add in your python script

from sklearnex import patch_sklearn
patch_sklearn()


问:
How to remove the character at a given index from a string in C?
How do I remove a character from a string?

If I have the string "abcdef" and I want to remove "b" how do I do that?

Removing the first character is easy with this code:

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

int main()
{
    char word[] = "abcdef";
    char word2[10];

    strcpy(word2, &word[1]);

    printf("%s\n", word2);

    return 0;
}
</code>```

and

```<code>strncpy(word2, word, strlen(word) - 1);
</code>```

will give me the string without the last character, but I still didn't figure out how to remove a char in the middle of a string.

答:
This is a pretty basic way to do it:

```<code>void remove_character(char *string, int index) {
   for (index; *(string + index) != '\0'; index++) {
      *(string + index) = *(string + index + 1);
   }
}
</code>```

Body:
How do I remove a character from a string?

If I have the string "abcdef" and I want to remove "b" how do I do that?

Removing the first character is easy with this code:

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

int main()
{
    char word[] = "abcdef";
    char word2[10];

    strcpy(word2, &word[1]);

    printf("%s\n", word2);

    return 0;
}

and

strncpy(word2, word, strlen(word) - 1);

will give me the string without the last character, but I still didn't figure out how to remove a char in the middle of a string.

Body:
This is a pretty basic way to do it:

void remove_character(char *string, int index) {
   for (index; *(string + index) != '\0'; index++) {
      *(string + index) = *(string + index + 1);
   }
}


问:
Do I need to do anything at the frontend to do anything to use TLS express api
I am quite new to the web and I am currently running into an issue. I want to build a safe express API but I am stuck and couldn't find much about this (I believe I don't know the right keyword to search for related articles).

So here's the problem. I am using a react frontend and an express backend. I want to use TLS to secure my APIs. So, I first generate the cert with OpenSSL and config the backend as follows:

import fs from 'fs'
import { createServer as createHttpsServer } from 'https'
import express from 'express'
import helmet from 'helmet'

const app = express();
app.use(helmet())

// configure TLS server
const server = createHttpsServer(
    {
        key: fs.readFileSync(config.ssl_key).toString(),
        cert: fs.readFileSync(config.ssl_cert).toString(),
        ca: fs.readFileSync(config.ssl_ca).toString(),
    }, app
);

// Listen to port
server.listen(config.port, config.host, () => {
            console.log(`HTTPS server is now listening on ${config.host}:${config.port}!`));
```

After setting up the backend, I am wondering what should I do at the frontend to use the TLS. Do I need to sign the certificate at the react frontend before using Axios to connect to the backend? Or can I directly use Axios at the frontend without the need of signing any kind of cert or registering for anything?

Thank you, I really appreciate everyone's help!

答:
Since you did not specify the requestCert option to your server, it will not request a certificate from the client (and the ca option has no effect). Therefore the client (that is, your browser) does not need a client certificate.

However, it must trust the server certificate from your cert option. Unless you had your server certificate signed by a trusted root certification authority (and paid for that), your browser will refuse the connection unless you upload the server certificate (or the root certificate that signed it) as a "trusted certificate".

Body:
I am quite new to the web and I am currently running into an issue. I want to build a safe express API but I am stuck and couldn't find much about this (I believe I don't know the right keyword to search for related articles).

So here's the problem. I am using a react frontend and an express backend. I want to use TLS to secure my APIs. So, I first generate the cert with OpenSSL and config the backend as follows:

import fs from 'fs'
import { createServer as createHttpsServer } from 'https'
import express from 'express'
import helmet from 'helmet'

const app = express();
app.use(helmet())

// configure TLS server
const server = createHttpsServer(
    {
        key: fs.readFileSync(config.ssl_key).toString(),
        cert: fs.readFileSync(config.ssl_cert).toString(),
        ca: fs.readFileSync(config.ssl_ca).toString(),
    }, app
);

// Listen to port
server.listen(config.port, config.host, () => {
            console.log(`HTTPS server is now listening on ${config.host}:${config.port}!`));

After setting up the backend, I am wondering what should I do at the frontend to use the TLS. Do I need to sign the certificate at the react frontend before using Axios to connect to the backend? Or can I directly use Axios at the frontend without the need of signing any kind of cert or registering for anything?

Thank you, I really appreciate everyone's help!


问:
Is root activity the current first activity in the stack or the activity specified as launch activity in manifest?
Is root activity the current first activity in the stack or the activity specified as launch activity in manifest?

Support application P starts activity A at launch. Then A starts B and finish itself, and then B starts C. Now the stack contains B and C, with B the first in the stack.

Can I say B is the root activity, or A is still the root activity.

I want to make clear of it because I am trying to understanding the definition of clearTaskOnLaunch:

android:clearTaskOnLaunch
    Whether or not all activities will be removed from the task, except for the root activity,   whenever it is re-launched from the home screen — "true" if the task is always stripped down to its root activity, and "false" if not.

答: I am a little uncertain of how you are launching Activity B from A. If A is being removed from the stack, and Activity C is launched from B - and if clearTaskOnLaunch is set to true - if the user presses HOME from Activity C, and then returns to your application - Activity B will be displayed, as C will have been removed from the stack.

ContentLicense: CC BY-SA 2.5


问:
Use element to style inside

The emb is not a class but an element. Can I use this element to style the div or, the only way to do it is making emb a class such as .emb?

  Hello

```

答:
Mistake in OP's code

style=emb is not a correct way to assign the class to an element.

Correction

To use an element to style inside div, you have to give it a class or id that maps the element to the style.css where you define the styles. Also ,replace emb with .emb, you have to add . decorator while using class

Some info

We have mainly 3 types of CSS decorators which we use to associate the HTML component with CSS component.

Simple tag like

```<code><div >
        Hello
</div>

<style>
   div {
   font-weight: 500;
    }
</style>
</code>```

Use class decorator with .

```<code><div class="emb">
        Hello
</div>

<style>
   .emb {
   font-weight: 500;
    }
</style>
</code>```

Use class decorator with .

```<code><div id="emb">
        Hello
</div>

<style>
   #emb {
   font-weight: 500;
    }
</style>
</code>```

Working code

  Hello

```
</div>
</div>
</p>
<h3>Alternate method with code</h3>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="emb">
  Hello
</div>

<style>
  #emb {
    font-weight: 500;
    font-style: italic;
    background: transparent;
    font-size: 18px
  }
</style></code>```

Title: Use element to style inside <div>

Body:
Mistake in OP's code

style=emb is not a correct way to assign the class to an element.

Correction

To use an element to style inside div, you have to give it a class or id that maps the element to the style.css where you define the styles. Also ,replace emb with .emb, you have to add . decorator while using class

Some info

We have mainly 3 types of CSS decorators which we use to associate the HTML component with CSS component.

Simple tag like

<div >
        Hello
</div>

<style>
   div {
   font-weight: 500;
    }
</style>

Use class decorator with .

<div class="emb">
        Hello
</div>

<style>
   .emb {
   font-weight: 500;
    }
</style>

Use class decorator with .

<div id="emb">
        Hello
</div>

<style>
   #emb {
   font-weight: 500;
    }
</style>

Working code

<div class="emb">
  Hello
</div>

<style>
  .emb {
    font-weight: 500;
    font-style: italic;
    background: transparent;
    font-size: 18px
  }
</style>

Alternate method with code

<div id="emb">
  Hello
</div>

<style>
  #emb {
    font-weight: 500;
    font-style: italic;
    background: transparent;
    font-size: 18px
  }
</style>


问:
How do delete All rows at DataGridView?
this is code :

```<code>         BindingSource bs = new BindingSource();

       DataTable tbl(string sql)
        {

        OracleConnection con = new OracleConnection(connectionstring);
        OracleDataAdapter adp = new OracleDataAdapter(sql, con);
        DataSet ds = new DataSet();
        adp.Fill(ds, "tbl");
        return ds.Tables["tbl"];
        }
 void GetData()
  {

   bs.DataSource = Class1.tbl("select USER_ID   ,EMP_NAME as pName,EMP_MOBILE from TBLUSERS");
            datagridview1.Columns[0].DataPropertyName = "USER_ID";
            datagridview1.Columns[1].DataPropertyName = "pName";
            datagridview1.Columns[2].DataPropertyName = "EMP_MOBILE";
            datagridview1.DataSource = bs;
 }

  void ClearAllRows()
    {
          datagridview1.Rows.Clear();
   //The error occurs here
    }
</code>```

The error occurs here
How do delete All rows at DataGridView ?
my DataGridView  is BindingSource

答:
Please Do This Code</p>
```<code>if(dgvItemDetails.Rows.Count>0) {
    do
    {
        dgvItemDetails.Rows.RemoveAt(0);
    }
    while (dgvItemDetails.Rows.Count > 0);
}
</code>```

Title: How do delete All rows at DataGridView?

Body:
this is code :

         BindingSource bs = new BindingSource();

       DataTable tbl(string sql)
        {

        OracleConnection con = new OracleConnection(connectionstring);
        OracleDataAdapter adp = new OracleDataAdapter(sql, con);
        DataSet ds = new DataSet();
        adp.Fill(ds, "tbl");
        return ds.Tables["tbl"];
        }
 void GetData()
  {

   bs.DataSource = Class1.tbl("select USER_ID   ,EMP_NAME as pName,EMP_MOBILE from TBLUSERS");
            datagridview1.Columns[0].DataPropertyName = "USER_ID";
            datagridview1.Columns[1].DataPropertyName = "pName";
            datagridview1.Columns[2].DataPropertyName = "EMP_MOBILE";
            datagridview1.DataSource = bs;
 }

  void ClearAllRows()
    {
          datagridview1.Rows.Clear();
   //The error occurs here
    }

The error occurs here
How do delete All rows at DataGridView ?
my DataGridView  is BindingSource

Body:
Please Do This Code

if(dgvItemDetails.Rows.Count>0) {
    do
    {
        dgvItemDetails.Rows.RemoveAt(0);
    }
    while (dgvItemDetails.Rows.Count > 0);
}


答:
const treeData = [
  {
    title: 'parent 1',
    key: '0-0',
    children: [
      {
        title: 'parent 1-0',
        key: '0-0-0',
        disabled: true,
        children: [
          { title: 'leafffff', key: '0-0-0-0', disableCheckbox: true },
          { title: 'leaf', key: '0-0' },
        ],
      },
    ],
  },
];
const findNodeInTree = (tree, key) => {
  let result = null;
  tree.forEach(node => {
    if (node.key === key) {
      result = node;
    } else if (node.children) {
      result = findNodeInTree(node.children, key);
    }
  });
  return result;
}
console.log(findNodeInTree(treeData, '0-0-0-0'));```

Title: Trying to find an object with a key in a nested array in javascript

Body:
I'm trying to pass a key to a recursive function and find and return that object with that key.

This is the array that I like to search into

const treeData = [
  {
    title: 'parent 1',
    key: '0-0',
    children: [
      {
        title: 'parent 1-0',
        key: '0-0-0',
        disabled: true,
        children: [
          {
            title: 'leafffff',
            key: '0-0-0-0',
            disableCheckbox: true,
          },
          {
            title: 'leaf',
            key: '0-0-0-1',
          },
        ],
      },
    ],
  },
];

And this is my current function

function findNode(x, key) {
    if (x.key === key)
        return x
    else if (Array.isArray(x)) {
        return x.map(item => {
            const r = findNode(item, key)
            if (r) return r
            if (item.children)
                return findNode(item.children, key)
        })
    }
}

Live example:

const treeData = [ { title: 'parent 1', key: '0-0', children: [ { title: 'parent 1-0', key: '0-0-0', disabled: true, children: [ { title: 'leafffff', key: '0-0-0-0', disableCheckbox: true, }, { title: 'leaf', key: '0-0-0-1', }, ], }, ], }, ];
function findNode(x, key) {
  if (x.key === key)
    return x
  else if (Array.isArray(x)) {
    return x.map(item => {
      const r = findNode(item, key)
      if (r) return r
      if (item.children)
        return findNode(item.children, key)
    })
  }
}

const node = findNode(treeData, '0-0-0-1')
console.log(node)

Using this function I can find the result but is not in the current format. I like to get a single object but gives me nested array with that object in the most nested child


问:
From trait - How to implement it from a slice
Looking at the documentation for the trait std::convert::From, it says:

Used to do value-to-value conversions while consuming the input value.

To me, and looking at the fn from(T) -> Self signature, it sounds like the function takes ownership of the argument.

How can e.g. String implement the From<&str> trait? It cannot take ownership from the shared reference.

I want to implement a "viewer" structure; something that doesn't take ownership: Say a &[u8] represents my binary data; the first byte is my "data id".

```<code>struct DataView {
    id: u8,
    data: &[u8],
}
</code>```

Then I would like to be able to do something like:

```<code>impl From<&[u8]> for DataView {
    fn from(buffer: &[u8]) -> DataView {
        DataView {
            id: buffer[0],
            data: &buffer[1..],
        }
    }
}
</code>```

Is something like this possible? Does such a structure make sense if I am only interested in "viewing"?

答:
Yes you can do that without taking ownership. But first, every stuct that contains a reference needs a lifetime to assert, that it doesn't exist passt the scope of the data it references:

```<code>#[derive(Debug)]
struct DataView<'a> {
    id: u8,
    data: &'a [u8],
}
</code>```

Now we can implement the From trait the following manner:

```<code>impl<'a> From<&'a [u8]> for DataView<'a> {
    fn from(arg: &'a [u8]) -> Self {
        let id = arg[0];
        let data = &arg[1..];
        Self { id, data }
    }
}
</code>```

Note that we are explicitly asserting that the referenced argmument has the same lifetime as the DataView object.
Now we can do:

```<code>fn main() {
    let arg: &[u8] = &[1, 2, 3, 4, 6];

    let view = DataView::from(arg);
    println!("{:?}", view);
}
</code>```

Body:
Looking at the documentation for the trait std::convert::From, it says:

Used to do value-to-value conversions while consuming the input value.

To me, and looking at the fn from(T) -> Self signature, it sounds like the function takes ownership of the argument.

How can e.g. String implement the From<&str> trait? It cannot take ownership from the shared reference.

I want to implement a "viewer" structure; something that doesn't take ownership: Say a &[u8] represents my binary data; the first byte is my "data id".

struct DataView {
    id: u8,
    data: &[u8],
}

Then I would like to be able to do something like:

impl From<&[u8]> for DataView {
    fn from(buffer: &[u8]) -> DataView {
        DataView {
            id: buffer[0],
            data: &buffer[1..],
        }
    }
}

Is something like this possible? Does such a structure make sense if I am only interested in "viewing"?

Body:
Yes you can do that without taking ownership. But first, every stuct that contains a reference needs a lifetime to assert, that it doesn't exist passt the scope of the data it references:

#[derive(Debug)]
struct DataView<'a> {
    id: u8,
    data: &'a [u8],
}

Now we can implement the From trait the following manner:

impl<'a> From<&'a [u8]> for DataView<'a> {
    fn from(arg: &'a [u8]) -> Self {
        let id = arg[0];
        let data = &arg[1..];
        Self { id, data }
    }
}

Note that we are explicitly asserting that the referenced argmument has the same lifetime as the DataView object.
Now we can do:

fn main() {
    let arg: &[u8] = &[1, 2, 3, 4, 6];

    let view = DataView::from(arg);
    println!("{:?}", view);
}


问:
Calculate string value in javascript, not using eval
Is there a way to calculate a formula stored in a string in JavaScript without using eval()?

Normally I would do something like

var apa = "12/5*9+9.4*2";
console.log(eval(apa));```

So, does anyone know about alternatives to eval()?

答:
Note : There is no library used in this solution purely hard coded

My solution takes into account of brackets also like 8+6(7(-1)) or 8+6(7(-1))

You can do these operations ^, *, /, +, -

To calculate a string use calculate(tokenize(pieval("8+6(7(-1))").join("")))

function tokenize(s) {
    // --- Parse a calculation string into an array of numbers and operators
    const r = [];
    let token = '';
    for (const character of s) {
        if ('^*/+-'.indexOf(character) > -1) {
            if (token === '' && character === '-') {
                token = '-';
            } else {
                r.push(parseFloat(token), character);
                token = '';
            }
        } else {
            token += character;
        }
    }
    if (token !== '') {
        r.push(parseFloat(token));
    }
    return r;
}

function calculate(tokens) {
    // --- Perform a calculation expressed as an array of operators and numbers
    const operatorPrecedence = [{'^': (a, b) => Math.pow(a, b)},
               {'*': (a, b) => a * b, '/': (a, b) => a / b},
               {'+': (a, b) => a + b, '-': (a, b) => a - b}];
    let operator;
    for (const operators of operatorPrecedence) {
        const newTokens = [];
        for (const token of tokens) {
            if (token in operators) {
                operator = operators[token];
            } else if (operator) {
                newTokens[newTokens.length - 1] =
                    operator(newTokens[newTokens.length - 1], token);
                operator = null;
            } else {
                newTokens.push(token);
            }
        }
        tokens = newTokens;
    }
    if (tokens.length > 1) {
        console.log('Error: unable to resolve calculation');
        return tokens;
    } else {
        return tokens[0];
    }
}

function pieval(input) {
  let openParenCount = 0;
  let myOpenParenIndex = 0;
  let myEndParenIndex = 0;
  const result = [];

  for (let i = 0; i < input.length; i++) {
    if (input[i] === "(") {
      if (openParenCount === 0) {
        myOpenParenIndex = i;

        // checking if anything exists before this set of parentheses
        if (i !== myEndParenIndex) {
            if(!isNaN(input[i-1])){
                result.push(input.substring(myEndParenIndex, i) + "*");
            }else{
                result.push(input.substring(myEndParenIndex, i));
            }
        }
      }
      openParenCount++;
    }

    if (input[i] === ")") {
      openParenCount--;
      if (openParenCount === 0) {
        myEndParenIndex = i + 1;

        // recurse the contents of the parentheses to search for nested ones
        result.push(pieval(input.substring(myOpenParenIndex + 1, i)));
      }
    }
  }

  // capture anything after the last parentheses
  if (input.length > myEndParenIndex) {
    result.push(input.substring(myEndParenIndex, input.length));
  }

  //console.log(cal(result))
  let response = cal(result);
  return result;
}

function cal(arr) {
  let calstr = "";
  for (let i = 0; i < arr.length; i++) {
    if (typeof arr[i] != "string") {
      if (cal(arr[i]) < 0) {
        arr[i] = `${cal(arr[i])}`;
      } else {
        arr[i] = `${cal(arr[i])}`;
      }
    }
    if (typeof arr[i] === "string") {
      calstr += arr[i];
    }
    if (i == arr.length - 1) {
      //console.log("cal" ,calstr,calculate(tokenize(calstr)) );
      return calculate(tokenize(calstr));
    }
  }
}
console.log(calculate(tokenize(pieval("8+6(7(-1))").join("")))); // ["1+",["2-",["3+4"]]]
console.log(calculate(tokenize(pieval("1+(1+(2(4/4))+4)").join("")))); // ["1+",["2-",["3+4"]]]```

Body:
Is there a way to calculate a formula stored in a string in JavaScript without using eval()?

Normally I would do something like

var apa = "12/5*9+9.4*2";
console.log(eval(apa));

So, does anyone know about alternatives to eval()?


问:
How to add quotes from specific delimiter to end of the line, using awk?
I am trying to modify a file: (file.txt)

```<code>abc~123~xyz~123456~12~0.12~14~1.1~
omn~124~xdz~923231~13~0.0~13~1.1~14~0.45~19~80.1~
</code>```

to (new_file.txt)

```<code>abc~123~xyz~123456~"12~0.12~14~1.1~"
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~"
</code>```

I tried using awk command:

```<code>awk -F'~' '{for(i=1;i<=4;i++){printf "%s~", $i}; printf"\""} {for(i=5;i<=NF;i+=1){printf "%s~", $i}; printf "\"\n"}' file.txt > new_file.txt
</code>```

but I am getting output as:

```<code>abc~123~xyz~123456~"12~0.12~14~1.1~~"
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~~"
</code>```

Can anyone help me out in this as I am getting an extra "~" at end of each line? Any reference would also be helpful as I get confused while dealing with sed and awk commands.

答:
You have a ~ separator at the end of your lines. So, you have an extra empty field after this field separator. You can check this with:

```<code>$ awk -F'~' '{print NF "|" $NF "|"}' file.txt
9||
13||
</code>```

See? When printing this last empty field followed by a ~, you simply concatenate it to the previous one, thus the ~~. Try:

```<code>$ awk -F '~' -vOFS='~' '{$5 = "\"" $5; $NF = $NF "\""; print}' file.txt
abc~123~xyz~123456~"12~0.12~14~1.1~"
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~"
</code>```

We just declare ~ as the input and output (with variable OFS) field separator, prepend a " to the fifth field, append one to the last field, and print.

Body:
I am trying to modify a file: (file.txt)

abc~123~xyz~123456~12~0.12~14~1.1~
omn~124~xdz~923231~13~0.0~13~1.1~14~0.45~19~80.1~

to (new_file.txt)

abc~123~xyz~123456~"12~0.12~14~1.1~"
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~"

I tried using awk command:

awk -F'~' '{for(i=1;i<=4;i++){printf "%s~", $i}; printf"\""} {for(i=5;i<=NF;i+=1){printf "%s~", $i}; printf "\"\n"}' file.txt > new_file.txt

but I am getting output as:

abc~123~xyz~123456~"12~0.12~14~1.1~~"
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~~"

Can anyone help me out in this as I am getting an extra "~" at end of each line? Any reference would also be helpful as I get confused while dealing with sed and awk commands.

Body:
You have a ~ separator at the end of your lines. So, you have an extra empty field after this field separator. You can check this with:

$ awk -F'~' '{print NF "|" $NF "|"}' file.txt
9||
13||

See? When printing this last empty field followed by a ~, you simply concatenate it to the previous one, thus the ~~. Try:

$ awk -F '~' -vOFS='~' '{$5 = "\"" $5; $NF = $NF "\""; print}' file.txt
abc~123~xyz~123456~"12~0.12~14~1.1~"
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~"

We just declare ~ as the input and output (with variable OFS) field separator, prepend a " to the fifth field, append one to the last field, and print.


问:
Python function won't print
The function looks as follows:

def calc_pi():
    pi = 4
    for i in range (0,200):
        y = 4/(3+(2*i))
        if i % 2 == 0:
            pi -= y
        else:
            pi += y
        return pi
        print("{}: pi = {}, y = {}".format( i, pi, y))
```

For some reason Python won't print the result. I don't really know where the problem lies here. I'm absolutely new to programming so it could perfectly well be that I overlooked some huge mistakes I've made.

Title: Python function won't print

Body:
The function looks as follows:

def calc_pi():
    pi = 4
    for i in range (0,200):
        y = 4/(3+(2*i))
        if i % 2 == 0:
            pi -= y
        else:
            pi += y
        return pi
        print("{}: pi = {}, y = {}".format( i, pi, y))

For some reason Python won't print the result. I don't really know where the problem lies here. I'm absolutely new to programming so it could perfectly well be that I overlooked some huge mistakes I've made.

Body:
The reason is the line return pi before the print.

This exits the function. Swap the around and it works:

In [1]: def calc_pi():
   ...:     pi = 4
   ...:     for i in range(0, 200):
   ...:         y = 4 / (3 + (2 * i))
   ...:         if i % 2 == 0:
   ...:             pi -= y
   ...:         else:
   ...:             pi += y
   ...:         return pi
   ...:         print("{}: pi = {}, y = {}".format(i, pi, y))
   ...:

In [2]: calc_pi()
Out[2]: 2.666666666666667

In [3]: def calc_pi():
   ...:     pi = 4
   ...:     for i in range(0, 200):
   ...:         y = 4 / (3 + (2 * i))
   ...:         if i % 2 == 0:
   ...:             pi -= y
   ...:         else:
   ...:             pi += y
   ...:         print("{}: pi = {}, y = {}".format(i, pi, y))
   ...:         return pi
   ...:

In [4]: calc_pi()
0: pi = 2.666666666666667, y = 1.3333333333333333
Out[4]: 2.666666666666667

Also, your indentation is wrong. As written, your function returns after the first iteration. That it probably not what you want?

It should be:

In [7]: def calc_pi():
   ...:     pi = 4
   ...:     for i in range(0, 200):
   ...:         y = 4 / (3 + (2 * i))
   ...:         if i % 2 == 0:
   ...:             pi -= y
   ...:         else:
   ...:             pi += y
   ...:         print("{}: pi = {}, y = {}".format(i, pi, y))
   ...:     return pi
   ...:

In [8]: calc_pi()
0: pi = 2.666666666666667, y = 1.3333333333333333
1: pi = 3.466666666666667, y = 0.8
2: pi = 2.8952380952380956, y = 0.5714285714285714
3: pi = 3.3396825396825403, y = 0.4444444444444444
4: pi = 2.9760461760461765, y = 0.36363636363636365
5: pi = 3.2837384837384844, y = 0.3076923076923077
6: pi = 3.017071817071818, y = 0.26666666666666666
7: pi = 3.2523659347188767, y = 0.23529411764705882
8: pi = 3.0418396189294032, y = 0.21052631578947367
...
195: pi = 3.1466687630233094, y = 0.010178117048346057
196: pi = 3.1365421807448284, y = 0.010126582278481013
197: pi = 3.146617747495458, y = 0.010075566750629723
198: pi = 3.136592684838816, y = 0.010025062656641603
199: pi = 3.1465677471829556, y = 0.00997506234413965
Out[8]: 3.1465677471829556


问:
Typescript: Infer generic type by checking string value
I have types like this:

```<code>export type NotificationType = 'comment' | 'like' | 'message' | 'follow' | unknown

type MessageBody<T extends NotificationType> = T extends 'comment'
  ? {
      body: string
      threadId: string
      projectId: string
    }
  : T extends 'like'
  ? {
      resourceId: string
      resourceType: 'project' | 'projectVersion' | 'thread' | 'comment'
    }
  : T extends 'message'
  ? {
      body: string
      chatId: string
    }
  : T extends 'follow'
  ? {}
  : never

export type Message<T extends NotificationType = unknown> = {
  channel: string
  message: MessageBody<T> & {
    type: T
  }
  timetoken: string | number
  uuid?: string
  publisher?: string
}
</code>```

What I want to do now is infer the type of T by checking the property message.type without having to specify the type of T beforehand, so something like this:

```<code>function checkMessage(message: Message) { // No generic type given
  switch (message.message.type) {
    case 'comment':
      message.message.body // infers to MessageBody<'comment'>
  }
}
</code>```

But with this approach I get an error on the switch statement with:
Property 'type' does not exist on type 'never'.

Which probably comes from the usage of unknown inside the NotificationType. How can I have the generic optional and still infer the type by checking the string?

答:
I'd willing to bet that NotificationType should only be a string. Hence, using unknown is not the best idea for representing unknown string type. It is much better to use just refular  string type. However, using string type with other literal strings like comment and follow will clash them to just a string. This is why t is better to use string & {}.

Also, I have used map data stucture instead conditional type MessageBody.

export type KnownType = 'comment' | 'like' | 'message' | 'follow'

export type UnknownType = string & {}

type NotificationType = KnownType | UnknownType

type MessageMap = {
  comment: {
    body: string
    threadId: string
    projectId: string
  },
  like: {
    resourceId: string
    resourceType: 'project' | 'projectVersion' | 'thread' | 'comment'
  },
  message: {
    body: string
    chatId: string
  },
  follow: {}
}

type MessageBase = {
  channel: string
  timetoken: string | number
  uuid?: string
  publisher?: string
}

type MessageBody<T extends KnownType> = { message: MessageMap[T] & { type: T } } & MessageBase

export type ComputeMessage<T extends NotificationType> = T extends KnownType ? MessageBody<T> : never

function checkMessage<MessageType extends NotificationType>(message: ComputeMessage<MessageType>) {

  switch (message.message.type) {
    case 'comment':
      message.message.projectId // ok
      message.message.threadId // ok
  }
}
```

Playground

Body:
I have types like this:

export type NotificationType = 'comment' | 'like' | 'message' | 'follow' | unknown

type MessageBody<T extends NotificationType> = T extends 'comment'
  ? {
      body: string
      threadId: string
      projectId: string
    }
  : T extends 'like'
  ? {
      resourceId: string
      resourceType: 'project' | 'projectVersion' | 'thread' | 'comment'
    }
  : T extends 'message'
  ? {
      body: string
      chatId: string
    }
  : T extends 'follow'
  ? {}
  : never

export type Message<T extends NotificationType = unknown> = {
  channel: string
  message: MessageBody<T> & {
    type: T
  }
  timetoken: string | number
  uuid?: string
  publisher?: string
}

What I want to do now is infer the type of T by checking the property message.type without having to specify the type of T beforehand, so something like this:

function checkMessage(message: Message) { // No generic type given
  switch (message.message.type) {
    case 'comment':
      message.message.body // infers to MessageBody<'comment'>
  }
}

But with this approach I get an error on the switch statement with:
Property 'type' does not exist on type 'never'.

Which probably comes from the usage of unknown inside the NotificationType. How can I have the generic optional and still infer the type by checking the string?

Body:
I'd willing to bet that NotificationType should only be a string. Hence, using unknown is not the best idea for representing unknown string type. It is much better to use just refular  string type. However, using string type with other literal strings like comment and follow will clash them to just a string. This is why t is better to use string & {}.

Also, I have used map data stucture instead conditional type MessageBody.

export type KnownType = 'comment' | 'like' | 'message' | 'follow'

export type UnknownType = string & {}

type NotificationType = KnownType | UnknownType

type MessageMap = {
  comment: {
    body: string
    threadId: string
    projectId: string
  },
  like: {
    resourceId: string
    resourceType: 'project' | 'projectVersion' | 'thread' | 'comment'
  },
  message: {
    body: string
    chatId: string
  },
  follow: {}
}

type MessageBase = {
  channel: string
  timetoken: string | number
  uuid?: string
  publisher?: string
}

type MessageBody<T extends KnownType> = { message: MessageMap[T] & { type: T } } & MessageBase

export type ComputeMessage<T extends NotificationType> = T extends KnownType ? MessageBody<T> : never

function checkMessage<MessageType extends NotificationType>(message: ComputeMessage<MessageType>) {

  switch (message.message.type) {
    case 'comment':
      message.message.projectId // ok
      message.message.threadId // ok
  }
}

Playground


答:
The code below the return can't be reached try this.</p>
```<code>def calc_pi():
    pi = 4
    for i in range (0,200):
        y = 4/(3+(2*i))
        if i % 2 == 0:
            pi -= y
        else:
            pi += y
        print("{}: pi = {}, y = {}".format( i, pi, y))
    return pi
</code>```

Title: Python function won't print

Body:
The code below the return can't be reached try this.

def calc_pi():
    pi = 4
    for i in range (0,200):
        y = 4/(3+(2*i))
        if i % 2 == 0:
            pi -= y
        else:
            pi += y
        print("{}: pi = {}, y = {}".format( i, pi, y))
    return pi


问:
can somebody explain what this function does?
I am doing online coding questions, and this is the recommended format to take inputs from the website:

```<code>numStudents = map(int, input().split())
</code>```

I'm also wondering how I'm meant to know what type of output the website is giving if they're not directly telling me.

答:
map() function takes 2 arguments: First a function and then an iterable. It applies the function to each element in the iterable and returns a new iterable.

split() function takes a single parameter: Which character/string to split the string with. If none is specified then it defaults to whitespace(' ').

input() just asks the user to enter a line. It interprets everything as a singular string.

```<code>numStudents = map(int, input().split())
</code>```

So this code asks the user to enter a line, splits this string based on whitespace and then converts each of those splitted strings to int and returns it as a new map object. It is usually followed by list() function like this to convert it into a list:

```<code>numStudents = list(map(int, input().split()))
</code>```

Body:
I am doing online coding questions, and this is the recommended format to take inputs from the website:

numStudents = map(int, input().split())

I'm also wondering how I'm meant to know what type of output the website is giving if they're not directly telling me.

Body:
map() function takes 2 arguments: First a function and then an iterable. It applies the function to each element in the iterable and returns a new iterable.

split() function takes a single parameter: Which character/string to split the string with. If none is specified then it defaults to whitespace(' ').

input() just asks the user to enter a line. It interprets everything as a singular string.

numStudents = map(int, input().split())

So this code asks the user to enter a line, splits this string based on whitespace and then converts each of those splitted strings to int and returns it as a new map object. It is usually followed by list() function like this to convert it into a list:

numStudents = list(map(int, input().split()))


问:
MongoDB - how can I pass variable or expression to $limit aggregation pipeline?
I use this expression for limiting the number of documents, but Mongo seems not accept it (in the official document, $limit only allow Integer value). But is there any tricks to get it?</p>
```<code>{ $limit: '$numQuestion', },
</code>```

答:
So you mean this?</p>
```<code>numQuestion = 10;
{ $limit: numQuestion  },
</code>```

Body:
I use this expression for limiting the number of documents, but Mongo seems not accept it (in the official document, $limit only allow Integer value). But is there any tricks to get it?

{ $limit: '$numQuestion', },

Body:
So you mean this?

numQuestion = 10;
{ $limit: numQuestion  },


问:
Tools and techniques for effective use of feature toggles in .NET
I have read a lot about feature toggles but have no practical experience of using them. What tools and techniques do people recommend for effective management of feature toggles?

I imagine the simplest way would be to store toggles as true/false values in the web.config file as appSettings but this doesn't sound a particularly good method.

Ideally I would like any method of managing feature toggles to:

Flag any uses of the toggle on removal. E.g. A compilation error

Highlight any old toggles. I.e. A toggle that is still in place after the feature has been released

答:
One suggestion from a colleague is to store them in a .settings file. The advantage of this is that if you delete a toggle you get compiler errors anywhere the toggle has been used so you can be certain it's been completely removed from the code.

It's also possible to use some simple techniques to do feature toggling. It's not big or clever, but it's straight forward and it works.

UPDATE

Since asking this question I've had some more experience using feature toggles. I've looked at a few of the open source tools available and written about another simple database driven toggling mechanism I've used at work.


问:
Why does the result of #pragma omp parallel look like this
```<code>    #include<stdio.h>

    int main()
    {
        int a=0, b=0;
        #pragma omp parallel num_threads(16)
        {
            // #pragma omp single
            a++;
            // #pragma omp critical
            b++;
        }
        printf("single: %d -- critical: %d\n", a, b);
    }
</code>```

Why is my output single: 5 -- critical: 5 here?

And why is it output single: 3 -- critical: 3 when num_threads(4)?

I should not code anything like this, right? If the threads are confused here (I guess), why the result is consistent?

答:
You have race conditions, therefore the values of a and b are undefined. To correct it you can

a) use reduction (it is the best solution):

```<code>#pragma omp parallel num_threads(16) reduction(+:a,b)
</code>```

b) use atomic operations (generally it is less efficient):

```<code>#pragma omp atomic
   a++;
#pragma omp atomic
   b++;
</code>```

c) use critical section (i.e. locks, which is the worst solution):

```<code>#pargma omp critical
{
   a++;
   b++;
}
</code>```

Body:
    #include<stdio.h>

    int main()
    {
        int a=0, b=0;
        #pragma omp parallel num_threads(16)
        {
            // #pragma omp single
            a++;
            // #pragma omp critical
            b++;
        }
        printf("single: %d -- critical: %d\n", a, b);
    }

Why is my output single: 5 -- critical: 5 here?

And why is it output single: 3 -- critical: 3 when num_threads(4)?

I should not code anything like this, right? If the threads are confused here (I guess), why the result is consistent?

Body:
You have race conditions, therefore the values of a and b are undefined. To correct it you can

a) use reduction (it is the best solution):

#pragma omp parallel num_threads(16) reduction(+:a,b)

b) use atomic operations (generally it is less efficient):

#pragma omp atomic
   a++;
#pragma omp atomic
   b++;

c) use critical section (i.e. locks, which is the worst solution):

#pargma omp critical
{
   a++;
   b++;
}


问:
How to get href using innertext and regex
How to get Href from the  tag.

how to get href link using selectors, I have tried like below but it didn't work.

expected to get "www.test.com/all_reviews"

var a = document.querySelectorAll("a[href =*'all_reviews'*]")
console.log(a)```
<pre class="snippet-code-html lang-html prettyprint-override"><code>All Reviews
All Reviews</code>```

答:
To access the href you should use getAttribute of the selected element

let anchors = document.querySelectorAll('a[href*="all_reviews"]');
let link = null;
Array.from(anchors).forEach(element => {
    let pattern = /all_reviews$/;
    let url = element.getAttribute('href');
    if(pattern.test(url)) {
      link = url;
    }
});

console.log(link);```
<pre class="snippet-code-html lang-html prettyprint-override"><code>All Reviews
All Reviews</code>```

You can use a Regular expression which check if the link and with all_reviews as the second link all_reviews is not at the end of the URL.

Body:
How to get Href from the  tag.

how to get href link using selectors, I have tried like below but it didn't work.

expected to get "www.test.com/all_reviews"

var a = document.querySelectorAll("a[href =*'all_reviews'*]")
console.log(a)

All Reviews
All Reviews

Body:
To access the href you should use getAttribute of the selected element

let anchors = document.querySelectorAll('a[href*="all_reviews"]');
let link = null;
Array.from(anchors).forEach(element => {
    let pattern = /all_reviews$/;
    let url = element.getAttribute('href');
    if(pattern.test(url)) {
      link = url;
    }
});

console.log(link);

<a href="www.test.com/all_reviews">All Reviews</a>
<a href="www.test.com/all_reviews/altered">All Reviews</a>

You can use a Regular expression which check if the link and with all_reviews as the second link all_reviews is not at the end of the URL.


问:
Escape special characters in XQuery or XSLT
I have an xml that has uname and pwd. The pwd has special characters like ‘&’.

I am using a XQuery or XSLT to transform it.. the output generated should have exact password and not &.

Is there a way I can do that?

```<code><uname>xyz</uname>
<pwd>12a&ad&12</pwd>
</code>```

Output after transformation should exactly same

(I am doing this in OSB, so when I test through OSB it doesn't allow me to, so I am using SoapUI to validate ut, but at the first stage itself it fails to handle it)

Can someone please guide me with the escaping special characters or XQuery or XSLT functions for this

Thanks

答:
XQuery and XSLT are both designed for processing well-formed XML, and your input is not well-formed XML, so it cannot be processed using these languages. To make it well-formed XML, it needs to be written

```<code><data>
  <uname>xyz</uname>
  <pwd>12a&ad&12</pwd>
</data>
</code>```

Similarly, the output will always be well-formed XML.

Body:
I have an xml that has uname and pwd. The pwd has special characters like ‘&’.

I am using a XQuery or XSLT to transform it.. the output generated should have exact password and not &.

Is there a way I can do that?

<uname>xyz</uname>
<pwd>12a&ad&12</pwd>

Output after transformation should exactly same

(I am doing this in OSB, so when I test through OSB it doesn't allow me to, so I am using SoapUI to validate ut, but at the first stage itself it fails to handle it)

Can someone please guide me with the escaping special characters or XQuery or XSLT functions for this

Thanks

Body:
XQuery and XSLT are both designed for processing well-formed XML, and your input is not well-formed XML, so it cannot be processed using these languages. To make it well-formed XML, it needs to be written

<data>
  <uname>xyz</uname>
  <pwd>12a&amp;ad&amp;12</pwd>
</data>

Similarly, the output will always be well-formed XML.


问:
php - is there some built-in way to get the last matched pattern?
```<code>echo preg_replace("/f(o)o/", 'b$1r', 'This is foo.');

$var = ???   // here I want to get what $1 captured
</code>```

For "built-in" I mean some PHP special variable, like Ruby's $1.

If PHP hasn't a proper way to get that, what is the best way to achieve it?

Body:
echo preg_replace("/f(o)o/", 'b$1r', 'This is foo.');

$var = ???   // here I want to get what $1 captured

For "built-in" I mean some PHP special variable, like Ruby's $1.

If PHP hasn't a proper way to get that, what is the best way to achieve it?


问:
How to query fields in elasticsearch?
I try to do some query with fields mapping but it not working.

define index mapping

```<code>english_mapping = {
 "mappings": {
    "properties": {
      "text": {
        "type": "text",
        "fields": {
          "english": {
            "type":     "text",
            "analyzer": "english"
          }
        }
      }
    }
  }
}

es.indices.create(index = 'english', body = english_mapping)
</code>```

add some data

```<code>doc2 = { "text": "quick brown fox" }
doc3 = { "text": "quick brown foxes" }
es.index(index='english', document = doc2, id = 1)
es.index(index='english', document = doc3, id = 2)
</code>```

query on text.english field but it not working (it return both document)

```<code>res = es.search(index = 'english',  body = {"query": {
    "match": {
        "text.english" : "foxes"
    }
}})
</code>```

Please help me how to query on text.english field.

答:
The english analyzer you're using is composed of an english_stemmer token filter, and what this does is stemming words, like for instance foxes gets' stemmed to fox.

Hence, both of your documents below get analyzed/stemmed the same way

```<code>doc2 = { "text": "quick brown fox" }
doc3 = { "text": "quick brown foxes" }
</code>```

i.e. the following tokens get indexed: quick, brown and fox.

Same thing at search time when searching for foxes, it's gets analyzed to fox and that's the reason why it finds both documents.

If you search on the text field instead of text.english, the standard analyzer will be used instead and no stemming occurs, so it will work as you expect.

Title: How to query fields in elasticsearch?

Body:
I try to do some query with fields mapping but it not working.

define index mapping

english_mapping = {
 "mappings": {
    "properties": {
      "text": {
        "type": "text",
        "fields": {
          "english": {
            "type":     "text",
            "analyzer": "english"
          }
        }
      }
    }
  }
}

es.indices.create(index = 'english', body = english_mapping)

add some data

doc2 = { "text": "quick brown fox" }
doc3 = { "text": "quick brown foxes" }
es.index(index='english', document = doc2, id = 1)
es.index(index='english', document = doc3, id = 2)

query on text.english field but it not working (it return both document)

res = es.search(index = 'english',  body = {"query": {
    "match": {
        "text.english" : "foxes"
    }
}})

Please help me how to query on text.english field.

Body:
The english analyzer you're using is composed of an english_stemmer token filter, and what this does is stemming words, like for instance foxes gets' stemmed to fox.

Hence, both of your documents below get analyzed/stemmed the same way

doc2 = { "text": "quick brown fox" }
doc3 = { "text": "quick brown foxes" }

i.e. the following tokens get indexed: quick, brown and fox.

Same thing at search time when searching for foxes, it's gets analyzed to fox and that's the reason why it finds both documents.

If you search on the text field instead of text.english, the standard analyzer will be used instead and no stemming occurs, so it will work as you expect.


问:
How to parse JSON in Java
I have the following JSON text. How can I parse it to get the values of pageName, pagePic, post_id, etc.?

{
  "pageInfo": {
    "pageName": "abc",
    "pagePic": "http://example.com/content.jpg"
  },
  "posts": [
    {
      "post_id": "123456789012_123456789012",
      "actor_id": "1234567890",
      "picOfPersonWhoPosted": "http://example.com/photo.jpg",
      "nameOfPersonWhoPosted": "Jane Doe",
      "message": "Sounds cool. Can't wait to see it!",
      "likesCount": "2",
      "comments": [],
      "timeOfPost": "1234567890"
    }
  ]
}
```

答:
Any kind of json array
steps to solve the issue.

Convert your JSON object to a java object.

You can use this link or any online tool.

Save out as a java class like Myclass.java.

Myclass obj = new Gson().fromJson(JsonStr, Myclass.class);

Using obj, you can get your values.

Title: How to parse JSON in Java


问:
Circular background of flutter widget as progressbar
this is Antika. I have started learning to code since a few days back, and am only familiar with HTML/CSS/JS, and basics of dart/flutter

Developer Level: Beginner

Project type & language: I am developing a Study planner app  for myself, using flutter.

Problem - I have tried many ways to create a widget, that has the details of the task,with a progress bar - like background.

SOMETHING LIKE THIS (WIDGET)-

How do I create a Widget like this with flutter.

答:
LinearProgressIndicator can be wrapped with SizedBox.

ClipRRect(
    borderRadius: BorderRadius.circular(12), // have border decoration
    child: Stack(
      // you may need to wrap with sizedBOx
      children: [
        SizedBox(
          height: 100, //stack size, or use fit
          width: 400,
          child: LinearProgressIndicator(
            value: sliderValue,
          ),
        )

        //place your widget
      ],
    )),
```


问:
python discord bot sleep to stop people spamming
when trying the make the bot sleep for 5 seconds before it replies again. but i can continue spamming "down" and bot replies

```<code>import os
import random
import discord
import time

keywords3 = ['down']

@client.event
async def on_message(message):
global cooldown

if message.author == client.user:
    return

 messC = message.content.lower()

if any(word in messC for word in keywords3):
    await message.channel.send('hello')
    await asyncio.sleep(5)
</code>```

`

答:
i'm not familiar with the discord api but this should do what you want

cooling_down = False
eventually_cool_up_task = None

async def eventually_cool_up(wait):
    global cooling_down

    await asyncio.sleep(wait)
    cooling_down = False

@client.event
async def on_message(message):
    global cooling_down, eventually_cool_up_task

    if message.author == client.user:
        return

    messC = message.content.lower()

    if any(word in messC for word in keywords3):
        if not cooling_down:
            cooling_down = True
            await message.channel.send('hello')
            eventually_cool_up_task = asyncio.create_task(eventually_cool_up(5))

```

Body:
when trying the make the bot sleep for 5 seconds before it replies again. but i can continue spamming "down" and bot replies

import os
import random
import discord
import time

keywords3 = ['down']

@client.event
async def on_message(message):
global cooldown

if message.author == client.user:
    return

 messC = message.content.lower()

if any(word in messC for word in keywords3):
    await message.channel.send('hello')
    await asyncio.sleep(5)

`


答:
You could use the jquery :contains() selector like this:

```<code> $("a:contains(All Reviews)")
</code>```

See a code example and read more about it here: https://api.jquery.com/contains-selector/

Title: How to get href using innertext and regex

Body:
You could use the jquery :contains() selector like this:

 $("a:contains(All Reviews)")

See a code example and read more about it here: https://api.jquery.com/contains-selector/