问:
I want to place a button above another UI element programmatically in swift
I tried to place a button programmatically above a separator but it doesn't show at run time this is my view in story board shown in the picture

the separator is UIview I dragged and dropped it in storyboard and linked it to my controller

this is my code
//

```<code>import UIKit
import Firebase
import FBSDKCoreKit
import FBSDKLoginKit

class LoginController: UIViewController, FBSDKLoginButtonDelegate {

    @IBOutlet weak var separator: UIView!
    @IBOutlet var fbLoginButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        if FBSDKAccessToken.current() != nil {
            // Present the main view because user already logged in
            self.performSegue(withIdentifier: "goToHome", sender: self)
        }else{

            loginButtonUI()
        }
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)

        loginButtonUI()
    }

    private func loginButtonUI(){

        let loginButton = FBSDKLoginButton()
        loginButton.delegate = self
        // Optional: Place the button in the center of your view.
        loginButton.center = view.center
        view.addSubview(loginButton)
    }

    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {

        // fb login code

    }

}
</code>```

but the button doesn't show at run time why?

答:
you need to activate your constraints, and make sure you added correctly</p>

```<code>let loginButton = FBSDKLoginButton()
    loginButton.delegate = self

    view.addSubview(loginButton)
    loginButton.translatesAutoresizingMaskIntoConstraints = false
    loginButton.centerXAnchor.constraint(equalTo: separatorView.centerXAnchor).isActive = true
    loginButton.bottomAnchor.constraint(equalTo: separatorView.topAnchor, constant: 20).isActive = true
    loginButton.widthAnchor.constraint(equalToConstant: 100).isActive = true
    loginButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
</code>```

Body:
I tried to place a button programmatically above a separator but it doesn't show at run time this is my view in story board shown in the picture

the separator is UIview I dragged and dropped it in storyboard and linked it to my controller

this is my code
//

import UIKit
import Firebase
import FBSDKCoreKit
import FBSDKLoginKit

class LoginController: UIViewController, FBSDKLoginButtonDelegate {

    @IBOutlet weak var separator: UIView!
    @IBOutlet var fbLoginButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        if FBSDKAccessToken.current() != nil {
            // Present the main view because user already logged in
            self.performSegue(withIdentifier: "goToHome", sender: self)
        }else{

            loginButtonUI()
        }
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)

        loginButtonUI()
    }

    private func loginButtonUI(){

        let loginButton = FBSDKLoginButton()
        loginButton.delegate = self
        // Optional: Place the button in the center of your view.
        loginButton.center = view.center
        view.addSubview(loginButton)
    }

    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {

        // fb login code

    }

}

but the button doesn't show at run time why?

Body:
you need to activate your constraints, and make sure you added correctly

let loginButton = FBSDKLoginButton()
    loginButton.delegate = self

    view.addSubview(loginButton)
    loginButton.translatesAutoresizingMaskIntoConstraints = false
    loginButton.centerXAnchor.constraint(equalTo: separatorView.centerXAnchor).isActive = true
    loginButton.bottomAnchor.constraint(equalTo: separatorView.topAnchor, constant: 20).isActive = true
    loginButton.widthAnchor.constraint(equalToConstant: 100).isActive = true
    loginButton.heightAnchor.constraint(equalToConstant: 40).isActive = true


来源: stackexchange

问:
How can I write a nested arbitrary associative Array value set to a .psd1 file in powershell?
I have a powershell Array object that is programmatically generated, something with arrays inside arrays, inside arrays, sometimes called a "property bag" or a "hashtable", but I think it's natively called an "Array containing Arrays" in the most native powershell terminology.

For example:

```<code> @{
 Version  = '1.0.0'
 Name     = 'thing'
 Revision = 'c3a89cd20e19bb82f41e95e0806edc5b6cfd224e'
 Date     = '2016-12-09'
 Build    = '1234'
 Contents = @{
      "index.html" = "23dd7b993f40bb3ae8848fe104b3b767"
 }
 }
</code>```

Generating a function to save only one specific set of contents to a .PSD1 file seems not general enough.
I want to save that exact in-memory Array structure to a PSD1 file. Does any built-in way in Powershell exist to Persist an in-memory variable with the values above? The "opposite function" of Import-PowershellDataFile. I would have guessed it would be called Export-PowershellDatafile but no such function seems to exist.

答:
Have you tried using New-ModuleManifest? Without knowing any additional details, it appears that you're creating something substantially similar to a manifest file used in a module... But even if your use case is different, you should still be able to use the cmdlet.

New-ModuleManifest has been around for a while (at least since v3, but I seem to recall using it with v2 as well). It allows you to define a hashtable of properties and save it down as a .psd1.

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/new-modulemanifest?view=powershell-5.1

ContentLicense: CC BY-SA 3.0

Body:
I have a powershell Array object that is programmatically generated, something with arrays inside arrays, inside arrays, sometimes called a "property bag" or a "hashtable", but I think it's natively called an "Array containing Arrays" in the most native powershell terminology.

For example:

 @{
 Version  = '1.0.0'
 Name     = 'thing'
 Revision = 'c3a89cd20e19bb82f41e95e0806edc5b6cfd224e'
 Date     = '2016-12-09'
 Build    = '1234'
 Contents = @{
      "index.html" = "23dd7b993f40bb3ae8848fe104b3b767"
 }
 }

Generating a function to save only one specific set of contents to a .PSD1 file seems not general enough.
I want to save that exact in-memory Array structure to a PSD1 file. Does any built-in way in Powershell exist to Persist an in-memory variable with the values above? The "opposite function" of Import-PowershellDataFile. I would have guessed it would be called Export-PowershellDatafile but no such function seems to exist.

ContentLicense: CC BY-SA 4.0


问:
Efficient algorithm to produce the n-way intersection of sorted arrays in C
I need to produce the intersection between some sorted arrays of integers in C. I know how to find the intersection between two sorted arrays, but I need to do this for more than two arrays, efficiently and without prior knowledge of the number of arrays. I can impose a sensible limit on the maximum number - let's say ten for now. These arrays could be anywhere from a few items to a couple of hundred thousand items long, and are by no means necessarily the same length.

Pseudo-code for producing the intersection of two sorted arrays:

```<code>while i < m and j < n do:
    if array1[i] < array2[j]:
        increment i
    else if array1[i] > array2[j]:
        increment j
    else
        add array1[i] to intersection(array1, array2)
        increment i
        increment j
</code>```

I am working with C, and I am after a clear explanation rather than code.

答:
You already have the logic for intersect on two arrays, so just call it multiple times.

Your intersect logic,

```<code>while i < m and j < n do:
if array1[i] < array1[j]:
    increment i
else if array1[i] > array2[j]:
    increment j
else
    add array1[i] to intersection(array1, array2)
    increment i
    increment j
</code>```

Encapsulate the above code in an Intersect(int[] array1, int[] array2, int array1Length, int array2Length), that returns int[]. Call the method again on the result.

Call1: int[] result = Intersect(array1, array2, array1Length, array2Length)

Call2: result = Intersect(result, array3, resultArrayLength, array3Length)

...

Call(n-1): result = Intersect(result, arrayn, resultArrayLength, arraynLength)

Possible optimizations:

Continue with the calls only if the resultArrayLength > 0 (otherwise the interestion is a null set).

In the intersect method compare the last element of array1 with the first element of array2, i.e.

EDITED
    if (array1[array1Length - 1] < array2[0]) return empty set (assuming that the arrays are sorted).

Body:
I need to produce the intersection between some sorted arrays of integers in C. I know how to find the intersection between two sorted arrays, but I need to do this for more than two arrays, efficiently and without prior knowledge of the number of arrays. I can impose a sensible limit on the maximum number - let's say ten for now. These arrays could be anywhere from a few items to a couple of hundred thousand items long, and are by no means necessarily the same length.

Pseudo-code for producing the intersection of two sorted arrays:

while i < m and j < n do:
    if array1[i] < array2[j]:
        increment i
    else if array1[i] > array2[j]:
        increment j
    else
        add array1[i] to intersection(array1, array2)
        increment i
        increment j

I am working with C, and I am after a clear explanation rather than code.

Body:
You already have the logic for intersect on two arrays, so just call it multiple times.

Your intersect logic,

while i < m and j < n do:
if array1[i] < array1[j]:
    increment i
else if array1[i] > array2[j]:
    increment j
else
    add array1[i] to intersection(array1, array2)
    increment i
    increment j

Encapsulate the above code in an Intersect(int[] array1, int[] array2, int array1Length, int array2Length), that returns int[]. Call the method again on the result.

Call1: int[] result = Intersect(array1, array2, array1Length, array2Length)

Call2: result = Intersect(result, array3, resultArrayLength, array3Length)

...

Call(n-1): result = Intersect(result, arrayn, resultArrayLength, arraynLength)

Possible optimizations:

Continue with the calls only if the resultArrayLength > 0 (otherwise the interestion is a null set).

In the intersect method compare the last element of array1 with the first element of array2, i.e.

EDITED
    if (array1[array1Length - 1] < array2[0]) return empty set (assuming that the arrays are sorted).


问:
Instance variables and Inheritance
Currently I am trying to calculate the distance between the Image1 and Player classes, in my main(). My variables of interest are Bx,By,Px, and Py seen below. Currently I can get the images in the Pygame window to update and print out their respective coordinates in real time. However I would like to have access to the individual variables so I can implement a distance variable.

class Image1(pygame.sprite.Sprite):
    def __init__(self, img, all_active_sprites):
        super().__init__()

        #scale player image
        self.image = pygame.transform.scale(ImageOne, (100, 100))
        self.image.set_colorkey(BLACK)
        self.rect = self.image.get_rect()

        #set spawn location for image
        self.rect.x = random.randrange(25, WINDOWWIDTH - 25)
        self.rect.y = random.randrange(25, WINDOWHEIGHT - 25)

        #set speed/direction
        self.speed_x = random.choice([-1,1])
        self.speed_y = random.choice([-1,1])

    def update(self):
        ''' update Image1 class '''
        self.rect.y += self.speed_y
        self.rect.x += self.speed_x

        #simulate zigzag movement

        "Omitted for Space - Movement Rules"

        #calculate coordinates
        Bx = self.rect.x
        By = self.rect.y
        coordinates_Image1 = (Bx,By)
        print("Image1 Position:",coordinates_Image1)

class Player(pygame.sprite.Sprite):
    def __init__(self, player_img,all_active_sprites):
        super().__init__()
        #scale player image
        self.image = pygame.transform.scale(player_img, (25, 25))
        self.image.set_colorkey(BLACK)
        self.rect = self.image.get_rect()

        #player starting location
        self.rect.x = WINDOWWIDTH / 2
        self.rect.y = WINDOWHEIGHT/ 2

        #player speed
        self.speed_x = 0
        self.speed_y = 0

    def update(self):
        '''update the Player class'''
        #arrow controls
        "Omitted for Space - Key Commands"

        #update movement, stop at boundaries
        self.rect.x += self.speed_x
        self.rect.y += self.speed_y

        "Omitted for Space - Movement Rules"

        #calculate coordinates
        Px = self.rect.x
        Py = self.rect.y
        coordinates_player = Px,Py
        print("Player Position:",coordinates_player)

```

My thinking was that I needed to find a way to access these instance variables outside of the locale, so what I tried as a solution was as follows. I separated the coordinates into their own functions inside each class, away from the movement calculations. Then in my main() I created an instance for each class, p = Player(args) for example. I then called the coordinate functions from my main(), and the paired coordinates, (x,y), would print as before but I still could not access/print the individual variables desired. Not sure what I'm doing wrong. Thank you and be well!

答: The variables Px and Py are only in scope in the update() function. They are called "local variables". On the other hand, you have a variable named p which represents an entire player. It has a field p.rect that is its bounding rectangle. And from there you can access p.rect.x and p.rect.y.

Title: Instance variables and Inheritance

Body:
Currently I am trying to calculate the distance between the Image1 and Player classes, in my main(). My variables of interest are Bx,By,Px, and Py seen below. Currently I can get the images in the Pygame window to update and print out their respective coordinates in real time. However I would like to have access to the individual variables so I can implement a distance variable.

class Image1(pygame.sprite.Sprite):
    def __init__(self, img, all_active_sprites):
        super().__init__()

        #scale player image
        self.image = pygame.transform.scale(ImageOne, (100, 100))
        self.image.set_colorkey(BLACK)
        self.rect = self.image.get_rect()

        #set spawn location for image
        self.rect.x = random.randrange(25, WINDOWWIDTH - 25)
        self.rect.y = random.randrange(25, WINDOWHEIGHT - 25)

        #set speed/direction
        self.speed_x = random.choice([-1,1])
        self.speed_y = random.choice([-1,1])

    def update(self):
        ''' update Image1 class '''
        self.rect.y += self.speed_y
        self.rect.x += self.speed_x

        #simulate zigzag movement

        "Omitted for Space - Movement Rules"

        #calculate coordinates
        Bx = self.rect.x
        By = self.rect.y
        coordinates_Image1 = (Bx,By)
        print("Image1 Position:",coordinates_Image1)

class Player(pygame.sprite.Sprite):
    def __init__(self, player_img,all_active_sprites):
        super().__init__()
        #scale player image
        self.image = pygame.transform.scale(player_img, (25, 25))
        self.image.set_colorkey(BLACK)
        self.rect = self.image.get_rect()

        #player starting location
        self.rect.x = WINDOWWIDTH / 2
        self.rect.y = WINDOWHEIGHT/ 2

        #player speed
        self.speed_x = 0
        self.speed_y = 0

    def update(self):
        '''update the Player class'''
        #arrow controls
        "Omitted for Space - Key Commands"

        #update movement, stop at boundaries
        self.rect.x += self.speed_x
        self.rect.y += self.speed_y

        "Omitted for Space - Movement Rules"

        #calculate coordinates
        Px = self.rect.x
        Py = self.rect.y
        coordinates_player = Px,Py
        print("Player Position:",coordinates_player)

My thinking was that I needed to find a way to access these instance variables outside of the locale, so what I tried as a solution was as follows. I separated the coordinates into their own functions inside each class, away from the movement calculations. Then in my main() I created an instance for each class, p = Player(args) for example. I then called the coordinate functions from my main(), and the paired coordinates, (x,y), would print as before but I still could not access/print the individual variables desired. Not sure what I'm doing wrong. Thank you and be well!


问:
How can I spin an object each 5 seconds in other random values?
```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateCamera : MonoBehaviour
{
    public GameObject objectToSpin;
    public float spinX;
    public float spinY;
    public float spinZ;
    public bool randomSpin = false;

    private void Start()
    {
        var rb = GetComponent<Rigidbody>();
        rb.angularVelocity = Random.insideUnitSphere;
    }

    private void Update()
    {
        if (randomSpin == true)
        {
            objectToSpin.transform.Rotate(Random.Range(spinX, 360), Random.Range(spinY, 360), Random.Range(spinZ, 360));
        }
        else
        {
            objectToSpin.transform.Rotate(spinX, spinY, spinZ);
        }
    }
}
</code>```

Now when changing the randomSpin flag to true it will spin random nonstop changing random angle on x y z each frame.

But I want it to spin random for 5 seconds after 5 seconds to change to random values the x y z and continue from last point and then after 5 seconds random angles and so on.

答:
If you want a constant speed and just a random direction, You can randomly select an Axis to rotate around using Random.onUnitSphere and then rotate around it at a speed.

Here's a solution that uses a Coroutine. If you want to stop the Coroutine, you can use StopCoroutine("Spin") to stop the coroutine and start it up later with StartCoroutine("Spin"):

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateCamera : MonoBehaviour
{
    public GameObject objectToSpin;
    public Vector3 spinAxis;
    public float timeToSpin = 5f;
    public float spinSpeed = 20f;
    public bool randomSpin = false;

    private void Start()
    {
        var rb = GetComponent<Rigidbody>();
        rb.angularVelocity = Random.insideUnitSphere;
        StartCoroutine("Spin");
    }

    private void Update()
    {
    }
}

IEnumerator Spin()
{
    float spinTimer;
    while (true)
    {
        if (randomSpin == true)
        {
            spinAxis = Random.onUnitSphere;
        }

        spinTimer = timeToSpin;
        while (spinTimer > 0f)
        {
            objectToSpin.transform.Rotate(spinAxis, Time.deltaTime * spinSpeed);
            spinTimer -= Time.deltaTime;
            yield return null;
        }
    }
}
</code>```

Body:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateCamera : MonoBehaviour
{
    public GameObject objectToSpin;
    public float spinX;
    public float spinY;
    public float spinZ;
    public bool randomSpin = false;

    private void Start()
    {
        var rb = GetComponent<Rigidbody>();
        rb.angularVelocity = Random.insideUnitSphere;
    }

    private void Update()
    {
        if (randomSpin == true)
        {
            objectToSpin.transform.Rotate(Random.Range(spinX, 360), Random.Range(spinY, 360), Random.Range(spinZ, 360));
        }
        else
        {
            objectToSpin.transform.Rotate(spinX, spinY, spinZ);
        }
    }
}

Now when changing the randomSpin flag to true it will spin random nonstop changing random angle on x y z each frame.

But I want it to spin random for 5 seconds after 5 seconds to change to random values the x y z and continue from last point and then after 5 seconds random angles and so on.

Body:
If you want a constant speed and just a random direction, You can randomly select an Axis to rotate around using Random.onUnitSphere and then rotate around it at a speed.

Here's a solution that uses a Coroutine. If you want to stop the Coroutine, you can use StopCoroutine("Spin") to stop the coroutine and start it up later with StartCoroutine("Spin"):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateCamera : MonoBehaviour
{
    public GameObject objectToSpin;
    public Vector3 spinAxis;
    public float timeToSpin = 5f;
    public float spinSpeed = 20f;
    public bool randomSpin = false;

    private void Start()
    {
        var rb = GetComponent<Rigidbody>();
        rb.angularVelocity = Random.insideUnitSphere;
        StartCoroutine("Spin");
    }

    private void Update()
    {
    }
}

IEnumerator Spin()
{
    float spinTimer;
    while (true)
    {
        if (randomSpin == true)
        {
            spinAxis = Random.onUnitSphere;
        }

        spinTimer = timeToSpin;
        while (spinTimer > 0f)
        {
            objectToSpin.transform.Rotate(spinAxis, Time.deltaTime * spinSpeed);
            spinTimer -= Time.deltaTime;
            yield return null;
        }
    }
}


问:
How to make a Vuetify rule async and await with a ajax call
I am using Vuetify form validation to check an input field, and I'm trying to figure out if it's possible to call a ajax get call and make it await so that I can use the result in a rule?

I've attempted it below, but it doesn't seem to work!

```<code>export default {
  data() {
    return {
      rules: {
        isLocationNew: value => {

          if (value == '' || value == null || value.length <= 1) {
            this.validLocation = false;
            return 'Invalid length.';
          }

          this.validLocation = true;

          var hasName = this.newLocationNameSearch(value);
          if (hasName) {
            return 'Location name already exists.';
          } else {
            return true;
          }
        }
      },

      // down in methods
      methods: {
        async newLocationNameSearch(text) {
          if (text == '' || text == null || text.length <= 1) {
            return false;
          }

          await axios.get('/api/Locations/HasLocationName', {
            params: {
              text: text,
              jobsiteId: this.jobsiteId
            }
          }).then(response => {
            return response.data;
          }).catch(function(error) {
            console.log(error)
          })

        }
      }
</code>```

答:
newLocationNameSearch Is an async function. Async functions return promises, so when you write

```<code>var hasName = this.newLocationNameSearch(value);
</code>```

hasName is set to a promise, which is always truthy.

You need something like:

```<code>    isLocationNew: async value => {

      if (value == '' || value == null || value.length <= 1) {
        this.validLocation = false;
        return 'Invalid length.';
      }

      this.validLocation = true;

      var hasName = await this.newLocationNameSearch(value);
      if (hasName) {
        return 'Location name already exists.';
      } else {
        return true;
      }
    }
</code>```

And remember that wherever isLocationNew is called, it will need to be awaited as well.

Furthermore, the newLocationNameSearch method does not actually return a value when awaited.

```<code>      await axios.get('/api/Locations/HasLocationName', {
        params: {
          text: text,
          jobsiteId: this.jobsiteId
        }
      }).then(response => {
        return response.data;
      }).catch(function(error) {
        console.log(error)
      })
</code>```

Has the return statement inside the callback for the .then() call. The newLocationNameSearch then doesn't return anything, meaning it returns undefined, which is falsy.

The good new is that async/await means we don't have to bother with then callbacks anymore.

We can instead write

```<code>try {
     var response = await axios.get('/api/Locations/HasLocationName', {
        params: {
          text: text,
          jobsiteId: this.jobsiteId
        }
      });

      return response.data;

} catch (error) {
    console.log(error)
}
</code>```

Body:
I am using Vuetify form validation to check an input field, and I'm trying to figure out if it's possible to call a ajax get call and make it await so that I can use the result in a rule?

I've attempted it below, but it doesn't seem to work!

export default {
  data() {
    return {
      rules: {
        isLocationNew: value => {

          if (value == '' || value == null || value.length <= 1) {
            this.validLocation = false;
            return 'Invalid length.';
          }

          this.validLocation = true;

          var hasName = this.newLocationNameSearch(value);
          if (hasName) {
            return 'Location name already exists.';
          } else {
            return true;
          }
        }
      },

      // down in methods
      methods: {
        async newLocationNameSearch(text) {
          if (text == '' || text == null || text.length <= 1) {
            return false;
          }

          await axios.get('/api/Locations/HasLocationName', {
            params: {
              text: text,
              jobsiteId: this.jobsiteId
            }
          }).then(response => {
            return response.data;
          }).catch(function(error) {
            console.log(error)
          })

        }
      }

Body:
newLocationNameSearch Is an async function. Async functions return promises, so when you write

var hasName = this.newLocationNameSearch(value);

hasName is set to a promise, which is always truthy.

You need something like:

    isLocationNew: async value => {

      if (value == '' || value == null || value.length <= 1) {
        this.validLocation = false;
        return 'Invalid length.';
      }

      this.validLocation = true;

      var hasName = await this.newLocationNameSearch(value);
      if (hasName) {
        return 'Location name already exists.';
      } else {
        return true;
      }
    }

And remember that wherever isLocationNew is called, it will need to be awaited as well.

Furthermore, the newLocationNameSearch method does not actually return a value when awaited.

      await axios.get('/api/Locations/HasLocationName', {
        params: {
          text: text,
          jobsiteId: this.jobsiteId
        }
      }).then(response => {
        return response.data;
      }).catch(function(error) {
        console.log(error)
      })

Has the return statement inside the callback for the .then() call. The newLocationNameSearch then doesn't return anything, meaning it returns undefined, which is falsy.

The good new is that async/await means we don't have to bother with then callbacks anymore.

We can instead write

try {
     var response = await axios.get('/api/Locations/HasLocationName', {
        params: {
          text: text,
          jobsiteId: this.jobsiteId
        }
      });

      return response.data;

} catch (error) {
    console.log(error)
}


问:
How to combine plot of two GPy models?
I have calculated two GP regression models and would like to have them plotted in the same figure.

Model 1

```<code>kernel = GPy.kern.RBF(input_dim=1, variance=.1, lengthscale=1.)
m1 = GPy.models.GPRegression(xa, ya,kernel)
m1.optimize_restarts(num_restarts = 10)
m1.optimize(messages=True)

from IPython.display import display
display(m1)

fig1 = m1.plot(plot_density=True)
m1.plot(plot_density=True)
GPy.plotting.show(fig2, filename='2')
</code>```

Model 2

```<code>m2 = GPy.models.GPRegression(xe, ye,kernel)
m2.optimize_restarts(num_restarts = 10)
m2.optimize(messages=True)

from IPython.display import display
display(m2)

fig2 = m2.plot(plot_density=True,)

GPy.plotting.show(fig2, filename='2')
</code>```

I want both plots in one figure, in either matplotlib or plotly i.e. GPy.plotting.show(fig, filename='filename').

Thanks

答:
Using matplotlib, you can define a subplot, and specify the subplot to be used using the same axes (specifically, param ax).

```<code>import matplotlib.plt as plt
fig, ax = plt.subplots()
m1.plot(plot_density=True, ax=ax)
m2.plot(plot_density=True, ax=ax)
</code>```

I tested this out with a test data set:

```<code># Random Test Data
import pods
data = pods.datasets.olympic_marathon_men()

# First X,Y Regression Model
kernel = GPy.kern.RBF(input_dim=1, variance=.1, lengthscale=1.)
m1 = GPy.models.GPRegression(data['X'], data['Y'], kernel)
m1.optimize_restarts(num_restarts = 10)
m1.optimize(messages=True)

# Second model; changed the X, Y slightly.
m2 = GPy.models.GPRegression(data['X'] + 5, data['Y'] + 3,kernel)
m2.optimize_restarts(num_restarts = 10)
m2.optimize(messages=True)
</code>```

Related:
What is the best way of combining two independent plots with matplotlib?

Title: How to combine plot of two GPy models?

Body:
I have calculated two GP regression models and would like to have them plotted in the same figure.

Model 1

kernel = GPy.kern.RBF(input_dim=1, variance=.1, lengthscale=1.)
m1 = GPy.models.GPRegression(xa, ya,kernel)
m1.optimize_restarts(num_restarts = 10)
m1.optimize(messages=True)

from IPython.display import display
display(m1)

fig1 = m1.plot(plot_density=True)
m1.plot(plot_density=True)
GPy.plotting.show(fig2, filename='2')

Model 2

m2 = GPy.models.GPRegression(xe, ye,kernel)
m2.optimize_restarts(num_restarts = 10)
m2.optimize(messages=True)

from IPython.display import display
display(m2)

fig2 = m2.plot(plot_density=True,)

GPy.plotting.show(fig2, filename='2')

I want both plots in one figure, in either matplotlib or plotly i.e. GPy.plotting.show(fig, filename='filename').

Thanks

Body:
Using matplotlib, you can define a subplot, and specify the subplot to be used using the same axes (specifically, param ax).

import matplotlib.plt as plt
fig, ax = plt.subplots()
m1.plot(plot_density=True, ax=ax)
m2.plot(plot_density=True, ax=ax)

I tested this out with a test data set:

# Random Test Data
import pods
data = pods.datasets.olympic_marathon_men()

# First X,Y Regression Model
kernel = GPy.kern.RBF(input_dim=1, variance=.1, lengthscale=1.)
m1 = GPy.models.GPRegression(data['X'], data['Y'], kernel)
m1.optimize_restarts(num_restarts = 10)
m1.optimize(messages=True)

# Second model; changed the X, Y slightly.
m2 = GPy.models.GPRegression(data['X'] + 5, data['Y'] + 3,kernel)
m2.optimize_restarts(num_restarts = 10)
m2.optimize(messages=True)

Related:
What is the best way of combining two independent plots with matplotlib?


问:
How do I return array data from a foreach loop in Angular
I'm looping through a nested object to get a some data. This is working, but I can't seem to return the data and use it elsewhere.

I've tried putting the loop in a promise and couldn't get anywhere either. What am I doing wrong?

```<code>data: any = {
    '1234': {
        url: 'https://example1.com/',
        path: 'uploads',
        link: 'https://example1.com/uploads',
    },
    '5678': {
        url: 'https://example2.com/',
        path: 'uploads',
        link: 'https://example2.com/uploads',
    }
}

onSubmit(formData) {

    this.formdata = formData;

    Object.keys(this.data).forEach(key => {
        if (key == this.formdata.pin) {
            const url = this.data[key].url;
            // have also tried this.url to no avail
        }
    });

    // says undefined
    console.log(url);

    // set up headers, etc...

    // I need to use here
    this.http.post(url, body, head)
    ...
}
</code>```

答:
Switching your forEach to a map can simplify this; map return values, whereas forEach does not.

Old:

```<code>Object.keys(this.data).forEach(key => {
    if (key == this.formdata.pin) {
        const url = this.data[key].url;
    }
});

// says undefined
console.log(url);
</code>```

New: (I've also added a === in here based on the comment below)

```<code>const urls = Object.keys(this.data).map(key => {
    if (key === this.formdata.pin) {
        return this.data[key].url;
        // have also tried this.url to no avail
    }
});

console.log(urls);
</code>```

map docs and forEach docs

Body:
I'm looping through a nested object to get a some data. This is working, but I can't seem to return the data and use it elsewhere.

I've tried putting the loop in a promise and couldn't get anywhere either. What am I doing wrong?

data: any = {
    '1234': {
        url: 'https://example1.com/',
        path: 'uploads',
        link: 'https://example1.com/uploads',
    },
    '5678': {
        url: 'https://example2.com/',
        path: 'uploads',
        link: 'https://example2.com/uploads',
    }
}

onSubmit(formData) {

    this.formdata = formData;

    Object.keys(this.data).forEach(key => {
        if (key == this.formdata.pin) {
            const url = this.data[key].url;
            // have also tried this.url to no avail
        }
    });

    // says undefined
    console.log(url);

    // set up headers, etc...

    // I need to use here
    this.http.post(url, body, head)
    ...
}

Body:
Switching your forEach to a map can simplify this; map return values, whereas forEach does not.

Old:

Object.keys(this.data).forEach(key => {
    if (key == this.formdata.pin) {
        const url = this.data[key].url;
    }
});

// says undefined
console.log(url);

New: (I've also added a === in here based on the comment below)

const urls = Object.keys(this.data).map(key => {
    if (key === this.formdata.pin) {
        return this.data[key].url;
        // have also tried this.url to no avail
    }
});

console.log(urls);

map docs and forEach docs


问:
Idiomatic Python implementation for finite sets, images, and preimages of finite functions?
Suppose I have a finite concrete function between finite sets.  Of course, Python has sets implemented natively.

But what is the best way to implement the idea of a finite function between sets, precisely?  A wrapped dictionary?  Also, how would one implement the calculations of images and preimages? [See below.]

For images I can use map, clearly.  For preimages I can loop over the domain set and filter.  Still, I'm wondering about the more pythonic idiomatic solution.

Wikipedia: Images (mathematics)

答:
```<code>def preimage(b: B, f: Dict[A, B]) -> Set[A]:
    ''' get the preimage of one item. '''
    return set(a for a in f.keys() if f[a]==b)
</code>```

This assumes TypeVar and other things from pep484

```<code>from typing import TypeVar, Dict, Set
A = TypeVar('A')
B = TypeVar('B')
</code>```

Without type annotation it looks like this

```<code>def preimage(b, f):
  ...
</code>```

or a subset of the codomain

```<code>from typing import Collection
from functools import reduce

def preimage_(bs: Collection[B], f: Dict[A, B]) -> Set[A]:
    ''' get the preimage of a collection of items '''
    return reduce(lambda a, b: a.union(b), [preimage(b, f) for b in bs])
</code>```

Body:
def preimage(b: B, f: Dict[A, B]) -> Set[A]:
    ''' get the preimage of one item. '''
    return set(a for a in f.keys() if f[a]==b)

This assumes TypeVar and other things from pep484

from typing import TypeVar, Dict, Set
A = TypeVar('A')
B = TypeVar('B')

Without type annotation it looks like this

def preimage(b, f):
  ...

or a subset of the codomain

from typing import Collection
from functools import reduce

def preimage_(bs: Collection[B], f: Dict[A, B]) -> Set[A]:
    ''' get the preimage of a collection of items '''
    return reduce(lambda a, b: a.union(b), [preimage(b, f) for b in bs])


问:
Bixby Capsule does not launch on phone
I have a capsule that I want to test on my Samsung S9+, and have enabled developer options, and created a submission.

However, when I attempt to launch on the phone, I get "Oh, there was a connection problem. Try again later"

How can I figure out what is going on?

答:
I got this email from the development team a few days ago. I guess we should just sit tight.

Hello Bixby Developers,

On the latest version of the Bixby client (2.1.17.10), if you are
  using private submissions for on-device testing, there is currently an
  issue that causes Bixby to fail with an error: "Oh there was a
  connection problem.  Please try again later"

Our engineering teams are working hard to release a hotfix as soon as
  possible. We will provide a final email update once this issue is
  resolved. In the meantime, we will provide ad-hoc updates here.

Thanks, The Bixby Team

Title: Bixby Capsule does not launch on phone


问:
How do I get this program to print out the contents of a list in a list?
I'm still a beginner at python, but I've been trying to get better at it lately. I'm trying to create a program that asks the user what day it is and what they have to do. It will then take this and place it in a list. I'm trying to get the program to print out the list that has the new assignment in it, but it's not working. (The list that has the assignment is in another list.)

I tried placing it all in a function and using a return stmt, but it says that "the object is not callable". I also tried normally printing it out with a print stmt, but it doesn't work.

```<code>#List of days
doa = ["M","T","W","TH","F","S","SU"]

#Lists for every day
my_list = []
for i in range(7):
    my_list.append([i])

#Ask user what today is
day = input("What is the day today?")

#Ask user assignment
ast = input("What do you have to do my sir?")

#Add to list
if day == doa[i]:
    my_list[i].append(ast)

#Print that days list to check
print(my_list(day))
</code>```

I know what I'm doing is wrong. I'm assuming the way I'm doing it prints out the index for the list (that's in another list)...,but I couldn't think of any other way.

答:
I assume the user inputs TH for the day, so you can use list.index to get the index for the day and use that to append and print from.

```<code>doa = ["M","T","W","TH","F","S","SU"]

my_list = []
for i in range(7):
    my_list.append([i])

day = input("What is the day today?")
day_index = doa.index(day)

ast = input("What do you have to do my sir?")

my_list[day_index].append(ast)

print(my_list[day_index])
</code>```

Body:
I'm still a beginner at python, but I've been trying to get better at it lately. I'm trying to create a program that asks the user what day it is and what they have to do. It will then take this and place it in a list. I'm trying to get the program to print out the list that has the new assignment in it, but it's not working. (The list that has the assignment is in another list.)

I tried placing it all in a function and using a return stmt, but it says that "the object is not callable". I also tried normally printing it out with a print stmt, but it doesn't work.

#List of days
doa = ["M","T","W","TH","F","S","SU"]

#Lists for every day
my_list = []
for i in range(7):
    my_list.append([i])

#Ask user what today is
day = input("What is the day today?")

#Ask user assignment
ast = input("What do you have to do my sir?")

#Add to list
if day == doa[i]:
    my_list[i].append(ast)

#Print that days list to check
print(my_list(day))

I know what I'm doing is wrong. I'm assuming the way I'm doing it prints out the index for the list (that's in another list)...,but I couldn't think of any other way.

Body:
I assume the user inputs TH for the day, so you can use list.index to get the index for the day and use that to append and print from.

doa = ["M","T","W","TH","F","S","SU"]

my_list = []
for i in range(7):
    my_list.append([i])

day = input("What is the day today?")
day_index = doa.index(day)

ast = input("What do you have to do my sir?")

my_list[day_index].append(ast)

print(my_list[day_index])


问:
What UNIX commands support coloured output?
I enjoy using UNIX/bash commands that support coloured output.  Consequently, I have a few aliases defined which automatically enable coloured output of the commands that I know support this option.  However, I'm sure there are hundreds of commands out there that support coloured output - I'd like to know what they are.

The ones in my ~/.bash_aliases file are:

```<code>ls --color=auto
grep --color
phpunit --ansi
</code>```

What else is there?  Is there a list somewhere of all commands that support coloured output?  Or better still, some command for grepping my local man pages and plucking out the appropriate command names.

答:
Why don't you try:

```<code>man -K color
</code>```

That should search for the word color in all your man pages (content, not just headings).

It asks, for each man page, whether you want to open and view the page:

```<code>$ man -K color
/usr/share/man/mann/Widget.n.gz? [ynq] y
/usr/share/man/mann/usual.n.gz? [ynq] y
/usr/share/man/mann/Toplevel.n.gz? [ynq] n
/usr/share/man/mann/itk.n.gz? [ynq] n
/usr/share/man/mann/Archetype.n.gz? [ynq] n
/usr/share/man/man8/squid.8.gz? [ynq] n
/usr/share/man/man7/Xprint.7.gz? [ynq]
/usr/share/man/man7/X.7.gz? [ynq]
/usr/share/man/man7/urxvt.7.gz? [ynq]
/usr/share/man/man7/term.7.gz? [ynq] q

$
</code>```

Inside each individual man page, you can use your normal search method (e.g., /color<ENTER>) for finding the text. When done with a man page, just exit and it will continue searching.

OwnerDisplayName: DavidWinterbottom

ContentLicense: CC BY-SA 2.5

Body:
I enjoy using UNIX/bash commands that support coloured output.  Consequently, I have a few aliases defined which automatically enable coloured output of the commands that I know support this option.  However, I'm sure there are hundreds of commands out there that support coloured output - I'd like to know what they are.

The ones in my ~/.bash_aliases file are:

ls --color=auto
grep --color
phpunit --ansi

What else is there?  Is there a list somewhere of all commands that support coloured output?  Or better still, some command for grepping my local man pages and plucking out the appropriate command names.

LastEditorDisplayName: Eddie

Body:
Why don't you try:

man -K color

That should search for the word color in all your man pages (content, not just headings).

It asks, for each man page, whether you want to open and view the page:

$ man -K color
/usr/share/man/mann/Widget.n.gz? [ynq] y
/usr/share/man/mann/usual.n.gz? [ynq] y
/usr/share/man/mann/Toplevel.n.gz? [ynq] n
/usr/share/man/mann/itk.n.gz? [ynq] n
/usr/share/man/mann/Archetype.n.gz? [ynq] n
/usr/share/man/man8/squid.8.gz? [ynq] n
/usr/share/man/man7/Xprint.7.gz? [ynq]
/usr/share/man/man7/X.7.gz? [ynq]
/usr/share/man/man7/urxvt.7.gz? [ynq]
/usr/share/man/man7/term.7.gz? [ynq] q

$

Inside each individual man page, you can use your normal search method (e.g., /color<ENTER>) for finding the text. When done with a man page, just exit and it will continue searching.

OwnerDisplayName: Pax

LastEditorDisplayName: Pax


答:
This is a reported issue in the latest version of Bixby.  It is being addressed.

https://support.bixbydevelopers.com/hc/en-us/articles/360023521654-Bixby-client-2-1-17-10-breaks-on-device-testing

issues should be resolved as of 5/31/2019

Title: Bixby Capsule does not launch on phone

Body:
I have a capsule that I want to test on my Samsung S9+, and have enabled developer options, and created a submission.

However, when I attempt to launch on the phone, I get "Oh, there was a connection problem. Try again later"

How can I figure out what is going on?


问:
How to open Fragment on click of push notification

My Firebasemessagingservice class code for passing intent:

```<code>private void showNotification(String message){
    Intent intent=new Intent(this, DrawerActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("data", message);
    PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder=new NotificationCompat.Builder(this)
            .setAutoCancel(true)
            .setContentTitle("Registry")
            .setContentText(message)
            .setSmallIcon(R.drawable.com_facebook_button_send_icon_blue)
            .setContentIntent(pendingIntent);
    NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.notify(0,builder.build());
}
</code>```

My Fragment BaseActivity code in onCreate() method:

```<code>Intent notifyIntent = getIntent();
    Bundle extras = notifyIntent.getExtras();
    if (extras != null) {

       replacefragment code;

    }
</code>```

It's not working..

答:
First, in the code were you make the notification declarate the intent at the next way:

```<code>Intent intent=new Intent(getApplicationContext(), MyClass.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("menuFragment", "MyFragment");
PendingIntent pendingIntent=PendingIntent.getActivity(MyClass.this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
</code>```

Assign the intent to mBuilder

```<code>mBuilder.setContentIntent(pendingIntent);
</code>```

Then go to the activity main and add this code in the onCreate method:

```<code>protected void onCreate(Bundle savedInstanceState) {
    onNewIntent(getIntent());
}
</code>```

Finaly add this method in MainActivity:

```<code>@Override
    protected void onNewIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        if(extras != null){
            if(extras.containsKey("menuFragment"))
            {
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.detail_fragment_container, MyFragment.newInstance() ).commit();
            }
        }
    }
</code>```

Body:
My Firebasemessagingservice class code for passing intent:

private void showNotification(String message){
    Intent intent=new Intent(this, DrawerActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("data", message);
    PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder=new NotificationCompat.Builder(this)
            .setAutoCancel(true)
            .setContentTitle("Registry")
            .setContentText(message)
            .setSmallIcon(R.drawable.com_facebook_button_send_icon_blue)
            .setContentIntent(pendingIntent);
    NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.notify(0,builder.build());
}

My Fragment BaseActivity code in onCreate() method:

Intent notifyIntent = getIntent();
    Bundle extras = notifyIntent.getExtras();
    if (extras != null) {

       replacefragment code;

    }

It's not working..

Body:
First, in the code were you make the notification declarate the intent at the next way:

Intent intent=new Intent(getApplicationContext(), MyClass.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("menuFragment", "MyFragment");
PendingIntent pendingIntent=PendingIntent.getActivity(MyClass.this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);

Assign the intent to mBuilder

mBuilder.setContentIntent(pendingIntent);

Then go to the activity main and add this code in the onCreate method:

protected void onCreate(Bundle savedInstanceState) {
    onNewIntent(getIntent());
}

Finaly add this method in MainActivity:

@Override
    protected void onNewIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        if(extras != null){
            if(extras.containsKey("menuFragment"))
            {
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.detail_fragment_container, MyFragment.newInstance() ).commit();
            }
        }
    }


问:
Examples of non-separate compilation?
From section 1.1 of "The C Book":

At the coarsest level, an obvious feature is the multi-file structure
  of a program. The language permits separate compilation, where the
  parts of a complete program can be kept in one or more source files
  and compiled independently of each other. The idea is that the
  compilation process will produce files which can then be linked
  together using whatever link editor or loader that your system
  provides. The block structure of the Algol-like languages makes this
  harder by insisting that the whole program comes in one chunk,
  although there are usually ways of getting around it.

Can anyone provide some basic examples / overview of programming in this nature ?

答:
Example Algol program, which does nothing useful but is here to illustrate the point:

```<code>   begin
   int x; x:=3;

   procedure p;
       begin
       integer y; y:=4;

       procedure q(n);
          value n; integer n;
          if n > 0
          then q(n-1)
          else begin
              integer z; z:=x+y;
              print(z)
              end;

       q(1)
       end;

    p; comment a parameterless procedure call;
    end;
</code>```

The basic problem here is nested scopes. The procedure q depends on the surrounding blocks that define integers x and y. The procedure p likewise depends (by virtue of containing q) on the block that defines x.

You'll see, then, that each part of this stupid example program is inseparable from the surrounding text.  This is the natural mode of expression to Algolers; to nest procedures in a way that makes sense for the program being written. In general this makes separate compilation quite complicated.  This differs from C-like languages which have no nested procedures (functions, whatever) because the only non-local identifiers they can refer to are file scope or global scope (if I have those terms correct).

Here, the variables x and y are local to some procedure and are therefore on the stack. Just to make it more complicated, q is recursive, which makes the "distance down the stack" from its innermost invocation to the locations of x and y a variable quantity, so it's not just a matter of compiling a fixed value off some stack-frame pointer.

Nevertheless, there were some systems that allowed separate compilation. As far as I recall, there were restrictions, such as the unit of compilation (a file, if you like) having to contain only procedures 'at the top level'. They might also have needed some extended syntax (like 'external procedure foo') to tell the compiler that something being referenced was not expected to be defined in the current file.

Title: Examples of non-separate compilation?

Body:
Example Algol program, which does nothing useful but is here to illustrate the point:

   begin
   int x; x:=3;

   procedure p;
       begin
       integer y; y:=4;

       procedure q(n);
          value n; integer n;
          if n > 0
          then q(n-1)
          else begin
              integer z; z:=x+y;
              print(z)
              end;

       q(1)
       end;

    p; comment a parameterless procedure call;
    end;

The basic problem here is nested scopes. The procedure q depends on the surrounding blocks that define integers x and y. The procedure p likewise depends (by virtue of containing q) on the block that defines x.

You'll see, then, that each part of this stupid example program is inseparable from the surrounding text.  This is the natural mode of expression to Algolers; to nest procedures in a way that makes sense for the program being written. In general this makes separate compilation quite complicated.  This differs from C-like languages which have no nested procedures (functions, whatever) because the only non-local identifiers they can refer to are file scope or global scope (if I have those terms correct).

Here, the variables x and y are local to some procedure and are therefore on the stack. Just to make it more complicated, q is recursive, which makes the "distance down the stack" from its innermost invocation to the locations of x and y a variable quantity, so it's not just a matter of compiling a fixed value off some stack-frame pointer.

Nevertheless, there were some systems that allowed separate compilation. As far as I recall, there were restrictions, such as the unit of compilation (a file, if you like) having to contain only procedures 'at the top level'. They might also have needed some extended syntax (like 'external procedure foo') to tell the compiler that something being referenced was not expected to be defined in the current file.


问:
pyarrow hdfs reads more data than requested
I am using pyarrow's HdfsFilesystem interface. When I call a read on n bytes, I often get 0%-300% more data sent over the network. My suspicion is that pyarrow is reading ahead.

The pyarrow parquet reader doesn't have this behavior, and I am looking for a way to turn off read ahead for the general HDFS interface.

I am running on ubuntu 14.04. This issue is present in pyarrow 0.10 - 0.13 (newest released version). I am on python 2.7

I have been using wireshark to track the packets passed on the network.

I suspect it is read ahead since the time for the 1st read is much greater than the time for 2nd read.

The regular pyarrow reader

```<code>import pyarrow as pa
fs = pa.hdfs.connect(hostname)

file_path = 'dataset/train/piece0000'
f = fs.open(file_path)
f.seek(0)
n_bytes = 3000000
f.read(n_bytes)
</code>```

Parquet code without the same issue

```<code>parquet_file = 'dataset/train/parquet/part-22e3'
pf = fs.open(parquet_path)
pqf = pa.parquet.ParquetFile(pf)
data = pqf.read_row_group(0, columns=['col_name'])
</code>```

答:
Discussed in the JIRA ticket: https://issues.apache.org/jira/browse/ARROW-5432

A read_at function is being added to pyarrow api that will allow you to read a file at an offset for a certain length with no reading ahead.

Body:
I am using pyarrow's HdfsFilesystem interface. When I call a read on n bytes, I often get 0%-300% more data sent over the network. My suspicion is that pyarrow is reading ahead.

The pyarrow parquet reader doesn't have this behavior, and I am looking for a way to turn off read ahead for the general HDFS interface.

I am running on ubuntu 14.04. This issue is present in pyarrow 0.10 - 0.13 (newest released version). I am on python 2.7

I have been using wireshark to track the packets passed on the network.

I suspect it is read ahead since the time for the 1st read is much greater than the time for 2nd read.

The regular pyarrow reader

import pyarrow as pa
fs = pa.hdfs.connect(hostname)

file_path = 'dataset/train/piece0000'
f = fs.open(file_path)
f.seek(0)
n_bytes = 3000000
f.read(n_bytes)

Parquet code without the same issue

parquet_file = 'dataset/train/parquet/part-22e3'
pf = fs.open(parquet_path)
pqf = pa.parquet.ParquetFile(pf)
data = pqf.read_row_group(0, columns=['col_name'])


问:
Remove Bixby public submission
I accidentally created a public submission while developing my capsule.

I do not see a remove or delete feature within the submission form of the Bixby IDE.

How can I delete/remove it?

答: You cannot remove public submissions (in fact, you can't remove a private submission either). It is fine to leave the wrong submission there - nothing is done with it unless you submit it for review. Just use a different version number for your next submission. </p>

Title: Remove Bixby public submission


问:
ansible facts with condition
I am trying to set the facts based input variable. </p>

```<code>if input protocol = to TCP/UDP
  then service name will be TCP-443/UDP-443
else service name will be ALL
</code>```

<p>I am able to achieve the  my requirement with the below method but I would like to simplify the same, can someone help me here  </p>

```<code>  - name: setting fact for service name
    set_fact:
      servicename: TCP-{{port}}
    when: >
          protocol == "TCP" or protocol == "tcp"

  - name: setting fact for service name
    set_fact:
      servicename: UDP-{{ port }}
    when: >
          protocol == "UDP" or protocol == "udp"

  - name: setting fact for service name
    set_fact:
      servicename: "ALL"
    when: >
          protocol == "all" or protocol == "ALL"

  - name: setting fact for service name
    set_fact:
      protocolname: "tcp_udp_sctp"
    when: >
          protocol == "TCP" or protocol == "tcp"

  - name: setting fact for service name
    set_fact:
      protocolname: "tcp_udp_sctp"
    when: >
          protocol == "UDP" or protocol == "udp"

  - name: setting fact for service name
    set_fact:
      protocolname: "ALL"
    when: >
          protocol == "all" or protocol == "ALL"
</code>```

答:
The equivalent is as follows, I think</p>

```<code>  vars:
    port: 443
  tasks:
    - name: setting fact for service name
      set_fact:
        servicename: "{{ protocol|upper }}-{{ port }}"
        protocolname: "tcp_udp_sctp"
      when: protocol|upper == "TCP" or
            protocol|upper == "UDP"

    - name: setting fact for service name
      set_fact:
        servicename: "ALL"
        protocolname: "ALL"
      when: protocol|upper == "ALL"
</code>```

Title: ansible facts with condition

Body:
I am trying to set the facts based input variable.

if input protocol = to TCP/UDP
  then service name will be TCP-443/UDP-443
else service name will be ALL

I am able to achieve the  my requirement with the below method but I would like to simplify the same, can someone help me here

  - name: setting fact for service name
    set_fact:
      servicename: TCP-{{port}}
    when: >
          protocol == "TCP" or protocol == "tcp"

  - name: setting fact for service name
    set_fact:
      servicename: UDP-{{ port }}
    when: >
          protocol == "UDP" or protocol == "udp"

  - name: setting fact for service name
    set_fact:
      servicename: "ALL"
    when: >
          protocol == "all" or protocol == "ALL"

  - name: setting fact for service name
    set_fact:
      protocolname: "tcp_udp_sctp"
    when: >
          protocol == "TCP" or protocol == "tcp"

  - name: setting fact for service name
    set_fact:
      protocolname: "tcp_udp_sctp"
    when: >
          protocol == "UDP" or protocol == "udp"

  - name: setting fact for service name
    set_fact:
      protocolname: "ALL"
    when: >
          protocol == "all" or protocol == "ALL"

Body:
The equivalent is as follows, I think

  vars:
    port: 443
  tasks:
    - name: setting fact for service name
      set_fact:
        servicename: "{{ protocol|upper }}-{{ port }}"
        protocolname: "tcp_udp_sctp"
      when: protocol|upper == "TCP" or
            protocol|upper == "UDP"

    - name: setting fact for service name
      set_fact:
        servicename: "ALL"
        protocolname: "ALL"
      when: protocol|upper == "ALL"


问:
Need assistance with a for loop in Tic Tac Toe game
My program is exiting without iterating. It automatically goes to "YOU WON". Without the champion function the program runs fine. Its probably some obvious error Im missing. If anyone could please I would greatly appreciate it.</p>

```<code>#include <iostream>
#include <string>

#define GRID_SIZE 3

class TicTacToe {
private:
    char map[GRID_SIZE][GRID_SIZE];

public:

    void champion() {
        const char *possiblities[8]{
                "123"
                "456"
                "789"
                "147"
                "159"
                "258"
                "369"
                "753"
        };

        for (int i = 0; i < 8; i++) {
            bool winner = true;
            char previous_pos = '0';
            const char *possible_moves = possiblities[i];

            for (int index = 0; index < GRID_SIZE; index++) {
                char character = possible_moves[i];
                int entered_num = character - '0';
                int grid_space = entered_num - 1;
                int row = index / GRID_SIZE;
                int col = index % GRID_SIZE;

                char grid_coordinate = map[row][col];

                if (previous_pos == '0') {
                    previous_pos = grid_coordinate;
                } else if
                        (previous_pos == grid_coordinate) {
                    continue;
                } else {
                    winner = false;
                    break;
                }
            }
            if (winner = true) {
                std::cout << "YOU WON" << std::endl;
                exit(0);
                break;
            }

        }

    }

    void playgame() {
        std::string input;

        while (true) {
            std::cout << "Go player one" << std::endl;
            getline(std::cin, input);
            if (input != " ") {
                char entered = input.c_str()[0];

                if (entered >= '1' && entered <= '9') {
                    int entered_num = entered - '0';
                    int index = entered_num - 1;
                    int row = index / 3;
                    int col = index % 3;
                    char grid_position = map[row][col];

                    if (grid_position == 'X' || grid_position == 'O') {
                        std::cout << "Space taken. Try again" << std::endl;
                    } else {
                        map[row][col] = (char) 'X';
                        break;
                    }

                } else {
                    std::cout << "Only numbers 1 - 9" << std::endl;
                }
            } else {
                std::cout << "Have to enter something, try again" << std::endl;
            }

        }
    }

    void generateGrid() {
        int number = 1;

        for (int x = 0; x < GRID_SIZE; x++) {
            for (int y = 0; y < GRID_SIZE; y++) {
                map[x][y] = std::to_string(number).c_str()[0];
                number += 1;
            }
        }
    }

    void tictacToeMap() {

        std::cout << std::endl;

        for (int x = 0; x < GRID_SIZE; x++) {
            for (int y = 0; y < GRID_SIZE; y++) {
                std::printf(" %c ", map[x][y]);
            }
            std::cout << std::endl;
        }

    }

    TicTacToe() {
        generateGrid();
        while (true) {
            tictacToeMap();
            playgame();
            champion();

        }
    }
};

int main() {

    TicTacToe tic;
    tic.playgame();

    return 0;

}
</code>```

答:
The problem is here:

if (winner = true) {
                std::cout << "YOU WON" << std::endl;
                exit(0);
                break;
            }
```

<p>You probably meant:</p>

<pre class="lang-cpp prettyprint-override"><code>if (winner == true) {
                std::cout << "YOU WON" << std::endl;
                exit(0);
                break;
            }
</code>```

Body:
My program is exiting without iterating. It automatically goes to "YOU WON". Without the champion function the program runs fine. Its probably some obvious error Im missing. If anyone could please I would greatly appreciate it.

#include <iostream>
#include <string>

#define GRID_SIZE 3

class TicTacToe {
private:
    char map[GRID_SIZE][GRID_SIZE];

public:

    void champion() {
        const char *possiblities[8]{
                "123"
                "456"
                "789"
                "147"
                "159"
                "258"
                "369"
                "753"
        };

        for (int i = 0; i < 8; i++) {
            bool winner = true;
            char previous_pos = '0';
            const char *possible_moves = possiblities[i];

            for (int index = 0; index < GRID_SIZE; index++) {
                char character = possible_moves[i];
                int entered_num = character - '0';
                int grid_space = entered_num - 1;
                int row = index / GRID_SIZE;
                int col = index % GRID_SIZE;

                char grid_coordinate = map[row][col];

                if (previous_pos == '0') {
                    previous_pos = grid_coordinate;
                } else if
                        (previous_pos == grid_coordinate) {
                    continue;
                } else {
                    winner = false;
                    break;
                }
            }
            if (winner = true) {
                std::cout << "YOU WON" << std::endl;
                exit(0);
                break;
            }

        }

    }

    void playgame() {
        std::string input;

        while (true) {
            std::cout << "Go player one" << std::endl;
            getline(std::cin, input);
            if (input != " ") {
                char entered = input.c_str()[0];

                if (entered >= '1' && entered <= '9') {
                    int entered_num = entered - '0';
                    int index = entered_num - 1;
                    int row = index / 3;
                    int col = index % 3;
                    char grid_position = map[row][col];

                    if (grid_position == 'X' || grid_position == 'O') {
                        std::cout << "Space taken. Try again" << std::endl;
                    } else {
                        map[row][col] = (char) 'X';
                        break;
                    }

                } else {
                    std::cout << "Only numbers 1 - 9" << std::endl;
                }
            } else {
                std::cout << "Have to enter something, try again" << std::endl;
            }

        }
    }

    void generateGrid() {
        int number = 1;

        for (int x = 0; x < GRID_SIZE; x++) {
            for (int y = 0; y < GRID_SIZE; y++) {
                map[x][y] = std::to_string(number).c_str()[0];
                number += 1;
            }
        }
    }

    void tictacToeMap() {

        std::cout << std::endl;

        for (int x = 0; x < GRID_SIZE; x++) {
            for (int y = 0; y < GRID_SIZE; y++) {
                std::printf(" %c ", map[x][y]);
            }
            std::cout << std::endl;
        }

    }

    TicTacToe() {
        generateGrid();
        while (true) {
            tictacToeMap();
            playgame();
            champion();

        }
    }
};

int main() {

    TicTacToe tic;
    tic.playgame();

    return 0;

}

Body:
The problem is here:

if (winner = true) {
                std::cout << "YOU WON" << std::endl;
                exit(0);
                break;
            }

You probably meant:

if (winner == true) {
                std::cout << "YOU WON" << std::endl;
                exit(0);
                break;
            }


问:
Constructing a simple interpreter
I’m starting a project where I need to implement a light-weight interpreter.
The interpreter is used to execute simple scientific algorithms.
The programming language that this interpreter will use should be simple, since it is targeting non- software developers (for example, mathematicians.)

The interpreter should support basic programming languages features:

Real numbers, variables, multi-dimensional arrays

Binary (+, -, *, /, %) and Boolean (==, !=, <, >, <=, >=) operations

Loops (for, while), Conditional expressions (if)

Functions

MathWorks MatLab is a good example of where I’m heading, just much simpler.
The interpreter will be used as an environment to demonstrate algorithms; simple algorithms such as finding the average of a dataset/array, or slightly more complicated algorithms such as Gaussian elimination or RSA.

Best/Most practical resource I found on the subject is Ron Ayoub’s entry on Code Project (Parsing Algebraic Expressions Using the Interpreter Pattern) - a perfect example of a minified version of my problem.

The Purple Dragon Book seems to be too much, anything more practical?

The interpreter will be implemented as a .NET library, using C#. However, resources for any platform are welcome, since the design-architecture part of this problem is the most challenging.

Any practical resources?

(please avoid “this is not trivial” or “why re-invent the wheel” responses)

答: The Silk library has just been published to GitHub. It seems to do most of what you are asking. It is very easy to use. Just register the functions you want to make available to the script, compile the script to bytecode and execute it.</p>

OwnerDisplayName: ANaimi

Title: Constructing a simple interpreter


问:
or where clause - Laravel eloquent
I have this query:

```<code>if($keyword){
    array_push($where, ['name_en', 'LIKE', '%'.$keyword.'%']);
}
</code>```

The problem is that I have and name_fr column and I need to use OR clause - array_push($where, ['name_fr', 'LIKE', '%'.$keyword.'%']).

I can't use ->orWhere, because I have many dynamic search fields - they may exists or not.

For the example:

```<code>if($fromPrice){
    array_push($where, ['price', '>=', $fromPrice]);
}
if($toPrice){
    array_push($where, ['price', '<=', $toPrice]);
}
</code>```

And the query is:

```<code>$cars= Property::with(array(
    'photos'=>function($query){
            $query->select(['car_id', 'name']);
        }
))->where($where)->paginate(10);
</code>```

I need to select WHERE name_en LIKE %val% OR name_fr LIKE %val% with another queries.

Is there a way to use somehow where, 'OR' and LIKE in the above way including another values from $where array ?

答:
to achieve that a suggest you to divide your query as below and don't put your keyword condition within $where array:

```<code>$query = Property::with(array(
    'photos'=>function($query){
            $query->select(['car_id', 'name']);
        }
))->where($where);

if($keyword){

     $query = $query->where(function ($query) use ($keyword) {
                  $query->where('name_fr', 'like', $keyword)
                  ->orWhere('name_en', 'like', $keyword);
     });
}

$cars = $query->paginate(10);
</code>```

Title: or where clause - Laravel eloquent

Body:
I have this query:

if($keyword){
    array_push($where, ['name_en', 'LIKE', '%'.$keyword.'%']);
}

The problem is that I have and name_fr column and I need to use OR clause - array_push($where, ['name_fr', 'LIKE', '%'.$keyword.'%']).

I can't use ->orWhere, because I have many dynamic search fields - they may exists or not.

For the example:

if($fromPrice){
    array_push($where, ['price', '>=', $fromPrice]);
}
if($toPrice){
    array_push($where, ['price', '<=', $toPrice]);
}

And the query is:

$cars= Property::with(array(
    'photos'=>function($query){
            $query->select(['car_id', 'name']);
        }
))->where($where)->paginate(10);

I need to select WHERE name_en LIKE %val% OR name_fr LIKE %val% with another queries.

Is there a way to use somehow where, 'OR' and LIKE in the above way including another values from $where array ?

Body:
to achieve that a suggest you to divide your query as below and don't put your keyword condition within $where array:

$query = Property::with(array(
    'photos'=>function($query){
            $query->select(['car_id', 'name']);
        }
))->where($where);

if($keyword){

     $query = $query->where(function ($query) use ($keyword) {
                  $query->where('name_fr', 'like', $keyword)
                  ->orWhere('name_en', 'like', $keyword);
     });
}

$cars = $query->paginate(10);


问:
how sharing & annotation/marking on shared holograms works on new Mixed Reality ToolKit (MRTK) for unity
I'm looking for solution to get rid of old version of MRTK and start using new version of MRTK for Unity sharing applications.

but i am no sure still the new version is supporting sharing as well as annotation or marking on shared holographic objects.

i had tried to find out the solution everywhere on Google and youtube to draw circle or highlight the part of shared object.
still i did not able to get the solution.

答:
yes it is possible to support sharing as well as annotation on holographic objects using MRTK, however a code sample is not yet available for this. Similar to what you would do in old MRTK, you just need deploy a sharing-enabled Unity application to both devices, and have the two devices synchronize their state of the network. An example of this using MRTK v2 is available on this YouTube video at 37:37.

The example code to match this behavior is coming soon, I will update this answer once it is posted.


问:
Redirection to a locale page with a Firefox extension
I'd like to have a page redirecting to another using Javascript. I've tried with document.location.href but it doesn't work with local pages (stored in my hard drive).
 Does someone know something that would do the trick ?

thanks,

Bruno

答:
Doesn't it? I've tried the following and it works fine:

```<code><html>
    <head>
        <meta http-equiv="content-type" content="text/html;charset=utf-8">
    </head>
    <body>
        <input type="text" value="" id="test"/>
    </body>

    <script type="text/javascript">
        document.location.href = "file:///C:/dev/PICCS/vb/binaries/";
   </script>
</html>
</code>```

Tested in IE8 and Chrome

Body:
Doesn't it? I've tried the following and it works fine:

<html>
    <head>
        <meta http-equiv="content-type" content="text/html;charset=utf-8">
    </head>
    <body>
        <input type="text" value="" id="test"/>
    </body>

    <script type="text/javascript">
        document.location.href = "file:///C:/dev/PICCS/vb/binaries/";
   </script>
</html>

Tested in IE8 and Chrome


问:
Object Cell/Range doesn't support .Font property in VBA
I'm trying to colour code cells to give the user a warning about which cell's data is incorrect before running a calculation. Currently throwing a:

run time error 438 object doesn't support property

when trying to run through all the data.

Basically creating a worksheet to allow the user to input some data on a consist, then based off some back end data/restrictions, spit out an answer of what they can/can't do. I've got a level of error checking already in the initial code as the user inputs data (basically to try and encourage them to make sure the data they're inputting is valid before they try and run the calculation) and this works fine using a Worksheet_Change subroutine which can loop through all cells one at a time (within the target range) no worries.

If I try replicate this (using a named range instead of the Target cells from the change function) it seems to do one of two things: it will try and send through a range of cells, rather than individual cells and fail when it tries to match data from the "cells" rather than the single cell it should be trying to match, OR it will throw the 438 error when it tries to colour it in.

Private Sub CommandButton1_Click()
    Dim ErrorWagonPack As Boolean, ErrorCellsNotEmpty As Boolean, WagonPack As Integer, cel As Range, Target As Range

    ErrorWagonPack = False
    ErrorCellsNotEmpty = False
    Set Target = Application.Range("ConsistInput")

    For Each cel In Target 'issue is here somewhere I think. It's related to how the cel is created and as such what properties it can have
        Application.EnableEvents = False
        WagonPack = 0
        If Len(cel.Value) > 0 Then
            WagonPack = Application.Index(Application.Range("WagonData"), Application.Match(cel.Value, Application.Range("WagonData").Columns(1), 0), 4)
            If cel.Offset(0, 1).Value Mod WagonPack > 0 Then
                ErrorWagonPack = True
                cel.Font.ColourIndex = RGB(156, 0, 6) '438 error here
                cel.Interior.ColourIndex = RGB(255, 199, 206) '438 error here too
            End If
        End If
    Next cel

If ErrorWagonPack = True Or ErrorCellsNotEmpty = True Then
    Exit Sub
End If

'calculate stuff
Application.EnableEvents = True
End Sub
```

Ideally I'd like to get to a point where I run the code, colour the cells causing issues/with incorrect data, then if doesn't throw any error variables, run the calculation but the 438 error seems to be the sticking point. I'm almost willing to bet it's something simple I'm just missing but can't figure it out. Probably doesn't help I'm still pretty green with VBA.

答:
.ColorIndex is incorrect. Use .Color

```<code>Private Sub CommandButton1_Click()
    Dim ErrorWagonPack As Boolean, ErrorCellsNotEmpty As Boolean, WagonPack As Integer, cel As Range, Target As Range

    ErrorWagonPack = False
    ErrorCellsNotEmpty = False
    Set Target = Application.Range("ConsistInput")

    For Each cel In Target 'issue is here somewhere I think. It's related to how the cel is created and as such what properties it can have
        Application.EnableEvents = False
        WagonPack = 0
        If Len(cel.Value) > 0 Then
            WagonPack = Application.Index(Application.Range("WagonData"), Application.Match(cel.Value, Application.Range("WagonData").Columns(1), 0), 4)
            If cel.Offset(0, 1).Value Mod WagonPack > 0 Then
                ErrorWagonPack = True
                cel.Font.Color = RGB(156, 0, 6) '438 error here
                cel.Interior.Color = RGB(255, 199, 206) '438 error here too
            End If
        End If
    Next cel

If ErrorWagonPack = True Or ErrorCellsNotEmpty = True Then
    Exit Sub
End If

'calculate stuff
Application.EnableEvents = True
End Sub
</code>```

Body:
I'm trying to colour code cells to give the user a warning about which cell's data is incorrect before running a calculation. Currently throwing a:

run time error 438 object doesn't support property

when trying to run through all the data.

Basically creating a worksheet to allow the user to input some data on a consist, then based off some back end data/restrictions, spit out an answer of what they can/can't do. I've got a level of error checking already in the initial code as the user inputs data (basically to try and encourage them to make sure the data they're inputting is valid before they try and run the calculation) and this works fine using a Worksheet_Change subroutine which can loop through all cells one at a time (within the target range) no worries.

If I try replicate this (using a named range instead of the Target cells from the change function) it seems to do one of two things: it will try and send through a range of cells, rather than individual cells and fail when it tries to match data from the "cells" rather than the single cell it should be trying to match, OR it will throw the 438 error when it tries to colour it in.

Private Sub CommandButton1_Click()
    Dim ErrorWagonPack As Boolean, ErrorCellsNotEmpty As Boolean, WagonPack As Integer, cel As Range, Target As Range

    ErrorWagonPack = False
    ErrorCellsNotEmpty = False
    Set Target = Application.Range("ConsistInput")

    For Each cel In Target 'issue is here somewhere I think. It's related to how the cel is created and as such what properties it can have
        Application.EnableEvents = False
        WagonPack = 0
        If Len(cel.Value) > 0 Then
            WagonPack = Application.Index(Application.Range("WagonData"), Application.Match(cel.Value, Application.Range("WagonData").Columns(1), 0), 4)
            If cel.Offset(0, 1).Value Mod WagonPack > 0 Then
                ErrorWagonPack = True
                cel.Font.ColourIndex = RGB(156, 0, 6) '438 error here
                cel.Interior.ColourIndex = RGB(255, 199, 206) '438 error here too
            End If
        End If
    Next cel

If ErrorWagonPack = True Or ErrorCellsNotEmpty = True Then
    Exit Sub
End If

'calculate stuff
Application.EnableEvents = True
End Sub

Ideally I'd like to get to a point where I run the code, colour the cells causing issues/with incorrect data, then if doesn't throw any error variables, run the calculation but the 438 error seems to be the sticking point. I'm almost willing to bet it's something simple I'm just missing but can't figure it out. Probably doesn't help I'm still pretty green with VBA.

Body:
.ColorIndex is incorrect. Use .Color

Private Sub CommandButton1_Click()
    Dim ErrorWagonPack As Boolean, ErrorCellsNotEmpty As Boolean, WagonPack As Integer, cel As Range, Target As Range

    ErrorWagonPack = False
    ErrorCellsNotEmpty = False
    Set Target = Application.Range("ConsistInput")

    For Each cel In Target 'issue is here somewhere I think. It's related to how the cel is created and as such what properties it can have
        Application.EnableEvents = False
        WagonPack = 0
        If Len(cel.Value) > 0 Then
            WagonPack = Application.Index(Application.Range("WagonData"), Application.Match(cel.Value, Application.Range("WagonData").Columns(1), 0), 4)
            If cel.Offset(0, 1).Value Mod WagonPack > 0 Then
                ErrorWagonPack = True
                cel.Font.Color = RGB(156, 0, 6) '438 error here
                cel.Interior.Color = RGB(255, 199, 206) '438 error here too
            End If
        End If
    Next cel

If ErrorWagonPack = True Or ErrorCellsNotEmpty = True Then
    Exit Sub
End If

'calculate stuff
Application.EnableEvents = True
End Sub


问:
ASP.NET Core: Prevent Automatic HTTP 400 responses for individual action
I like the Automatic HTTP 400 responses functionality new to ASP.NET Core 2.1 and it's working out really well for most cases.

However, in one action I need to do a bit of pre-processing before validation the payload. I have a custom validator that requires two values in the model to perform validation. One of those values is in the path so I would like to set that value on the model from the path then validate.

I don't want to switch the functionality off for all actions with:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.Configure<ApiBehaviorOptions>(options =>
    {
        options.SuppressModelStateInvalidFilter = true;
    });
}
</code>```

Is there any way I could switch it off just for an individual action?

Edit:

I tried modifying the InvalidModelStateResponseFactory but it didn't solve my problem because I still need to get into the controller action:

```<code>services.Configure<ApiBehaviorOptions>(options =>
{
    options.InvalidModelStateResponseFactory = actionContext =>
    {
        var ignore = actionContext.ActionDescriptor.FilterDescriptors.Any(fd => fd.Filter is SuppressModelStateInvalidFilterAttribute);
        if (ignore)
        {
            // Can only return IActionResult so doesn't enter the controller action.
        }

        return new BadRequestObjectResult(actionContext.ModelState);
    };
});

[AttributeUsage(AttributeTargets.Method)]
public class SuppressModelStateInvalidFilterAttribute : FormatFilterAttribute
{
}
</code>```

Edit:

Here's a link to an issue I raised on the asp.net core repo in case I get anywhere with that - https://github.com/aspnet/Mvc/issues/8575

答:
Update: you can just use the following code in ConfigureServices in Startup.cs:

```<code>services.Configure<ApiBehaviorOptions>(apiBehaviorOptions => {
    apiBehaviorOptions.SuppressModelStateInvalidFilter = true;
});
</code>```

Based on Simon Vane's answer, I had to modify the attribute for ASP.Net Core 2.2 as follows:

```<code>/// <summary>
/// Suppresses the default ApiController behaviour of automatically creating error 400 responses
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class SuppressModelStateInvalidFilterAttribute : Attribute, IActionModelConvention {
    private static readonly Type ModelStateInvalidFilterFactory = typeof(ModelStateInvalidFilter).Assembly.GetType("Microsoft.AspNetCore.Mvc.Infrastructure.ModelStateInvalidFilterFactory");

    public void Apply(ActionModel action) {
        for (var i = 0; i < action.Filters.Count; i++) {
            if (action.Filters[i] is ModelStateInvalidFilter || action.Filters[i].GetType() == ModelStateInvalidFilterFactory) {
                action.Filters.RemoveAt(i);
                break;
            }
        }
    }
}
</code>```

Body:
I like the Automatic HTTP 400 responses functionality new to ASP.NET Core 2.1 and it's working out really well for most cases.

However, in one action I need to do a bit of pre-processing before validation the payload. I have a custom validator that requires two values in the model to perform validation. One of those values is in the path so I would like to set that value on the model from the path then validate.

I don't want to switch the functionality off for all actions with:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<ApiBehaviorOptions>(options =>
    {
        options.SuppressModelStateInvalidFilter = true;
    });
}

Is there any way I could switch it off just for an individual action?

Edit:

I tried modifying the InvalidModelStateResponseFactory but it didn't solve my problem because I still need to get into the controller action:

services.Configure<ApiBehaviorOptions>(options =>
{
    options.InvalidModelStateResponseFactory = actionContext =>
    {
        var ignore = actionContext.ActionDescriptor.FilterDescriptors.Any(fd => fd.Filter is SuppressModelStateInvalidFilterAttribute);
        if (ignore)
        {
            // Can only return IActionResult so doesn't enter the controller action.
        }

        return new BadRequestObjectResult(actionContext.ModelState);
    };
});

[AttributeUsage(AttributeTargets.Method)]
public class SuppressModelStateInvalidFilterAttribute : FormatFilterAttribute
{
}

Edit:

Here's a link to an issue I raised on the asp.net core repo in case I get anywhere with that - https://github.com/aspnet/Mvc/issues/8575

Body:
Update: you can just use the following code in ConfigureServices in Startup.cs:

services.Configure<ApiBehaviorOptions>(apiBehaviorOptions => {
    apiBehaviorOptions.SuppressModelStateInvalidFilter = true;
});

Based on Simon Vane's answer, I had to modify the attribute for ASP.Net Core 2.2 as follows:

/// <summary>
/// Suppresses the default ApiController behaviour of automatically creating error 400 responses
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class SuppressModelStateInvalidFilterAttribute : Attribute, IActionModelConvention {
    private static readonly Type ModelStateInvalidFilterFactory = typeof(ModelStateInvalidFilter).Assembly.GetType("Microsoft.AspNetCore.Mvc.Infrastructure.ModelStateInvalidFilterFactory");

    public void Apply(ActionModel action) {
        for (var i = 0; i < action.Filters.Count; i++) {
            if (action.Filters[i] is ModelStateInvalidFilter || action.Filters[i].GetType() == ModelStateInvalidFilterFactory) {
                action.Filters.RemoveAt(i);
                break;
            }
        }
    }
}


问:
Can someone help explain why it returns a different sum?
var x = 10 + Number("1"+"6");
console.log(x);

returns: 26

var y = 10 + 1 + 6;
console.log(y);

returns: 17

答:
"1"+"6" = "16" : concatenation fo 2 strings
Number("1"+"6") = Number("16") = 16

10 + 16 = 26

```<code>    let x = 10 + Number("1") + Number("6"); //for x to equal 17
</code>```

here a function i use to sum numbers regardless of arguments are numbers or strings (return null if any of the arguments is not a number)

```<code>function sumNumbers(){
    let result = 0;
    for(arg of arguments){
        let nArg = Number(arg);
        if(isNaN(nArg)){
            return null;
        };
        result+=nArg;
    }
    return result;
}
</code>```

Body:
"1"+"6" = "16" : concatenation fo 2 strings
Number("1"+"6") = Number("16") = 16

10 + 16 = 26

    let x = 10 + Number("1") + Number("6"); //for x to equal 17

here a function i use to sum numbers regardless of arguments are numbers or strings (return null if any of the arguments is not a number)

function sumNumbers(){
    let result = 0;
    for(arg of arguments){
        let nArg = Number(arg);
        if(isNaN(nArg)){
            return null;
        };
        result+=nArg;
    }
    return result;
}


问:
Trying to rescue HTTParty connection error in Rails 5
I am using Rails 5 and HTTParty.

Problem is that if the API is down for some reason my app crashes. I want to handle this case and have found several solutions but did not make them work.

What I did is:

```<code>begin
   api = HTTParty.get(URL)
rescue HTTParty::Error
   puts('API not available')
end
</code>```

What I hoped is that if the API is down or if I use an invalid URL it would not give me an internal server error but tell me the the API is not available and continue with the code.

But instead it gives and internal server error:

```<code>SocketError (Failed to open TCP connection to URL (getaddrinfo: nodename nor servname provided, or not known)):
</code>```

How can I make sure that this does not happen?

答:
I had this same issue, but rescuing from HTTParty::Error did nothing. My actual error was always Errno::ECONNREFUSED, thus the following is what solved it for me:

```<code>begin
  api = HTTParty.get(URL)
rescue Errno::ECONNREFUSED
  puts('API not available')
end
</code>```

Body:
I am using Rails 5 and HTTParty.

Problem is that if the API is down for some reason my app crashes. I want to handle this case and have found several solutions but did not make them work.

What I did is:

begin
   api = HTTParty.get(URL)
rescue HTTParty::Error
   puts('API not available')
end

What I hoped is that if the API is down or if I use an invalid URL it would not give me an internal server error but tell me the the API is not available and continue with the code.

But instead it gives and internal server error:

SocketError (Failed to open TCP connection to URL (getaddrinfo: nodename nor servname provided, or not known)):

How can I make sure that this does not happen?

Body:
I had this same issue, but rescuing from HTTParty::Error did nothing. My actual error was always Errno::ECONNREFUSED, thus the following is what solved it for me:

begin
  api = HTTParty.get(URL)
rescue Errno::ECONNREFUSED
  puts('API not available')
end


问:
Homework problem, available fields for queen in chess
I have school asignment due tommorow and would apreaciate some help.  My assigment is "Create a program that determines which chess board fields are available to the queen from the field where it is located. The chessboard is presented as a matrix 8x8. Queen's position is entered from the keyboard into [letter] [number]. And the result is saved in a string. " </p>

<p>Iam kinda stuck on how to continiue, i think i need like 8 different if's. 2 for horizontal, 2 for vertical and 4 for diagonals, but i dont know how to do them. </p>

```<code>int main()
{

    int horizontal,vertical,i,j,current;
    char poz;

    printf("Enter the horizontal position of queen(A-H)\n");
    scanf("%s", &poz);

    if(poz=='A')
    {
        horizontal=1;
    }
    else if (poz=='B')
    {
        horizontal=2;
    }
    else if (poz=='C')
    {
        horizontal=3;
    }
    else if (poz=='D')
    {
        horizontal=4;
    }
    else if (poz=='E')
    {
        horizontal=5;
    }
    else if (poz=='F')
    {
        horizontal=6;
    }
    else if (poz=='G')
    {
        horizontal=7;
    }
    else if (poz=='H')
    {
        horizontal=8;
    }

    printf("Enter the vertical position of queen(1-8)\n");
    scanf("%d",&vertical);

    int n=8,m=8;

    int chess[8][8]={
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    };

    printf("Queen pos is %c-%d",poz,vertical );

return 0;
}
</code>```

答:
Strongly suggest the indexing be modified to 0...7 for both horizontal and vertical positions  Then include: (where 'r' is the row and 'c' is the column)

```<code>All positions in the column (0..7)/(c) where the queen is placed except (r)/(c)

All positions in the row (r)/(0..7) where the queen is placed except (r)/(c)
</code>```

Then starting at the queen placement (r)/(c)

```<code>all successive positions (r+1)/(c-1) until edge of board
all successive positions (r+1)/(c+1) until edge of board
all successive positions (r-1)/(c-1) until edge of board
all successive positions (r-1)/(c+1) until edge of board
</code>```

The above is a few 'for()' statements and should be 'relatively' easy to implement.

Body:
I have school asignment due tommorow and would apreaciate some help.  My assigment is "Create a program that determines which chess board fields are available to the queen from the field where it is located. The chessboard is presented as a matrix 8x8. Queen's position is entered from the keyboard into [letter] [number]. And the result is saved in a string. "

Iam kinda stuck on how to continiue, i think i need like 8 different if's. 2 for horizontal, 2 for vertical and 4 for diagonals, but i dont know how to do them.

int main()
{

    int horizontal,vertical,i,j,current;
    char poz;

    printf("Enter the horizontal position of queen(A-H)\n");
    scanf("%s", &poz);

    if(poz=='A')
    {
        horizontal=1;
    }
    else if (poz=='B')
    {
        horizontal=2;
    }
    else if (poz=='C')
    {
        horizontal=3;
    }
    else if (poz=='D')
    {
        horizontal=4;
    }
    else if (poz=='E')
    {
        horizontal=5;
    }
    else if (poz=='F')
    {
        horizontal=6;
    }
    else if (poz=='G')
    {
        horizontal=7;
    }
    else if (poz=='H')
    {
        horizontal=8;
    }

    printf("Enter the vertical position of queen(1-8)\n");
    scanf("%d",&vertical);

    int n=8,m=8;

    int chess[8][8]={
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    {1,2,3,4,5,6,7,8},
    };

    printf("Queen pos is %c-%d",poz,vertical );

return 0;
}

Body:
Strongly suggest the indexing be modified to 0...7 for both horizontal and vertical positions  Then include: (where 'r' is the row and 'c' is the column)

All positions in the column (0..7)/(c) where the queen is placed except (r)/(c)

All positions in the row (r)/(0..7) where the queen is placed except (r)/(c)

Then starting at the queen placement (r)/(c)

all successive positions (r+1)/(c-1) until edge of board
all successive positions (r+1)/(c+1) until edge of board
all successive positions (r-1)/(c-1) until edge of board
all successive positions (r-1)/(c+1) until edge of board

The above is a few 'for()' statements and should be 'relatively' easy to implement.