问:
DISTANCE expected input to be an agent but got the agentset (agentset, 16 patches) instead
I keep getting this error message (DISTANCE expected input to be an agent but got the agentset (agentset, 16 patches) instead.) at the bottom of my code when I run the following code:

```<code>globals
[
  x-grid-size ;; Global variable for inter-city grid-sizing in the x direction
  y-grid-size ;; Global variable for inter-city grid-sizing in the y-direction
  grid-x-inc ;; Global variable for inter-city street spacing in x-direction
  grid-y-inc ;; Global variable for inter-city street spacing in y-direction
  roads ;; Global variable for inter-city road network
  outer-roads ;; Global variable for outer-city road network
  a-station
]

breed [inter-buildings inter-building] ;; Inter-city buildings such as office, retail, business, apartments, etc.
breed [outer-buildings outer-building] ;; Outer-city buildings such as residential, reatail, apartments, etc.
breed [AVs AV]

AVs-own
[
  goal
  trip-status ;; (0 = heading to station, 1 = pick-up passenger from station, 2 = heading to drop-off point)
  destination ;;
]

patches-own
[
  my-row ;; The row of the intersection counting from the upper left corner of the world.  -1 for non-intersection patches.
  my-column ;; The column of the intersection counting from the upper left corner of the world. -1 for non-intersection patches.
]

to setup
  clear-all
  setup-globals ;; Command for setting up and initializing the global variables
  setup-patches ;; Command for setting up the patches for the inter-city and outer-city zones of simulation

  ;;setup-building-infras ;; Command for setting up the building infrastructure on approp. patches
  if show-buildings? ;; if the show-building switch is true then building infras will be shown
  [
    create-inter-buildings Inter-City_Density ;; Creating the inter-city building density
    [
      set heading 0
      set shape "square"
      set size (random 0.5) + 1
      set color grey
      move-to one-of patches with [pcolor != white] ;; if building is on the road, move it to patch that isn't white
      setxy (-25 + random-float 50) (-25 + random-float 50) ;; Set position building infras anywhere ranging from -25 to 25 for x- and y-directions
      ask inter-buildings
      [
        if (pcolor = white) ;; if building infras. still lands on road move to patch that isn't white in color
        [
          move-to one-of patches with [pcolor != white]
        ]

        if (pcolor = red)
        [
          move-to one-of patches with [pcolor = 96]
        ]

        ifelse (pcolor = white)
        [
          move-to one-of patches with [pcolor != white]
        ]

        [
          if (pcolor = 66)
          [
            move-to one-of patches with [pcolor != 66]
          ]
        ]
      ]
    ]

    create-outer-buildings Outer-City_Density ;; Creating the outer-city building density
    [
      set heading 0
      set shape "square"
      set size (random 0.05) + 0.65
      set color yellow
      move-to one-of patches with [pcolor != white] ;; if building is on the road, move it to patch that isn't white
      setxy (0 + random-float 0) (0 + random-float 0) ;; Set position building infras anywhere ranging from -50 to 50 for x- and y-directions

      ask outer-buildings
      [
        if (pcolor = white) ;; if building infras. still lands on road move to patch that isn't white in color
        [
          move-to one-of patches with [pcolor != white]
        ]

        if (pcolor = red)
        [
          move-to one-of patches with [pcolor = 96]
        ]

        ifelse (pcolor = white)
        [
          move-to one-of patches with [pcolor != white]
        ]

        [
          if (pcolor = 66)
          [
            move-to one-of patches with [pcolor != 66]
          ]
        ]
      ]
    ]
  ]

  create-AVs (Market_Pentr) * Vehicles
  [
    set size 0.4
    set shape "car"
    set color orange
    move-to one-of roads
    set goal a-station
    set-heading-to-station

  ]

  create-TVs (1 - Market_Pentr) * Vehicles
  [
    set size 0.5
    set shape "car"
    set color magenta
    move-to one-of roads
  ]
 reset-ticks
end

to set-heading-to-station
  set trip-status 0

  let goal-candidates patches with [pcolor = red and any? neighbors with [pcolor = white]]
  set a-station one-of goal-candidates

  set destination one-of goal-candidates with [self != [a-station] of myself]
end

to setup-patches ;; Command for setting up patch design for simulation
  ask patches
  [
    ifelse ((pxcor <= 25 and pxcor >= -25) and (pycor <= 25 and pycor >= -23)) ;; if a patch is between pxcor and pycor of -25 and 25
    [
      set my-row -1
      set my-column -1
      set pcolor yellow + 3 ;; set the patch's color to yellow for inter-city block representation
    ]

    [
      set pcolor 96 ;; otherwise set the patch's color to a modified sky blue for outer-city block representation
    ]
  ]

  ask patches
  [
    if ((pxcor <= 25 and pxcor >= -25) and (pycor <= 25 and pycor >= -25))
    [
      set roads patches with
      [
        (floor ((pxcor + max-pxcor - floor (grid-x-inc - 1)) mod grid-x-inc) = 0) or
        (floor ((pycor + max-pycor) mod grid-y-inc) = 0)
      ]
    ]
  ]

  ;; setup the a-station
  set a-station patches with [(pxcor >= 36 and pxcor <= 39) and (pycor >= 37 and pycor <= 40)]
  ask a-station
  [
    set pcolor red
  ]

ask roads
  [
    ifelse ((pxcor <= 25 and pxcor >= -26) and (pycor <= 26 and pycor >= -25))
    [
      set pcolor white
    ]

    [
      set pcolor white ;; this is a placeholder
    ]
  ]
end

to Drive-Around
  ask AVs
  [
    if [pcolor] of patch-here = white
    [
      face drive-forward
      forward AV-speed
    ]
  ]
end

to-report drive-forward
  ask AVs
  [
    if goal = a-station ;;and (member? patch-here [neighbors4] of a-station) ;; CHANGE THIS SO IS CONDUCIVE WITH PEDESTRIAN AGENTS LATER ON
    [
      set trip-status 1
      set goal destination
    ]

    if goal = destination ;;and (member? patch-here [neighbors4] of destination)
    [
      set trip-status 2
      ;; this could be the count of the number of assisted citizens

      set-heading-to-station
      let A-Station_X_Cor [pxcor] of a-station
      let A-Station_Y_Cor [pycor] of a-station
      let Destination_X_Cor [pxcor] of destination
      let Destination_Y_Cor [pycor] of destination

      let required_range 1.5 * (
        abs(A-Station_X_Cor - [xcor] of myself) +
        abs(Destination_X_Cor - A-Station_X_Cor) +
        abs(A-Station_Y_Cor - [ycor] of myself) +
        abs(Destination_Y_Cor - A-Station_Y_Cor))

      if required_range < 50
      [
        set goal a-station
      ]
    ]
  ]

  let choices neighbors with [pcolor = white]
  let choice min-one-of choices [distance [goal] of myself]
  report choice
end
</code>```

I am trying to see if I can get the vehicle agents to move to a specific location in simulation, but at the same time stay on the white patches which are the roadways in my city grid system. One thing to note is that the primitive known as distance keeps giving me errors and I am not sure what the error message is telling me nor do I know what to do at this point. I have tried placing an if statement in the to Drive-Around command but it doesn't seem to remove the error message.

答:
In one place you have:

```<code>set a-station patches with [...]
</code>```

which makes a-station hold an agentset.

In another place you have:

```<code>set goal a-station
</code>```

if a-station was holding an agentset, now goal is also holding an agentset.

And then when you do:

```<code>distance [goal] of myself
</code>```

that's an error, because you can't compute the distance to agentset. You can only compute the distance to an individual agent (patch or turtle).

I don't know what fix to suggest, because I don't understand enough about the intent of the code.

Body:
I keep getting this error message (DISTANCE expected input to be an agent but got the agentset (agentset, 16 patches) instead.) at the bottom of my code when I run the following code:

globals
[
  x-grid-size ;; Global variable for inter-city grid-sizing in the x direction
  y-grid-size ;; Global variable for inter-city grid-sizing in the y-direction
  grid-x-inc ;; Global variable for inter-city street spacing in x-direction
  grid-y-inc ;; Global variable for inter-city street spacing in y-direction
  roads ;; Global variable for inter-city road network
  outer-roads ;; Global variable for outer-city road network
  a-station
]

breed [inter-buildings inter-building] ;; Inter-city buildings such as office, retail, business, apartments, etc.
breed [outer-buildings outer-building] ;; Outer-city buildings such as residential, reatail, apartments, etc.
breed [AVs AV]

AVs-own
[
  goal
  trip-status ;; (0 = heading to station, 1 = pick-up passenger from station, 2 = heading to drop-off point)
  destination ;;
]

patches-own
[
  my-row ;; The row of the intersection counting from the upper left corner of the world.  -1 for non-intersection patches.
  my-column ;; The column of the intersection counting from the upper left corner of the world. -1 for non-intersection patches.
]

to setup
  clear-all
  setup-globals ;; Command for setting up and initializing the global variables
  setup-patches ;; Command for setting up the patches for the inter-city and outer-city zones of simulation

  ;;setup-building-infras ;; Command for setting up the building infrastructure on approp. patches
  if show-buildings? ;; if the show-building switch is true then building infras will be shown
  [
    create-inter-buildings Inter-City_Density ;; Creating the inter-city building density
    [
      set heading 0
      set shape "square"
      set size (random 0.5) + 1
      set color grey
      move-to one-of patches with [pcolor != white] ;; if building is on the road, move it to patch that isn't white
      setxy (-25 + random-float 50) (-25 + random-float 50) ;; Set position building infras anywhere ranging from -25 to 25 for x- and y-directions
      ask inter-buildings
      [
        if (pcolor = white) ;; if building infras. still lands on road move to patch that isn't white in color
        [
          move-to one-of patches with [pcolor != white]
        ]

        if (pcolor = red)
        [
          move-to one-of patches with [pcolor = 96]
        ]

        ifelse (pcolor = white)
        [
          move-to one-of patches with [pcolor != white]
        ]

        [
          if (pcolor = 66)
          [
            move-to one-of patches with [pcolor != 66]
          ]
        ]
      ]
    ]

    create-outer-buildings Outer-City_Density ;; Creating the outer-city building density
    [
      set heading 0
      set shape "square"
      set size (random 0.05) + 0.65
      set color yellow
      move-to one-of patches with [pcolor != white] ;; if building is on the road, move it to patch that isn't white
      setxy (0 + random-float 0) (0 + random-float 0) ;; Set position building infras anywhere ranging from -50 to 50 for x- and y-directions

      ask outer-buildings
      [
        if (pcolor = white) ;; if building infras. still lands on road move to patch that isn't white in color
        [
          move-to one-of patches with [pcolor != white]
        ]

        if (pcolor = red)
        [
          move-to one-of patches with [pcolor = 96]
        ]

        ifelse (pcolor = white)
        [
          move-to one-of patches with [pcolor != white]
        ]

        [
          if (pcolor = 66)
          [
            move-to one-of patches with [pcolor != 66]
          ]
        ]
      ]
    ]
  ]

  create-AVs (Market_Pentr) * Vehicles
  [
    set size 0.4
    set shape "car"
    set color orange
    move-to one-of roads
    set goal a-station
    set-heading-to-station

  ]

  create-TVs (1 - Market_Pentr) * Vehicles
  [
    set size 0.5
    set shape "car"
    set color magenta
    move-to one-of roads
  ]
 reset-ticks
end

to set-heading-to-station
  set trip-status 0

  let goal-candidates patches with [pcolor = red and any? neighbors with [pcolor = white]]
  set a-station one-of goal-candidates

  set destination one-of goal-candidates with [self != [a-station] of myself]
end

to setup-patches ;; Command for setting up patch design for simulation
  ask patches
  [
    ifelse ((pxcor <= 25 and pxcor >= -25) and (pycor <= 25 and pycor >= -23)) ;; if a patch is between pxcor and pycor of -25 and 25
    [
      set my-row -1
      set my-column -1
      set pcolor yellow + 3 ;; set the patch's color to yellow for inter-city block representation
    ]

    [
      set pcolor 96 ;; otherwise set the patch's color to a modified sky blue for outer-city block representation
    ]
  ]

  ask patches
  [
    if ((pxcor <= 25 and pxcor >= -25) and (pycor <= 25 and pycor >= -25))
    [
      set roads patches with
      [
        (floor ((pxcor + max-pxcor - floor (grid-x-inc - 1)) mod grid-x-inc) = 0) or
        (floor ((pycor + max-pycor) mod grid-y-inc) = 0)
      ]
    ]
  ]

  ;; setup the a-station
  set a-station patches with [(pxcor >= 36 and pxcor <= 39) and (pycor >= 37 and pycor <= 40)]
  ask a-station
  [
    set pcolor red
  ]

ask roads
  [
    ifelse ((pxcor <= 25 and pxcor >= -26) and (pycor <= 26 and pycor >= -25))
    [
      set pcolor white
    ]

    [
      set pcolor white ;; this is a placeholder
    ]
  ]
end

to Drive-Around
  ask AVs
  [
    if [pcolor] of patch-here = white
    [
      face drive-forward
      forward AV-speed
    ]
  ]
end

to-report drive-forward
  ask AVs
  [
    if goal = a-station ;;and (member? patch-here [neighbors4] of a-station) ;; CHANGE THIS SO IS CONDUCIVE WITH PEDESTRIAN AGENTS LATER ON
    [
      set trip-status 1
      set goal destination
    ]

    if goal = destination ;;and (member? patch-here [neighbors4] of destination)
    [
      set trip-status 2
      ;; this could be the count of the number of assisted citizens

      set-heading-to-station
      let A-Station_X_Cor [pxcor] of a-station
      let A-Station_Y_Cor [pycor] of a-station
      let Destination_X_Cor [pxcor] of destination
      let Destination_Y_Cor [pycor] of destination

      let required_range 1.5 * (
        abs(A-Station_X_Cor - [xcor] of myself) +
        abs(Destination_X_Cor - A-Station_X_Cor) +
        abs(A-Station_Y_Cor - [ycor] of myself) +
        abs(Destination_Y_Cor - A-Station_Y_Cor))

      if required_range < 50
      [
        set goal a-station
      ]
    ]
  ]

  let choices neighbors with [pcolor = white]
  let choice min-one-of choices [distance [goal] of myself]
  report choice
end

I am trying to see if I can get the vehicle agents to move to a specific location in simulation, but at the same time stay on the white patches which are the roadways in my city grid system. One thing to note is that the primitive known as distance keeps giving me errors and I am not sure what the error message is telling me nor do I know what to do at this point. I have tried placing an if statement in the to Drive-Around command but it doesn't seem to remove the error message.

Body:
In one place you have:

set a-station patches with [...]

which makes a-station hold an agentset.

In another place you have:

set goal a-station

if a-station was holding an agentset, now goal is also holding an agentset.

And then when you do:

distance [goal] of myself

that's an error, because you can't compute the distance to agentset. You can only compute the distance to an individual agent (patch or turtle).

I don't know what fix to suggest, because I don't understand enough about the intent of the code.


来源: stackexchange

问:
SQL Server Float data type calculation vs decimal
In the following query

```<code>declare @a float(23)
declare @b float(23)
declare @c float(53)
set @a = 123456789012.1234
set @b = 1234567.12345678
set @c = @a * @b
select @c

select LTRIM(STR((@c),32,12))

declare @x  decimal(16,4)
declare @y decimal(16,8)
declare @z decimal (32,12)

set @x = 123456789012.1234
set @y = 1234567.12345678
set @z = @x * @y
select @z
</code>```

I get answers as

```<code>1.52415693411713E+17
152415693411713020.000000000000
152415692881907790.143935926652
</code>```

From the above answers the third answer is the correct one. Is this the reason why float data type is called Approximate Numeric Data Type

Or am I doing something fundamentally wrong.

BTW this is due to a problem I have with legacy system wherein I have to use float as storage data type, at the same time in there should not be loss of precision while calculation.

Please suggest alternatives, or an explanation.

答:
Always check what is the value to have actually assigned to a variable:

```<code>declare @a float(23)
declare @b float(23)
declare @c float(23)

set @a = 123456789012.1234
set @b = 1234567.12345678
SET @c = @a * @b

select @a, @b, @c

GO

declare @a float
declare @b float
declare @c float

set @a = 123456789012.1234
set @b = 1234567.12345678
SET @c = @a * @b

select @a, @b, @c

GO

The outputs of the SELECTs:

1.234568E+11    1234567     1.524157E+17

123456789012.123    1234567.12345678    1.52415692881908E+17
</code>```

P.S. Operations of 2nd level (multiplication, division) and upper on decimal values use float point computing, so they cannot be any more precise than same operations on FLOAT values, assuming the same level of depth used for both types.

ContentLicense: CC BY-SA 3.0

Body:
In the following query

declare @a float(23)
declare @b float(23)
declare @c float(53)
set @a = 123456789012.1234
set @b = 1234567.12345678
set @c = @a * @b
select @c

select LTRIM(STR((@c),32,12))

declare @x  decimal(16,4)
declare @y decimal(16,8)
declare @z decimal (32,12)

set @x = 123456789012.1234
set @y = 1234567.12345678
set @z = @x * @y
select @z

I get answers as

1.52415693411713E+17
152415693411713020.000000000000
152415692881907790.143935926652

From the above answers the third answer is the correct one. Is this the reason why float data type is called Approximate Numeric Data Type

Or am I doing something fundamentally wrong.

BTW this is due to a problem I have with legacy system wherein I have to use float as storage data type, at the same time in there should not be loss of precision while calculation.

Please suggest alternatives, or an explanation.

Body:
Always check what is the value to have actually assigned to a variable:

declare @a float(23)
declare @b float(23)
declare @c float(23)

set @a = 123456789012.1234
set @b = 1234567.12345678
SET @c = @a * @b

select @a, @b, @c

GO

declare @a float
declare @b float
declare @c float

set @a = 123456789012.1234
set @b = 1234567.12345678
SET @c = @a * @b

select @a, @b, @c

GO

The outputs of the SELECTs:

1.234568E+11    1234567     1.524157E+17

123456789012.123    1234567.12345678    1.52415692881908E+17

P.S. Operations of 2nd level (multiplication, division) and upper on decimal values use float point computing, so they cannot be any more precise than same operations on FLOAT values, assuming the same level of depth used for both types.

ContentLicense: CC BY-SA 4.0


问:
Why image don't autosize in grid panel?
I tried to make a wp7 app with expression blend. But is there a problem that make me crazy!

I created a Panorama Controller, a Panorama Item and a Grid. In this grid i create an Image.

Why my image won't enlarge on width?

Here the screenshots:

The gray image is rounded also at dx, like sx side.

Here the config:

Is there a solution to enlarge my image on width like max size of grid?

How can I do this?

This is my snippet of code:

```<code><controls:PanoramaItem Foreground="Black" >
  <Grid Margin="1,26,160,46" Width="418">
    [...]
    <Grid Margin="0,190,8,0" VerticalAlignment="Top" Height="207" >
      <Image Source="JobRow.png" Margin="8,34,27,50" Stretch="None" />
    </Grid>
  </Grid>
</controls:PanoramaItem>
</code>```

Any idea please?

EDIT 1: if I change Stretch this is the result, my image enlarge only in height!

It's like that is blocked at certain position... but i don't know why!!!

EDIT 2: Changing default orientation will not enlarge my grid!

```<code><controls:PanoramaItem Foreground="Black" Width="438" Orientation="Horizontal">
</code>```

答:
Ok, solved removing all Width="xxx" from XAML file and after, from Expression Blend, manually resizing all the components.

I don't know why, but it works!

thanks all

Title: Why image don't autosize in grid panel?

Body:
I tried to make a wp7 app with expression blend. But is there a problem that make me crazy!

I created a Panorama Controller, a Panorama Item and a Grid. In this grid i create an Image.

Why my image won't enlarge on width?

Here the screenshots:

The gray image is rounded also at dx, like sx side.

Here the config:

Is there a solution to enlarge my image on width like max size of grid?

How can I do this?

This is my snippet of code:

<controls:PanoramaItem Foreground="Black" >
  <Grid Margin="1,26,160,46" Width="418">
    [...]
    <Grid Margin="0,190,8,0" VerticalAlignment="Top" Height="207" >
      <Image Source="JobRow.png" Margin="8,34,27,50" Stretch="None" />
    </Grid>
  </Grid>
</controls:PanoramaItem>

Any idea please?

EDIT 1: if I change Stretch this is the result, my image enlarge only in height!

It's like that is blocked at certain position... but i don't know why!!!

EDIT 2: Changing default orientation will not enlarge my grid!

<controls:PanoramaItem Foreground="Black" Width="438" Orientation="Horizontal">


问:
How to get the 3 highest values in a HashMap?
I have a hashmap which is the following:

```<code>    HashMap<String, Integer> hm = new HashMap<String, Integer>;
    hm.put("a", 1);
    hm.put("b", 12);
    hm.put("c", 53);
    hm.put("d", 2);
    hm.put("e", 17);
    hm.put("f", 8);
    hm.put("g", 8);
</code>```

How would I get the keys which have the 3 highest values? So it would return:

```<code>    "c", "e", "b"
</code>```

Thanks.

答:
This is a lot harder to read, but will perform a lot better:

```<code> public static List<String> firstN(Map<String, Integer> map, int n) {
    PriorityQueue<Entry<String, Integer>> pq = new PriorityQueue<>(
        n + 1, Map.Entry.comparingByValue()
    );

    int bound = n + 1;
    for (Entry<String, Integer> en : map.entrySet()) {
        pq.offer(en);
        if (pq.size() == bound) {
            pq.poll();
        }
    }

    int i = n;
    String[] array = new String[n];
    while (--i >= 0) {
        array[i] = pq.remove().getKey();
    }
    return Arrays.asList(array);
}
</code>```

If you know how a PriorityQueue works, this is rather trivial: it keeps only n + 1 elements at any given point in time. As elements are being added, the smallest element is removed, one by one.

When this is done, we insert elements into an array, but in reverse order (because a PriorityQueue keeps sorted only its head or the head is always max/min according to the Comparator).

You can even make this generic, or create a custom collector with streams for this.

Body:
I have a hashmap which is the following:

    HashMap<String, Integer> hm = new HashMap<String, Integer>;
    hm.put("a", 1);
    hm.put("b", 12);
    hm.put("c", 53);
    hm.put("d", 2);
    hm.put("e", 17);
    hm.put("f", 8);
    hm.put("g", 8);

How would I get the keys which have the 3 highest values? So it would return:

    "c", "e", "b"

Thanks.

Body:
This is a lot harder to read, but will perform a lot better:

 public static List<String> firstN(Map<String, Integer> map, int n) {
    PriorityQueue<Entry<String, Integer>> pq = new PriorityQueue<>(
        n + 1, Map.Entry.comparingByValue()
    );

    int bound = n + 1;
    for (Entry<String, Integer> en : map.entrySet()) {
        pq.offer(en);
        if (pq.size() == bound) {
            pq.poll();
        }
    }

    int i = n;
    String[] array = new String[n];
    while (--i >= 0) {
        array[i] = pq.remove().getKey();
    }
    return Arrays.asList(array);
}

If you know how a PriorityQueue works, this is rather trivial: it keeps only n + 1 elements at any given point in time. As elements are being added, the smallest element is removed, one by one.

When this is done, we insert elements into an array, but in reverse order (because a PriorityQueue keeps sorted only its head or the head is always max/min according to the Comparator).

You can even make this generic, or create a custom collector with streams for this.


问:
Trying to run 2 queries in one connection
I have a small piece of code I am trying to run in which I first check if the value exists and then update my database if it does not. My problem is I can run one query or the other but not both, because then it states the database is open and cannot be accessed. I know for sure I can write to the database. It is not read protected, located where I can't access it etc. The routine runs if I just try to update and not check. The check definitely results in no record. I have tried separate routines using completely different variables for the connection. I am stumped big time. I have tried closing, using, disposing, but I need someone a lot smarter than me to advise me of what I am doing wrong...

```<code>For Each strfile As String In flist
    Dim pth As String = Path.GetDirectoryName(strfile)
    Dim objReader As New System.IO.StreamReader(strfile)
    Dim dVal As String = String.Empty
    TextLine = objReader.ReadLine()
    SplitLine = Split(TextLine, ",")
    dVal = SplitLine(1)

    Using Dcon As New OleDbConnection
        Dcon.ConnectionString = dbProvider
        Dcon.Open()

        Dim q1 As String = "SELECT Shares.[_Date] FROM Shares WHERE (((Shares.[_Date])=" & dVal & "))"
        Dim comd As OleDbCommand = New OleDbCommand(q1, Dcon)
        comd.ExecuteReader()

        Dim q2 As String = "INSERT INTO Shares (Code, _Date, _Open, _High, _Low, _Close, _Volume) " &
                                                                  "SELECT F1, F2, F3, F4, F5, F6, F7 FROM [Text;HDR=NO;DATABASE=" & pth & "].[" & Path.GetFileName(strfile) & "];"

        Dim cmd As OleDbCommand = New OleDbCommand(q2, Dcon)

        cmd.ExecuteNonQuery()
        Dcon.Close()
    End Using
Next
</code>```

I have tried separate routines, I have tried opening, closing and then re-opening. I have tried one connection, I have tried two. Does anybody know what I am doing wrong and why it keeps telling me the database is exclusively opened and why it won't let me write to it?

Thank you in advance to those who help.

答:
The actual error message would have told you that there was already an open reader on the connection. The obvious solution is to close the data reader you opened.

There are some serious issues with your code. You call ExecuteReader and that is what opens the data reader that is blocking your second command but you never actually do anything with that data reader. You don't assign it to a variable so you can't get data from it and you can't close it either. You could do this:

Dim reader = comd.ExecuteReader()

'Use reader here.

reader.Close()
```

<p>The proper way is to use a <code>Using</code> block though:</p>

<pre class="lang-vb prettyprint-override"><code>Using reader = comd.ExecuteReader()
    'Use reader here.
End Using
</code>```

That said, if all you're trying to do is determine whether data exists and not actually use that data then you don't need a data reader at all. Just use a query that returns a Boolean and call ExecuteScalar, e.g.

Using connection As New OleDbConnection("connection string here")
    connection.Open()

    Dim query As New OleDbCommand("SELECT COUNT(*) > 0 FROM MyTable", connection)

    If CBool(query.ExecuteScalar()) Then
        'The table does contain data.
    End If
End Using
```

You may be able to use a more efficient query, depending on the database.

Body:
I have a small piece of code I am trying to run in which I first check if the value exists and then update my database if it does not. My problem is I can run one query or the other but not both, because then it states the database is open and cannot be accessed. I know for sure I can write to the database. It is not read protected, located where I can't access it etc. The routine runs if I just try to update and not check. The check definitely results in no record. I have tried separate routines using completely different variables for the connection. I am stumped big time. I have tried closing, using, disposing, but I need someone a lot smarter than me to advise me of what I am doing wrong...

For Each strfile As String In flist
    Dim pth As String = Path.GetDirectoryName(strfile)
    Dim objReader As New System.IO.StreamReader(strfile)
    Dim dVal As String = String.Empty
    TextLine = objReader.ReadLine()
    SplitLine = Split(TextLine, ",")
    dVal = SplitLine(1)

    Using Dcon As New OleDbConnection
        Dcon.ConnectionString = dbProvider
        Dcon.Open()

        Dim q1 As String = "SELECT Shares.[_Date] FROM Shares WHERE (((Shares.[_Date])=" & dVal & "))"
        Dim comd As OleDbCommand = New OleDbCommand(q1, Dcon)
        comd.ExecuteReader()

        Dim q2 As String = "INSERT INTO Shares (Code, _Date, _Open, _High, _Low, _Close, _Volume) " &
                                                                  "SELECT F1, F2, F3, F4, F5, F6, F7 FROM [Text;HDR=NO;DATABASE=" & pth & "].[" & Path.GetFileName(strfile) & "];"

        Dim cmd As OleDbCommand = New OleDbCommand(q2, Dcon)

        cmd.ExecuteNonQuery()
        Dcon.Close()
    End Using
Next

I have tried separate routines, I have tried opening, closing and then re-opening. I have tried one connection, I have tried two. Does anybody know what I am doing wrong and why it keeps telling me the database is exclusively opened and why it won't let me write to it?

Thank you in advance to those who help.

Body:
The actual error message would have told you that there was already an open reader on the connection. The obvious solution is to close the data reader you opened.

There are some serious issues with your code. You call ExecuteReader and that is what opens the data reader that is blocking your second command but you never actually do anything with that data reader. You don't assign it to a variable so you can't get data from it and you can't close it either. You could do this:

Dim reader = comd.ExecuteReader()

'Use reader here.

reader.Close()

The proper way is to use a Using block though:

Using reader = comd.ExecuteReader()
    'Use reader here.
End Using

That said, if all you're trying to do is determine whether data exists and not actually use that data then you don't need a data reader at all. Just use a query that returns a Boolean and call ExecuteScalar, e.g.

Using connection As New OleDbConnection("connection string here")
    connection.Open()

    Dim query As New OleDbCommand("SELECT COUNT(*) > 0 FROM MyTable", connection)

    If CBool(query.ExecuteScalar()) Then
        'The table does contain data.
    End If
End Using

You may be able to use a more efficient query, depending on the database.


问:
How to add a list with a list of lists so that each index would be a list containing a an element and a list in python
I have two lists to start with.

Say I had a list like
ls_1 = ["2", "1", "2", "1"] and a second list which contains lists ls_2 = [[2, 7], [1, 2], [4, 6], [5,2]]

how would I combine them into:

```<code>final_ls = [["2", [2, 7]], ["1", [1, 2]], ["2", [4, 6]], ["1", [5, 2]]]
</code>```

where final_ls[0][0] would be "2"?
and final_ls[1][0] would be "1"?

I've tried to append the lists but that doesn't work

Body:
I have two lists to start with.

Say I had a list like
ls_1 = ["2", "1", "2", "1"] and a second list which contains lists ls_2 = [[2, 7], [1, 2], [4, 6], [5,2]]

how would I combine them into:

final_ls = [["2", [2, 7]], ["1", [1, 2]], ["2", [4, 6]], ["1", [5, 2]]]

where final_ls[0][0] would be "2"?
and final_ls[1][0] would be "1"?

I've tried to append the lists but that doesn't work

Body:
Defining your lists:

ls_1 = ["2", "1", "2", "1"]
ls_2 = [[2, 7], [1, 2], [4, 6], [5,2]]

Use zip function as follows:

final_ls = list(zip(ls_1,ls_2))
print(final_ls)

# [('2', [2, 7]), ('1', [1, 2]), ('2', [4, 6]), ('1', [5, 2])]

Your required output:

final_ls[0][0]  #'2'
final_ls[1][0]  #'1'

Hope it helps.


问:
Swift Fatal error: Index out of range (out of bounds index)
Hello I am trying to learn swift. I have a little experience with javascript so i tried modeling this loop in the same manner i usually do. The function actually outputs what its supposed to but I keep getting an error message and I am unsure of what I am doing wrong. Here is my code:

```<code>import UIKit
let dir: [String] = ["north", "east", "south", "west"]
var num = dir.count
func move(){
    for i in 0 ... num{
        var holder = dir[i]
        switch holder{
        case "north":
            print("you've moved north")
        case "east":
            print("you've moved east")
        case "south":
            print("you've moved south")
        case "west":
            print("you've moved west")
        default:
            print("where you going?")
        }
        if i == 3{
            print("round the world")
        }

    }
}

move()
</code>```

i get this error on the last line "move()"

error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION
  (code=EXC_I386_INVOP, subcode=0x0).

this is what outputs to the console:

you've moved north

you've moved east

you've moved south

you've moved west

round the world

Fatal error: Index out of range: file
  /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.2.25.8/swift/stdlib/public/core/ContiguousArrayBuffer.swift,
  line 444

答: So, here you are first taking count of the num which is here 4.

Body:
Hello I am trying to learn swift. I have a little experience with javascript so i tried modeling this loop in the same manner i usually do. The function actually outputs what its supposed to but I keep getting an error message and I am unsure of what I am doing wrong. Here is my code:

import UIKit
let dir: [String] = ["north", "east", "south", "west"]
var num = dir.count
func move(){
    for i in 0 ... num{
        var holder = dir[i]
        switch holder{
        case "north":
            print("you've moved north")
        case "east":
            print("you've moved east")
        case "south":
            print("you've moved south")
        case "west":
            print("you've moved west")
        default:
            print("where you going?")
        }
        if i == 3{
            print("round the world")
        }

    }
}

move()

i get this error on the last line "move()"

error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION
  (code=EXC_I386_INVOP, subcode=0x0).

this is what outputs to the console:

you've moved north

you've moved east

you've moved south

you've moved west

round the world

Fatal error: Index out of range: file
  /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.2.25.8/swift/stdlib/public/core/ContiguousArrayBuffer.swift,
  line 444


Title: How do I create an index variable for unique values of X within a group Y?

Body:
I have the following table:

id_question  id_event   num_events
2015012713    49508          1
2015012711    49708          1
2015011523    41808          3
2015011523    44008          3
2015011523    44108          3
2015011522    41508          3
2015011522    43608          3
2015011522    43708          3
2015011521    39708          1
2015011519    44208          1

The third column gives the count of events by question. I want to create a variable that would index the events by question only where there are multiple events per question. It would look something like that:

id_question  id_event   num_events  index_event
2015012713    49508          1
2015012711    49708          1
2015011523    41808          3          1
2015011523    44008          3          2
2015011523    44108          3          3
2015011522    41508          3          1
2015011522    43608          3          2
2015011522    43708          3          3
2015011521    39708          1
2015011519    44208          1

How can I do that?

Body:
If num_events = 1 you can return NA or create a row-index for each id_question.

This can be done in base R :

df$index_event <- with(df, ave(num_events == 1, id_question,
                       FUN = function(x) replace(seq_along(x), x, NA)))

df
#   id_question id_event num_events index_event
#1   2015012713    49508          1          NA
#2   2015012711    49708          1          NA
#3   2015011523    41808          3           1
#4   2015011523    44008          3           2
#5   2015011523    44108          3           3
#6   2015011522    41508          3           1
#7   2015011522    43608          3           2
#8   2015011522    43708          3           3
#9   2015011521    39708          1          NA
#10  2015011519    44208          1          NA

dplyr :

library(dplyr)
df %>%
   group_by(id_question) %>%
   mutate(index_event = if_else(num_events == 1, NA_integer_, row_number()))

Or data.table :

library(data.table)
setDT(df)
df[,index_event := ifelse(num_events == 1, NA_integer_, seq_len(.N)), id_question]

data

df <- structure(list(id_question = c(2015012713L, 2015012711L, 2015011523L,
2015011523L, 2015011523L, 2015011522L, 2015011522L, 2015011522L,
2015011521L, 2015011519L), id_event = c(49508L, 49708L, 41808L,
44008L, 44108L, 41508L, 43608L, 43708L, 39708L, 44208L), num_events = c(1L,
1L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L)),class = "data.frame",row.names = c(NA, -10L))


问:
Creating 10 categorical and 10 continuous random variables and save them as a data frame
I would like to create a data frame with 10 categorical and 10 continuous random variables. I can do it using the following loop.

```<code>   p_val=rbeta(10,1,1)   #10 probabilities
    n=20
    library(truncnorm)
    mu_val=rtruncnorm(length(p_val),0,Inf, mean = 100, sd=5)#rnorm(length(p))
    d_mat_cat=matrix(NA, nrow = n, ncol = length(p))
    d_mat_cont= matrix(NA, nrow = n, ncol = length(p))
      for ( j in 1:length(p)){
        d_mat_cat[,j]=rbinom(n,1,p[j]) #Binary RV
        d_mat_cont[,j]=rnorm(n,mu_val[j]) #Cont. RV
      }
    d_mat=cbind(d_mat_cat, d_mat_cont)
</code>```

Any alternative options are appreciated.

答:
rbinom is vectorized over prob, and rnorm is vectorized over mean, so you can use this:

```<code>cbind(
  matrix(rbinom(n * length(p_val), size = 1, prob = p_val),
         ncol = length(p_val), byrow = TRUE),
  matrix(rnorm(n * length(mu_val), mean = mu_val),
         ncol = length(mu_val), byrow = TRUE)
)
</code>```

We can be a little clever with rep to make the call much cleaner:

```<code>p_val = c(0, 0.5, 1)
mu_val = c(1, 10, 100)
n = 4

##
matrix(
  c(
    rbinom(n * length(p_val), size = 1, prob = rep(c(0, .5, 1), each = n)),
    rnorm(n * length(mu_val), mean = rep(c(1, 10, 100), each = n))
  ),
  nrow = n,
)

#      [,1] [,2] [,3]       [,4]     [,5]     [,6]
# [1,]    0    1    1  1.1962718 9.373595 100.1739
# [2,]    0    0    1 -0.1854631 9.574706 100.0725
# [3,]    0    1    1  3.4873697 9.447363 100.1345
# [4,]    0    1    1  2.8467450 9.700975 101.3178
</code>```

Body:
I would like to create a data frame with 10 categorical and 10 continuous random variables. I can do it using the following loop.

   p_val=rbeta(10,1,1)   #10 probabilities
    n=20
    library(truncnorm)
    mu_val=rtruncnorm(length(p_val),0,Inf, mean = 100, sd=5)#rnorm(length(p))
    d_mat_cat=matrix(NA, nrow = n, ncol = length(p))
    d_mat_cont= matrix(NA, nrow = n, ncol = length(p))
      for ( j in 1:length(p)){
        d_mat_cat[,j]=rbinom(n,1,p[j]) #Binary RV
        d_mat_cont[,j]=rnorm(n,mu_val[j]) #Cont. RV
      }
    d_mat=cbind(d_mat_cat, d_mat_cont)

Any alternative options are appreciated.

Body:
rbinom is vectorized over prob, and rnorm is vectorized over mean, so you can use this:

cbind(
  matrix(rbinom(n * length(p_val), size = 1, prob = p_val),
         ncol = length(p_val), byrow = TRUE),
  matrix(rnorm(n * length(mu_val), mean = mu_val),
         ncol = length(mu_val), byrow = TRUE)
)

We can be a little clever with rep to make the call much cleaner:

p_val = c(0, 0.5, 1)
mu_val = c(1, 10, 100)
n = 4

##
matrix(
  c(
    rbinom(n * length(p_val), size = 1, prob = rep(c(0, .5, 1), each = n)),
    rnorm(n * length(mu_val), mean = rep(c(1, 10, 100), each = n))
  ),
  nrow = n,
)

#      [,1] [,2] [,3]       [,4]     [,5]     [,6]
# [1,]    0    1    1  1.1962718 9.373595 100.1739
# [2,]    0    0    1 -0.1854631 9.574706 100.0725
# [3,]    0    1    1  3.4873697 9.447363 100.1345
# [4,]    0    1    1  2.8467450 9.700975 101.3178


问:
Select First Child List Item That has Children
I have the following unordered list item with nested ul. How do I select the first li aka the text "List A" ?

I tried ul > li:first-child but this selects the first list item's child as well.

```<code><div class="container">
  <ul>
        <li>
          List A
          <ul>
            <li>List A sub</li>
            <li>List A sub</li>
            <li>List A sub</li>
            <li>List A sub</li>
          </ul>
        </li>
        <li>
          List B
          <ul>
            <li>List B sub</li>
            <li>List B sub</li>
            <li>List B sub</li>
            <li>List B sub</li>
          </ul>
        </li>
    </ul>
</div>
</code>```

答:
You should set it up with the default style of ul > li.

ul > li{
  font-weight: normal;
  color: gray;
}
.container > ul > li:first-child {
  font-weight: bold;
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <ul>
        <li>
          List A
          <ul>
            <li>List A sub</li>
            <li>List A sub</li>
            <li>List A sub</li>
            <li>List A sub</li>
          </ul>
        </li>
        <li>
          List B
          <ul>
            <li>List B sub</li>
            <li>List B sub</li>
            <li>List B sub</li>
            <li>List B sub</li>
          </ul>
        </li>
    </ul>
</div></code>```

Body:
I have the following unordered list item with nested ul. How do I select the first li aka the text "List A" ?

I tried ul > li:first-child but this selects the first list item's child as well.

          List A

List A sub

List A sub

List A sub

List A sub

          List B

List B sub

List B sub

List B sub

List B sub

Body:
You should set it up with the default style of ul > li.

ul > li{
  font-weight: normal;
  color: gray;
}
.container > ul > li:first-child {
  font-weight: bold;
  color: red;
}

<div class="container">
  <ul>
        <li>
          List A
          <ul>
            <li>List A sub</li>
            <li>List A sub</li>
            <li>List A sub</li>
            <li>List A sub</li>
          </ul>
        </li>
        <li>
          List B
          <ul>
            <li>List B sub</li>
            <li>List B sub</li>
            <li>List B sub</li>
            <li>List B sub</li>
          </ul>
        </li>
    </ul>
</div>


问:
How can I inspect the window object for mobile safari?
How can I inspect the window object for mobile safari?

Or more specifically window.navigator - trying to convert to string doesn't work and I can't explore it within the console either.

Thanks!

EDIT:

console.log(window.navigator);

console.log(String(window.navigator));

console.log(JSON.stringify(window.navigator));

console.log(window.navigator.serialize());

Also tried sending all these variations over the socket to the server and logging them there.

Output is either [object Navigator], "{}", or nothing

答:
Those outputs look entirely correct. E.g., when I ask for the string version of window.navigator, I correctly get

```<code>console.log(String(window.navigator));
"[object Navigator]"
</code>```

On the other hand, when I ask for a specific value, I get (in Chromium):

```<code>console.log(window.navigator.userAgent);
"Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.71 Safari/534.24"
</code>```

And when I try to enumerate all items, I get

```<code>for (var i in window.navigator) console.log(i);
language
product
mimeTypes
appVersion
plugins
onLine
platform
vendor
appCodeName
cookieEnabled
geolocation
appName
productSub
userAgent
vendorSub
javaEnabled
getStorageUpdates
</code>```

(please be aware that in the above line of code I didn't check for hasOwnProperty, which you normally should use when iterating over object elements).

Body:
Those outputs look entirely correct. E.g., when I ask for the string version of window.navigator, I correctly get

console.log(String(window.navigator));
"[object Navigator]"

On the other hand, when I ask for a specific value, I get (in Chromium):

console.log(window.navigator.userAgent);
"Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.71 Safari/534.24"

And when I try to enumerate all items, I get

for (var i in window.navigator) console.log(i);
language
product
mimeTypes
appVersion
plugins
onLine
platform
vendor
appCodeName
cookieEnabled
geolocation
appName
productSub
userAgent
vendorSub
javaEnabled
getStorageUpdates

(please be aware that in the above line of code I didn't check for hasOwnProperty, which you normally should use when iterating over object elements).


问:
Pivoting A Column in Pandas based on groups and dynamic column names
I have a data frame in python pandas as follows:
      ( the first two columns, mygroup1 & mygroup2 are groupby columns)

```<code>  df =

 **mygroup1  mygroup2   tname       @dt      @num   @vek**

   a         p          alpha        may      6       a
   b         q          alpha        june     8       b
   c         r          beta         may      9       c
   d         s          beta         june     11      d
</code>```

I want to pivot the table (the values in tname column) which should be the following with names of columns joined with tname values taken from the other columns (@dt,@num and @vec)

```<code> **mygroup1  mygroup2    alpha@dt    alpha@num    alpha@vec    beta@dt  beta@num  beta@vec**
    a         p           may            6            a           nan     nan        nan
    b         q           june           8            b            nan    nan        nan
    c         r           nan            nan        nan            may     9          c
    d         s            nan           nan        nan            june    11         d
</code>```

I am trying to do a pivot using pandas pivot table but not able to get in the below format which I really want. I will appreciate any help.

答:
You can do:

```<code>new_df = df.set_index(['mygroup1','mygroup2','tname']).unstack('tname')
new_df.columns = [f'{y}{x}' for x,y in new_df.columns]
new_df = new_df.sort_index(axis=1).reset_index()
</code>```

Output:

```<code>  mygroup1 mygroup2 alpha@dt  alpha@num alpha@vek beta@dt  beta@num beta@vek
0        a        p      may        6.0         a     NaN       NaN      NaN
1        b        q     june        8.0         b     NaN       NaN      NaN
2        c        r      NaN        NaN       NaN     may       9.0        c
3        d        s      NaN        NaN       NaN    june      11.0        d
</code>```

Body:
I have a data frame in python pandas as follows:
      ( the first two columns, mygroup1 & mygroup2 are groupby columns)

  df =

 **mygroup1  mygroup2   tname       @dt      @num   @vek**

   a         p          alpha        may      6       a
   b         q          alpha        june     8       b
   c         r          beta         may      9       c
   d         s          beta         june     11      d

I want to pivot the table (the values in tname column) which should be the following with names of columns joined with tname values taken from the other columns (@dt,@num and @vec)

 **mygroup1  mygroup2    alpha@dt    alpha@num    alpha@vec    beta@dt  beta@num  beta@vec**
    a         p           may            6            a           nan     nan        nan
    b         q           june           8            b            nan    nan        nan
    c         r           nan            nan        nan            may     9          c
    d         s            nan           nan        nan            june    11         d

I am trying to do a pivot using pandas pivot table but not able to get in the below format which I really want. I will appreciate any help.

Body:
You can do:

new_df = df.set_index(['mygroup1','mygroup2','tname']).unstack('tname')
new_df.columns = [f'{y}{x}' for x,y in new_df.columns]
new_df = new_df.sort_index(axis=1).reset_index()

Output:

  mygroup1 mygroup2 alpha@dt  alpha@num alpha@vek beta@dt  beta@num beta@vek
0        a        p      may        6.0         a     NaN       NaN      NaN
1        b        q     june        8.0         b     NaN       NaN      NaN
2        c        r      NaN        NaN       NaN     may       9.0        c
3        d        s      NaN        NaN       NaN    june      11.0        d


问:
React JS - How better to add React component to ReactDOM
Is it okay if I insert React component directly in document body by id?

Or it is better to wrap it in DIV?

index.js

```<code>ReactDOM.render(
    <Provider store={store()}>
        <App/>
    </Provider>,
    document.querySelector("#root")
)
</code>```

index.html

```<code><body class="d-flex flex-column h-100" id="root">
  <noscript>You need to enable JavaScript to run this app.</noscript>
</body>
</code>```

答:
I don't recommend to use body as root of the virtual DOM for 3 reasons:

body normally contains script tags, which might include your React logic. Rerendering body means that you need to take care of all your scripts too, and everytime body needs to be re-rendered, all your scripts need to be reload again, which is not efficient, not to mention side effect of reloading React code (which I don't have any experience to justify). The only way to avoid this is to put all your scripts into header, which is not recommended.

If you need to modify body, e.g. adding classes "modal-open" if you use Bootstrap modal, there are other solutions like using React's hook or an event listener dedicated to updating body.

Normally a web application product does not only use a DOM manipulator script, but also other scripts for business purposes (e.g. Google Analytics, Analytics.js, Google map). There are apps which contains more than 1 React script working independently. In those cases, the script logic should be separated and not coupled together. If there are 2 React scripts, the 2 root nodes should not be nested to avoid unneeded re-render.

Body:
Is it okay if I insert React component directly in document body by id?

Or it is better to wrap it in DIV?

index.js

ReactDOM.render(
    <Provider store={store()}>
        <App/>
    </Provider>,
    document.querySelector("#root")
)

index.html

  You need to enable JavaScript to run this app.


问:
NetLogo can 3d model be saved as Netlogo web?
Just wondering if NetLogo 3d model is allowed to export as NetLogo Web? Because I notice that the button for export to NetLogo Web in 3d version is grayed out. Thanks in advance!</p>

答: It cannot. NetLogo Web is 2D-only.</p>

Body: It cannot. NetLogo Web is 2D-only.


问:
macOS cannot verify the developer of "clang"
I updated to macos-catalina and I am trying to crosscompile c++ code for android using android-ndk-r18b

macOS cannot verify the developer of “clang". Are you sure you want to open it?

It asks me for all different executables/compilers (e.g arm-linux-androideabi-ranlib). I got around this by got around it by going to Security & Privacy and allowing all executables that show up there. Is there a more generic way to authorize everything within the android ndk?

答:
Open `System Preferences/Security & Privacy/Developer Tools.

Allow Terminal app to run software locally that does not meet system's security policy


问:
How to rotate a two-dimensional array to an arbitrary degree?
Say I have a bool[][], and I want to rotate it by 37 degrees. I am aware that the transformation wouldn't always be perfect, and that's okay. I've ready plenty of answers on here similar to my question, but the only solutions I've found only solve the problem for 90 degree increments. </p>

答:
The best way is to loop over the destination locations and for each of them read the correct source location. If you try the other way around (i.e. looping on source and writing on destination) you will end up with gaps.

The rotation formula is simple...

```<code>source_x = dest_x * c + dest_y * s + x0
source_y = dest_x * -s + dest_y * c + y0
</code>```

where c is the cosine of the angle, s is the sine of the angle and x0, y0 are used to correctly translate the rotated image. In psedudocode

```<code>for y = 0, 1, ... dest_height
    for x = 0, 1, ... dest_width
        src_x = c*x + s*y + x0
        src_y = -s*x + c*y + y0
        copy from source[src_y][src_x] to dest[y][x]
</code>```

x0, y0 can be computed so that the source center will end up in the destination center by

```<code> x0 = src_width/2 - c*dest_width/2 - s*dest_height/2
 y0 = src_height/2 - c*dest_height/2 + s*dest_width/2
</code>```

If instead of just using c = cos(angle) and s = sin(angle) you scale both of them with a factor k the resulting image will be rotated and zoomed around the center.

Note also that the formulas are bilinear in x and y; this means that you can use the full formula for the complete value for the first pixel of a row and then just do src_x += c and src_y -= s for each element of the same row because that is what happens when moving from x to x+1.

Note also that depending on source and destination size it may be that the computed source element is not available because out of the image. In this case there are several normally used options

Write a fixed value (e.g. false)

Don't write that destination cell

Do a "clamping" limiting both coordinates to the maximum allowed before reading

Do a "tiling" by normalizing coordinates using the modulo operator

Do a mirrored continuation by normalizing with TWICE the size and taking the symmetrical value 2*size-value if normalized value is bigger than the size

Body:
The best way is to loop over the destination locations and for each of them read the correct source location. If you try the other way around (i.e. looping on source and writing on destination) you will end up with gaps.

The rotation formula is simple...

source_x = dest_x * c + dest_y * s + x0
source_y = dest_x * -s + dest_y * c + y0

where c is the cosine of the angle, s is the sine of the angle and x0, y0 are used to correctly translate the rotated image. In psedudocode

for y = 0, 1, ... dest_height
    for x = 0, 1, ... dest_width
        src_x = c*x + s*y + x0
        src_y = -s*x + c*y + y0
        copy from source[src_y][src_x] to dest[y][x]

x0, y0 can be computed so that the source center will end up in the destination center by

 x0 = src_width/2 - c*dest_width/2 - s*dest_height/2
 y0 = src_height/2 - c*dest_height/2 + s*dest_width/2

If instead of just using c = cos(angle) and s = sin(angle) you scale both of them with a factor k the resulting image will be rotated and zoomed around the center.

Note also that the formulas are bilinear in x and y; this means that you can use the full formula for the complete value for the first pixel of a row and then just do src_x += c and src_y -= s for each element of the same row because that is what happens when moving from x to x+1.

Note also that depending on source and destination size it may be that the computed source element is not available because out of the image. In this case there are several normally used options

Write a fixed value (e.g. false)

Don't write that destination cell

Do a "clamping" limiting both coordinates to the maximum allowed before reading

Do a "tiling" by normalizing coordinates using the modulo operator

Do a mirrored continuation by normalizing with TWICE the size and taking the symmetrical value 2*size-value if normalized value is bigger than the size


问:
How to import node library into webpage using CDN
So I've created a simple program using node.js and a couple of libraries using puppeteer and kijiji-scraper from npm and I want to run it on a webpage like Github pages. In the past, I've had success using a CDN to import the node library I needed to do so by following the instructions on the readme. But for these packages, there aren't any instructions for importing using CDN. Is it just not possible to do so or am I missing something?

Packages:

https://www.jsdelivr.com/package/npm/kijiji-scraper

https://www.npmjs.com/package/puppeteer

答:
NodeJS and the web have fundamentally different moduling systems. You won't be able to import libraries written for Node in the web. If the libraries are pure JavaScript libraries (not relying on the standard library or native modules) or are browser-based libraries relying on the DOM, then you can use Browserify to compile the library's source code into a single file and include that on the web page with a
<script src="/app/index.js"></script>
```

I'm not sure what your file structure looks like but you get the idea.

Body:
NodeJS and the web have fundamentally different moduling systems. You won't be able to import libraries written for Node in the web. If the libraries are pure JavaScript libraries (not relying on the standard library or native modules) or are browser-based libraries relying on the DOM, then you can use Browserify to compile the library's source code into a single file and include that on the web page with a <script>. Otherwise, you'll need to restructure your application around this limitation.

In your case however, it looks like Kijiji is a client-side library and Browserify will be your solution here.

You can come to this conclusion by skimming some of its source code. You'll notice that there's a require call in it. The require function doesn't exist on the DOM API and hence will throw the error you're getting.

The solution I would use in your case would be a) Grunt or Gulp or b) compiling the code and import them statically.

If you have a more complex build chain, I would suggest including the browserify stage in it. I would also not use the CDN based library, rather use the NPM library. The browserify stage will bundle the library and all required dependencies into a single file that can be used in HTML

<script src="/static/kijiji.js"></script>
<script src="/app/index.js"></script>

I'm not sure what your file structure looks like but you get the idea.


问:
Nodejs script to generate oath2 token for ansible tower
How to write a node js script to generate oauth2 token for ansible tower.
Through cli :</p>

```<code>curl -u username:password -k -X POST https://<tower-host>/api/v2/tokens/
</code>```

答:
using axios (npm i axios) the script is:

```<code>var axios = require('axios');
var https = require('https');

const instance = axios.create({
  httpsAgent: new https.Agent({ rejectUnauthorized: false })
});

(async () => {
  var response = await instance({
    method: 'post',
    url: 'https://api/v2/token',
    auth: { username: 'foo', password: 'bar' }
  });
  console.log('response is', response.data);
})();
</code>```

agent explanation

Body:
How to write a node js script to generate oauth2 token for ansible tower.
Through cli :

curl -u username:password -k -X POST https://<tower-host>/api/v2/tokens/

Body:
using axios (npm i axios) the script is:

var axios = require('axios');
var https = require('https');

const instance = axios.create({
  httpsAgent: new https.Agent({ rejectUnauthorized: false })
});

(async () => {
  var response = await instance({
    method: 'post',
    url: 'https://api/v2/token',
    auth: { username: 'foo', password: 'bar' }
  });
  console.log('response is', response.data);
})();

agent explanation


问:
MSAL throws MsalClientException when calling MultipleAccountPublicClientApplication()
PublicClientApplication.createMultipleAccountPublicClientApplication() throws MsalClientException on some Android devices. In some devices everything works well.

Intune Company Portal app is installed in all the devices and acts as a broker app. The broker application view is not displayed in devices affected by the issue.

What could be the reason why it works on some devices and not in others although all use the same code base and has same broker app installed?

Android Version: 10

Tested MSAL versions: 1.0.1 and 1.5.1

Stack trace:

```<code>com.microsoft.identity.client.exception.MsalClientException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
at com.microsoft.identity.client.internal.controllers.MsalExceptionAdapter.msalExceptionFromBaseException(MsalExceptionAdapter.java:51)
at com.microsoft.identity.client.PublicClientApplication$2.onError(PublicClientApplication.java:873)
at com.microsoft.identity.client.PublicClientApplication$2.onError(PublicClientApplication.java:870)
at com.microsoft.identity.common.internal.controllers.CommandDispatcher$2.run(CommandDispatcher.java:176)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7860)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
Caused by: com.microsoft.identity.common.exception.ClientException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
at com.microsoft.identity.common.internal.controllers.ExceptionAdapter.baseExceptionFromException(ExceptionAdapter.java:252)
at com.microsoft.identity.common.internal.controllers.CommandDispatcher.executeCommand(CommandDispatcher.java:142)
at com.microsoft.identity.common.internal.controllers.CommandDispatcher.access$200(CommandDispatcher.java:52)
at com.microsoft.identity.common.internal.controllers.CommandDispatcher$1.run(CommandDispatcher.java:94)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
at com.microsoft.identity.client.internal.controllers.BrokerMsalController$5.putValueInSuccessEvent(BrokerMsalController.java:412)
at com.microsoft.identity.client.internal.controllers.BrokerMsalController$5.putValueInSuccessEvent(BrokerMsalController.java:392)
at com.microsoft.identity.client.internal.controllers.BrokerMsalController.invokeBrokerOperation(BrokerMsalController.java:221)
at com.microsoft.identity.client.internal.controllers.BrokerMsalController.getDeviceMode(BrokerMsalController.java:391)
at com.microsoft.identity.common.internal.controllers.GetDeviceModeCommand.execute(GetDeviceModeCommand.java:44)
at com.microsoft.identity.common.internal.controllers.GetDeviceModeCommand.execute(GetDeviceModeCommand.java:33)
at com.microsoft.identity.common.internal.controllers.CommandDispatcher.executeCommand(CommandDispatcher.java:137)
… 5 more
</code>```

答:
I'm not sure if this is your issue, but here is one possible reason:
under the docs, it states:
This function will pass back an MsalClientException object if it is unable to return IMultipleAccountPublicClientApplication. For example, when the device is marked as 'shared' (PublicClientApplication#isSharedDevice() is set to true)

meaning if the device is a shared device mode device, then that call to createmultiple... will fail with that msal exception..
to check if its a shared device, according to here https://learn.microsoft.com/en-ca/azure/active-directory/develop/tutorial-v2-shared-device-mode#set-up-an-android-device-in-shared-mode you can check through azure portal

it could very well not be your issue, but just a thought / something to check.

Body:
PublicClientApplication.createMultipleAccountPublicClientApplication() throws MsalClientException on some Android devices. In some devices everything works well.

Intune Company Portal app is installed in all the devices and acts as a broker app. The broker application view is not displayed in devices affected by the issue.

What could be the reason why it works on some devices and not in others although all use the same code base and has same broker app installed?

Android Version: 10

Tested MSAL versions: 1.0.1 and 1.5.1

Stack trace:

com.microsoft.identity.client.exception.MsalClientException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
at com.microsoft.identity.client.internal.controllers.MsalExceptionAdapter.msalExceptionFromBaseException(MsalExceptionAdapter.java:51)
at com.microsoft.identity.client.PublicClientApplication$2.onError(PublicClientApplication.java:873)
at com.microsoft.identity.client.PublicClientApplication$2.onError(PublicClientApplication.java:870)
at com.microsoft.identity.common.internal.controllers.CommandDispatcher$2.run(CommandDispatcher.java:176)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7860)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
Caused by: com.microsoft.identity.common.exception.ClientException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
at com.microsoft.identity.common.internal.controllers.ExceptionAdapter.baseExceptionFromException(ExceptionAdapter.java:252)
at com.microsoft.identity.common.internal.controllers.CommandDispatcher.executeCommand(CommandDispatcher.java:142)
at com.microsoft.identity.common.internal.controllers.CommandDispatcher.access$200(CommandDispatcher.java:52)
at com.microsoft.identity.common.internal.controllers.CommandDispatcher$1.run(CommandDispatcher.java:94)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
at com.microsoft.identity.client.internal.controllers.BrokerMsalController$5.putValueInSuccessEvent(BrokerMsalController.java:412)
at com.microsoft.identity.client.internal.controllers.BrokerMsalController$5.putValueInSuccessEvent(BrokerMsalController.java:392)
at com.microsoft.identity.client.internal.controllers.BrokerMsalController.invokeBrokerOperation(BrokerMsalController.java:221)
at com.microsoft.identity.client.internal.controllers.BrokerMsalController.getDeviceMode(BrokerMsalController.java:391)
at com.microsoft.identity.common.internal.controllers.GetDeviceModeCommand.execute(GetDeviceModeCommand.java:44)
at com.microsoft.identity.common.internal.controllers.GetDeviceModeCommand.execute(GetDeviceModeCommand.java:33)
at com.microsoft.identity.common.internal.controllers.CommandDispatcher.executeCommand(CommandDispatcher.java:137)
… 5 more


问:
Standard_init_linux.go:211: exec user process caused “exec format error”
The following code generates an error:
standard_init_linux.go:211: exec user process caused “exec format error”

Any pointers to what I’m doing wrong?

```<code>
FROM golang:alpine AS builder

ENV GO111MODULE=on CGO_ENABLED=0 GOOS=linux GOARCH=amd64 GOARCH=wasm GOOS=js

WORKDIR /build

COPY . .

COPY wasm_exec.js .
COPY server.go .
COPY main.wasm .
COPY manifest.json .
COPY sw.js .
COPY wasm_exec.js .
COPY app.js .
COPY index.html .

EXPOSE 8989
ENTRYPOINT ["./server.go"]
</code>```

答:
The error is because you are trying to execute server.go file without compiling you need to compile server.go to get the executable which then can be used as executable.

```<code>go build server.go
</code>```

Or you can directly run it using

```<code>go run server.go
</code>```

Body:
The following code generates an error:
standard_init_linux.go:211: exec user process caused “exec format error”

Any pointers to what I’m doing wrong?

FROM golang:alpine AS builder

ENV GO111MODULE=on CGO_ENABLED=0 GOOS=linux GOARCH=amd64 GOARCH=wasm GOOS=js

WORKDIR /build

COPY . .

COPY wasm_exec.js .
COPY server.go .
COPY main.wasm .
COPY manifest.json .
COPY sw.js .
COPY wasm_exec.js .
COPY app.js .
COPY index.html .

EXPOSE 8989
ENTRYPOINT ["./server.go"]

Body:
The error is because you are trying to execute server.go file without compiling you need to compile server.go to get the executable which then can be used as executable.

go build server.go

Or you can directly run it using

go run server.go


问:
Is it possible to have 3 delimiters for the explode function
Option 1 (spaces)

```<code>keyword keyword keyword
</code>```

Option 2 (line breaks)

```<code>keyword
keyword
keyword
</code>```

Option 3 (commas)

```<code>keyword, keyword, keyword
</code>```

Or would I have to use the split function instead? And if so, how?

答: Not as simple as preg_split, but strtok() is also an option</p>

Body:
Option 1 (spaces)

keyword keyword keyword

Option 2 (line breaks)

keyword
keyword
keyword

Option 3 (commas)

keyword, keyword, keyword

Or would I have to use the split function instead? And if so, how?


问:
How can I change text color of items in safe area in React Native?
I am trying to change the color of text and other icons in SafeAreaView (check this Screenshot) based on theme in react-native-ui-kitten. I tried setting color in stylesheet but no good.

答:
You could try Status bar's props barStyle like this:

import { StatusBar } from 'react-native';
...
<StatusBar barStyle="light-content" /> //or "dark-content"
...
```

DOC example

Body:
You could try Status bar's props barStyle like this:

import { StatusBar } from 'react-native';
...
<StatusBar barStyle="light-content" /> //or "dark-content"
...

DOC example


问:
Find Confidence via applying excel formula
I'm trying to find out the affinity among two products based on 16 transactions happened. First I calculated the support, which means no. of times the product bought in all 16 transactions.
Next one is confidence, which is nothing but the occurrence of another product provided the first one has already occurred.
Ex:- Confidence (11 when 7 occurred)=P(11intersection 7)= no. of (11 intersection 7)/no.of occurance of 7= (1/16)/(1/16)=100%
Similarly, for confidence (11 when 3 occurred)=(1/16)/(4/16)=25%

I want to find the confidence of all the products vs other products by applying excel formula. I'm not able to apply the formula to find the confidence among the products. The sheet is attached here. Confidence (expected Output) is the table where I want to find the formula to find confidence automatically.

Sample Data

enter image description here

enter image description here

答:
P(X) and P(X|Y) could be done by countif() and countifs(). To identify the correct column, use offset() and match()

with the location of data as

the formula in cell J3 of the Confidence matrix is:

```<code>=COUNTIFS(OFFSET($A$3:$A$18,0,MATCH($I3,$B$2:$G$2,0)),"=TRUE",OFFSET($A$3:$A$18,0,MATCH(J$2,$B$2:$G$2,0)),"=TRUE")/COUNTIF(OFFSET($A$3:$A$18,0,MATCH(J$2,$B$2:$G$2,0)),TRUE)

</code>```

which you can use to fill the rest of the matrix.

Body:
P(X) and P(X|Y) could be done by countif() and countifs(). To identify the correct column, use offset() and match()

with the location of data as

the formula in cell J3 of the Confidence matrix is:

=COUNTIFS(OFFSET($A$3:$A$18,0,MATCH($I3,$B$2:$G$2,0)),"=TRUE",OFFSET($A$3:$A$18,0,MATCH(J$2,$B$2:$G$2,0)),"=TRUE")/COUNTIF(OFFSET($A$3:$A$18,0,MATCH(J$2,$B$2:$G$2,0)),TRUE)

which you can use to fill the rest of the matrix.


问:
Pandas delete Column where Header is NAN
How can I drop all column with a NaN value from dataframes?

```<code>      count       bal  NaN        NaN      sum           NaN

0   10.534709  254.38   0  215490.85  -7118.52     2013-07-31
1    0.000000  135.39   0  227822.73 -10034.44     2013-08-31
2    0.000000  143.58   0  247432.23   -107.51     2013-09-30
</code>```

I have tried various versions of this:

```<code>df.drop ( '', axis = 1 )
</code>```

Thank you.

答:
might not be best solution but it worked.

I found a way to rename the NaN columns with the .fillna - here I just renamed them to 'z'.

after that I had a way to drop the columns.

```<code>        df.columns = df.columns.fillna ( 'z' )
        df.drop ( ['comments', 'z'], axis = 1, inplace=True )
</code>```

always open to a better idea.  cheers.

Body:
How can I drop all column with a NaN value from dataframes?

      count       bal  NaN        NaN      sum           NaN

0   10.534709  254.38   0  215490.85  -7118.52     2013-07-31
1    0.000000  135.39   0  227822.73 -10034.44     2013-08-31
2    0.000000  143.58   0  247432.23   -107.51     2013-09-30

I have tried various versions of this:

df.drop ( '', axis = 1 )

Thank you.

Body:
might not be best solution but it worked.

I found a way to rename the NaN columns with the .fillna - here I just renamed them to 'z'.

after that I had a way to drop the columns.

        df.columns = df.columns.fillna ( 'z' )
        df.drop ( ['comments', 'z'], axis = 1, inplace=True )

always open to a better idea.  cheers.


问:
How to make a rectangle of characters?
How to make a rectangle of characters?
I need to make such a picture appear in the console

```<code> **********
*          *
*          *
*          *
 **********
</code>```

But I get this:

```<code>*********
*********
*********
*********
*********
</code>```

Sides a and b are entered from the console.

```<code>    int a = requestNumber();
    int b = requestNumber();
    for (int i = 0; i < a; i++) {
        for (int j = 0; j < b; j++) {
            if (j == 0 || j < (b - 1))
            System.out.print("*");
            else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }
}
</code>```

答:
A pretty concise way to do it just a few lines:

```<code>int a = requestNumber();
int b = requestNumber();

System.out.println(" " + new String(new char[a]).replace("\0", "*"));
for (int i = 0; i < b; i++) {
    System.out.println("*" + new String(new char[a]).replace("\0", " ") + "*");
}
System.out.println(" " + new String(new char[a]).replace("\0", "*"));
</code>```

EDIT: Fixed typo, works now!

Title: How to make a rectangle of characters?

Body:
How to make a rectangle of characters?
I need to make such a picture appear in the console

 **********
*          *
*          *
*          *
 **********

But I get this:

*********
*********
*********
*********
*********

Sides a and b are entered from the console.

    int a = requestNumber();
    int b = requestNumber();
    for (int i = 0; i < a; i++) {
        for (int j = 0; j < b; j++) {
            if (j == 0 || j < (b - 1))
            System.out.print("*");
            else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }
}

Body:
A pretty concise way to do it just a few lines:

int a = requestNumber();
int b = requestNumber();

System.out.println(" " + new String(new char[a]).replace("\0", "*"));
for (int i = 0; i < b; i++) {
    System.out.println("*" + new String(new char[a]).replace("\0", " ") + "*");
}
System.out.println(" " + new String(new char[a]).replace("\0", "*"));

EDIT: Fixed typo, works now!


问:
How to get the next line with TextPointer.GetLineStartPosition() in a RichTextBox
I'm trying to get the lines of the RichTextBox.

Here they show how to do it:

Using GetLineStartPosition to get the end of a line in WPF RichTextBox

But for whatever reason I always get null as the return of GetLineStartPosition(1).

XAML

```<code>    <Grid>
        <StackPanel>
            <Button Height="40" Click="Button_Click"></Button>

            <RichTextBox x:Name="rtbEditor">
                <FlowDocument>
                    <Paragraph>Hello, world!
                        a
                        <LineBreak/>
                        b
                        <LineBreak/>
                        c
                        <LineBreak/>
                        d
                    </Paragraph>
                </FlowDocument>
            </RichTextBox>
        </StackPanel>
    </Grid>
</code>```

Code

```<code>        public MainWindow()
        {
            InitializeComponent();

            rtbEditor.AppendText("testtext" + "\r");
            rtbEditor.AppendText("testtext" + "\r");
            rtbEditor.AppendText("testtext" + "\r");
            rtbEditor.AppendText("testtext" + "\r\n");
            rtbEditor.AppendText("testtext" + "\r\n");
            rtbEditor.AppendText("testtext" + "\r\n");
            rtbEditor.AppendText("testtext" + "\n");
            rtbEditor.AppendText("testtext" + "\n");
            rtbEditor.AppendText("testtext" + "\n");
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            TextPointer contentStart = rtbEditor.Document.ContentStart;
            var nextStart = contentStart.GetLineStartPosition(1);
        }
</code>```

nextStart is null. What am I doing wrong here?

答:
This took a bit of research into how FlowDocuments and TextPointers worked. I'd suggest reading the TextPointer Remarks Section because it really helped me understand this.

My theory is that the GetLineStartPosition method won't work if the current TextPointer doesn't have a Paragraph to reference. Document.ContentStart gives you a TextPointer that's just before the first Paragraph in the FlowDocument. You can call GetNextInsertionPosition(LogicalDirection.Forward) to return a TextPointer to the next valid insertion point- in this case the first valid insertion point- in the document. From there you are inside the first Paragraph and GetLineStartPosition starts to work.

```<code>TextPointer contentStart = rtbEditor.Document.ContentStart.GetNextInsertionPosition(LogicalDirection.Forward);
var nextStart = contentStart.GetLineStartPosition(1);
</code>```

Body:
I'm trying to get the lines of the RichTextBox.

Here they show how to do it:

Using GetLineStartPosition to get the end of a line in WPF RichTextBox

But for whatever reason I always get null as the return of GetLineStartPosition(1).

XAML

    <Grid>
        <StackPanel>
            <Button Height="40" Click="Button_Click"></Button>

            <RichTextBox x:Name="rtbEditor">
                <FlowDocument>
                    <Paragraph>Hello, world!
                        a
                        <LineBreak/>
                        b
                        <LineBreak/>
                        c
                        <LineBreak/>
                        d
                    </Paragraph>
                </FlowDocument>
            </RichTextBox>
        </StackPanel>
    </Grid>

Code

        public MainWindow()
        {
            InitializeComponent();

            rtbEditor.AppendText("testtext" + "\r");
            rtbEditor.AppendText("testtext" + "\r");
            rtbEditor.AppendText("testtext" + "\r");
            rtbEditor.AppendText("testtext" + "\r\n");
            rtbEditor.AppendText("testtext" + "\r\n");
            rtbEditor.AppendText("testtext" + "\r\n");
            rtbEditor.AppendText("testtext" + "\n");
            rtbEditor.AppendText("testtext" + "\n");
            rtbEditor.AppendText("testtext" + "\n");
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            TextPointer contentStart = rtbEditor.Document.ContentStart;
            var nextStart = contentStart.GetLineStartPosition(1);
        }

nextStart is null. What am I doing wrong here?

Body:
This took a bit of research into how FlowDocuments and TextPointers worked. I'd suggest reading the TextPointer Remarks Section because it really helped me understand this.

My theory is that the GetLineStartPosition method won't work if the current TextPointer doesn't have a Paragraph to reference. Document.ContentStart gives you a TextPointer that's just before the first Paragraph in the FlowDocument. You can call GetNextInsertionPosition(LogicalDirection.Forward) to return a TextPointer to the next valid insertion point- in this case the first valid insertion point- in the document. From there you are inside the first Paragraph and GetLineStartPosition starts to work.

TextPointer contentStart = rtbEditor.Document.ContentStart.GetNextInsertionPosition(LogicalDirection.Forward);
var nextStart = contentStart.GetLineStartPosition(1);


问:
Getting "NA" when I run a standard deviation
Quick question. I read my csv file into the variable data. It has a column label var, which has numerical values.

When I run the command

```<code>sd(data$var)
</code>```

I get

```<code>[1] NA
</code>```

instead of my standard deviation.

Could you please help me figure out what I am doing wrong?

答:
I've made the mistake a time or two of reusing variable names in dplyr strings which has caused issues.

```<code>mtcars %>%
  group_by(gear) %>%
  mutate(ave = mean(hp)) %>%
  ungroup() %>%
  group_by(cyl) %>%
  summarise(med = median(ave),
            ave = mean(ave), # should've named this variable something different
            sd = sd(ave)) # this is the sd of my newly created variable "ave", not the original one.
</code>```

Body:
Quick question. I read my csv file into the variable data. It has a column label var, which has numerical values.

When I run the command

sd(data$var)

I get

[1] NA

instead of my standard deviation.

Could you please help me figure out what I am doing wrong?

Body:
I've made the mistake a time or two of reusing variable names in dplyr strings which has caused issues.

mtcars %>%
  group_by(gear) %>%
  mutate(ave = mean(hp)) %>%
  ungroup() %>%
  group_by(cyl) %>%
  summarise(med = median(ave),
            ave = mean(ave), # should've named this variable something different
            sd = sd(ave)) # this is the sd of my newly created variable "ave", not the original one.


问:
What is the difference between Lottie Events and Lottie EventListeners and How to use?
The documentation has both Events and EventListeners. I can get the EventListeners to fire but the Events do not have adequate documentation for me to get going. What is the difference and how do you use? Thank you.

https://github.com/airbnb/lottie-web#events

Events (Do not work, how to use?)

// From the Documentation

onComplete

onLoopComplete

onEnterFrame

onSegmentStart

you can also use addEventListener with the following events:

complete

loopComplete

enterFrame

segmentStart

config_ready (when initial config is done)

data_ready (when all parts of the animation have been loaded)

data_failed (when part of the animation can not be loaded)

loaded_images (when all image loads have either succeeded or errored)

DOMLoaded (when elements have been added to the DOM)

destroy

// End Documentation

From the standard addEventListener usage, this works...

```<code>birbSequence.addEventListener('loopComplete', (e) => {
    console.log(e);
});
</code>```

although 'complete' does not fire.

But to try out the stuff in Events like onEnterFrame?

```<code>var birbSequence = lottie.loadAnimation({
    container: bodyMovinContainer1,
    loop: true,
    renderer: 'svg',
    path: 'Birb Sequence 1.json',
    onEnterFrame: function(e) { console.log(e); }
});
</code>```

I am really new to using Lottie though so could use some help.

Just want a way to see how to use Events

答:
Let's say we have our lottie animation:

```<code>const anim = lottie.loadAnimation({
  container: '#container',
  renderer: 'svg',
  loop: true,
  autoplay: true,
  ...
})
</code>```

With Events:

```<code>anim.onComplete = function() {
  console.log('complete')
}
anim.onLoopComplete = function() {
  console.log('loopComplete')
}
</code>```

With addEventListener:

```<code>anim.addEventListener('complete', function() {
  console.log('complete')
})
anim.addEventListener('loopComplete', function() {
  console.log('loopComplete')
})
</code>```

Body:
The documentation has both Events and EventListeners. I can get the EventListeners to fire but the Events do not have adequate documentation for me to get going. What is the difference and how do you use? Thank you.

https://github.com/airbnb/lottie-web#events

Events (Do not work, how to use?)

// From the Documentation

onComplete

onLoopComplete

onEnterFrame

onSegmentStart

you can also use addEventListener with the following events:

complete

loopComplete

enterFrame

segmentStart

config_ready (when initial config is done)

data_ready (when all parts of the animation have been loaded)

data_failed (when part of the animation can not be loaded)

loaded_images (when all image loads have either succeeded or errored)

DOMLoaded (when elements have been added to the DOM)

destroy

// End Documentation

From the standard addEventListener usage, this works...

birbSequence.addEventListener('loopComplete', (e) => {
    console.log(e);
});

although 'complete' does not fire.

But to try out the stuff in Events like onEnterFrame?

var birbSequence = lottie.loadAnimation({
    container: bodyMovinContainer1,
    loop: true,
    renderer: 'svg',
    path: 'Birb Sequence 1.json',
    onEnterFrame: function(e) { console.log(e); }
});

I am really new to using Lottie though so could use some help.

Just want a way to see how to use Events

Body:
Let's say we have our lottie animation:

const anim = lottie.loadAnimation({
  container: '#container',
  renderer: 'svg',
  loop: true,
  autoplay: true,
  ...
})

With Events:

anim.onComplete = function() {
  console.log('complete')
}
anim.onLoopComplete = function() {
  console.log('loopComplete')
}

With addEventListener:

anim.addEventListener('complete', function() {
  console.log('complete')
})
anim.addEventListener('loopComplete', function() {
  console.log('loopComplete')
})


问:
How to filter outbound routing using Mule ESB?
I have a instance of Mule that is configured to process xml responses from a third party provider.  Recently the provider has moved to a new revision and hence changed the xml response.  Now I need a way to identify if the response is a v1 or v2 implementation and call the appropriate endpoint on my side to process the response.

What I have currently is:

```<code><service name="processResponse">
...
    <outbound>
        <pass-through-router>
            <cxf:outbound-endpoint address="..." clientClass="..." wsdlPort="..." wsdlLocation="..." operation="..."/>
        </pass-through-router>
   </outbound>
</service>
</code>```

I would prefer to add a filter in mule to identify the revision of the 3rd party (perhaps through the xml namespace in the response), and then call the appropriate class.  I cannot find any good examples of this.

Can someone provide an example of how this could be solved?

答:
I suspect the most straight forward means is a filtered route using an xpath filter. First define vm services for each version. Next you'll filter to them through a service with following outbound endpoint. A catch all is always a good idea.</p>

```<code><outbound>
  <filtering-router>
    <vm:outbound-endpoint ref="Version1"/>
    <expression-filter evaluator="jxpath" expression="/your/version1/xpath/descriminator"/>
  </filtering-router>
  <filtering-router>
    <vm:outbound-endpoint ref="Version2"/>
    <expression-filter evaluator="jxpath" expression="/your/version2/xpath/descriminator"/>
  </filtering-router>
  <forwarding-catch-all-strategy>
    <stdio:outbound-endpoint system="ERR"/>
  </forwarding-catch-all-strategy>
</outbound>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a instance of Mule that is configured to process xml responses from a third party provider.  Recently the provider has moved to a new revision and hence changed the xml response.  Now I need a way to identify if the response is a v1 or v2 implementation and call the appropriate endpoint on my side to process the response.

What I have currently is:

<service name="processResponse">
...
    <outbound>
        <pass-through-router>
            <cxf:outbound-endpoint address="..." clientClass="..." wsdlPort="..." wsdlLocation="..." operation="..."/>
        </pass-through-router>
   </outbound>
</service>

I would prefer to add a filter in mule to identify the revision of the 3rd party (perhaps through the xml namespace in the response), and then call the appropriate class.  I cannot find any good examples of this.

Can someone provide an example of how this could be solved?

Body:
I suspect the most straight forward means is a filtered route using an xpath filter. First define vm services for each version. Next you'll filter to them through a service with following outbound endpoint. A catch all is always a good idea.

<outbound>
  <filtering-router>
    <vm:outbound-endpoint ref="Version1"/>
    <expression-filter evaluator="jxpath" expression="/your/version1/xpath/descriminator"/>
  </filtering-router>
  <filtering-router>
    <vm:outbound-endpoint ref="Version2"/>
    <expression-filter evaluator="jxpath" expression="/your/version2/xpath/descriminator"/>
  </filtering-router>
  <forwarding-catch-all-strategy>
    <stdio:outbound-endpoint system="ERR"/>
  </forwarding-catch-all-strategy>
</outbound>


问:
how can i catch errors if variables are not set?
How can catch the error caused by a module variable not being set when the function is called

so example i have this code

```<code>file = "whatever the file path is"
menu= [] #this is a global variable

def ordermenu():
    with open(file) as f:  # read file
        reader = csv.reader(f, delimiter=",")
        next(reader, None) #skip the header

def showmenu():
    for i in range(len(menu)):
        print(menu)

ordermenu()
showmenu()
</code>```

In this function i need to catch the error.

NOTE: i won't be using those global variable as parameters.

答:
It is called NameError for something not defined. Just wrap your code with try-except like this:

```<code>try:
    b = a+1
except NameError:
    print("a not defined")
</code>```

Body:
How can catch the error caused by a module variable not being set when the function is called

so example i have this code

file = "whatever the file path is"
menu= [] #this is a global variable

def ordermenu():
    with open(file) as f:  # read file
        reader = csv.reader(f, delimiter=",")
        next(reader, None) #skip the header

def showmenu():
    for i in range(len(menu)):
        print(menu)

ordermenu()
showmenu()

In this function i need to catch the error.

NOTE: i won't be using those global variable as parameters.

Body:
It is called NameError for something not defined. Just wrap your code with try-except like this:

try:
    b = a+1
except NameError:
    print("a not defined")


答:
You can do:</p>

```<code>df = df.loc[:, df.columns.notnull()]
</code>```

Title: Pandas delete Column where Header is NAN

Body:
You can do:

df = df.loc[:, df.columns.notnull()]


问:
spring boot application run, but I get error 404 in the web browser
spring boot application run, but I get 404 error in web browser, for frontend I have used jsp. The app was developed in spring mvc then I converted it to spring boot. after conversion is run as expected, but I do not see the data in browser. "This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu May 28 18:07:37 GMT-06:00 2020
There was an unexpected error (type=Not Found, status=404).
No message available"

I have a WebMvcConfigurer class, it contains my view resolver do I needs it?
Thymeleaf does not need a view Reslover, is it the same for jps, too?
here my class:

```<code>import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

import thursday.com.todolist.util.ViewNames;

public class WebConfig implements WebMvcConfigurer {
    private static final String RESOLVER_PREFIX = "/templates/WEB-INF/view/";
    private static final String RESOLVER_SUFFIX = ".jsp";

    @Bean
    public ViewResolver viewResolver(){
        UrlBasedViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix(RESOLVER_PREFIX);
        viewResolver.setSuffix(RESOLVER_SUFFIX);
        return viewResolver;
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName(ViewNames.HOME);
    }
}
</code>```

答:
Yeah you do need the suffix and prefix for the view resolver as the internal view resolver uses the prefix and suffix to make a logical mapping for your view , but you could also provide it in the application.properties file like :

```<code>spring.mvc.view.prefix = /WEB-INF/classes/templates
spring.mvc.view.suffix = .jsp
</code>```

Also, Embedded Tomcat package (which is used in springboot to create executable jar)does not include JSP by default, we must add the module “org.apache.tomcat.embed:tomcat-embed-jasper” as dependency as well.The reason why we are adding tomcat-embed-jasper as dependency in springboot, is that we can use the jstl tags in jsp.The jsp files needs to be transpiled into html.

Also, since you moved to spring-boot from spring mvc make sure you
removed the annotation @EnableWebMvc from your project as this will
disable all spring-boot autoconfigurations.Unless, you are explicitly providing it yourself to handle all configurations manually like in spring-mvc.

Also spring-boot and JSP quite doesn't work together with jar as the packaging so try to use war packaging if you are using jsp as the view template.The contents of the webapp folder is automatically taken up during build only if you keep the packaging as war .

Body:
spring boot application run, but I get 404 error in web browser, for frontend I have used jsp. The app was developed in spring mvc then I converted it to spring boot. after conversion is run as expected, but I do not see the data in browser. "This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu May 28 18:07:37 GMT-06:00 2020
There was an unexpected error (type=Not Found, status=404).
No message available"

I have a WebMvcConfigurer class, it contains my view resolver do I needs it?
Thymeleaf does not need a view Reslover, is it the same for jps, too?
here my class:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

import thursday.com.todolist.util.ViewNames;

public class WebConfig implements WebMvcConfigurer {
    private static final String RESOLVER_PREFIX = "/templates/WEB-INF/view/";
    private static final String RESOLVER_SUFFIX = ".jsp";

    @Bean
    public ViewResolver viewResolver(){
        UrlBasedViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix(RESOLVER_PREFIX);
        viewResolver.setSuffix(RESOLVER_SUFFIX);
        return viewResolver;
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName(ViewNames.HOME);
    }
}

Body:
Yeah you do need the suffix and prefix for the view resolver as the internal view resolver uses the prefix and suffix to make a logical mapping for your view , but you could also provide it in the application.properties file like :

spring.mvc.view.prefix = /WEB-INF/classes/templates
spring.mvc.view.suffix = .jsp

Also, Embedded Tomcat package (which is used in springboot to create executable jar)does not include JSP by default, we must add the module “org.apache.tomcat.embed:tomcat-embed-jasper” as dependency as well.The reason why we are adding tomcat-embed-jasper as dependency in springboot, is that we can use the jstl tags in jsp.The jsp files needs to be transpiled into html.

Also, since you moved to spring-boot from spring mvc make sure you
removed the annotation @EnableWebMvc from your project as this will
disable all spring-boot autoconfigurations.Unless, you are explicitly providing it yourself to handle all configurations manually like in spring-mvc.

Also spring-boot and JSP quite doesn't work together with jar as the packaging so try to use war packaging if you are using jsp as the view template.The contents of the webapp folder is automatically taken up during build only if you keep the packaging as war .