问:
Is there a design pattern that supports injections of several abstract class implementations and conditionally uses one of the injected beans
I am on a project using Java and Spring Boot that processes several different message types from the same queue. Each message gets processed conditionally based on the message type, using an implementation of MessageProcessingService abstract class for each message type.

As of now, we have 5 different message types coming into the same consumer.  We are using the same queue because we leverage group policies in JMS, and each message type has the same business key as the group policy.

So what we end up with is that every time a requirement requires receiving a new message type, we add a new implementation of a MessageProcessingService and another dependency to the consumer object.  I want to find a better strategy to selectively choose the message processing

Here is an example similar to what we are doing. I do not guarantee the syntax is compilable or syntactically perfect, just demonstrating the problem. Notice all the messages resolve around a person

Consumer:

@Component
public class PersonMessageConsumer {
  private MessageProcessingService<HeightUpdate> heightUpdateMessageProcessingService;
  private MessageProcessingService<WeightUpdate> weightUpdateMessageProcessingService;
  private MessageProcessingService<NameUpdate>   nameUpdateMessageProcessingService;
  private MessageProcessingService<ShowSizeUpdate> shoeSizeUpdateMessageProcessingService;

  public PersonMessageConsumer(
         MessageProcessingService<HeightUpdate> heightUpdateMessageProcessingService,
         MessageProcessingService<WeightUpdate> weightUpdateMessageProcessingService,
         MessageProcessingService<NameUpdate>   nameUpdateMessageProcessingService,
         MessageProcessingService<ShowSizeUpdate> shoeSizeUpdateMessageProcessingService) {

    this.heightUpdateMessageProcessingService = heightUpdateMessageProcessingService;
    this.weightUpdateMessageProcessingService = weightUpdateMessageProcessingService;
    this.nameUpdateMessageProcessingService = nameUpdateMessageProcessingService;
    this.shoeSizeUpdateMessageProcessingService = shoeSizeUpdateMessageProcessingService;
  }

  @JmsListener(destination = "${queueName}")
  public void receiveMessage(TextMessage message) {
    String messageType = message.getHeader("MessageType");
    switch (messageType) {
      case "HeightUpdate":
        heightUpdateMessageProcessingService.processMessage(message.getText());
        return;
      case "WeightUpdate":
        weightUpdateMessageProcessingServivce.processMessage(message.getText());
        return;
      // And other message types
      default:
        throw new UnknownMessageTypeException(messageType);
  }
}
```

<p>Message POJO example</p>

<pre class="lang-java prettyprint-override"><code>public class HeightUpdate implements PersonMessage {
  @Getter
  @Setter
  private int height;
}
</code>```

PersonMessage interface

public interface PersonMessage {
  int getPersonId();
}
```

<p>MessageProcessingService </p>

<pre class="lang-java prettyprint-override"><code>public abstract class MessageProcessingService<T extends PersonMessage> {

  public void processMessage(String messageText) {
    //Common message processing, we do some more involved work here but just as a simple example
    T message = new ObjectMapper.readValue(messageText, getClassType());

    Person person = personRepository.load(message.getPersonId());
    Person originalPerson = person.deepCopy();
    processMessageLogic(person, message);

    if (originalPerson.isDifferentFrom(person)) {
      personRespository.update(person);
    }
  }

  protected abstract void processMessageLogic(Person person, T message);

  protected abstract Class getClassType();
}
</code>```

Abstract class implementation example

@Service("heightUpdateMessageProcessingService")
public class HeightUpdateMessageProcessingService extends MessageProcessingService<HeightUpdate> {
  @Override
  protected void processMessageLogic(Person person, HeightUpdate update) {
    person.setHeight(update.getHeight());
  }

  @Override
  protected Class getMessageType() {
    return HeightUpdate.getClass();
  }
}
```

So my question is whether or not there is a better design pattern or way of coding this in java and spring that is a little easier to clean and maintain and keeps SOLID principles in mind

答:
Add an abstract method in the MessageProcessingService to return the messageType that each concrete implementation can handle.

Rather than wiring each individual service into PersonMessageConsumer, wire in a List<MessageProcessingService> so that you get all of them at once.

Transform that List into a Map<String, MessageProcessingService>, using the messageType as the key.

Replace the switch statement by looking up the appropriate service in the Map and then invoking its processMessage method.

In the future you can add new instances of MessageProcessingService without having to edit PersonMessageConsumer because Spring will automatically add those new instances to the List<MessageProcessingService> that you wire in.

Body:
I am on a project using Java and Spring Boot that processes several different message types from the same queue. Each message gets processed conditionally based on the message type, using an implementation of MessageProcessingService abstract class for each message type.

As of now, we have 5 different message types coming into the same consumer.  We are using the same queue because we leverage group policies in JMS, and each message type has the same business key as the group policy.

So what we end up with is that every time a requirement requires receiving a new message type, we add a new implementation of a MessageProcessingService and another dependency to the consumer object.  I want to find a better strategy to selectively choose the message processing

Here is an example similar to what we are doing. I do not guarantee the syntax is compilable or syntactically perfect, just demonstrating the problem. Notice all the messages resolve around a person

Consumer:

@Component
public class PersonMessageConsumer {
  private MessageProcessingService<HeightUpdate> heightUpdateMessageProcessingService;
  private MessageProcessingService<WeightUpdate> weightUpdateMessageProcessingService;
  private MessageProcessingService<NameUpdate>   nameUpdateMessageProcessingService;
  private MessageProcessingService<ShowSizeUpdate> shoeSizeUpdateMessageProcessingService;

  public PersonMessageConsumer(
         MessageProcessingService<HeightUpdate> heightUpdateMessageProcessingService,
         MessageProcessingService<WeightUpdate> weightUpdateMessageProcessingService,
         MessageProcessingService<NameUpdate>   nameUpdateMessageProcessingService,
         MessageProcessingService<ShowSizeUpdate> shoeSizeUpdateMessageProcessingService) {

    this.heightUpdateMessageProcessingService = heightUpdateMessageProcessingService;
    this.weightUpdateMessageProcessingService = weightUpdateMessageProcessingService;
    this.nameUpdateMessageProcessingService = nameUpdateMessageProcessingService;
    this.shoeSizeUpdateMessageProcessingService = shoeSizeUpdateMessageProcessingService;
  }

  @JmsListener(destination = "${queueName}")
  public void receiveMessage(TextMessage message) {
    String messageType = message.getHeader("MessageType");
    switch (messageType) {
      case "HeightUpdate":
        heightUpdateMessageProcessingService.processMessage(message.getText());
        return;
      case "WeightUpdate":
        weightUpdateMessageProcessingServivce.processMessage(message.getText());
        return;
      // And other message types
      default:
        throw new UnknownMessageTypeException(messageType);
  }
}

Message POJO example

public class HeightUpdate implements PersonMessage {
  @Getter
  @Setter
  private int height;
}

PersonMessage interface

public interface PersonMessage {
  int getPersonId();
}

MessageProcessingService

public abstract class MessageProcessingService<T extends PersonMessage> {

  public void processMessage(String messageText) {
    //Common message processing, we do some more involved work here but just as a simple example
    T message = new ObjectMapper.readValue(messageText, getClassType());

    Person person = personRepository.load(message.getPersonId());
    Person originalPerson = person.deepCopy();
    processMessageLogic(person, message);

    if (originalPerson.isDifferentFrom(person)) {
      personRespository.update(person);
    }
  }

  protected abstract void processMessageLogic(Person person, T message);

  protected abstract Class getClassType();
}

Abstract class implementation example

@Service("heightUpdateMessageProcessingService")
public class HeightUpdateMessageProcessingService extends MessageProcessingService<HeightUpdate> {
  @Override
  protected void processMessageLogic(Person person, HeightUpdate update) {
    person.setHeight(update.getHeight());
  }

  @Override
  protected Class getMessageType() {
    return HeightUpdate.getClass();
  }
}

So my question is whether or not there is a better design pattern or way of coding this in java and spring that is a little easier to clean and maintain and keeps SOLID principles in mind


来源: stackexchange

问:
input fields keeping the same information entered previously
I'm working on a web development assignment and i'm a little stuck, so i have 2 pages, the first one is formulaire.html which contains a form that sends informations to my second page which is recap.php, and in that page i have a button that must send me back to the form page with all the informations entered previously still there, i can't use any php in the first page it must remain .html, i was thinking of creating a modify.js file but i would have to get my $_SESSION variables in it, which i don't know if it's possible, if anyone can help me out it'd be great.</p>

答:
did you try to use localStorage in javascript???</p>

```<code>localStorage.setItem("key", "value");
var key = localStorage.getItem("key");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
did you try to use localStorage in javascript???

localStorage.setItem("key", "value");
var key = localStorage.getItem("key");


问:
FETCH/ROWNUM() first n percent from each BRANCH (BRANCH_NO). I am trying to retrieve top 10 percent of each branch
```<code> SELECT e.EMPLOYEE_NO, e.FNAME, e.LNAME, b.BRANCH_NO, o.SUBTOTAL,
     PERCENT_RANK() OVER ( partition by e.EMPLOYEE_NO ORDER BY e.EMPLOYEE_NO ASC) AS percent
 FROM EMPLOYEE e
 INNER JOIN BRANCH b
  ON e.BRANCH_NO = b.BRANCH_NO
 INNER JOIN ORDERS o
  ON o.BRANCH_NO = b.BRANCH_NO
 ORDER BY b.BRANCH_NO
 FETCH FIRST 10 PERCENT ROWS ONLY;
</code>```

I am trying to retrieve top 10 percent of each branch.

PL SQL

答:
You can use analytical functions as following:

```<code>Select employee_no,
       Fname,
       Lname,
       employee_total_order,
       Branch_no
From
(SELECT e.EMPLOYEE_NO, e.FNAME, e.LNAME, b.BRANCH_NO,
        SUM(o.SUBTOTAL) AS employee_total_order,
        Count(distinct e.employee_no)
         over (partition by b.branch_no) as total_emp,
        Row_number()
         over (partition by b.branch_no order by SUM(o.SUBTOTAL) desc nulls last) as rn
 FROM EMPLOYEE e
 INNER JOIN BRANCH b
  ON e.BRANCH_NO = b.BRANCH_NO
 INNER JOIN ORDERS o
  ON o.BRANCH_NO = b.BRANCH_NO
 Group by e.EMPLOYEE_NO, e.FNAME, e.LNAME, b.BRANCH_NO)
Where rn/total_emp <= 0.1
      or rn = 1 -- this condition is used to fetch atleast one employee
                -- if branch has less than 10 employees
</code>```

Cheers!!

Body:
 SELECT e.EMPLOYEE_NO, e.FNAME, e.LNAME, b.BRANCH_NO, o.SUBTOTAL,
     PERCENT_RANK() OVER ( partition by e.EMPLOYEE_NO ORDER BY e.EMPLOYEE_NO ASC) AS percent
 FROM EMPLOYEE e
 INNER JOIN BRANCH b
  ON e.BRANCH_NO = b.BRANCH_NO
 INNER JOIN ORDERS o
  ON o.BRANCH_NO = b.BRANCH_NO
 ORDER BY b.BRANCH_NO
 FETCH FIRST 10 PERCENT ROWS ONLY;

I am trying to retrieve top 10 percent of each branch.

PL SQL

Body:
You can use analytical functions as following:

Select employee_no,
       Fname,
       Lname,
       employee_total_order,
       Branch_no
From
(SELECT e.EMPLOYEE_NO, e.FNAME, e.LNAME, b.BRANCH_NO,
        SUM(o.SUBTOTAL) AS employee_total_order,
        Count(distinct e.employee_no)
         over (partition by b.branch_no) as total_emp,
        Row_number()
         over (partition by b.branch_no order by SUM(o.SUBTOTAL) desc nulls last) as rn
 FROM EMPLOYEE e
 INNER JOIN BRANCH b
  ON e.BRANCH_NO = b.BRANCH_NO
 INNER JOIN ORDERS o
  ON o.BRANCH_NO = b.BRANCH_NO
 Group by e.EMPLOYEE_NO, e.FNAME, e.LNAME, b.BRANCH_NO)
Where rn/total_emp <= 0.1
      or rn = 1 -- this condition is used to fetch atleast one employee
                -- if branch has less than 10 employees

Cheers!!


问:
Visibility of villages in Mapbox
In my Mapbox GL project, I have a layer with towns and villages which looks like this:

```<code>{
            "id": "towns",
            "type": "symbol",
            "source": "composite",
            "source-layer": "place_label",
            "minzoom": 1,
            "maxzoom": 14,
            "filter": [
                "all",
                [
                  "match",
                  ["get", "type"],
                  ["town", "village", "hamlet"],
                  true,
                  false
                ],
                ["match", ["get", "name"], [
                  // list of villages
                ], true, false]
            ],
            "layout": {
                "text-variable-anchor": ["top", "bottom", "left", "right"],
                "text-allow-overlap": true,
                "text-ignore-placement": true,
                "icon-allow-overlap": true,
                "text-field": ["get", "name"],
                "text-font": ["Roboto Regular", "Arial Unicode MS Regular"],
                "text-size": [
                    "interpolate",
                    ["linear"],
                    ["zoom"],
                    3,
                    8,
                    22,
                    16
                ]
            },
            "paint": {
                "text-halo-color": "hsla(0, 0%, 100%, 0.95)",
                "text-halo-width": 1,
                "text-halo-blur": 0.4
            }
        },
</code>```

The text-size zoom interpolation works fine for the towns. However, the village will only show up after a zoomlevel of 9. Is there any way I could make the villages visible at all time?

答:
Most likely, the Mapbox Streets Tileset you're using only includes those villages in the data after zoom 9, so there is nothing you can do in the style to make it show up earlier.

You'd need to create your own dataset which includes the data you want at lower zoom levels (and maybe just check this is the cause first in Mapbox Studio data view).

Title: Visibility of villages in Mapbox

Body:
In my Mapbox GL project, I have a layer with towns and villages which looks like this:

{
            "id": "towns",
            "type": "symbol",
            "source": "composite",
            "source-layer": "place_label",
            "minzoom": 1,
            "maxzoom": 14,
            "filter": [
                "all",
                [
                  "match",
                  ["get", "type"],
                  ["town", "village", "hamlet"],
                  true,
                  false
                ],
                ["match", ["get", "name"], [
                  // list of villages
                ], true, false]
            ],
            "layout": {
                "text-variable-anchor": ["top", "bottom", "left", "right"],
                "text-allow-overlap": true,
                "text-ignore-placement": true,
                "icon-allow-overlap": true,
                "text-field": ["get", "name"],
                "text-font": ["Roboto Regular", "Arial Unicode MS Regular"],
                "text-size": [
                    "interpolate",
                    ["linear"],
                    ["zoom"],
                    3,
                    8,
                    22,
                    16
                ]
            },
            "paint": {
                "text-halo-color": "hsla(0, 0%, 100%, 0.95)",
                "text-halo-width": 1,
                "text-halo-blur": 0.4
            }
        },

The text-size zoom interpolation works fine for the towns. However, the village will only show up after a zoomlevel of 9. Is there any way I could make the villages visible at all time?


问:
Pattern matching on records in F#
Is there a more idiomatic way how to do pattern matching on records? My code just doesn't seem right.</p>

```<code>type Period = AM | PM

type TimeOfDay = {hours : int; minutes : int; p : Period}

let before (tod1 : TimeOfDay, tod2 : TimeOfDay) =
   match tod1, tod2 with
   | {hours = h1; minutes = m1; p = AM}, {hours = h2; minutes = m2; p = AM} -> (h1, m1) < (h2, m2)
   | {hours = h1; minutes = m1; p = PM}, {hours = h2; minutes = m2; p = PM} -> (h1, m1) < (h2, m2)
   | {hours = _; minutes = _; p = AM}, {hours = _; minutes = _; p = PM} -> true
   | {hours = _; minutes = _; p = PM}, {hours = _; minutes = _; p = AM} -> false
</code>```

答:
you can remove the properties that you dont need on the match, use "guards" (when clauses) to check if both pproperties are equals, and create a local function to simplify tuple comparasion.

```<code>let before (tod1: TimeOfDay, tod2: TimeOfDay) =
   let getTime tod = (tod.hours, tod.minutes)
   match tod1, tod2 with
   | { p = x }, { p = y } when x = y -> getTime tod1 < getTime tod2
   | { p = AM }, _ -> true
   | _ -> false
</code>```

or to remove the last pattern just do

```<code>let before (tod1: TimeOfDay, tod2: TimeOfDay) =
   let getTime tod = (tod.hours, tod.minutes)
   match tod1, tod2 with
   | { p = x }, { p = y } when x = y -> getTime tod1 < getTime tod2
   | { p = x }, _ -> x = AM
</code>```

ContentLicense: CC BY-SA 3.0

Title: Pattern matching on records in F#

Body:
Is there a more idiomatic way how to do pattern matching on records? My code just doesn't seem right.

type Period = AM | PM

type TimeOfDay = {hours : int; minutes : int; p : Period}

let before (tod1 : TimeOfDay, tod2 : TimeOfDay) =
   match tod1, tod2 with
   | {hours = h1; minutes = m1; p = AM}, {hours = h2; minutes = m2; p = AM} -> (h1, m1) < (h2, m2)
   | {hours = h1; minutes = m1; p = PM}, {hours = h2; minutes = m2; p = PM} -> (h1, m1) < (h2, m2)
   | {hours = _; minutes = _; p = AM}, {hours = _; minutes = _; p = PM} -> true
   | {hours = _; minutes = _; p = PM}, {hours = _; minutes = _; p = AM} -> false

Body:
you can remove the properties that you dont need on the match, use "guards" (when clauses) to check if both pproperties are equals, and create a local function to simplify tuple comparasion.

let before (tod1: TimeOfDay, tod2: TimeOfDay) =
   let getTime tod = (tod.hours, tod.minutes)
   match tod1, tod2 with
   | { p = x }, { p = y } when x = y -> getTime tod1 < getTime tod2
   | { p = AM }, _ -> true
   | _ -> false

or to remove the last pattern just do

let before (tod1: TimeOfDay, tod2: TimeOfDay) =
   let getTime tod = (tod.hours, tod.minutes)
   match tod1, tod2 with
   | { p = x }, { p = y } when x = y -> getTime tod1 < getTime tod2
   | { p = x }, _ -> x = AM


问:
Powershell-ImportVM Command Compare VM returns the expected result, but when using import-vm inside the script it throws an error
```<code>Compare-VM

PS C:\San\SV65\ps> Compare-VM -Path 'C:\San\SV65\hyper-packer\hyper-packer\output-centos8-9\Virtual Machines\FEEBFC7A-7AB7-4C57-A3D4-B3C5593F8FF7.vmcx'
DEBUG:    1+  >>>> Compare-VM -Path 'C:\San\SV65\hyper-packer\hyper-packer\output-centos8-9\Virtual
Machines\FEEBFC7A-7AB7-4C57-A3D4-B3C5593F8FF7.vmcx'
DEBUG:     ! CALL function '<ScriptBlock>'

VM                 : VirtualMachine (Name = 'packer-centos8-base-g2-9') [Id = 'feebfc7a-7ab7-4c57-a3d4-b3c5593f8ff7']
OperationType      : ImportVirtualMachine
Destination        : F06E0BBCFD35P
Path               : C:\San\SV65\hyper-packer\hyper-packer\output-centos8-9\Virtual
                     Machines\FEEBFC7A-7AB7-4C57-A3D4-B3C5593F8FF7.vmcx
SnapshotPath       : C:\San\SV65\hyper-packer\hyper-packer\output-centos8-9\Snapshots
VhdDestinationPath : C:\San\SV65\hyper-packer\hyper-packer\output-centos8-9\Virtual Hard Disks
VhdSourcePath      :
Incompatibilities  : {}
CheckpointPath     : C:\San\SV65\hyper-packer\hyper-packer\output-centos8-9\Snapshots
</code>```

But when using through scripts

```<code> Import-VM -Path 'C:\San\SV65\hyper-packer\hyper-packer\output-centos8-9\Virtual Machines\FEEBFC7A-7AB7-4C57-A3D4-B3C5593F8FF7.vmcx' -Copy -VhdSourcePath 'C:\San\SV65\hyper-packer\hyper-packer\output-centos8-9\Virtual Hard Disks\packer-centos8-base-g2-9.vhdx' -Confirm
</code>```

It returns a error

```<code>Import-VM : Unable to import virtual machine due to configuration errors.  Please use Compare-VM to repair the virtual machine.
At C:\San\SV65\ps\Import-VM.ps1:26 char:3
+   Import-VM -Path 'C:\San\SV65\hyper-packer\hyper-packer\output-cento ...
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Import-VM], VirtualizationException
    + FullyQualifiedErrorId : OperationFailed,Microsoft.HyperV.PowerShell.Commands.ImportVM
</code>```

Any help ?

答:
Import-VM -Path 'C:\San\SV65\hyper-packer\hyper-packer\output-centos8-9\Virtual Machines\FEEBFC7A-7AB7-4C57-A3D4-B3C5593F8FF7.vmcx' -Copy

works well not with the -vhd


问:
envelope for Foxall Jfox giving "error in Hest" in R spatstat
I want to explore the distance of points in a point pattern to the nearest polygon in a polygon shapefile.

Using the R package spatstat, my approach is to calculate the envelope for the function Jfox that consider the distance of my points to the polygons.

My full dataset include point patterns from multiple sites, and I have been successfully using this approach with several sites.

However, when running the envelope on a particular site I get this error:

```<code>Generating 99 simulations of CSR with fixed number of points  ...
Error : in Hest(X,r) the successive r values must be finely spaced: given spacing = 0.0043766; required spacing <=  0.00393
In addition: Warning messages:
1: In resolve.foxall.window(X, Y, W) :
  Trimming the window of X to be a subset of the Frame of Y
2: In resolve.foxall.window(X, Y, W) :
  Trimming the window of X to be a subset of the Frame of Y
[retrying]
Error : in Hest(X,r) the successive r values must be finely spaced: given spacing = 0.0043766; required spacing <=  0.00393
In addition: Warning message:
In resolve.foxall.window(X, Y, W) :
  Trimming the window of X to be a subset of the Frame of Y
[retrying]
... and so on.
</code>```

I cannot figure out what is causing the issue.

Reproducible example:

Datafiles can be found here:

https://www.dropbox.com/sh/fzucl5f6u4s2igx/AAAzgf2Fn-L9cfwzSCwj1RbPa?dl=0

please adapt the code for importing the data according to where you store the files.

```<code>
library(tidyverse)
{ # load these two together because spatstat rely on them but I don't know exactely for what.
library(sp)
library(maptools)  # needed for method such as as.ppp
}
library(spatstat)
library(sf)
library(xlsx)

# load transect polygon giving the Window of ppp, and make it a owin object
tr_poly_win<-st_read('transect.shp') %>%
             select(geometry) %>% as(., 'Spatial') %>% as(.,'SpatialPolygons') %>%
             as.owin(tr_poly_sp)

# load points and make them a ppp with correct window

options(digits=15) # this to allow enough decimals
points<-read.table('points.txt', head=T,sep='\t',dec='.') %>%
        mutate(geometry=as.character(geometry)) %>%
        mutate(lon=as.numeric(sapply(strsplit(geometry, '[(,)]'), "[[", 2)),
               lat=as.numeric(sapply(strsplit(geometry, '[(,)]'), "[[", 3))) %>%
        st_as_sf(coords=c('lon','lat'),crs= 32619) %>%
        as(.,'Spatial') %>%
        as.ppp(.)

Window(points)<-tr_poly_win

# load polygons
win<-st_read('polygons.shp') %>% as(.,'Spatial') %>% as(.,'owin')

# create an hyperframe

hyp<-hyperframe(points=points,win=win)

# visualize data:
# points as open circles; points' window as black contour; polygons in red;
# Frame of the polygons as red rectangle; Frame of points as green rectangle
plot(hyp, quote({plot(points,which.marks='pos',type='n')
                 plot(win,col=2,add=TRUE)
                 plot(points,which.marks='pos',type='p', add=T)
                 plot(Frame(win),border=2, add=T)
                 plot(Frame(points),border=3, add=T)}) )
</code>```

points as open circles; points' window as black contour; polygons in red;
Frame of the polygons as red rectangle; Frame of points as green rectangle

```<code># computing the Jfox function works
with(hyp,Jfox(points,win))

# try to compute the envelope for the Jfox and you'll get the error
with(hyp,envelope(Y=points,  fun=Jfox, funargs=list(Y=win) , nsim=99, fix.n=T))
</code>```

Is there any underlying reason why I get this error or it is a bug (e.g. see the links in the PS)?

My session info is as follow:

```<code>R version 3.6.2 (2019-12-12)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=Italian_Italy.1252  LC_CTYPE=Italian_Italy.1252    LC_MONETARY=Italian_Italy.1252 LC_NUMERIC=C                   LC_TIME=Italian_Italy.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] xlsx_0.6.1          sf_0.7-4            spatstat_1.63-0     rpart_4.1-15        nlme_3.1-140        spatstat.data_1.4-3 maptools_0.9-5      sp_1.3-1            forcats_0.4.0
[10] stringr_1.4.0       dplyr_0.8.3         purrr_0.3.3         readr_1.3.1         tidyr_1.0.0         tibble_2.1.3        ggplot2_3.2.1       tidyverse_1.2.1

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.1            lubridate_1.7.4       lattice_0.20-38       deldir_0.1-16         xlsxjars_0.6.1        class_7.3-15          assertthat_0.2.1      zeallot_0.1.0
 [9] R6_2.4.0              cellranger_1.1.0      backports_1.1.4       e1071_1.7-1           httr_1.4.1            tensor_1.5            pillar_1.4.0          rlang_0.4.1
[17] lazyeval_0.2.2        readxl_1.3.1          rstudioapi_0.10       Matrix_1.2-18         goftest_1.2-2         splines_3.6.2         rgdal_1.4-3           foreign_0.8-72
[25] polyclip_1.10-0       munsell_0.5.0         broom_0.5.2           compiler_3.6.2        modelr_0.1.5          pkgconfig_2.0.2       mgcv_1.8-31           tidyselect_0.2.5
[33] crayon_1.3.4          withr_2.1.2           grid_3.6.2            jsonlite_1.6          gtable_0.3.0          lifecycle_0.1.0       DBI_1.0.0             magrittr_1.5
[41] units_0.6-3           scales_1.0.0          KernSmooth_2.23-16    cli_1.1.0             stringi_1.4.3         xml2_1.2.2            spatstat.utils_1.17-0 generics_0.0.2
[49] vctrs_0.2.0           tools_3.6.2           glue_1.3.1            hms_0.5.2             abind_1.4-5           colorspace_1.4-1      classInt_0.3-3        rvest_0.3.5
[57] rJava_0.9-11          haven_2.2.0
</code>```

Ps: My search for an explanation lead to similar problems that resulted from a bug in previous version of the spatstat code. here the links:

http://r-sig-geo.2731867.n2.nabble.com/Error-in-random-labelling-using-the-J-function-td7593210.html

http://r-sig-geo.2731867.n2.nabble.com/Complete-spatial-randomness-testing-td7590425.html

As you can see, though, my statspat and my R versions should be current.

答:
This is a bug.

It is now fixed in the development version of spatstat (version 1.63-0.020 and later) available from the repository on GitHub.

Body:
I want to explore the distance of points in a point pattern to the nearest polygon in a polygon shapefile.

Using the R package spatstat, my approach is to calculate the envelope for the function Jfox that consider the distance of my points to the polygons.

My full dataset include point patterns from multiple sites, and I have been successfully using this approach with several sites.

However, when running the envelope on a particular site I get this error:

Generating 99 simulations of CSR with fixed number of points  ...
Error : in Hest(X,r) the successive r values must be finely spaced: given spacing = 0.0043766; required spacing <=  0.00393
In addition: Warning messages:
1: In resolve.foxall.window(X, Y, W) :
  Trimming the window of X to be a subset of the Frame of Y
2: In resolve.foxall.window(X, Y, W) :
  Trimming the window of X to be a subset of the Frame of Y
[retrying]
Error : in Hest(X,r) the successive r values must be finely spaced: given spacing = 0.0043766; required spacing <=  0.00393
In addition: Warning message:
In resolve.foxall.window(X, Y, W) :
  Trimming the window of X to be a subset of the Frame of Y
[retrying]
... and so on.

I cannot figure out what is causing the issue.

Reproducible example:

Datafiles can be found here:

https://www.dropbox.com/sh/fzucl5f6u4s2igx/AAAzgf2Fn-L9cfwzSCwj1RbPa?dl=0

please adapt the code for importing the data according to where you store the files.

library(tidyverse)
{ # load these two together because spatstat rely on them but I don't know exactely for what.
library(sp)
library(maptools)  # needed for method such as as.ppp
}
library(spatstat)
library(sf)
library(xlsx)

# load transect polygon giving the Window of ppp, and make it a owin object
tr_poly_win<-st_read('transect.shp') %>%
             select(geometry) %>% as(., 'Spatial') %>% as(.,'SpatialPolygons') %>%
             as.owin(tr_poly_sp)

# load points and make them a ppp with correct window

options(digits=15) # this to allow enough decimals
points<-read.table('points.txt', head=T,sep='\t',dec='.') %>%
        mutate(geometry=as.character(geometry)) %>%
        mutate(lon=as.numeric(sapply(strsplit(geometry, '[(,)]'), "[[", 2)),
               lat=as.numeric(sapply(strsplit(geometry, '[(,)]'), "[[", 3))) %>%
        st_as_sf(coords=c('lon','lat'),crs= 32619) %>%
        as(.,'Spatial') %>%
        as.ppp(.)

Window(points)<-tr_poly_win

# load polygons
win<-st_read('polygons.shp') %>% as(.,'Spatial') %>% as(.,'owin')

# create an hyperframe

hyp<-hyperframe(points=points,win=win)

# visualize data:
# points as open circles; points' window as black contour; polygons in red;
# Frame of the polygons as red rectangle; Frame of points as green rectangle
plot(hyp, quote({plot(points,which.marks='pos',type='n')
                 plot(win,col=2,add=TRUE)
                 plot(points,which.marks='pos',type='p', add=T)
                 plot(Frame(win),border=2, add=T)
                 plot(Frame(points),border=3, add=T)}) )

points as open circles; points' window as black contour; polygons in red;
Frame of the polygons as red rectangle; Frame of points as green rectangle

# computing the Jfox function works
with(hyp,Jfox(points,win))

# try to compute the envelope for the Jfox and you'll get the error
with(hyp,envelope(Y=points,  fun=Jfox, funargs=list(Y=win) , nsim=99, fix.n=T))

Is there any underlying reason why I get this error or it is a bug (e.g. see the links in the PS)?

My session info is as follow:

R version 3.6.2 (2019-12-12)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=Italian_Italy.1252  LC_CTYPE=Italian_Italy.1252    LC_MONETARY=Italian_Italy.1252 LC_NUMERIC=C                   LC_TIME=Italian_Italy.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] xlsx_0.6.1          sf_0.7-4            spatstat_1.63-0     rpart_4.1-15        nlme_3.1-140        spatstat.data_1.4-3 maptools_0.9-5      sp_1.3-1            forcats_0.4.0
[10] stringr_1.4.0       dplyr_0.8.3         purrr_0.3.3         readr_1.3.1         tidyr_1.0.0         tibble_2.1.3        ggplot2_3.2.1       tidyverse_1.2.1

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.1            lubridate_1.7.4       lattice_0.20-38       deldir_0.1-16         xlsxjars_0.6.1        class_7.3-15          assertthat_0.2.1      zeallot_0.1.0
 [9] R6_2.4.0              cellranger_1.1.0      backports_1.1.4       e1071_1.7-1           httr_1.4.1            tensor_1.5            pillar_1.4.0          rlang_0.4.1
[17] lazyeval_0.2.2        readxl_1.3.1          rstudioapi_0.10       Matrix_1.2-18         goftest_1.2-2         splines_3.6.2         rgdal_1.4-3           foreign_0.8-72
[25] polyclip_1.10-0       munsell_0.5.0         broom_0.5.2           compiler_3.6.2        modelr_0.1.5          pkgconfig_2.0.2       mgcv_1.8-31           tidyselect_0.2.5
[33] crayon_1.3.4          withr_2.1.2           grid_3.6.2            jsonlite_1.6          gtable_0.3.0          lifecycle_0.1.0       DBI_1.0.0             magrittr_1.5
[41] units_0.6-3           scales_1.0.0          KernSmooth_2.23-16    cli_1.1.0             stringi_1.4.3         xml2_1.2.2            spatstat.utils_1.17-0 generics_0.0.2
[49] vctrs_0.2.0           tools_3.6.2           glue_1.3.1            hms_0.5.2             abind_1.4-5           colorspace_1.4-1      classInt_0.3-3        rvest_0.3.5
[57] rJava_0.9-11          haven_2.2.0

Ps: My search for an explanation lead to similar problems that resulted from a bug in previous version of the spatstat code. here the links:

http://r-sig-geo.2731867.n2.nabble.com/Error-in-random-labelling-using-the-J-function-td7593210.html

http://r-sig-geo.2731867.n2.nabble.com/Complete-spatial-randomness-testing-td7590425.html

As you can see, though, my statspat and my R versions should be current.


问:
How to prove the correctness of insertion sort with recursion?
I have to do insertion sort with recursion and prove its correctness by using a loop invariant. I am confident that my code is correct and it works with different inputs. But, I don't know how to prove its correctness the way my book does. Can someone prove it is correct by using a loop invariant ?

The algorithms are proved correct in the book by using the steps below which are similar to mathematical induction. If needed, refer enter link description here

1 - Find the loop invariant for each loop in your algorithm. The loop invariant is a condition which is true before the start of the loop, after any of the subsequent iterations and upon termination of the loop.

2 - Use logic to prove that the loop invariants are true prior before loop initialization, are maintained in subsequent loop runs and are true when the loop has terminated.

```<code>//n - The index till which the array D is to be sorted.
public static void sort(int n, int [] D){
    if(n == 0){
        return;
    }else {
        sort(n-1, D);
    }

    int lastItem = D[n];
    int j = n-1;

    while (j >= 0 && lastItem < D[j]) {
        D[j + 1] = D[j];
        j--;
    }

    //Insert the lastItem at the correct position.
    D[j+1] = lastItem;
}
</code>```

}

PS -  The book I use is "Introduction to Algorithms" by Thomas Cormen i.e. the CLRS book.

答:
May be answer is somewhat redundant.
For convenience we split method on two parts - recursion and loop. Loop invariant is described in code below:</p>

```<code>// Correctness of sort can be proved by mathematical induction
public static void sort(int n, int[] D)
{
    if (n == 0)
    {
        return;
    }
    else
    {
        sort(n - 1, D);
    }
    InsertNElementInSortedArray(n, D);
}

// This method insert n-th element of D in already sorted slice D[0 .. n-1] (right bound included).
// After method execution we have sorted slice D[0 .. n] (right bound included).
// Case 1. n==0. We swap 0-th element with 0-th element.
// Case 2. n > 0 and first n element sorted in D. Use loop invariant method only for this case.
// P.S. Case 1-2 can be combined.
public static void InsertNElementInSortedArray(int n, int[] D)
{
    int lastItem = D[n];
    int j = n - 1;

    // Define DR as slice of D[j+1 .. n] (right bound included)
    // Define DL as slice of D[0 .. j] (right bound included)
    // Loop invariant: DR are sorted
    //                 DL are sorted
    //                 All elements in DR except first element are greater or equal than all elements in DL
    //                 All elements in DR except first element are greater or equal than lastItem
    //                 DR (except first element) and DL contains all elements from source D[0 .. n-1] (right bound included)
    //
    // Initialization: It is true prior to the first iteration of the loop:
    //                 DR are sorted because DR have only one element
    //                 DL are sorted because first n element sorted in D
    //                 All elements in DR except first are greater or equal than all elements in DL because DR have only one element lastItem
    //                 All elements in DR except first element are greater or equal than lastItem because DR have only one element lastItem
    //                 DR(except first element) and DL contains all elements from source D[0..n - 1] because DL == D[0..n - 1]
    //
    // Maintenance: If it is true before an iteration of the loop, it remains true before the next iteration because
    //              In loop step we take last element from DL and replace them first element in DR and next change boundaries of DL and DR.
    //              DR are sorted because all elements in DR except first element are greater or equal than all elements in DL
    //              DL are sorted because first n element sorted in source D
    //              All elements in DR except first element are greater or equal than all elements in DL because we take maximum element from DL
    //              All elements in DR except first element are greater or equal than lastItem because lastItem less than maximum element from DL (by loop condition)
    //              DR (except first element) and DL contains all elements from source D[0 .. n-1] by construction
    while (j >= 0 && lastItem < D[j])
    {
        D[j + 1] = D[j];
        j--;
    }

    // Termination: When the loop terminates, the invariant gives us a useful property that helps show that the algorithm is correct.
    //              When loop terminates we have
    //              DR sorted
    //              DL sorted
    //              All elements in DR except first element are greater or equal than all elements in DL
    //              All elements in DR except first element are greater or equal than lastItem
    //              DR (except first element) and DL contains all elements from source D[0 .. n-1] (right bound included)
    //
    //              1 case. Loop terminates when lastItem >= D[j].
    //                      lastItem is greater or equal than all elements in DL.
    //                      Replace first element from DR by lastItem. Now we have DR >= DL and both slices sorted then D[0 .. n] sorted.
    //
    //              2 case. Loop terminates when j == -1.
    //                      DR contains all elements from source D[0 .. n-1] and DR sorted.
    //                      lastItem is less than all elements from DR.
    //                      When we assign D[0] = lastItem then then D[0 .. n] sorted.
    D[j + 1] = lastItem;
}
</code>```

Body:
I have to do insertion sort with recursion and prove its correctness by using a loop invariant. I am confident that my code is correct and it works with different inputs. But, I don't know how to prove its correctness the way my book does. Can someone prove it is correct by using a loop invariant ?

The algorithms are proved correct in the book by using the steps below which are similar to mathematical induction. If needed, refer enter link description here

1 - Find the loop invariant for each loop in your algorithm. The loop invariant is a condition which is true before the start of the loop, after any of the subsequent iterations and upon termination of the loop.

2 - Use logic to prove that the loop invariants are true prior before loop initialization, are maintained in subsequent loop runs and are true when the loop has terminated.

//n - The index till which the array D is to be sorted.
public static void sort(int n, int [] D){
    if(n == 0){
        return;
    }else {
        sort(n-1, D);
    }

    int lastItem = D[n];
    int j = n-1;

    while (j >= 0 && lastItem < D[j]) {
        D[j + 1] = D[j];
        j--;
    }

    //Insert the lastItem at the correct position.
    D[j+1] = lastItem;
}

}

PS -  The book I use is "Introduction to Algorithms" by Thomas Cormen i.e. the CLRS book.

Body:
May be answer is somewhat redundant.
For convenience we split method on two parts - recursion and loop. Loop invariant is described in code below:

// Correctness of sort can be proved by mathematical induction
public static void sort(int n, int[] D)
{
    if (n == 0)
    {
        return;
    }
    else
    {
        sort(n - 1, D);
    }
    InsertNElementInSortedArray(n, D);
}

// This method insert n-th element of D in already sorted slice D[0 .. n-1] (right bound included).
// After method execution we have sorted slice D[0 .. n] (right bound included).
// Case 1. n==0. We swap 0-th element with 0-th element.
// Case 2. n > 0 and first n element sorted in D. Use loop invariant method only for this case.
// P.S. Case 1-2 can be combined.
public static void InsertNElementInSortedArray(int n, int[] D)
{
    int lastItem = D[n];
    int j = n - 1;

    // Define DR as slice of D[j+1 .. n] (right bound included)
    // Define DL as slice of D[0 .. j] (right bound included)
    // Loop invariant: DR are sorted
    //                 DL are sorted
    //                 All elements in DR except first element are greater or equal than all elements in DL
    //                 All elements in DR except first element are greater or equal than lastItem
    //                 DR (except first element) and DL contains all elements from source D[0 .. n-1] (right bound included)
    //
    // Initialization: It is true prior to the first iteration of the loop:
    //                 DR are sorted because DR have only one element
    //                 DL are sorted because first n element sorted in D
    //                 All elements in DR except first are greater or equal than all elements in DL because DR have only one element lastItem
    //                 All elements in DR except first element are greater or equal than lastItem because DR have only one element lastItem
    //                 DR(except first element) and DL contains all elements from source D[0..n - 1] because DL == D[0..n - 1]
    //
    // Maintenance: If it is true before an iteration of the loop, it remains true before the next iteration because
    //              In loop step we take last element from DL and replace them first element in DR and next change boundaries of DL and DR.
    //              DR are sorted because all elements in DR except first element are greater or equal than all elements in DL
    //              DL are sorted because first n element sorted in source D
    //              All elements in DR except first element are greater or equal than all elements in DL because we take maximum element from DL
    //              All elements in DR except first element are greater or equal than lastItem because lastItem less than maximum element from DL (by loop condition)
    //              DR (except first element) and DL contains all elements from source D[0 .. n-1] by construction
    while (j >= 0 && lastItem < D[j])
    {
        D[j + 1] = D[j];
        j--;
    }

    // Termination: When the loop terminates, the invariant gives us a useful property that helps show that the algorithm is correct.
    //              When loop terminates we have
    //              DR sorted
    //              DL sorted
    //              All elements in DR except first element are greater or equal than all elements in DL
    //              All elements in DR except first element are greater or equal than lastItem
    //              DR (except first element) and DL contains all elements from source D[0 .. n-1] (right bound included)
    //
    //              1 case. Loop terminates when lastItem >= D[j].
    //                      lastItem is greater or equal than all elements in DL.
    //                      Replace first element from DR by lastItem. Now we have DR >= DL and both slices sorted then D[0 .. n] sorted.
    //
    //              2 case. Loop terminates when j == -1.
    //                      DR contains all elements from source D[0 .. n-1] and DR sorted.
    //                      lastItem is less than all elements from DR.
    //                      When we assign D[0] = lastItem then then D[0 .. n] sorted.
    D[j + 1] = lastItem;
}


问:
Why am I getting a "no matching function" error?
Pretty new to C++, I was given an assignment that is basically about utilizing two different classes, however when creating my header files and c++ files and attempting to compile I get an error that reads no matching function for call to 'Owner::Owner()'. Since I am not super familiar with C++ yet I am assuming that this issue has something to do with my constructors and the way I am trying to call them, my assignment details what I think my issue is about but I am having trouble understanding exactly what needs to be done. I will provide the assignment details on the issue, as well as the code and compilation error below. Sorry for all the information I've just been stuck with this issue for a while and I can't seem to figure out a solution.

Transcribed Error
In constructor 'Dog::Dog(std::__cxx11::string, int)':
Dog.cpp:23:46: error: no matching function for call to 'Owner::Owner()' Dog::Dog(std::string unsetBreed, int unsetAge){

Assignment Details

Now you will write a program that consists of two classes, a Dog class and an Owner class. Their specification is shown in the UML diagram below. Notice that in our design, every Dog has an Owner class member. Class Owner is immutable, as mentioned above. An immutable class is just a class whose members cannot be changed(mutated) after an object was instantiated. Therefore, the Owner class does not have any setter methods. The Owner’s class attributes must be set at the time of creation(in the Owner’s constructor). You will call Owner’s constructor from inside Dog’s constructor. Do not forget to do it inside each constructor in class Dog.

Dog.h File

```<code>#ifndef DOG_H_INCLUDED
#define DOG_H_INCLUDED

#include <iostream>
#include "Owner.h"

class Dog {
//-----------------------//
  private:
    std::string breed;
    int age;
    Owner owner;
    static int dogCount;
//-----------------------//
  public:
    Dog();
    Dog(std::string, int);
    std::string getBreed();
    int getAge();
    void setBreed(std::string);
    void setAge(int);
    void printDogInfo();
    int getDogCount();
};
#endif // DOG_H_INCLUDED
</code>```

Owner.h File

```<code>#ifndef OWNER_H_INCLUDED
#define OWNER_H_INCLUDED
#include <iostream>

class Owner {
//-----------------------//
  private:
    std::string name;
    int age;
//-----------------------//
  public:
    Owner(std::string, int);
    std::string getName();
    int getAge();
//-----------------------//
};

#endif // OWNER_H_INCLUDED
</code>```

Dog.cpp File

```<code>#include <iostream>
#include "Owner.cpp"
#include "Owner.h"
#include "Dog.h"

//---------------SETTERS------------------//
void Dog::setBreed(std::string dogBreed){dogBreed = breed;}
void Dog::setAge(int dogAge){dogAge = age;}

//--------------GETTERS------------------//
std::string Dog::getBreed(){return breed;}
int Dog::getAge(){return age;}
int Dog::getDogCount(){return dogCount;}

//--------------OTHERS-------------------//
Dog::Dog(std::string unsetBreed, int unsetAge){
  Owner::Owner(std::string unsetName, int unsetOwnerAge);
  Dog::setBreed(unsetBreed);
  Dog::setAge(unsetAge);
}

void Dog::printDogInfo(){
  Dog::getBreed();
  Dog::getAge();
}
</code>```

Owner.cpp File

```<code>#include <iostream>
#include "Owner.h"
#include "Dog.h"

//--------------GETTERS------------------//
int Owner::getAge(){return age;}
std::string Owner::getName(){return name;}

//--------------OTHERS-------------------//
Owner::Owner(std::string unsetName, int unsetOwnerAge){
  Owner::getName();
  Owner::getAge();
}
</code>```

答:
The problem here is that you don't have a constructor that receives 0 parameters.
You have 2 options:

1 - Define other constructor:

```<code>//header file
class Owner {
...
  public:
    Owner(std::string, int);
    Owner();
...
};
</code>```

```<code>//cpp file
...
Owner::Owner(){
  name = "Jhon Doe";
  age = 18;
}
...
</code>```

2 - Define default params:

```<code>//header file
class Owner {
...
  public:
    Owner(std::string unsetName = "John Doe", int unsetAge = 18);
...
};
</code>```

```<code>//cpp file
...
Owner::Owner(std::string unsetName = "John Doe", int unsetAge = 18);
  Owner::getName();
  Owner::getAge();
}
...
</code>```

Note: I don't know why you are calling getter in the constructors.

Body:
Pretty new to C++, I was given an assignment that is basically about utilizing two different classes, however when creating my header files and c++ files and attempting to compile I get an error that reads no matching function for call to 'Owner::Owner()'. Since I am not super familiar with C++ yet I am assuming that this issue has something to do with my constructors and the way I am trying to call them, my assignment details what I think my issue is about but I am having trouble understanding exactly what needs to be done. I will provide the assignment details on the issue, as well as the code and compilation error below. Sorry for all the information I've just been stuck with this issue for a while and I can't seem to figure out a solution.

Transcribed Error
In constructor 'Dog::Dog(std::__cxx11::string, int)':
Dog.cpp:23:46: error: no matching function for call to 'Owner::Owner()' Dog::Dog(std::string unsetBreed, int unsetAge){

Assignment Details

Now you will write a program that consists of two classes, a Dog class and an Owner class. Their specification is shown in the UML diagram below. Notice that in our design, every Dog has an Owner class member. Class Owner is immutable, as mentioned above. An immutable class is just a class whose members cannot be changed(mutated) after an object was instantiated. Therefore, the Owner class does not have any setter methods. The Owner’s class attributes must be set at the time of creation(in the Owner’s constructor). You will call Owner’s constructor from inside Dog’s constructor. Do not forget to do it inside each constructor in class Dog.

Dog.h File

#ifndef DOG_H_INCLUDED
#define DOG_H_INCLUDED

#include <iostream>
#include "Owner.h"

class Dog {
//-----------------------//
  private:
    std::string breed;
    int age;
    Owner owner;
    static int dogCount;
//-----------------------//
  public:
    Dog();
    Dog(std::string, int);
    std::string getBreed();
    int getAge();
    void setBreed(std::string);
    void setAge(int);
    void printDogInfo();
    int getDogCount();
};
#endif // DOG_H_INCLUDED

Owner.h File

#ifndef OWNER_H_INCLUDED
#define OWNER_H_INCLUDED
#include <iostream>

class Owner {
//-----------------------//
  private:
    std::string name;
    int age;
//-----------------------//
  public:
    Owner(std::string, int);
    std::string getName();
    int getAge();
//-----------------------//
};

#endif // OWNER_H_INCLUDED

Dog.cpp File

#include <iostream>
#include "Owner.cpp"
#include "Owner.h"
#include "Dog.h"

//---------------SETTERS------------------//
void Dog::setBreed(std::string dogBreed){dogBreed = breed;}
void Dog::setAge(int dogAge){dogAge = age;}

//--------------GETTERS------------------//
std::string Dog::getBreed(){return breed;}
int Dog::getAge(){return age;}
int Dog::getDogCount(){return dogCount;}

//--------------OTHERS-------------------//
Dog::Dog(std::string unsetBreed, int unsetAge){
  Owner::Owner(std::string unsetName, int unsetOwnerAge);
  Dog::setBreed(unsetBreed);
  Dog::setAge(unsetAge);
}

void Dog::printDogInfo(){
  Dog::getBreed();
  Dog::getAge();
}

Owner.cpp File

#include <iostream>
#include "Owner.h"
#include "Dog.h"

//--------------GETTERS------------------//
int Owner::getAge(){return age;}
std::string Owner::getName(){return name;}

//--------------OTHERS-------------------//
Owner::Owner(std::string unsetName, int unsetOwnerAge){
  Owner::getName();
  Owner::getAge();
}

Body:
The problem here is that you don't have a constructor that receives 0 parameters.
You have 2 options:

1 - Define other constructor:

//header file
class Owner {
...
  public:
    Owner(std::string, int);
    Owner();
...
};

//cpp file
...
Owner::Owner(){
  name = "Jhon Doe";
  age = 18;
}
...

2 - Define default params:

//header file
class Owner {
...
  public:
    Owner(std::string unsetName = "John Doe", int unsetAge = 18);
...
};

//cpp file
...
Owner::Owner(std::string unsetName = "John Doe", int unsetAge = 18);
  Owner::getName();
  Owner::getAge();
}
...

Note: I don't know why you are calling getter in the constructors.


问:
Webpack cannot resolve ant design modules
I'm trying to setup react with typescript and Antdesign without the react-create-app overhead. When I import an Antdesign component in a react component, I get errors.

I was wondering my import was incorrect but importing the module like import Button from 'antd/es/button'; only throws Error: Can't resolve 'antd/es/button'...

package.json:

```<code>  "name": "myName",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "devDependencies": {
    "@types/react": "^16.9.9",
    "@types/react-dom": "^16.9.2",
    "source-map-loader": "^0.2.4",
    "ts-loader": "^6.2.1",
    "tslint": "^5.20.0",
    "typescript": "^3.6.4",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.9"
  },
  "dependencies": {
    "antd": "^3.24.2",
    "react": "^16.11.0",
    "react-dom": "^16.11.0"
  }
}
</code>```

webpack.config.js:

```<code>    mode: "production",
    devtool: "source-map",
    resolve: {
        extensions: ["js", ".ts", ".tsx"]
    },
    module: {
        rules: [
            {
                test: /\.ts(x?)$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: "ts-loader"
                    }
                ]
            },
            {
                enforce: "pre",
                test: /\.js$/,
                loader: "source-map-loader"
            }
        ]
    },
    externals: {
        "react": "React",
        "react-dom": "ReactDOM"
    }
};
</code>```

index.tsx:

```<code>import * as ReactDOM from "react-dom";
import { Button } from "antd";

ReactDOM.render(
    <div>
        <Button>Click Me!</Button>
    </div>,
    document.getElementById("app")
);
</code>```

index.html:

```<code><html>
    <body>
        <div id="app"></div>
        <script src="./node_modules/react/umd/react.development.js"></script>
        <script src="./node_modules/react-dom/umd/react-dom.development.js"></script>
        <script src="./dist/main.js"></script>
    </body>
</html>
</code>```

When I run npx webpack it runs through all the different ant design components and for each it will give me the following error:

```<code>Module not found: Error: Can't resolve './upload' in '/Userpath/node_modules/antd/es'
 @ ./node_modules/antd/es/index.js 66:0-45 66:0-45
 @ ./src/index.tsx```
```

答:
I met the same exact issue, and finally fixed it by upgrade antd from 3.26.2 to 3.26.11.

You may check your package.json too.

Body:
I'm trying to setup react with typescript and Antdesign without the react-create-app overhead. When I import an Antdesign component in a react component, I get errors.

I was wondering my import was incorrect but importing the module like import Button from 'antd/es/button'; only throws Error: Can't resolve 'antd/es/button'...

package.json:

  "name": "myName",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "devDependencies": {
    "@types/react": "^16.9.9",
    "@types/react-dom": "^16.9.2",
    "source-map-loader": "^0.2.4",
    "ts-loader": "^6.2.1",
    "tslint": "^5.20.0",
    "typescript": "^3.6.4",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.9"
  },
  "dependencies": {
    "antd": "^3.24.2",
    "react": "^16.11.0",
    "react-dom": "^16.11.0"
  }
}

webpack.config.js:

    mode: "production",
    devtool: "source-map",
    resolve: {
        extensions: ["js", ".ts", ".tsx"]
    },
    module: {
        rules: [
            {
                test: /\.ts(x?)$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: "ts-loader"
                    }
                ]
            },
            {
                enforce: "pre",
                test: /\.js$/,
                loader: "source-map-loader"
            }
        ]
    },
    externals: {
        "react": "React",
        "react-dom": "ReactDOM"
    }
};

index.tsx:

import * as ReactDOM from "react-dom";
import { Button } from "antd";

ReactDOM.render(

        <Button>Click Me!</Button>

,
    document.getElementById("app")
);

index.html:

When I run npx webpack it runs through all the different ant design components and for each it will give me the following error:

Module not found: Error: Can't resolve './upload' in '/Userpath/node_modules/antd/es'
 @ ./node_modules/antd/es/index.js 66:0-45 66:0-45
 @ ./src/index.tsx```


问:
C# conversion failed when converting nvarchar to int
I am trying to insert values to my database but I keep getting the error

"conversion failed when converting the nvarchar 'Year' value to
  datatype int"

in c#. I don't know how to fix this.

Here is my code:

```<code>private void btnSave_Click(object sender, EventArgs e)
{
    try
    {
        if (MessageBox.Show("Are you sure you want to save this book?", "Saving Record", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
        {
            //open connection to the database
            cn.Open();
            //command to be executed on the database
            cm = new SqlCommand("INSERT INTO Books(BookTitle, Edition, Genre, Author, Publisher, Year, ISBN) VALUES (@BookTitle, @Edition, @Genre, @Author, @Publisher, @Year, @ISBN )", cn);
            //set paramaters value
            cm.Parameters.AddWithValue("@booktitle", txtBook.Text);
            cm.Parameters.AddWithValue("@edition", txtEdition.Text);
            cm.Parameters.AddWithValue("@genre", txtGenre.Text);
            cm.Parameters.AddWithValue("@author", txtAuthor.Text);
            cm.Parameters.AddWithValue("@publisher", txtPublisher.Text);
            cm.Parameters.AddWithValue("@year", txtYear.Text);
            cm.Parameters.AddWithValue("@isbn", txtISBN.Text);
            //ask db to execute query
            cm.ExecuteNonQuery();
            //close connection
            cn.Close();
            MessageBox.Show("Record has been sucessfully saved!");
            Clear();
            frmlist.LoadRecords();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
</code>```

答:
Assuming the year field in your table be an integer, you should be binding an integer variable to it:</p>

```<code>cm.Parameters.AddWithValue("@year", Int64.Parse(txtYear.Text));
</code>```

Body:
I am trying to insert values to my database but I keep getting the error

"conversion failed when converting the nvarchar 'Year' value to
  datatype int"

in c#. I don't know how to fix this.

Here is my code:

private void btnSave_Click(object sender, EventArgs e)
{
    try
    {
        if (MessageBox.Show("Are you sure you want to save this book?", "Saving Record", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
        {
            //open connection to the database
            cn.Open();
            //command to be executed on the database
            cm = new SqlCommand("INSERT INTO Books(BookTitle, Edition, Genre, Author, Publisher, Year, ISBN) VALUES (@BookTitle, @Edition, @Genre, @Author, @Publisher, @Year, @ISBN )", cn);
            //set paramaters value
            cm.Parameters.AddWithValue("@booktitle", txtBook.Text);
            cm.Parameters.AddWithValue("@edition", txtEdition.Text);
            cm.Parameters.AddWithValue("@genre", txtGenre.Text);
            cm.Parameters.AddWithValue("@author", txtAuthor.Text);
            cm.Parameters.AddWithValue("@publisher", txtPublisher.Text);
            cm.Parameters.AddWithValue("@year", txtYear.Text);
            cm.Parameters.AddWithValue("@isbn", txtISBN.Text);
            //ask db to execute query
            cm.ExecuteNonQuery();
            //close connection
            cn.Close();
            MessageBox.Show("Record has been sucessfully saved!");
            Clear();
            frmlist.LoadRecords();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Body:
Assuming the year field in your table be an integer, you should be binding an integer variable to it:

cm.Parameters.AddWithValue("@year", Int64.Parse(txtYear.Text));


答:
Your Year is a string type and needs to be converted to a number (int). You can use something like

cm.Parameters.AddWithValue("@year", int.Parse(txtYear.Text));

Make sure that the year text is not empty and convertible to int.

Title: C# conversion failed when converting nvarchar to int


问:
pytorch: sum of cross entropy over all classes
I want to compute sum of cross entropy over all classes for each prediction, where the input is batch (size n), and the output is batch (size n).

The simplest way is for loop (for 1000 classes):

```<code>def sum_of_CE_lost(input):
    L = 0
    for c in range(1000):
        L = L + torch.nn.CrossEntropyLoss(input, c)
    return L
</code>```

However, it is very slow. What is a better way? How can we parallelized it for GPU (CUDA)?

答:
First of all, to make it faster, you need to vectorize it, that is, work with matrices.

So, image you have 1,000 samples to compute the loss. Also, your classification problem has 5 labels. To compute the CrossEntropyLoss we need an input and a target. Let's simulate that as follows:

```<code>loss = nn.CrossEntropyLoss() # the loss function
input = torch.randn(1000, 5) #1000 samples and 5 labels' predictions
target = torch.empty(1000, dtype=torch.long).random_(5) # 1000 samples with labels from 0 to 4
loss_value = loss(input, target) # It'll output the loss
</code>```

There we go! Now the loss is computed considering the 1,000 samples. This is the fatest way to do that.

Body:
I want to compute sum of cross entropy over all classes for each prediction, where the input is batch (size n), and the output is batch (size n).

The simplest way is for loop (for 1000 classes):

def sum_of_CE_lost(input):
    L = 0
    for c in range(1000):
        L = L + torch.nn.CrossEntropyLoss(input, c)
    return L

However, it is very slow. What is a better way? How can we parallelized it for GPU (CUDA)?

Body:
First of all, to make it faster, you need to vectorize it, that is, work with matrices.

So, image you have 1,000 samples to compute the loss. Also, your classification problem has 5 labels. To compute the CrossEntropyLoss we need an input and a target. Let's simulate that as follows:

loss = nn.CrossEntropyLoss() # the loss function
input = torch.randn(1000, 5) #1000 samples and 5 labels' predictions
target = torch.empty(1000, dtype=torch.long).random_(5) # 1000 samples with labels from 0 to 4
loss_value = loss(input, target) # It'll output the loss

There we go! Now the loss is computed considering the 1,000 samples. This is the fatest way to do that.


问:
PHP:PCRE: How to replace repeatable char
for example I have following string:

```<code>a_b__c___d____e
</code>```

How to preg_replace char _ to char '-', but only if part ' __...' contains more than N repeated _.

I hope you understand me ))

```<code>source: a_b__c___d____e
cond: change '_' where 2 or more
result: a_b--c---d----e
</code>```

or

```<code>source: a_b__c___d____e_____f
cont: change '_' where 4 or more
result: a_b__c___d----e-----f
</code>```

Thanks!

p.s. Interesting solution without using loops. How implement it with loops (I think) know anybody. Just a one regex and preg_replace.

答:
```<code>$source = 'a_b__c___d____e_____f';
function yourfunc($param)
{
    $count  = strlen($param);
    $return = '';
    for ($i = 0; $i < $count; $i++)
    {
        $return .= '-';
    }
    return $return;
}
echo preg_replace('#(_{4,})#e', 'yourfunc("$1");', $source);
</code>```

A solution without callback function and loop is much harder to read.

```<code>preg_replace('#(_{4,})#e', 'implode("", array_pad(array(), strlen("$1"), "-"));', $source);
</code>```

Body:
for example I have following string:

a_b__c___d____e

How to preg_replace char _ to char '-', but only if part ' __...' contains more than N repeated _.

I hope you understand me ))

source: a_b__c___d____e
cond: change '_' where 2 or more
result: a_b--c---d----e

or

source: a_b__c___d____e_____f
cont: change '_' where 4 or more
result: a_b__c___d----e-----f

Thanks!

p.s. Interesting solution without using loops. How implement it with loops (I think) know anybody. Just a one regex and preg_replace.

Body:
$source = 'a_b__c___d____e_____f';
function yourfunc($param)
{
    $count  = strlen($param);
    $return = '';
    for ($i = 0; $i < $count; $i++)
    {
        $return .= '-';
    }
    return $return;
}
echo preg_replace('#(_{4,})#e', 'yourfunc("$1");', $source);

A solution without callback function and loop is much harder to read.

preg_replace('#(_{4,})#e', 'implode("", array_pad(array(), strlen("$1"), "-"));', $source);


答:
If you simply add int.Parse(txtYear.Text) as some of the other comments suggest, and the user enters any non-digit characters in the txtYear field you are going to get an exception.

You ought to change your text box to a number input so the value is an integer and you won't have to bother parsing it and hoping users input numbers only because that will be enforced by the number input itself.

Checkout this article on numeric inputs in Windows Forms:
https://www.c-sharpcorner.com/blogs/how-to-create-a-textbox-accepting-only-numbers-in-windows-forms1

That being said, if you are being forced to use a text input for some reason:

I would try and parse txtYear.Text as an integer using int.TryParse(txtYear.Text, out int year) before passing it into the SQL command. You can do something like the following at the top of the function to check the field and throw a more meaningful exception if the user has entered text into the field instead of all numbers:

```<code>if(!int.TryParse(txtYear.Text, out int year))
{
  throw new Exception("Only digits are allowed in the year field");
}

//the rest of your code goes here
//and use the year variable for the @year parameter
</code>```

Body:
If you simply add int.Parse(txtYear.Text) as some of the other comments suggest, and the user enters any non-digit characters in the txtYear field you are going to get an exception.

You ought to change your text box to a number input so the value is an integer and you won't have to bother parsing it and hoping users input numbers only because that will be enforced by the number input itself.

Checkout this article on numeric inputs in Windows Forms:
https://www.c-sharpcorner.com/blogs/how-to-create-a-textbox-accepting-only-numbers-in-windows-forms1

That being said, if you are being forced to use a text input for some reason:

I would try and parse txtYear.Text as an integer using int.TryParse(txtYear.Text, out int year) before passing it into the SQL command. You can do something like the following at the top of the function to check the field and throw a more meaningful exception if the user has entered text into the field instead of all numbers:

if(!int.TryParse(txtYear.Text, out int year))
{
  throw new Exception("Only digits are allowed in the year field");
}

//the rest of your code goes here
//and use the year variable for the @year parameter


问:
How to build semantic search for a given domain
There is a problem we are trying to solve where we want to do a semantic search on our set of data,
i.e we have a domain-specific data (example: sentences talking about automobiles)

Our data is just a bunch of sentences and what we want is to give a phrase and get back the sentences which are:

Similar to that phrase

Has a part of a sentence that is similar to the phrase

A sentence which is having contextually similar meanings

Let me try giving you an example suppose I search for the phrase "Buying Experience", I should get the sentences like:

I never thought car buying could take less than 30 minutes to sign
and buy.

I found a car that i liked and the purchase process was

straightforward and easy

I absolutely hated going car shopping, but today i’m glad i did

I want to lay emphasis on the fact that we are looking for contextual similarity and not just a brute force word search.

If the sentence uses different words then also it should be able to find it.

Things that we have already tried:

Open Semantic Search the problem we faced here is generating ontology from the data we have, or
for that sake searching for available ontology from different domains of our interest.

Elastic Search(BM25 + Vectors(tf-idf)), we tried this where it gave a few sentences but precision was not that great. The accuracy was bad
as well. We tried against a human-curated dataset, it was able to get around 10% of the sentences only.

We tried different embeddings like the once mentioned in sentence-transformers and also went through the example and tried evaluating against our human-curated set
and that also had very low accuracy.

We tried ELMO. This was better but still lower accuracy than we expected and there is a
cognitive load to decide the cosine value below which we shouldn't consider the sentences. This even applies to point 3.

Any help will be appreciated. Thanks a lot for the help in advance

答:
I would highly suggest that you watch Trey Grainger's lecture on how to build a semantic search system => https://www.youtube.com/watch?v=4fMZnunTRF8. He talks about the anatomy of a semantic search system and each of the pieces used to fit together to deliver a final solution.

A great example of the contextual similarity is Bing's search engine:

The original query had the terms {canned soda} and bing's search results can refer to {canned diet soda} , {soft drinks}, {unopened room temperature pop} or {carbonated drinks}. How did bing do this?:

Well, words that have similar meanings get similar vectors and then these vectors can be projected onto a 2-dimensional graph to be easily visualized. These vectors are trained by ensuring words with similar meanings are physically near each other. You can train your own vector based model by training the GloVe model

The closer the distances of the vectors are to each other the better. Now you can search for nearest neighbour queries based of the distance of their vectors. For example, for the query {how to stop animals from destroying my garden}, the nearest neighbour gives these results:

You can learn more about it here. For your case you can find a threshold for the maximum distance a vector of a sentence can be from the original search query for it to be consider a contextually similar sentence.

The contextual similarity can also possibly be done by reducing the vocabulary dimension using something like LSI(Latent Semantic Indexing). To do this in Python I would highly suggest you check out the genism library for python: https://radimrehurek.com/gensim/about.html.


问:
Angular - Prevent click event on disabled buttons
I'm trying to prevent click event on disabled buttons, in other words, prevent some user who removes the disabled attribute to call some action.

For now, I have the following code to do this:

<button [disabled]="someCondition" (click)="executeAction()">Execute action</button>
```

```executeAction(): void {
  if (this.someCondition) return;

  // ...
}
```

<p>Works, but it isn't a good solution as I have to do it for ALL buttons in my app (and believe me, it's easy to forgot to do this and even a <em>Linter</em> can't help me here).</p>

<p>Looking for a more robust solution, I thought that <code>directive</code> could help me:</p>

```import { Directive, HostListener, Input, Renderer2, ElementRef } from '@angular/core';

@Directive({
  selector: 'button'
})
export class ButtonDirective {
  @Input() set disabled(value: boolean) {
    this._disabled = value != null;
    this.renderer2.setAttribute(this.elementRef.nativeElement, 'disabled', `${this._disabled}`);
  }

  private _disabled: boolean;

  constructor(
    private readonly elementRef: ElementRef,
    private readonly renderer2: Renderer2
  ) { }

  @HostListener('click', ['$event'])
  onClick(mouseEvent: MouseEvent) {
    // nothing here does what I'm expecting
    if (this._disabled) {
      mouseEvent.preventDefault();
      mouseEvent.stopImmediatePropagation();
      mouseEvent.stopPropagation();

      return false; // just for test
    }
  }
}
```

<pre class="lang-html prettyprint-override"><code><button [disabled]="someCondition" (click)="executeAction()">Execute action</button>
</code>```

```<code>executeAction(): void {
  console.log('still being called');
}
</code>```

...however it does absolutely nothing. It doesn't prevent the click event. Is there any solution that I don't have to control the action itself in its call?

STACKBLITZ

答:
In your directive, you can do something like this. You can achieve it by adding an event listener to parent in the capturing phase.

```<code>ngOnInit() {
    this.elementRef.nativeElement.parentElement.addEventListener('click',(e) => {
      if(this._disabled && e.target.tagName === 'BUTTON') {
        e.stopImmediatePropagation();
        e.stopPropagation();
      }
    }, true);
  }
</code>```

You can remove the listener in onDestroy

Body:
I'm trying to prevent click event on disabled buttons, in other words, prevent some user who removes the disabled attribute to call some action.

For now, I have the following code to do this:

<button [disabled]="someCondition" (click)="executeAction()">Execute action</button>

executeAction(): void {
  if (this.someCondition) return;

  // ...
}

Works, but it isn't a good solution as I have to do it for ALL buttons in my app (and believe me, it's easy to forgot to do this and even a Linter can't help me here).

Looking for a more robust solution, I thought that directive could help me:

import { Directive, HostListener, Input, Renderer2, ElementRef } from '@angular/core';

@Directive({
  selector: 'button'
})
export class ButtonDirective {
  @Input() set disabled(value: boolean) {
    this._disabled = value != null;
    this.renderer2.setAttribute(this.elementRef.nativeElement, 'disabled', `${this._disabled}`);
  }

  private _disabled: boolean;

  constructor(
    private readonly elementRef: ElementRef,
    private readonly renderer2: Renderer2
  ) { }

  @HostListener('click', ['$event'])
  onClick(mouseEvent: MouseEvent) {
    // nothing here does what I'm expecting
    if (this._disabled) {
      mouseEvent.preventDefault();
      mouseEvent.stopImmediatePropagation();
      mouseEvent.stopPropagation();

      return false; // just for test
    }
  }
}

<button [disabled]="someCondition" (click)="executeAction()">Execute action</button>

executeAction(): void {
  console.log('still being called');
}

...however it does absolutely nothing. It doesn't prevent the click event. Is there any solution that I don't have to control the action itself in its call?

STACKBLITZ

Body:
In your directive, you can do something like this. You can achieve it by adding an event listener to parent in the capturing phase.

ngOnInit() {
    this.elementRef.nativeElement.parentElement.addEventListener('click',(e) => {
      if(this._disabled && e.target.tagName === 'BUTTON') {
        e.stopImmediatePropagation();
        e.stopPropagation();
      }
    }, true);
  }

You can remove the listener in onDestroy


问:
How can i center a <mat-card> in the middle of the screen in Angular 9
* I have a <mat-card> that i want to center in the middle of the screen I tried but it didn't center. It should looks good in toggle-device-toolbar because its for phones, i need some help with this.Im using angular-material and ng-bootstrap*

This is the code of the <mat-card>

    <mat-card>
    <mat-radio-group aria-label="Select an option" [(ngModel)]="radio_btn">
        <mat-radio-button  [value]="true" >Admin</mat-radio-button>
        <mat-radio-button [value]="false">User</mat-radio-button>
    </mat-radio-group>

            <form class="example-form " [formGroup]="loginForm" (ngSubmit)="send()">
                <mat-form-field class="example-full-width">
                    <input matInput formControlName="Identifier" placeholder="User" >
                </mat-form-field>

Introduce an email

                <mat-form-field class="example-full-width">
                    <input matInput formControlName="Password" placeholder="Password" type="password">
                </mat-form-field>

Introduce the correctly password

                <button mat-raised-button [disabled]="loginForm.invalid" class="colour_button " type="submit">Login 1</button>
            </form>

</mat-card>

```

This is how it looks like right now

答:
This is how i solve it

This is my css file

.center{
    width: 75%;
    margin: 10px auto;
  }

  .main-div{
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
  }
```

<p><code>This is my html file</code></p>

<pre class="lang-html prettyprint-override"><code><div class="main-div">
    <mat-card class="z-depth center" flex="50" >
        <mat-radio-group aria-label="Select an option" [(ngModel)]="radio_btn">
            <mat-radio-button  [value]="true" >Admin</mat-radio-button>
            <mat-radio-button [value]="false">User</mat-radio-button>
        </mat-radio-group>
            <div *ngIf="radio_btn==true;else form2">
                <form class="example-form " [formGroup]="loginForm" (ngSubmit)="send()">
                    <mat-form-field class="example-full-width">
                        <input matInput formControlName="Identifier" placeholder="User" >
                    </mat-form-field><br>
                    <div *ngIf="loginForm.get('Identifier').hasError('Identifier') && loginForm.get('Identifier').touched">Introduce an email</div><br>
                    <mat-form-field class="example-full-width">
                        <input matInput formControlName="Password" placeholder="Password" type="password">
                    </mat-form-field><br>
                    <div *ngIf="loginForm.get('Password').hasError('Password') && loginForm.get('Password').touched">Introduce the correctly password</div><br>
                    <button mat-raised-button [disabled]="loginForm.invalid" class="colour_button " type="submit">Login 1</button>
                </form>
            </div>
    </mat-card>
  </div>
</code>```

Body:
* I have a <mat-card> that i want to center in the middle of the screen I tried but it didn't center. It should looks good in toggle-device-toolbar because its for phones, i need some help with this.Im using angular-material and ng-bootstrap*

This is the code of the <mat-card>

    <mat-card>
    <mat-radio-group aria-label="Select an option" [(ngModel)]="radio_btn">
        <mat-radio-button  [value]="true" >Admin</mat-radio-button>
        <mat-radio-button [value]="false">User</mat-radio-button>
    </mat-radio-group>

            <form class="example-form " [formGroup]="loginForm" (ngSubmit)="send()">
                <mat-form-field class="example-full-width">
                    <input matInput formControlName="Identifier" placeholder="User" >
                </mat-form-field>

Introduce an email

                <mat-form-field class="example-full-width">
                    <input matInput formControlName="Password" placeholder="Password" type="password">
                </mat-form-field>

Introduce the correctly password

                <button mat-raised-button [disabled]="loginForm.invalid" class="colour_button " type="submit">Login 1</button>
            </form>

</mat-card>

This is how it looks like right now

Body:
This is how i solve it

This is my css file

.center{
    width: 75%;
    margin: 10px auto;
  }

  .main-div{
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
  }

This is my html file

<div class="main-div">
    <mat-card class="z-depth center" flex="50" >
        <mat-radio-group aria-label="Select an option" [(ngModel)]="radio_btn">
            <mat-radio-button  [value]="true" >Admin</mat-radio-button>
            <mat-radio-button [value]="false">User</mat-radio-button>
        </mat-radio-group>
            <div *ngIf="radio_btn==true;else form2">
                <form class="example-form " [formGroup]="loginForm" (ngSubmit)="send()">
                    <mat-form-field class="example-full-width">
                        <input matInput formControlName="Identifier" placeholder="User" >
                    </mat-form-field><br>
                    <div *ngIf="loginForm.get('Identifier').hasError('Identifier') && loginForm.get('Identifier').touched">Introduce an email</div><br>
                    <mat-form-field class="example-full-width">
                        <input matInput formControlName="Password" placeholder="Password" type="password">
                    </mat-form-field><br>
                    <div *ngIf="loginForm.get('Password').hasError('Password') && loginForm.get('Password').touched">Introduce the correctly password</div><br>
                    <button mat-raised-button [disabled]="loginForm.invalid" class="colour_button " type="submit">Login 1</button>
                </form>
            </div>
    </mat-card>
  </div>


问:
Vanilla JavaScript in Svelte
I've been following a guide to collapse a sidebar. I realised that I cannot use the $ because it's reserved in Svelte. Can someone guide me on how to make this work? Thanks :)

```<code>$(document).ready(function () {
    $('#sidebarCollapse').on('click', function () {
        $('#sidebar').toggleClass('active');
    });
});
</code>```

答:
You should really read through/follow along with the Svelte tutorial, it might help you better understand how to overcome small challenges like this.

Toggling a class is as easy as toggling a variable and using Svelte's shorthand class directive

```<code><script>
    let active = false;
</script>

<button on:click={()=> active = !active}>
    Some menu text or an icon here
</button>

<aside class:active>
    I'm a sidebar
</aside>
</code>```

Then you just make the styles equal to whatever tutorial you're following along with since the active class would be conditionally applied at that point.

Here's a simple REPL example.

Title: Vanilla JavaScript in Svelte

Body:
I've been following a guide to collapse a sidebar. I realised that I cannot use the $ because it's reserved in Svelte. Can someone guide me on how to make this work? Thanks :)

$(document).ready(function () {
    $('#sidebarCollapse').on('click', function () {
        $('#sidebar').toggleClass('active');
    });
});

Body:
You should really read through/follow along with the Svelte tutorial, it might help you better understand how to overcome small challenges like this.

Toggling a class is as easy as toggling a variable and using Svelte's shorthand class directive

<script>
    let active = false;
</script>

<button on:click={()=> active = !active}>
    Some menu text or an icon here
</button>

<aside class:active>
    I'm a sidebar
</aside>

Then you just make the styles equal to whatever tutorial you're following along with since the active class would be conditionally applied at that point.

Here's a simple REPL example.


问:
Visual Studio 2008 debugging: when I click on the play button, it flashes real quick
I am having a weird issue with VS 2008 when I go to debug my program. When I click on the play button to run the program it flashes real quick and goes back to the VB IDE. No matter how many times I click on the play button it continually flashes and then goes back without displaying my form window or anything.

What type of setting would I need to change in order to correct this issue? I've been through most settings in the "my project" section and i do not see anything that could be causing it to do something like this.

My older vb apps I've made seem to work just fine when I click the play button on them. Only noticed this problem whenever I go and make a new vb app.

update video of what's going on
http://tinypic.com/r/2eycaas/7

答:
Fixed.

Changing it to x86 instead of Any CPU worked!!!! :) But question is, why me having an Core i7 Quad doesn't support the program when i choose x64.....

David


问:
How do you log into an account in Active Directory that doesn't have a password set?
I'm doing some InfoSec testing and I've discovered some accounts that don't have a password set.

I'm wondering if there is a way to can log into these accounts. I know that for these accounts, their password will be required to be reset upon login, but I'm not sure how to log in. Any ideas?

答:
It might help if you tell us how you determined that they don't have a password set. But if that truly is the case, then there are only two possibilities:

The accounts are disabled. This might happen if the accounts are created via automation. Creating accounts has to be done in two steps: create the account (which is created disabled), then set the password and enable it. You can't enable it without setting a password.

The accounts have the ADS_UF_PASSWD_NOTREQD flag set in the userAccountControl attribute. This means the account can be enabled with no password and you can login with such an account by just not putting anything as the password. You can read more about this here if you'd like.


问:
Using xpath with c#, help
I'm trying to select the content of MINRANGE of the below XML. This is the code I'm using, the string min just gives me a long block of text not the node i wanted.

```<code>XPathDocument _BTCall = new XPathDocument(callUrl);
XPathNavigator nav = _BTCall.CreateNavigator();
XPathExpression exp;
exp = nav.Compile("//MAX/MINRANGE");
XPathNodeIterator iterator = nav.Select(exp);
iterator.MoveNext();

XPathNavigator nav2 = iterator.Current.Clone();
string min = nav.Value;
return int.Parse(min);
</code>```

```<code><ADSL_CHECKER>
  <ERRORID>0</ERRORID>
  <INPUT>01491410786</INPUT>
  <INPUTTYPE>TELNO</INPUTTYPE>
  <FIXEDRATE>
    <RAG>G</RAG>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </FIXEDRATE>
  <RATEADAPTIVE>
    <RAG>G</RAG>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </RATEADAPTIVE>
  <MAX>
    <RAG>G</RAG>
    <SPEED>4500</SPEED>
    <MINRANGE>3500</MINRANGE>
    <MAXRANGE>5500</MAXRANGE>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </MAX>
  <WBC>
    <RAG>G</RAG>
    <SPEED>5500</SPEED>
    <MINRANGE>4500</MINRANGE>
    <MAXRANGE>6500</MAXRANGE>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </WBC>
  <WBCFTTC>
    <RAG>G</RAG>
    <DOWNSPEED>32500</DOWNSPEED>
    <UPSPEED>7200</UPSPEED>
    <MINRANGE />
    <MAXRANGE />
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </WBCFTTC>
  <EXCHANGECODE>THHT</EXCHANGECODE>
  <EXCHANGENAME>HENLEY-ON-THAMES</EXCHANGENAME>
  <REASONCODE>L</REASONCODE>
  <VPCONTENTION>N</VPCONTENTION>
  <SPNAME />
  <CAD />
  <CPNAME>BE UN LIMITED</CPNAME>
  <CPCONTACTNO>02074795000</CPCONTACTNO>
  <POSTCODE>RG9 1LT</POSTCODE>
  <SUGGESTEDMSG>Your exchange is ADSL enabled, and our initial test on your line indicates that your line should be able to have an ADSL broadband service that provides a fixed line speed up to 2Mbps.

    Our test also indicates that your line currently supports an estimated ADSL Max broadband line speed of 4.5Mbps. Similar lines predicted with this speed have achieved ADSL Max line speeds in the range of 3.5 to 5.5Mbps.
    Our test also indicates that your line currently supports an estimated ADSL2+ broadband line speed of 5.5Mbps. Similar lines predicted with this speed have achieved ADSL2+ line speed in the range of 4.5 to 6.5Mbps.
    Our test also indicates that your line currently supports a fibre technology with an estimated WBC FTTC Broadband where consumers have received downstream line speed of 32.5Mbps and upstream line speed of 7.2Mbps.
    The actual stable line speed supportable will be determined during the first 10 days of use. This speed may change over time, to ensure line stability is maintained.
    If you decide to place an order, a further test will be performed to confirm if your line is suitable for the service you wish to purchase.
    Thank you for your interest.
    Please note that postcode and address check results are indicative only. Most accurate results can be obtained from a telephone number check.
  </SUGGESTEDMSG>
  <SUPPLEMENTARYMSG>Note: If you already have a Broadband service enabled on this line and you want to switch service providers, you will need to contact both your current provider and your new provider to get your service changed over new and existing service provider to have this service transferred.
  </SUPPLEMENTARYMSG>
</ADSL_CHECKER>
</code>```

Text in XML was modified slightly for formatting purposes.  See previous version for exact.

答:
There are actually quite a few different methods of selecting the content of an XmlNode. Let me share a few. (You can of course modify the code to use a String of Xml instead of loading from an Xml file)

Using an XmlDocument object and SelectSingleNode()

```<code>//-----------------------------------------------------------------------------
// <copyright file="Program.cs" company="DCOM Productions">
//     Copyright (c) DCOM Productions.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------

namespace ConsoleApplication1 {
    using System;
    using System.Xml;

    class Program {
        static void Main(string[] args) {
            XmlDocument xdoc = new XmlDocument();
            try {
                xdoc.Load(".\\App.xml");
            }
            catch (System.Xml.XmlException ex) {
                // handle
            }
            XmlNode node = xdoc.SelectSingleNode("ADSL_CHECKER//MAX//MINRANGE");
            Console.WriteLine(node.InnerText);
            Console.ReadKey(true);
        }
    }
}
</code>```

Using an XDocument object and Element()

```<code>//-----------------------------------------------------------------------------
// <copyright file="Program.cs" company="DCOM Productions">
//     Copyright (c) DCOM Productions.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------

namespace ConsoleApplication1 {
    using System;
    using System.Xml;
    using System.Xml.Linq;

    class Program {
        static void Main(string[] args) {
            XDocument xdoc = XDocument.Load(".\\App.xml");
            XElement element = xdoc.Element("ADSL_CHECKER").Element("MAX").Element("MINRANGE");
            Console.WriteLine(element.Value);
            Console.ReadKey(true);
        }
    }
}
</code>```

Using an XDocument object and LINQ query

```<code>//-----------------------------------------------------------------------------
// <copyright file="Program.cs" company="DCOM Productions">
//     Copyright (c) DCOM Productions.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------

namespace ConsoleApplication1 {
    using System;
    using System.Linq;
    using System.Xml;
    using System.Xml.Linq;

    class Program {
        static void Main(string[] args) {
            XDocument xdoc = XDocument.Load(".\\App.xml");
            var result = from e in xdoc.Element("ADSL_CHECKER").Element("MAX").Elements()
                         where e.Name == "MINRANGE"
                         select e;
            Console.WriteLine(result.First().Value);
            Console.ReadKey(true);
        }
    }
}
</code>```

It is always important that your XPath's are correct, and as always refer to the Msdn Documentation for help on using XmlDocument and XDocument.

Title: Using xpath with c#, help

Body:
I'm trying to select the content of MINRANGE of the below XML. This is the code I'm using, the string min just gives me a long block of text not the node i wanted.

XPathDocument _BTCall = new XPathDocument(callUrl);
XPathNavigator nav = _BTCall.CreateNavigator();
XPathExpression exp;
exp = nav.Compile("//MAX/MINRANGE");
XPathNodeIterator iterator = nav.Select(exp);
iterator.MoveNext();

XPathNavigator nav2 = iterator.Current.Clone();
string min = nav.Value;
return int.Parse(min);

<ADSL_CHECKER>
  <ERRORID>0</ERRORID>
  <INPUT>01491410786</INPUT>
  <INPUTTYPE>TELNO</INPUTTYPE>
  <FIXEDRATE>
    <RAG>G</RAG>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </FIXEDRATE>
  <RATEADAPTIVE>
    <RAG>G</RAG>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </RATEADAPTIVE>
  <MAX>
    <RAG>G</RAG>
    <SPEED>4500</SPEED>
    <MINRANGE>3500</MINRANGE>
    <MAXRANGE>5500</MAXRANGE>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </MAX>
  <WBC>
    <RAG>G</RAG>
    <SPEED>5500</SPEED>
    <MINRANGE>4500</MINRANGE>
    <MAXRANGE>6500</MAXRANGE>
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </WBC>
  <WBCFTTC>
    <RAG>G</RAG>
    <DOWNSPEED>32500</DOWNSPEED>
    <UPSPEED>7200</UPSPEED>
    <MINRANGE />
    <MAXRANGE />
    <READYDATE />
    <EXCHSTATE>E</EXCHSTATE>
    <CAPACITY />
  </WBCFTTC>
  <EXCHANGECODE>THHT</EXCHANGECODE>
  <EXCHANGENAME>HENLEY-ON-THAMES</EXCHANGENAME>
  <REASONCODE>L</REASONCODE>
  <VPCONTENTION>N</VPCONTENTION>
  <SPNAME />
  <CAD />
  <CPNAME>BE UN LIMITED</CPNAME>
  <CPCONTACTNO>02074795000</CPCONTACTNO>
  <POSTCODE>RG9 1LT</POSTCODE>
  <SUGGESTEDMSG>Your exchange is ADSL enabled, and our initial test on your line indicates that your line should be able to have an ADSL broadband service that provides a fixed line speed up to 2Mbps.

    Our test also indicates that your line currently supports an estimated ADSL Max broadband line speed of 4.5Mbps. Similar lines predicted with this speed have achieved ADSL Max line speeds in the range of 3.5 to 5.5Mbps.
    Our test also indicates that your line currently supports an estimated ADSL2+ broadband line speed of 5.5Mbps. Similar lines predicted with this speed have achieved ADSL2+ line speed in the range of 4.5 to 6.5Mbps.
    Our test also indicates that your line currently supports a fibre technology with an estimated WBC FTTC Broadband where consumers have received downstream line speed of 32.5Mbps and upstream line speed of 7.2Mbps.
    The actual stable line speed supportable will be determined during the first 10 days of use. This speed may change over time, to ensure line stability is maintained.
    If you decide to place an order, a further test will be performed to confirm if your line is suitable for the service you wish to purchase.
    Thank you for your interest.
    Please note that postcode and address check results are indicative only. Most accurate results can be obtained from a telephone number check.
  </SUGGESTEDMSG>
  <SUPPLEMENTARYMSG>Note: If you already have a Broadband service enabled on this line and you want to switch service providers, you will need to contact both your current provider and your new provider to get your service changed over new and existing service provider to have this service transferred.
  </SUPPLEMENTARYMSG>
</ADSL_CHECKER>

Text in XML was modified slightly for formatting purposes.  See previous version for exact.

Body:
There are actually quite a few different methods of selecting the content of an XmlNode. Let me share a few. (You can of course modify the code to use a String of Xml instead of loading from an Xml file)

Using an XmlDocument object and SelectSingleNode()

//-----------------------------------------------------------------------------
// <copyright file="Program.cs" company="DCOM Productions">
//     Copyright (c) DCOM Productions.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------

namespace ConsoleApplication1 {
    using System;
    using System.Xml;

    class Program {
        static void Main(string[] args) {
            XmlDocument xdoc = new XmlDocument();
            try {
                xdoc.Load(".\\App.xml");
            }
            catch (System.Xml.XmlException ex) {
                // handle
            }
            XmlNode node = xdoc.SelectSingleNode("ADSL_CHECKER//MAX//MINRANGE");
            Console.WriteLine(node.InnerText);
            Console.ReadKey(true);
        }
    }
}

Using an XDocument object and Element()

//-----------------------------------------------------------------------------
// <copyright file="Program.cs" company="DCOM Productions">
//     Copyright (c) DCOM Productions.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------

namespace ConsoleApplication1 {
    using System;
    using System.Xml;
    using System.Xml.Linq;

    class Program {
        static void Main(string[] args) {
            XDocument xdoc = XDocument.Load(".\\App.xml");
            XElement element = xdoc.Element("ADSL_CHECKER").Element("MAX").Element("MINRANGE");
            Console.WriteLine(element.Value);
            Console.ReadKey(true);
        }
    }
}

Using an XDocument object and LINQ query

//-----------------------------------------------------------------------------
// <copyright file="Program.cs" company="DCOM Productions">
//     Copyright (c) DCOM Productions.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------

namespace ConsoleApplication1 {
    using System;
    using System.Linq;
    using System.Xml;
    using System.Xml.Linq;

    class Program {
        static void Main(string[] args) {
            XDocument xdoc = XDocument.Load(".\\App.xml");
            var result = from e in xdoc.Element("ADSL_CHECKER").Element("MAX").Elements()
                         where e.Name == "MINRANGE"
                         select e;
            Console.WriteLine(result.First().Value);
            Console.ReadKey(true);
        }
    }
}

It is always important that your XPath's are correct, and as always refer to the Msdn Documentation for help on using XmlDocument and XDocument.