答:
Replace your existing ajax function like this</p>

```<code>$(document).ready(function() {
  var opt = '';
  var sta = '';
  $("#updateStatus").change(function() {
     opt = $("#updateStatus").val();
  });

  $("#updateStatus1").change(function() {
     sta = $("#updateStatus1").val();
     callAjax(opt,sta);
  });
});

function callAjax(opt,sta) {
  $.ajax({
    url: 'updatecode.php',
    type: 'POST',
    data: "opt=" + opt + "&sta=" + sta,
    dataType: 'json',
    success: function(data) {
      alert(data + "hello");
    }
  });
}
</code>```

Title: selecting 2 different option values and sending data to php using ajax

Body:
Replace your existing ajax function like this

$(document).ready(function() {
  var opt = '';
  var sta = '';
  $("#updateStatus").change(function() {
     opt = $("#updateStatus").val();
  });

  $("#updateStatus1").change(function() {
     sta = $("#updateStatus1").val();
     callAjax(opt,sta);
  });
});

function callAjax(opt,sta) {
  $.ajax({
    url: 'updatecode.php',
    type: 'POST',
    data: "opt=" + opt + "&sta=" + sta,
    dataType: 'json',
    success: function(data) {
      alert(data + "hello");
    }
  });
}


来源: stackexchange

问:
Best way to send and receive image files in JSON in webservice?
Please suggest the best way to send and receive image files using JSON?</p>

答:
Android: Upload image or file using http POST multi-part

By using multi-part ,  you will be able to upload a file from your SD Card and also Bitmap image as a file.

Prerequisite: httpmime-4.1-beta1.jar

Android SDK uses apache  http Client of version 3.0. That does not support for the mime type.

```<code>package com.isummation.fileupload;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;

public class FileUpload extends Activity {
    Bitmap bm;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
            // bm = BitmapFactory.decodeResource(getResources(),
            // R.drawable.forest);
            bm = BitmapFactory.decodeFile("/sdcard/DCIM/forest.png");
            executeMultipartPost();
        } catch (Exception e) {
            Log.e(e.getClass().getName(), e.getMessage());
        }
    }

    public void executeMultipartPost() throws Exception {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bm.compress(CompressFormat.JPEG, 75, bos);
            byte[] data = bos.toByteArray();
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost(
                    "http://10.0.2.2/cfc/iphoneWebservice.cfc?returnformat=json&method=testUpload");
            ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
            // File file= new File("/mnt/sdcard/forest.png");
            // FileBody bin = new FileBody(file);
            MultipartEntity reqEntity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("uploaded", bab);
            reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
            postRequest.setEntity(reqEntity);
            HttpResponse response = httpClient.execute(postRequest);
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent(), "UTF-8"));
            String sResponse;
            StringBuilder s = new StringBuilder();

            while ((sResponse = reader.readLine()) != null) {
                s = s.append(sResponse);
            }
            System.out.println("Response: " + s);
        } catch (Exception e) {
            // handle exception here
            Log.e(e.getClass().getName(), e.getMessage());
        }
    }
}
</code>```

See below link:

Multipart Image Upload

ContentLicense: CC BY-SA 3.0

Body:
Android: Upload image or file using http POST multi-part

By using multi-part ,  you will be able to upload a file from your SD Card and also Bitmap image as a file.

Prerequisite: httpmime-4.1-beta1.jar

Android SDK uses apache  http Client of version 3.0. That does not support for the mime type.

package com.isummation.fileupload;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;

public class FileUpload extends Activity {
    Bitmap bm;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
            // bm = BitmapFactory.decodeResource(getResources(),
            // R.drawable.forest);
            bm = BitmapFactory.decodeFile("/sdcard/DCIM/forest.png");
            executeMultipartPost();
        } catch (Exception e) {
            Log.e(e.getClass().getName(), e.getMessage());
        }
    }

    public void executeMultipartPost() throws Exception {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bm.compress(CompressFormat.JPEG, 75, bos);
            byte[] data = bos.toByteArray();
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost(
                    "http://10.0.2.2/cfc/iphoneWebservice.cfc?returnformat=json&amp;method=testUpload");
            ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
            // File file= new File("/mnt/sdcard/forest.png");
            // FileBody bin = new FileBody(file);
            MultipartEntity reqEntity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("uploaded", bab);
            reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
            postRequest.setEntity(reqEntity);
            HttpResponse response = httpClient.execute(postRequest);
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent(), "UTF-8"));
            String sResponse;
            StringBuilder s = new StringBuilder();

            while ((sResponse = reader.readLine()) != null) {
                s = s.append(sResponse);
            }
            System.out.println("Response: " + s);
        } catch (Exception e) {
            // handle exception here
            Log.e(e.getClass().getName(), e.getMessage());
        }
    }
}

See below link:

Multipart Image Upload


问:
Find the count of each category in a dataframe for uniques value of third column
I have dataframe df1:

```<code>A|A2|A3
-+--+--
a|ut|x
a|tv|y
a|ut|x
a|pq|y
a|ut|y
b|st|x
b|qp|x
b|nt|y
c|st|x
c|st|x
c|st|y
c|st|z
</code>```

I want to know the frequency of A2 with unique A3 for each A, i.e. I want following output:

```<code>A|A2|freq
-+--+----
a|ut|2
a|tv|1
a|pq|1
b|st|1
b|qp|1
b|nt|1
c|st|3
</code>```

I tried

```<code>count(df1, A, A2, A3)
</code>```

but get the error

Error in count(df1, A, A2, A3)  :  unused argument A3

答:
You can use aggregate for this:

```<code>> aggregate(A3 ~ A+A2, data=df1, FUN=function(x) length(unique(x)))
  A A2 A3
1 b nt  1
2 a pq  1
3 b qp  1
4 b st  1
5 c st  3
6 a tv  1
7 a ut  2
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have dataframe df1:

A|A2|A3
-+--+--
a|ut|x
a|tv|y
a|ut|x
a|pq|y
a|ut|y
b|st|x
b|qp|x
b|nt|y
c|st|x
c|st|x
c|st|y
c|st|z

I want to know the frequency of A2 with unique A3 for each A, i.e. I want following output:

A|A2|freq
-+--+----
a|ut|2
a|tv|1
a|pq|1
b|st|1
b|qp|1
b|nt|1
c|st|3

I tried

count(df1, A, A2, A3)

but get the error

Error in count(df1, A, A2, A3)  :  unused argument A3

Body:
You can use aggregate for this:

> aggregate(A3 ~ A+A2, data=df1, FUN=function(x) length(unique(x)))
  A A2 A3
1 b nt  1
2 a pq  1
3 b qp  1
4 b st  1
5 c st  3
6 a tv  1
7 a ut  2


问:
Error while installing Bot Framework Emulator on Ubuntu
I am unable to install microsoft emulator on ubuntu 16.04.

I downloaded BotFramework-Emulator-3.5.29.zip file from the portal, then extracted it and run npm install successfully (but got the following message):

```<code>npm WARN optional SKIPPING OPTIONAL DEPENDENCY: 7zip-bin-mac@^1.0.1(node_modules/7zip-bin/node_modules/7zip-bin-mac):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for 7zip-bin-mac@1.0.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: 7zip-bin-win@^2.1.0 (node_modules/7zip-bin/node_modules/7zip-bin-win):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for 7zip-bin-win@2.1.0: wanted {"os":"win32","arch":"any"} (current: {"os":"linux","arch":"x64"})
</code>```

Then gulp build-app throws the following error:

```<code>[14:32:40] Using gulpfile /var/www/BotFramework-Emulator-3.5.29/gulpfile.js
[14:32:40] Starting 'clean'...
[14:32:40] Finished 'clean' after 23 ms
[14:32:40] Starting 'build-app'...
[14:32:40] Compiling TypeScript files using tsc version 2.1.5
[14:32:46] [tsc] > node_modules/botframework-directlinejs/built/directLine.d.ts(204,13): error TS2304: Cannot find name 'object'.
[14:32:46] Failed to compile TypeScript: Error: tsc command has exited with code:1

  events.js:160
  throw er; // Unhandled 'error' event
  ^
Error: Failed to compile: tsc command has exited with code:1
</code>```

答:
add the latest dependancies in package.json, may be some dependancies version changed after development
I changed all the version in package.json

```<code>"dependencies": {    "gulp-debug": "2.1.2",
"gulp-filter": "4.0.0",
"gulp-flatmap": "1.0.0",
"gulp-inject": "4.2.0",
"gulp-rename": "1.2.2",
"gulp-tsc": "1.2.6",
"gulp-util": "3.0.8",
"license-list": "0.1.3",
"object-assign": "4.1.0",
"tslib": "1.5.0",
"typescript": "2.2.2",
"vinyl": "2.0.1",
"vinyl-fs": "2.4.4"
},
</code>```

then rebuild the gulp app

```<code>build gulp-app
</code>```

then run the project with

```<code>npm start
</code>```

this resolved me all issues and all works smooth

Body:
I am unable to install microsoft emulator on ubuntu 16.04.

I downloaded BotFramework-Emulator-3.5.29.zip file from the portal, then extracted it and run npm install successfully (but got the following message):

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: 7zip-bin-mac@^1.0.1(node_modules/7zip-bin/node_modules/7zip-bin-mac):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for 7zip-bin-mac@1.0.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: 7zip-bin-win@^2.1.0 (node_modules/7zip-bin/node_modules/7zip-bin-win):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for 7zip-bin-win@2.1.0: wanted {"os":"win32","arch":"any"} (current: {"os":"linux","arch":"x64"})

Then gulp build-app throws the following error:

[14:32:40] Using gulpfile /var/www/BotFramework-Emulator-3.5.29/gulpfile.js
[14:32:40] Starting 'clean'...
[14:32:40] Finished 'clean' after 23 ms
[14:32:40] Starting 'build-app'...
[14:32:40] Compiling TypeScript files using tsc version 2.1.5
[14:32:46] [tsc] > node_modules/botframework-directlinejs/built/directLine.d.ts(204,13): error TS2304: Cannot find name 'object'.
[14:32:46] Failed to compile TypeScript: Error: tsc command has exited with code:1

  events.js:160
  throw er; // Unhandled 'error' event
  ^
Error: Failed to compile: tsc command has exited with code:1

Body:
add the latest dependancies in package.json, may be some dependancies version changed after development
I changed all the version in package.json

"dependencies": {    "gulp-debug": "2.1.2",
"gulp-filter": "4.0.0",
"gulp-flatmap": "1.0.0",
"gulp-inject": "4.2.0",
"gulp-rename": "1.2.2",
"gulp-tsc": "1.2.6",
"gulp-util": "3.0.8",
"license-list": "0.1.3",
"object-assign": "4.1.0",
"tslib": "1.5.0",
"typescript": "2.2.2",
"vinyl": "2.0.1",
"vinyl-fs": "2.4.4"
},

then rebuild the gulp app

build gulp-app

then run the project with

npm start

this resolved me all issues and all works smooth


问:
mdInput messages show animation called on invalid messages element:
Not sure why I'm getting the following message. Has anyone else encountered this in AngularJS/Angular Material? What am I doing wrong? The message itself seems a little vague.</p>

```<code>mdInput messages show animation called on invalid messages element:
md-input-container.md-block.md-icon-right.md-default-theme.md-input-has-value
</code>```

答:
Old question, but just in case anyone bumps into this, you need to supply an error message for the input field. The error is saying that it can't animate the error message into view because the messages element is missing.

In your md-input-container include the ng-messages element to handle the error. For example, if you have a form called myFrm with a required email address input named email, your code would be something like this:

```<code><form name="myFrm">
  <md-input-container>
    <label>Email Address</label>
    <input type="email" ng-model="myFrm.email" name="email" required/>
    <div ng-messages="myFrm.email.$error">
      <div ng-message="required">Email address is required</div>
    </div>
  </md-input-container>
  <!-- Other form elements.... -->
</form>
</code>```

Body:
Not sure why I'm getting the following message. Has anyone else encountered this in AngularJS/Angular Material? What am I doing wrong? The message itself seems a little vague.

mdInput messages show animation called on invalid messages element:
md-input-container.md-block.md-icon-right.md-default-theme.md-input-has-value

Body:
Old question, but just in case anyone bumps into this, you need to supply an error message for the input field. The error is saying that it can't animate the error message into view because the messages element is missing.

In your md-input-container include the ng-messages element to handle the error. For example, if you have a form called myFrm with a required email address input named email, your code would be something like this:

<form name="myFrm">
  <md-input-container>
    <label>Email Address</label>
    <input type="email" ng-model="myFrm.email" name="email" required/>
    <div ng-messages="myFrm.email.$error">
      <div ng-message="required">Email address is required</div>
    </div>
  </md-input-container>
  <!-- Other form elements.... -->
</form>


问:
selecting 2 different option values and sending data to php using ajax
I am taking two different values from select options and sending it using AJAX, but PHP is not responding to the request.

This is my jQuery code:

```<code>$(document).ready(function() {
  $("#updateStatus").change(function() {
    var opt = $("#updateStatus").val();

    $("#updateStatus1").change(function() {
      var sta = $("#updateStatus1").val();

      $.ajax({
        url: 'updatecode.php',
        type: 'POST',
        data: "option=" + opt + "&status=" + sta,
        dataType: 'json',
        success: function(data) {
          alert(data + "hello");
        }
      });
    });
  });
});
</code>```

This is my PHP code:

```<code>$id = $_POST['opt'];
$status = $_POST['sta'];
$query = "UPDATE projectstable SET projectStatus='".$status."'WHERE id='".$id."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);

if (!$row) {
  echo json_encode("fail");
} else {
  echo json_encode("sucess");
}
</code>```

答:
You are passing the json body as a query string, and you are declaring to use dataType: "json"

```<code>$.ajax({
        url: 'updatecode.php',
        type: 'POST',
        data: "option=" + opt + "&status=" + sta,
        dataType: 'json',
        success: function(data) {
          alert(data + "hello");
        }
 });
</code>```

instead that you should do it like this:

```<code>$.ajax({
        url: 'updatecode.php',
        type: 'POST',
        data: {"option": opt, "status": sta},
        dataType: 'json',
        success: function(data) {
          alert(data + "hello");
        }
});
</code>```

Body:
I am taking two different values from select options and sending it using AJAX, but PHP is not responding to the request.

This is my jQuery code:

$(document).ready(function() {
  $("#updateStatus").change(function() {
    var opt = $("#updateStatus").val();

    $("#updateStatus1").change(function() {
      var sta = $("#updateStatus1").val();

      $.ajax({
        url: 'updatecode.php',
        type: 'POST',
        data: "option=" + opt + "&status=" + sta,
        dataType: 'json',
        success: function(data) {
          alert(data + "hello");
        }
      });
    });
  });
});

This is my PHP code:

$id = $_POST['opt'];
$status = $_POST['sta'];
$query = "UPDATE projectstable SET projectStatus='".$status."'WHERE id='".$id."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);

if (!$row) {
  echo json_encode("fail");
} else {
  echo json_encode("sucess");
}

Body:
You are passing the json body as a query string, and you are declaring to use dataType: "json"

$.ajax({
        url: 'updatecode.php',
        type: 'POST',
        data: "option=" + opt + "&status=" + sta,
        dataType: 'json',
        success: function(data) {
          alert(data + "hello");
        }
 });

instead that you should do it like this:

$.ajax({
        url: 'updatecode.php',
        type: 'POST',
        data: {"option": opt, "status": sta},
        dataType: 'json',
        success: function(data) {
          alert(data + "hello");
        }
});


问:
How can I create a count down timer for cocos2d?
I am developing a 2D iPhone game by using cocos2d. I need a countdown timer. How can I create a count down timer in cocos2d?</p>

答:
Look at NSTimer, it can most likely provide any needed timer functionality.

NSTimer class reference

OwnerDisplayName: Nahid

LastEditorDisplayName: Adam Rosenfield

ContentLicense: CC BY-SA 2.5


问:
Open Closed Principle and Strategy Pattern Question
I have a couple of ideas but I wanted to see what the SO community would suggest.

I have an abstract class with an abstract Calculate method on it. I have 2 implementations of it that calculate differently. This screams Strategy pattern to me however one of the implementations requires that a selected_type variable be set because it is used inside the Calculate method. I want to follow the OCP so my Calculate method shouldn't take in the dependencies.

This class is retrieved from the DB via NHibernate and the selected_type variable won't be set until after the object has been created. I'm trying to avoid an if statement to set the selected_type only if it is of a specific implementation. What would be the best way?

Here is a code example:

```<code>public abstract class TagType
{
        public virtual long id { get; protected set; }
        public virtual string description { get; protected set; }

        protected TagType(){}

        protected TagType(string description)
        {
            this.description = description;
        }

        public abstract decimal Calculate();
}

public class TagTypeImpl1
{
    public virtual int tag_months { get; protected set; }

    protected TagType() { }

    protected TagType(string description, int tag_months): base(description)
    {
        this.tag_months = tag_months;
    }

    public override decimal Calculate()
    {
        return (12*tag_months);
    }
}

public class TagTypeImpl2
{
    public virtual int tag_months { get; protected set; }
    public virtual TagType selected_tag_type { get; protected set; }

    protected TagType() { }

    protected TagType(string description, int tag_months, TagType selected_tag_type): base(description)
    {
        this.tag_months = tag_months;
        this.selected_tag_type = selected_tag_type;
    }

    public override decimal Calculate()
    {
        return selected_tag_type.Calculate() + (12*tag_months);
    }
}

public class ConsumerController
{
    private readonly IRepository<TagType> repository;

    public ConsumerController(IRepository<TagType> repository)
    {
        this.repository = repository;
    }

    public ActionResult Index(long id)
    {
        var tag_type = repository.get(id);

        //If using TagTypeImpl2 then the selected_tag_type variable needs to be set
        //I want to avoid if(tag_type.GetType() == typeof(TagTypeImpl2)) set selected_tag_type
        var result = tag_type.Calculate();

        return Json(new {result});
    }
}
</code>```

I might be trying to do too much with this class adn maybe the persisted entity class is the wrong place to have the Calculate method but it seemed the best place since it knows the most about how to do the calculation.

答:
It's not the responsibility of your class to decide what the strategies need, it's the responsibility of the strategy. The whole idea is that you can call whatever strategy you're using the same way, all the time.

Simply make all strategies implement the same interface -including selected_type-, but one of them ignores the selected_type, the other uses it. It's up to the strategy itself to decide this.

Alternatively, your implementations of strategy can have more properties than are defined in the interface. If you can initialize the strategies from outside of your class, and it's not a problem for the initializing class to know more about the specific implementation you might be able to set the properties for only the specific strategy that needs it. The former solution is cleaner though (always using the same interface).

Body:
I have a couple of ideas but I wanted to see what the SO community would suggest.

I have an abstract class with an abstract Calculate method on it. I have 2 implementations of it that calculate differently. This screams Strategy pattern to me however one of the implementations requires that a selected_type variable be set because it is used inside the Calculate method. I want to follow the OCP so my Calculate method shouldn't take in the dependencies.

This class is retrieved from the DB via NHibernate and the selected_type variable won't be set until after the object has been created. I'm trying to avoid an if statement to set the selected_type only if it is of a specific implementation. What would be the best way?

Here is a code example:

public abstract class TagType
{
        public virtual long id { get; protected set; }
        public virtual string description { get; protected set; }

        protected TagType(){}

        protected TagType(string description)
        {
            this.description = description;
        }

        public abstract decimal Calculate();
}

public class TagTypeImpl1
{
    public virtual int tag_months { get; protected set; }

    protected TagType() { }

    protected TagType(string description, int tag_months): base(description)
    {
        this.tag_months = tag_months;
    }

    public override decimal Calculate()
    {
        return (12*tag_months);
    }
}

public class TagTypeImpl2
{
    public virtual int tag_months { get; protected set; }
    public virtual TagType selected_tag_type { get; protected set; }

    protected TagType() { }

    protected TagType(string description, int tag_months, TagType selected_tag_type): base(description)
    {
        this.tag_months = tag_months;
        this.selected_tag_type = selected_tag_type;
    }

    public override decimal Calculate()
    {
        return selected_tag_type.Calculate() + (12*tag_months);
    }
}

public class ConsumerController
{
    private readonly IRepository<TagType> repository;

    public ConsumerController(IRepository<TagType> repository)
    {
        this.repository = repository;
    }

    public ActionResult Index(long id)
    {
        var tag_type = repository.get(id);

        //If using TagTypeImpl2 then the selected_tag_type variable needs to be set
        //I want to avoid if(tag_type.GetType() == typeof(TagTypeImpl2)) set selected_tag_type
        var result = tag_type.Calculate();

        return Json(new {result});
    }
}

I might be trying to do too much with this class adn maybe the persisted entity class is the wrong place to have the Calculate method but it seemed the best place since it knows the most about how to do the calculation.


问:
How to integrate LUIS to a QnA bot Azure
So I was recently tinkering with Azure Bot Services and Q&A but I noticed it didn't answer everything correctly and didn't get the intent sometimes so I decided to add LUIS to it but I don't really get how to integrate it to the bot. (They give a code sample but I don't really know where to put it).

I also wanted to know if there's a way for me to change the Q&A bot's language from English to French because most of my customers are French.

答: See another sample here to use QnA+LUIS together: https://github.com/Microsoft/BotBuilder-CognitiveServices/tree/master/Node/samples</p>


问:
Initialising mock in new objects
My class cannot autowired UserService - it throws NullPointerException. I would like to find a way to test UserValidator class. I don't know how to inject mocks in ExistingValidationRule class.</p>

```<code>public class ExistingValidationRule implements RegistrationRule<User> {
@Autowired
private UserService service;

@Override
public void validate(User user, Errors errors) {

    service.find(user, errors);
}
}

@Component
public class UserValidator implements Validator {

    @Override
    public void validate(Object o, Errors errors) {
        User user = (User) o;
        rules.add(new ExistingValidationRule());

        for(RegistrationRule<User> rule : rules){
            rule.validate(user, errors);
        }
    }
}

public class UserValidatorTest {
@InjectMocks
private UserValidator userValidator;

@InjectMocks
private ExistingValidationRule existingValidationRule;

@Mock
private UserService service;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}
@Test
    public void testValidUser() throws Exception{

        userValidator.validate(createdUser,errors);
}
</code>```

答:
```<code>class UserValidator
// if all roles that you need are spring beans- then do autowired then by super type
@Autowired
privete Collection<RegistrationRule> roles ;

@Override
public void validate(Object o, Errors errors) {
    User user = (User) o;

    // all spring-bean configured validators were autowired
    for(RegistrationRule<User> rule : rules){
        rule.validate(user, errors);
    }
}
</code>```

or

```<code>@Component
public class UserValidator implements Validator {
    //if rules was created before
    @Autowired
    public void setExistingValidationRule(ExistingValidationRule existingValidationRule){
        rules.add(existingValidationRule);
    }

@Override
public void validate(Object o, Errors errors) {
    User user = (User) o;

    for(RegistrationRule<User> rule : rules){
        rule.validate(user, errors);
    }
}
</code>```

and try to avoid adding new responsibility in method validate() - like add new validator. method validate  should do only validation , nothing more

Title: Initialising mock in new objects

Body:
My class cannot autowired UserService - it throws NullPointerException. I would like to find a way to test UserValidator class. I don't know how to inject mocks in ExistingValidationRule class.

public class ExistingValidationRule implements RegistrationRule<User> {
@Autowired
private UserService service;

@Override
public void validate(User user, Errors errors) {

    service.find(user, errors);
}
}

@Component
public class UserValidator implements Validator {

    @Override
    public void validate(Object o, Errors errors) {
        User user = (User) o;
        rules.add(new ExistingValidationRule());

        for(RegistrationRule<User> rule : rules){
            rule.validate(user, errors);
        }
    }
}

public class UserValidatorTest {
@InjectMocks
private UserValidator userValidator;

@InjectMocks
private ExistingValidationRule existingValidationRule;

@Mock
private UserService service;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}
@Test
    public void testValidUser() throws Exception{

        userValidator.validate(createdUser,errors);
}

Body:
class UserValidator
// if all roles that you need are spring beans- then do autowired then by super type
@Autowired
privete Collection<RegistrationRule> roles ;

@Override
public void validate(Object o, Errors errors) {
    User user = (User) o;

    // all spring-bean configured validators were autowired
    for(RegistrationRule<User> rule : rules){
        rule.validate(user, errors);
    }
}

or

@Component
public class UserValidator implements Validator {
    //if rules was created before
    @Autowired
    public void setExistingValidationRule(ExistingValidationRule existingValidationRule){
        rules.add(existingValidationRule);
    }

@Override
public void validate(Object o, Errors errors) {
    User user = (User) o;

    for(RegistrationRule<User> rule : rules){
        rule.validate(user, errors);
    }
}

and try to avoid adding new responsibility in method validate() - like add new validator. method validate  should do only validation , nothing more


问:
Android / Java find the correct library for a particular class
How can I figure out which class needs to import which library?
For example, I see a sample code like below:

```<code>RequestQueue queue = Volley.newRequestQueue(this);
</code>```

When I try this code Android Studio throws that RequestQueue and Volley cannot resolve.
Is there any documentation, wiki, a website for finding out the correct import library for these classes?

答:
There is a library that you can use for parsing and this code is related to Volley library to remove that error you must check that library is in your project or not.

Check your build.gradlefile(App)

```<code>dependencies {
    ...
    compile 'com.android.volley:volley:1.0.0'
}
</code>```

If above line is there then you can use that library

Body:
How can I figure out which class needs to import which library?
For example, I see a sample code like below:

RequestQueue queue = Volley.newRequestQueue(this);

When I try this code Android Studio throws that RequestQueue and Volley cannot resolve.
Is there any documentation, wiki, a website for finding out the correct import library for these classes?

Body:
There is a library that you can use for parsing and this code is related to Volley library to remove that error you must check that library is in your project or not.

Check your build.gradlefile(App)

dependencies {
    ...
    compile 'com.android.volley:volley:1.0.0'
}

If above line is there then you can use that library


问:
Forge Viewer select element by tapping screen not working correctly on Surface Pro using IE 11 (via cordova)
Using Surface pro touch screen to select element in viewer works sometimes other times it seems to translate to a rotate/zoom action. In this case the viewer rotates/moves and the element is NOT selected.

When logging the events there are plenty of mouse down/up events along with mouse moves when it doesnt work. When select does work a single click event occurs.

Double click seems to work ok.
Zoom/rotate etc using standard tools works ok.

Using the keyboard cover touch pad that you can get for the Surface pro to move and click works as expected and the element is selected.

Running same application on a GETAC Windows 10 ruggadised tablet the select element works correctly so it seems related to the Surface Pro.

Unable to change browsers as cordova apps use IE11 on windows and that is currently fixed.

The only solution i can think of for the moment is to remove the standard navigation tools completely (somehow) and recreate a select mode tool that would ignore any mouse moves and use button down event to select element.

Any suggestions on how to fix this?

Tech Details:
Windows 10 Pro,
Surface Pro,
Browser: IE11,
Viewer version 2.11,
Other: WINJS81 cordova application

Thanks for any help

答:
Found a fix to this issue. In viewer3D in the base toolcontroller there is line

```<code>var kClickThreshold = 2;
</code>```

This value is used further down in code to determine if singleClick has occured. It does it by comparing XY on down and up events.

```<code>var deltaX = _downX - event.canvasX;
var deltaY = _downY - event.canvasY;

_downX = -1;
_downY = -1;

if( Math.abs(deltaX) <= kClickThreshold && Math.abs(deltaY) <= kClickThreshold )
    _this.handleSingleClick( event );
</code>```

If movement is above this threshold it does not trigger singleClick if below it does.

Did testing and increasing the value to around 5-7 means that the selection of elements worked consistently. (there is still a minor rotate or zoom at same time as select occurs but I assume that this would be another part of viewer that would need adjusting)

Unfortunately it does require edit of viewer code but easy enough. I added code to overwrite standard value if external variable existed.

Would be nice for future viewer dev if more of these types of properties be exposed so that direct edit of code is not required.

Still it is good to have the source code to be able to debug at this level.

At a guess the Surface Pro 4 must have a more sensitive touch system or it could just be related to IE11 as well.

Body:
Found a fix to this issue. In viewer3D in the base toolcontroller there is line

var kClickThreshold = 2;

This value is used further down in code to determine if singleClick has occured. It does it by comparing XY on down and up events.

var deltaX = _downX - event.canvasX;
var deltaY = _downY - event.canvasY;

_downX = -1;
_downY = -1;

if( Math.abs(deltaX) <= kClickThreshold && Math.abs(deltaY) <= kClickThreshold )
    _this.handleSingleClick( event );

If movement is above this threshold it does not trigger singleClick if below it does.

Did testing and increasing the value to around 5-7 means that the selection of elements worked consistently. (there is still a minor rotate or zoom at same time as select occurs but I assume that this would be another part of viewer that would need adjusting)

Unfortunately it does require edit of viewer code but easy enough. I added code to overwrite standard value if external variable existed.

Would be nice for future viewer dev if more of these types of properties be exposed so that direct edit of code is not required.

Still it is good to have the source code to be able to debug at this level.

At a guess the Surface Pro 4 must have a more sensitive touch system or it could just be related to IE11 as well.


问:
numpy boolean array with 1 bit entries
Is there a way in numpy to create an array of booleans that uses just 1 bit for each entry?

The standard np.bool type is 1 byte, but this way I use 8 times the required memory.

On Google I found that C++ has std::vector<bool>.

答:
To do this you can use numpy's packbits and unpackbits:

```<code>import numpy as np
# original boolean array
A1 = np.array([
    [0, 1, 1, 0, 1],
    [0, 0, 1, 1, 1],
    [1, 1, 1, 1, 1],
], dtype=bool)

# packed data
A2 = np.packbits(A1, axis=None)

# checking the size
print(len(A1.tostring())) # 15 bytes
print(len(A2.tostring())) #  2 bytes (ceil(15/8))

# reconstructing from packed data. You need to resize and reshape
A3 = np.unpackbits(A2, count=A1.size).reshape(A1.shape).view(bool)

# and the arrays are equal
print(np.array_equal(A1, A3)) # True
</code>```

Prior to numpy 1.17.0, the first function is straight-forward to use, but reconstruction required additional manipulations. Here is an example:

```<code>import numpy as np
# original boolean array
A1 = np.array([
    [0, 1, 1, 0, 1],
    [0, 0, 1, 1, 1],
    [1, 1, 1, 1, 1],
], dtype=np.bool)

# packed data
A2 = np.packbits(A1, axis=None)

# checking the size
print(len(A1.tostring())) # 15 bytes
print(len(A2.tostring())) #  2 bytes (ceil(15/8))

# reconstructing from packed data. You need to resize and reshape
A3 = np.unpackbits(A2, axis=None)[:A1.size].reshape(A1.shape).astype(np.bool)

# and the arrays are equal
print(np.array_equal(A1, A3)) # True
</code>```

Title: numpy boolean array with 1 bit entries

Body:
To do this you can use numpy's packbits and unpackbits:

import numpy as np
# original boolean array
A1 = np.array([
    [0, 1, 1, 0, 1],
    [0, 0, 1, 1, 1],
    [1, 1, 1, 1, 1],
], dtype=bool)

# packed data
A2 = np.packbits(A1, axis=None)

# checking the size
print(len(A1.tostring())) # 15 bytes
print(len(A2.tostring())) #  2 bytes (ceil(15/8))

# reconstructing from packed data. You need to resize and reshape
A3 = np.unpackbits(A2, count=A1.size).reshape(A1.shape).view(bool)

# and the arrays are equal
print(np.array_equal(A1, A3)) # True

Prior to numpy 1.17.0, the first function is straight-forward to use, but reconstruction required additional manipulations. Here is an example:

import numpy as np
# original boolean array
A1 = np.array([
    [0, 1, 1, 0, 1],
    [0, 0, 1, 1, 1],
    [1, 1, 1, 1, 1],
], dtype=np.bool)

# packed data
A2 = np.packbits(A1, axis=None)

# checking the size
print(len(A1.tostring())) # 15 bytes
print(len(A2.tostring())) #  2 bytes (ceil(15/8))

# reconstructing from packed data. You need to resize and reshape
A3 = np.unpackbits(A2, axis=None)[:A1.size].reshape(A1.shape).astype(np.bool)

# and the arrays are equal
print(np.array_equal(A1, A3)) # True


问:
Tuple and List to formatted string in python
In Python3.4 I have a tuple

```<code>t = ('A', 'B', 'C')
</code>```

and a list

```<code>l = ['P', 'Q', 'R']
</code>```

and I need to convert the tuple to a string formatted as "(#A;#B;#C)" and the list to a string formatted as "(@P; @Q; @R)". The obvious way is to traverse using a for loop and string manipulation.

Is there a way to do it without running the loop?

Thanks!

答:
Why not use a loop? This can be done very simply using a comprehension:</p>

```<code>>>> t = ('A', 'B', 'C')
>>> '({})'.format(';'.join('#{}'.format(s) for s in t))
'(#A;#B;#C)'
>>>
>>> l = ['P', 'Q', 'R']
>>> '({})'.format('; '.join('@{}'.format(s) for s in l))
'(@P; @Q; @R)'
>>>
</code>```

Body:
In Python3.4 I have a tuple

t = ('A', 'B', 'C')

and a list

l = ['P', 'Q', 'R']

and I need to convert the tuple to a string formatted as "(#A;#B;#C)" and the list to a string formatted as "(@P; @Q; @R)". The obvious way is to traverse using a for loop and string manipulation.

Is there a way to do it without running the loop?

Thanks!

Body:
Why not use a loop? This can be done very simply using a comprehension:

>>> t = ('A', 'B', 'C')
>>> '({})'.format(';'.join('#{}'.format(s) for s in t))
'(#A;#B;#C)'
>>>
>>> l = ['P', 'Q', 'R']
>>> '({})'.format('; '.join('@{}'.format(s) for s in l))
'(@P; @Q; @R)'
>>>


问:
Isn't "document.body.firstChild.nodeName" = tagName of first element of body?
The alertbox displays '#text'. It should say 'h1' by my understanding. What is wrong?</p>

```<code><!DOCTYPE html>
<html>
<body id="bodi">

<h1 id="id01">My First Page</h1>

<script>
alert(document.body.firstChild.nodeName);
</script>
</body>
</html>
</code>```

答:
The firstElementChild property returns only elements, while the firstChild property returns element, #text, #comment... So To return h1, you have to use firstElementChild property

```<code><script>
  alert(document.body.firstElementChild.tagName);
</script>
</code>```

or

```<code><script>
  alert(document.getElementById("id01").tagName);
</script>
</code>```

Body:
The alertbox displays '#text'. It should say 'h1' by my understanding. What is wrong?

<!DOCTYPE html>

My First Page

Body:
The firstElementChild property returns only elements, while the firstChild property returns element, #text, #comment... So To return h1, you have to use firstElementChild property

<script>
  alert(document.body.firstElementChild.tagName);
</script>

or

<script>
  alert(document.getElementById("id01").tagName);
</script>


问:
Array of two types
I have two arrays :

```<code>Array
(
    [0] => Mon
    [1] => Sun
)

Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] => 4
        )

    [1] => Array
        (
            [date] => 2010-12-19
            [hours] => 2.0
        )

)
</code>```

How to combine both as:

```<code>Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] => 4
     [day] => Mon
        )

    [1] => Array
        (
            [date] => 2010-12-19
            [hours] => 2.0
     [day] => Sun
        )

)
</code>```

Thanks -
Haan

答:
updated.

```<code>$secondArray[0]['day'] = $firstArray[0];
$secondArray[1]['day'] = $firstArray[1];
</code>```

if you are sure thay they are both the same size:

```<code>for($i = 0; $i < count($firstArray); $i++)
{
    $secondArray[$i]['day'] = $firstArray[$i];
}
</code>```

Title: Array of two types

Body:
I have two arrays :

Array
(
    [0] => Mon
    [1] => Sun
)

Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] => 4
        )

    [1] => Array
        (
            [date] => 2010-12-19
            [hours] => 2.0
        )

)

How to combine both as:

Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] => 4
     [day] => Mon
        )

    [1] => Array
        (
            [date] => 2010-12-19
            [hours] => 2.0
     [day] => Sun
        )

)

Thanks -
Haan

Body:
updated.

$secondArray[0]['day'] = $firstArray[0];
$secondArray[1]['day'] = $firstArray[1];

if you are sure thay they are both the same size:

for($i = 0; $i < count($firstArray); $i++)
{
    $secondArray[$i]['day'] = $firstArray[$i];
}


问:
ngx-translate: loading i18n json from firebase in ionic3
In an Ionic3 app what are the ways I could load the language JSON's for ngx-translate? Current approach given on github mention about keeping JSON files for each language in assets folder. The problem with this approach is that every time I have to add a new language support I have to release a new version of app. Is there a way we could load JSON from Firebase?</p>

答:
I was able to create a new TranslateLoader which would fetch from Firebase. Here is the code:</p>

```<code>import {AngularFireDatabase} from 'angularfire2/database';
import {TranslateLoader} from "@ngx-translate/core";

export class TranslateFirebaseLoader implements TranslateLoader {
    constructor(public db : AngularFireDatabase) {}

    /**
     * Gets the translations from firebase
     * @param lang
     * @returns {any}
     */
    public getTranslation(lang: string): any {
      return this.db.list('/translations/'+lang)
            .map(data => {
              let fields={};
              data.forEach(field =>{
                fields[field.$key]=field.$value;
              });
              return fields;
            });
    }
}
</code>```

Body:
I was able to create a new TranslateLoader which would fetch from Firebase. Here is the code:

import {AngularFireDatabase} from 'angularfire2/database';
import {TranslateLoader} from "@ngx-translate/core";

export class TranslateFirebaseLoader implements TranslateLoader {
    constructor(public db : AngularFireDatabase) {}

    /**
     * Gets the translations from firebase
     * @param lang
     * @returns {any}
     */
    public getTranslation(lang: string): any {
      return this.db.list('/translations/'+lang)
            .map(data => {
              let fields={};
              data.forEach(field =>{
                fields[field.$key]=field.$value;
              });
              return fields;
            });
    }
}


问:
SQL query to find counts of numbers in running total
Suppose the table has 1 column ID and the values are as below:

```<code>ID
5
5
5
6
5
5
6
6
</code>```

the output should be

```<code>ID  count
5    3
6    1
5    2
6    2
</code>```

How can we do that in a single SQL query.

答:
In relational databases data in the table has no any order, see this: https://en.wikipedia.org/wiki/Table_(database)

the database system does not guarantee any ordering of the rows unless
  an ORDER BY clause is specified in the SELECT statement that queries
  the table.

therefore, in order to get desired results, you must have an additional colum in the table that defines an order of rows (and can by used in ORDER BY clause).

In the below examle cn column defines such an order:

```<code>select * from tab123 ORDER BY rn;

        RN ID
---------- -------
         1 5
         2 5
         3 5
         4 6
         5 5
         6 5
         7 6
         8 6
</code>```

Starting from Oracle version 12c new MATCH_REGOGNIZE clause can be used:

```<code>select * from tab123
match_recognize(
   order by rn
   measures
     strt.id as id,
     count(*) as cnt
   one row per match
   after match skip past last row
   pattern( strt ss* )
   define ss as ss.id = prev( ss.id )
);
</code>```

On earlier versions that support windows function (Oracle 10 and above) you can use two windows functions: LAG ... over and SUM ... over, in this way

```<code>select max( id ) as id, count(*) as cnt
FROM (
    select id, sum( xxx ) over (order by rn ) as yyy
    from (
        select t.*,
               case lag( id ) over (order by rn )
               when id then 0 else 1 end as xxx
        from tab123 t
    )
)
GROUP BY yyy
ORDER BY yyy;
</code>```

Body:
Suppose the table has 1 column ID and the values are as below:

ID
5
5
5
6
5
5
6
6

the output should be

ID  count
5    3
6    1
5    2
6    2

How can we do that in a single SQL query.

Body:
In relational databases data in the table has no any order, see this: https://en.wikipedia.org/wiki/Table_(database)

the database system does not guarantee any ordering of the rows unless
  an ORDER BY clause is specified in the SELECT statement that queries
  the table.

therefore, in order to get desired results, you must have an additional colum in the table that defines an order of rows (and can by used in ORDER BY clause).

In the below examle cn column defines such an order:

select * from tab123 ORDER BY rn;

        RN ID
---------- -------
         1 5
         2 5
         3 5
         4 6
         5 5
         6 5
         7 6
         8 6

Starting from Oracle version 12c new MATCH_REGOGNIZE clause can be used:

select * from tab123
match_recognize(
   order by rn
   measures
     strt.id as id,
     count(*) as cnt
   one row per match
   after match skip past last row
   pattern( strt ss* )
   define ss as ss.id = prev( ss.id )
);

On earlier versions that support windows function (Oracle 10 and above) you can use two windows functions: LAG ... over and SUM ... over, in this way

select max( id ) as id, count(*) as cnt
FROM (
    select id, sum( xxx ) over (order by rn ) as yyy
    from (
        select t.*,
               case lag( id ) over (order by rn )
               when id then 0 else 1 end as xxx
        from tab123 t
    )
)
GROUP BY yyy
ORDER BY yyy;


问:
PL/SQL Triggers -firing question3
i try to answer this question:

Create a trigger that displays "insert book" after each insert.

i try :

```<code>create trigger insert_book after insert on Books
for each rows
begin
insert into books (id_book,title) values(12,'book12');
end;
</code>```

答:
Try this.... for trigger</p>

```<code>CREATE TRIGGER insert_book ON [dbo].[Books]
FOR INSERT
AS
    insert into books (id_book,title) values(12,'book12');
    PRINT 'Insert Book'
GO
</code>```

Title: PL/SQL Triggers -firing question3

Body:
i try to answer this question:

Create a trigger that displays "insert book" after each insert.

i try :

create trigger insert_book after insert on Books
for each rows
begin
insert into books (id_book,title) values(12,'book12');
end;

Body:
Try this.... for trigger

CREATE TRIGGER insert_book ON [dbo].[Books]
FOR INSERT
AS
    insert into books (id_book,title) values(12,'book12');
    PRINT 'Insert Book'
GO


问:
In Dart, Angular2 3.x requires AppComponent to have a getter 'toggled'
I'm programming a client web app in Dart, using Angular2.

Since Version 3.x of the dart's angular2 package the AppComponent (or whatever class is bootstrapped from main()) requires a getter toggled. If it's missing, the browser (Dartium) reports an error:

```<code>VM2848:1 EXCEPTION: NoSuchMethodError: Class 'AppComponent' has no instance
getter 'toggled'.
Receiver: Instance of 'AppComponent'
Tried calling: toggled
STACKTRACE:
#0      Object._noSuchMethod (dart:core-patch/object_patch.dart:43)
#1      Object.noSuchMethod (dart:core-patch/object_patch.dart:47)
#2      ViewAppComponent0.build
(package:myproject/app_component.template.dart:140:93)
#3      AppView.create
(package:angular2/src/core/linker/app_view.dart:180:12)
#4      DebugAppView.create
(package:angular2/src/debug/debug_app_view.dart:73:26)
</code>```

(etc.)

What is this getter good for? I implemented it as

```<code>get toggled => () => null;
</code>```

and my app seems to work, but I'd like to know what toggled is supposed to return.

答: Angular definitely doesn't require this toggled property. It is defined inside your app_component.html, I would recommend looking at [bindings] and {{string interpolations}}.

Body:
I'm programming a client web app in Dart, using Angular2.

Since Version 3.x of the dart's angular2 package the AppComponent (or whatever class is bootstrapped from main()) requires a getter toggled. If it's missing, the browser (Dartium) reports an error:

VM2848:1 EXCEPTION: NoSuchMethodError: Class 'AppComponent' has no instance
getter 'toggled'.
Receiver: Instance of 'AppComponent'
Tried calling: toggled
STACKTRACE:
#0      Object._noSuchMethod (dart:core-patch/object_patch.dart:43)
#1      Object.noSuchMethod (dart:core-patch/object_patch.dart:47)
#2      ViewAppComponent0.build
(package:myproject/app_component.template.dart:140:93)
#3      AppView.create
(package:angular2/src/core/linker/app_view.dart:180:12)
#4      DebugAppView.create
(package:angular2/src/debug/debug_app_view.dart:73:26)

(etc.)

What is this getter good for? I implemented it as

get toggled => () => null;

and my app seems to work, but I'd like to know what toggled is supposed to return.


问:
javascript counting duplicates in array
Please consider this JS function

I have seen this similar question but couldn't understand.

```<code>function a (ResultArray){
    var counts={};
    for ( p = 0; p < ResultArray.length; p++){
        counts[ResultArray[p]] = (counts[ResultArray[p]] + 1) || 1;
    }
    return counts;
}

var arr = ["a","b","c","d","a","b","e"];
var res = new a(arr);
console.log(res)
</code>```

Its working fine and giving the count. I need to understand  how is it giving the count, specially (counts[ResultArray[p]] + 1) || 1; part. what is +1 and || doing.

答:
there are some things to keep in mind in the above algorithm

javascript objects are represented by sets, dictionary hence counts = {} is just a set or dict hence counts."a" or counts.a or counts[a] can all be used to access the value inside of counts object therefore counts.a = 1 or counts["a"] = null is an assignment to counts set (object).

javascript dynamically allocates variables hence counts[ResultArray[p]] sincecountsis a object javascript dynamically creates the value of
ResultArray[p]]as a property or key tocounts` as javascript is loosely typed

evaluations start from left to right on the line
counts[ResultArray[p]] = (counts[ResultArray[p]] + 1) || 1;
javascript start evaluating starting from count[ResultArray[p]] where
counts evaluates to an object (set, dictionary) then it moves to ResultArray which evaluates to array during runtime p is then evaluated to a number say 0 in first iteration hence the whole evaluation is counts[ResultArray[0]] where javascript creates the key counts.a or counts."a" and assigns to it undefined evaluation then continues to
(counts[ResultArray[p]] + 1) || 1; and inside of it counts[ResultArray[p]] since it had already done in previous step that evaluates to counts.a or counts."a" = undefined then moves to undefined + this should look like this after left right evaluation (undefined + 1)
javascript then evaluates that to NaN in the next step of evaluation

'(NaN)|| 1  whereNaNis always false but 1 is always true in javascript and true = 1 false = 0 hence 1 is assigned tocounts.aorcounts."a" or counts[a] = 1

here is javascript evaluation steps from left to right broken down
counts[ResultArray[p]] = (counts[ResultArray[p]] + 1) || 1;

counts = {} (object,set or dict) in javascript

ResultArray  (array)

p            (integer)

ResultArray[p] = "a" in first iteration

counts["a"]    (undefined is assigned since there was no previous assignement)

=              (assignment operator)

counts = {} (object,set or dict) in javascript

ResultArray  (array)

p            (integer)

ResultArray[p] = "a" in first iteration

counts["a"]    (undefined)

+             (addition operation)

1            (integer)

counts["a"] + 1 = undefined + 1 = NaN

NaN || 1 = 1 (boolean 1 = true false = 0 Nan = 0 = false 0 || 1  1 wins in or statement)

counts["a"] = 0 || 1  (1 is assigned to counts["a"])

Title: javascript counting duplicates in array

Body:
Please consider this JS function

I have seen this similar question but couldn't understand.

function a (ResultArray){
    var counts={};
    for ( p = 0; p < ResultArray.length; p++){
        counts[ResultArray[p]] = (counts[ResultArray[p]] + 1) || 1;
    }
    return counts;
}

var arr = ["a","b","c","d","a","b","e"];
var res = new a(arr);
console.log(res)

Its working fine and giving the count. I need to understand  how is it giving the count, specially (counts[ResultArray[p]] + 1) || 1; part. what is +1 and || doing.


问:
Postgres - Moving Data Folder
I wanted to move my PostgreSQL data folder on my Ubuntu server and I was following this tutorial to move it.

I was able to move it, and update my conf file to point to the new location.

When I go to run Postgres, it starts, but when I try to connect via

```<code>sudo -u postgres psql
</code>```

It gives me this error:

```<code>psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
</code>```

Any ideas what happened? It says it's running.

答:
After done moving PostgreSQL data directory. Don't forget to restart the PostgreSQL service.

Check the PostgreSQL status by command ps -ef  | grep postgres. -D parameter value should be new directory location.

ERROR /var/run/postgresql/.s.PGSQL.5432 that's mean your PostgreSQL service not starting up Properly or Failed to when starting up.

Title: Postgres - Moving Data Folder

Body:
I wanted to move my PostgreSQL data folder on my Ubuntu server and I was following this tutorial to move it.

I was able to move it, and update my conf file to point to the new location.

When I go to run Postgres, it starts, but when I try to connect via

sudo -u postgres psql

It gives me this error:

psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

Any ideas what happened? It says it's running.


问:
Why would my twilio portion of the program work on my laptop but not my pi?
Currently using twilio sms library so that the the data collected from my house can be sent to my phone.  When I ran it from my laptop it worked fine, but after pip importing it onto my Pi and trying to run it I still got the exception:

```<code>ImportError no module named 'twilio'
</code>```

This seems so simple, but I have spent a long time reading through documentation and know I'm just missing something super basic.

```<code>from twilio.rest import Client

client = Client("***************", "**************")

client.messages.create(to="++*******",
                       from_="*******",
                       body="Pi says hi")
</code>```

Thanks a ton for anyone who helps me out!
Note: I'm using python 3 for both and raspbian as the OS.

答:
If you are using python3, then the problem is likely that you used pip. pip will install modules for python2. If you want to install to a python3 env, you need to use pip3.

```<code>pip3 install twillio
</code>```

Note:

If you don't already have pip3 installed, you'll need to do that as well.

```<code>sudo apt-get install python-pip3
</code>```

Body:
Currently using twilio sms library so that the the data collected from my house can be sent to my phone.  When I ran it from my laptop it worked fine, but after pip importing it onto my Pi and trying to run it I still got the exception:

ImportError no module named 'twilio'

This seems so simple, but I have spent a long time reading through documentation and know I'm just missing something super basic.

from twilio.rest import Client

client = Client("***************", "**************")

client.messages.create(to="++*******",
                       from_="*******",
                       body="Pi says hi")

Thanks a ton for anyone who helps me out!
Note: I'm using python 3 for both and raspbian as the OS.

Body:
If you are using python3, then the problem is likely that you used pip. pip will install modules for python2. If you want to install to a python3 env, you need to use pip3.

pip3 install twillio

Note:

If you don't already have pip3 installed, you'll need to do that as well.

sudo apt-get install python-pip3


问:
Is there any way to disable the JSON ModelBinder in ASP.NET MVC 3 RC2?
In ASP.NET MVC 3 RC2, the default ModelBinder will automatically parse the request body if the Content-Type is set to application/json. Problem is, this leaves the Request.InputStream at the end of the stream. This means that if you try to read the input stream using your own code, you first have reset it back to the beginning:

```<code>// client sends HTTP request with Content-Type: application/json and a JSON
// string in the body

// requestBody is null because the stream is already at the end
var requestBody = new StreamReader(Request.InputStream).ReadToEnd();

// resets the position back to the beginning of the input stream
var reader = new StreamReader(Request.InputStream);
reader.BaseStream.Position = 0;
var requestBody = reader.ReadToEnd();
</code>```

Since I'm using Json.NET to do my serialization/deserialization, I'd like to disable the default ModelBinder from doing this extra parsing. Is there any way to do that?

答:
You can put the following in Application_Start in your Global.asax:

```<code>ValueProviderFactories.Factories.Remove(
            ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().First());
</code>```

This assumes there is only one of that type (which by default there is), but it can easily be changed to work if there is more than one.  I don't believe there is a cleaner way if that is what you are looking for.

Body:
In ASP.NET MVC 3 RC2, the default ModelBinder will automatically parse the request body if the Content-Type is set to application/json. Problem is, this leaves the Request.InputStream at the end of the stream. This means that if you try to read the input stream using your own code, you first have reset it back to the beginning:

// client sends HTTP request with Content-Type: application/json and a JSON
// string in the body

// requestBody is null because the stream is already at the end
var requestBody = new StreamReader(Request.InputStream).ReadToEnd();

// resets the position back to the beginning of the input stream
var reader = new StreamReader(Request.InputStream);
reader.BaseStream.Position = 0;
var requestBody = reader.ReadToEnd();

Since I'm using Json.NET to do my serialization/deserialization, I'd like to disable the default ModelBinder from doing this extra parsing. Is there any way to do that?

Body:
You can put the following in Application_Start in your Global.asax:

ValueProviderFactories.Factories.Remove(
            ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().First());

This assumes there is only one of that type (which by default there is), but it can easily be changed to work if there is more than one.  I don't believe there is a cleaner way if that is what you are looking for.


问:
How to create a React onClick with a HTML string
I am using Google Map API to create an app. In order to render the text in the bubble when you click on a marker in the app you have to make an HTML string.

IE:

```<code>const markerBubble = '<div class="marker-wrapper">' +
  `<div class="marker-title">${locations[i][0]}</div>` +
  `<div class="marker-view-btn">View</div>` +
'</div>';
</code>```

As you can see I can render the title dynamically. But, I have button in there that I want to use to push the page (also using React Router). I can't do

<Link>
View
</Link>

because the Link doesn't render correctly. How would I go about adding an onClick to this div?

答:
If you want to push the page on different component/route you could do this using 'Link' component of react-router v4.0.

```<code><Link className="marker-view-btn" to='/newDestination'>View</Link>
</code>```

where, /newDestination is your new route where you want to go on click of 'View'.

Body:
I am using Google Map API to create an app. In order to render the text in the bubble when you click on a marker in the app you have to make an HTML string.

IE:

const markerBubble = '
' +
  `<div class="marker-title">${locations[i][0]}</div>` +
  `<div class="marker-view-btn">View</div>` +
'
';

As you can see I can render the title dynamically. But, I have button in there that I want to use to push the page (also using React Router). I can't do

<Link>
View
</Link>

because the Link doesn't render correctly. How would I go about adding an onClick to this div?

Body:
If you want to push the page on different component/route you could do this using 'Link' component of react-router v4.0.

<Link className="marker-view-btn" to='/newDestination'>View</Link>

where, /newDestination is your new route where you want to go on click of 'View'.


问:
How can I get rid of "result", "insertedCount", and "insertedIds" from MongoDB callback and node and get only an array of database objects?
I just updated Node after not doing so for a while and had to reinstall MongoDB and other modules.  Where I previously would only get an array of database objects when using the find() function, I'm now getting a JSON object that includes "results", "ops", "insertedCount", and "insertedIds".  I can't remember what I might have done when I initially set it up or maybe this is just an annoying change with Mongo, but I'd like to return to only getting an array of database objects so that I don't have to test my entire server.  I've tried several npm parse modules with no success.

Here's an example:

```<code>{ result: { ok: 1, n: 1 },
  ops:
   [ { user: '595ee2fec2924e5435dfdd2d'},
       _id: 595f0fe55e84fa2468b17ce8 } ],
  insertedCount: 1,
  insertedIds: [ 595f0fe55e84fa2468b17ce8 ] }
</code>```

Whereas previously, it would have only returned:

```<code>[ { user: '595ee2fec2924e5435dfdd2d'},
       _id: 595f0fe55e84fa2468b17ce8 } ]
</code>```

答:
You can simply get the ops array.

```<code>result.ops;
</code>```

You may also need to make sure to follow your call stack correctly as those objects are only returned on an insert.

Body:
I just updated Node after not doing so for a while and had to reinstall MongoDB and other modules.  Where I previously would only get an array of database objects when using the find() function, I'm now getting a JSON object that includes "results", "ops", "insertedCount", and "insertedIds".  I can't remember what I might have done when I initially set it up or maybe this is just an annoying change with Mongo, but I'd like to return to only getting an array of database objects so that I don't have to test my entire server.  I've tried several npm parse modules with no success.

Here's an example:

{ result: { ok: 1, n: 1 },
  ops:
   [ { user: '595ee2fec2924e5435dfdd2d'},
       _id: 595f0fe55e84fa2468b17ce8 } ],
  insertedCount: 1,
  insertedIds: [ 595f0fe55e84fa2468b17ce8 ] }

Whereas previously, it would have only returned:

[ { user: '595ee2fec2924e5435dfdd2d'},
       _id: 595f0fe55e84fa2468b17ce8 } ]

Body:
You can simply get the ops array.

result.ops;

You may also need to make sure to follow your call stack correctly as those objects are only returned on an insert.


问:
Adding zeros spaces to an array of a picture
I have an image defined as:

```<code>imagen = scipy.misc.imread("C:\\Users\\Reymi\\Downloads\\imagen.png")
</code>```

It has a size of (1929,1280)
I need to add 2 columns and rows with zeros to each side of the array so I can use a kernel without worrying about it going outside of the array.

How? Thank you

答:
Option - 1 - Using OpenCV

```<code>imagenBorder = cv2.copyMakeBorder(imagen,2,2,2,2,cv2.BORDER_REFLECT)
</code>```

Option - 2 - Manually padding to numpy array

```<code>import numpy as np
borderWidth = 2
i = 0
while i < borderWidth:
    imagen = np.insert(imagen, 0, 0, axis=1)
    imagen = np.insert(imagen, imagen.shape[1], 0, axis=1)
    imagen = np.insert(imagen, 0, 0, axis=0)
    imagen = np.insert(imagen, imagen.shape[0], 0, axis=0)
    i = i+1
</code>```

Body:
I have an image defined as:

imagen = scipy.misc.imread("C:\\Users\\Reymi\\Downloads\\imagen.png")

It has a size of (1929,1280)
I need to add 2 columns and rows with zeros to each side of the array so I can use a kernel without worrying about it going outside of the array.

How? Thank you

Body:
Option - 1 - Using OpenCV

imagenBorder = cv2.copyMakeBorder(imagen,2,2,2,2,cv2.BORDER_REFLECT)

Option - 2 - Manually padding to numpy array

import numpy as np
borderWidth = 2
i = 0
while i < borderWidth:
    imagen = np.insert(imagen, 0, 0, axis=1)
    imagen = np.insert(imagen, imagen.shape[1], 0, axis=1)
    imagen = np.insert(imagen, 0, 0, axis=0)
    imagen = np.insert(imagen, imagen.shape[0], 0, axis=0)
    i = i+1


问:
c++ dereference pointed object and pass into a function as reference, value is changed
Dear experienced c++ expert:

In recent coding process, there is a trick problem associated with reference and
dereference operation.

```<code>typedef io::SequenceDataAccess<DNA_N>     read_access_type;
</code>```

here is class constructor:

```<code>AlignmentData( // ignored some arguments
              const io::SequenceDataHost*   read_data_batch
             )
{
read_access_type read_data_access( *read_data_batch );
......
}
</code>```

in a debug session, I set a breakpoint at the function body(the unique line), the
value of read_data_batch(a pointer) is 0x7fff9a0489a0, and print the other state info:

```<code>(gdb) print read_data_batch
$7 = (const bxtbio::io::SequenceDataHost *) **0x7fff9a0489a0**
(gdb) print *read_data_batch
$8 = (bxtbio::io::SequenceData) {<bxtbio::io::SequenceData> =
{<bxtbio::io::SequenceDataInfo> = {m_alphabet = bxtbio::DNA_N,
m_n_seqs = 250, m_n_segments = 0, m_name_stream_len = 16392,
m_sequence_stream_len = 25000, m_sequence_stream_words = 3125,
......
</code>```

but when I step into the constructor of class SequenceDataAccess,

shown as below:

```<code>NVBIO_HOST_DEVICE NVBIO_FORCEINLINE
SequenceDataAccess(const SequenceDataT& data):m_data(data)
</code>```

the argument data's state:

```<code>(gdb) print &data
$9 = (const bxtbio::io::SequenceDataViewCore<unsigned int const*,
unsigned int const*, char const*, char const*> *) **0x7fffa0aacb50**

(gdb) print data
$10 = (const bxtbio::io::SequenceDataViewCore<unsigned int const*, unsigned int const*, char const*, char const*> &) @0x7fffa0aacb50: {<bxtbio::io::SequenceDataInfo> = {m_alphabet = bxtbio::PROTEIN, m_n_seqs = 0, m_n_segments = 0, m_name_stream_len = 0, m_sequence_stream_len = 0, m_sequence_stream_words = 0, m_has_qualities = 0, .......
</code>```

My Questions:

shouldn't data has the same address as the  read_data_batch which is
passed in the copy-constructor?

why are the data member's values all changed? What are the possible
reasons?

this code is running in a multiple threads environment.

Thanks.

Here is a small invoke chain code excerpt:

```<code>// file1.cpp
void MapSpliceWorker::align(io::HostOutputBatchSE *cpu_batch)
{
    log_info(stderr, "MapSpliceWorker::align called cpu_batch.count = %d\n",cpu_batch->count);

    for (uint32 c = 0; c < cpu_batch->count; c++) {
        AlignmentData alignment = get(*cpu_batch, c);   // Here is the entrypoint invocation
    }
}

// file2.cpp
AlignmentData get(HostOutputBatchSE& batch, const uint32 aln_id)
{
    const uint32 read_id = batch.read_ids.size() ?
                           batch.read_ids[ aln_id ] : aln_id;
   // construct a AlignmentData object and return
    return AlignmentData(&batch.alignments[aln_id],
                         batch.mapq[aln_id],
                         aln_id,
                         read_id,
                         batch.read_data,
                         &batch.cigar,
                         &batch.mds);
}
// file3.h
struct AlignmentData
{
    AlignmentData(const Alignment*              _aln,
                  const uint32                  _mapq,
                  const uint32                  _aln_id,
                  const uint32                  _read_id,
                  const io::SequenceDataHost*   read_data_batch,
                  const HostCigarArray*         cigar_array,
                  const HostMdsArray*           mds_array)
        : valid(true),
          aln(_aln),
          aln_id(_aln_id),
          read_id(_read_id),
          mapq(_mapq),
          read_data_batch_p(read_data_batch),
          cigar_array_p(cigar_array),
          mds_array_p(mds_array)
    {
        read_access_type read_data_access( *read_data_batch );   // up to now, read_data_batch has valid states
    }
};

// file4. h
template <
    Alphabet  SEQUENCE_ALPHABET_T,
    typename  SequenceDataT = ConstSequenceDataView>
struct SequenceDataAccess
{
    /// constructor
    NVBIO_HOST_DEVICE NVBIO_FORCEINLINE
SequenceDataAccess(const SequenceDataT& data)
: m_data( data )   // here the data's states is cleaned and the address is not same as read_data_batch in previous context.
    {
      #if !defined(NVBIO_DEVICE_COMPILATION) || defined(NVBIO_CUDA_DEBUG)
        assert( m_data.m_alphabet == SEQUENCE_ALPHABET );
        // failed by this assert
      #endif
    }
}
</code>```

答:
Pass by reference just allows you to work with the variables without derefrencing them. It's still like passing a pointer. A perma-derefrenced pointer.

When you take an objects reference you are taking its address. A pointer is just an objects address. So a reference and pointer to the same object have the same value. The difference between a reference and a pointer is that references are immutable and pointers are mutable. There's a lot more little differences but that's a pretty big one.

Body:
Dear experienced c++ expert:

In recent coding process, there is a trick problem associated with reference and
dereference operation.

typedef io::SequenceDataAccess<DNA_N>     read_access_type;

here is class constructor:

AlignmentData( // ignored some arguments
              const io::SequenceDataHost*   read_data_batch
             )
{
read_access_type read_data_access( *read_data_batch );
......
}

in a debug session, I set a breakpoint at the function body(the unique line), the
value of read_data_batch(a pointer) is 0x7fff9a0489a0, and print the other state info:

(gdb) print read_data_batch
$7 = (const bxtbio::io::SequenceDataHost *) **0x7fff9a0489a0**
(gdb) print *read_data_batch
$8 = (bxtbio::io::SequenceData) {<bxtbio::io::SequenceData> =
{<bxtbio::io::SequenceDataInfo> = {m_alphabet = bxtbio::DNA_N,
m_n_seqs = 250, m_n_segments = 0, m_name_stream_len = 16392,
m_sequence_stream_len = 25000, m_sequence_stream_words = 3125,
......

but when I step into the constructor of class SequenceDataAccess,

shown as below:

NVBIO_HOST_DEVICE NVBIO_FORCEINLINE
SequenceDataAccess(const SequenceDataT& data):m_data(data)

the argument data's state:

(gdb) print &data
$9 = (const bxtbio::io::SequenceDataViewCore<unsigned int const*,
unsigned int const*, char const*, char const*> *) **0x7fffa0aacb50**

(gdb) print data
$10 = (const bxtbio::io::SequenceDataViewCore<unsigned int const*, unsigned int const*, char const*, char const*> &) @0x7fffa0aacb50: {<bxtbio::io::SequenceDataInfo> = {m_alphabet = bxtbio::PROTEIN, m_n_seqs = 0, m_n_segments = 0, m_name_stream_len = 0, m_sequence_stream_len = 0, m_sequence_stream_words = 0, m_has_qualities = 0, .......

My Questions:

shouldn't data has the same address as the  read_data_batch which is
passed in the copy-constructor?

why are the data member's values all changed? What are the possible
reasons?

this code is running in a multiple threads environment.

Thanks.

Here is a small invoke chain code excerpt:

// file1.cpp
void MapSpliceWorker::align(io::HostOutputBatchSE *cpu_batch)
{
    log_info(stderr, "MapSpliceWorker::align called cpu_batch.count = %d\n",cpu_batch->count);

    for (uint32 c = 0; c < cpu_batch->count; c++) {
        AlignmentData alignment = get(*cpu_batch, c);   // Here is the entrypoint invocation
    }
}

// file2.cpp
AlignmentData get(HostOutputBatchSE& batch, const uint32 aln_id)
{
    const uint32 read_id = batch.read_ids.size() ?
                           batch.read_ids[ aln_id ] : aln_id;
   // construct a AlignmentData object and return
    return AlignmentData(&batch.alignments[aln_id],
                         batch.mapq[aln_id],
                         aln_id,
                         read_id,
                         batch.read_data,
                         &batch.cigar,
                         &batch.mds);
}
// file3.h
struct AlignmentData
{
    AlignmentData(const Alignment*              _aln,
                  const uint32                  _mapq,
                  const uint32                  _aln_id,
                  const uint32                  _read_id,
                  const io::SequenceDataHost*   read_data_batch,
                  const HostCigarArray*         cigar_array,
                  const HostMdsArray*           mds_array)
        : valid(true),
          aln(_aln),
          aln_id(_aln_id),
          read_id(_read_id),
          mapq(_mapq),
          read_data_batch_p(read_data_batch),
          cigar_array_p(cigar_array),
          mds_array_p(mds_array)
    {
        read_access_type read_data_access( *read_data_batch );   // up to now, read_data_batch has valid states
    }
};

// file4. h
template <
    Alphabet  SEQUENCE_ALPHABET_T,
    typename  SequenceDataT = ConstSequenceDataView>
struct SequenceDataAccess
{
    /// constructor
    NVBIO_HOST_DEVICE NVBIO_FORCEINLINE
SequenceDataAccess(const SequenceDataT& data)
: m_data( data )   // here the data's states is cleaned and the address is not same as read_data_batch in previous context.
    {
      #if !defined(NVBIO_DEVICE_COMPILATION) || defined(NVBIO_CUDA_DEBUG)
        assert( m_data.m_alphabet == SEQUENCE_ALPHABET );
        // failed by this assert
      #endif
    }
}


问:
Are android adapters an example of Adapter Design pattern?
Do Android adapters use Adapter Design pattern? The GoF design patterns book describes Adapter Design Pattern as

The Adapter Pattern converts the interface of a class
  into another interface the clients expect. Adapter lets
  classes work together that couldn’t otherwise because of
  incompatible interfaces.

There's a target interface which the adapter implements and the client uses(expects) and there is an adaptee to which the adapter delegates all the requests made by client.

I understand that its theory and real world pattern adapter interfaces don't exactly look like it, but still I can't figure out what the android adapters adapt(what target interface) and to which adaptee are the requests actually made to.

I have checked this, this and this. But none of them explain clearly how is the android adapter the adapter design pattern. The 1st and 2nd answers, in fact, are somewhat conflicting.

Can anyone please explain this?

答:
Android adapters are in fact the same Adapter design pattern as per the GoF.
Adapters are used to give a known interface to unknown objects.
eg: if we are using any 3rd party libraries, it is recommended to have adapters implemented so that the 3rd party interface is converted to a known interface.
Then it becomes easy to replace the 3rp party libraries with just adding a new adapter.

Now, look at the ListView Adapter concept in Android as a whole.
3rd party developers are free to add any data backend and make the list view work if they implement the known interface which is the Android defined adapter kind. I hope that clarifies the design pattern.


问:
How to draw custom routes in Google maps?
i'm working with Xamarin crossplatform and i want to draw custom route. App needs to draw the route from one place to another exactly which the user using, not alternative routes.</p>

答:
See this link may be it's help you

https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/custom-renderer/map/polyline-map-overlay/

you can Get RouteCoordinates Position using google direction map API.


问:
How to allow javascript tasks to run across multiple screens on Cordova
I'm working on a mobile app with Cordova.  When the user starts up the app, I'd like to kick off a non-blocking function to load data from the server.  This function can take up to a few seconds.

I'm using the leecrossley/cordova-plugin-background-task plugin.  It works fine if I stay on the page that kicked off the function.  If I change pages, it stops the function.

Any thoughts?

Jon

答:
Sounds as if you are experiencing web-view-throttling!
Cordova uses the Chromium web engine so it usually follows all of the performance settings implemented in the chrome browser.

You can read some more about the throttling issue here:
https://thenextweb.com/apps/2017/01/26/chrome-throttle-background-tabs-google/#.tnw_WIKDX2EX

The solution to your problem is

to create a main page to function as the core of your application. This main page will always be open 'thus saving your from scripts being stopped when a new page is loaded.

For app pages, i recommend either:

creating a separate .html file per app page, then load those external pages into your main app page via an iFrame ...the src of the iFrame can be updated via javascript. (the downside to this approach is that you will need to write additional javascript to monitor and control the events that happen inside of your iFrames -from the main page.)

or

Build a very big single page application; wrapping all of your app pages in divs.. then create a javascrip menu function that manages what page is displayed and what page is hidden. (This may result in a massive .html page but this method will allow you to run any number of non-blocking scripts the device can handle at once.) <-- This is the method i have been using for over three years, i also add some iFrames to include special page modules when needed. CSS and JavaScript can be loaded from external files.

I believe most cordova developers actually use this single-page method!


答:
The most correct solution would be to continue running your project with the exact versions of everything your package.json depends on.

That said, I'm assuming you're encountering this issue is because you're running Node locally on your system and needed to upgrade it for another project or security fix. If this is the case, you may want to consider using a Node version management tool like nvm or nodenv. These allow you to have multiple versions of Node installed and associate them with individual projects so you don't run into compatibility issues.

For an even more powerful variation of this, you might want to virtualize your entire development environment using a virtual machine such as VirtualBox or a container system like Docker. Both let you create files that define how you'd like to provision your VMs or containers (what OS, what versions of software are installed, etc.). They're the most robust way of ensuring that when you come back to a project months, or even years later, it will still run exactly the way you left it.

Title: How can I get rid of "result", "insertedCount", and "insertedIds" from MongoDB callback and node and get only an array of database objects?


问:
selecting 2 different option values and sending data to php using ajax
I am taking two different values from select options and sending it using AJAX, but PHP is not responding to the request.

This is my jQuery code:

```<code>$(document).ready(function() {
  $("#updateStatus").change(function() {
    var opt = $("#updateStatus").val();

    $("#updateStatus1").change(function() {
      var sta = $("#updateStatus1").val();

      $.ajax({
        url: 'updatecode.php',
        type: 'POST',
        data: "option=" + opt + "&status=" + sta,
        dataType: 'json',
        success: function(data) {
          alert(data + "hello");
        }
      });
    });
  });
});
</code>```

This is my PHP code:

```<code>$id = $_POST['opt'];
$status = $_POST['sta'];
$query = "UPDATE projectstable SET projectStatus='".$status."'WHERE id='".$id."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);

if (!$row) {
  echo json_encode("fail");
} else {
  echo json_encode("sucess");
}
</code>```

答:
You are sending request under data using "option=" and "&status=" but you are reading these values in PHP through $_POST['opt'] and $_POST['stat'] which should actually be $_POST['option'] and $_POST['status'] respectively.
Also you need to change the data request to JSON format like data: {option:opt,status:sta} for your dataType is JSON

Body:
I am taking two different values from select options and sending it using AJAX, but PHP is not responding to the request.

This is my jQuery code:

$(document).ready(function() {
  $("#updateStatus").change(function() {
    var opt = $("#updateStatus").val();

    $("#updateStatus1").change(function() {
      var sta = $("#updateStatus1").val();

      $.ajax({
        url: 'updatecode.php',
        type: 'POST',
        data: "option=" + opt + "&status=" + sta,
        dataType: 'json',
        success: function(data) {
          alert(data + "hello");
        }
      });
    });
  });
});

This is my PHP code:

$id = $_POST['opt'];
$status = $_POST['sta'];
$query = "UPDATE projectstable SET projectStatus='".$status."'WHERE id='".$id."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);

if (!$row) {
  echo json_encode("fail");
} else {
  echo json_encode("sucess");
}


问:
Conflict control ID
I am having problem in publishing my custom project in Acumatica ERP. It prompts me the following message.

Conflict control ID:phG_tab_Items#0_grid_Levels#0 from page
  ~/pages/so/so303000.aspx Validation failed.

Here is what my code looks like in the Invoices page (ScreenID: SO303000)

```<code><Page path="~/pages/so/so303000.aspx" ControlId="2" pageSource="711Ft7m6F+foDk0z4+/8B">
    <PXGridLevel DataMember="Transactions" ParentId="phG_tab_Items#0_grid_Levels#0" TypeFullName="PX.Web.UI.PXGridLevel">
        <Children Key="Columns">
            <AddItem>
                <PXGridColumn TypeFullName="PX.Web.UI.PXGridColumn">
                    <Prop Key="DataField" Value="UsrContractID" />
                    <Prop Key="Width" Value="70" />
                </PXGridColumn>
            </AddItem>
            <AddItem>
                <PXGridColumn TypeFullName="PX.Web.UI.PXGridColumn">
                    <Prop Key="DataField" Value="UsrPhoneNumber" />
                    <Prop Key="Width" Value="70" />
                </PXGridColumn>
            </AddItem>
            <AddItem>
                <PXGridColumn TypeFullName="PX.Web.UI.PXGridColumn">
                    <Prop Key="DataField" Value="UsrSIMCardID" />
                    <Prop Key="Width" Value="160" />
                </PXGridColumn>
            </AddItem>
        </Children>
    </PXGridLevel>
</Page>
</code>```

I have shortened the pageSource value for readability.

Since, I have another custom project as well, and got answer that that could cause this, I have no idea what changes should I do to make this work.

答:
When you publish more that one customization project, the system merges the content of all projects into a single customization project. If different projects include customization for the same ASPX page, the platform tries to merge the changes. For example, the platform can merge different properties of the same control in an ASPX page.

On the Customization Projects form, you can specify an optional number (level) for each customization project, assigning the highest number to the most important change. The level can be used to resolve conflicts that arise while you are publishing customization projects if multiple modifications for the same ASPX page are merged. As a result, the customization from the project with the highest level is added to the merged project.

For more information on this topic, please check Acumatica Customization Guide

Title: Conflict control ID

Body:
I am having problem in publishing my custom project in Acumatica ERP. It prompts me the following message.

Conflict control ID:phG_tab_Items#0_grid_Levels#0 from page
  ~/pages/so/so303000.aspx Validation failed.

Here is what my code looks like in the Invoices page (ScreenID: SO303000)

<Page path="~/pages/so/so303000.aspx" ControlId="2" pageSource="711Ft7m6F+foDk0z4+/8B">
    <PXGridLevel DataMember="Transactions" ParentId="phG_tab_Items#0_grid_Levels#0" TypeFullName="PX.Web.UI.PXGridLevel">
        <Children Key="Columns">
            <AddItem>
                <PXGridColumn TypeFullName="PX.Web.UI.PXGridColumn">
                    <Prop Key="DataField" Value="UsrContractID" />
                    <Prop Key="Width" Value="70" />
                </PXGridColumn>
            </AddItem>
            <AddItem>
                <PXGridColumn TypeFullName="PX.Web.UI.PXGridColumn">
                    <Prop Key="DataField" Value="UsrPhoneNumber" />
                    <Prop Key="Width" Value="70" />
                </PXGridColumn>
            </AddItem>
            <AddItem>
                <PXGridColumn TypeFullName="PX.Web.UI.PXGridColumn">
                    <Prop Key="DataField" Value="UsrSIMCardID" />
                    <Prop Key="Width" Value="160" />
                </PXGridColumn>
            </AddItem>
        </Children>
    </PXGridLevel>
</Page>

I have shortened the pageSource value for readability.

Since, I have another custom project as well, and got answer that that could cause this, I have no idea what changes should I do to make this work.


问:
Error: $controller:ctrlreg A controller with this name is not registered Service issue
My application is executed successfully without maninSvc.js. After adding this file I'm seeing errror:

```<code>angular.min.js:123 Error: [$controller:ctrlreg] http://errors.angularjs.org/1.6.5/$controller/ctrlreg?p0=MainController
at angular.min.js:7
</code>```

My Code:

Index.html

```<code><!DOCTYPE html>
<html ng-app="app">

<head>
  <title></title>
  <script src="Scripts/jquery-3.2.1.min.js"></script>
  <script src="Scripts/bootstrap-3.3.7/js/bootstrap.min.js"></script>
  <script src="Scripts/angular.min.js"></script>
  <script src="Scripts/angular-route.min.js"></script>
  <script src="Scripts/angular-resource.min.js"></script>

  <link href="Scripts/bootstrap-3.3.7/css/bootstrap.min.css" rel="stylesheet" />
  <link href="Css/Shared.css" rel="stylesheet" />

  <script src="MainController.js"></script>
  <script src="mainSvc.js"></script>
</head>

<body ng-controller="MainController as vm">

  <div data-ng-if="vm.success" class="success">{{vm.success}}</div>
  <div data-ng-if="vm.catch" class="catch">{{vm.catch}}</div>
  <div data-ng-if="vm.finally" class="finally">{{vm.finally}}</div>

</body>

</html>
</code>```

MainController.js

```<code>(function() {
  angular
    .module('app', ['ngRoute'])
    .controller('MainController', mainController);
  mainController.$inject = ['mainSvc'];

  function mainController(mainSvc) {
    var vm = this;
    mainSvc.getData()
      .then(function(data) {
      vm.success = "success";
    }).catch(function(response) {
      vm.catch = "catch";
    }).finally(function() {
      vm.finally = "finally";
    });
  }
})();
</code>```

mainSvc.js

```<code>(function() {
  angular
    .module('app', [])
    .factory('mainSvc', mainSvc);
  mainSvc.$inject = ['$resource'];

  function mainSvc($resource) {
    var ResourceData = $resource({
      query: {
        isArray: true
      },
      get: {},
      save: {
        method: 'POST'
      },
      update: {
        method: 'PATCH'
      },
      put: {
        method: 'PUT'
      },
      remove: {
        method: 'DELETE'
      }
    });
    return {
      getData: getData,
    };

    function getData() {
      /// <summary>
      /// Gets Data
      /// </summary>
      return ResourceData
        .get()
        .$promise;
    }
  }
})();
</code>```

答:
Your mainSvc.js should not have empty dependencies to the module, Then it will be considered as a new module. change it as

```<code>(function () {
    angular
    .module('app')
    .factory('mainSvc', mainSvc);
</code>```

Body:
My application is executed successfully without maninSvc.js. After adding this file I'm seeing errror:

angular.min.js:123 Error: [$controller:ctrlreg] http://errors.angularjs.org/1.6.5/$controller/ctrlreg?p0=MainController
at angular.min.js:7

My Code:

Index.html

<!DOCTYPE html>

  <title></title>

  <link href="Scripts/bootstrap-3.3.7/css/bootstrap.min.css" rel="stylesheet" />
  <link href="Css/Shared.css" rel="stylesheet" />

{{vm.success}}

{{vm.catch}}

{{vm.finally}}

MainController.js

(function() {
  angular
    .module('app', ['ngRoute'])
    .controller('MainController', mainController);
  mainController.$inject = ['mainSvc'];

  function mainController(mainSvc) {
    var vm = this;
    mainSvc.getData()
      .then(function(data) {
      vm.success = "success";
    }).catch(function(response) {
      vm.catch = "catch";
    }).finally(function() {
      vm.finally = "finally";
    });
  }
})();

mainSvc.js

(function() {
  angular
    .module('app', [])
    .factory('mainSvc', mainSvc);
  mainSvc.$inject = ['$resource'];

  function mainSvc($resource) {
    var ResourceData = $resource({
      query: {
        isArray: true
      },
      get: {},
      save: {
        method: 'POST'
      },
      update: {
        method: 'PATCH'
      },
      put: {
        method: 'PUT'
      },
      remove: {
        method: 'DELETE'
      }
    });
    return {
      getData: getData,
    };

    function getData() {
      ///
      /// Gets Data
      ///
      return ResourceData
        .get()
        .$promise;
    }
  }
})();

Body:
Your mainSvc.js should not have empty dependencies to the module, Then it will be considered as a new module. change it as

(function () {
    angular
    .module('app')
    .factory('mainSvc', mainSvc);


问:
Uncheck box is other is selected with jQuery
I have a several checkboxes like this:

```<code><div class="col-sm-12">
        <div class="col-sm-4">
            <div class="checkbox checkbox-default">
                <input type="checkbox" name="RAT_RoomList[]" value="10">
                <label for="custome-checkbox1"># 11</label>
            </div>
        </div>
        <div class="col-sm-4">
            <div class="checkbox checkbox-default">
                <input type="checkbox" name="RAT_RoomList[]" value="11">
                <label for="custome-checkbox2"># 12</label>
            </div>
        </div>
        <div class="col-sm-4">
            <div class="checkbox checkbox-default">
                <input type="checkbox" name="RAT_RoomList[]" value="12">
                <label for="custome-checkbox3"># 13</label>
            </div>
        </div>
        <div class="col-sm-12">
            <div class="checkbox checkbox-default">
                <input type="checkbox" class="selectAll">
                <label for="custome-checkbox">Select all</label>
            </div>
        </div>
</div>
</code>```

How can unselect all other when the Select all is checked and how can I unselect Select All when one of the other checkboxes is checked?

Thanks.

答:
Using not Selector with class you can achieve this.

$('.selectAll').click(function() {
  if ($(this).prop("checked", true)) {
    $(".col-sm-12").find('input[type=checkbox]').not('.selectAll').each(function() {
      this.checked = false;
    });
  }
});
$('input[type=checkbox]').not('.selectAll').click(function() {
  if ($(this).prop("checked", true)) {
    $('.selectAll').prop("checked", false)
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="col-sm-12">
  <div class="col-sm-4">
    <div class="checkbox checkbox-default">
      <input type="checkbox" name="RAT_RoomList[]" value="10">
      <label for="custome-checkbox1"># 11</label>
    </div>
  </div>
  <div class="col-sm-4">
    <div class="checkbox checkbox-default">
      <input type="checkbox" name="RAT_RoomList[]" value="11">
      <label for="custome-checkbox2"># 12</label>
    </div>
  </div>
  <div class="col-sm-4">
    <div class="checkbox checkbox-default">
      <input type="checkbox" name="RAT_RoomList[]" value="12">
      <label for="custome-checkbox3"># 13</label>
    </div>
  </div>
  <div class="col-sm-12">
    <div class="checkbox checkbox-default">
      <input type="checkbox" class="selectAll">
      <label for="custome-checkbox">Select all</label>
    </div>
  </div>
</div></code>```

Body:
I have a several checkboxes like this:

                <input type="checkbox" name="RAT_RoomList[]" value="10">
                # 11

                <input type="checkbox" name="RAT_RoomList[]" value="11">
                # 12

                <input type="checkbox" name="RAT_RoomList[]" value="12">
                # 13

                <input type="checkbox" class="selectAll">
                Select all

How can unselect all other when the Select all is checked and how can I unselect Select All when one of the other checkboxes is checked?

Thanks.

Body:
Using not Selector with class you can achieve this.

$('.selectAll').click(function() {
  if ($(this).prop("checked", true)) {
    $(".col-sm-12").find('input[type=checkbox]').not('.selectAll').each(function() {
      this.checked = false;
    });
  }
});
$('input[type=checkbox]').not('.selectAll').click(function() {
  if ($(this).prop("checked", true)) {
    $('.selectAll').prop("checked", false)
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="col-sm-12">
  <div class="col-sm-4">
    <div class="checkbox checkbox-default">
      <input type="checkbox" name="RAT_RoomList[]" value="10">
      <label for="custome-checkbox1"># 11</label>
    </div>
  </div>
  <div class="col-sm-4">
    <div class="checkbox checkbox-default">
      <input type="checkbox" name="RAT_RoomList[]" value="11">
      <label for="custome-checkbox2"># 12</label>
    </div>
  </div>
  <div class="col-sm-4">
    <div class="checkbox checkbox-default">
      <input type="checkbox" name="RAT_RoomList[]" value="12">
      <label for="custome-checkbox3"># 13</label>
    </div>
  </div>
  <div class="col-sm-12">
    <div class="checkbox checkbox-default">
      <input type="checkbox" class="selectAll">
      <label for="custome-checkbox">Select all</label>
    </div>
  </div>
</div>


问:
How to get the value of a data-amount JMeter
How to get the value of a data-amount JMeter
I tried to get the value using a xpath extractor. But I always got an empty string. What am I doing wrong?

```<code>//*[@class = 'panel-body']//*[@class='fade-in'][1]/@data-amount
</code>```

答:
There is a couple of problems with your XPath expression, for instance:

```<code>//*[@class = 'panel-body']//*[@class='fade-in'][1]/@data-amount
                           ^ - extra slash      ^ - not required
</code>```

I also don't like * wildcard, however it might be a weird form of your test scenario so let it be.

Being converted to "normal" XPath expression it should look something like:

```<code>//*[@class='panel-body']/*/@data-amount
</code>```

Demo:

It may be simplified to something like:

```<code>//div[@data-action='bid_online']/@data-amount
</code>```

References:

XPath Language Specification

Using the XPath Extractor in JMeter

XPath Tutorial

Body:
How to get the value of a data-amount JMeter
I tried to get the value using a xpath extractor. But I always got an empty string. What am I doing wrong?

//*[@class = 'panel-body']//*[@class='fade-in'][1]/@data-amount

Body:
There is a couple of problems with your XPath expression, for instance:

//*[@class = 'panel-body']//*[@class='fade-in'][1]/@data-amount
                           ^ - extra slash      ^ - not required

I also don't like * wildcard, however it might be a weird form of your test scenario so let it be.

Being converted to "normal" XPath expression it should look something like:

//*[@class='panel-body']/*/@data-amount

Demo:

It may be simplified to something like:

//div[@data-action='bid_online']/@data-amount

References:

XPath Language Specification

Using the XPath Extractor in JMeter

XPath Tutorial