问:
Printing an entire character array after looping through every point in a rectangular area
I'm using a double for-loop in order to check every point (coordinate pair) in a rectangular area from (-2.0, -1.12) to (0.47, 1.12) to see whether it belongs to the Mandelbrot set. If it does, I want to print a 1. Likewise, if it does not, I want to print a 0. The basic idea is to print, line by line, an array of characters that displays a simplified Mandelbrot set.

This is my main function:

```<code>#include <stdio.h>
#include "complex.h"
#include "mandelbrot.h"

#define STEP_X   0.06175
#define STEP_Y   0.07466

int main(void){

    int i = 0;
    char arr[50];
    complex_t c, abs, max;
    max.real = 10000;
    max.imag = 0;

    for (c.imag = -1.12; c.imag <= 1.12; c.imag += STEP_Y){
            for (c.real = -2.0; c.real <= 0.47; c.real += STEP_X){
                    abs = abs_complex(mandelbrot(c,15));
                    if (abs.real < max.real){
                            arr[i] = 1;
                            i++;
                    }
                    else{
                            arr[i] = 0;
                            i++;
                    }
            }
            printf("%s", arr);
            i = 0;
    }
}
</code>```

The program compiles just fine, but does not produce an output. I know I must not be printing the array the right way, but for the life of me I can not figure out how to do it.

Any feedback, hints, or tips would be greatly appreciated.

Thanks in advance!

答:
The problems you are having are two-fold. (1) you are copying decimal values to arr (e.g. 0 and 1) instead of ASCII characters ('0' and '1'). Decimal 0 and 1 are non-printable. Ironically decimal 0 is the nul-terminating character, so if if (abs.real >= max.real) for i == 0 arr holds the empty-string.

Second you call printf without having insured the final character is the nul-terminating character. (you can do this by default by initializing char arr[MAXC] = ""; and insuring your loop is limited to i + 1 < 50 && c.real <= 0.47 or you can simply affirmatively terminate arr with arr[i] = 0; before calling i = 0; (or move your declaration of i inside the first for loop and initialize).

This is untested (I don't have your local headers), but it looks like you intended:

```<code>#include <stdio.h>
#include "complex.h"
#include "mandelbrot.h"

#define MAXC     50
#define STEP_X   0.06175
#define STEP_Y   0.07466

int main(void){

    complex_t c, abs, max;
    max.real = 10000;
    max.imag = 0;

    for (c.imag = -1.12; c.imag <= 1.12; c.imag += STEP_Y) {

        int i = 0;             /* declare/initialize i & arr here */
        char arr[MAXC] = "";   /* set to all zero */

        for (c.real = -2.0;
            i + 1 < MAXC && c.real <= 0.47;  /* limit to 49 chars max */
            c.real += STEP_X) {

            abs = abs_complex (mandelbrot (c,15));

            if (abs.real < max.real)
                arr[i++] = '1';   /* assign character '1' */
            else
                arr[i++] = '0';   /* assign character '0' */
        }
        arr[i] = 0;               /* nul-terminate line */
        printf ("%s\n", arr);     /* output line */
    }
    return 0;
}
</code>```

Give it a try and let me know if you have further questions.

Body:
I'm using a double for-loop in order to check every point (coordinate pair) in a rectangular area from (-2.0, -1.12) to (0.47, 1.12) to see whether it belongs to the Mandelbrot set. If it does, I want to print a 1. Likewise, if it does not, I want to print a 0. The basic idea is to print, line by line, an array of characters that displays a simplified Mandelbrot set.

This is my main function:

#include <stdio.h>
#include "complex.h"
#include "mandelbrot.h"

#define STEP_X   0.06175
#define STEP_Y   0.07466

int main(void){

    int i = 0;
    char arr[50];
    complex_t c, abs, max;
    max.real = 10000;
    max.imag = 0;

    for (c.imag = -1.12; c.imag <= 1.12; c.imag += STEP_Y){
            for (c.real = -2.0; c.real <= 0.47; c.real += STEP_X){
                    abs = abs_complex(mandelbrot(c,15));
                    if (abs.real < max.real){
                            arr[i] = 1;
                            i++;
                    }
                    else{
                            arr[i] = 0;
                            i++;
                    }
            }
            printf("%s", arr);
            i = 0;
    }
}

The program compiles just fine, but does not produce an output. I know I must not be printing the array the right way, but for the life of me I can not figure out how to do it.

Any feedback, hints, or tips would be greatly appreciated.

Thanks in advance!

Body:
The problems you are having are two-fold. (1) you are copying decimal values to arr (e.g. 0 and 1) instead of ASCII characters ('0' and '1'). Decimal 0 and 1 are non-printable. Ironically decimal 0 is the nul-terminating character, so if if (abs.real >= max.real) for i == 0 arr holds the empty-string.

Second you call printf without having insured the final character is the nul-terminating character. (you can do this by default by initializing char arr[MAXC] = ""; and insuring your loop is limited to i + 1 < 50 && c.real <= 0.47 or you can simply affirmatively terminate arr with arr[i] = 0; before calling i = 0; (or move your declaration of i inside the first for loop and initialize).

This is untested (I don't have your local headers), but it looks like you intended:

#include <stdio.h>
#include "complex.h"
#include "mandelbrot.h"

#define MAXC     50
#define STEP_X   0.06175
#define STEP_Y   0.07466

int main(void){

    complex_t c, abs, max;
    max.real = 10000;
    max.imag = 0;

    for (c.imag = -1.12; c.imag <= 1.12; c.imag += STEP_Y) {

        int i = 0;             /* declare/initialize i & arr here */
        char arr[MAXC] = "";   /* set to all zero */

        for (c.real = -2.0;
            i + 1 < MAXC && c.real <= 0.47;  /* limit to 49 chars max */
            c.real += STEP_X) {

            abs = abs_complex (mandelbrot (c,15));

            if (abs.real < max.real)
                arr[i++] = '1';   /* assign character '1' */
            else
                arr[i++] = '0';   /* assign character '0' */
        }
        arr[i] = 0;               /* nul-terminate line */
        printf ("%s\n", arr);     /* output line */
    }
    return 0;
}

Give it a try and let me know if you have further questions.


来源: stackexchange

问:
How to gauss-filter (blur) a floating point numpy array
I have got a numpy array a of type float64.  How can I blur this data with a Gauss filter?

I have tried

```<code>from PIL import Image, ImageFilter

image = Image.fromarray(a)
filtered = image.filter(ImageFilter.GaussianBlur(radius=7))
</code>```

, but this yields ValueError: 'image has wrong mode'. (It has mode F.)

I could create an image of suitable mode by multiplying a with some constant, then rounding to integer. That should work, but I would like to have a more direct way.

(I am using Pillow 2.7.0.)

答:
Here is my approach using only numpy.
It is prepared with a simple 3x3 kernel, minor changes could make it work with custom sized kernels.</p>

```<code>def blur(a):
    kernel = np.array([[1.0,2.0,1.0], [2.0,4.0,2.0], [1.0,2.0,1.0]])
    kernel = kernel / np.sum(kernel)
    arraylist = []
    for y in range(3):
        temparray = np.copy(a)
        temparray = np.roll(temparray, y - 1, axis=0)
        for x in range(3):
            temparray_X = np.copy(temparray)
            temparray_X = np.roll(temparray_X, x - 1, axis=1)*kernel[y,x]
            arraylist.append(temparray_X)

    arraylist = np.array(arraylist)
    arraylist_sum = np.sum(arraylist, axis=0)
    return arraylist_sum
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have got a numpy array a of type float64.  How can I blur this data with a Gauss filter?

I have tried

from PIL import Image, ImageFilter

image = Image.fromarray(a)
filtered = image.filter(ImageFilter.GaussianBlur(radius=7))

, but this yields ValueError: 'image has wrong mode'. (It has mode F.)

I could create an image of suitable mode by multiplying a with some constant, then rounding to integer. That should work, but I would like to have a more direct way.

(I am using Pillow 2.7.0.)

Body:
Here is my approach using only numpy.
It is prepared with a simple 3x3 kernel, minor changes could make it work with custom sized kernels.

def blur(a):
    kernel = np.array([[1.0,2.0,1.0], [2.0,4.0,2.0], [1.0,2.0,1.0]])
    kernel = kernel / np.sum(kernel)
    arraylist = []
    for y in range(3):
        temparray = np.copy(a)
        temparray = np.roll(temparray, y - 1, axis=0)
        for x in range(3):
            temparray_X = np.copy(temparray)
            temparray_X = np.roll(temparray_X, x - 1, axis=1)*kernel[y,x]
            arraylist.append(temparray_X)

    arraylist = np.array(arraylist)
    arraylist_sum = np.sum(arraylist, axis=0)
    return arraylist_sum


问:
Converting Enum between modules
I have an enum definition in one module(A), e.g. SUCCESS = 0, INVALID_REQ = 1 etc. Then I have another dll (module B) which has its own set of status enum. Once we add a new enum value in A, we have to manually add it to B since A is in .NET and B is C code. Beside, enum in A is only part of the status enum in B (B has its own internal status besides status from A).
This seems a very tight coupling between these two modules. Any suggestions to make them less coupled?
Thx!</p>

答: Why not write a simple script that generates these enums based on a file during build? If you truly want to uncouple them, you will need to make someone a master and expose its content to the other side.. Likely using RCW..</p>

ContentLicense: CC BY-SA 2.5

Title: Converting Enum between modules


问:
Efficient Prime Number Computing Program Java
So I was trying to make a prime number calculator in java that goes from 1 up to the upper limit of the range given by the user and prints out all of the primes.

One way of approaching this was by simply using a nested for loop and testing divisibility for every number in the range by all of the numbers less than it.

However, I figured it would be more efficient to only test prime numbers to avoid repeated factors and speed up the program.

For example, if the number we were on was 16, rather than testing if it's divisible by 2,3,4,5,...14,15,16, I could only test out 2,3,5,7,11,13 and stop once a factor is found.

So I tried to make an array to store all of the primes found so far and only use those values to test for the next number.

Here's my code, I can't figure out why it's not working

```<code>    Scanner sc = new Scanner (System.in);
    System.out.print ("Enter the upper limit: ");
    int high = sc.nextInt();

    boolean isPrime = true;
    int[] primearray = new int[0];

    for (int num = 1; num <= high; num++)
    {
        for (int x: primearray)
        {
            if (num%x==0)
            {
                isPrime = false;
                break;
            }
        }
        if (isPrime == true) {
            int size = primearray.length;
            primearray = new int[size+1];
            primearray [size] = num;

            System.out.println (num);
        }
    }
</code>```

答:
As you say the key simplification is to only test primes when you find the next prime. For example:

```<code>public class PrimeGenerator {
    private long current = 1;
    private final List<Long> primes = new ArrayList<>();

    public long next() {
        do {
            current++;
        } while (primes.stream().anyMatch(n -> current % n == 0));
        primes.add(current);
        return current;
    }

    public LongStream stream() {
        return LongStream.generate(this::next);
    }
}
</code>```

This records each prime as it is generated.

You can generate get all primes to a certain value with

```<code>generator.stream().takeWhile(p -> p < value)...
</code>```

Body:
So I was trying to make a prime number calculator in java that goes from 1 up to the upper limit of the range given by the user and prints out all of the primes.

One way of approaching this was by simply using a nested for loop and testing divisibility for every number in the range by all of the numbers less than it.

However, I figured it would be more efficient to only test prime numbers to avoid repeated factors and speed up the program.

For example, if the number we were on was 16, rather than testing if it's divisible by 2,3,4,5,...14,15,16, I could only test out 2,3,5,7,11,13 and stop once a factor is found.

So I tried to make an array to store all of the primes found so far and only use those values to test for the next number.

Here's my code, I can't figure out why it's not working

    Scanner sc = new Scanner (System.in);
    System.out.print ("Enter the upper limit: ");
    int high = sc.nextInt();

    boolean isPrime = true;
    int[] primearray = new int[0];

    for (int num = 1; num <= high; num++)
    {
        for (int x: primearray)
        {
            if (num%x==0)
            {
                isPrime = false;
                break;
            }
        }
        if (isPrime == true) {
            int size = primearray.length;
            primearray = new int[size+1];
            primearray [size] = num;

            System.out.println (num);
        }
    }

Body:
As you say the key simplification is to only test primes when you find the next prime. For example:

public class PrimeGenerator {
    private long current = 1;
    private final List<Long> primes = new ArrayList<>();

    public long next() {
        do {
            current++;
        } while (primes.stream().anyMatch(n -> current % n == 0));
        primes.add(current);
        return current;
    }

    public LongStream stream() {
        return LongStream.generate(this::next);
    }
}

This records each prime as it is generated.

You can generate get all primes to a certain value with

generator.stream().takeWhile(p -> p < value)...


问:
Extremely simple Ajax code doesn't work
The external website spits proper JSON and the code is too simple I don't know what can be wrong. I tried with get and post.

$(document).ready(function() {
  $.get("https://www.w3schools.com/jquery/demo_ajax_json.js", function(result) {
    alert(result);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script></code>```

答:
if you are trying to access from localhost append this line
http://cors-anywhere.herokuapp.com/ else keep it like https://www.w3schools.com/jquery/demo_ajax_json.js and then use $.getJson , it will output the result as you required , also JSON.stringify the JSON data so that you can view the data in alert else [Object][Object] will be alerted</p>

```<code>var resultUrl = 'http://cors-anywhere.herokuapp.com/'+'https://www.w3schools.com/jquery/demo_ajax_json.js';

    $.getJSON(resultUrl, function(result) {
        alert(JSON.stringify(result));
    });
</code>```

Title: Extremely simple Ajax code doesn't work

Body:
if you are trying to access from localhost append this line
http://cors-anywhere.herokuapp.com/ else keep it like https://www.w3schools.com/jquery/demo_ajax_json.js and then use $.getJson , it will output the result as you required , also JSON.stringify the JSON data so that you can view the data in alert else [Object][Object] will be alerted

var resultUrl = 'http://cors-anywhere.herokuapp.com/'+'https://www.w3schools.com/jquery/demo_ajax_json.js';

    $.getJSON(resultUrl, function(result) {
        alert(JSON.stringify(result));
    });


问:
Safely clone a Hibernate Spring JPA entity - Javassist
I'm cloning an entity using Spring BeanUtils.copyProperties(source, target, excludes) method and the issue is there is a method called setHandler that gets called and it basically resets all the properties I set in my exclusion list during the copy. If I exclude handler, then I get an exception saving the new object.

I just want to do a clone of a Hibernate object, excluding 10 properties and save the new object.

```<code>    public static <T> T cloneClass(T existing, Class<? extends Annotation> ignores)
        throws Exception {

    final Collection<String> excludes = new ArrayList<>();

    Set<Method> annotated = getMethodsWithAnnotation(ignores, existing.getClass());

    for (Method method : annotated) {

        if (!method.getName().startsWith("get") && !method.getName().startsWith("is"))
            continue;
        String exclude = ReflectUtil.decap(method.getName());
        log.debug("Exclude from copy: " + exclude);
        excludes.add(exclude);
    }

    excludes.add("handler"); <-- must have this
    Object newInstance = existing.getClass().newInstance();
    String[] excludeArray = excludes.toArray(new String[excludes.size()]);

    BeanUtils.copyProperties(existing, newInstance, excludeArray);

    return (T) newInstance;
}
</code>```

If I don't include

```<code>excludes.add("handler"); <-- must have this
</code>```

Then what happens is the target object gets all the properties from the source and basically makes my exclude list useless, but once I try to save that object, Hibernate throws an internal hibernate error.

Is there an easier way to clone an object than what I am doing?

答: I don't think you really need to do any cloning. Simply retrieve the object and then remove the object from the session and it is effectively a clone: Is it possible to detach Hibernate entity, so that changes to object are not automatically saved to database?. Start another session again once you want to update the instance.</p>

Body:
I'm cloning an entity using Spring BeanUtils.copyProperties(source, target, excludes) method and the issue is there is a method called setHandler that gets called and it basically resets all the properties I set in my exclusion list during the copy. If I exclude handler, then I get an exception saving the new object.

I just want to do a clone of a Hibernate object, excluding 10 properties and save the new object.

    public static <T> T cloneClass(T existing, Class<? extends Annotation> ignores)
        throws Exception {

    final Collection<String> excludes = new ArrayList<>();

    Set<Method> annotated = getMethodsWithAnnotation(ignores, existing.getClass());

    for (Method method : annotated) {

        if (!method.getName().startsWith("get") && !method.getName().startsWith("is"))
            continue;
        String exclude = ReflectUtil.decap(method.getName());
        log.debug("Exclude from copy: " + exclude);
        excludes.add(exclude);
    }

    excludes.add("handler"); <-- must have this
    Object newInstance = existing.getClass().newInstance();
    String[] excludeArray = excludes.toArray(new String[excludes.size()]);

    BeanUtils.copyProperties(existing, newInstance, excludeArray);

    return (T) newInstance;
}

If I don't include

excludes.add("handler"); <-- must have this

Then what happens is the target object gets all the properties from the source and basically makes my exclude list useless, but once I try to save that object, Hibernate throws an internal hibernate error.

Is there an easier way to clone an object than what I am doing?


问:
Eclipse C++ content assist, auto activation
I have noticed in Eclipse that content assist kicks in after inserting -> or . or ::

I really like this feature, but I was hoping that it would be a little more flexible and auto activate after every 2-3 character typed. An example of this is in Code::Blocks. It allows you to auto activate content assist after a certain number of chars typed. Another example of this is in Visual Studio while using Visual Assist X, "Whole Tomato".

Is it possible to somehow enable this for Eclipse?

答: I havn't seen a setting to auto-activate the content assist, for other than . :: and -> However, Hit CTRL+Space to autocomplete or bring up the content assist  , e.g. after you typed 2-3 chars.


问:
How Do I Pass State (Value) when Calling Component in React?
I have a React APP which displays images perfectly fine from the Flickr API based on a 'dogs' query which is built into the code--this is container which accomplishes this:

```<code>import React, { Component } from 'react';
import axios from 'axios';
import apiKey from './config.js';
import Navigation from './Navigation.js';
import Photos from './Photos.js';
import SearchBar from './SearchBar.js';

class Container extends Component {

  constructor (){
    super();
    this.state = {
        imgs:[],
        query: '',
        loading: true
    }
  }

  componentDidMount() {
    this.performSearch();

}

  performSearch = (query = 'dogs') => {
    axios.get(`https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=${apiKey}&tags=${query}&per_page=24&format=json&nojsoncallback=1`)
    .then(response => {
      this.setState({
        imgs: response.data.photos.photo,
        loading: false
      });
    })
    .catch(err => {
      console.log('Error happened during fetching!', err);
    });
  }

    render() {
        return (
            <div className="container">
            <SearchBar onSearch={this.performSearch}/>
             <Navigation />
              {
                (this.state.loading)
                ? <p>Loading....</p>
                : <Photos data={this.state.imgs}/>
              }
            </div>
            );
    }
}
export default Container;
</code>```

I have a nav bar with three different links--and I would like to call the Container component for each-- passing a specific value for the query in the API.

So for example, if my links are bears, cats, and mice, I would like the respective link to generate the correct api based on the query term.

I am just uncertain as to how I pass the query term utilizing the Container component.  Go easy, as I'm a bit new to react, but I was trying something like

```<code><Container query="bears" />
</code>```

or

```<code><Container performSearch("bears") />
</code>```

But I can't seem to figure out how to pass the appropriate value.

答:
It looks like you want to pass the query in as a prop. I would begin by updating the constructor to receive props, pass them to super(), and use them to set the value of the state's query property:

```<code>constructor(props) {
    super(props);
    this.state = {
        imgs: [],
        query: this.props.query,
        loading: true
    }
}
</code>```

Next, update the performSearch() method to use the state's query property instead of the hard-coded 'dogs' value:

```<code>performSearch = (query = this.state.query) => {
</code>```

Now you can pass the appropriate query property to the Container like you were thinking:

```<code><Container query="bears" />
<Container query="cats" />
<Container query="mice" />
</code>```

Body:
I have a React APP which displays images perfectly fine from the Flickr API based on a 'dogs' query which is built into the code--this is container which accomplishes this:

import React, { Component } from 'react';
import axios from 'axios';
import apiKey from './config.js';
import Navigation from './Navigation.js';
import Photos from './Photos.js';
import SearchBar from './SearchBar.js';

class Container extends Component {

  constructor (){
    super();
    this.state = {
        imgs:[],
        query: '',
        loading: true
    }
  }

  componentDidMount() {
    this.performSearch();

}

  performSearch = (query = 'dogs') => {
    axios.get(`https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=${apiKey}&tags=${query}&per_page=24&format=json&nojsoncallback=1`)
    .then(response => {
      this.setState({
        imgs: response.data.photos.photo,
        loading: false
      });
    })
    .catch(err => {
      console.log('Error happened during fetching!', err);
    });
  }

    render() {
        return (

            <SearchBar onSearch={this.performSearch}/>
             <Navigation />
              {
                (this.state.loading)
                ?
Loading....

                : <Photos data={this.state.imgs}/>
              }

            );
    }
}
export default Container;

I have a nav bar with three different links--and I would like to call the Container component for each-- passing a specific value for the query in the API.

So for example, if my links are bears, cats, and mice, I would like the respective link to generate the correct api based on the query term.

I am just uncertain as to how I pass the query term utilizing the Container component.  Go easy, as I'm a bit new to react, but I was trying something like

<Container query="bears" />

or

<Container performSearch("bears") />

But I can't seem to figure out how to pass the appropriate value.

Body:
It looks like you want to pass the query in as a prop. I would begin by updating the constructor to receive props, pass them to super(), and use them to set the value of the state's query property:

constructor(props) {
    super(props);
    this.state = {
        imgs: [],
        query: this.props.query,
        loading: true
    }
}

Next, update the performSearch() method to use the state's query property instead of the hard-coded 'dogs' value:

performSearch = (query = this.state.query) => {

Now you can pass the appropriate query property to the Container like you were thinking:

<Container query="bears" />
<Container query="cats" />
<Container query="mice" />


问:
JavaScript regular expression returns false, but regex tester returning true
I have a JavaScript regular expression that I'm using for frontend password validation in an input field. Here is what my input field looks like:

```<code><input type='password' placeholder='Password...' id='password' pattern='^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})' required>
</code>```

That regular expression is looking for a string: eight characters or longer, with an uppercase letter, lowercase letter, number, and a special character. Let's take the string: November2017! for instance. That should pass the regular expression, but it doesn't in my webapp. And when I copy and paste the regular expression from my input field ^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,}) and put it into regex101.com, that string passes the validation. But it does not pass the validation in my webapp. Is there a specific reason why putting it in a pattern attribute would change whether or not it would pass validation?

答:
You need to add the .{8,} in the end.

```<code>^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*]).{8,}
</code>```

It happens because the pattern must match the complete string, and your current expression only matches the beginning of the string.

Body:
I have a JavaScript regular expression that I'm using for frontend password validation in an input field. Here is what my input field looks like:

<input type='password' placeholder='Password...' id='password' pattern='^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})' required>

That regular expression is looking for a string: eight characters or longer, with an uppercase letter, lowercase letter, number, and a special character. Let's take the string: November2017! for instance. That should pass the regular expression, but it doesn't in my webapp. And when I copy and paste the regular expression from my input field ^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,}) and put it into regex101.com, that string passes the validation. But it does not pass the validation in my webapp. Is there a specific reason why putting it in a pattern attribute would change whether or not it would pass validation?

Body:
You need to add the .{8,} in the end.

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*]).{8,}

It happens because the pattern must match the complete string, and your current expression only matches the beginning of the string.


问:
How do I remove surrounding spaces from each value in multidimensional array recursively
Each string value within my $arr array contains 2 preceeding white spaces. I would like to remove these spaces using the trim() method. Furthermore, I would like to do the same for any arrays within the $arr array assuming an infinite number of arrays within arrays. I attempted to do this recursively with no success.

Although there might be a built in php method to do this for me, I am learning, and would like to know why this code block doesn't work as well as what altercation can be made to fix it.

```<code>$arr = array("  one", "  two", array("  three"));

function trimAll(&$array) {
  foreach($array as $key => $value) {
    if(gettype($value) !== "array") {
        $array[$key] = trim($value);
    } else {
        trimAll($value);
    }
  }
}

trimAll($arr);

echo $arr[0];//"one" (worked)
echo $arr[1];//"two" (worked)
echo $arr[2][0];// "  three"(didn't work)
</code>```

答:
The best/simplest function to call in this case is: array_walk_recursive().  There is no need to reinvent a function that php has already designed for just this purpose.  It only visits "leaf nodes" so you don't need to check if it is processing an array-type element.

You merely need to modify the elements by reference (using & in the anonymous function parameter).  I'll demo ltrim() since your input strings only have leading spaces, but you can use trim() to handle spaces on both sides of the string.

Code: (Demo) (PHP7.4 and higher version)

```<code>array_walk_recursive(
    $arr,
    function(&$v) {
        $v = ltrim($v);
    }
);
</code>```

Output:

```<code>array (
  0 => 'one',
  1 => 'two',
  2 =>
  array (
    0 => 'three',
  ),
)
</code>```

As for your custom function, it could be written like this to provide a successful result:

```<code>function trimAll(&$array) {     // modify the original input array by reference
    foreach ($array as &$value) {  // modify each value by reference
        if (!is_array($value)) {      // if it is not an array
            $value = trim($value);    // trim the string
        } else {
            trimAll($value);        // recurse
        }
    }
}

trimAll($arr);                  // modify the array (no return value from function call)
var_export($arr);               // print the array
</code>```

You see, the reason your subarray element is not being affected is because there is no assignment occuring between $value and trimAll($value).  The way you have set up trimAll, it does not return a value.  So, even if you used:

```<code>} else {
    $array[$key] = trimAll($value);
}
</code>```

You would find that $array[$key] would be replaced by NULL.  The solution is to make $value modifiable by reference by using &$value in the foreach loop.

And as if this answer wasn't long enough already, here is a way to reconfigure your function so that it returns the modified array instead of modifying the input array with no return.

```<code>function trimAll($array){            // input array is not modifiable
    foreach ($array as &$value) {      // $value IS modifiable
        if (is_array($value)) {        // if an array...
            $value = trimAll($value);  // assign recursion result to $value
        } else {                       // not an array...
            $value = trim($value);     // trim the string
        }
    }
    return $array;                   // return the new trimmed array
}
var_export(trimAll($arr));           // now trimAll() can be directly printed to screen
</code>```

or if you wish to avoid modifying by reference entirely:

```<code>function trimAll($array) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $array[$key] = trimAll($value);
        } else {
            $array[$key] = trim($value);
        }
    }
    return $array;
}
var_export(trimAll($arr));
</code>```

Body:
Each string value within my $arr array contains 2 preceeding white spaces. I would like to remove these spaces using the trim() method. Furthermore, I would like to do the same for any arrays within the $arr array assuming an infinite number of arrays within arrays. I attempted to do this recursively with no success.

Although there might be a built in php method to do this for me, I am learning, and would like to know why this code block doesn't work as well as what altercation can be made to fix it.

$arr = array("  one", "  two", array("  three"));

function trimAll(&$array) {
  foreach($array as $key => $value) {
    if(gettype($value) !== "array") {
        $array[$key] = trim($value);
    } else {
        trimAll($value);
    }
  }
}

trimAll($arr);

echo $arr[0];//"one" (worked)
echo $arr[1];//"two" (worked)
echo $arr[2][0];// "  three"(didn't work)

Body:
The best/simplest function to call in this case is: array_walk_recursive().  There is no need to reinvent a function that php has already designed for just this purpose.  It only visits "leaf nodes" so you don't need to check if it is processing an array-type element.

You merely need to modify the elements by reference (using & in the anonymous function parameter).  I'll demo ltrim() since your input strings only have leading spaces, but you can use trim() to handle spaces on both sides of the string.

Code: (Demo) (PHP7.4 and higher version)

array_walk_recursive(
    $arr,
    function(&$v) {
        $v = ltrim($v);
    }
);

Output:

array (
  0 => 'one',
  1 => 'two',
  2 =>
  array (
    0 => 'three',
  ),
)

As for your custom function, it could be written like this to provide a successful result:

function trimAll(&$array) {     // modify the original input array by reference
    foreach ($array as &$value) {  // modify each value by reference
        if (!is_array($value)) {      // if it is not an array
            $value = trim($value);    // trim the string
        } else {
            trimAll($value);        // recurse
        }
    }
}

trimAll($arr);                  // modify the array (no return value from function call)
var_export($arr);               // print the array

You see, the reason your subarray element is not being affected is because there is no assignment occuring between $value and trimAll($value).  The way you have set up trimAll, it does not return a value.  So, even if you used:

} else {
    $array[$key] = trimAll($value);
}

You would find that $array[$key] would be replaced by NULL.  The solution is to make $value modifiable by reference by using &$value in the foreach loop.

And as if this answer wasn't long enough already, here is a way to reconfigure your function so that it returns the modified array instead of modifying the input array with no return.

function trimAll($array){            // input array is not modifiable
    foreach ($array as &$value) {      // $value IS modifiable
        if (is_array($value)) {        // if an array...
            $value = trimAll($value);  // assign recursion result to $value
        } else {                       // not an array...
            $value = trim($value);     // trim the string
        }
    }
    return $array;                   // return the new trimmed array
}
var_export(trimAll($arr));           // now trimAll() can be directly printed to screen

or if you wish to avoid modifying by reference entirely:

function trimAll($array) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $array[$key] = trimAll($value);
        } else {
            $array[$key] = trim($value);
        }
    }
    return $array;
}
var_export(trimAll($arr));

ContentLicense: CC BY-SA 4.0


问:
jQuery toggle span text not functioning
My Structure is like this : JSFiddle

I have been referring to various similar questions that the other asked but those solutions are not working for me.

So what I wanted is when I clicked on "Show+", the following content will show and the text will change from "Show+" to "Hide-" which they can be toggled.

I am trying to use if function to achieve this but not working...

```<code>if($(this).find('.expand').text()=="Show+"){
  $(this).find('.expand').text("Hide-");
}else{
  $(this).find('.expand').text("Show+");
}
</code>```

Does anyone get any solution with this?? Thank you so much!

答:
Here you go with a solution https://jsfiddle.net/sgwj3kbk/1/

$(function(){
  $('.title .expand').click(function(){
    $(this).closest("div").next(".dropdown").slideToggle("fast", function(){
      if($('.dropdown').css('display') == 'block'){
        $('.expand').text("Hide-");
      }else{
        $('.expand').text("Show+");
      }
    });
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.title{
  background-color:#CCCCCC;
}
.dropdown{
  display: none;
}</code>```

    Show+

    Content ..... XXX

```

I've used slideToggle instead of toggle.

slideToggle will provide animation effect.

One more solution with few more animation https://jsfiddle.net/sgwj3kbk/2/

Hope this will help you.

Title: jQuery toggle span text not functioning

Body:
My Structure is like this : JSFiddle

I have been referring to various similar questions that the other asked but those solutions are not working for me.

So what I wanted is when I clicked on "Show+", the following content will show and the text will change from "Show+" to "Hide-" which they can be toggled.

I am trying to use if function to achieve this but not working...

if($(this).find('.expand').text()=="Show+"){
  $(this).find('.expand').text("Hide-");
}else{
  $(this).find('.expand').text("Show+");
}

Does anyone get any solution with this?? Thank you so much!

Body:
Here you go with a solution https://jsfiddle.net/sgwj3kbk/1/

$(function(){
  $('.title .expand').click(function(){
    $(this).closest("div").next(".dropdown").slideToggle("fast", function(){
      if($('.dropdown').css('display') == 'block'){
        $('.expand').text("Hide-");
      }else{
        $('.expand').text("Show+");
      }
    });
  })
});

.title{
  background-color:#CCCCCC;
}
.dropdown{
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
  <div class="title">
    <span class="expand">Show+</span>
  </div>
  <div class="dropdown">
    Content ..... XXX
  </div>
</div>

I've used slideToggle instead of toggle.

slideToggle will provide animation effect.

One more solution with few more animation https://jsfiddle.net/sgwj3kbk/2/

Hope this will help you.


问:
Android app icon shows on device to allow uninstall but does not allow to execute
I am able to run an android app in two virtual devices when degugging.(Galaxy tab and phone). When I close the app in debug mode the icon is not showing in the virtual device.

The same thing occurs when I load a signed .apk file to the actual devices.

The app icon shows when I go into manage applications. I can uninstall the app. Thats all I can do. I cannot launch the app since the icon is not visible with the other app icons.

I am using platform 2.2 with google api's 8.

What am I doing wrong? How can I get the app icon to show with other apps and be able to launch?

Here is my manifest file.
Any help is appreciated.

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

<uses-permission android:name="android.permission.SET_DEBUG_APP"></uses-permission>

<application
    android:label="@string/app_name"
    android:icon="@drawable/appicon"
    android:name=".ApplicationController"
    android:debuggable="true" >

    <uses-library android:name="com.google.android.maps" />

    <activity android:name=".MainActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.Main" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".MainFlippingActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MainFlipping" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".PrefsTabWidget"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.PrefsTabWidget" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".PrefsTaskingActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.PrefsTasking" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".SatelliteSelectionActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.SatelliteSelection" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="MainSettingsActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MainSettings" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="ClassificationActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.Classification" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="ListItemPrefActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.ListItemPref" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="TimeOnTargetActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.TimeOnTarget" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="LatLonActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.LatLon" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="QuantityActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.Quantity" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="IncidenceAngleActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.IncidenceAngle" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="SendUrlActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.SendUrl" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="TestActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.Test" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="Slide"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.Slide" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>

<uses-sdk android:minSdkVersion="8"/>
</code>```

答:
You should only be using <category android:name="android.intent.category.LAUNCHER" /> for one of your activities, not all of them. Try removing all others except the one that goes with <action android:name="android.intent.action.Main" />

EDIT: I may be wrong but I think you'll also need to capitalize MAIN as in <action android:name="android.intent.action.MAIN" /> for it to be recognised as the 'main' entry point (main activity).

Body:
I am able to run an android app in two virtual devices when degugging.(Galaxy tab and phone). When I close the app in debug mode the icon is not showing in the virtual device.

The same thing occurs when I load a signed .apk file to the actual devices.

The app icon shows when I go into manage applications. I can uninstall the app. Thats all I can do. I cannot launch the app since the icon is not visible with the other app icons.

I am using platform 2.2 with google api's 8.

What am I doing wrong? How can I get the app icon to show with other apps and be able to launch?

Here is my manifest file.
Any help is appreciated.

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

<uses-permission android:name="android.permission.SET_DEBUG_APP"></uses-permission>

<application
    android:label="@string/app_name"
    android:icon="@drawable/appicon"
    android:name=".ApplicationController"
    android:debuggable="true" >

    <uses-library android:name="com.google.android.maps" />

    <activity android:name=".MainActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.Main" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".MainFlippingActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MainFlipping" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".PrefsTabWidget"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.PrefsTabWidget" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".PrefsTaskingActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.PrefsTasking" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".SatelliteSelectionActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.SatelliteSelection" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="MainSettingsActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MainSettings" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="ClassificationActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.Classification" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="ListItemPrefActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.ListItemPref" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="TimeOnTargetActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.TimeOnTarget" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="LatLonActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.LatLon" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="QuantityActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.Quantity" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="IncidenceAngleActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.IncidenceAngle" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="SendUrlActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.SendUrl" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="TestActivity"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.Test" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="Slide"
            android:screenOrientation="portrait"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.Slide" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>

<uses-sdk android:minSdkVersion="8"/>


问:
Android emulator not showing up on desktop screen
I encounter really strange behavior with android emulator. First of all, I am using extended monitor for development. So i code on my laptop and check the app on emulator on second screen. For some reason, I can't see emulator again after disconnect vga cable but I can see emulator is running on taskbar. Somehow, I can't bring emulator out on desktop screen or move to another screen, it just hidden and I don't know how to bring it out. It already happens to me two or three times. Can somebody help me out? What can I do to solve it?
Below is screenshots of my desktop with emulator running.

alt+tab

avd manager

答:
It happens again when I change to another monitor for extended screen. I try what @Zoe suggested press ALT+SPACE to move but it doesn't work because move is grey out.

So my solution, I created two emulators, for two different monitors.

I am not sure why I got downvoted though.


问:
Show values instead of getter/setter functions in Firefox DevTools variable view
When inspecting a JavaScript object, that uses getter/setter functions for properties (defined with Object.defineProperties) in the Firefox DevTools variables view, it shows the defined getter and setter functions for this particular property:

Is there any way to show the actual content instead of the functions in this view?

Edit: as nils commented, viewing the actual content means technically invoking the getter.

答:
An alternative is to use this workaround - instead of logging the object:

```<code>console.log(objectVar)
</code>```

You can assign the current state into an empty object and then log it:

```<code>console.log(Object.assign({}, objectVar)) // works on all browsers
// OR
console.log({...objectVar}) // es6 only
</code>```

Sidenote: writing this gets tedious fast so if you use a code editor (Atom/VScode) then you can add this as a snippet

Here is an example snippet where you can just type 'l' then press tab:

```<code>'.source.js':
  'console.log object':
    'prefix': 'l'
    'body': "console.log('${1:variable}', Object.assign({}, ${1:variable}))"
</code>```

OR for ES6:

```<code>'.source.js':
      'console.log object':
        'prefix': 'l'
        'body': "console.log('${1:variable}', {...${1:variable}})"
</code>```

Body:
An alternative is to use this workaround - instead of logging the object:

console.log(objectVar)

You can assign the current state into an empty object and then log it:

console.log(Object.assign({}, objectVar)) // works on all browsers
// OR
console.log({...objectVar}) // es6 only

Sidenote: writing this gets tedious fast so if you use a code editor (Atom/VScode) then you can add this as a snippet

Here is an example snippet where you can just type 'l' then press tab:

'.source.js':
  'console.log object':
    'prefix': 'l'
    'body': "console.log('${1:variable}', Object.assign({}, ${1:variable}))"

OR for ES6:

'.source.js':
      'console.log object':
        'prefix': 'l'
        'body': "console.log('${1:variable}', {...${1:variable}})"


问:
yii2 doesn't work $this->redirect
I'm new in yii2. When i click button, jquery triggers event that send ajax request to controller. Here's code:

```<code>$("#save").on('click', function() {
        var data = 'test';
        $.ajax({
            url: 'index.php?r=site%2Fcreate-mockup',
            type: 'POST',
            data: {dat: data},
            success: function(data) {
                console.log(data);
            }
        });
    });
</code>```

In controller creats instance of Mockup class

```<code> public function actionCreateMockup()
    {
      if (Yii::$app->request->isAjax)
      {
          $create_model = new Mockup();
          //filling $create_model
          return $this->redirect(Url::to(['site/saved-mockups']));
       }
     }
</code>```

when i delete $create_model = new Mockup(); //filling $create_model, then it's work.
Mockup.php:

```<code><?php
namespace app\models;
use yii\base\Model;
use yii\db\ActiveRecord;

class Mockup extends ActiveRecord
{

}

?>
</code>```

答:
Since you are using ajax to submit your form and expecting a response back in your ajax success callback you could just continue using JavaScript to handle the rest of the scenarios and redirect the user once the data submitted is saved.

here is something to get you going

```<code>$("#save").on('click', function() {
    var data = 'test';
    $.ajax({
        url: 'index.php?r=site%2Fcreate-mockup',
        type: 'POST',
        data: {dat: data},
        dataType: 'JSON',
        success: function(response) {
            if(response.success){
                  window.location = response.route //redirect on success
            }else{
                 //handle errors here
            }
        }
    });
});
</code>```

than in your controller

```<code>    public function actionCreateMockup()
    {
      if (Yii::$app->request->isAjax)
      {
          $create_model = new Mockup();
          //filling $create_model
          \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
          if($create_model->load(\Yii::$app->getRequest()->post()) && $create_model->save()){
             return [
                'success'=> true,
                'route'=> Url::to(['site/saved-mockups'])
             ];
           }else{
             return [
                'success'=> false,
                'errors'=> $create_model->getErrros();
            ];
        }
       }
     }
</code>```

Title: yii2 doesn't work $this->redirect

Body:
I'm new in yii2. When i click button, jquery triggers event that send ajax request to controller. Here's code:

$("#save").on('click', function() {
        var data = 'test';
        $.ajax({
            url: 'index.php?r=site%2Fcreate-mockup',
            type: 'POST',
            data: {dat: data},
            success: function(data) {
                console.log(data);
            }
        });
    });

In controller creats instance of Mockup class

 public function actionCreateMockup()
    {
      if (Yii::$app->request->isAjax)
      {
          $create_model = new Mockup();
          //filling $create_model
          return $this->redirect(Url::to(['site/saved-mockups']));
       }
     }

when i delete $create_model = new Mockup(); //filling $create_model, then it's work.
Mockup.php:

<?php
namespace app\models;
use yii\base\Model;
use yii\db\ActiveRecord;

class Mockup extends ActiveRecord
{

}

?>

Body:
Since you are using ajax to submit your form and expecting a response back in your ajax success callback you could just continue using JavaScript to handle the rest of the scenarios and redirect the user once the data submitted is saved.

here is something to get you going

$("#save").on('click', function() {
    var data = 'test';
    $.ajax({
        url: 'index.php?r=site%2Fcreate-mockup',
        type: 'POST',
        data: {dat: data},
        dataType: 'JSON',
        success: function(response) {
            if(response.success){
                  window.location = response.route //redirect on success
            }else{
                 //handle errors here
            }
        }
    });
});

than in your controller

    public function actionCreateMockup()
    {
      if (Yii::$app->request->isAjax)
      {
          $create_model = new Mockup();
          //filling $create_model
          \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
          if($create_model->load(\Yii::$app->getRequest()->post()) && $create_model->save()){
             return [
                'success'=> true,
                'route'=> Url::to(['site/saved-mockups'])
             ];
           }else{
             return [
                'success'=> false,
                'errors'=> $create_model->getErrros();
            ];
        }
       }
     }


问:
Count days worked per employee number in Excel
I have a timesheet entry form that people use to enter their hours worked per day. Sometimes they enter multiple entries per day because of different areas worked.

I want to count how many days worked based on the work date. There could be multiple entries per workdate.

For example:

```<code>Employee #       Date          Hours
12345            11/15/17      8
12345            11/16/17      4
12345            11/16/17      3
98765            11/15/17      2
98765            11/15/17      2
98765            11/15/17      2
</code>```

I have a consolidated table that sums the hours worked per employee, but I also would like the days worked. So, for example:

```<code>Employee #       Hours         Days
12345            15            2
98765            6             1
</code>```

I can't seem to put my finger on the right formula/combination of formulas to use. Countif would work perfectly if it worked similarly to sumif.

答:
Maybe you can try Advanced Filter,then COUNTIF and SUMIF:

Hope this helps.

Body:
I have a timesheet entry form that people use to enter their hours worked per day. Sometimes they enter multiple entries per day because of different areas worked.

I want to count how many days worked based on the work date. There could be multiple entries per workdate.

For example:

Employee #       Date          Hours
12345            11/15/17      8
12345            11/16/17      4
12345            11/16/17      3
98765            11/15/17      2
98765            11/15/17      2
98765            11/15/17      2

I have a consolidated table that sums the hours worked per employee, but I also would like the days worked. So, for example:

Employee #       Hours         Days
12345            15            2
98765            6             1

I can't seem to put my finger on the right formula/combination of formulas to use. Countif would work perfectly if it worked similarly to sumif.


问:
Regex - If string doesn't contain specific word within bracket, then remove bracket and its content
Using Regex, I want to remove some words within brackets, except containing certain words.

Target words are:

```<code>hoho
haha
</code>```

So I want to change this string:

```<code>"Nice (foo line) (haha great) (bar) (hoho how)"
</code>```

to

```<code>"Nice (haha great) (hoho how)"
</code>```

I tried some expresseions with this question, but I couldn't find any answer. What should I do?

答:
If you are not opposed to using some python in addition to regex, you can break apart the word groups, then search each group for the patterns you want to keep.  Finally, join the kept groups together into a single string.</p>

```<code>import re

s = "Nice (foo line) (haha great) (bar) (hoho how)"

' '.join(x.group() for x in re.finditer(r'\([\w\s]+\)|\b\w+\b',s)
         if re.search(r'^[\w\s]+$|hoho|haha', x.group()))
# returns:
'Nice (haha great) (hoho how)'
</code>```

Body:
Using Regex, I want to remove some words within brackets, except containing certain words.

Target words are:

hoho
haha

So I want to change this string:

"Nice (foo line) (haha great) (bar) (hoho how)"

to

"Nice (haha great) (hoho how)"

I tried some expresseions with this question, but I couldn't find any answer. What should I do?

Body:
If you are not opposed to using some python in addition to regex, you can break apart the word groups, then search each group for the patterns you want to keep.  Finally, join the kept groups together into a single string.

import re

s = "Nice (foo line) (haha great) (bar) (hoho how)"

' '.join(x.group() for x in re.finditer(r'\([\w\s]+\)|\b\w+\b',s)
         if re.search(r'^[\w\s]+$|hoho|haha', x.group()))
# returns:
'Nice (haha great) (hoho how)'


问:
Checking values in a class list
Basically, I have a class for the Player of a game

```<code>class Player:
    def __init__(self,inventory,hp):
        self.inventory = []
        self.hp = 20
    ...
    ...

P = Player()
</code>```

And I simply want to check for an item in the inventory (where items are each a class as well)

```<code>class Book():
    def __init__(self,name,description):
        ...
        ...
</code>```

Then do this.

```<code>if Book() in P.inventory:
    print("You have a book.")
else:
    print("You don't have a book.")
</code>```

The problem I'm having is that even if the Book() object is in the player's inventory, it reads the if statement as false and runs the else statement.

I'm thinking I could try to use a for loop like so

```<code>for i in P.inventory:
    counter = 0
    if i == Book():
        print("You have a book.")
        counter = 1
if counter == 0:
    print("You don't have a book.")
</code>```

but I'm hoping I won't have to use that much code for such a simple task.

答:
Book() creates a new object everytime so Book() == Book() returns False. You might want to use isinstance instead:

```<code>a_book = Book()
isinstance(a_book, Book)
</code>```

with something like:

```<code>def check_for_books(inventory):
    for i in inventory:
        if isinstance(i, Book):
            print("You have a book.")
            return
    else:
        print("You have no books.")
</code>```

Title: Checking values in a class list

Body:
Basically, I have a class for the Player of a game

class Player:
    def __init__(self,inventory,hp):
        self.inventory = []
        self.hp = 20
    ...
    ...

P = Player()

And I simply want to check for an item in the inventory (where items are each a class as well)

class Book():
    def __init__(self,name,description):
        ...
        ...

Then do this.

if Book() in P.inventory:
    print("You have a book.")
else:
    print("You don't have a book.")

The problem I'm having is that even if the Book() object is in the player's inventory, it reads the if statement as false and runs the else statement.

I'm thinking I could try to use a for loop like so

for i in P.inventory:
    counter = 0
    if i == Book():
        print("You have a book.")
        counter = 1
if counter == 0:
    print("You don't have a book.")

but I'm hoping I won't have to use that much code for such a simple task.

Body:
Book() creates a new object everytime so Book() == Book() returns False. You might want to use isinstance instead:

a_book = Book()
isinstance(a_book, Book)

with something like:

def check_for_books(inventory):
    for i in inventory:
        if isinstance(i, Book):
            print("You have a book.")
            return
    else:
        print("You have no books.")


问:
SP-initiated Single Logout not working with SalesForce
I am attempting to use SP-initiated SLO with SalesForce (trying Redirect and POST) with the following LogoutRequest:

```<code><samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="_1583fa34b3e9426ba5885849204d6f8d" Version="2.0" IssueInstant="2017-11-14T18:42:25Z" Destination="https://myorg-dev-ed.my.salesforce.com/services/auth/idp/saml2/logout">
  <saml:Issuer>myorg</saml:Issuer>
  <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">me@myorg</saml:NameID>
</samlp:LogoutRequest>
</code>```

I am using my SP entity ID for Issuer. I also tried using it for NameID SPNameQualifier. My Redirect and POST logic work for AuthnRequest. This SLO is working with OneLogin.

The error I get back is:

We are unable to log you out. Please contact your administrator for
  more information.

I can not find any relevant log entries.

答:
Which tool are you using to generate the XML?
Add the tag SessionIndex, which you can get from the login.</p>

Body:
I am attempting to use SP-initiated SLO with SalesForce (trying Redirect and POST) with the following LogoutRequest:

<samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="_1583fa34b3e9426ba5885849204d6f8d" Version="2.0" IssueInstant="2017-11-14T18:42:25Z" Destination="https://myorg-dev-ed.my.salesforce.com/services/auth/idp/saml2/logout">
  <saml:Issuer>myorg</saml:Issuer>
  <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">me@myorg</saml:NameID>
</samlp:LogoutRequest>

I am using my SP entity ID for Issuer. I also tried using it for NameID SPNameQualifier. My Redirect and POST logic work for AuthnRequest. This SLO is working with OneLogin.

The error I get back is:

We are unable to log you out. Please contact your administrator for
  more information.

I can not find any relevant log entries.


问:
When testing in main function, it goes wrong in SpringMVC configuration
I just want to test in main function about a small spring application, but it goes wrong seemingly in SpringMVC configuration .

This is my SpringMVC configuration in spring/spring-mvc.xml file:

```<code><mvc:resources mapping="/BasePlu/**" location="classpath:/static/BasePlu/" />
<mvc:resources mapping="/Lib/**" location="classpath:/static/Lib/" />

<bean id="natureRepository" class="com.autumnframework.blog.repository.NatureRepositoryImpl">
</bean>
</code>```

This is my test code in Test.java file:

```<code>public static void main(String[] args) {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:/spring/spring-mvc.xml");

    Repository repository = context.getBean(NatureRepositoryImpl.class);
    System.out.println("4. " + repository.getAllObjects());
}
</code>```

The wrong detail like below:

```<code>Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [static/BasePlu/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@43bd930a]]] does not run in a WebApplicationContext but in: org.springframework.context.support.ClassPathXmlApplicationContext@1a86f2f1: startup date [Wed Nov 15 10:31:23 CST 2017]; root of context hierarchy
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1589)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:554)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at Test.main(Test.java:26)
Caused by: java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [static/BasePlu/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@43bd930a]]] does not run in a WebApplicationContext but in: org.springframework.context.support.ClassPathXmlApplicationContext@1a86f2f1: startup date [Wed Nov 15 10:31:23 CST 2017]; root of context hierarchy
at org.springframework.web.context.support.WebApplicationObjectSupport.getWebApplicationContext(WebApplicationObjectSupport.java:112)
at org.springframework.web.context.support.WebApplicationObjectSupport.getServletContext(WebApplicationObjectSupport.java:128)
at org.springframework.web.servlet.resource.ResourceHttpRequestHandler.initContentNegotiationStrategy(ResourceHttpRequestHandler.java:306)
at org.springframework.web.servlet.resource.ResourceHttpRequestHandler.afterPropertiesSet(ResourceHttpRequestHandler.java:268)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1648)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1585)
... 12 more
</code>```

I comment the two lines in spring/spring-mvc.xml file:

```<code><!--<mvc:resources mapping="/BasePlu/**" location="classpath:/static/BasePlu/" />-->
<!--<mvc:resources mapping="/Lib/**" location="classpath:/static/Lib/" />-->

<bean id="natureRepository" class="com.autumnframework.blog.repository.NatureRepositoryImpl">
</bean>
</code>```

It can run successfully, but I don't know why it can run successfully in this way.

答:
The two MVC resources need to be run in a WebApplicationContext but you are running it within a ClassPathXmlApplicationContext which doesn't implement the WebApplicationContext. The error message in the stack trace states this:

```<code>Caused by: java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [static/BasePlu/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@43bd930a]]] does not run in a WebApplicationContext but in: org.springframework.context.support.ClassPathXmlApplicationContext@1a86f2f1: startup date [Wed Nov 15 10:31:23 CST 2017]; root of context hierarchy
</code>```

I haven't tried creating a WebApplicationContext before within a main but you could attempt to use XmlWebApplicationContext instead and see if you have better luck.

If you are just looking for a way to test other spring functionality outside of MVC enabled stuff then you could do as you did and comment out the mvc resources or have two XML configurations. One for your web app and one for the main app.

Body:
I just want to test in main function about a small spring application, but it goes wrong seemingly in SpringMVC configuration .

This is my SpringMVC configuration in spring/spring-mvc.xml file:

<mvc:resources mapping="/BasePlu/**" location="classpath:/static/BasePlu/" />
<mvc:resources mapping="/Lib/**" location="classpath:/static/Lib/" />

<bean id="natureRepository" class="com.autumnframework.blog.repository.NatureRepositoryImpl">
</bean>

This is my test code in Test.java file:

public static void main(String[] args) {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:/spring/spring-mvc.xml");

    Repository repository = context.getBean(NatureRepositoryImpl.class);
    System.out.println("4. " + repository.getAllObjects());
}

The wrong detail like below:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [static/BasePlu/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@43bd930a]]] does not run in a WebApplicationContext but in: org.springframework.context.support.ClassPathXmlApplicationContext@1a86f2f1: startup date [Wed Nov 15 10:31:23 CST 2017]; root of context hierarchy
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1589)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:554)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at Test.main(Test.java:26)
Caused by: java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [static/BasePlu/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@43bd930a]]] does not run in a WebApplicationContext but in: org.springframework.context.support.ClassPathXmlApplicationContext@1a86f2f1: startup date [Wed Nov 15 10:31:23 CST 2017]; root of context hierarchy
at org.springframework.web.context.support.WebApplicationObjectSupport.getWebApplicationContext(WebApplicationObjectSupport.java:112)
at org.springframework.web.context.support.WebApplicationObjectSupport.getServletContext(WebApplicationObjectSupport.java:128)
at org.springframework.web.servlet.resource.ResourceHttpRequestHandler.initContentNegotiationStrategy(ResourceHttpRequestHandler.java:306)
at org.springframework.web.servlet.resource.ResourceHttpRequestHandler.afterPropertiesSet(ResourceHttpRequestHandler.java:268)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1648)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1585)
... 12 more

I comment the two lines in spring/spring-mvc.xml file:

<bean id="natureRepository" class="com.autumnframework.blog.repository.NatureRepositoryImpl">
</bean>

It can run successfully, but I don't know why it can run successfully in this way.

Body:
The two MVC resources need to be run in a WebApplicationContext but you are running it within a ClassPathXmlApplicationContext which doesn't implement the WebApplicationContext. The error message in the stack trace states this:

Caused by: java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [static/BasePlu/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@43bd930a]]] does not run in a WebApplicationContext but in: org.springframework.context.support.ClassPathXmlApplicationContext@1a86f2f1: startup date [Wed Nov 15 10:31:23 CST 2017]; root of context hierarchy

I haven't tried creating a WebApplicationContext before within a main but you could attempt to use XmlWebApplicationContext instead and see if you have better luck.

If you are just looking for a way to test other spring functionality outside of MVC enabled stuff then you could do as you did and comment out the mvc resources or have two XML configurations. One for your web app and one for the main app.


答:
This works:

```<code>>>> class Book():
...     def __init__(self,name,description):
...         self.name = name
...         self.description = description
...
>>> class Player:
...     def __init__(self,inventory,hp):
...         self.inventory = inventory
...         self.hp = hp
...
>>> b = Book('myname', 'mydesc')
>>> p = Player([b], 'hp')
>>> b in p.inventory
True
</code>```

This returns False because it is a different instance of Book:

```<code>>>> c = Book('myname', 'mydesc')
>>> c in p.inventory
False
</code>```

Title: Checking values in a class list

Body:
This works:

>>> class Book():
...     def __init__(self,name,description):
...         self.name = name
...         self.description = description
...
>>> class Player:
...     def __init__(self,inventory,hp):
...         self.inventory = inventory
...         self.hp = hp
...
>>> b = Book('myname', 'mydesc')
>>> p = Player([b], 'hp')
>>> b in p.inventory
True

This returns False because it is a different instance of Book:

>>> c = Book('myname', 'mydesc')
>>> c in p.inventory
False


问:
How can I implement a legend like the attached in victory?

I am using victory to create charts, but VictoryLegend does not provide such kind of legend. Is there any existing react Legend component that can be used directly?

答:
From a brief look at the docs it looks like victory does provide legends, read more here

Here's a simple implementation from their docs:

```<code><VictoryLegend x={125} y={50}
  title="Legend"
  centerTitle
  orientation="vertical"
  gutter={20}
  style={{ border: { stroke: "black" }, title: {fontSize: 20 } }}
  data={[
    { name: "One", symbol: { fill: "tomato", type: "square" } },
    { name: "Two", symbol: { fill: "orange", type: "square" } },
    { name: "Three", symbol: { fill: "gold", type: "square" } }
  ]}
/>
</code>```

To create square shaped points specify type "square", other options are listed here.

You can choose "circle", "diamond", "plus", "square", "star",
  "triangleDown", "triangleUp"

Body:
From a brief look at the docs it looks like victory does provide legends, read more here

Here's a simple implementation from their docs:

<VictoryLegend x={125} y={50}
  title="Legend"
  centerTitle
  orientation="vertical"
  gutter={20}
  style={{ border: { stroke: "black" }, title: {fontSize: 20 } }}
  data={[
    { name: "One", symbol: { fill: "tomato", type: "square" } },
    { name: "Two", symbol: { fill: "orange", type: "square" } },
    { name: "Three", symbol: { fill: "gold", type: "square" } }
  ]}
/>

To create square shaped points specify type "square", other options are listed here.

You can choose "circle", "diamond", "plus", "square", "star",
  "triangleDown", "triangleUp"


问:
Promise resolves before forEach loop completes
I'm building my first CRUD (library) application and recently learned about promises as a means to avoid deeply-nested callbacks. I'm attempting to seed my DB with some data each time the server starts, but I seem to be missing something conceptually.

I have four objects in a bookData array that I want to iterate over and save to the DB using Mongoose:

function seedBooks() {
    return new Promise(function(resolve,reject){
        bookData.forEach(function(seed){
            Book.create(seed, function(err, newBook){
                if(err) {
                    reject(err);
                }
            });
        });
        resolve();
    });
}```
</div>
</div>
</p>

<p>This function is one of a few that I am attempting to chain together, which is why I'm using promises. But I'm finding that <code>seedBooks()</code> resolves with anywhere between 1 and 4 of the sample books created,  </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function seedDB() {
    removeAllBooks()
    .then(function(){
        return removeAllUsers();
    })
    .then(function(){
        return seedUsers();
    })
    .then(function(){
        return seedBooks();
    })
    .then(function(){
        return seedBookInstances();
    });
}</code>```

Am I understanding or using promises & resolve incorrectly? Any help is appreciated. Thanks!

答:
You are resolving your Promise synchronously, right after you started your  forEached requests, which are async. You may try the following approach instead:

```<code>function seedBooks() {
    return new Promise(function(resolve,reject){
        var count = 0, length = bookData.length;
        bookData.forEach(function(seed){
            Book.create(seed, function(err, newBook){
                if(err) {
                    reject(err);
                    return;
                }
                if(count++ >= length ) {
                  resolve();
                }
            });
        });
    });
}
</code>```

Here the Promise is being resolved only after all async requests are done.

Another option would be just to use Promise.all. In that approach you need to promisify all your requests in the loop, return an array of Promises and then call Promise.all(_seedBooks()).then(), where _seedBook returns an array of Promises:

```<code>function _seedBooks() {
    return bookData.map(function(seed) {
        return new Promise(function(resolve, reject) {
            Book.create(seed, function(err, newBook) {
                if(err) {
                    reject(err);
                    return;
                }
                resolve(newBook);
            });
        });
    });
}

Promise.all(_seedBooks())
.then(function(result) { /* result is the array of newBook objects */ })
.catch(function(error) { /* error is the first rejected err */ })
</code>```

Body:
I'm building my first CRUD (library) application and recently learned about promises as a means to avoid deeply-nested callbacks. I'm attempting to seed my DB with some data each time the server starts, but I seem to be missing something conceptually.

I have four objects in a bookData array that I want to iterate over and save to the DB using Mongoose:

function seedBooks() {
    return new Promise(function(resolve,reject){
        bookData.forEach(function(seed){
            Book.create(seed, function(err, newBook){
                if(err) {
                    reject(err);
                }
            });
        });
        resolve();
    });
}

This function is one of a few that I am attempting to chain together, which is why I'm using promises. But I'm finding that seedBooks() resolves with anywhere between 1 and 4 of the sample books created,

function seedDB() {
    removeAllBooks()
    .then(function(){
        return removeAllUsers();
    })
    .then(function(){
        return seedUsers();
    })
    .then(function(){
        return seedBooks();
    })
    .then(function(){
        return seedBookInstances();
    });
}

Am I understanding or using promises & resolve incorrectly? Any help is appreciated. Thanks!

Body:
You are resolving your Promise synchronously, right after you started your  forEached requests, which are async. You may try the following approach instead:

function seedBooks() {
    return new Promise(function(resolve,reject){
        var count = 0, length = bookData.length;
        bookData.forEach(function(seed){
            Book.create(seed, function(err, newBook){
                if(err) {
                    reject(err);
                    return;
                }
                if(count++ >= length ) {
                  resolve();
                }
            });
        });
    });
}

Here the Promise is being resolved only after all async requests are done.

Another option would be just to use Promise.all. In that approach you need to promisify all your requests in the loop, return an array of Promises and then call Promise.all(_seedBooks()).then(), where _seedBook returns an array of Promises:

function _seedBooks() {
    return bookData.map(function(seed) {
        return new Promise(function(resolve, reject) {
            Book.create(seed, function(err, newBook) {
                if(err) {
                    reject(err);
                    return;
                }
                resolve(newBook);
            });
        });
    });
}

Promise.all(_seedBooks())
.then(function(result) { /* result is the array of newBook objects */ })
.catch(function(error) { /* error is the first rejected err */ })


问:
AWS CloudFormation - Add New Certificate to an existing listener
What I have is one platform stack, and possibly multiple web application stacks (each represent one web application).  The platform stack deploys an ECS platform that allows hosting multiple web applications, but doesn't actually have any web applications.  It's just a platform.  Then, each web application stack represents a web application.

One of the HTTPS listeners I have in my platform stack template is this.  Basically I have an HTTPS listener on port 443, and will carry one default certificate (by requirement you will need at least one certificate to create https listener):

```<code>"BsAlbListenerHttps": {
  "Type": "AWS::ElasticLoadBalancingV2::Listener",
  "Properties": {
    "Certificates": [{
      "CertificateArn": {
        "Ref": "BsCertificate1"
      }
    }],
    ...
    "Port": "443",
    "Protocol": "HTTPS"
  }
},
...
</code>```

Now, let's say if I want to create a new web application (eg. www.example.com), I deploy the web application stack, specify some parameters, and obviously, I'll have to make a bunch of new resources.  But at the same time, I will have to modify the current "BsAlbListenerHttps".

I'm able to import the current listener (using Imports and Exports) into my web application stack.  But what I want to do is also add a new certificate for www.example.com to the listener.

I've tried looking around but failed to find any answer.

Does anyone know how to do this?  Your help is appreciated.  Thank you!

答:
What I do in similar cases, is to use only one certificate for the entire region, and add domains to it as I add apps/listeners that are on different domains.  I also do this per environment, so I have a staging cert and a production cert in 2 different templates. But for each you would define a standalone cert stack, called for example, certificate-production.json, but use the stack name as 'certificate' so that regardless of the environment, the stack reference is consistent:

```<code>{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Description" : "SSL certificates for production V2",

  "Resources" : {
    "Certificate" : {
      "Type": "AWS::CertificateManager::Certificate",
      "Properties": {
        "DomainName": "*.example.com",
        "SubjectAlternativeNames" : [ "*.example2.com","*.someotherdomain.com" ]
      }
    }
  },

  "Outputs": {
    "CertificateId" : {
        "Value" : {"Ref":"Certificate"},
        "Description" : "Certificate ID",
        "Export" : {  "Name" : {"Fn::Sub": "${AWS::StackName}-CertificateId" }}
    }
  }
}
</code>```

As you can see by using the SubjectAlternativeNames property, this certificate will serve 3 wild card domains. This way I can update the domains as I add services, and rerun the stack. The dependent listeners are not changed in anyway - they always refer to the single app certificate in the region.

One caveat: When you update a cert in CloudFormation, it will email all host administrtors on the given domain (hostmaster@example.com etc.). Each domain will get a confirmation email, and each email has to be confirmed again. If all the domains are not confirmed in this way, then the stack will fail to create/update.

Using this technique, I can manage SSL for all my apps without any trouble, while making it easy to add new ssl endpoints for new domains.

I create the certificate stack right after the main VPC stack, so all later stacks can refer to the certificate id defined here via an export.

Body:
What I have is one platform stack, and possibly multiple web application stacks (each represent one web application).  The platform stack deploys an ECS platform that allows hosting multiple web applications, but doesn't actually have any web applications.  It's just a platform.  Then, each web application stack represents a web application.

One of the HTTPS listeners I have in my platform stack template is this.  Basically I have an HTTPS listener on port 443, and will carry one default certificate (by requirement you will need at least one certificate to create https listener):

"BsAlbListenerHttps": {
  "Type": "AWS::ElasticLoadBalancingV2::Listener",
  "Properties": {
    "Certificates": [{
      "CertificateArn": {
        "Ref": "BsCertificate1"
      }
    }],
    ...
    "Port": "443",
    "Protocol": "HTTPS"
  }
},
...

Now, let's say if I want to create a new web application (eg. www.example.com), I deploy the web application stack, specify some parameters, and obviously, I'll have to make a bunch of new resources.  But at the same time, I will have to modify the current "BsAlbListenerHttps".

I'm able to import the current listener (using Imports and Exports) into my web application stack.  But what I want to do is also add a new certificate for www.example.com to the listener.

I've tried looking around but failed to find any answer.

Does anyone know how to do this?  Your help is appreciated.  Thank you!

Body:
What I do in similar cases, is to use only one certificate for the entire region, and add domains to it as I add apps/listeners that are on different domains.  I also do this per environment, so I have a staging cert and a production cert in 2 different templates. But for each you would define a standalone cert stack, called for example, certificate-production.json, but use the stack name as 'certificate' so that regardless of the environment, the stack reference is consistent:

{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Description" : "SSL certificates for production V2",

  "Resources" : {
    "Certificate" : {
      "Type": "AWS::CertificateManager::Certificate",
      "Properties": {
        "DomainName": "*.example.com",
        "SubjectAlternativeNames" : [ "*.example2.com","*.someotherdomain.com" ]
      }
    }
  },

  "Outputs": {
    "CertificateId" : {
        "Value" : {"Ref":"Certificate"},
        "Description" : "Certificate ID",
        "Export" : {  "Name" : {"Fn::Sub": "${AWS::StackName}-CertificateId" }}
    }
  }
}

As you can see by using the SubjectAlternativeNames property, this certificate will serve 3 wild card domains. This way I can update the domains as I add services, and rerun the stack. The dependent listeners are not changed in anyway - they always refer to the single app certificate in the region.

One caveat: When you update a cert in CloudFormation, it will email all host administrtors on the given domain (hostmaster@example.com etc.). Each domain will get a confirmation email, and each email has to be confirmed again. If all the domains are not confirmed in this way, then the stack will fail to create/update.

Using this technique, I can manage SSL for all my apps without any trouble, while making it easy to add new ssl endpoints for new domains.

I create the certificate stack right after the main VPC stack, so all later stacks can refer to the certificate id defined here via an export.


问:
Parameter to disable Azkaban job by default
Given the following Azkaban configuration that has 1 flow containing 3 jobs, how do I disable Job2 by default? Is there a parameter/configuration for that?

I know that I could go in the UI and disable the job manually. However, I'd like to have the Job2 disabled by default and possibly enable it from the UI only when needed.

```<code>hadoop {

  def input = "..."

  workflow('MyWorkflow') {

    hadoopJavaJob('Job1') {
      uses 'my.package.Job1Runner'

      reads files: [ ... ]
      writes files: [ ... ]
    }

    hadoopJavaJob('Job2') {
      uses 'my.package.Job2Runner'
      depends 'Job1'

      reads files: [ ... ]
      writes files: [ ... ]
    }

    hadoopJavaJob('Job3') {
      uses 'my.package.Job3Runner'
      depends 'Job2'

      reads files: [ ... ]
      writes files: [ ... ]
    }

    targets 'Job3'
  }
}
</code>```

答: You can use the optional disabled parameter. See "Execute A Flow" section of the documentation.

Body:
Given the following Azkaban configuration that has 1 flow containing 3 jobs, how do I disable Job2 by default? Is there a parameter/configuration for that?

I know that I could go in the UI and disable the job manually. However, I'd like to have the Job2 disabled by default and possibly enable it from the UI only when needed.

hadoop {

  def input = "..."

  workflow('MyWorkflow') {

    hadoopJavaJob('Job1') {
      uses 'my.package.Job1Runner'

      reads files: [ ... ]
      writes files: [ ... ]
    }

    hadoopJavaJob('Job2') {
      uses 'my.package.Job2Runner'
      depends 'Job1'

      reads files: [ ... ]
      writes files: [ ... ]
    }

    hadoopJavaJob('Job3') {
      uses 'my.package.Job3Runner'
      depends 'Job2'

      reads files: [ ... ]
      writes files: [ ... ]
    }

    targets 'Job3'
  }
}


问:
Make a unity game look like it has crashed C#
I want to make my Unity game look like it has crashed (Unresponsive Application Crash, Not a code exception crash).

There probably is some function in the Windows API you can call to emulate this.

I have also seen a game called "Pony Island" do this before, so it certainly is possible. However I don't own a copy nor can I decompile a steam game.

If there is a way to actually hang the program while still being able to bring it back at anytime that solution is preferable, this seems to be unlikely.

To be clear, I want it to look legitimate, so I would prefer the windows API be used to change the window color and generate a pop-up, instead of having them in unity as GUI objects or something similar. I also don't really care about cross-compatibility because the Mac API appears to be hard to implement and even harder to test (on a Windows machine), and most likely won't be compatible with as many hacky features as the Windows API is.

答:
Best way to do this safely would be to run some script setting time.timeScale = 0 - effectively 'freezing' the game, while simultaneously playing the windows 'error' sound effect.

(Note: You may have to also pause audio sources and particle emitters from this script, I've not used timescale before an am unsure if it affects these)

I know you suggested against using UGUI but an image with no source placed over the entire screen, with it's colour and alpha tweaked could very easily emulate the 'frozen screen' too.

You could also look into ways to forcibly 'restore'/change fullscreen mode of the window (if it is played in full screen)