问:
vba: How to For Each Loop with Mutiple If, Else Conditions and Formulas based on dynamic criteria?
I have a Macro that calculates Values in a Range depending on their existence. If all exist then perform a certain calculation else it goes through a variations of multiple conditions and calculates according to what exist. I am so far able to get it to calculate if all values exist but not the variations of some not existing. Any assistance would be greatly appreciated. (see code below)

Private Sub example()

    Dim ws As Worksheet
    Dim s As Range
    Dim lastcol as Long
    Dim lastrow as Long
    Dim h1 As Variant
    Dim a As String
    Dim b As String
    Dim c As String
    Dim d As String
    Dim e As String

    lastcol = ws.Cells(4, Columns.Count).End(xlToLeft).Column
    lastrow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
    On Error Resume Next

    h1 = ws.Range("A4:Z4").Find("Header1").Offset(1, 0).Address(False, False)
    'h2 to h6 - same as above

    a = "Header1"
    b = "Header2"
    c = "Header3"
    d = "Header4"
    e = "Header5"

    ws.Range(Range("A4:Z4").Find("Header0").Offset(0, 1), Range("A4:Z4").Find("Header6").Offset(0, -1)).Select
    With Selection
    For Each s In Selection

            'Calc (Header1, Header2, Header3, Header4, Header5) - ALL
    If s.Value.a = True And s.Value.b = True And s.Value.c = True And s.Value.d = True And s.Value.e = True Then
    ws.Range(Range("A4:Z4").Find("Result %").Offset(1, 0), Cells(lastrow, lastcol)).Formula = _
"=IFERROR(SUM(" & h1 & "," & h2 & "," & h3 & "," & h4 & ", If(" & h5 & "/" & h6 & ">1%," & h6 & "*1%," & h5 & "))/ " & h6 & ", """") "

        'Calc (Header1, Header2, Header3, Header4) - NO Header5
    ElseIf s.Value.a = True And s.Value.b = True And s.Value.c = True And s.Value.d = True And s.Value.e = False Then
    ws.Range(Range("A4:Z4").Find("Result %").Offset(1, 0), Cells(lastrow, lastcol)).Formula = _
"=IFERROR(SUM(" & h1 & "," & h2 & "," & h3 & "," & h4 & ")/" & h6 & ", """") "

        'Calc (Header1, Header2, Header3, Header5) - NO Header4
    ElseIf s.Value.a = True And s.Value.b = True And s.Value.c = True And s.Value.d = False And s.Value.e = True Then
    ws.Range(Range("A4:Z4").Find("Result %").Offset(1, 0), Cells(lastrow, lastcol)).Formula = _
"=IFERROR(SUM(" & h1 & "," & h2 & "," & h3 & ", IF(" & h5 & "/" & h6 & ">1%," & h6 & "*1%," & h5 & "))/" & h6 & ", """") "
    ' Total of 15 conditions and formulas

    End If
    Next
    End With
End Sub
```

答:
Your formulas are pretty complex. I'm not sure if I'm understanding what you need correctly, but I wrote and tested this code. It should at least give you some ideas of what you can do to make your macro work.

```<code>Sub CreateDynamicFormula()

    Dim strList(1 To 5) As String
    Dim r As Range
    Dim s As Variant
    Dim counter As Long

    Const h1 As String = "Header1"
    Const h2 As String = "Header2"

    counter = 1

    'This is the inner loop
    'finds which columns meet your condition and adds them to an array
    For Each r In Range("A1:C3")
        If r.Value = h1 Then
            strList(counter) = r.Address
            counter = counter + 1
        ElseIf r.Value = h2 Then
            strList(counter) = r.Address
            counter = counter + 1
        End If
    Next r

'Make Formula

    Formula = "=IFERROR(SUM("

    For Each s In strList
        'only returns array items that have text in them
        If Not s = "" Then
            Formula = Formula & s & ", "
        End If
    Next s

    Formula = Formula + ")"

    Debug.Print Formula

End Sub
</code>```

Here is the spreadsheet I made to test the code:

Results:

Body:
Your formulas are pretty complex. I'm not sure if I'm understanding what you need correctly, but I wrote and tested this code. It should at least give you some ideas of what you can do to make your macro work.

Sub CreateDynamicFormula()

    Dim strList(1 To 5) As String
    Dim r As Range
    Dim s As Variant
    Dim counter As Long

    Const h1 As String = "Header1"
    Const h2 As String = "Header2"

    counter = 1

    'This is the inner loop
    'finds which columns meet your condition and adds them to an array
    For Each r In Range("A1:C3")
        If r.Value = h1 Then
            strList(counter) = r.Address
            counter = counter + 1
        ElseIf r.Value = h2 Then
            strList(counter) = r.Address
            counter = counter + 1
        End If
    Next r

'Make Formula

    Formula = "=IFERROR(SUM("

    For Each s In strList
        'only returns array items that have text in them
        If Not s = "" Then
            Formula = Formula & s & ", "
        End If
    Next s

    Formula = Formula + ")"

    Debug.Print Formula

End Sub

Here is the spreadsheet I made to test the code:

Results:


来源: stackexchange

问:
LINQ Group elements that are equal together
I have a simple question on LINQ and haven't found an answer that directly addresses my question. Say I have an arbitrary collection of objects: {cat, apple, orange, cat, orange, apple, cat}. I want to order to use LINQ to order these lists by equality, e.g. so now the collection reads {apple, apple, orange, orange, cat, cat, cat}. It doesn't matter what order the types are (i.e. whether apple comes first or cat, for example), only that they are appropriately grouped.

Say I have access to Equals() or some boolean method to determine if any two instances are equal. How would I do this?

答:
Sorting has complexity O(n log n). The following, has linear complexity.

```<code>collection.GroupBy(x => x).SelectMany(g => g).ToList();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Sorting has complexity O(n log n). The following, has linear complexity.

collection.GroupBy(x => x).SelectMany(g => g).ToList();


问:
Detect which `View` was clicked on a `Cell`
i have three UIImageView on a single Cell when i click on any of the UIImageView on the cell i want to detect which one was clicked on onCellSelection, without placing a UITapGestureRecognizer on each UIImageview

```<code>func SocialViewRow(address: SocialMedia)-> ViewRow<SocialMediaViewFile> {

let viewRow = ViewRow<SocialMediaViewFile>() { (row) in

    row.tag = UUID.init().uuidString
    }
    .cellSetup { (cell, row) in
        //  Construct the view
        let bundle = Bundle.main
        let nib = UINib(nibName: "SocialMediaView", bundle: bundle)

        cell.view = nib.instantiate(withOwner: self, options: nil)[0] as? SocialMediaViewFile
        cell.view?.backgroundColor = cell.backgroundColor
        cell.height =  { 50 }
        print("LINK \(address.facebook?[0] ?? "")")

        cell.view?.iconOne.tag = 90090

        //self.itemDetails.activeURL = address

        let openFace = UITapGestureRecognizer(target: self, action: #selector(QuickItemDetailVC.openFace))
        let openT = UITapGestureRecognizer(target: self, action: #selector(QuickItemDetailVC.openTwit))
        let you = UITapGestureRecognizer(target: self, action: #selector(QuickItemDetailVC.openYouYub))

         cell.view?.iconOne.addGestureRecognizer(openFace)

         cell.view?.iconTwo.addGestureRecognizer(openT)
         cell.view?.iconThree.addGestureRecognizer(you)

        cell.frame.insetBy(dx: 5.0, dy: 5.0)
        cell.selectionStyle = .none

    }.onCellSelection() {cell,row in

     //example
    //print(iconTwo was clicked)

}

return viewRow
}
</code>```

答:
Using UITapGestureRecogniser (or UIButton) would be a better approach. These classes intended for tasks like this.

If you still want to use different approach, add method to your cell subclass (replace imageView1, imageView2, imageView3 with your own properties)

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  guard let touch = touches.first else { return }
  let point = touch.location(in: view)
  if imageView1.frame.containsPoint(point) {
    // code for 1st image view
  } else if imageView2.frame.containsPoint(point) {
    // code for 2nd image view
  } else if imageView3.frame.containsPoint(point) {
    // code for 3rd image view
  }
}
</code>```

Docs:

location(ofTouch:in:)

contains(_ point: CGPoint)

Body:
i have three UIImageView on a single Cell when i click on any of the UIImageView on the cell i want to detect which one was clicked on onCellSelection, without placing a UITapGestureRecognizer on each UIImageview

func SocialViewRow(address: SocialMedia)-> ViewRow<SocialMediaViewFile> {

let viewRow = ViewRow<SocialMediaViewFile>() { (row) in

    row.tag = UUID.init().uuidString
    }
    .cellSetup { (cell, row) in
        //  Construct the view
        let bundle = Bundle.main
        let nib = UINib(nibName: "SocialMediaView", bundle: bundle)

        cell.view = nib.instantiate(withOwner: self, options: nil)[0] as? SocialMediaViewFile
        cell.view?.backgroundColor = cell.backgroundColor
        cell.height =  { 50 }
        print("LINK \(address.facebook?[0] ?? "")")

        cell.view?.iconOne.tag = 90090

        //self.itemDetails.activeURL = address

        let openFace = UITapGestureRecognizer(target: self, action: #selector(QuickItemDetailVC.openFace))
        let openT = UITapGestureRecognizer(target: self, action: #selector(QuickItemDetailVC.openTwit))
        let you = UITapGestureRecognizer(target: self, action: #selector(QuickItemDetailVC.openYouYub))

         cell.view?.iconOne.addGestureRecognizer(openFace)

         cell.view?.iconTwo.addGestureRecognizer(openT)
         cell.view?.iconThree.addGestureRecognizer(you)

        cell.frame.insetBy(dx: 5.0, dy: 5.0)
        cell.selectionStyle = .none

    }.onCellSelection() {cell,row in

     //example
    //print(iconTwo was clicked)

}

return viewRow
}

Body:
Using UITapGestureRecogniser (or UIButton) would be a better approach. These classes intended for tasks like this.

If you still want to use different approach, add method to your cell subclass (replace imageView1, imageView2, imageView3 with your own properties)

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  guard let touch = touches.first else { return }
  let point = touch.location(in: view)
  if imageView1.frame.containsPoint(point) {
    // code for 1st image view
  } else if imageView2.frame.containsPoint(point) {
    // code for 2nd image view
  } else if imageView3.frame.containsPoint(point) {
    // code for 3rd image view
  }
}

Docs:

location(ofTouch:in:)

contains(_ point: CGPoint)


问:
How to find a GameObject (lower in Hierarchy), starting at root GameObject?
Ok, this one is a little difficult to explain.

Let's say that you have multiple characters in your game.

Each character (prefab) may have a different bone structure & bone names.

Certain GameObjects (in the prefabs) you renamed for simplicity.  (E.g. each
character has a GameObject named "Head")

Now, given an OnTriggerEnter() Method, you find the "root" GameObject from the collider.

From this point, how do you locate the "Head" GameObject, from the root of this GameObject?

Keep in mind, each GameObject (character) contains a Head.  You want to find this particular GameObject's Head.

Code I've tried:  (which returns a null reference)

```<code>private void OnTriggerEnter(Collider char)
{
    var en = char.gameObject;
    var head = en.transform.Find("Head");
}
</code>```

Is this possible to do without explicitly typing out each hierarchy, of each different type of bone structure?

答:
Hellium was correct in the comment.  Please credit him or her for their efforts!

Here is a simplified version of the answer:

```<code>    public static Transform FindDeepChild(Transform aParent, string aName)
    {
        Queue<Transform> queue = new Queue<Transform>();
        queue.Enqueue(aParent);
        while (queue.Count > 0)
        {
            var c = queue.Dequeue();
            if (c.name == aName) return c;
            foreach (Transform t in c) queue.Enqueue(t);
        }
        return null;
    }
</code>```

Body:
Ok, this one is a little difficult to explain.

Let's say that you have multiple characters in your game.

Each character (prefab) may have a different bone structure & bone names.

Certain GameObjects (in the prefabs) you renamed for simplicity.  (E.g. each
character has a GameObject named "Head")

Now, given an OnTriggerEnter() Method, you find the "root" GameObject from the collider.

From this point, how do you locate the "Head" GameObject, from the root of this GameObject?

Keep in mind, each GameObject (character) contains a Head.  You want to find this particular GameObject's Head.

Code I've tried:  (which returns a null reference)

private void OnTriggerEnter(Collider char)
{
    var en = char.gameObject;
    var head = en.transform.Find("Head");
}

Is this possible to do without explicitly typing out each hierarchy, of each different type of bone structure?

Body:
Hellium was correct in the comment.  Please credit him or her for their efforts!

Here is a simplified version of the answer:

    public static Transform FindDeepChild(Transform aParent, string aName)
    {
        Queue<Transform> queue = new Queue<Transform>();
        queue.Enqueue(aParent);
        while (queue.Count > 0)
        {
            var c = queue.Dequeue();
            if (c.name == aName) return c;
            foreach (Transform t in c) queue.Enqueue(t);
        }
        return null;
    }


问:
Create button formatting in android
I am working on a project where I will have many buttons of the same size.

I was wondering if there is a way to create a standard button formatting with a set

height

weight

padding

etc.

I have looked into styles but I am not sure if that is the road I should be taking. I also thought about extending the button class and programmatically setting these values to a standard.

答:
Hello, how are you!

The best way is to create a style in the style.xml resource, all the necessary features.

just add the style with style = "@style/mystyle" to all the buttons.

example:

```<code><style name="mystyle">
    <item name="android:textSize">20sp</item>
    <item name="android:gravity">center|center_horizontal</item>
    <item name="android:textAlignment">center</item>
</style>
</code>```

In the same way when you want to create a customized button (java/kotlin)
it will also be added in the same way.

Greetings.

Title: Create button formatting in android

Body:
Hello, how are you!

The best way is to create a style in the style.xml resource, all the necessary features.

just add the style with style = "@style/mystyle" to all the buttons.

example:

<style name="mystyle">
    <item name="android:textSize">20sp</item>
    <item name="android:gravity">center|center_horizontal</item>
    <item name="android:textAlignment">center</item>
</style>

In the same way when you want to create a customized button (java/kotlin)
it will also be added in the same way.

Greetings.


问:
Rotation of a point around a fixed point at a particular radius in Directx?
I am trying to rotate a point say (20,6,30) around a point (10,6,10) at a radius of 2  and i have failed so far trying to do it.
I know that to rotate a point around origin you just multiply rotation matrix with world matrix and to rotate a point around itself is translating the point to origin ,then rotating and translating back, but not sure how to approach this problem.</p>

答:
Using a radius doesn't make sense if you are rotating an object coordinate around an arbitrary origin coordinate because the radius is going to be constant during the rotation. To use a desired radius during rotation make sure that the object coordinate and origin coordinate are the desired radius apart.
Also note that you need a rotation axis to rotate around a point while using euler angles (vs. spherical or quaternions) because otherwise its undefined in which direction(s) you will be rotating.

If you are willing to do matrix math here is how I do it (using pseudo code because I only know OGL):

```<code>vec3 translate_around_point
(
    vec3 object_pos,
    vec3 origin_pos,
    vec3 rotation_axis,
    float rotation
)
{
    // get difference
    vec3 difference = object_pos - origin_pos;
    //rotate difference on rotation axis
    mat4 model = rotate(mat4 model(1.0), rotation, rotation_axis);
    vec3 trans = model * vec4(difference, 1.0);
    //add add translation to origin pos
    return origin_pos + trans;
}
</code>```

Your code using this function would look like this (radius is 22.360679626464844):

```<code>vec3 object_pos(20.0, 6.0, 30.0);
vec3 orig_pos(10.0, 6.0, 10.0);
vec3 axis(0.0, 1.0, 0.0); // rotation axis is 'up' in world space
float angle = 90.0;
object_pos = translate_around_point(object_pos, orig_pos, axis, angle);
</code>```

Also if you were to run it with the object position having a greater height or a tilted axis of rotation then the origin position may not appear to be at the center of the rotation anymore. This is ok, because if the rotation doesn't rotate on part of the axis (x,y, or z), then it won't effect the translation on that part.

ContentLicense: CC BY-SA 3.0

Body:
Using a radius doesn't make sense if you are rotating an object coordinate around an arbitrary origin coordinate because the radius is going to be constant during the rotation. To use a desired radius during rotation make sure that the object coordinate and origin coordinate are the desired radius apart.
Also note that you need a rotation axis to rotate around a point while using euler angles (vs. spherical or quaternions) because otherwise its undefined in which direction(s) you will be rotating.

If you are willing to do matrix math here is how I do it (using pseudo code because I only know OGL):

vec3 translate_around_point
(
    vec3 object_pos,
    vec3 origin_pos,
    vec3 rotation_axis,
    float rotation
)
{
    // get difference
    vec3 difference = object_pos - origin_pos;
    //rotate difference on rotation axis
    mat4 model = rotate(mat4 model(1.0), rotation, rotation_axis);
    vec3 trans = model * vec4(difference, 1.0);
    //add add translation to origin pos
    return origin_pos + trans;
}

Your code using this function would look like this (radius is 22.360679626464844):

vec3 object_pos(20.0, 6.0, 30.0);
vec3 orig_pos(10.0, 6.0, 10.0);
vec3 axis(0.0, 1.0, 0.0); // rotation axis is 'up' in world space
float angle = 90.0;
object_pos = translate_around_point(object_pos, orig_pos, axis, angle);

Also if you were to run it with the object position having a greater height or a tilted axis of rotation then the origin position may not appear to be at the center of the rotation anymore. This is ok, because if the rotation doesn't rotate on part of the axis (x,y, or z), then it won't effect the translation on that part.


问:
Is sizeof(<variable>) instead of sizeof(<type>) always safe?
I know that I can protect myself by writing

```<code>int *ptr = malloc(sizeof (*ptr))
</code>```

instead of

```<code>int *ptr = malloc(sizeof (int))
</code>```

The benefit is that if you decide to change the type of ptr to for instance long* instead of int*, then you only need to change the code at one place.

My question is, is this strategy always safe to do? Is there any situation where the construct T *ptr = malloc(sizeof(*ptr)) would not work? Does it matter if T is some complex struct, pointer to pointer, function pointer or an array? Or a combination of them for that matter.

I have tried to come up with a situation where it causes problems, but to me it seems safe. But I want to be able to trust the code completely.

答:
It is safe, portable  and it is considered as a good practice.

Of course it will not safe if someone will hide pointers in the typedefs and make the code unreadable. But this is considered as a very bad practice.

Function pointers are very specific as they do not need the memory for the object (function)

Body:
I know that I can protect myself by writing

int *ptr = malloc(sizeof (*ptr))

instead of

int *ptr = malloc(sizeof (int))

The benefit is that if you decide to change the type of ptr to for instance long* instead of int*, then you only need to change the code at one place.

My question is, is this strategy always safe to do? Is there any situation where the construct T *ptr = malloc(sizeof(*ptr)) would not work? Does it matter if T is some complex struct, pointer to pointer, function pointer or an array? Or a combination of them for that matter.

I have tried to come up with a situation where it causes problems, but to me it seems safe. But I want to be able to trust the code completely.


答:
Find does not descend the Transform hierarchy. Find will only search the given list of children looking for a named Transform if no child can be found, null is returned. In other words it won't look in the children of its children. If you wish to use Find on child that is already child then you must access it like a path using /, eg. transform.Find("Body/Head").

In general string reference like that is a very bad idea, one way you could do it is by creating an empty script (Let's say Head.cs) and attach it to the child of the parent GameObject then instead of looking for the transfrom  by string reference you can look for component Head.cs

It would look something like this:

```<code>private void OnTriggerEnter(Collider collider)
{
   //Where Head is an empty script attached to the Head.
   var head = collider.GetComponentInChildren<Head>();
   //Do something... Logging the name for example
   Debug.log(head.transfrom.name);
}
</code>```

Title: How to find a GameObject (lower in Hierarchy), starting at root GameObject?

Body:
Find does not descend the Transform hierarchy. Find will only search the given list of children looking for a named Transform if no child can be found, null is returned. In other words it won't look in the children of its children. If you wish to use Find on child that is already child then you must access it like a path using /, eg. transform.Find("Body/Head").

In general string reference like that is a very bad idea, one way you could do it is by creating an empty script (Let's say Head.cs) and attach it to the child of the parent GameObject then instead of looking for the transfrom  by string reference you can look for component Head.cs

It would look something like this:

private void OnTriggerEnter(Collider collider)
{
   //Where Head is an empty script attached to the Head.
   var head = collider.GetComponentInChildren<Head>();
   //Do something... Logging the name for example
   Debug.log(head.transfrom.name);
}


问:
How to use components in my custom js file in Laravel and Vue.js?
I'm new to Laravel and Vue.js. I created a simple Laravel/Vue.js project like this post: https://itsolutionstuff.com/post/laravel-5-and-vue-js-crud-with-pagination-example-and-demo-from-scratchexample.html

Now I want to add date-picker to my blade files: https://talkhabi.github.io/vue-persian-datetime-picker/#/installation

However, when I import component to my js file (for example item.js), I get the following error message:

SyntaxError: import declarations may only appear at top level of a module.

答: Your import statements must come first at the beginning of your JS files. No import statements should come after regular code. </p>


问:
There is a way to enforce referential integrity in MongoDB
When you search for referential integrity in relation to Mongo-DB the standard response is "MongoDB does not support this". The standard explanation is that MongoDB supports refs and populate, however there is nothing that prevents you changing the ref to an invalid value. This is a major deterrent for many developers coming from a SQL background.</p>

答:
In relation to referential integrity on deletes, provided all delete requests are served by your application then it can be handled by checking ID does not exists in related collections prior to deleting records. I do this as follows

CRUD Operations (We are only concerned with Delete here - note how I am passing an array of objects being the collection and field that needs to be matched against ID of document (record) we are deleting

```<code>const express = require('express')
const router = express.Router()
const iflexCRUD = require('../../lib/iflexCRUD')

const { UnitType } = require('../../models/Unittype')
const { Unit } = require('../../models/Unit')

iflexCRUD.create(router, '/', UnitType)
iflexCRUD.read(router, '/', UnitType, { sort: 'name' })
iflexCRUD.update(router, '/:id', UnitType)
iflexCRUD.deleteByID(router, '/:id', UnitType, [
  {
    model: Unit,
    field: 'unittype'
  }
])
iflexCRUD.delete(router, '/unittype/:unittype', UnitType)

module.exports = router
</code>```

CRUD Delete Handler
This is a generic delete request handler that I use for CRUD operations
I passes an array of Collection / Field values and checks to see if there is a single record that matches the ID of the document being deleted.

```<code>// CRUD-DELETE
iflexCRUD.deleteByID = (router, route, Collection, refs = []) => {
  router.delete(route, async (req, res) => {
    try {
      let exception = false
      //Enforce Referential Integrity for deletes - Deny when ID is used in any of refs collections
      //Loop through any referenced files (first record) to ensure there are no other collections using this document
      for (let i = 0; i < refs.length; i++) {
        if (!exception) {
          let refObj = {}
          refObj[refs[0].field] = req.params.id
          const result = await refs[i].model.findOne(refObj, (err, rec) => {})
          exception = result !== null
        }
      }
      // Process deletion of there are no exceptions
      if (!exception) {
        const doc = await Collection.deleteOne({ _id: req.params.id })
        res.send(doc)
      } else {
        return res
          .status(401)
          .json(
            'Document is already use in related collection  - it cannot Delete!'
          )
      }
    } catch (e) {
      return res.status(401).json(e.message)
    }
  })
}
</code>```

Body:
In relation to referential integrity on deletes, provided all delete requests are served by your application then it can be handled by checking ID does not exists in related collections prior to deleting records. I do this as follows

CRUD Operations (We are only concerned with Delete here - note how I am passing an array of objects being the collection and field that needs to be matched against ID of document (record) we are deleting

const express = require('express')
const router = express.Router()
const iflexCRUD = require('../../lib/iflexCRUD')

const { UnitType } = require('../../models/Unittype')
const { Unit } = require('../../models/Unit')

iflexCRUD.create(router, '/', UnitType)
iflexCRUD.read(router, '/', UnitType, { sort: 'name' })
iflexCRUD.update(router, '/:id', UnitType)
iflexCRUD.deleteByID(router, '/:id', UnitType, [
  {
    model: Unit,
    field: 'unittype'
  }
])
iflexCRUD.delete(router, '/unittype/:unittype', UnitType)

module.exports = router

CRUD Delete Handler
This is a generic delete request handler that I use for CRUD operations
I passes an array of Collection / Field values and checks to see if there is a single record that matches the ID of the document being deleted.

// CRUD-DELETE
iflexCRUD.deleteByID = (router, route, Collection, refs = []) => {
  router.delete(route, async (req, res) => {
    try {
      let exception = false
      //Enforce Referential Integrity for deletes - Deny when ID is used in any of refs collections
      //Loop through any referenced files (first record) to ensure there are no other collections using this document
      for (let i = 0; i < refs.length; i++) {
        if (!exception) {
          let refObj = {}
          refObj[refs[0].field] = req.params.id
          const result = await refs[i].model.findOne(refObj, (err, rec) => {})
          exception = result !== null
        }
      }
      // Process deletion of there are no exceptions
      if (!exception) {
        const doc = await Collection.deleteOne({ _id: req.params.id })
        res.send(doc)
      } else {
        return res
          .status(401)
          .json(
            'Document is already use in related collection  - it cannot Delete!'
          )
      }
    } catch (e) {
      return res.status(401).json(e.message)
    }
  })
}


问:
Flutter - How to fix dynamic widgets that are not loading on page load?
I am creating a flutter app and created a page that pulls data from a sqlite database and load a widget dynamically that displays the data from the sqlite db when the page loads. For some reason, the widgets are not loading. It only loads the dynamic widgets in debug mode when I hot reload the app.

Here is my code:

```<code>Users userList = new Users();
List details = new List<Widget>();
var db = new DB_Helper();

_addToUserList(Map<dynamic, dynamic> json)
{
    userList.membersList.add(json);
    return userList.membersList;
}

  List<Widget> getTeamMembers()
   {
    // Get data from db
   db.getMembers().then((data) {
      // clear list to prevent repeating if page refreshes
      userList.membersList.clear();
      details.clear();
      for (Members m  in data)
      {
        Map<String, dynamic> json;
        json =
        {
          "member_id": m.memberId,
          "member_name": m.memberName,
          "member_email": m.memberEmail
        };
        _addToUserList(json);
      }

       for (Map<dynamic, dynamic> u in userList.membersList) {
        Map<String, dynamic> js = u;
        var emailCtrl = new TextEditingController();
        var name = js["member_name"];
        emailCtrl.text = js["member_email"];

      details.add(

         new Card(
           color: Colors.blue,
        margin: EdgeInsets.all(2),
          child: ExpansionTile(
            title: Text(name),
            children: <Widget>[
               Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                    Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[

                       Container(
                         width: 280,
                         padding: EdgeInsets.all(0),
                         margin: EdgeInsets.all(0),
                         child: TextField(
                           enabled: false,
                           controller: emailCtrl,
                           style: TextStyle(color: Colors.purple),
                           decoration: InputDecoration(
                             labelText: "EMAIL:",
                             labelStyle: new TextStyle(color: Colors.black),
                             border: InputBorder.none,
                           ),
                         ),
                       ),

                      ],
                    ),
                      ),
                ],
              ),
            ],
          ),
        ),
      );
       }

    });

    return details;
  }
</code>```

I have tried fetching the data and storing it in a list in initState(), but the page still loads blank.

I have tried to use await when querying sqlite but it throws an error inside the  scaffold body property where I call the widget.

The only time it loads properly, is when I remove the code that queries the db and hard code the userList with values rather than pull it out from sqlite. Querying sqlite db seems to be preventing the widgets from displaying. How can I pull data out from sqlite and add it to a dynamic widget to display on page loads?

答:
Your code is definitely kind of a mess.

You should you use a ListView.builder instead. You should NOT use any Dart for loops for building your Widgets. Simply have your array of data properly setup and use the ListView.builder to build the Cards and other Widgets. Here is an example of using ListView.builder:

```<code>ListView.builder(
          itemCount: list.length,
          itemBuilder: (BuildContext context, int i) {
            return Dismissible(
              key: ObjectKey(list[i]),
              background: Container(
                alignment: AlignmentDirectional.centerEnd,
                color: Colors.red,
                child: Padding(
                  padding: EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
                  child: Icon(
                    Icons.delete,
                    color: Colors.white,
                  ),
                ),
              ),
              confirmDismiss: (direction) async {
                if (direction == DismissDirection.startToEnd) {
                  /// edit item
                  return false;
                } else if (direction == DismissDirection.endToStart) {
                  /// delete
                  return true;
                }
              },
              onDismissed: (direction) {
                setState(() {
                  var paymentMethod = list[i];
                  list.removeAt(i);
                  _showDeletePaymentDialog(paymentMethod);
                });
              },
              child: Card(
                color: BmsColors.primaryBackgroundColor,
                elevation: 2.0,
                child: ListTile(
                  title: Text(
                    'xxxx-${list[i].last4}',
                    style: UIUtil.getTxtStyleCaption(),
                  ),
                  subtitle: Text(
                    list[i].brandDisplay,
                    style: UIUtil.getTxtStyleCaption(),
                  ),
                  leading: CardUtils.getCardIcon(list[i].brand),
                  trailing: (list[i].isDefault)
                      ? Icon(
                          Icons.check_circle,
                          size: 32,
                          color: BmsColors.primaryForegroundColor,
                        )
                      : Container(
                          width: 32,
                        ),
                  onTap: () {
                    debugPrint('Tapped on ');
                  },
                ),
              ),
            );
          },
        ),
</code>```

You should also be using a FutureBuilder for your async call to get data:

```<code> FutureBuilder(
    future: _getDataFromDatabase(), //async function that returns a Future<Map<String, dynamic>>
    builder: (BuildContext context, AsyncSnapshot snapshot) {
      if (!snapshot.hasData) {
        if (snapshot.connectionState == ConnectionState.done) {
          list = [];
        }
        return CircularProgressIndicator();
      }

      list = snapshot.data;
      return _buildScaffold(); //contains your ListView.builder
    });
</code>```

Body:
I am creating a flutter app and created a page that pulls data from a sqlite database and load a widget dynamically that displays the data from the sqlite db when the page loads. For some reason, the widgets are not loading. It only loads the dynamic widgets in debug mode when I hot reload the app.

Here is my code:

Users userList = new Users();
List details = new List<Widget>();
var db = new DB_Helper();

_addToUserList(Map<dynamic, dynamic> json)
{
    userList.membersList.add(json);
    return userList.membersList;
}

  List<Widget> getTeamMembers()
   {
    // Get data from db
   db.getMembers().then((data) {
      // clear list to prevent repeating if page refreshes
      userList.membersList.clear();
      details.clear();
      for (Members m  in data)
      {
        Map<String, dynamic> json;
        json =
        {
          "member_id": m.memberId,
          "member_name": m.memberName,
          "member_email": m.memberEmail
        };
        _addToUserList(json);
      }

       for (Map<dynamic, dynamic> u in userList.membersList) {
        Map<String, dynamic> js = u;
        var emailCtrl = new TextEditingController();
        var name = js["member_name"];
        emailCtrl.text = js["member_email"];

      details.add(

         new Card(
           color: Colors.blue,
        margin: EdgeInsets.all(2),
          child: ExpansionTile(
            title: Text(name),
            children: <Widget>[
               Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                    Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[

                       Container(
                         width: 280,
                         padding: EdgeInsets.all(0),
                         margin: EdgeInsets.all(0),
                         child: TextField(
                           enabled: false,
                           controller: emailCtrl,
                           style: TextStyle(color: Colors.purple),
                           decoration: InputDecoration(
                             labelText: "EMAIL:",
                             labelStyle: new TextStyle(color: Colors.black),
                             border: InputBorder.none,
                           ),
                         ),
                       ),

                      ],
                    ),
                      ),
                ],
              ),
            ],
          ),
        ),
      );
       }

    });

    return details;
  }

I have tried fetching the data and storing it in a list in initState(), but the page still loads blank.

I have tried to use await when querying sqlite but it throws an error inside the  scaffold body property where I call the widget.

The only time it loads properly, is when I remove the code that queries the db and hard code the userList with values rather than pull it out from sqlite. Querying sqlite db seems to be preventing the widgets from displaying. How can I pull data out from sqlite and add it to a dynamic widget to display on page loads?

Body:
Your code is definitely kind of a mess.

You should you use a ListView.builder instead. You should NOT use any Dart for loops for building your Widgets. Simply have your array of data properly setup and use the ListView.builder to build the Cards and other Widgets. Here is an example of using ListView.builder:

ListView.builder(
          itemCount: list.length,
          itemBuilder: (BuildContext context, int i) {
            return Dismissible(
              key: ObjectKey(list[i]),
              background: Container(
                alignment: AlignmentDirectional.centerEnd,
                color: Colors.red,
                child: Padding(
                  padding: EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
                  child: Icon(
                    Icons.delete,
                    color: Colors.white,
                  ),
                ),
              ),
              confirmDismiss: (direction) async {
                if (direction == DismissDirection.startToEnd) {
                  /// edit item
                  return false;
                } else if (direction == DismissDirection.endToStart) {
                  /// delete
                  return true;
                }
              },
              onDismissed: (direction) {
                setState(() {
                  var paymentMethod = list[i];
                  list.removeAt(i);
                  _showDeletePaymentDialog(paymentMethod);
                });
              },
              child: Card(
                color: BmsColors.primaryBackgroundColor,
                elevation: 2.0,
                child: ListTile(
                  title: Text(
                    'xxxx-${list[i].last4}',
                    style: UIUtil.getTxtStyleCaption(),
                  ),
                  subtitle: Text(
                    list[i].brandDisplay,
                    style: UIUtil.getTxtStyleCaption(),
                  ),
                  leading: CardUtils.getCardIcon(list[i].brand),
                  trailing: (list[i].isDefault)
                      ? Icon(
                          Icons.check_circle,
                          size: 32,
                          color: BmsColors.primaryForegroundColor,
                        )
                      : Container(
                          width: 32,
                        ),
                  onTap: () {
                    debugPrint('Tapped on ');
                  },
                ),
              ),
            );
          },
        ),

You should also be using a FutureBuilder for your async call to get data:

 FutureBuilder(
    future: _getDataFromDatabase(), //async function that returns a Future<Map<String, dynamic>>
    builder: (BuildContext context, AsyncSnapshot snapshot) {
      if (!snapshot.hasData) {
        if (snapshot.connectionState == ConnectionState.done) {
          list = [];
        }
        return CircularProgressIndicator();
      }

      list = snapshot.data;
      return _buildScaffold(); //contains your ListView.builder
    });


问:
Cumulative deposits with fixed rate decay
I'm trying to model the accumulation of biomass from dead wood deposited anually. The wood decays at a rate of 4.6% each year.

My data is formatted:

Cols: Treatment, Year, New.deposit
Treatment (A, B, C...)
Year (0:105)
New.deposit (numeric)

For the past few days, I've tried a combination of functions looking roughly as follows, but ended up with wrong combinations - maybe I'm making things too difficult:

```<code>#OBS! These code attempts are incorrect.
df <- df %>% group_by(Treatment) %>% mutate(Accumulated.deposits = cumsum(lag(New.deposit, n=1, default=0))*(1-0.046))

df <- df %>% group_by(Treatment) %>% mutate(Accumulated.deposits = cumsum((lag(Accumulated.deposits, n=1, default=0)*(1-0.046))) + new.deposit

My goal is to have one variable, Accumulated.biomass.yearY = deposit.year0 *  (1-0.046)^(Y) + deposit.year1 * (1-0.046)^(Y-1) + deposit.year2 * (1-0.046)^(Y-2)..... deposit.yearY * (1-0.046)^(Y-Y).
</code>```

I would love an matrix showing amount of remaining biomass from each years deposit at year X.

答:
Data

```<code>set.seed(1)
df <- data.frame(treatment = rep(c('A','B'), each=5), years = rep(1:5, times=2), new_deposit=runif(10))

   treatment years new_deposit
1          A     1  0.26550866
2          A     2  0.37212390
3          A     3  0.57285336
4          A     4  0.90820779
5          A     5  0.20168193
6          B     1  0.89838968
7          B     2  0.94467527
8          B     3  0.66079779
9          B     4  0.62911404
10         B     5  0.06178627
</code>```

Custom function

```<code>custom <- function(z, decay) { ans <- accumulate(z, function(x, y) { (x + y) * (1-decay) }, .init=0); tail(ans, -1) }
</code>```

The function will take a vector z and decay-rate decay and using purrr::accumulate will recursively apply the formula (x+y)*(1-decay) where x is the ith element in the vector and y is the i+1th element in the vector. I pad the vector .init=0 with a starting value of 0 and return the answer without padding tail(ans, -1).

Usage

```<code>df %>%
  group_by(treatment) %>%
  mutate(accumulated = custom(new_deposit, 0.046))

    treatment years new_deposit accumulated
   <fct>     <int>       <dbl>       <dbl>
 1 A             1      0.266        0.253
 2 A             2      0.372        0.597
 3 A             3      0.573        1.12
 4 A             4      0.908        1.93
 5 A             5      0.202        2.03
 6 B             1      0.898        0.857
 7 B             2      0.945        1.72
 8 B             3      0.661        2.27
 9 B             4      0.629        2.77
10 B             5      0.0618       2.70
</code>```

Body:
I'm trying to model the accumulation of biomass from dead wood deposited anually. The wood decays at a rate of 4.6% each year.

My data is formatted:

Cols: Treatment, Year, New.deposit
Treatment (A, B, C...)
Year (0:105)
New.deposit (numeric)

For the past few days, I've tried a combination of functions looking roughly as follows, but ended up with wrong combinations - maybe I'm making things too difficult:

#OBS! These code attempts are incorrect.
df <- df %>% group_by(Treatment) %>% mutate(Accumulated.deposits = cumsum(lag(New.deposit, n=1, default=0))*(1-0.046))

df <- df %>% group_by(Treatment) %>% mutate(Accumulated.deposits = cumsum((lag(Accumulated.deposits, n=1, default=0)*(1-0.046))) + new.deposit

My goal is to have one variable, Accumulated.biomass.yearY = deposit.year0 *  (1-0.046)^(Y) + deposit.year1 * (1-0.046)^(Y-1) + deposit.year2 * (1-0.046)^(Y-2)..... deposit.yearY * (1-0.046)^(Y-Y).

I would love an matrix showing amount of remaining biomass from each years deposit at year X.

Body:
Data

set.seed(1)
df <- data.frame(treatment = rep(c('A','B'), each=5), years = rep(1:5, times=2), new_deposit=runif(10))

   treatment years new_deposit
1          A     1  0.26550866
2          A     2  0.37212390
3          A     3  0.57285336
4          A     4  0.90820779
5          A     5  0.20168193
6          B     1  0.89838968
7          B     2  0.94467527
8          B     3  0.66079779
9          B     4  0.62911404
10         B     5  0.06178627

Custom function

custom <- function(z, decay) { ans <- accumulate(z, function(x, y) { (x + y) * (1-decay) }, .init=0); tail(ans, -1) }

The function will take a vector z and decay-rate decay and using purrr::accumulate will recursively apply the formula (x+y)*(1-decay) where x is the ith element in the vector and y is the i+1th element in the vector. I pad the vector .init=0 with a starting value of 0 and return the answer without padding tail(ans, -1).

Usage

df %>%
  group_by(treatment) %>%
  mutate(accumulated = custom(new_deposit, 0.046))

    treatment years new_deposit accumulated
   <fct>     <int>       <dbl>       <dbl>
 1 A             1      0.266        0.253
 2 A             2      0.372        0.597
 3 A             3      0.573        1.12
 4 A             4      0.908        1.93
 5 A             5      0.202        2.03
 6 B             1      0.898        0.857
 7 B             2      0.945        1.72
 8 B             3      0.661        2.27
 9 B             4      0.629        2.77
10 B             5      0.0618       2.70


问:
Rendering XML in Firefox 3.6
There was a point in time that Firefox (Version 3.5 or 3.6), by default, would render an XML file in a tree like format similar to that which Internet Explorer generates when pointed to an XML file.  Somewhere along the way, Firefox, or my installations of Firefox lost that ability.  Firefox now strips the XML elements from the XML file and displays only a glob of raw text.

It is possible to see the raw XML file using the View Source command.

However, I would like to adjust Firefox so that it will return to a behavior such that XML files are rendered as a 'tree' control with collapsible nodes, etc., much like Internet Explorer does by default for XML files.

I have searched a good bit and there are references to mime type mapping for XML files, or installation of an appropriate XSLT rendering for XML, but I cannot seem to identify precisely what is needed to create this behavior.  Also tried to find a Plug In for this purpose, but nothing that addresses only this particular problem.  No luck so far.

Seems like a really simple issue, but there seems to be frustratingly little information available.

Thanks,

EulerOperator

答:
For Firefox to render the contents of an XML file as a document tree using its default styles, at the very least,

the file shouldn't link to any XSL stylesheet

if the file is received from a Web server, the MIME type must be text/xml (I think application/xml works too, not sure)

This is inferred if opening an XML file from disk and the extension is known to Firefox as text/xml

Title: Rendering XML in Firefox 3.6


问:
MySQL Where Clause Issues
```<code>SELECT `location`.`building`, `location`.`classroom` FROM `schools`
LEFT OUTER JOIN `location`
ON `location`.`location_serial` = `classroom`.`location_serial`
LEFT OUTER JOIN `rack_info`
ON `classroom_info`.`location_serial` = `classroom`.`location_serial`
WHERE (
    (((`location`.`building` LIKE 'SCH%')))
    AND
    (`classroom_info`.`status` NOT IN (1, 2))
    AND
    (
        (
            (`location`.`building` = 'SCH1' AND `location`.`classroom` != '99')
            AND
            (`location`.`building` = 'SCH1' AND `location`.`classroom` != '34')
        )
    )
)
</code>```

I'm having a problem in my WHERE clause.

Let's say location.building can be SCH1, SCH2, SCH3, SCH4, CAB1, CAB2. I'm trying to select all of the SCH classrooms, where some classroom statuses are 1 & 2.

This all works fine

The problem arises when I try to further filter my results to exclude instances when the building is SCH1 and the classroom ID is 99, and when the building is SCH1 and the classroom ID is 34. I want to show all other classrooms across all SCH buildings (including SCH1, e.g. SCH1.98) but exclude the two specific classrooms mentioned in the SQL query above (SCH1.99 and SCH1.34)

I may also want to exclude other SCH rooms, like SCH2.24, SCH3.33 - but I want all the other classrooms to appear.

I've been looking for hours and I think I've reached the limits of my ability - all help welcome.

答:
Here are some ways how I would write the WHERE clause:

```<code>WHERE location.building LIKE 'SCH%'
  AND classroom_info.status NOT IN (1, 2)
  AND NOT (location.building = 'SCH1' AND location.classroom = '99')
  AND NOT (location.building = 'SCH1' AND location.classroom = '34')

WHERE location.building LIKE 'SCH%'
  AND classroom_info.status NOT IN (1, 2)
  AND NOT (location.building = 'SCH1' AND location.classroom IN ('99', '34'))

WHERE location.building LIKE 'SCH%'
  AND classroom_info.status NOT IN (1, 2)
  AND (location.building, location.classroom) NOT IN (
      ('SCH1', '99'),
      ('SCH1', '34')
  )
</code>```

This makes it quite simple to add more exclusion cases.

Title: MySQL Where Clause Issues

Body:
SELECT `location`.`building`, `location`.`classroom` FROM `schools`
LEFT OUTER JOIN `location`
ON `location`.`location_serial` = `classroom`.`location_serial`
LEFT OUTER JOIN `rack_info`
ON `classroom_info`.`location_serial` = `classroom`.`location_serial`
WHERE (
    (((`location`.`building` LIKE 'SCH%')))
    AND
    (`classroom_info`.`status` NOT IN (1, 2))
    AND
    (
        (
            (`location`.`building` = 'SCH1' AND `location`.`classroom` != '99')
            AND
            (`location`.`building` = 'SCH1' AND `location`.`classroom` != '34')
        )
    )
)

I'm having a problem in my WHERE clause.

Let's say location.building can be SCH1, SCH2, SCH3, SCH4, CAB1, CAB2. I'm trying to select all of the SCH classrooms, where some classroom statuses are 1 & 2.

This all works fine

The problem arises when I try to further filter my results to exclude instances when the building is SCH1 and the classroom ID is 99, and when the building is SCH1 and the classroom ID is 34. I want to show all other classrooms across all SCH buildings (including SCH1, e.g. SCH1.98) but exclude the two specific classrooms mentioned in the SQL query above (SCH1.99 and SCH1.34)

I may also want to exclude other SCH rooms, like SCH2.24, SCH3.33 - but I want all the other classrooms to appear.

I've been looking for hours and I think I've reached the limits of my ability - all help welcome.

Body:
Here are some ways how I would write the WHERE clause:

WHERE location.building LIKE 'SCH%'
  AND classroom_info.status NOT IN (1, 2)
  AND NOT (location.building = 'SCH1' AND location.classroom = '99')
  AND NOT (location.building = 'SCH1' AND location.classroom = '34')

WHERE location.building LIKE 'SCH%'
  AND classroom_info.status NOT IN (1, 2)
  AND NOT (location.building = 'SCH1' AND location.classroom IN ('99', '34'))

WHERE location.building LIKE 'SCH%'
  AND classroom_info.status NOT IN (1, 2)
  AND (location.building, location.classroom) NOT IN (
      ('SCH1', '99'),
      ('SCH1', '34')
  )

This makes it quite simple to add more exclusion cases.


问:
How to save a bool value into a memory location pointed to by a void*?
I have a void* lhs_value pointing to a sufficiently sized mallocated region of memory. I want to save a rvalue of type bool into it. Don't ask me why I wanted that. I think that this is as simple as casting that pointer to bool* and de referencing it. However the compiler complains. I am apparently doing something wrong. Can you help me with this?

```<code> error: expected '(' for function-style cast or type construction
                *((*bool) lhs_value) = true;
</code>```

```<code>void* lhs_value;
lhs_value = malloc( sizeof(int) );
memset(lhs_value, 0, sizeof(int));
*((*bool) lhs_value) = true;
</code>```

答:
```<code>   *static_cast<bool*>(lhs_value) = true;
</code>```

be aware of aliasing rules before doing this; they are complex and hard to get right, and the symptom of getting them wrong is "the code works" until it breaks in a random way in a random spot after a compiler upgrade.

Body:
I have a void* lhs_value pointing to a sufficiently sized mallocated region of memory. I want to save a rvalue of type bool into it. Don't ask me why I wanted that. I think that this is as simple as casting that pointer to bool* and de referencing it. However the compiler complains. I am apparently doing something wrong. Can you help me with this?

 error: expected '(' for function-style cast or type construction
                *((*bool) lhs_value) = true;

void* lhs_value;
lhs_value = malloc( sizeof(int) );
memset(lhs_value, 0, sizeof(int));
*((*bool) lhs_value) = true;

Body:
   *static_cast<bool*>(lhs_value) = true;

be aware of aliasing rules before doing this; they are complex and hard to get right, and the symptom of getting them wrong is "the code works" until it breaks in a random way in a random spot after a compiler upgrade.


问:
TypeError: 'numpy.uint32' object is not iterable in using numpy.full function
In some lines within a huge python script, there is a 3d array of 74537000 elements that are all float numbers:

```<code>import numpy as np
prop_shape = [74537000, 3]  # to produce this however a long script is written and this will be printed (just before the controversial line below) in the first run of the code assuming it's a vector quantity like position.
prop_in_dtype = np.float32  # position array with the shape (74537000, 3) is made up of float32 values. In general, however, prop_in_dtype is changing across the script due to the nature of the array
</code>```

When we are trying to make an identical array whose elements are all -1, we can use numpy as follows:

```<code>.
.
.
my_array = np.full(tuple(prop_shape), -1, prop_in_dtype)
.
.
.
</code>```

While running this, I have the following error message:

```<code>Traceback (most recent call last):
  File "DLA_DM.py", line 19, in <module>
    settings_centroid.init()
  File "/usr5/username/settings_centroid.py", line 43, in init
    part=gizmo.io.Read.read_snapshots(species, snapshot_value_kind, snapshot_number, simulation_directory='.', snapshot_directory='output/', simulation_name='', properties=properties, element_indices=None, particle_subsample_factor=0, separate_dark_lowres=True, sort_dark_by_id=False, convert_float32=True, host_number=1, assign_host_coordinates=True, assign_host_principal_axes=False, assign_host_orbits=False, assign_formation_coordinates=False, assign_pointers=False, check_properties=True)
  File "/usr5/username/simulation/gizmo/gizmo_io.py", line 649, in read_snapshots
    element_indices, convert_float32, header)
  File "/usr5/username/simulation/gizmo/gizmo_io.py", line 1164, in read_particles
    part[spec_name][prop] = np.full(tuple(prop_shape), - 1, prop_in_dtype)
TypeError: 'numpy.uint32' object is not iterable
</code>```

答:
I can reproduce the error message with:

```<code>In [174]: tuple(np.uint32(1))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-174-3420675a1788> in <module>
----> 1 tuple(np.uint32(1))

TypeError: 'numpy.uint32' object is not iterable
</code>```

So my guess is there's something wrong with the prop_shape variable.

Body:
In some lines within a huge python script, there is a 3d array of 74537000 elements that are all float numbers:

import numpy as np
prop_shape = [74537000, 3]  # to produce this however a long script is written and this will be printed (just before the controversial line below) in the first run of the code assuming it's a vector quantity like position.
prop_in_dtype = np.float32  # position array with the shape (74537000, 3) is made up of float32 values. In general, however, prop_in_dtype is changing across the script due to the nature of the array

When we are trying to make an identical array whose elements are all -1, we can use numpy as follows:

.
.
.
my_array = np.full(tuple(prop_shape), -1, prop_in_dtype)
.
.
.

While running this, I have the following error message:

Traceback (most recent call last):
  File "DLA_DM.py", line 19, in <module>
    settings_centroid.init()
  File "/usr5/username/settings_centroid.py", line 43, in init
    part=gizmo.io.Read.read_snapshots(species, snapshot_value_kind, snapshot_number, simulation_directory='.', snapshot_directory='output/', simulation_name='', properties=properties, element_indices=None, particle_subsample_factor=0, separate_dark_lowres=True, sort_dark_by_id=False, convert_float32=True, host_number=1, assign_host_coordinates=True, assign_host_principal_axes=False, assign_host_orbits=False, assign_formation_coordinates=False, assign_pointers=False, check_properties=True)
  File "/usr5/username/simulation/gizmo/gizmo_io.py", line 649, in read_snapshots
    element_indices, convert_float32, header)
  File "/usr5/username/simulation/gizmo/gizmo_io.py", line 1164, in read_particles
    part[spec_name][prop] = np.full(tuple(prop_shape), - 1, prop_in_dtype)
TypeError: 'numpy.uint32' object is not iterable

Body:
I can reproduce the error message with:

In [174]: tuple(np.uint32(1))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-174-3420675a1788> in <module>
----> 1 tuple(np.uint32(1))

TypeError: 'numpy.uint32' object is not iterable

So my guess is there's something wrong with the prop_shape variable.


问:
Send function(with parameters) inside the JSON object
I am trying to pass function(with parameter) to another function inside the json object. It always undefined and I couldn't find the reason.

First triggering packtNs.graduateForm.loadEvent function. Then sending
packtNs.common.populateWithTodaysDate("packt_supervisor", "packt_postgraduatestartdate") function to packtNs.common.wireOnChangeEvents function.

Here is my code:

```<code>var packtNs = packtNs || {};

packtNs.common = packtNs.common || {};

/**
* A method that populates the post graduate start date
* when the supervisor lookup is populated.
* @returns {Void}
*/

packtNs.common.populateWithTodaysDate = function(attributeToMonitor, dateAttributeToChange)
{
    console.log("Populatewithtodaysdate function triggered");
}

packtNs.common.wireOnChangeEvents =
    function(eventAttributeTuples){
        debugger;
        for (var i in eventAttributeTuples) {
           console.log(eventAttributeTuples[i].attribute);
           ////attribute is OK
           console.log(eventAttributeTuples[i].function);
           ////function is always undefined. eventAttributeTuples[0] object doesnt have function - tried different names
        }

}

packtNs.graduateForm = packtNs.graduateForm || {};

packtNs.graduateForm.loadEvent = function(){
    packtNs.common.wireOnChangeEvents([
        {
            attribute: "packt_supervisor",
            function:packtNs.common.populateWithTodaysDate("packt_supervisor", "packt_postgraduatestartdate")
        }
    ]);
    debugger;
}
</code>```

答:
This is a name spaced object not JSON, but to get something you have to return something.  I renamed your "function" to "mything" because well it was wrong.

var packtNs = packtNs || {};

packtNs.common = packtNs.common || {};

/**
 * A method that populates the post graduate start date
 * when the supervisor lookup is populated.
 * @returns {Void}
 */

packtNs.common.populateWithTodaysDate = function(attributeToMonitor, dateAttributeToChange) {
  console.log("Populatewithtodaysdate function triggered");
  return {
    arg1: attributeToMonitor,
    arg2: dateAttributeToChange
  };
}

packtNs.common
  .wireOnChangeEvents = function(eventAttributeTuples) {
    //debugger;
    console.log("tup:", eventAttributeTuples);
    for (var i in eventAttributeTuples) {
      console.log(eventAttributeTuples[i].attribute);
      ////attribute is OK
      console.log(eventAttributeTuples[i].mything);
      ////function is always undefined. eventAttributeTuples[0] object doesnt have function - tried different names
    }
    return eventAttributeTuples;
  }

packtNs.graduateForm = packtNs.graduateForm || {};

packtNs.graduateForm.loadEvent = function() {
  return packtNs.common.wireOnChangeEvents([{
    attribute: "packt_supervisor",
    mything: packtNs.common.populateWithTodaysDate("packt_supervisor", "packt_postgraduatestartdate")
  }]);
  // debugger;
}

var myresult = packtNs.graduateForm.loadEvent();
console.log("myresult:",myresult);```

Body:
I am trying to pass function(with parameter) to another function inside the json object. It always undefined and I couldn't find the reason.

First triggering packtNs.graduateForm.loadEvent function. Then sending
packtNs.common.populateWithTodaysDate("packt_supervisor", "packt_postgraduatestartdate") function to packtNs.common.wireOnChangeEvents function.

Here is my code:

var packtNs = packtNs || {};

packtNs.common = packtNs.common || {};

/**
* A method that populates the post graduate start date
* when the supervisor lookup is populated.
* @returns {Void}
*/

packtNs.common.populateWithTodaysDate = function(attributeToMonitor, dateAttributeToChange)
{
    console.log("Populatewithtodaysdate function triggered");
}

packtNs.common.wireOnChangeEvents =
    function(eventAttributeTuples){
        debugger;
        for (var i in eventAttributeTuples) {
           console.log(eventAttributeTuples[i].attribute);
           ////attribute is OK
           console.log(eventAttributeTuples[i].function);
           ////function is always undefined. eventAttributeTuples[0] object doesnt have function - tried different names
        }

}

packtNs.graduateForm = packtNs.graduateForm || {};

packtNs.graduateForm.loadEvent = function(){
    packtNs.common.wireOnChangeEvents([
        {
            attribute: "packt_supervisor",
            function:packtNs.common.populateWithTodaysDate("packt_supervisor", "packt_postgraduatestartdate")
        }
    ]);
    debugger;
}


问:
I can upload images to specific directory but can't view them in template (Page not found (404))
I am trying to add upload image to admin form in my Django project I found on GitHub. I can upload image to folder my_app(catalog)/media/images/image.png but when I try to call it in the template I can only see that image icon that appears when there is no picture.

settings.py

```<code>STATIC_URL = '/static/'

MEDIA_URL = '/media/'

MEDIA_ROOT  = os.path.join(BASE_DIR, 'catalog/media')
</code>```

model.py

```<code>class Book(models.Model):
    image = models.ImageField(blank=True, null = True, upload_to='images')
</code>```

book_detail.html

```<code>img src="{{ book.image.url}}" width="250"
</code>```

views.py

```<code>class BookDetailView(generic.DetailView):
    model = Book
</code>```

urls.py

```<code>from django.urls import path
from . import views
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('', views.index, name='index'),
    path('book/create/', views.BookCreate.as_view(), name='book_create'),
    path('books/', views.BookListView.as_view(), name='books'),
    path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'),

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

This is how it looks like (I print {{ book.image }} next to the picture (images/screenshot_4.png):

This is the error I get:

答:
Ok I found out after spending way to much time on it.
img src="{{ book.image.url}}" width="250" line in template should look like
img src="../media/{{ book.image.url}}" width="250".

Hope this helps someone with the same problem.

Body:
I am trying to add upload image to admin form in my Django project I found on GitHub. I can upload image to folder my_app(catalog)/media/images/image.png but when I try to call it in the template I can only see that image icon that appears when there is no picture.

settings.py

STATIC_URL = '/static/'

MEDIA_URL = '/media/'

MEDIA_ROOT  = os.path.join(BASE_DIR, 'catalog/media')

model.py

class Book(models.Model):
    image = models.ImageField(blank=True, null = True, upload_to='images')

book_detail.html

img src="{{ book.image.url}}" width="250"

views.py

class BookDetailView(generic.DetailView):
    model = Book

urls.py

from django.urls import path
from . import views
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('', views.index, name='index'),
    path('book/create/', views.BookCreate.as_view(), name='book_create'),
    path('books/', views.BookListView.as_view(), name='books'),
    path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'),

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

This is how it looks like (I print {{ book.image }} next to the picture (images/screenshot_4.png):

This is the error I get:


问:
How to include bootstrap css and js in reactjs app?
I am new to ReactJS, I want to include bootstrap in my React app

I have installed bootstrap by npm install bootstrap --save

Now, want to load bootstrap CSS and JS in my React app.

I am using webpack.

webpack.config.js

```<code>var config = {
    entry: './src/index',

    output: {
        path: './',
        filename: 'index.js'
    },

    devServer: {
        inline: true,
        port: 8080,
        historyApiFallback: true,
        contentBase:'./src'
    },

    module: {
        loaders: [
            {
                test: /\.js?$/,
                exclude: /node_modules/,
                loader: 'babel',

                query: {
                    presets: ['es2015', 'react']
               }
            }
        ]
    }
};

module. exports = config;
</code>```

My issue is “how to include bootstrap CSS and JS in ReactJS app from node modules?" How to set up for bootstrap to include in my React app?

答:
I just want to add that installing and importing bootstrap in your index.js file won't be enough for using bootstrap components.
Every time you want to use a component you should import it, like:
I need to use a container and a row

```<code>    <Container>
        <Row>
        <Col sm={4}> Test </Col>
        <Col sm={8}> Test </Col>
        </Row>
</Container>
</code>```

You should import in your js file

```<code>import {Container, Row, Col} from 'react-bootstrap';
</code>```

Body:
I am new to ReactJS, I want to include bootstrap in my React app

I have installed bootstrap by npm install bootstrap --save

Now, want to load bootstrap CSS and JS in my React app.

I am using webpack.

webpack.config.js

var config = {
    entry: './src/index',

    output: {
        path: './',
        filename: 'index.js'
    },

    devServer: {
        inline: true,
        port: 8080,
        historyApiFallback: true,
        contentBase:'./src'
    },

    module: {
        loaders: [
            {
                test: /\.js?$/,
                exclude: /node_modules/,
                loader: 'babel',

                query: {
                    presets: ['es2015', 'react']
               }
            }
        ]
    }
};

module. exports = config;

My issue is “how to include bootstrap CSS and JS in ReactJS app from node modules?" How to set up for bootstrap to include in my React app?

Body:
I just want to add that installing and importing bootstrap in your index.js file won't be enough for using bootstrap components.
Every time you want to use a component you should import it, like:
I need to use a container and a row

    <Container>
        <Row>
        <Col sm={4}> Test </Col>
        <Col sm={8}> Test </Col>
        </Row>
</Container>

You should import in your js file

import {Container, Row, Col} from 'react-bootstrap';


问:
How to access a matlab function from java code?
My java program uses matlab code packaged as jar files for image processing. The problem is when I call a function(written by me) with a call to 'mmreader' for the first time, it works fine. However any subsequent call to a function(same or different) calling 'mmreader' doesn't work and I get an error stating function mmreader not found.

I am also facing a similar problem in another part of my application where the call to matlab function simply throws an exception, the same piece of code works fine in other files.

```<code>try{
      vplayer.playmov(player_params);
   }
catch(Exception e){
            System.out.println("error playing cluster");
  }
</code>```

答: Besides that, in MATLAB you can create a JAR with your functions and sign that JAR to only work with your applications. Perhaps you'll need the MATLAB runtime to make that app work I'm not sure about that.</p>

ContentLicense: CC BY-SA 2.5

Body:
My java program uses matlab code packaged as jar files for image processing. The problem is when I call a function(written by me) with a call to 'mmreader' for the first time, it works fine. However any subsequent call to a function(same or different) calling 'mmreader' doesn't work and I get an error stating function mmreader not found.

I am also facing a similar problem in another part of my application where the call to matlab function simply throws an exception, the same piece of code works fine in other files.

try{
      vplayer.playmov(player_params);
   }
catch(Exception e){
            System.out.println("error playing cluster");
  }


问:
How to get Windows Explorer's selected file from within Excel VBA? What is de VBA code needed to do this?
I want to capture the name of the file already selected (with the checkbox selected) in a Windows Explorer open window using Excel VBA code. How do I do This? What is the code needed?</p>

答:
An alternate method: You can use a version of getsaveasname, or getopenfilename to open a dialog box that will prompt you to select a file assign the result to a variable and then you can do what you need to with it. You don't have to save or open the file, but those two inputboxes each have different settings.

nameYouWant = application.GetSaveAsName

I'm not sure how to do what you want to do, but it would take some really complex code in my estimation.

https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/getfilename-method-visual-basic-for-applications

https://wellsr.com/vba/2018/excel/get-filename-with-vba-getopenfilename/

In order to get excel to look outside itself to a different program is difficult. It means you would need to reference another library. If you are new to VBA, I wouldn't try to tackle it, but change your process if you can.

To give you a taste, here are some subroutines that are on the track of what you are asking for:
https://wellsr.com/vba/2016/excel/open-folder-using-vba-and-show-if-already-open/
http://vbadud.blogspot.com/2009/01/how-to-windows-explorer-using-vba.html


问:
db.collection().document().get() never returns null
MainActivity.kt

```<code>val db = FirebaseFirestore.getInstance()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val user = db.collection("zzz").document("ttt")
    user.get()
        .addOnSuccessListener { document ->
            if (document != null) {
                Log.d(TAG, "DocumentSnapshot: ${document}")
            }
        }
</code>```

My Log prints DocumentSnapshot: DocumentSnapshot{key=zzz/ttt, metadata=SnapshotMetadata{hasPendingWrites=false, isFromCache=false}, doc=null}.

No matter what collection() value or document() value I make user - it will never return null.

Why is this?

PS: The document also doesn't appear in my Firebase console.

答:
You should use exists() instead:

```<code>if (document.exists()) {
                Log.d(TAG, "DocumentSnapshot: ${document}")
            }

</code>```

From the docs:

public boolean exists()

Returns
true if the document existed in this snapshot

Body:
MainActivity.kt

val db = FirebaseFirestore.getInstance()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val user = db.collection("zzz").document("ttt")
    user.get()
        .addOnSuccessListener { document ->
            if (document != null) {
                Log.d(TAG, "DocumentSnapshot: ${document}")
            }
        }

My Log prints DocumentSnapshot: DocumentSnapshot{key=zzz/ttt, metadata=SnapshotMetadata{hasPendingWrites=false, isFromCache=false}, doc=null}.

No matter what collection() value or document() value I make user - it will never return null.

Why is this?

PS: The document also doesn't appear in my Firebase console.

Body:
You should use exists() instead:

if (document.exists()) {
                Log.d(TAG, "DocumentSnapshot: ${document}")
            }

From the docs:

public boolean exists()

Returns
true if the document existed in this snapshot


问:
VS Code: How to make the multi-line comment as Right Click menu item?
Using the latest Visual Studio Code, how can I make the below combination key

Shift + Alt + A

so that it can appear as right-click menu function?

答:
Assuming you want Shift-Alt-A to bring up the editor context menu there is a keybinding for that:

```<code>{
  "key": "shift+f10",
  "command": "editor.action.showContextMenu",
  "when": "textInputFocus"
}
</code>```

So you could change that to your chosen keybinding which I note is already bound to editor.action.blockComment so you will lose the block comment toggle ability if you use Shift-Alt-A.

Also that command only brings up the editor context menu, even if your explorer has focus for instance - which have a different context menu.  There doesn't appear to be any command for bringing up whichever context menu is contextual given current focus - only the editor context menu which may be what you want anyhow?

Body:
Assuming you want Shift-Alt-A to bring up the editor context menu there is a keybinding for that:

{
  "key": "shift+f10",
  "command": "editor.action.showContextMenu",
  "when": "textInputFocus"
}

So you could change that to your chosen keybinding which I note is already bound to editor.action.blockComment so you will lose the block comment toggle ability if you use Shift-Alt-A.

Also that command only brings up the editor context menu, even if your explorer has focus for instance - which have a different context menu.  There doesn't appear to be any command for bringing up whichever context menu is contextual given current focus - only the editor context menu which may be what you want anyhow?


问:
array manipulation
So i'm trying to avoid using vectors to do this, i know it would make it easier, but i'm trying to better my understanding of pointers and arrays. So is there a way to expand and shift an array without using the vectors? Here is what i have so far:</p>

```<code>int *expand(int *&arr, int size)
{
    int *newArray;

    size = size * 2;

    newArray = new int[size * 2];
    for (int index = 0; index < size; index++)
        newArray[index] = arr[index];
    return newArray;

}
</code>```

答:
See this link for a method that uses memcpy instead of looping through individual items.

```<code>int *expand(int *&arr, int size)
{
    size_t newSize = size * 2;
    int* newArr = new int[newSize];

    memcpy( newArr, arr, size * sizeof(int) );

    size = newSize;
    delete [] arr;
    arr = newArr;
}
</code>```

Title: array manipulation

Body:
So i'm trying to avoid using vectors to do this, i know it would make it easier, but i'm trying to better my understanding of pointers and arrays. So is there a way to expand and shift an array without using the vectors? Here is what i have so far:

int *expand(int *&arr, int size)
{
    int *newArray;

    size = size * 2;

    newArray = new int[size * 2];
    for (int index = 0; index < size; index++)
        newArray[index] = arr[index];
    return newArray;

}

Body:
See this link for a method that uses memcpy instead of looping through individual items.

int *expand(int *&arr, int size)
{
    size_t newSize = size * 2;
    int* newArr = new int[newSize];

    memcpy( newArr, arr, size * sizeof(int) );

    size = newSize;
    delete [] arr;
    arr = newArr;
}


问:
Is sizeof(<variable>) instead of sizeof(<type>) always safe?
I know that I can protect myself by writing

```<code>int *ptr = malloc(sizeof (*ptr))
</code>```

instead of

```<code>int *ptr = malloc(sizeof (int))
</code>```

The benefit is that if you decide to change the type of ptr to for instance long* instead of int*, then you only need to change the code at one place.

My question is, is this strategy always safe to do? Is there any situation where the construct T *ptr = malloc(sizeof(*ptr)) would not work? Does it matter if T is some complex struct, pointer to pointer, function pointer or an array? Or a combination of them for that matter.

I have tried to come up with a situation where it causes problems, but to me it seems safe. But I want to be able to trust the code completely.

答:
The only case I could see causing problems is if *ptr has a variable-length array type, because that's the only case where sizeof evaluates its operand.

That is:

```<code>int n = ...;
T (*ptr)[n] = malloc(sizeof *ptr);
</code>```

has undefined behavior because the type of *ptr is T [n], which is a variable-length array type, which means sizeof evaluates its operand, which dereferences an uninitialized pointer (*ptr).

However, it's hard to run into that issue by accident. Normally you'd just do

```<code>T *ptr = malloc(n * sizeof *ptr);
</code>```

which is fine1.

1 Well, the multiplication might overflow. To protect against that, you need something like T *ptr = calloc(n, sizeof *ptr);.

Body:
I know that I can protect myself by writing

int *ptr = malloc(sizeof (*ptr))

instead of

int *ptr = malloc(sizeof (int))

The benefit is that if you decide to change the type of ptr to for instance long* instead of int*, then you only need to change the code at one place.

My question is, is this strategy always safe to do? Is there any situation where the construct T *ptr = malloc(sizeof(*ptr)) would not work? Does it matter if T is some complex struct, pointer to pointer, function pointer or an array? Or a combination of them for that matter.

I have tried to come up with a situation where it causes problems, but to me it seems safe. But I want to be able to trust the code completely.

Body:
The only case I could see causing problems is if *ptr has a variable-length array type, because that's the only case where sizeof evaluates its operand.

That is:

int n = ...;
T (*ptr)[n] = malloc(sizeof *ptr);

has undefined behavior because the type of *ptr is T [n], which is a variable-length array type, which means sizeof evaluates its operand, which dereferences an uninitialized pointer (*ptr).

However, it's hard to run into that issue by accident. Normally you'd just do

T *ptr = malloc(n * sizeof *ptr);

which is fine1.

1 Well, the multiplication might overflow. To protect against that, you need something like T *ptr = calloc(n, sizeof *ptr);.


问:
Programmatically retrieve Visual Studio install directory
I know there is a registry key indicating the install directory, but I don't remember what it is off-hand.

I am currently interested in Visual Studio 2008 install directory, though it wouldn't hurt to list others for future reference.

答:
Here is something I have been updating over the years... (for CudaPAD)

Usage examples:

```<code>var vsPath = VS_Tools.GetVSPath(avoidPrereleases:true, requiredWorkload:"NativeDesktop");
var vsPath = VS_Tools.GetVSPath();
var vsPath = VS_Tools.GetVSPath(specificVersion:"15");
</code>```

The drop-in function:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.Setup.Configuration;
using System.IO;
using Microsoft.Win32;

static class VS_Tools
{
    public static string GetVSPath(string specificVersion = "", bool avoidPrereleases = true, string requiredWorkload = "")
    {
        string vsPath = "";
        // Method 1 - use "Microsoft.VisualStudio.Setup.Configuration.SetupConfiguration" method.

        // Note: This code has is a heavily modified version of Heath Stewart's code.
        // original source: (Heath Stewart, May 2016) https://github.com/microsoft/vs-setup-samples/blob/80426ad4ba10b7901c69ac0fc914317eb65deabf/Setup.Configuration.CS/Program.cs
        try
        {
            var e = new SetupConfiguration().EnumAllInstances();

            int fetched;
            var instances = new ISetupInstance[1];
            do
            {
                e.Next(1, instances, out fetched);
                if (fetched > 0)
                {
                    var instance2 = (ISetupInstance2)instances[0];
                    var state = instance2.GetState();

                    // Let's make sure this install is complete.
                    if (state != InstanceState.Complete)
                        continue;

                    // If we have a version to match lets make sure to match it.
                    if (!string.IsNullOrWhiteSpace(specificVersion))
                        if (!instances[0].GetInstallationVersion().StartsWith(specificVersion))
                            continue;

                    // If instances[0] is null then skip
                    var catalog = instances[0] as ISetupInstanceCatalog;
                    if (catalog == null)
                        continue;

                    // If there is not installation path lets skip
                    if ((state & InstanceState.Local) != InstanceState.Local)
                        continue;

                    // Let's make sure it has the required workload - if one was given.
                    if (!string.IsNullOrWhiteSpace(requiredWorkload))
                    {
                        if ((state & InstanceState.Registered) == InstanceState.Registered)
                        {
                            if (!(from package in instance2.GetPackages()
                                    where string.Equals(package.GetType(), "Workload", StringComparison.OrdinalIgnoreCase)
                                    where package.GetId().Contains(requiredWorkload)
                                    orderby package.GetId()
                                    select package).Any())
                            {
                                continue;
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }

                    // Let's save the installation path and make sure it has a value.
                    vsPath = instance2.GetInstallationPath();
                    if (string.IsNullOrWhiteSpace(vsPath))
                        continue;

                    // If specified, avoid Pre-release if possible
                    if (avoidPrereleases && catalog.IsPrerelease())
                        continue;

                    // We found the one we need - lets get out of here
                    return vsPath;
                }
            }
            while (fetched > 0);
        }
        catch (Exception){ }

        if (string.IsNullOrWhiteSpace(vsPath))
            return vsPath;

        // Fall-back Method: Find the location of visual studio (%VS90COMNTOOLS%\..\..\vc\vcvarsall.bat)
        // Note: This code has is a heavily modified version of Kevin Kibler's code.
        // source: (Kevin Kibler, 2014) http://stackoverflow.com/questions/30504/programmatically-retrieve-visual-studio-install-directory
        List<Version> vsVersions = new List<Version>() { new Version("15.0"), new Version("14.0"),
            new Version("13.0"), new Version("12.0"), new Version("11.0") };
        foreach (var version in vsVersions)
        {
            foreach (var isExpress in new bool[] { false, true })
            {
                RegistryKey registryBase32 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
                RegistryKey vsVersionRegistryKey = registryBase32.OpenSubKey(
                    string.Format(@"{0}\{1}.{2}",
                    (isExpress) ? @"SOFTWARE\Microsoft\VCSExpress" : @"SOFTWARE\Microsoft\VisualStudio",
                    version.Major, version.Minor));
                if (vsVersionRegistryKey == null) { continue; }
                string path = vsVersionRegistryKey.GetValue("InstallDir", string.Empty).ToString();
                if (!string.IsNullOrEmpty(path))
                {
                    path = Directory.GetParent(path).Parent.Parent.FullName;
                    if (File.Exists(path + @"\VC\bin\cl.exe") && File.Exists(path + @"\VC\vcvarsall.bat"))
                    {
                        vsPath = path;
                        break;
                    }
                }
            }
            if (!string.IsNullOrWhiteSpace(vsPath))
                break;
        }
        return vsPath;
    }
}
</code>```

OwnerDisplayName: Emperor XLII

Body:
Here is something I have been updating over the years... (for CudaPAD)

Usage examples:

var vsPath = VS_Tools.GetVSPath(avoidPrereleases:true, requiredWorkload:"NativeDesktop");
var vsPath = VS_Tools.GetVSPath();
var vsPath = VS_Tools.GetVSPath(specificVersion:"15");

The drop-in function:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.Setup.Configuration;
using System.IO;
using Microsoft.Win32;

static class VS_Tools
{
    public static string GetVSPath(string specificVersion = "", bool avoidPrereleases = true, string requiredWorkload = "")
    {
        string vsPath = "";
        // Method 1 - use "Microsoft.VisualStudio.Setup.Configuration.SetupConfiguration" method.

        // Note: This code has is a heavily modified version of Heath Stewart's code.
        // original source: (Heath Stewart, May 2016) https://github.com/microsoft/vs-setup-samples/blob/80426ad4ba10b7901c69ac0fc914317eb65deabf/Setup.Configuration.CS/Program.cs
        try
        {
            var e = new SetupConfiguration().EnumAllInstances();

            int fetched;
            var instances = new ISetupInstance[1];
            do
            {
                e.Next(1, instances, out fetched);
                if (fetched > 0)
                {
                    var instance2 = (ISetupInstance2)instances[0];
                    var state = instance2.GetState();

                    // Let's make sure this install is complete.
                    if (state != InstanceState.Complete)
                        continue;

                    // If we have a version to match lets make sure to match it.
                    if (!string.IsNullOrWhiteSpace(specificVersion))
                        if (!instances[0].GetInstallationVersion().StartsWith(specificVersion))
                            continue;

                    // If instances[0] is null then skip
                    var catalog = instances[0] as ISetupInstanceCatalog;
                    if (catalog == null)
                        continue;

                    // If there is not installation path lets skip
                    if ((state & InstanceState.Local) != InstanceState.Local)
                        continue;

                    // Let's make sure it has the required workload - if one was given.
                    if (!string.IsNullOrWhiteSpace(requiredWorkload))
                    {
                        if ((state & InstanceState.Registered) == InstanceState.Registered)
                        {
                            if (!(from package in instance2.GetPackages()
                                    where string.Equals(package.GetType(), "Workload", StringComparison.OrdinalIgnoreCase)
                                    where package.GetId().Contains(requiredWorkload)
                                    orderby package.GetId()
                                    select package).Any())
                            {
                                continue;
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }

                    // Let's save the installation path and make sure it has a value.
                    vsPath = instance2.GetInstallationPath();
                    if (string.IsNullOrWhiteSpace(vsPath))
                        continue;

                    // If specified, avoid Pre-release if possible
                    if (avoidPrereleases && catalog.IsPrerelease())
                        continue;

                    // We found the one we need - lets get out of here
                    return vsPath;
                }
            }
            while (fetched > 0);
        }
        catch (Exception){ }

        if (string.IsNullOrWhiteSpace(vsPath))
            return vsPath;

        // Fall-back Method: Find the location of visual studio (%VS90COMNTOOLS%\..\..\vc\vcvarsall.bat)
        // Note: This code has is a heavily modified version of Kevin Kibler's code.
        // source: (Kevin Kibler, 2014) http://stackoverflow.com/questions/30504/programmatically-retrieve-visual-studio-install-directory
        List<Version> vsVersions = new List<Version>() { new Version("15.0"), new Version("14.0"),
            new Version("13.0"), new Version("12.0"), new Version("11.0") };
        foreach (var version in vsVersions)
        {
            foreach (var isExpress in new bool[] { false, true })
            {
                RegistryKey registryBase32 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
                RegistryKey vsVersionRegistryKey = registryBase32.OpenSubKey(
                    string.Format(@"{0}\{1}.{2}",
                    (isExpress) ? @"SOFTWARE\Microsoft\VCSExpress" : @"SOFTWARE\Microsoft\VisualStudio",
                    version.Major, version.Minor));
                if (vsVersionRegistryKey == null) { continue; }
                string path = vsVersionRegistryKey.GetValue("InstallDir", string.Empty).ToString();
                if (!string.IsNullOrEmpty(path))
                {
                    path = Directory.GetParent(path).Parent.Parent.FullName;
                    if (File.Exists(path + @"\VC\bin\cl.exe") && File.Exists(path + @"\VC\vcvarsall.bat"))
                    {
                        vsPath = path;
                        break;
                    }
                }
            }
            if (!string.IsNullOrWhiteSpace(vsPath))
                break;
        }
        return vsPath;
    }
}


问:
Checking if two dictionaries of key-val pairs with values as array are equal
I have two dictionaries as:

```<code>a = {0: array([4.5, 5. ]), 1: array([3.5, 4.5]), 2: array([1., 1.])}
b = {0: array([4., 5. ]), 1: array([3, 4]), 2: array([1.5, 1.])}
</code>```

How do I check if these two dictionaries are equal?
I tried:

```<code>a==b

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

Also,

```<code>(a==b).all()
a.all()==b.all()
</code>```

All return errors.

答:
== with dictionaries compares keys and values.  But the values are arrays.  array1 == array2 produces a boolean array, which does not play well with the yes/no expectations of the dictionary test (the ambiguity error).

A way around that is to compare the values individually.  np.allclose is the best test for float arrays.  Assuming that the keys match, the following list comprehension works nicely:

```<code>In [177]: array=np.array
In [178]: a = {0: array([4.5, 5. ]), 1: array([3.5, 4.5]), 2: array([1., 1.])}
     ...: b = {0: array([4., 5. ]), 1: array([3, 4]), 2: array([1.5, 1.])}
In [179]: a
Out[179]: {0: array([4.5, 5. ]), 1: array([3.5, 4.5]), 2: array([1., 1.])}
In [180]: b
Out[180]: {0: array([4., 5.]), 1: array([3, 4]), 2: array([1.5, 1. ])}
In [181]: [np.allclose(a[k],b[k]) for k in a]
Out[181]: [False, False, False]
In [182]: [np.allclose(a[k],a[k]) for k in a]
Out[182]: [True, True, True]
</code>```

There should be another lay of testing, for equal keys.

However allclose does not work if the arrays differ in shape:

```<code>In [183]: c = {0: array([4., 5., 0 ]), 1: array([3, 4]), 2: array([1, 1.])}
In [185]: [np.allclose(a[k],c[k]) for k in a]
....
ValueError: operands could not be broadcast together with shapes (2,) (3,)
</code>```

The comparison task will be a lot simpler if you know how the dictionaries might differ.  Can they differ in keys?  Can they differ in types of the values (array vs a list vs a number)?  If values are arrays, can they differ in shape?

Body:
I have two dictionaries as:

a = {0: array([4.5, 5. ]), 1: array([3.5, 4.5]), 2: array([1., 1.])}
b = {0: array([4., 5. ]), 1: array([3, 4]), 2: array([1.5, 1.])}

How do I check if these two dictionaries are equal?
I tried:

a==b

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Also,

(a==b).all()
a.all()==b.all()

All return errors.

Body:
== with dictionaries compares keys and values.  But the values are arrays.  array1 == array2 produces a boolean array, which does not play well with the yes/no expectations of the dictionary test (the ambiguity error).

A way around that is to compare the values individually.  np.allclose is the best test for float arrays.  Assuming that the keys match, the following list comprehension works nicely:

In [177]: array=np.array
In [178]: a = {0: array([4.5, 5. ]), 1: array([3.5, 4.5]), 2: array([1., 1.])}
     ...: b = {0: array([4., 5. ]), 1: array([3, 4]), 2: array([1.5, 1.])}
In [179]: a
Out[179]: {0: array([4.5, 5. ]), 1: array([3.5, 4.5]), 2: array([1., 1.])}
In [180]: b
Out[180]: {0: array([4., 5.]), 1: array([3, 4]), 2: array([1.5, 1. ])}
In [181]: [np.allclose(a[k],b[k]) for k in a]
Out[181]: [False, False, False]
In [182]: [np.allclose(a[k],a[k]) for k in a]
Out[182]: [True, True, True]

There should be another lay of testing, for equal keys.

However allclose does not work if the arrays differ in shape:

In [183]: c = {0: array([4., 5., 0 ]), 1: array([3, 4]), 2: array([1, 1.])}
In [185]: [np.allclose(a[k],c[k]) for k in a]
....
ValueError: operands could not be broadcast together with shapes (2,) (3,)

The comparison task will be a lot simpler if you know how the dictionaries might differ.  Can they differ in keys?  Can they differ in types of the values (array vs a list vs a number)?  If values are arrays, can they differ in shape?


问:
What is the most concise programming language?
What is the most concise programming language?
in case a criteria is needed for conciseness: on balance requires the least amount of characters to create any given program. </p>

答:
As yassin pointed out, for daily use, functional programming languages offer more terseness. Haskell seems a great example: the "xmonad" window manager was written in less than 1000 lines of code!

While not directly related to the question, it's also interesting to know that xmonad doesn't crash, because a theorem prover was run over the code to prove it wouldn't crash! 1


问:
Kotlin FP : Convert List<String> to Map<String,Int>
I have a List of String, I want to transform into a Map of occurrences. ( ~ The Map values are the count of many times the String was repeated in the List)

The imperative way, I'd write like the following

```<code>fun transformMap(list: List<String>): Map<String, Int> {
    val map = mutableMapOf<String,Int>()
    for(n in list){
        map.put(n,map.getOrDefault(n,0) + 1)
    }
    return map.toMap()
}
</code>```

How to write this in Functional Programming way ?

In Java 8+, this will be written like this

```<code>String[] note;
Map<String, Integer> noteMap = Arrays.stream(note)
         .collect(groupingBy(Function.identity(),
          collectingAndThen(counting(), Long::intValue)));
</code>```

答:
You can use streams in Kotlin too. But if you want to avoid streams, you can use fold():

```<code>val list = listOf("a", "b", "c", "a")
val histogram = list.fold(mutableMapOf<String, Int>()) { map, s ->
    map[s] = map.getOrDefault(s, 0) + 1
    map
}.toMap()

println(histogram)
</code>```

Body:
I have a List of String, I want to transform into a Map of occurrences. ( ~ The Map values are the count of many times the String was repeated in the List)

The imperative way, I'd write like the following

fun transformMap(list: List<String>): Map<String, Int> {
    val map = mutableMapOf<String,Int>()
    for(n in list){
        map.put(n,map.getOrDefault(n,0) + 1)
    }
    return map.toMap()
}

How to write this in Functional Programming way ?

In Java 8+, this will be written like this

String[] note;
Map<String, Integer> noteMap = Arrays.stream(note)
         .collect(groupingBy(Function.identity(),
          collectingAndThen(counting(), Long::intValue)));

Body:
You can use streams in Kotlin too. But if you want to avoid streams, you can use fold():

val list = listOf("a", "b", "c", "a")
val histogram = list.fold(mutableMapOf<String, Int>()) { map, s ->
    map[s] = map.getOrDefault(s, 0) + 1
    map
}.toMap()

println(histogram)