问:
Unity 3D Stop spawn particles after hit a wall
I'm doing a work for school: a game like bomberman.

My problem is when a bomb explodes, the particles should stop spawning after the wall. Here an image of the problem:

I have this code here to spawn the bomb and start the coroutine to spawn the particles in every diresction:

```<code>void Explode()
    {
        Instantiate(explosionPrefab, transform.position, Quaternion.identity);
        StartCoroutine(CreateExplosions(Vector3.forward));
        StartCoroutine(CreateExplosions(Vector3.right));
        StartCoroutine(CreateExplosions(Vector3.back));
        StartCoroutine(CreateExplosions(Vector3.left));
        GetComponent<MeshRenderer>().enabled = false;
        exploded = true;
        GetComponent<CapsuleCollider>().enabled = false;
        Invoke("desativar_particulas", 0.4f);
        Destroy(gameObject, .45f);

      }
</code>```

And here is my coroutine to spawn the particles:

```<code> private IEnumerator CreateExplosions(Vector3 direction)
{
    for (int i = 1; i < 3; i++)
    {

        RaycastHit hit;

        Physics.Raycast(transform.position + new Vector3(0, .5f, 0), direction * 10, out hit, i, levelMask);

        if (!hit.collider)
        {
                Instantiate(explosionPrefab, transform.position + (i * direction * 10), explosionPrefab.transform.rotation);
        }

        else
        {
            break;
        }

        yield return new WaitForSeconds(.05f);
    }
}
</code>```

That if statement should do the trick: the wall have a box component collider and the particle have a box collider component as a trigger.
Am I missing something? Please help, thank you.

答:
In this:
Physics.Raycast(transform.position + new Vector3(0, .5f, 0), direction * 10, out hit, i, levelMask)
It looks like you're incrementing the distance of each cast to reach the next block each time (smart move, by the way. I would have done this in a much more convoluted way.), but only going to a distance as high as 3, whereas in all the references to the location of the explosions, you've magnified it by ten.
Did you perhaps mean to do something like this:

```<code>Physics.Raycast(transform.position + new Vector3(0, .5f, 0), direction, out hit, i * 10, levelMask)
</code>```

Wherein the direction of the raycast is simply the direction you input to the function and the distance is magnified by ten?

Body:
I'm doing a work for school: a game like bomberman.

My problem is when a bomb explodes, the particles should stop spawning after the wall. Here an image of the problem:

I have this code here to spawn the bomb and start the coroutine to spawn the particles in every diresction:

void Explode()
    {
        Instantiate(explosionPrefab, transform.position, Quaternion.identity);
        StartCoroutine(CreateExplosions(Vector3.forward));
        StartCoroutine(CreateExplosions(Vector3.right));
        StartCoroutine(CreateExplosions(Vector3.back));
        StartCoroutine(CreateExplosions(Vector3.left));
        GetComponent<MeshRenderer>().enabled = false;
        exploded = true;
        GetComponent<CapsuleCollider>().enabled = false;
        Invoke("desativar_particulas", 0.4f);
        Destroy(gameObject, .45f);

      }

And here is my coroutine to spawn the particles:

 private IEnumerator CreateExplosions(Vector3 direction)
{
    for (int i = 1; i < 3; i++)
    {

        RaycastHit hit;

        Physics.Raycast(transform.position + new Vector3(0, .5f, 0), direction * 10, out hit, i, levelMask);

        if (!hit.collider)
        {
                Instantiate(explosionPrefab, transform.position + (i * direction * 10), explosionPrefab.transform.rotation);
        }

        else
        {
            break;
        }

        yield return new WaitForSeconds(.05f);
    }
}

That if statement should do the trick: the wall have a box component collider and the particle have a box collider component as a trigger.
Am I missing something? Please help, thank you.

Body:
In this:
Physics.Raycast(transform.position + new Vector3(0, .5f, 0), direction * 10, out hit, i, levelMask)
It looks like you're incrementing the distance of each cast to reach the next block each time (smart move, by the way. I would have done this in a much more convoluted way.), but only going to a distance as high as 3, whereas in all the references to the location of the explosions, you've magnified it by ten.
Did you perhaps mean to do something like this:

Physics.Raycast(transform.position + new Vector3(0, .5f, 0), direction, out hit, i * 10, levelMask)

Wherein the direction of the raycast is simply the direction you input to the function and the distance is magnified by ten?


来源: stackexchange

问:
How to run a block of code after each @test, no matter if the test is @Disabled or not?
Basically I would like to add an entry to my Extent report for "Skipped Tests". I understand I can use @AfterEach, however I see that the @AfterEach code block does not get executed for @Disabled Test in Junit5.

I tried using TestWatcher interface and overrided the method testDisabled like below:

```<code>package utils;

import java.util.Optional;

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestWatcher;

public class MyTestWatcher implements TestWatcher {
                public static String testStatus;
                public static String testCaseName;
    @Override
    public void testAborted(ExtensionContext Context, Throwable throwable) {
                testStatus = "Aborted";
                testCaseName = Context.getDisplayName();
                System.out.println("Test Aborted: " + Context.getDisplayName());
                }

    @Override
    public void testDisabled(ExtensionContext Context, Optional<String> optional) {
                testStatus = "Skipped";
                testCaseName = Context.getDisplayName();
                System.out.println("Test Skipped: " + Context.getDisplayName());
                }

    @Override
    public void testFailed(ExtensionContext Context, Throwable throwable) {
                testStatus = "Failed";
                testCaseName = Context.getDisplayName();
               System.out.println("Test Failed: " + Context.getDisplayName());
}

    @Override
    public void testSuccessful(ExtensionContext Context) {
                testStatus = "Passed";
                testCaseName = Context.getDisplayName();
                System.out.println("Test Passed: " + Context.getDisplayName());
    }

}
</code>```

Based on the 'testStatus' and 'testCaseName' variables, which are set in the testDisabled() method above, I would like to run a block of code from my test class, to add an entry to my Extent report saying which test case was skipped.

答:
If I understood your question correctly you just need to apply TestWatcher to your test to solve your problem. With JUnit 5 you can use @ExtendsWith annotation. Complete example will be:

```<code>@ExtendWith(MyTestWatcher.class)
class MyTest {

  @Test
  void test() {
    System.out.println("inside active test");
  }

  @Test
  @Disabled
  void testDisabled() {
    System.out.println("inside disabled test");
  }

}
</code>```

With output:

```<code>inside active test
Test Passed: test()
Test Skipped: testDisabled()
</code>```

Tested with JUnit 5.4.2

ContentLicense: CC BY-SA 4.0

Body:
Basically I would like to add an entry to my Extent report for "Skipped Tests". I understand I can use @AfterEach, however I see that the @AfterEach code block does not get executed for @Disabled Test in Junit5.

I tried using TestWatcher interface and overrided the method testDisabled like below:

package utils;

import java.util.Optional;

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestWatcher;

public class MyTestWatcher implements TestWatcher {
                public static String testStatus;
                public static String testCaseName;
    @Override
    public void testAborted(ExtensionContext Context, Throwable throwable) {
                testStatus = "Aborted";
                testCaseName = Context.getDisplayName();
                System.out.println("Test Aborted: " + Context.getDisplayName());
                }

    @Override
    public void testDisabled(ExtensionContext Context, Optional<String> optional) {
                testStatus = "Skipped";
                testCaseName = Context.getDisplayName();
                System.out.println("Test Skipped: " + Context.getDisplayName());
                }

    @Override
    public void testFailed(ExtensionContext Context, Throwable throwable) {
                testStatus = "Failed";
                testCaseName = Context.getDisplayName();
               System.out.println("Test Failed: " + Context.getDisplayName());
}

    @Override
    public void testSuccessful(ExtensionContext Context) {
                testStatus = "Passed";
                testCaseName = Context.getDisplayName();
                System.out.println("Test Passed: " + Context.getDisplayName());
    }

}

Based on the 'testStatus' and 'testCaseName' variables, which are set in the testDisabled() method above, I would like to run a block of code from my test class, to add an entry to my Extent report saying which test case was skipped.

Body:
If I understood your question correctly you just need to apply TestWatcher to your test to solve your problem. With JUnit 5 you can use @ExtendsWith annotation. Complete example will be:

@ExtendWith(MyTestWatcher.class)
class MyTest {

  @Test
  void test() {
    System.out.println("inside active test");
  }

  @Test
  @Disabled
  void testDisabled() {
    System.out.println("inside disabled test");
  }

}

With output:

inside active test
Test Passed: test()
Test Skipped: testDisabled()

Tested with JUnit 5.4.2


问:
Matlab - Recursive function to browse and modify a structure
I have some troubles with a Matlab recursive function that I created in order to browse a data structure and modify each field that contains a path starting by a keyword.

My function that replaces a relative path starting by a keyword by an absolute path works perfectly fine and has already been tested (for instance, '$KEYWORD\Desktop\Documents' will be replaced by 'C:\Users\Name\Desktop\Documents')

I am trying to apply this function to a data structure that contains many (too many) fields, with a recursive function. I want this recursive function to browse my data structure, and as soon as it detects a char parameter starting by $KEYWORD, it changes the value by an absolute path stored in an environment parameter.
Here is my code:

```<code>function newStruct = browse_struct(initStruct)

   fields = fieldnames(initStruct);
   n_fields = length(fields);

   for n = 1 : n_fields
      val = getfield(initStruct, fields{n});
      if isstruct(val)
         browse_struct(val);
      elseif( ischar(val) && val(1)=='$' )
         newVal = replace_keyword(val);
         newStruct = setfield(initStruct, fields{n}, newVal);
      end
   end

end
</code>```

When I run my code in debug mode, I see that my function browses entirely my data structure, and that the fields of interest are being replaced by what I want, but when the run is over, the new structure is identical to initial one. No field has been changed, so in the end I still have relative paths starting by $KEYWORD, while it should be an absolute path instead.

I also tried to replace the line 7 (the one just under the if condition) by:

```<code>newStruct = browse_struct(val)
</code>```

And it doesn't work either, it completely destroys the initial structure.

I don't know how to fix that problem. Can someone help me please? Thanks a lot.

答:
Problem 1: In your function you are applying changes to newStruct but keep using initStruct for new changes, so you are overriding previous changes to newStruct.

Solution: when you pass a struct (or any object) to a function in MATLAB, you pass it by value, so the original struct does not change. You can simply remove newStruct from the function and only work with initStruct.

Problem 2: browse_struct(val); does not change the struct, and newStruct = browse_struct(val); changes the struct to its field.

Solution: Use newStruct = setfield(initStruct, fields{n}, browse_struct(val));

The corrected function:

```<code>function initStruct = browse_struct(initStruct)

    fields = fieldnames(initStruct);
    n_fields = length(fields);

    for n = 1 : n_fields
        val = getfield(initStruct, fields{n});
        if isstruct(val)
            initStruct = setfield(initStruct, fields{n}, browse_struct(val));
        elseif( ischar(val) && val(1)=='$' )
            newVal = replace_keyword(val);
            initStruct = setfield(initStruct, fields{n}, newVal);
        end
    end

end
</code>```

Instead of using getfield and setfield, MATLAB suggests "Use dynamic field names with structures" so you can modify the function like this:

```<code>function initStruct = browse_struct(initStruct)

    fields = fieldnames(initStruct);
    n_fields = length(fields);

    for n = 1 : n_fields
        val = initStruct.(fields{n});
        if isstruct(val)
            initStruct.(fields{n}) = browse_struct(val);
        elseif( ischar(val) && val(1)=='$' )
            newVal = replace_keyword(val);
            initStruct.(fields{n}) = newVal;
        end
    end

end
</code>```

Body:
I have some troubles with a Matlab recursive function that I created in order to browse a data structure and modify each field that contains a path starting by a keyword.

My function that replaces a relative path starting by a keyword by an absolute path works perfectly fine and has already been tested (for instance, '$KEYWORD\Desktop\Documents' will be replaced by 'C:\Users\Name\Desktop\Documents')

I am trying to apply this function to a data structure that contains many (too many) fields, with a recursive function. I want this recursive function to browse my data structure, and as soon as it detects a char parameter starting by $KEYWORD, it changes the value by an absolute path stored in an environment parameter.
Here is my code:

function newStruct = browse_struct(initStruct)

   fields = fieldnames(initStruct);
   n_fields = length(fields);

   for n = 1 : n_fields
      val = getfield(initStruct, fields{n});
      if isstruct(val)
         browse_struct(val);
      elseif( ischar(val) && val(1)=='$' )
         newVal = replace_keyword(val);
         newStruct = setfield(initStruct, fields{n}, newVal);
      end
   end

end

When I run my code in debug mode, I see that my function browses entirely my data structure, and that the fields of interest are being replaced by what I want, but when the run is over, the new structure is identical to initial one. No field has been changed, so in the end I still have relative paths starting by $KEYWORD, while it should be an absolute path instead.

I also tried to replace the line 7 (the one just under the if condition) by:

newStruct = browse_struct(val)

And it doesn't work either, it completely destroys the initial structure.

I don't know how to fix that problem. Can someone help me please? Thanks a lot.

Body:
Problem 1: In your function you are applying changes to newStruct but keep using initStruct for new changes, so you are overriding previous changes to newStruct.

Solution: when you pass a struct (or any object) to a function in MATLAB, you pass it by value, so the original struct does not change. You can simply remove newStruct from the function and only work with initStruct.

Problem 2: browse_struct(val); does not change the struct, and newStruct = browse_struct(val); changes the struct to its field.

Solution: Use newStruct = setfield(initStruct, fields{n}, browse_struct(val));

The corrected function:

function initStruct = browse_struct(initStruct)

    fields = fieldnames(initStruct);
    n_fields = length(fields);

    for n = 1 : n_fields
        val = getfield(initStruct, fields{n});
        if isstruct(val)
            initStruct = setfield(initStruct, fields{n}, browse_struct(val));
        elseif( ischar(val) && val(1)=='$' )
            newVal = replace_keyword(val);
            initStruct = setfield(initStruct, fields{n}, newVal);
        end
    end

end

Instead of using getfield and setfield, MATLAB suggests "Use dynamic field names with structures" so you can modify the function like this:

function initStruct = browse_struct(initStruct)

    fields = fieldnames(initStruct);
    n_fields = length(fields);

    for n = 1 : n_fields
        val = initStruct.(fields{n});
        if isstruct(val)
            initStruct.(fields{n}) = browse_struct(val);
        elseif( ischar(val) && val(1)=='$' )
            newVal = replace_keyword(val);
            initStruct.(fields{n}) = newVal;
        end
    end

end


问:
CORS issues occurs randomly
I am developing Web Api which passes data to mobile Application.My issue is Mobile Application facing CORS issue but randomly.Its working fyn sometimes.

I have already enabled cors by simply writing

[EnableCors(origins: "", headers: "", methods: "*")] in all controllers as public

and
 config.EnableCors();

in WebApiConfig.cs file

[EnableCors(origins: "", headers: "", methods: "*")]

The issue occurs sometime And I need permanant solution .
And May I know if the issue is on client side or serverside.

Help me on this.Thanks in advance.

答:
```<code> var cors = new EnableCorsAttribute("*", "*", "*", "*") { SupportsCredentials = true };
        config.EnableCors(cors);
</code>```

<p>Add this to the WebApiConfig.cs file, you can remove the Cors attribute from the controllers. This should work. </p>

Title: CORS issues occurs randomly

Body:
 var cors = new EnableCorsAttribute("*", "*", "*", "*") { SupportsCredentials = true };
        config.EnableCors(cors);

Add this to the WebApiConfig.cs file, you can remove the Cors attribute from the controllers. This should work.


问:
Make radio buttons checked /unchecked

$("input[type='radio']").each(function() {
  if ($(this).is(":checked")) {
    $(this).css('background', 'blue');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" data="cool" name="cool" checked="checked">
<input type="radio" data="cool" name="cool">
<input type="radio" data="cool" name="cool"></code>```

My approach is to first check if my inputs are :checked and if they are, put some CSS class with the background color. I achieve that, the next thing I want to is to remove that :checked when users click on radio button or any other (better) idea. After the form is submitted, this code checks if inputs are:checked, the problem is when I want to select another radio button I get something like this:

1 and 2 radio buttons are selected, it  should be only 2 :checked

答:
I think the issue with your code is that you are using each event instead of change or click event. It means that you are trying to change the color of your radio button, even before user has performed any action. Read the following code, this will solve the issue of submitting the form and also customizing the radio button:

$(".radio-button").click(function() {
  $(this).addClass("blue-background");
  $(this).siblings().removeClass("blue-background");
  var radioID = $(this).data('radio');
  $('#' + radioID).attr("checked", "checked");
  if ($('#' + radioID).siblings(":checked")) {
    $('#' + radioID).siblings().removeAttr("checked");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.blue-background {
  background-color: blue;
}

input[type='radio'] {
  visibility: hidden;
}

.radio-button {
  height: 15px;
  width: 15px;
  margin: 5px;
  border-radius: 50%;
  display: inline-block;
  border: 1px solid black;
}</code>```

  <input type="radio" id="radio1" data="cool" name="cool" checked="checked">
  <input type="radio" id="radio2" data="cool" name="cool">
  <input type="radio" id="radio3" data="cool" name="cool">

```

I hope this was helpful.

Title: Make radio buttons checked /unchecked

Body:
$("input[type='radio']").each(function() {
  if ($(this).is(":checked")) {
    $(this).css('background', 'blue');
  }
});

<input type="radio" data="cool" name="cool" checked="checked">
<input type="radio" data="cool" name="cool">
<input type="radio" data="cool" name="cool">

My approach is to first check if my inputs are :checked and if they are, put some CSS class with the background color. I achieve that, the next thing I want to is to remove that :checked when users click on radio button or any other (better) idea. After the form is submitted, this code checks if inputs are:checked, the problem is when I want to select another radio button I get something like this:

1 and 2 radio buttons are selected, it  should be only 2 :checked

Body:
I think the issue with your code is that you are using each event instead of change or click event. It means that you are trying to change the color of your radio button, even before user has performed any action. Read the following code, this will solve the issue of submitting the form and also customizing the radio button:

$(".radio-button").click(function() {
  $(this).addClass("blue-background");
  $(this).siblings().removeClass("blue-background");
  var radioID = $(this).data('radio');
  $('#' + radioID).attr("checked", "checked");
  if ($('#' + radioID).siblings(":checked")) {
    $('#' + radioID).siblings().removeAttr("checked");
  }
});

.blue-background {
  background-color: blue;
}

input[type='radio'] {
  visibility: hidden;
}

.radio-button {
  height: 15px;
  width: 15px;
  margin: 5px;
  border-radius: 50%;
  display: inline-block;
  border: 1px solid black;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="parent">
  <input type="radio" id="radio1" data="cool" name="cool" checked="checked">
  <input type="radio" id="radio2" data="cool" name="cool">
  <input type="radio" id="radio3" data="cool" name="cool">
  <div class="radio-button" data-radio="radio1"></div>
  <div class="radio-button" data-radio="radio2"></div>
  <div class="radio-button" data-radio="radio3"></div>
</div>

I hope this was helpful.


问:
Is it wrong to use * when reseting Margins/Padding in CSS?
Should the following be shunned, or praised for its simplicity?

For the record, I use it in every site I build, but I've noticed it's not present in many main-stream CSS-reset frameworks — is there a reason they don't use it too?

* { margin: 0; padding: 0; }
```

答:
The universal selector can slow things down quite a bit, especially on some WAP browsers. Just think about it for a second: it matches every single element in the document tree.

Besides, for most elements, you'll go on and specify a margin/padding that is different from 0 anyway. As in, there's no point in resetting them for all elements to begin with.

OwnerDisplayName: Jonathan Sampson

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Jonathan Sampson

OwnerDisplayName: RegDwight

ContentLicense: CC BY-SA 2.5


问:
Starting Tornado with Nginx on Ubuntu 10.04 automatically with domain name
I've managed to set up my nginx.conf file and it looks like this:

```<code>root       www www;

worker_processes 1;

worker_rlimit_nofile 8192;

events {

  worker_connections  8000;

  accept_mutex off;

}

error_log  logs/error.log;
pid        logs/nginx.pid;

http {
  # Set the mime-types
  include       mime.types;

  # And the fallback mime-type
  default_type  application/octet-stream;

  # Format for our log files
  log_format   main '$remote_addr - $remote_user [$time_local]  $status '
    '"$request" $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';

  # Click tracking!
  access_log   logs/access.log  main;

  # ~2 seconds is often enough for HTML/CSS, but connections in
  # Nginx are cheap, so generally it's safe to increase it
  keepalive_timeout  5;

  # You usually want to serve static files with Nginx
  sendfile on;

  tcp_nopush on; # off may be better for Comet/long-poll stuff
  tcp_nodelay off; # on may be better for Comet/long-poll stuff

  # Enable Gzip
  gzip  on;
  gzip_http_version 1.0;
  gzip_comp_level 2;
  gzip_min_length 1100;
  gzip_buffers     4 8k;
  gzip_proxied any;
  gzip_types text/html text/plain text/xml application/xml application/xml+rss text/css text/javascript application/javascript application/json;

  gzip_static on;

  gzip_proxied        expired no-cache no-store private auth;
  gzip_disable        "MSIE [1-6]\.";
  gzip_vary           on;

  server {
    # listen 80 default deferred; # for Linux
    # listen 80 default accept_filter=httpready; # for FreeBSD
    listen 80 default;

    # e.g. "localhost" to accept all connections, or "www.example.com"
    # to handle the requests for "example.com" (and www.example.com)
    server_name _;

    # Path for static files
    root /srv/www/example.com/public_html/src/static;

    expires 1M;

    # Static assets
    location ~* ^.+\.(manifest)$ {
      expires -1D;
      root   /srv/www/example.com/public_html/src/;
      access_log /srv/www/example.com/logs/static.logs;
    }

    location ~* ^.+\.(ico|ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|css|rss|atom|js|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
      # Only set expires max IFF the file is a static file and exists
      if (-f $request_filename) {
        expires max;
        root   /srv/www/example.come/public_html/src/static;
        access_log /srv/www/example.com/logs/static.logs;
      }
    }
  }
}
</code>```

My questions for nginx file is:
1) I would want to host my application with the domain name : www.example.com, which line of the nginx.conf file do i change?

My nginx.conf file is found in the same folder as app.py.

2) When I was trying to start nginx by typing /etc/init.d/nginx start, I received the following error message:

Error Message:

```<code>Starting nginx: [emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)
[emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)
[emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)
[emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)
[emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)
[emerg]: still could not bind()
nginx.
</code>```

I have not done any configuration to the nginx.conf file found at /etc/nginx
My questions for this part are:
3)  How do i fix the error?
4) How do i start nginx automatically?

I've tried running my Tornado app by typing
python app.py
Than I navigate to http://xxx.xx.xxx.xxx:8888 , and my app works correctly.

However, should I close my terminal ( killing the process ) , my tornado app is no longer active.

My question here is:
5) how do i start tornado app automatically?
6) How do i run tornado on a domain name?

Thank you all for your kind patience.

Best Regards.

答:
1) Change the server_name.

2) You probably have Apache running.

3) Stop the service (using something like service httpd stop) and then start nginx.

4) Try the following commands:

```<code>$ chkconfig httpd off
$ chkconfig --add nginx
$ chkconfig nginx on
$ service nginx start
</code>```

5) Look at using supervisor for running python apps

6) Check out the nginx wiki for information on reverse proxying; nginx handles requests to the domain and passes those requests to your tornado backend.

Body:
I've managed to set up my nginx.conf file and it looks like this:

root       www www;

worker_processes 1;

worker_rlimit_nofile 8192;

events {

  worker_connections  8000;

  accept_mutex off;

}

error_log  logs/error.log;
pid        logs/nginx.pid;

http {
  # Set the mime-types
  include       mime.types;

  # And the fallback mime-type
  default_type  application/octet-stream;

  # Format for our log files
  log_format   main '$remote_addr - $remote_user [$time_local]  $status '
    '"$request" $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';

  # Click tracking!
  access_log   logs/access.log  main;

  # ~2 seconds is often enough for HTML/CSS, but connections in
  # Nginx are cheap, so generally it's safe to increase it
  keepalive_timeout  5;

  # You usually want to serve static files with Nginx
  sendfile on;

  tcp_nopush on; # off may be better for Comet/long-poll stuff
  tcp_nodelay off; # on may be better for Comet/long-poll stuff

  # Enable Gzip
  gzip  on;
  gzip_http_version 1.0;
  gzip_comp_level 2;
  gzip_min_length 1100;
  gzip_buffers     4 8k;
  gzip_proxied any;
  gzip_types text/html text/plain text/xml application/xml application/xml+rss text/css text/javascript application/javascript application/json;

  gzip_static on;

  gzip_proxied        expired no-cache no-store private auth;
  gzip_disable        "MSIE [1-6]\.";
  gzip_vary           on;

  server {
    # listen 80 default deferred; # for Linux
    # listen 80 default accept_filter=httpready; # for FreeBSD
    listen 80 default;

    # e.g. "localhost" to accept all connections, or "www.example.com"
    # to handle the requests for "example.com" (and www.example.com)
    server_name _;

    # Path for static files
    root /srv/www/example.com/public_html/src/static;

    expires 1M;

    # Static assets
    location ~* ^.+\.(manifest)$ {
      expires -1D;
      root   /srv/www/example.com/public_html/src/;
      access_log /srv/www/example.com/logs/static.logs;
    }

    location ~* ^.+\.(ico|ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|css|rss|atom|js|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
      # Only set expires max IFF the file is a static file and exists
      if (-f $request_filename) {
        expires max;
        root   /srv/www/example.come/public_html/src/static;
        access_log /srv/www/example.com/logs/static.logs;
      }
    }
  }
}

My questions for nginx file is:
1) I would want to host my application with the domain name : www.example.com, which line of the nginx.conf file do i change?

My nginx.conf file is found in the same folder as app.py.

2) When I was trying to start nginx by typing /etc/init.d/nginx start, I received the following error message:

Error Message:

Starting nginx: [emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)
[emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)
[emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)
[emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)
[emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)
[emerg]: still could not bind()
nginx.

I have not done any configuration to the nginx.conf file found at /etc/nginx
My questions for this part are:
3)  How do i fix the error?
4) How do i start nginx automatically?

I've tried running my Tornado app by typing
python app.py
Than I navigate to http://xxx.xx.xxx.xxx:8888 , and my app works correctly.

However, should I close my terminal ( killing the process ) , my tornado app is no longer active.

My question here is:
5) how do i start tornado app automatically?
6) How do i run tornado on a domain name?

Thank you all for your kind patience.

Best Regards.

Body:
1) Change the server_name.

2) You probably have Apache running.

3) Stop the service (using something like service httpd stop) and then start nginx.

4) Try the following commands:

$ chkconfig httpd off
$ chkconfig --add nginx
$ chkconfig nginx on
$ service nginx start

5) Look at using supervisor for running python apps

6) Check out the nginx wiki for information on reverse proxying; nginx handles requests to the domain and passes those requests to your tornado backend.


问:
ERROR: Column not found: 1054 Unknown column 'updated_at' in 'field list'
So basically the error states that i don't have a column called updated_at but i know i dont have it and i dont want to have it. My database table only has the following columns : requester, user_requested, id, status.

this is my model

```<code>class Friendships extends Model
{
    protected $fillable = ['requester', 'user_requested', 'status'];
}

</code>```

this is my profilecontroller

```<code> public function sendRequest($id){
        return Auth::user()->addFriend($id);

  }
</code>```

And this is my friendable.php

```<code>
namespace App\Traits;
use App\Friendships;

trait Friendable{
    public function test(){
        return 'hi' ;
    }

    public function addFriend($id){
        $Friendship = Friendships::create([
                'requester' => $this->id,
                'user_requested' => $id
        ]);

        if($Friendship){
            return $Friendship;
        }
        return  'failed';
    }

}
</code>```

it says that method addFriend isnt found and the create doesnt work apparently because the id isnt found.

答:
By default, Eloquent expects created_at and updated_at columns to exist on your tables. If you do not wish to have these columns automatically managed by Eloquent, set the  $timestamps property on your model to false:

```<code>class Friendships extends Model
{
    public $timestamps = false;
    protected $fillable = ['requester', 'user_requested', 'status'];
}
</code>```

EDIT

fire commands,

```<code>php artisan make:migration modify_friendships_table;
</code>```

Then go to migration file which is generated in database/migrations

Write code in that class,

```<code>Schema::table('friendships', function (Blueprint $table) {
    $table->boolean("status")->default(0)->change();
});
</code>```

save above file, then fire below command

```<code>php artisan migrate
</code>```

And now check, if its working.

Body:
So basically the error states that i don't have a column called updated_at but i know i dont have it and i dont want to have it. My database table only has the following columns : requester, user_requested, id, status.

this is my model

class Friendships extends Model
{
    protected $fillable = ['requester', 'user_requested', 'status'];
}

this is my profilecontroller

 public function sendRequest($id){
        return Auth::user()->addFriend($id);

  }

And this is my friendable.php

namespace App\Traits;
use App\Friendships;

trait Friendable{
    public function test(){
        return 'hi' ;
    }

    public function addFriend($id){
        $Friendship = Friendships::create([
                'requester' => $this->id,
                'user_requested' => $id
        ]);

        if($Friendship){
            return $Friendship;
        }
        return  'failed';
    }

}

it says that method addFriend isnt found and the create doesnt work apparently because the id isnt found.

Body:
By default, Eloquent expects created_at and updated_at columns to exist on your tables. If you do not wish to have these columns automatically managed by Eloquent, set the  $timestamps property on your model to false:

class Friendships extends Model
{
    public $timestamps = false;
    protected $fillable = ['requester', 'user_requested', 'status'];
}

EDIT

fire commands,

php artisan make:migration modify_friendships_table;

Then go to migration file which is generated in database/migrations

Write code in that class,

Schema::table('friendships', function (Blueprint $table) {
    $table->boolean("status")->default(0)->change();
});

save above file, then fire below command

php artisan migrate

And now check, if its working.


问:
How to sor a dictionary by key?
I want to sort my dictionary by key only but I failed.

My dictionary is

```<code>myDic={'a':{},'b':{},'c':{}}

sorted(myDic.items(),reverse=True)
</code>```

but it returns

```<code>{'a': {}, 'c': {}, 'b': {}}
</code>```

but I want {'c': {}, 'b': {}, 'a': {}}
sort by descending order

答:
sorted will always return a list. You can’t have sorted dictionaries as before Python 3.6, dictionaries have no order.

You seem to have forgotten to assign your value to a variable:

```<code>myDic = {{'a':{},'b':{},'c':{}}
sorted_keys = sorted(myDic, reverse=True)
</code>```

I didn’t sort myDic.items() as we only need to sort the keys into a list.

Now when you want to loop over the dictionary ‘in order’, iterate over the list of sorted keys and get the corresponding value from the dictionary:

```<code>for key in sorted_keys:
    print(myDic[key])
</code>```

Title: How to sor a dictionary by key?

Body:
I want to sort my dictionary by key only but I failed.

My dictionary is

myDic={'a':{},'b':{},'c':{}}

sorted(myDic.items(),reverse=True)

but it returns

{'a': {}, 'c': {}, 'b': {}}

but I want {'c': {}, 'b': {}, 'a': {}}
sort by descending order

Body:
sorted will always return a list. You can’t have sorted dictionaries as before Python 3.6, dictionaries have no order.

You seem to have forgotten to assign your value to a variable:

myDic = {{'a':{},'b':{},'c':{}}
sorted_keys = sorted(myDic, reverse=True)

I didn’t sort myDic.items() as we only need to sort the keys into a list.

Now when you want to loop over the dictionary ‘in order’, iterate over the list of sorted keys and get the corresponding value from the dictionary:

for key in sorted_keys:
    print(myDic[key])


问:
update a column when multiple records of another columns of same table matches
I have table as below:

```<code>            Input table:
            RequestNumber            TrackName         Date
            -----------------------------------------------------------
            02209                    Middle         2017-05-28 00:00:00
            0263                     Middle         2017-06-29 00:00:00
            0633                     Middle         2017-09-10 00:00:00
            0762                     Back           2017-06-23 00:00:00
            0762                     Front          2017-06-23 00:00:00
            0762                     Middle         2017-06-23 00:00:00
            01839                    Middle         2017-03-09 00:00:00
</code>```

I need to check, if "RequestNumber" and "Date" is same for "TrackName".
if multiple reacords of "RequestNumber" and "Date" matches then I should update the "TrackName" column as "All three" as below
output example (in this example there are 3 records matching)

```<code>            Output table:
            RequestNumber            TrackName         Date
            -----------------------------------------------------------
            02209                    Middle         2017-05-28 00:00:00
            0263                     Middle         2017-06-29 00:00:00
            0633                     Middle         2017-09-10 00:00:00
            0762                     All three      2017-06-23 00:00:00
            01839                    Middle         2017-03-09 00:00:00
</code>```

To get the above desigred output this is the SQL I have tried. Howveer, its updating all TrackName to All three.

```<code>            UPDATE a
            SET a.[TrackName] = 'All three'
            FROM Table1 as a
            INNER JOIN
            (SELECT [RequestNumber], row_number() OVER (ORDER BY [RequestNumber] DESC) as rowNumber
            FROM Table1 ) drRowNumbers ON drRowNumbers.[RequestNumber] = a.[RequestNumber] and drRowNumbers.[Date] = a.[Date]
</code>```

Hope I have explained this correctly. What am I doing worng? Any query to fix this please?

Note: The records are coming dynamically so can not be hardcoded(if any).

Thanks.

答:
Try This. This will return "All 3" instead of "All Three"-</p>

```<code>SELECT RequestNumber,
CASE
    WHEN COUNT(*) = 1 THEN MAX(TrackName)
    ELSE 'All ' + CAST( COUNT(*) AS VARCHAR)
END TrackName,
Date
FROM your_table
GROUP BY RequestNumber,Date
</code>```

Body:
I have table as below:

            Input table:
            RequestNumber            TrackName         Date
            -----------------------------------------------------------
            02209                    Middle         2017-05-28 00:00:00
            0263                     Middle         2017-06-29 00:00:00
            0633                     Middle         2017-09-10 00:00:00
            0762                     Back           2017-06-23 00:00:00
            0762                     Front          2017-06-23 00:00:00
            0762                     Middle         2017-06-23 00:00:00
            01839                    Middle         2017-03-09 00:00:00

I need to check, if "RequestNumber" and "Date" is same for "TrackName".
if multiple reacords of "RequestNumber" and "Date" matches then I should update the "TrackName" column as "All three" as below
output example (in this example there are 3 records matching)

            Output table:
            RequestNumber            TrackName         Date
            -----------------------------------------------------------
            02209                    Middle         2017-05-28 00:00:00
            0263                     Middle         2017-06-29 00:00:00
            0633                     Middle         2017-09-10 00:00:00
            0762                     All three      2017-06-23 00:00:00
            01839                    Middle         2017-03-09 00:00:00

To get the above desigred output this is the SQL I have tried. Howveer, its updating all TrackName to All three.

            UPDATE a
            SET a.[TrackName] = 'All three'
            FROM Table1 as a
            INNER JOIN
            (SELECT [RequestNumber], row_number() OVER (ORDER BY [RequestNumber] DESC) as rowNumber
            FROM Table1 ) drRowNumbers ON drRowNumbers.[RequestNumber] = a.[RequestNumber] and drRowNumbers.[Date] = a.[Date]

Hope I have explained this correctly. What am I doing worng? Any query to fix this please?

Note: The records are coming dynamically so can not be hardcoded(if any).

Thanks.

Body:
Try This. This will return "All 3" instead of "All Three"-

SELECT RequestNumber,
CASE
    WHEN COUNT(*) = 1 THEN MAX(TrackName)
    ELSE 'All ' + CAST( COUNT(*) AS VARCHAR)
END TrackName,
Date
FROM your_table
GROUP BY RequestNumber,Date


答:
Laravel will automatically try to set the value for created_at and updated_at fields. It is highly recommended to have these, however if you don't want to you can disable them on your Model.

To do this simply add public $timestamps = false; to the model. For example:

class Friendships extends Model
{
    public $timestamps = false;
    protected $fillable = ['requester', 'user_requested', 'status'];
}
```

Title: ERROR: Column not found: 1054 Unknown column 'updated_at' in 'field list'


问:
npm test -- --coverage never exits
I am using create-react-app to create a react application. When I executes npm test -- --coverage the test never exists. npm test actually runs react-scripts test. Any Idea?

答:
Coverage won't work with Jest in watch mode.

Because "react-scripts test --env=jsdom" works in watch mode by default, the watch mode has to be switched off while generating the coverage output.

The following excerpt from the package.json contains a line "coverage" for illustration, how code coverage can be achieved within an app which was bootet by create-react-app.

It's just the modified "test" script, where the options --watchAll=false and --coverage are added in combination:

```<code> "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "coverage": "react-scripts test --env=jsdom --watchAll=false --coverage",
    "eject": "react-scripts eject"
  }
</code>```

Please note that it is obsolete to use standalone double-dash -- .

Title: npm test -- --coverage never exits

Body:
Coverage won't work with Jest in watch mode.

Because "react-scripts test --env=jsdom" works in watch mode by default, the watch mode has to be switched off while generating the coverage output.

The following excerpt from the package.json contains a line "coverage" for illustration, how code coverage can be achieved within an app which was bootet by create-react-app.

It's just the modified "test" script, where the options --watchAll=false and --coverage are added in combination:

 "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "coverage": "react-scripts test --env=jsdom --watchAll=false --coverage",
    "eject": "react-scripts eject"
  }

Please note that it is obsolete to use standalone double-dash -- .


问:
Pandas: dynamically shifting values across columns
I have the following df:

```<code>           sales2001   sales2002   sales2003  sales2004
   200012  19.12       0.98
   200101  19.1        0.98        2.3
   200102  21          0.97        0.8
    ...
   200112  19.12       0.99        2.4
   200201              0.98        2.5
   200202              0.97        0.8        1.2
</code>```

I would like to shift the content in order to align it a timegap view, as follow:

```<code>           sales+1y   sales+2y
   200012  19.12       0.98
   200101  0.98        2.3
   200102  0.97        0.8
    ...
   200112  0.99        2.4
   200201  0.98        2.5
   200202  0.8         1.2
</code>```

basically aligning the forecasted data points to a fixed timegap to the index.
I tried with iterrows and dynamically calling the columns given the index but cannot make it work. do you guys have any suggestion?

答:
Use justify with DataFrame.dropna and axis=1 for remove all columns with at least one NaN:

```<code>df1 = (pd.DataFrame(justify(df.values, invalid_val=np.nan, side='right'), index=df.index)
          .dropna(axis=1))
</code>```

If need select last columns by position:

```<code>df1 = pd.DataFrame(justify(df.values, invalid_val=np.nan, side='right')[:, -2:],index=df.index)
</code>```

Or:

```<code>df1 = (pd.DataFrame(justify(df.values, invalid_val=np.nan, side='right'), index=df.index)
        .iloc[:, -2:])
</code>```

```<code>df1.columns = [f'sales+{i+1}y' for i in range(len(df1.columns))]
print (df1)
        sales+1y  sales+2y
200012     19.12      0.98
200101      0.98      2.30
200102      0.97      0.80
200112      0.99      2.40
200201      0.98      2.50
200202      0.80      1.20
</code>```

Body:
I have the following df:

           sales2001   sales2002   sales2003  sales2004
   200012  19.12       0.98
   200101  19.1        0.98        2.3
   200102  21          0.97        0.8
    ...
   200112  19.12       0.99        2.4
   200201              0.98        2.5
   200202              0.97        0.8        1.2

I would like to shift the content in order to align it a timegap view, as follow:

           sales+1y   sales+2y
   200012  19.12       0.98
   200101  0.98        2.3
   200102  0.97        0.8
    ...
   200112  0.99        2.4
   200201  0.98        2.5
   200202  0.8         1.2

basically aligning the forecasted data points to a fixed timegap to the index.
I tried with iterrows and dynamically calling the columns given the index but cannot make it work. do you guys have any suggestion?

Body:
Use justify with DataFrame.dropna and axis=1 for remove all columns with at least one NaN:

df1 = (pd.DataFrame(justify(df.values, invalid_val=np.nan, side='right'), index=df.index)
          .dropna(axis=1))

If need select last columns by position:

df1 = pd.DataFrame(justify(df.values, invalid_val=np.nan, side='right')[:, -2:],index=df.index)

Or:

df1 = (pd.DataFrame(justify(df.values, invalid_val=np.nan, side='right'), index=df.index)
        .iloc[:, -2:])

df1.columns = [f'sales+{i+1}y' for i in range(len(df1.columns))]
print (df1)
        sales+1y  sales+2y
200012     19.12      0.98
200101      0.98      2.30
200102      0.97      0.80
200112      0.99      2.40
200201      0.98      2.50
200202      0.80      1.20


问:
Can't get mongoose to properly save an array
I'm trying to build an e-commerce from scratch using NodeJS, express and mongoose following this tutorial: https://www.youtube.com/playlist?list=PL55RiY5tL51rajp7Xr_zk-fCFtzdlGKUp but when I save() the program ends up writing a duplicate of everything and keeping the original too.

I've tried using updateMany() and insertMany() but it didn't help.

This is the Schema located in product.js

```<code>const schema = new Schema({
  imagePath: {type: String, required: true},
  title: {type: String, required: true},
  description: {type: String, required: true},
  price: {type: Number, required: true}
});

module.exports = mongoose.model('Product', schema);
</code>```

And this is in product-seeder.js

```<code>const Product = require('../models/product');

const products = [
  new Product({
    imagePath: 'https://images-na.ssl-images-amazon.com/images/I/41mPFjDCaXL.jpg',
    title: 'Gfuel 1',
    description: 'Lorem Ipsum',
    price: 20
  }), ...x4
]

let done = 0;
for (let i = 0; i < products.length; i++) {
  products[i].updateOne((err, result) => {
    done++;
    if (done === products.length) {
      exit();
    }
  });
}

const exit = () => {
  mongoose.disconnect();
}
</code>```

This works fine if there's nothing in the database but when I run this code multiple times, it keeps writing the same thing multiple times when it should just keep one of every object and if I change some info it should update it automatically.

答:
If you do not want the documents to be repeatedly created at every run, you need to make some key in your document as 'unique'.
Try setting the 'imagePath' in your schema as unique like below.</p>

```<code>const schema = new Schema({
imagePath: {type: String, required: true, unique: true},
title: {type: String, required: true},
description: {type: String, required: true},
price: {type: Number, required: true}});
</code>```

Body:
I'm trying to build an e-commerce from scratch using NodeJS, express and mongoose following this tutorial: https://www.youtube.com/playlist?list=PL55RiY5tL51rajp7Xr_zk-fCFtzdlGKUp but when I save() the program ends up writing a duplicate of everything and keeping the original too.

I've tried using updateMany() and insertMany() but it didn't help.

This is the Schema located in product.js

const schema = new Schema({
  imagePath: {type: String, required: true},
  title: {type: String, required: true},
  description: {type: String, required: true},
  price: {type: Number, required: true}
});

module.exports = mongoose.model('Product', schema);

And this is in product-seeder.js

const Product = require('../models/product');

const products = [
  new Product({
    imagePath: 'https://images-na.ssl-images-amazon.com/images/I/41mPFjDCaXL.jpg',
    title: 'Gfuel 1',
    description: 'Lorem Ipsum',
    price: 20
  }), ...x4
]

let done = 0;
for (let i = 0; i < products.length; i++) {
  products[i].updateOne((err, result) => {
    done++;
    if (done === products.length) {
      exit();
    }
  });
}

const exit = () => {
  mongoose.disconnect();
}

This works fine if there's nothing in the database but when I run this code multiple times, it keeps writing the same thing multiple times when it should just keep one of every object and if I change some info it should update it automatically.

Body:
If you do not want the documents to be repeatedly created at every run, you need to make some key in your document as 'unique'.
Try setting the 'imagePath' in your schema as unique like below.

const schema = new Schema({
imagePath: {type: String, required: true, unique: true},
title: {type: String, required: true},
description: {type: String, required: true},
price: {type: Number, required: true}});


问:
Is it possible to use reduce more than the array length?
It's the first time I use reduce with promise, and it's look perfect for my usage.

However, I'm trying to use reduce to iterate more than the original size of my array (call reduce_array in my example).

In fact, in this example, methodThatReturnsAPromise worth true in certain case, false in other. (in the end it always finish by worth false)

The idea is if results is false then reduce work normaly, and go to the next value (nextId). In the other hand, if results is true,
I have to resolve methodThatReturnsAPromise with the same value again.

I already try differents methods using the index in parameter, or I already try to push again the id in reduce_array but none of that work.

```<code>    reduce_array.reduce((accumulatorPromise, nextId, index, array) => {
        return accumulatorPromise.then((results) => {
            //if results === end || result === unknownDomain
            //next

            //first iteration, results don't exist
            if (results) {
                if (results === true) {
                    index++;
                    return methodThatReturnsAPromise(nextId - 1);
                } else {
                    return methodThatReturnsAPromise(nextId);
                }
            } else {
                return methodThatReturnsAPromise(nextId);
            }

        })
    }, Promise.resolve());
</code>```

答:
A do/while loop inside a for loop will probably be a lot simpler:

```<code>(async () => {
  for (const nextId of reduce_array) {
    let result;
    do {
      result = await methodThatReturnsAPromise(nextId);
    } while (result !== true);
  }
})();
</code>```

If you had to use reduce, you could put a named function which calls itself recursively inside the reduce callback:

```<code>reduce_array.reduce((accumulatorPromise, nextId) => {
  return accumulatorPromise.then(() => {
    const getThisInfo = () => methodThatReturnsAPromise(nextId)
      .then((result) => (
        result === true
          ? getThisInfo()
          : null
      ));
    return getThisInfo();
  })
}, Promise.resolve());
</code>```

Which is a bit ugly and not so easy to read. I'd prefer the for loop.

Body:
It's the first time I use reduce with promise, and it's look perfect for my usage.

However, I'm trying to use reduce to iterate more than the original size of my array (call reduce_array in my example).

In fact, in this example, methodThatReturnsAPromise worth true in certain case, false in other. (in the end it always finish by worth false)

The idea is if results is false then reduce work normaly, and go to the next value (nextId). In the other hand, if results is true,
I have to resolve methodThatReturnsAPromise with the same value again.

I already try differents methods using the index in parameter, or I already try to push again the id in reduce_array but none of that work.

    reduce_array.reduce((accumulatorPromise, nextId, index, array) => {
        return accumulatorPromise.then((results) => {
            //if results === end || result === unknownDomain
            //next

            //first iteration, results don't exist
            if (results) {
                if (results === true) {
                    index++;
                    return methodThatReturnsAPromise(nextId - 1);
                } else {
                    return methodThatReturnsAPromise(nextId);
                }
            } else {
                return methodThatReturnsAPromise(nextId);
            }

        })
    }, Promise.resolve());

Body:
A do/while loop inside a for loop will probably be a lot simpler:

(async () => {
  for (const nextId of reduce_array) {
    let result;
    do {
      result = await methodThatReturnsAPromise(nextId);
    } while (result !== true);
  }
})();

If you had to use reduce, you could put a named function which calls itself recursively inside the reduce callback:

reduce_array.reduce((accumulatorPromise, nextId) => {
  return accumulatorPromise.then(() => {
    const getThisInfo = () => methodThatReturnsAPromise(nextId)
      .then((result) => (
        result === true
          ? getThisInfo()
          : null
      ));
    return getThisInfo();
  })
}, Promise.resolve());

Which is a bit ugly and not so easy to read. I'd prefer the for loop.


问:
This iPhone 7 (Model 1660, 1778, 1779, 1780) is running iOS 12.3.1 (16F203), which may not be supported by this version of Xcode
I getting the following error when I run the app into device.

This iPhone 7 (Model 1660, 1778, 1779, 1780) is running iOS 12.3.1 (16F203), which may not be supported by this version of Xcode.

my Xcode is 10.1

答:
Your current version of Xcode does not support the iOS 12.3.1 version of the SDK.

There are a couple of options available:

Update Xcode to the latest version

Download a add the required device support files to your current version.

You can download the support files here or from the Apple Developer website. There is also instructions on where to place the files once downloaded


问:
Angular 7 - How to limit event trigger to specific component where event occurs?
I have a list of text areas:

text-area.component.html

<textarea [ngClass]="generateTextAreaClass()" (keypress)="onKeyPress($event)">{{ value }}</textarea>
```

<p>The textarea has a <code>keypress</code> event.</p>

<p>When I press a key in one of the textareas, it triggers the <code>keypress</code> event for all instances of this component.</p>

<p>As a result, I get 5 events being triggered. This obviously doesn't represent the action I just made as a user.</p>

```{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
```

<p>How can I limit the event to only be triggered for the textarea that I'm currently typing in so that only one event gets triggered?</p>

<pre class="lang-js prettyprint-override"><code>@Component({
  selector: 'app-utility-textarea',
  templateUrl: './text-area.component.html',
  styleUrls: ['./text-area.component.scss']
})
export class TextAreaComponent implements AfterViewInit {

  constructor(private eventBus: EventBusService) {
  }

  @Input() value: string;
  @Input() id: string;
  public textAreaClassPrefix = 'app-utility-textarea';

  ...

  generateTextAreaClass(): string {
    return `${this.textAreaClassPrefix}-${this.id}`;
  }

  onKeyPress(event: KeyboardEvent) {
    event.stopPropagation();
    if (event.key === 'Enter' && event.shiftKey) {
      event.preventDefault();
      const textAreaKeyPressEvent: TextAreaKeyPressEvent = {
        textareaSelector: this.generateTextAreaClassCSSSelector(),
        keypressType: TextAreaKeyPressType.SHIFT_ENTER
      };
      this.eventBus.textAreaKeyPressSubject$.next(textAreaKeyPressEvent);
    }
  }
}
</code>```

event-bus.service.ts

@Injectable()
export class EventBusService {

  public navbarSubject$ = new BehaviorSubject(DashboardNavbarEvent.SIDEBAR_MENU_CLOSED);
  public textAreaKeyPressSubject$ = new Subject<TextAreaKeyPressEvent>();

  constructor() {
  }

}
```

<p><strong>subscriber.component.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>@Component({
  selector: 'app-subscriber',
  templateUrl: './subscriber.component.html',
  styleUrls: ['./subscriber.component.scss']
})
export class SubscriberComponent implements OnInit {

  @Input() public block: any;
  @Input() public index: number;

  constructor(private eventBus: EventBusService) {
  }

  ngOnInit() {
    this.eventBus.textAreaKeyPressSubject$.subscribe((event: TextAreaKeyPressEvent) => {
      console.log(event);
    });
  }

}
</code>```

答:
you are using a subject from subject:

What is a Subject? An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast.

And you are emitting an event by next in :

```<code>this.eventBus.textAreaKeyPressSubject$.next(textAreaKeyPressEvent);
</code>```

so basically you are emitting something to multicast subscribers, so the event is fired from the right one textarea as you can see but you're propagating the event to the other subscribers. The point is that you want one to one subscription and not one to many. Hope this was helpful

Body:
I have a list of text areas:

text-area.component.html

<textarea [ngClass]="generateTextAreaClass()" (keypress)="onKeyPress($event)">{{ value }}</textarea>

The textarea has a keypress event.

When I press a key in one of the textareas, it triggers the keypress event for all instances of this component.

As a result, I get 5 events being triggered. This obviously doesn't represent the action I just made as a user.

{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}

How can I limit the event to only be triggered for the textarea that I'm currently typing in so that only one event gets triggered?

@Component({
  selector: 'app-utility-textarea',
  templateUrl: './text-area.component.html',
  styleUrls: ['./text-area.component.scss']
})
export class TextAreaComponent implements AfterViewInit {

  constructor(private eventBus: EventBusService) {
  }

  @Input() value: string;
  @Input() id: string;
  public textAreaClassPrefix = 'app-utility-textarea';

  ...

  generateTextAreaClass(): string {
    return `${this.textAreaClassPrefix}-${this.id}`;
  }

  onKeyPress(event: KeyboardEvent) {
    event.stopPropagation();
    if (event.key === 'Enter' && event.shiftKey) {
      event.preventDefault();
      const textAreaKeyPressEvent: TextAreaKeyPressEvent = {
        textareaSelector: this.generateTextAreaClassCSSSelector(),
        keypressType: TextAreaKeyPressType.SHIFT_ENTER
      };
      this.eventBus.textAreaKeyPressSubject$.next(textAreaKeyPressEvent);
    }
  }
}

event-bus.service.ts

@Injectable()
export class EventBusService {

  public navbarSubject$ = new BehaviorSubject(DashboardNavbarEvent.SIDEBAR_MENU_CLOSED);
  public textAreaKeyPressSubject$ = new Subject<TextAreaKeyPressEvent>();

  constructor() {
  }

}

subscriber.component.ts

@Component({
  selector: 'app-subscriber',
  templateUrl: './subscriber.component.html',
  styleUrls: ['./subscriber.component.scss']
})
export class SubscriberComponent implements OnInit {

  @Input() public block: any;
  @Input() public index: number;

  constructor(private eventBus: EventBusService) {
  }

  ngOnInit() {
    this.eventBus.textAreaKeyPressSubject$.subscribe((event: TextAreaKeyPressEvent) => {
      console.log(event);
    });
  }

}

Body:
you are using a subject from subject:

What is a Subject? An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast.

And you are emitting an event by next in :

this.eventBus.textAreaKeyPressSubject$.next(textAreaKeyPressEvent);

so basically you are emitting something to multicast subscribers, so the event is fired from the right one textarea as you can see but you're propagating the event to the other subscribers. The point is that you want one to one subscription and not one to many. Hope this was helpful


问:
Display data json (plot.ly) from influxdb
I'm trying to get a graph of my influxdb measurements.To display graphics, I use plot.ly and python. I started in python with a sql request to get my json data from localhost:8086, but it doesn't work. I've tried some things, I'm sending you my little piece of code:

import plotly
import plotly.plotly as py
import numpy as np
import plotly.graph_objs as go
import plotly.offline as ply
import pandas as pd
from plotly.tools import FigureFactory as FF

if __name__ == "__main__":
    df = pd.read_json('http://localhost:8086/query?q=SELECT%20%22I%22%20FROM%20%22michelin%22.%22autogen%22.%22mqtt_consumer%22%20WHERE%20time%20%3E%20now()%20-%202d%20AND%20%22topic%22=%27PI1%27')
    print(df['results'])
    #df = [go.Scatter(x=df['time'], y=df['mqtt_consumer.mean_I'])]
    ply.plot(df, filename = 'time-series-simple')

```

The link with the request shows me this :

I would like a time series, with the value "I" as a function of time.
If anyone can help me, thank you for your feedback

答:
You must unwind all the keys before plotting. The data inside the json object that you want to plot is at the innermost nested level. You need to reach that. Try this

```<code>dfff = pd.DataFrame(df["results"][0]["series"][0]["values"]).T
#dfff.plot()
</code>```

Specifically if you want to plot using plotly:

```<code>import plotly.plotly as py
import pandas as pd
import numpy as np

dfff = pd.DataFrame(df["results"][0]["series"][0]["values"]).T

dfff.columns = ["timestamp","value"]

py.iplot([{
    'x': dfff.timestamp,
    'y': dfff["value"],
    'name': "value"
}  ], filename='yourfilename')
</code>```

Body:
I'm trying to get a graph of my influxdb measurements.To display graphics, I use plot.ly and python. I started in python with a sql request to get my json data from localhost:8086, but it doesn't work. I've tried some things, I'm sending you my little piece of code:

import plotly
import plotly.plotly as py
import numpy as np
import plotly.graph_objs as go
import plotly.offline as ply
import pandas as pd
from plotly.tools import FigureFactory as FF

if __name__ == "__main__":
    df = pd.read_json('http://localhost:8086/query?q=SELECT%20%22I%22%20FROM%20%22michelin%22.%22autogen%22.%22mqtt_consumer%22%20WHERE%20time%20%3E%20now()%20-%202d%20AND%20%22topic%22=%27PI1%27')
    print(df['results'])
    #df = [go.Scatter(x=df['time'], y=df['mqtt_consumer.mean_I'])]
    ply.plot(df, filename = 'time-series-simple')

The link with the request shows me this :

I would like a time series, with the value "I" as a function of time.
If anyone can help me, thank you for your feedback

Body:
You must unwind all the keys before plotting. The data inside the json object that you want to plot is at the innermost nested level. You need to reach that. Try this

dfff = pd.DataFrame(df["results"][0]["series"][0]["values"]).T
#dfff.plot()

Specifically if you want to plot using plotly:

import plotly.plotly as py
import pandas as pd
import numpy as np

dfff = pd.DataFrame(df["results"][0]["series"][0]["values"]).T

dfff.columns = ["timestamp","value"]

py.iplot([{
    'x': dfff.timestamp,
    'y': dfff["value"],
    'name': "value"
}  ], filename='yourfilename')


问:
Can we set Minimum time for a telerik rad time picker in code behind
I am having a telerik RadTimePicker can we set the mimimum Start Time and End Time from code behind.Right now I am using this to display which is from 6 AM to 9PM.

答:
This can be done through the RadTimePicker1.TimeView.StartTime and RadTimePicker1.TimeView.EndTime properties of the control:</p>

```<code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        RadTimePicker1.TimeView.StartTime = New TimeSpan(8, 0, 0)
        RadTimePicker1.TimeView.EndTime = New TimeSpan(18, 0, 0)
        RadTimePicker1.TimeView.Interval = New TimeSpan(0, 15, 0)
        RadTimePicker1.TimeView.HeaderText = ""
        RadTimePicker1.TimeView.Columns = 4
    End If
End Sub
</code>```

Body:
This can be done through the RadTimePicker1.TimeView.StartTime and RadTimePicker1.TimeView.EndTime properties of the control:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        RadTimePicker1.TimeView.StartTime = New TimeSpan(8, 0, 0)
        RadTimePicker1.TimeView.EndTime = New TimeSpan(18, 0, 0)
        RadTimePicker1.TimeView.Interval = New TimeSpan(0, 15, 0)
        RadTimePicker1.TimeView.HeaderText = ""
        RadTimePicker1.TimeView.Columns = 4
    End If
End Sub


问:
How To Hide url display in bottom left on mouseover?
I have a page for member's where log in is essential. On this page members get links for  lectures conducted. Lectures links get added regularly. And Links to recording are fetched on this page from database and last 30 recording links are available (through Limit $max).
code is as follow -

Play Recording ">

Here, when user move cursor on "Play Recording" he can see recording link in left bottom corner of browser.

How can I hide this Link getting displayed in left bottom corner on mouseover ? Can i Show only Word "Recording" Instead of link displayed ?

答:
Check the below code it will work in all browsers

Hide url toaster in bottom left on mouseover

$(function(){
           $("a").each(function (index, element){
               var href = $(this).attr("href");
               $(this).attr("hiddenhref", href);
               $(this).removeAttr("href");
           });
           $("a").click(function(){
               url = $(this).attr("hiddenhref");
              // window.open(url);
                                         window.location.href = url;
           })
       });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul > li > a{
  font-size: 18px;
  line-height: 30px;
}

ul > li > a:hover {
  color: #425CD2;
  text-decoration: underline !important;
  cursor: pointer;
}</code>```

Google

Codepen

Codepen hide url toaster snippet

```

Body:
I have a page for member's where log in is essential. On this page members get links for  lectures conducted. Lectures links get added regularly. And Links to recording are fetched on this page from database and last 30 recording links are available (through Limit $max).
code is as follow -

<img src="https://i.stack.imgur.com/X7SRy.png" alt="<a class="fancybox fancybox.iframe more_info_btn" href="<?=$data\['recording_link'\]?>" >Play Recording ">

Here, when user move cursor on "Play Recording" he can see recording link in left bottom corner of browser.

How can I hide this Link getting displayed in left bottom corner on mouseover ? Can i Show only Word "Recording" Instead of link displayed ?

Body:
Check the below code it will work in all browsers

Hide url toaster in bottom left on mouseover

$(function(){
           $("a").each(function (index, element){
               var href = $(this).attr("href");
               $(this).attr("hiddenhref", href);
               $(this).removeAttr("href");
           });
           $("a").click(function(){
               url = $(this).attr("hiddenhref");
              // window.open(url);
                                         window.location.href = url;
           })
       });

ul > li > a{
  font-size: 18px;
  line-height: 30px;
}

ul > li > a:hover {
  color: #425CD2;
  text-decoration: underline !important;
  cursor: pointer;
}

<ul>
 <li><a href="http://www.google.com">Google</a></li>
 <li><a href="https://codepen.io">Codepen</a></li>
 <li><a href="https://codepen.io/awesomeSri/pen/WBKwpz?editors=1111" >Codepen hide url toaster snippet</a></li>

</ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>


问:
How To Align Ok Button Of A Dialog Pane In Javafx?
I want to align i.e Position CENTER an OK button of a DialogPane. I have tried the below code but its not working.</p>

```<code>Dialog dialog = new Dialog();
DialogPane dialogPane = dialog.getDialogPane();
dialogPane.setStyle("-fx-background-color: #fff;");

        // Set the button types.
ButtonType okButtonType = new ButtonType("Ok", ButtonBar.ButtonData.OK_DONE);
ButtonType cancelButtonType = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
dialog.getDialogPane().getButtonTypes().addAll(okButtonType, cancelButtonType);
dialogPane.lookupButton(cancelButtonType).setVisible(false);

        // Testing
Button okButton = (Button) dialog.getDialogPane().lookupButton(okButtonType);
okButton.setAlignment(Pos.CENTER);
        // End Testing

dialog.showAndWait();
</code>```

答:
Add this method to your code and call it when you need to align the buttons in a Dialog or Alert:

```<code>    private void centerButtons(DialogPane dialogPane) {
      Region spacer = new Region();
      ButtonBar.setButtonData(spacer, ButtonBar.ButtonData.BIG_GAP);
      HBox.setHgrow(spacer, Priority.ALWAYS);
      dialogPane.applyCss();
      HBox hboxDialogPane = (HBox) dialogPane.lookup(".container");
      hboxDialogPane.getChildren().add(spacer);
   }
</code>```

Call it in this way: centerButtons(dialog.getDialogPane);

Body:
I want to align i.e Position CENTER an OK button of a DialogPane. I have tried the below code but its not working.

Dialog dialog = new Dialog();
DialogPane dialogPane = dialog.getDialogPane();
dialogPane.setStyle("-fx-background-color: #fff;");

        // Set the button types.
ButtonType okButtonType = new ButtonType("Ok", ButtonBar.ButtonData.OK_DONE);
ButtonType cancelButtonType = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
dialog.getDialogPane().getButtonTypes().addAll(okButtonType, cancelButtonType);
dialogPane.lookupButton(cancelButtonType).setVisible(false);

        // Testing
Button okButton = (Button) dialog.getDialogPane().lookupButton(okButtonType);
okButton.setAlignment(Pos.CENTER);
        // End Testing

dialog.showAndWait();

Body:
Add this method to your code and call it when you need to align the buttons in a Dialog or Alert:

    private void centerButtons(DialogPane dialogPane) {
      Region spacer = new Region();
      ButtonBar.setButtonData(spacer, ButtonBar.ButtonData.BIG_GAP);
      HBox.setHgrow(spacer, Priority.ALWAYS);
      dialogPane.applyCss();
      HBox hboxDialogPane = (HBox) dialogPane.lookup(".container");
      hboxDialogPane.getChildren().add(spacer);
   }

Call it in this way: centerButtons(dialog.getDialogPane);


问:
Exact word matching instead of in between strings matches
Instead of matching the whole the below code is also returning the case where there are matching characters in between.

```<code>for(i in 1:dim(Step10)[1]) {
x <- agrep(Step10$Supplier.Name[i], Step9$SUPPLIER_NAME,
         ignore.case=TRUE, value=FALSE, fixed = TRUE,
         max.distance = 0.05, useBytes = FALSE)
x <- paste0(x,"")
Step10$Supplier_Name[i] <- x
}
</code>```

Below is the code

```<code>a<- c("LEARNING LLC", "BOC", "NCC","KAMAY")
b<- c("LEARNING LLC","BOCLKYN CENTRE", "YANCO CORP", "SAMAS DBA KAMAY")

a<- as.data.frame(a)
b<- as.data.frame(b)

colnames(a) <- c("names")
colnames(b) <- c("names")

a$names = as.character(a$names)
b$names = as.character(b$names)

a$name_1 <- ""

for(i in 1:dim(a)[1]) {
  x <- agrep(a$names[i],b$names,
         ignore.case=TRUE, value=TRUE,
         max.distance = 0.05, useBytes = TRUE)
  x <- paste0(x,"")
  a$name_1[i] <- x
  }
</code>```

答:
Since you want an exact match, you must use grep and add word boundaries around your words, i.e.

```<code>grep(paste0('\\b', a, '\\b', collapse = '|'), b, value = TRUE)
#[1] "LEARNING LLC"    "SAMAS DBA KAMAY"
</code>```

Body:
Instead of matching the whole the below code is also returning the case where there are matching characters in between.

for(i in 1:dim(Step10)[1]) {
x <- agrep(Step10$Supplier.Name[i], Step9$SUPPLIER_NAME,
         ignore.case=TRUE, value=FALSE, fixed = TRUE,
         max.distance = 0.05, useBytes = FALSE)
x <- paste0(x,"")
Step10$Supplier_Name[i] <- x
}

Below is the code

a<- c("LEARNING LLC", "BOC", "NCC","KAMAY")
b<- c("LEARNING LLC","BOCLKYN CENTRE", "YANCO CORP", "SAMAS DBA KAMAY")

a<- as.data.frame(a)
b<- as.data.frame(b)

colnames(a) <- c("names")
colnames(b) <- c("names")

a$names = as.character(a$names)
b$names = as.character(b$names)

a$name_1 <- ""

for(i in 1:dim(a)[1]) {
  x <- agrep(a$names[i],b$names,
         ignore.case=TRUE, value=TRUE,
         max.distance = 0.05, useBytes = TRUE)
  x <- paste0(x,"")
  a$name_1[i] <- x
  }

Body:
Since you want an exact match, you must use grep and add word boundaries around your words, i.e.

grep(paste0('\\b', a, '\\b', collapse = '|'), b, value = TRUE)
#[1] "LEARNING LLC"    "SAMAS DBA KAMAY"


问:
RegEx for matching everything except words starting with a plus sign
Sample string:
+Z XA( 0,1,6,22,26,33,34,35,36,25,24) +DD +I +M >x1 >bdz +A

Result should be:
+Z +DD +I +M +A
or
Z DD I M A

The regex (\+\w+) seems to find all tokens, but I don't know how to define the replace pattern. I'd like to remove everything else.

I use Omnis7 but the regex engine is a compiled Delphi library that I used to extend Omnis7. The regex engine is a full implementation of regex. I tried to find the regex with an online regex tool (regex101.com).

How do I solve this problem?

答:
Thanks to all here.
I played around with it and found the exact solution:

Search: +Z XA( 0,1,6,22,26,33,34,35,36,25,24) +DD +I +M >x1 >bdz +A

Find: (\+)(\w+\h?)(.?)|.

Replace: $1$2$3

Result: +Z +DD +I +M +A

or

Replace: $2$3

Result: Z DD I M A


问:
Send and receive hex codes over nodejs socket
I am sending hex code to machine in nodejs socket application and receive hex answer from code below:

```<code>socket.on('data', function(data){
  console.log('Socket:'+Buffer.from(data).toString('hex'));
});
</code>```

In console I receive this:
0104000100150104125d2befbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbfbd00efbfbdefbfbd

What is expected:

01 04 00 01 00 15 01 04 12 5D 2B FF FF FF FF FF FF FF FF FF FF FF FF 80 00 FF FF

I don't understand why there is additional data.

答:
Seems data is string, not buffer.

just try this code

```<code>const data = Buffer.from('01 04 00 01 00 15 01 04 12 5D 2B FF FF FF FF FF FF FF FF FF FF FF FF 80 00 FF FF'.split(' ').map(x => parseInt(x, 16)));
console.log(Buffer.from(data).toString('hex'));
const str = data.toString(); // <- problem!!!
console.log(Buffer.from(str).toString('hex'));
</code>```

You can't send binary buffer directly, just convert to hex string before and to buffer after for example.

Read this topic
Node Buffers, from utf8 to binary

Body:
I am sending hex code to machine in nodejs socket application and receive hex answer from code below:

socket.on('data', function(data){
  console.log('Socket:'+Buffer.from(data).toString('hex'));
});

In console I receive this:
0104000100150104125d2befbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbfbd00efbfbdefbfbd

What is expected:

01 04 00 01 00 15 01 04 12 5D 2B FF FF FF FF FF FF FF FF FF FF FF FF 80 00 FF FF

I don't understand why there is additional data.

Body:
Seems data is string, not buffer.

just try this code

const data = Buffer.from('01 04 00 01 00 15 01 04 12 5D 2B FF FF FF FF FF FF FF FF FF FF FF FF 80 00 FF FF'.split(' ').map(x => parseInt(x, 16)));
console.log(Buffer.from(data).toString('hex'));
const str = data.toString(); // <- problem!!!
console.log(Buffer.from(str).toString('hex'));

You can't send binary buffer directly, just convert to hex string before and to buffer after for example.

Read this topic
Node Buffers, from utf8 to binary


问:
Alternatives to using the clipboard feature in Automation Anywhere
What are some alternatives to using the clipboard feature in Automation Anywhere? I'm told using the clipboard feature is not ideal for consistency.</p>

答: You should use 'Prompt-Assignment' variable for holding temporary values. Use of 'Clipboard' should only be done where a Ctrl+C action needs to be performed however the value should immediately be transferred in 'Prompt-Assignment' or any other variable for holding the values.</p>


问:
How to send an email when publish posts?
I wanted to send a email when publish post and i don't wanted to use plugin.
i add below  code to functions.php of my theme folder ,but it doesn't send any email to me. it goes to else part.</p>

```<code> function dothisfunction() {
     $sent = wp_mail("nadia.amoee@gmail.com","sms test", "message");
     if($sent) {
         echo "sent";
     }else {
         echo "failed";
     }

 }
 add_action( 'publish_post', 'dothisfunction' );
</code>```

答:
You might have one of the following reasons why it is not being sent

1) There might be PHPMailer Exception : wp_mail is getting failed So try debugging the error using the below code

```<code>// show wp_mail() errors
add_action( 'wp_mail_failed', 'onMailError', 10, 1 );
function onMailError( $wp_error ) {
    echo "```";
    print_r($wp_error);
    echo "```";
}
</code>```

2) Wordpress relies on the PHPMailer class to send email through PHP's mail function.

Since PHP's mail function returns very little information after execution (only TRUE or FALSE), I suggest temporarily stripping down your function to a minimum in order to see if the wp_mail functions works.

```<code>$mailResult = false;
$mailResult = wp_mail( 'youremail@bla.com', 'test if mail works', 'hurray' );
echo $mailResult;
</code>```

3) You might be having server problems because "Not received" does not mean the same as "not sent" and this is an important distinction in troubleshooting.

If other email addresses are receiving, then it is likely that something is flagging your message at the receiving hosts that you listed.

4) Not all wordpress/server configurations allow the default Wordpress wp_mail function to send out mail. Certainly when testing on a local(host) server, lots of ISP's block the default outgoing mail traffic. Sometimes the blocking goes on silently, so it looks like everything works, but mail never gets sent. What helps is to install the WP Mail SMTP plugin (or similar) so you can configure outgoing SMTP servers (with or without authentication).

5) There is a possibility that your email is being marked as spam, or it's simply your email provider is not allowing it to reach your inbox.

Do you have SPF records setup? If you are sending an email from your website, and have the from header set as @gmail.com or @hotmail.com, this will surely not arrive in your inbox as the email is not originating from the gmail or hotmail servers, it's coming from yours, so it think's you are trying some phishing attack.

So you should also check your spam/trash folders for interception.

NOTE : There are many links related to this issue which you can go for
  but the ultimate favorite for everybody is to use WORDPRESS MAIL SMTP PLUGIN which i mentioned in point 4 and that resolves the issue for
  more than 95% of people.

Body:
I wanted to send a email when publish post and i don't wanted to use plugin.
i add below  code to functions.php of my theme folder ,but it doesn't send any email to me. it goes to else part.

 function dothisfunction() {
     $sent = wp_mail("nadia.amoee@gmail.com","sms test", "message");
     if($sent) {
         echo "sent";
     }else {
         echo "failed";
     }

 }
 add_action( 'publish_post', 'dothisfunction' );

Body:
You might have one of the following reasons why it is not being sent

1) There might be PHPMailer Exception : wp_mail is getting failed So try debugging the error using the below code

// show wp_mail() errors
add_action( 'wp_mail_failed', 'onMailError', 10, 1 );
function onMailError( $wp_error ) {
    echo "<pre>";
    print_r($wp_error);
    echo "</pre>";
}

2) Wordpress relies on the PHPMailer class to send email through PHP's mail function.

Since PHP's mail function returns very little information after execution (only TRUE or FALSE), I suggest temporarily stripping down your function to a minimum in order to see if the wp_mail functions works.

$mailResult = false;
$mailResult = wp_mail( 'youremail@bla.com', 'test if mail works', 'hurray' );
echo $mailResult;

3) You might be having server problems because "Not received" does not mean the same as "not sent" and this is an important distinction in troubleshooting.

If other email addresses are receiving, then it is likely that something is flagging your message at the receiving hosts that you listed.

4) Not all wordpress/server configurations allow the default Wordpress wp_mail function to send out mail. Certainly when testing on a local(host) server, lots of ISP's block the default outgoing mail traffic. Sometimes the blocking goes on silently, so it looks like everything works, but mail never gets sent. What helps is to install the WP Mail SMTP plugin (or similar) so you can configure outgoing SMTP servers (with or without authentication).

5) There is a possibility that your email is being marked as spam, or it's simply your email provider is not allowing it to reach your inbox.

Do you have SPF records setup? If you are sending an email from your website, and have the from header set as @gmail.com or @hotmail.com, this will surely not arrive in your inbox as the email is not originating from the gmail or hotmail servers, it's coming from yours, so it think's you are trying some phishing attack.

So you should also check your spam/trash folders for interception.

NOTE : There are many links related to this issue which you can go for
  but the ultimate favorite for everybody is to use WORDPRESS MAIL SMTP PLUGIN which i mentioned in point 4 and that resolves the issue for
  more than 95% of people.


问:
Flutter how to do for inside for loop with list widget?
i need to do for inside for loop inside widgets. i create two widgets and i called it form another widget. it says "Not in range 0..6, inclusive:7"

Code :

```<code>List<Widget> ListMyClips(i) {
    List<Widget> list = new List();
    var lengthItems = widget.data["recommended"][7]["blocks"][i]["items"].length;
    for (var c = 0; c <= lengthItems; i++) {
        list.add(
            ClipRRect(
                borderRadius: new BorderRadius.circular(100.0),
                child: Image.network(
                    first[widget.data["recommended"][7]["blocks"][i]["items"][c]
                        ["id"]]["image"]["full"],
                    width: 56,
                ),
            ),
        );
    }

    return list;
}

List <Widget> ListMyWidgets() {
    var lengthBlocks = widget.data["recommended"][7]["blocks"].length;
    List <Widget> list = new List();
    for (var i = 0; i <= lengthBlocks; i++) {
        list.add(ListTile(
            trailing: Icon(FontAwesomeIcons.chevronRight),
            title: Row(
                children: ListMyClips(i),
            ),
        ));
    }
    return list;
}
</code>```

what i need is, dynamically for inside for loop which it will create list of list tiles.

答:
With Dart 2.3 new features, you can use a for inside a collections, to minimize the boilerplate code and make it more legible.

Before Dart 2.3

```<code>Row(
 children: <Widget>[
   europeanCountries
   .map((country) => Text("New $country"))
   .toList();
  ],
)
</code>```

With Dart 2.3

```<code>Row(
 children: <Widget>[
  for (var country in europeanCountries) Text("New ${country.data}")
  ],
)
</code>```

Check more features that could help you in here: What's new in Dart 2.3

PS: Change your functions name to a camelCase form. This way, you should be creating a class instead of a method

Body:
i need to do for inside for loop inside widgets. i create two widgets and i called it form another widget. it says "Not in range 0..6, inclusive:7"

Code :

List<Widget> ListMyClips(i) {
    List<Widget> list = new List();
    var lengthItems = widget.data["recommended"][7]["blocks"][i]["items"].length;
    for (var c = 0; c <= lengthItems; i++) {
        list.add(
            ClipRRect(
                borderRadius: new BorderRadius.circular(100.0),
                child: Image.network(
                    first[widget.data["recommended"][7]["blocks"][i]["items"][c]
                        ["id"]]["image"]["full"],
                    width: 56,
                ),
            ),
        );
    }

    return list;
}

List <Widget> ListMyWidgets() {
    var lengthBlocks = widget.data["recommended"][7]["blocks"].length;
    List <Widget> list = new List();
    for (var i = 0; i <= lengthBlocks; i++) {
        list.add(ListTile(
            trailing: Icon(FontAwesomeIcons.chevronRight),
            title: Row(
                children: ListMyClips(i),
            ),
        ));
    }
    return list;
}

what i need is, dynamically for inside for loop which it will create list of list tiles.

Body:
With Dart 2.3 new features, you can use a for inside a collections, to minimize the boilerplate code and make it more legible.

Before Dart 2.3

Row(
 children: <Widget>[
   europeanCountries
   .map((country) => Text("New $country"))
   .toList();
  ],
)

With Dart 2.3

Row(
 children: <Widget>[
  for (var country in europeanCountries) Text("New ${country.data}")
  ],
)

Check more features that could help you in here: What's new in Dart 2.3

PS: Change your functions name to a camelCase form. This way, you should be creating a class instead of a method


问:
How to make RichTextValue catalog full text search for Plone 4
I created dexterity content type with Rich Text Field - "body text". I'd like to make "body text" full text searchable for my Plone 4.0.2.

I added catalog.xml in my theme, code below

I got error message from ZMI/portal/portal_catalog "body_text RichTextValue object. (Did you mean .raw or .output?) "

How can I change catalog.xml to use .output, I tried , but it doesn't work.

Thanks.

答:
Disclaimer: I have not encountered this issue myself, so this is just a guess.

Archetypes and others use SearchableText() index/accessor to populate the full text search index for Plone search.

You probably need to add SearchableText() method to your content type and make it return all the text concatenated which you want full text search to pick up.


问:
How do i make custom Shapes from an array of points in xyz with THREE.JS?
As an Example: i have the points [1,0,2],[2,0,2],[3,2,5]
Now i would like to make a shape from these points by connecting them.

I tried to use THREE.Shape but it can only build the shape on the x and y axis.
I need to use the z axis to build the shape aswell.
I would appreciate any help :)

答:
An instance of THREE.Shape is a 2D shape. In other words, it always lies in a conceptual plane. It's not possible to define an arbitrary 3D structure with it.

three.js R104


问:
I get an error message when I use Xamarin Essentials SecureStorage
I want to use SecureStorage on iOS and Android mobile phones and tablets but I get this error message on iOS. I have not yet tested SecureStorage on Android.

Xamarin Essentials SecureStorage

What is wrong? What does the error mean?

Error message image

答:
The issue is that you did not add the Keychain entitlement that is mentioned to be added to Entitlement.plist

If you check the Microsoft docs it says:

When developing on the iOS simulator, enable the Keychain entitlement and add a keychain access group for the application's bundle identifier.

Open the Entitlements.plist in the iOS project and find the Keychain entitlement and enable it. This will automatically add the application's identifier as a group.

In the project properties, under iOS Bundle Signing set the Custom Entitlements to Entitlements.plist.

Also under Platform Specifics it says:

KeyChain is used to store values securely on iOS devices. The SecRecord used to store the value has a Service value set to [YOUR-APP-BUNDLE-ID].xamarinessentials.

In some cases, KeyChain data is synchronized with iCloud, and uninstalling the application may not remove the secure values from iCloud and other devices of the user.

I hope this helps,

Goodluck

Revert in case of queries.


问:
Is there a way to get arround instagram bot dedector
I tried to write an automatic program with python and selenium to create automated Instagram accounts.  I have added all security options and even Instagram prevents me from creating new accounts.

I literally tried everything. Cleaning cookies, catch, incognito-mode, proxy, disabled location, used fake headers and at last I tried a new internet connection (Hotspot by my smartphone). But Instagram still blocks me. How can I modify my code to prevent Instagram me from being detected as me?

The InstaAction class only calls storage.clear()

```<code>class MyInstaAction(webdriver.Chrome):
    def __init__(self, *args, **kwargs):
        super().__init__('chromedriver.exe', *args, **kwargs)

    def root(self):
        self.get(mpaths.root)

    def create_account(self, user):
        self.get(mpaths.register)
        self.execute_script('localStorage.clear();')

        # Finding elements and doing other stuff
</code>```

"Main" securety settings

```<code>    if mconf.use_proxy:
        proxies = my_proxys.get_proxys()

        if count > len(proxies):
            print(f'Only {len(proxies)} available\n'
                  f'Setting counter to maximum of {len(proxies)}')
            count = len(proxies)
    else:
        proxies = [0 for _ in range(count)]

    for i, proxy in zip(range(count), proxies):
        try:
            user = MyUserFactory.get_user()
            if doc.does_user_exist(user):
                same += 1
                continue

            opt = webdriver.ChromeOptions()
            opt.add_argument("disable-infobars")
            opt.add_argument("--incognito")
            prefs = {"profile.default_content_setting_values.geolocation": 2}
            opt.add_experimental_option("prefs", prefs)
            ua = rua.random
            print(ua)
            opt.add_argument(f"user-agent={ua}")
            opt.add_experimental_option('prefs', {'intl.accept_languages': 'en,en_US'})
            if proxy:
                # Setting up proxy package
                opt.add_argument('--proxy-server=%s' % proxy)

            # end
            iact = MyInstaAction(options=opt)
            iact.delete_all_cookies()

</code>```

Does anybody how to get around this problem?

答:
Try to change the user-agent.
options.add_argument("user-agent=YOUR_DEVICE")

Body:
I tried to write an automatic program with python and selenium to create automated Instagram accounts.  I have added all security options and even Instagram prevents me from creating new accounts.

I literally tried everything. Cleaning cookies, catch, incognito-mode, proxy, disabled location, used fake headers and at last I tried a new internet connection (Hotspot by my smartphone). But Instagram still blocks me. How can I modify my code to prevent Instagram me from being detected as me?

The InstaAction class only calls storage.clear()

class MyInstaAction(webdriver.Chrome):
    def __init__(self, *args, **kwargs):
        super().__init__('chromedriver.exe', *args, **kwargs)

    def root(self):
        self.get(mpaths.root)

    def create_account(self, user):
        self.get(mpaths.register)
        self.execute_script('localStorage.clear();')

        # Finding elements and doing other stuff

"Main" securety settings

    if mconf.use_proxy:
        proxies = my_proxys.get_proxys()

        if count > len(proxies):
            print(f'Only {len(proxies)} available\n'
                  f'Setting counter to maximum of {len(proxies)}')
            count = len(proxies)
    else:
        proxies = [0 for _ in range(count)]

    for i, proxy in zip(range(count), proxies):
        try:
            user = MyUserFactory.get_user()
            if doc.does_user_exist(user):
                same += 1
                continue

            opt = webdriver.ChromeOptions()
            opt.add_argument("disable-infobars")
            opt.add_argument("--incognito")
            prefs = {"profile.default_content_setting_values.geolocation": 2}
            opt.add_experimental_option("prefs", prefs)
            ua = rua.random
            print(ua)
            opt.add_argument(f"user-agent={ua}")
            opt.add_experimental_option('prefs', {'intl.accept_languages': 'en,en_US'})
            if proxy:
                # Setting up proxy package
                opt.add_argument('--proxy-server=%s' % proxy)

            # end
            iact = MyInstaAction(options=opt)
            iact.delete_all_cookies()

Does anybody how to get around this problem?


问:
Convert output of retrain.py to tensorflow.js
The script retrain.py described in How to Retrain an Image Classifier for New Categories was run as

```<code>python retrain.py --tfhub_module https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/feature_vector/2 --image_dir /tmp/test
</code>```

and produced the output file /tmp/output_graph.pb. Converting this with

```<code>tensorflowjs_converter --input_format=tf_saved_model --output_format=tfjs_graph_model /tmp/output_graph.pb /tmp/model
</code>```

failed with

IOError: SavedModel file does not exist at: /tmp/output_graph.pb/{saved_model.pbtxt|saved_model.pb}

If the file output_graph.pb is renamed to saved_model.pb (by @edkeveked), the error changes to

RuntimeError: MetaGraphDef associated with tags 'serve' could not be found in SavedModel. To inspect available tag-sets in the SavedModel, please use the SavedModel CLI: saved_model_cli

saved_model_cli show --dir . reports an empty tag set.

How can this be fixed?

答:
As hinted by @Ping Yu in Retrain image detection with MobileNet, you can use

```<code>python retrain.py --tfhub_module https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/feature_vector/2 \
    --image_dir /tmp/flower_photos --saved_model_dir /tmp/saved_retrained_model
tensorflowjs_converter --input_format=tf_saved_model \
    --output_format=tfjs_graph_model \
    --saved_model_tags=serve \
    /tmp/saved_retrained_model/ /tmp/converted_model/
</code>```

This saves the model using the saved model format.

Body:
The script retrain.py described in How to Retrain an Image Classifier for New Categories was run as

python retrain.py --tfhub_module https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/feature_vector/2 --image_dir /tmp/test

and produced the output file /tmp/output_graph.pb. Converting this with

tensorflowjs_converter --input_format=tf_saved_model --output_format=tfjs_graph_model /tmp/output_graph.pb /tmp/model

failed with

IOError: SavedModel file does not exist at: /tmp/output_graph.pb/{saved_model.pbtxt|saved_model.pb}

If the file output_graph.pb is renamed to saved_model.pb (by @edkeveked), the error changes to

RuntimeError: MetaGraphDef associated with tags 'serve' could not be found in SavedModel. To inspect available tag-sets in the SavedModel, please use the SavedModel CLI: saved_model_cli

saved_model_cli show --dir . reports an empty tag set.

How can this be fixed?

Body:
As hinted by @Ping Yu in Retrain image detection with MobileNet, you can use

python retrain.py --tfhub_module https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/feature_vector/2 \
    --image_dir /tmp/flower_photos --saved_model_dir /tmp/saved_retrained_model
tensorflowjs_converter --input_format=tf_saved_model \
    --output_format=tfjs_graph_model \
    --saved_model_tags=serve \
    /tmp/saved_retrained_model/ /tmp/converted_model/

This saves the model using the saved model format.