问:
How to access data outside onResponse?
I have no idea why medicine_description is returning null outside onResponse.

```<code>        StringRequest stringRequest = new StringRequest(Request.Method.GET, fda_api + "acetaminophen", new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {

                    JSONObject json = new JSONObject(response);
                    JSONArray jArray = json.getJSONArray("results");
                    Log.d(TAG, "readJSON: " + jArray.length());

                    JSONObject json_data = jArray.getJSONObject(0);
                    medicine_description = json_data.getString("description");
                    Log.i("THIS ONE IS FINE",medicine_description);
                    /*for(int i=0; i<jArray.length(); i++){
                        JSONObject json_data = jArray.getJSONObject(i);
                        medicine_description = json_data.getString("description");

                        Log.i("log_tag",medicine_description);
                    }*/
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest);
        Log.i(TAG, "THIS RETURNS NULL: " + medicine_description);
</code>```

答:
Volley works in an asynchronous way, it means that you can't know when the response will arrive from your webservice. It will works on separate thread rather than UI thread.

So the outside block of code will get executed irrespective of the Volley response.

If you need the string in your function you should probably create a method and call it when you have the result.

Here is an example:

```<code>    public void onResponse(String response) {
            try {

                JSONObject json = new JSONObject(response);
                JSONArray jArray = json.getJSONArray("results");
                Log.d(TAG, "readJSON: " + jArray.length());

                JSONObject json_data = jArray.getJSONObject(0);
                medicine_description = json_data.getString("description");
                passdata(medicine_description);  //create method to pass data
                Log.i("THIS ONE IS FINE",medicine_description);
                /*for(int i=0; i<jArray.length(); i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    medicine_description = json_data.getString("description");

                    Log.i("log_tag",medicine_description);
                }*/
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
</code>```

Title: How to access data outside onResponse?

Body:
I have no idea why medicine_description is returning null outside onResponse.

        StringRequest stringRequest = new StringRequest(Request.Method.GET, fda_api + "acetaminophen", new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {

                    JSONObject json = new JSONObject(response);
                    JSONArray jArray = json.getJSONArray("results");
                    Log.d(TAG, "readJSON: " + jArray.length());

                    JSONObject json_data = jArray.getJSONObject(0);
                    medicine_description = json_data.getString("description");
                    Log.i("THIS ONE IS FINE",medicine_description);
                    /*for(int i=0; i<jArray.length(); i++){
                        JSONObject json_data = jArray.getJSONObject(i);
                        medicine_description = json_data.getString("description");

                        Log.i("log_tag",medicine_description);
                    }*/
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest);
        Log.i(TAG, "THIS RETURNS NULL: " + medicine_description);

Body:
Volley works in an asynchronous way, it means that you can't know when the response will arrive from your webservice. It will works on separate thread rather than UI thread.

So the outside block of code will get executed irrespective of the Volley response.

If you need the string in your function you should probably create a method and call it when you have the result.

Here is an example:

    public void onResponse(String response) {
            try {

                JSONObject json = new JSONObject(response);
                JSONArray jArray = json.getJSONArray("results");
                Log.d(TAG, "readJSON: " + jArray.length());

                JSONObject json_data = jArray.getJSONObject(0);
                medicine_description = json_data.getString("description");
                passdata(medicine_description);  //create method to pass data
                Log.i("THIS ONE IS FINE",medicine_description);
                /*for(int i=0; i<jArray.length(); i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    medicine_description = json_data.getString("description");

                    Log.i("log_tag",medicine_description);
                }*/
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }


来源: stackexchange

问:
How to preventDefault() in modal login form
I'm working with Spring Framework MVC and I'm trying to make my login form work but I'm really a beginner in ajax.

Here is my index.jsp code.

  ×

<form:form id="login-form" method="POST" commandName="users" class="modal-content2 animate">

      <img src="<c:url value=" /public/images/rsz_default-user.png "/>"   alt="Avatar2" class="avatar">

        Correo
        <input name="correo" id="correo" class="form-control" />

        Password
        <input type="password" name="password" id="password" class="form-control" />

      <button type="submit"onclick="submitForm();"class="cyan">Enviar</button>
      <button type="button" onclick="document.getElementById('modal1').style.display = 'none'" class="red">Cancel</button>
      Olvidaste tu Contraseña?

  </form:form>

```
</div>
</div>
</p>

<p>Here is my LoginController:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>@RequestMapping(value = "/index.htm", method = RequestMethod.POST)
public @ResponseBody String login(@ModelAttribute("users") Users u,BindingResult result) {
  String returnText;
  this.userValidations.validate(u, result);
  Users user = checkUser(u.getCorreo(), u.getPassword());
  if ((u.getCorreo().equals(user.getCorreo())) && (u.getPassword().equals(user.getPassword()))) {
    returnText = "¡Bienvenid@ " + user.getNombre() + "!";
  } else {
    returnText = "Usuario incorrecto";
  }
  return returnText;
}</code>```

and this is my ajax function to submit the modal form if the login was successfull.

function submitForm(){
    $('#login-form').on('submit', function (e) {

        e.preventDefault();
        var form = $(this);
        alert("Estoy aca");
        $.ajax('/index.htm', {
            type: 'POST',
            data: form.serialize(),
            success: function (result) {
                alert("Estoy aca");
                Materialize.toast(result);
            }
        });

    });
}```

My problem here is when I complete the form correctly the submit is working as expected but if I put wrong data into the form I don't know how to catch the error into the modal without refresh or redirect the page.

答:
Your code is wrong, why are you binding to the submit event in the onclick event. That is not necessary, since you are already binding to the onclick event, and you are programatically executing the ajax call...

Now to your actual question, if you return false in any eventhadler function, the event is cancelled.

One easy way to do it would be  making a validator javascript function, and return false if the validator is not satisfied..

```<code>function isEverythingValid(){
  var isFormValid = true;

  //Validate all your form here

  //for example:
  if(document.getElementById('someId').value == ""){
    isFormValid = isFormValid && false;
  }
  return isFormValid ;
}

function submitForm(){
 if(isEverythingValid()){
       $.ajax('/index.htm', {
        type: 'POST',
        data: form.serialize(),
        success: function (result) {
            alert("Estoy aca");
            Materialize.toast(result);
         }
       });
   }
  else{
     return false;
 }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working with Spring Framework MVC and I'm trying to make my login form work but I'm really a beginner in ajax.

Here is my index.jsp code.

  ×

<form:form id="login-form" method="POST" commandName="users" class="modal-content2 animate">

      <img src="<c:url value=" /public/images/rsz_default-user.png "/>"   alt="Avatar2" class="avatar">

        Correo
        <input name="correo" id="correo" class="form-control" />

        Password
        <input type="password" name="password" id="password" class="form-control" />

      <button type="submit"onclick="submitForm();"class="cyan">Enviar</button>
      <button type="button" onclick="document.getElementById('modal1').style.display = 'none'" class="red">Cancel</button>
      Olvidaste tu Contraseña?

  </form:form>

Here is my LoginController:

@RequestMapping(value = "/index.htm", method = RequestMethod.POST)
public @ResponseBody String login(@ModelAttribute("users") Users u,BindingResult result) {
  String returnText;
  this.userValidations.validate(u, result);
  Users user = checkUser(u.getCorreo(), u.getPassword());
  if ((u.getCorreo().equals(user.getCorreo())) && (u.getPassword().equals(user.getPassword()))) {
    returnText = "¡Bienvenid@ " + user.getNombre() + "!";
  } else {
    returnText = "Usuario incorrecto";
  }
  return returnText;
}

and this is my ajax function to submit the modal form if the login was successfull.

function submitForm(){
    $('#login-form').on('submit', function (e) {

        e.preventDefault();
        var form = $(this);
        alert("Estoy aca");
        $.ajax('/index.htm', {
            type: 'POST',
            data: form.serialize(),
            success: function (result) {
                alert("Estoy aca");
                Materialize.toast(result);
            }
        });

    });
}

My problem here is when I complete the form correctly the submit is working as expected but if I put wrong data into the form I don't know how to catch the error into the modal without refresh or redirect the page.

Body:
Your code is wrong, why are you binding to the submit event in the onclick event. That is not necessary, since you are already binding to the onclick event, and you are programatically executing the ajax call...

Now to your actual question, if you return false in any eventhadler function, the event is cancelled.

One easy way to do it would be  making a validator javascript function, and return false if the validator is not satisfied..

function isEverythingValid(){
  var isFormValid = true;

  //Validate all your form here

  //for example:
  if(document.getElementById('someId').value == ""){
    isFormValid = isFormValid && false;
  }
  return isFormValid ;
}

function submitForm(){
 if(isEverythingValid()){
       $.ajax('/index.htm', {
        type: 'POST',
        data: form.serialize(),
        success: function (result) {
            alert("Estoy aca");
            Materialize.toast(result);
         }
       });
   }
  else{
     return false;
 }


问:
What is the difference between ?matrix and ?matrix()
I was going through swirl() again as a refresher, and I've noticed that the author of swirl says the command ?matrix is the correct form to calling for a help screen. But, when I run ?matrix(), it still works? Is there a difference between having and not having a pair of parenthesis?

答: By running matrix and in general any_function you get the source code of it.


问:
Spring in a JavaFX application - how to property handle controller as dependency?
I have a JavaFX application that uses spring boot, exactly as described in this blog post:

http://www.greggbolinger.com/let-spring-be-your-javafx-controller-factory/

I am using the FXML loader overriding the controller factory to use spring.

The problem is that Spring loads the controller class marked as @Component on application start or later if marked with @Lazy, but keeps the bean in memory.

If I open a Stage, modify the data, close the stage and open it again, the data is still there (because the controller was kept by spring). It also gets in the way if I open two of the same Stage (window). It shares the same controller, so if I modify one, the other modifies too, and this is not the desired behavior.

How to I properly handle JavaFX controllers with spring?

Thanks!

答:
Mark the controller as having prototype scope, so that a new instance is created on each request:

```<code>@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class Controller {
    // ...
}
</code>```

Body:
Mark the controller as having prototype scope, so that a new instance is created on each request:

@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class Controller {
    // ...
}


问:
Signup page with additional options
I'm trying to create a pricing page where the user first selects the topic, and then they selects the plan.

I cant figure out to do both on one page, as the topic will be the same for all of the plans, but each plan is different.

I have a hidden field called topic which holds the selected topic, but how do I know which submit button will be clicked.

Heres an image with what I'm trying to achieve.

http://cl.ly/3N3b3U0J261r3f1T3q3i

答:
You can add different value to each submit button:

```<code><%= f.submit "Plan 1" %>
<%= f.submit "Plan 2" %>
<%= f.submit "Plan 3" %>
</code>```

And you can read this value from params hash.

Or you can change name field in submit button and check it also in params hash.

ContentLicense: CC BY-SA 2.5

Title: Signup page with additional options

Body:
You can add different value to each submit button:

<%= f.submit "Plan 1" %>
<%= f.submit "Plan 2" %>
<%= f.submit "Plan 3" %>

And you can read this value from params hash.

Or you can change name field in submit button and check it also in params hash.


问:
asp5 IConfigurationRoot get json array
I am trying to supply some additional configuration data to my asp 5 mvc 6 web app ("rc1-final" libraries) to be deployed on Azure.  Part of this additional data consists of an array of data in a json file.  I can add this json file to my configuration, and while debugging if I watch the configuration object I can browse to the provider entry and see it does in fact contact the array of data I'm looking for.

However, trying Configuration["extraData"] yields null (as the "value" of that property is null, even though it clearly contains the array of elements.

I have no problem accessing single values that are stored in json config (such as my database connection string, and other values.)  It just seems as though json data in array format is not supported?

See the following sample json file (which validates according to jsonlint and seems fine to me)...

```<code>//extraData.json
{
  "ExtraData": [
    {
      "Id": 1,
      "Description": "The first identifier"
    },
    {
      "Id": 2,
      "Description": "The second identifier"
    },
    {
      "Id": 3,
      "Description": "The third identifier"
    }
  ]
}
</code>```

...and the following sample Startup.cs...

```<code>//Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
using System.IO;
using Microsoft.AspNet.Authentication.Cookies;
using System.Net;

namespace MyProj {
    public class Startup {
        public static IConfigurationRoot Configuration;

        public Startup(IHostingEnvironment env) {
            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile("extraData.json")
                .AddEnvironmentVariables();

            Configuration = builder.Build();
        }

        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            MyDbSeed seed,
            ILoggerFactory logging) {

            dynamic xData = JObject.Parse("ExtraData"); //VALUE IS NULL, THROWS EX
            var myList = JsonConvert
                .DeserializeObject<List<MyID>>(
                    xData.ExtraData.ToString()
                );
            //Do something important with this list
        }

        public static void Main(string[] args) => WebApplication.Run<Startup>(args);
    }

    class MyID {
        public int ID { get; set; }
        public string Description { get; set; }
    }
}
</code>```

What I've been having to do instead (which seems hackish, especially given the handy Configuration system now available)...

```<code>dynamic xData = JObject.Parse(
    File.OpenText(
        env.MapPath(
            @"..\extraData.json"
        )
    ).ReadToEnd()
);
var xList = JsonConvert
    .DeserializeObject<List<MyID>>(
        xData.ExtraData.ToString()
    );
//Do something important with the list, eg...
var o = new MyClass(xList);
</code>```

I'm also uncertain as to the support on azure to do file io like this.

I found this resource which suggests that array/IEnum is supported, but it is just using an in-mem provider...

http://github.com/aspnet/Configuration/blob/dev/test/Microsoft.Extensions.Configuration.Binder.Test/ConfigurationCollectionBindingTests.cs

This resource is the documentation from MS...

http://docs.asp.net/en/latest/fundamentals/configuration.html

Some related questions that have turned up while searching since posted (not 1:1 related to my issue necessarily, but could prove useful for others searching)

How to use ConfigurationBinder in Configure method of startup.cs

Retrieve sections from config.json in ASP.NET 5

ASP.NET 5 (vNext) - Getting a Configuration Setting

答:
You can retrieve settings this way:</p>

```<code>var extraDataSection = configuration.GetSection("ExtraData");
foreach (IConfigurationSection section in extraDataSection.GetChildren())
{
    var id = section.GetValue<int>("Id");
    var description = section.GetValue<string>("Description");
}
</code>```

Title: asp5 IConfigurationRoot get json array

Body:
I am trying to supply some additional configuration data to my asp 5 mvc 6 web app ("rc1-final" libraries) to be deployed on Azure.  Part of this additional data consists of an array of data in a json file.  I can add this json file to my configuration, and while debugging if I watch the configuration object I can browse to the provider entry and see it does in fact contact the array of data I'm looking for.

However, trying Configuration["extraData"] yields null (as the "value" of that property is null, even though it clearly contains the array of elements.

I have no problem accessing single values that are stored in json config (such as my database connection string, and other values.)  It just seems as though json data in array format is not supported?

See the following sample json file (which validates according to jsonlint and seems fine to me)...

//extraData.json
{
  "ExtraData": [
    {
      "Id": 1,
      "Description": "The first identifier"
    },
    {
      "Id": 2,
      "Description": "The second identifier"
    },
    {
      "Id": 3,
      "Description": "The third identifier"
    }
  ]
}

...and the following sample Startup.cs...

//Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
using System.IO;
using Microsoft.AspNet.Authentication.Cookies;
using System.Net;

namespace MyProj {
    public class Startup {
        public static IConfigurationRoot Configuration;

        public Startup(IHostingEnvironment env) {
            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile("extraData.json")
                .AddEnvironmentVariables();

            Configuration = builder.Build();
        }

        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            MyDbSeed seed,
            ILoggerFactory logging) {

            dynamic xData = JObject.Parse("ExtraData"); //VALUE IS NULL, THROWS EX
            var myList = JsonConvert
                .DeserializeObject<List<MyID>>(
                    xData.ExtraData.ToString()
                );
            //Do something important with this list
        }

        public static void Main(string[] args) => WebApplication.Run<Startup>(args);
    }

    class MyID {
        public int ID { get; set; }
        public string Description { get; set; }
    }
}

What I've been having to do instead (which seems hackish, especially given the handy Configuration system now available)...

dynamic xData = JObject.Parse(
    File.OpenText(
        env.MapPath(
            @"..\extraData.json"
        )
    ).ReadToEnd()
);
var xList = JsonConvert
    .DeserializeObject<List<MyID>>(
        xData.ExtraData.ToString()
    );
//Do something important with the list, eg...
var o = new MyClass(xList);

I'm also uncertain as to the support on azure to do file io like this.

I found this resource which suggests that array/IEnum is supported, but it is just using an in-mem provider...

http://github.com/aspnet/Configuration/blob/dev/test/Microsoft.Extensions.Configuration.Binder.Test/ConfigurationCollectionBindingTests.cs

This resource is the documentation from MS...

http://docs.asp.net/en/latest/fundamentals/configuration.html

Some related questions that have turned up while searching since posted (not 1:1 related to my issue necessarily, but could prove useful for others searching)

How to use ConfigurationBinder in Configure method of startup.cs

Retrieve sections from config.json in ASP.NET 5

ASP.NET 5 (vNext) - Getting a Configuration Setting

Body:
You can retrieve settings this way:

var extraDataSection = configuration.GetSection("ExtraData");
foreach (IConfigurationSection section in extraDataSection.GetChildren())
{
    var id = section.GetValue<int>("Id");
    var description = section.GetValue<string>("Description");
}


问:
My onTouch method is not doing what it is programmed to do
I am making a Android app. The objective is to make circles that when touched something happens.In more detail this app will display 2 types of circles either a red or a green one. The color of the circle is stored in the lastColor variable. The purpose of the color is so that when a user "touches" a red or green circle something happens. For example if a green circle is touched a point is added to there score, or if a red circle is clicked the activity is changed, but when either of the circles are clicked nothing happens. Here is the onTouch method

```<code>public boolean onTouch(View v, MotionEvent event) {
   int x = (int) event.getX();
   int y = (int) event.getY();
   if(isInsideCircle(x, y) ==  true){
      //Do your things here
       if(redColor == lastColor){
          Intent i = new Intent(v.getContext(), YouFailed.class);
          v.getContext().startActivity(i);
       } else {
           addPoints++;
       }
   }else {

   }
   return true;
}
</code>```

This part of the code is the thing that is not functioning properly. Here is the entire class below.

```<code>public class DrawingView extends View {

    public DrawingView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub

    }

    RectF rectf = new RectF(0, 0, 200, 0);

    private static final int w = 100;
    public static int lastColor = Color.BLACK;
    private final Random random = new Random();
    private final Paint paint = new Paint();
    private final int radius = 230;
    private final Handler handler = new Handler();
    public static int redColor = Color.RED;
    public static int greenColor = Color.GREEN;
    int randomWidth = 0;
    int randomHeight = 0;
    public static int addPoints = 0;

    private final Runnable updateCircle = new Runnable() {
        @Override
        public void run() {
            lastColor = random.nextInt(2) == 1 ? redColor : greenColor;
            paint.setColor(lastColor);
            invalidate();
            handler.postDelayed(this, 1000);
        }
    };

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        handler.post(updateCircle);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        handler.removeCallbacks(updateCircle);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // your other stuff here
        if (random == null) {
            randomWidth = (int) (random.nextInt(Math.abs(getWidth() - radius / 2)) + radius / 2f);
            randomHeight = (random.nextInt((int) Math.abs((getHeight() - radius / 2 + radius / 2f))));
        }
        else {
            randomWidth = (int) (random.nextInt(Math.abs(getWidth() - radius / 2)) + radius / 2f);
            randomHeight = (random.nextInt((int) Math.abs((getHeight() - radius / 2 + radius / 2f))));
        }

        canvas.drawCircle(randomWidth, randomHeight + radius / 2f, radius, paint);

        paint.setColor(Color.BLACK);
        paint.setTextSize(150);
        canvas.drawText("Score: " + addPoints, 120, 300, paint);
    }

    public boolean onTouch(View v, MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();
        if (isInsideCircle(x, y) == true) {
            //Do your things here
            if (redColor == lastColor) {
                Intent i = new Intent(v.getContext(), YouFailed.class);
                v.getContext().startActivity(i);
            }
            else {
                addPoints++;
            }
        }
        else {

        }
        return true;
    }

    public boolean isInsideCircle(int x, int y) {
        if ((((x - randomWidth) * (x - randomWidth)) + ((y - randomHeight) * (y - randomHeight))) < ((radius) * (radius)))
            return true;
        return false;
    }
}
</code>```

答:
You need to override the onTouchEvent function. I tested the code and it fully works! Also, make sure to return false after addPoints++ to ensure only one point is added. Hopefully this works for you!</p>

```<code>@Override
public boolean onTouchEvent(MotionEvent event) {
    int x = (int) event.getX();
    int y = (int) event.getY();
    if (isInsideCircle(x, y)) {
        //Do your things here
        if (redColor == lastColor) {
            Intent i = new Intent(getContext(), null);
            getContext().startActivity(i);
        }
        else {
            addPoints++;
            return false;
        }
    }
    else {

    }
    return true;
}
</code>```

Body:
I am making a Android app. The objective is to make circles that when touched something happens.In more detail this app will display 2 types of circles either a red or a green one. The color of the circle is stored in the lastColor variable. The purpose of the color is so that when a user "touches" a red or green circle something happens. For example if a green circle is touched a point is added to there score, or if a red circle is clicked the activity is changed, but when either of the circles are clicked nothing happens. Here is the onTouch method

public boolean onTouch(View v, MotionEvent event) {
   int x = (int) event.getX();
   int y = (int) event.getY();
   if(isInsideCircle(x, y) ==  true){
      //Do your things here
       if(redColor == lastColor){
          Intent i = new Intent(v.getContext(), YouFailed.class);
          v.getContext().startActivity(i);
       } else {
           addPoints++;
       }
   }else {

   }
   return true;
}

This part of the code is the thing that is not functioning properly. Here is the entire class below.

public class DrawingView extends View {

    public DrawingView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub

    }

    RectF rectf = new RectF(0, 0, 200, 0);

    private static final int w = 100;
    public static int lastColor = Color.BLACK;
    private final Random random = new Random();
    private final Paint paint = new Paint();
    private final int radius = 230;
    private final Handler handler = new Handler();
    public static int redColor = Color.RED;
    public static int greenColor = Color.GREEN;
    int randomWidth = 0;
    int randomHeight = 0;
    public static int addPoints = 0;

    private final Runnable updateCircle = new Runnable() {
        @Override
        public void run() {
            lastColor = random.nextInt(2) == 1 ? redColor : greenColor;
            paint.setColor(lastColor);
            invalidate();
            handler.postDelayed(this, 1000);
        }
    };

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        handler.post(updateCircle);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        handler.removeCallbacks(updateCircle);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // your other stuff here
        if (random == null) {
            randomWidth = (int) (random.nextInt(Math.abs(getWidth() - radius / 2)) + radius / 2f);
            randomHeight = (random.nextInt((int) Math.abs((getHeight() - radius / 2 + radius / 2f))));
        }
        else {
            randomWidth = (int) (random.nextInt(Math.abs(getWidth() - radius / 2)) + radius / 2f);
            randomHeight = (random.nextInt((int) Math.abs((getHeight() - radius / 2 + radius / 2f))));
        }

        canvas.drawCircle(randomWidth, randomHeight + radius / 2f, radius, paint);

        paint.setColor(Color.BLACK);
        paint.setTextSize(150);
        canvas.drawText("Score: " + addPoints, 120, 300, paint);
    }

    public boolean onTouch(View v, MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();
        if (isInsideCircle(x, y) == true) {
            //Do your things here
            if (redColor == lastColor) {
                Intent i = new Intent(v.getContext(), YouFailed.class);
                v.getContext().startActivity(i);
            }
            else {
                addPoints++;
            }
        }
        else {

        }
        return true;
    }

    public boolean isInsideCircle(int x, int y) {
        if ((((x - randomWidth) * (x - randomWidth)) + ((y - randomHeight) * (y - randomHeight))) < ((radius) * (radius)))
            return true;
        return false;
    }
}

Body:
You need to override the onTouchEvent function. I tested the code and it fully works! Also, make sure to return false after addPoints++ to ensure only one point is added. Hopefully this works for you!

@Override
public boolean onTouchEvent(MotionEvent event) {
    int x = (int) event.getX();
    int y = (int) event.getY();
    if (isInsideCircle(x, y)) {
        //Do your things here
        if (redColor == lastColor) {
            Intent i = new Intent(getContext(), null);
            getContext().startActivity(i);
        }
        else {
            addPoints++;
            return false;
        }
    }
    else {

    }
    return true;
}


问:
How can I get my Android device country code without using GPS?
An Android mobile actually does know quite well where it is - but is there a way of retrieving the country by something, like a country code or country name?

There isn't any need to know the exact GPS position - the country code or name is sufficient, and I am using this code:

```<code> String locale = context.getResources().getConfiguration().locale.getCountry(Locale.getDefault());
 System.out.println("country = "+locale);
</code>```

It gives me the code "US", but my device kept in India. Is there a way to find the device's current country code without using GPS or a network provider?

Because I am using a tablet.

答:
The checked answer has deprecated code. You need to implement this:</p>

```<code>String locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    locale = context.getResources().getConfiguration().getLocales().get(0).getCountry();
} else {
    locale = context.getResources().getConfiguration().locale.getCountry();
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
An Android mobile actually does know quite well where it is - but is there a way of retrieving the country by something, like a country code or country name?

There isn't any need to know the exact GPS position - the country code or name is sufficient, and I am using this code:

 String locale = context.getResources().getConfiguration().locale.getCountry(Locale.getDefault());
 System.out.println("country = "+locale);

It gives me the code "US", but my device kept in India. Is there a way to find the device's current country code without using GPS or a network provider?

Because I am using a tablet.

Body:
The checked answer has deprecated code. You need to implement this:

String locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    locale = context.getResources().getConfiguration().getLocales().get(0).getCountry();
} else {
    locale = context.getResources().getConfiguration().locale.getCountry();
}


问:
Sending a slash through mysql
I'm not sure why this has stumped me. I have the following code

```<code>$website = "http://www.google.com";
$name = "Person";

if(!empty($website) {
   $name = "[url=$website]$name[/url]";
}
</code>```

Then i try to insert that into mysql. I tried adding mysql_real_escape_string to both $website and $name (after the if statement), thinking the "/url" might also cause problems.

```<code>$name       = mysql_real_escape_string($name);
</code>```

Still no luck though. Any advice? What am I missing? It's giving me this error

"Parse error: syntax error, unexpected '/', expecting T_STRING or T_VARIABLE or T_NUM_STRING"

答:
There wont be any problem at all. When reading from database you should then put stripslashes() around your value.

e.g.

```<code>$query = "SELECT field FROM table";
$row = mysql_fetch_array(mysql_query($query));

echo(stripslashes($row['field']));
</code>```

And your output will be the same like YOUR input.

Title: Sending a slash through mysql

Body:
I'm not sure why this has stumped me. I have the following code

$website = "http://www.google.com";
$name = "Person";

if(!empty($website) {
   $name = "[url=$website]$name[/url]";
}

Then i try to insert that into mysql. I tried adding mysql_real_escape_string to both $website and $name (after the if statement), thinking the "/url" might also cause problems.

$name       = mysql_real_escape_string($name);

Still no luck though. Any advice? What am I missing? It's giving me this error

"Parse error: syntax error, unexpected '/', expecting T_STRING or T_VARIABLE or T_NUM_STRING"

Body:
There wont be any problem at all. When reading from database you should then put stripslashes() around your value.

e.g.

$query = "SELECT field FROM table";
$row = mysql_fetch_array(mysql_query($query));

echo(stripslashes($row['field']));

And your output will be the same like YOUR input.


问:
Replace part of columns string value
I have a column with values like /i/t/item_xxl_12063874_18123233.jpg. I need a formula to get a string value item_xxl_12063874_18123233.jpg.

答:
If it's always to remove the first 5 characters, simply

```<code>=MID(A1, 6, 9999)
</code>```

BUT if it is about retrieving what is after the last /, with a random amount of characters before it, then it is a little more tricky:

```<code> =TRIM(RIGHT(SUBSTITUTE(A1, "/", REPT(" ", 300)), 300))
</code>```

Title: Replace part of columns string value

Body:
If it's always to remove the first 5 characters, simply

=MID(A1, 6, 9999)

BUT if it is about retrieving what is after the last /, with a random amount of characters before it, then it is a little more tricky:

 =TRIM(RIGHT(SUBSTITUTE(A1, "/", REPT(" ", 300)), 300))


问:
UIApplication.registerForRemoteNotifications() must be called from main thread only
Xcode 9 (iOS 11) showing me an error/warning while registering for Push (remote) notification.

Here is error message

And here is code, I've tried:

```<code>let center  = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
        if error == nil{
              UIApplication.shared.registerForRemoteNotifications()
        }
 }
</code>```

Error/Warning Line:

UIApplication.shared.registerForRemoteNotifications()

How to resolve this?

答:
TL;DR:
All UI manipulations should be done in the Main Thread to avoid problems. If failed to do so, Main Thread Checker (Newly introduced debugging feature in Xcode 9) will produce issues at Runtime. So wrap your code in Main Thread block like below to avoid glitches and runtime warnings.

```<code>DispatchQueue.main.async {
    UIApplication.shared.registerForRemoteNotifications()
}
</code>```

In Xcode releases before ver. 9, the warnings related to main thread would get printed in the console area textually. Anyway, you can optionally disable (not a recommended approach) the Main Thread Checker in the Diagnostic settings in Edit Scheme.

Explanation:

Apple introduced a new debugging option in Xcode 9 for checking issues at Runtime for UIKit and other API's that manipulate UI elements. If there's any change to the UI elements from UIKit API at Runtime, without a Main thread block, it is highly likely to cause UI glitches and crashes. The Main Thread Checker is enabled by default to catch those issues at runtime. You can disable Main Thread Checker in the Edit Scheme window just like below, although it is not really recommended to do so:

If you have any older SDK's or Frameworks, when updating to Xcode 9, you may face this warning since some of the UIKit method calls wouldn't have been wrapped in Main Thread. Updating them to latest version would fix the issue (if the developer is aware of it and fixed it).

Quote from Xcode 9 beta release notes:

New in Xcode 9 – Main Thread Checker.

Enable detection of UI API misuse from background thread

Detects AppKit, UIKit, and WebKit method calls that are not made on the main thread.

Automatically enabled during debugging, and can be disabled in the Diagnostic tab of the scheme editor.

Main Thread Checker works with Swift and C languages.

Body:
Xcode 9 (iOS 11) showing me an error/warning while registering for Push (remote) notification.

Here is error message

And here is code, I've tried:

let center  = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
        if error == nil{
              UIApplication.shared.registerForRemoteNotifications()
        }
 }

Error/Warning Line:

UIApplication.shared.registerForRemoteNotifications()

How to resolve this?

Body:
TL;DR:
All UI manipulations should be done in the Main Thread to avoid problems. If failed to do so, Main Thread Checker (Newly introduced debugging feature in Xcode 9) will produce issues at Runtime. So wrap your code in Main Thread block like below to avoid glitches and runtime warnings.

DispatchQueue.main.async {
    UIApplication.shared.registerForRemoteNotifications()
}

In Xcode releases before ver. 9, the warnings related to main thread would get printed in the console area textually. Anyway, you can optionally disable (not a recommended approach) the Main Thread Checker in the Diagnostic settings in Edit Scheme.

Explanation:

Apple introduced a new debugging option in Xcode 9 for checking issues at Runtime for UIKit and other API's that manipulate UI elements. If there's any change to the UI elements from UIKit API at Runtime, without a Main thread block, it is highly likely to cause UI glitches and crashes. The Main Thread Checker is enabled by default to catch those issues at runtime. You can disable Main Thread Checker in the Edit Scheme window just like below, although it is not really recommended to do so:

If you have any older SDK's or Frameworks, when updating to Xcode 9, you may face this warning since some of the UIKit method calls wouldn't have been wrapped in Main Thread. Updating them to latest version would fix the issue (if the developer is aware of it and fixed it).

Quote from Xcode 9 beta release notes:

New in Xcode 9 – Main Thread Checker.

Enable detection of UI API misuse from background thread

Detects AppKit, UIKit, and WebKit method calls that are not made on the main thread.

Automatically enabled during debugging, and can be disabled in the Diagnostic tab of the scheme editor.

Main Thread Checker works with Swift and C languages.


问:
D3 SVG to canvas
How can I convert d3 SVG element to canvas?

I got this working on web-chrome browser but it is not working in iOS safari:

Used this example. This example also not work on iOs safari but works on chrome desktop
Ref: http://bl.ocks.org/syntagmatic/1dd1acd35f77c1fc64863e42f4a405bb

Function for SVG to Canvas:

```<code>function svgToCanvas() {
          // d3.select("#aloft-canvas-container").html("");
            var devicePixelRatio = window.devicePixelRatio || 1;
            var canvas = d3.select("#aloft-canvas-container").append("canvas")
                .attr("width", (width) * devicePixelRatio)
                .attr("height", (ceilingChartHeight + topMarginFactor + xAxisTopContainerHeight) * devicePixelRatio)
                .style("width", width + "px")
                .style("height", (ceilingChartHeight+ topMarginFactor + xAxisTopContainerHeight) + "px")
                .style("position", "absolute");
            var context = canvas.node().getContext("2d");
            context.scale(devicePixelRatio, devicePixelRatio);
            // Convert SVG to Canvas
            // see: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Drawing_DOM_objects_into_a_canvas
            var DOMURL = window.URL || window.webkitURL || window;
            var svgNode = d3.select("#meteo-barbs-container").node(),
            serializer = new XMLSerializer();
            // var svgString = '<svg xmlns="http://www.w3.org/2000/svg">' + serializer.serializeToString(svgNode) + '</svg>';
            var svgString =  '<svg xmlns="http://www.w3.org/2000/svg">' + domNodeToString(svgNode) + '</svg>';;
            console.log(svgString);
            var image = new Image();
            var svgBlob = new Blob([svgString], {
                type: "image/svg+xml"
            });
            var url = DOMURL.createObjectURL(svgBlob);

            image.onload = function () {
                context.drawImage(image, 0, 0);
                DOMURL.revokeObjectURL(url);
                d3.select("#meteo-barbs-container").remove();
            }

            image.src = url;
        };
</code>```

In iOS it is drawing only half canvas. Not sure what is happening :-(

答:
Use of canvg library simplifies all this :-)

https://github.com/canvg/canvg

```<code>contents.convertSvgToCanvas = function (sourceSvgId, canvasContainerId, canvasId, canvasWidth, canvasHeight, callback) {
    var serializer = new XMLSerializer();
    var svgNode = d3.select("#" + sourceSvgId).node();
    var devicePixelRatio = window.devicePixelRatio || 1;
    d3.select("#" + canvasContainerId).append("canvas")
        .attr("id", canvasId)
        .attr("width", (canvasWidth) * devicePixelRatio)
        .attr("height", (canvasHeight) * devicePixelRatio)
        .style("position", "absolute");
    if (svgNode) {
        var cv = document.getElementById(canvasId);
        var ctx = cv.getContext("2d");
        var pixelRatio = window.devicePixelRatio || 1;
        cv.style.width = cv.width + "px";
        cv.style.height = cv.height + "px";
        cv.width *= pixelRatio;
        cv.height *= pixelRatio;
        ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
        canvg(document.getElementById(canvasId), serializer.serializeToString(svgNode));
        callback();
    }
};
</code>```

Title: D3 SVG to canvas

Body:
How can I convert d3 SVG element to canvas?

I got this working on web-chrome browser but it is not working in iOS safari:

Used this example. This example also not work on iOs safari but works on chrome desktop
Ref: http://bl.ocks.org/syntagmatic/1dd1acd35f77c1fc64863e42f4a405bb

Function for SVG to Canvas:

function svgToCanvas() {
          // d3.select("#aloft-canvas-container").html("");
            var devicePixelRatio = window.devicePixelRatio || 1;
            var canvas = d3.select("#aloft-canvas-container").append("canvas")
                .attr("width", (width) * devicePixelRatio)
                .attr("height", (ceilingChartHeight + topMarginFactor + xAxisTopContainerHeight) * devicePixelRatio)
                .style("width", width + "px")
                .style("height", (ceilingChartHeight+ topMarginFactor + xAxisTopContainerHeight) + "px")
                .style("position", "absolute");
            var context = canvas.node().getContext("2d");
            context.scale(devicePixelRatio, devicePixelRatio);
            // Convert SVG to Canvas
            // see: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Drawing_DOM_objects_into_a_canvas
            var DOMURL = window.URL || window.webkitURL || window;
            var svgNode = d3.select("#meteo-barbs-container").node(),
            serializer = new XMLSerializer();
            // var svgString = '<svg xmlns="http://www.w3.org/2000/svg">' + serializer.serializeToString(svgNode) + '</svg>';
            var svgString =  '<svg xmlns="http://www.w3.org/2000/svg">' + domNodeToString(svgNode) + '</svg>';;
            console.log(svgString);
            var image = new Image();
            var svgBlob = new Blob([svgString], {
                type: "image/svg+xml"
            });
            var url = DOMURL.createObjectURL(svgBlob);

            image.onload = function () {
                context.drawImage(image, 0, 0);
                DOMURL.revokeObjectURL(url);
                d3.select("#meteo-barbs-container").remove();
            }

            image.src = url;
        };

In iOS it is drawing only half canvas. Not sure what is happening :-(

Body:
Use of canvg library simplifies all this :-)

https://github.com/canvg/canvg

contents.convertSvgToCanvas = function (sourceSvgId, canvasContainerId, canvasId, canvasWidth, canvasHeight, callback) {
    var serializer = new XMLSerializer();
    var svgNode = d3.select("#" + sourceSvgId).node();
    var devicePixelRatio = window.devicePixelRatio || 1;
    d3.select("#" + canvasContainerId).append("canvas")
        .attr("id", canvasId)
        .attr("width", (canvasWidth) * devicePixelRatio)
        .attr("height", (canvasHeight) * devicePixelRatio)
        .style("position", "absolute");
    if (svgNode) {
        var cv = document.getElementById(canvasId);
        var ctx = cv.getContext("2d");
        var pixelRatio = window.devicePixelRatio || 1;
        cv.style.width = cv.width + "px";
        cv.style.height = cv.height + "px";
        cv.width *= pixelRatio;
        cv.height *= pixelRatio;
        ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
        canvg(document.getElementById(canvasId), serializer.serializeToString(svgNode));
        callback();
    }
};


问:
Is there something like `helm exec`?
I use the following helm (2.4.2) commands in my gitlab-ci.yml script:

```<code>- helm upgrade --install myapp-db --wait --set postgresUser=postgres,postgresPassword=postgres,postgresDatabase=myapp stable/postgresql
- helm upgrade --install myapp-web ./myapp-chart --wait --set env.DATABASE_URL="${DATABASE_URL}"
</code>```

It's part of a deployment to my staging/review environment. After the above commands complete, I would like to execute commands against the my-app pod to create/migrate the database. At the moment this is achieved through the use of an initContainer (defined in the referenced yaml file). But I would prefer the logic to be part of the CI script - so I don't have to have a separate deployment file for production.

Is there a way to do this with helm? Or is my only option to use kubectl exec? If I use kubectl exec, is there an easy way to get the name of the pod using helm?

答:
This GitHub issue addresses how you might use kubectl to find out the name of a pod based on a label:

https://github.com/kubernetes/kubernetes/issues/8876

I implemented the following:

```<code>- export POD_NAME=`kubectl get pod -l "app=myapp-web-chart" -o jsonpath='{.items[0].metadata.name}'`
- kubectl exec $POD_NAME -- mix ecto.migrate
</code>```

Still, it would be much nicer if there was a way to do this with helm

Title: Is there something like `helm exec`?

Body:
I use the following helm (2.4.2) commands in my gitlab-ci.yml script:

- helm upgrade --install myapp-db --wait --set postgresUser=postgres,postgresPassword=postgres,postgresDatabase=myapp stable/postgresql
- helm upgrade --install myapp-web ./myapp-chart --wait --set env.DATABASE_URL="${DATABASE_URL}"

It's part of a deployment to my staging/review environment. After the above commands complete, I would like to execute commands against the my-app pod to create/migrate the database. At the moment this is achieved through the use of an initContainer (defined in the referenced yaml file). But I would prefer the logic to be part of the CI script - so I don't have to have a separate deployment file for production.

Is there a way to do this with helm? Or is my only option to use kubectl exec? If I use kubectl exec, is there an easy way to get the name of the pod using helm?

Body:
This GitHub issue addresses how you might use kubectl to find out the name of a pod based on a label:

https://github.com/kubernetes/kubernetes/issues/8876

I implemented the following:

- export POD_NAME=`kubectl get pod -l "app=myapp-web-chart" -o jsonpath='{.items[0].metadata.name}'`
- kubectl exec $POD_NAME -- mix ecto.migrate

Still, it would be much nicer if there was a way to do this with helm


问:
Add Column values in sql server query
I have result of two queries like:

Result of query 1

```<code>ID   Value
1    4
2    0
3    6
4    9
</code>```

Result of query 2

```<code>ID   Value
1    6
2    4
3    0
4    1
</code>```

I want to add values column "Value" and show final result:

Result of Both queries

```<code>ID   Value
1    10
2    4
3    6
4    10
</code>```

plz guide me...

答:
```<code>select id, sum(value) as value
from (
    select id, value from query1
    uninon all
    select id, value from query2
) x
group by id
</code>```

Title: Add Column values in sql server query

Body:
I have result of two queries like:

Result of query 1

ID   Value
1    4
2    0
3    6
4    9

Result of query 2

ID   Value
1    6
2    4
3    0
4    1

I want to add values column "Value" and show final result:

Result of Both queries

ID   Value
1    10
2    4
3    6
4    10

plz guide me...


问:
PostgreSQL: Sorting on alphanumeric string and decimal field
Hope you all are fine and doing good!

I have a table items with 2 million+ records the structure looks like below:

```<code>id (int) | price (decimal) | priority (int)
-------------------------------------------
10001    |  59000.25       |    1
10002    |  73000.91       |    2
10003    |  1000.23        |    1
10004    |  9567.18        |    1
</code>```

The solution that I am looking for is very straightforward: How do I sort this table on price+priority on ASC|DESC order?

Current and working solution: I am using ORDER BY priority ASC, price ASC. But as far as my knowledge goes, sorting on multiple column is slow and not optimised approach (and I am facing realtime slowness because of this).

Solutions I tried: I've added a temporary column to this table:

```<code>id (int) | price (decimal) | priority (int) | new_priority (varchar)
--------------------------------------------------------------------
10001    |  59000.25       |    1           | a59000.25
10002    |  73000.91       |    2           | b73000.91
10003    |  1000.23        |    1           | a1000.23
10004    |  9567.18        |    1           | a9567.18
</code>```

I've replaced 1 => a, 2 => b, 3 => c up till 10 (max number I have in database)

Now, whenever I am trying below SQLs, none of them is working

```<code>SELECT * FROM items
ORDER BY new_priority ASC

SELECT * FROM items
ORDER BY new_priority::bytea

SELECT * FROM items
ORDER BY SUBSTRING(new_priority FROM '^(.*?)( \\d+)?$'),
     COALESCE(SUBSTRING(new_priority FROM ' (\\d+)$')::INTEGER, 0)
</code>```

Please advise!

Links I referred:

Postgresql sorting mixed alphanumeric data

Alphanumeric Sorting in PostgreSQL

Alphanumeric sorting with PostgreSQL

Alphanumeric case in-sensitive sorting in postgres

答:
May be you could do a better solution using NEW_PRIORITY as DECIMAL.

Assuming the value in PRICE is not greater then (say) 999999 and the PRIORITY is not too "large", you could use PRIORITY*1000000+PRICE.

Anyway, I think using index as said in comments could be a better solution.

To create a "composite index", you can use following sintax:

```<code>CREATE INDEX index_name ON table_name (priority ASC, price ASC);
</code>```

Body:
Hope you all are fine and doing good!

I have a table items with 2 million+ records the structure looks like below:

id (int) | price (decimal) | priority (int)
-------------------------------------------
10001    |  59000.25       |    1
10002    |  73000.91       |    2
10003    |  1000.23        |    1
10004    |  9567.18        |    1

The solution that I am looking for is very straightforward: How do I sort this table on price+priority on ASC|DESC order?

Current and working solution: I am using ORDER BY priority ASC, price ASC. But as far as my knowledge goes, sorting on multiple column is slow and not optimised approach (and I am facing realtime slowness because of this).

Solutions I tried: I've added a temporary column to this table:

id (int) | price (decimal) | priority (int) | new_priority (varchar)
--------------------------------------------------------------------
10001    |  59000.25       |    1           | a59000.25
10002    |  73000.91       |    2           | b73000.91
10003    |  1000.23        |    1           | a1000.23
10004    |  9567.18        |    1           | a9567.18

I've replaced 1 => a, 2 => b, 3 => c up till 10 (max number I have in database)

Now, whenever I am trying below SQLs, none of them is working

SELECT * FROM items
ORDER BY new_priority ASC

SELECT * FROM items
ORDER BY new_priority::bytea

SELECT * FROM items
ORDER BY SUBSTRING(new_priority FROM '^(.*?)( \\d+)?$'),
     COALESCE(SUBSTRING(new_priority FROM ' (\\d+)$')::INTEGER, 0)

Please advise!

Links I referred:

Postgresql sorting mixed alphanumeric data

Alphanumeric Sorting in PostgreSQL

Alphanumeric sorting with PostgreSQL

Alphanumeric case in-sensitive sorting in postgres

Body:
May be you could do a better solution using NEW_PRIORITY as DECIMAL.

Assuming the value in PRICE is not greater then (say) 999999 and the PRIORITY is not too "large", you could use PRIORITY*1000000+PRICE.

Anyway, I think using index as said in comments could be a better solution.

To create a "composite index", you can use following sintax:

CREATE INDEX index_name ON table_name (priority ASC, price ASC);


问:
Passing a php array to a javascript array inside a PHP function
I know this question has been asked a lot on StackOverflow, although I can't find any solution that can be applied to my problem.

I'm working on a platform that regroups all videos and pictures of my company (I'm taking back the project after my ex-coworker), my issue is on the Lightbox that displays the pictures.

I have a PHP function that returns HTML/CSS/Javascript in string format like this :

```<code>$block = '<div id="myModal" class="modal" style="margin:auto">'
            .'<span style="float:right;margin-right:33px"><a href="'.HTTP_IHM_PATH.'Suppression.php?id='.$records[$i]['Access_Key'].'" onclick="return confirm(\'Êtes-vous sûr de vouloir continuer cette suppression ? Elle sera définitive.\');"><img src="'.HTTP_IMG_PATH.'corbeille.jpg" style="width:20px;height:auto;"></a></span>'
            .'<span class="close cursor" onclick="closeModal()" style="color:#585858; font-size:60px;float:right;">×</span>'
[...]
return $block;
</code>```

I call the function like this : <?php echo function() ?>

In here, I have a PHP array $records that contains all informations about the pictures I want to display in my LightBox, I want later in my code to use those informations into my javascript functions.

I've heard that I can translate the array in javascript by using  but it doesn't work !

In the end what I want to do is when the user clicks on a picture, it opens up my LightBox and for every pictures he is watching, I want to call my php function UpdateViews() that add 1 to the number of views of the picture.

I tried using Ajax, but since it's pretty new to me I may be doing stupid mistakes (this is still in string format in the variable $block):

```<code>$block .= '//getSlideIndex returns slideIndex wich is the id of the <img/>
$(\'#\' + getSlideIndex()).on(\'click\', function (){
                    alert("Ok onclick" + records[getSlideIndex()]["Access_Key"];
                    //"Access_Key" is the property I need (primary key of the table)
                    $.ajax({
                        type:\'GET\',
                        url: \'/picture.php\',
                        data: {id=\' + records[getSlideIndex()]["Access_Key"] + \'},
                        success: function(data){
                            alert(\'success\' + data);
                        },
                        error: function(exception){
                            alert(\'Exception: \' + exception);
                        }
                    });
                    e.preventDefault();
                });';
</code>```

NOTE : My ex-coworker already used some Ajax in his code, so at the time I'm on this page, a $_GET is already set : Will I be able to make my ajax work in this case ?

Thank you if you read until this point, I hope you can help me get on the right track.

答:
I've heard that I can translate the array in javascript by using  but it doesn't work !

That's pretty close. This will make a JavaScript variable that's a JSON string. You can then use JavaScript's JSON parse to convert that JSON string back into an Array/Object.

Once you do all of that, you will have a JavaScript array with data delivered from your PHP array.

Body:
I know this question has been asked a lot on StackOverflow, although I can't find any solution that can be applied to my problem.

I'm working on a platform that regroups all videos and pictures of my company (I'm taking back the project after my ex-coworker), my issue is on the Lightbox that displays the pictures.

I have a PHP function that returns HTML/CSS/Javascript in string format like this :

$block = '
'
            .''
            .'×'
[...]
return $block;

I call the function like this : <?php echo function() ?>

In here, I have a PHP array $records that contains all informations about the pictures I want to display in my LightBox, I want later in my code to use those informations into my javascript functions.

I've heard that I can translate the array in javascript by using  but it doesn't work !

In the end what I want to do is when the user clicks on a picture, it opens up my LightBox and for every pictures he is watching, I want to call my php function UpdateViews() that add 1 to the number of views of the picture.

I tried using Ajax, but since it's pretty new to me I may be doing stupid mistakes (this is still in string format in the variable $block):

$block .= '//getSlideIndex returns slideIndex wich is the id of the
$(\'#\' + getSlideIndex()).on(\'click\', function (){
                    alert("Ok onclick" + records[getSlideIndex()]["Access_Key"];
                    //"Access_Key" is the property I need (primary key of the table)
                    $.ajax({
                        type:\'GET\',
                        url: \'/picture.php\',
                        data: {id=\' + records[getSlideIndex()]["Access_Key"] + \'},
                        success: function(data){
                            alert(\'success\' + data);
                        },
                        error: function(exception){
                            alert(\'Exception: \' + exception);
                        }
                    });
                    e.preventDefault();
                });';

NOTE : My ex-coworker already used some Ajax in his code, so at the time I'm on this page, a $_GET is already set : Will I be able to make my ajax work in this case ?

Thank you if you read until this point, I hope you can help me get on the right track.

Body:
I've heard that I can translate the array in javascript by using <script>var records = <?php json_encode($records) ?></script> but it doesn't work !

That's pretty close. This will make a JavaScript variable that's a JSON string. You can then use JavaScript's JSON parse to convert that JSON string back into an Array/Object.

Once you do all of that, you will have a JavaScript array with data delivered from your PHP array.


答: How about creating an index? Indexes are a mechanism to enhance the performance of databases. Creating an index may be slow and might last some hours, but you'll notice differences in further queries.</p>

Title: PostgreSQL: Sorting on alphanumeric string and decimal field


问:
Problems: Sending and Receiving Data
I am trying to perform two processes using bean, my problem is that I can not find the way these processes are performed continuously. The first process is to send an object and the second process is the response of the object.

```<code>@Component
public class Proceso implements InitializingBean{
    private static final String XML_SCHEMA_LOCATION = "/proceso/model/schema/proceso.xsd";
    private Envio envio;
    private Respuesta respuesta;

    public void Proceso_envio(Proceso proceso, OutputStream outputstream) throws JAXBException{
      envio.marshal(proceso, outputstream);}

    public void Proceso_respuesta(InputStream inputstream) throws JAXBException, FileNotFoundException{
    Object obj = unmarshaller.unmarshal(inputStream);
    return (Proceso_respuesta) obj;}

    @Override
    public void afterPropertiesSet() throws Exception{
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(getClass().getResource(XML_SCHEMA_LOCATION));
        JAXBContext jc = JAXBContext.newInstance(Envio.class, Respuesta.class);

        this.marshaller = jc.createMarshaller();
        this.marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        this.marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.displayName());
        this.marshaller.setSchema(schema);

        this.unmarshaller = jc.createUnmarshaller();

        this.unmarshaller.setSchema(schema);
     }
</code>```

I imagine that with the code my question becomes clearer.

答:
thanks maquina,

this is the solution:

```<code>@Component
public class Proceso implements InitializingBean{
    private static final String XML_SCHEMA_LOCATION = "/proceso/model/schema/proceso.xsd";
    private Envio envio;
    private Respuesta respuesta;

    public synchronized void Proceso_envio(Proceso proceso, OutputStream outputstream) throws JAXBException{
      envio.marshal(proceso, outputstream);}

    public void synchronized Proceso_respuesta(InputStream inputstream) throws JAXBException, FileNotFoundException{
    Object obj = unmarshaller.unmarshal(inputStream);
    return (Proceso_respuesta) obj;}

    @Override
    public void afterPropertiesSet() throws Exception{
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(getClass().getResource(XML_SCHEMA_LOCATION));
        JAXBContext jc = JAXBContext.newInstance(Envio.class, Respuesta.class);

        this.marshaller = jc.createMarshaller();
        this.marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        this.marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.displayName());
        this.marshaller.setSchema(schema);

        this.unmarshaller = jc.createUnmarshaller();

        this.unmarshaller.setSchema(schema);
     }
</code>```

Title: Problems: Sending and Receiving Data

Body:
I am trying to perform two processes using bean, my problem is that I can not find the way these processes are performed continuously. The first process is to send an object and the second process is the response of the object.

@Component
public class Proceso implements InitializingBean{
    private static final String XML_SCHEMA_LOCATION = "/proceso/model/schema/proceso.xsd";
    private Envio envio;
    private Respuesta respuesta;

    public void Proceso_envio(Proceso proceso, OutputStream outputstream) throws JAXBException{
      envio.marshal(proceso, outputstream);}

    public void Proceso_respuesta(InputStream inputstream) throws JAXBException, FileNotFoundException{
    Object obj = unmarshaller.unmarshal(inputStream);
    return (Proceso_respuesta) obj;}

    @Override
    public void afterPropertiesSet() throws Exception{
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(getClass().getResource(XML_SCHEMA_LOCATION));
        JAXBContext jc = JAXBContext.newInstance(Envio.class, Respuesta.class);

        this.marshaller = jc.createMarshaller();
        this.marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        this.marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.displayName());
        this.marshaller.setSchema(schema);

        this.unmarshaller = jc.createUnmarshaller();

        this.unmarshaller.setSchema(schema);
     }

I imagine that with the code my question becomes clearer.

Body:
thanks maquina,

this is the solution:

@Component
public class Proceso implements InitializingBean{
    private static final String XML_SCHEMA_LOCATION = "/proceso/model/schema/proceso.xsd";
    private Envio envio;
    private Respuesta respuesta;

    public synchronized void Proceso_envio(Proceso proceso, OutputStream outputstream) throws JAXBException{
      envio.marshal(proceso, outputstream);}

    public void synchronized Proceso_respuesta(InputStream inputstream) throws JAXBException, FileNotFoundException{
    Object obj = unmarshaller.unmarshal(inputStream);
    return (Proceso_respuesta) obj;}

    @Override
    public void afterPropertiesSet() throws Exception{
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(getClass().getResource(XML_SCHEMA_LOCATION));
        JAXBContext jc = JAXBContext.newInstance(Envio.class, Respuesta.class);

        this.marshaller = jc.createMarshaller();
        this.marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        this.marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.displayName());
        this.marshaller.setSchema(schema);

        this.unmarshaller = jc.createUnmarshaller();

        this.unmarshaller.setSchema(schema);
     }


问:
Cons for defining logger non-static
Comments for this answer How do you reduce Java logging boilerplate code? strongly suggest not to use loggers as instance member variables. I can think of two negative side-effects:

1) superclass logs with the subclass's logger

2) object cannot be serialized (unless marked transient)

But if serializing is not necessary and logging with subclass name is not a problem, is there anything else why it should be avoided? I think it reduces boilerplate code and avoids copy-paste errors while copying logger variable definition from one class to another. Even Spring framework (which I believe has very good coding standards) uses this method.

答:
If your Logger is an instance member instead of static, the Logger has to be retrieved every time a new object is created. Albeit this overhead is probably insignificant, but it's one disadvantage.

From a design perspective, Loggers aren't really a property of an object, since they're usually meta-information about your system rather than business information within the system itself. A Logger isn't really part of something like a Car object in the same way an Engine or a Transmission is. Tying Loggers to objects as members (in most cases) doesn't make sense semantically more than anything.

OwnerDisplayName: martsraits

Title: Cons for defining logger non-static

OwnerDisplayName: robhruska


问:
CPU, RAM and I/O intensive code runs slowly on Azure Functions
We have some code that is fairly CPU, RAM and I/O intensive (it creates lots of temporary files, decompresses, resizes and compresses images). We're trying to integrate this into a "serverless" web application, and seeing as our code only runs on Windows at the moment we're testing it on Azure Functions.

We've observed that our code runs considerably slower on Azure Functions than it does on my local workstation (Core i7-4790, 16GB RAM, SSD). For example, one typical workload gives us these timings:

```<code>Dev workstation:                                2.47 sec
Azure Functions, "App Service" plan (S3 size): 10.59 sec
Azure Functions, "Consumption" plan:           15.96 sec
</code>```

We've also found that on the "Consumption" plan, timings vary quite widely - one particular job gave us times varying between 112 and 153 seconds. The same job on the S3 "App Service" plan took between 117 and 119 seconds, and around 31 seconds on my workstation.

Timings on P3 were similar to S3, which is about what I expected as the CPU and RAM specs are the same.

So I have a few questions really:

Is there anything we can do to profile our application running on Azure, to identify where the bottlenecks might be?

Are we crazy to be trying to run such a heavy workload on Azure Functions?

Does anyone have any suggestions as to how we could get our code running on more powerful hardware without swallowing all the complexity of managing a farm of virtual machines?

答:
You can profile App Service app (including Function App) remotely, see this link. I used Kudu and it worked good.

Really depends on your targets. The timings that your quoted can be perfectly fine for some applications.

This seems to be too broad a question for SO.

A more FunctionApp-ish approach would be to try to break down your long-running function into smaller short-running functions, and thus break down and potentially parallelize the processing.

Body:
We have some code that is fairly CPU, RAM and I/O intensive (it creates lots of temporary files, decompresses, resizes and compresses images). We're trying to integrate this into a "serverless" web application, and seeing as our code only runs on Windows at the moment we're testing it on Azure Functions.

We've observed that our code runs considerably slower on Azure Functions than it does on my local workstation (Core i7-4790, 16GB RAM, SSD). For example, one typical workload gives us these timings:

Dev workstation:                                2.47 sec
Azure Functions, "App Service" plan (S3 size): 10.59 sec
Azure Functions, "Consumption" plan:           15.96 sec

We've also found that on the "Consumption" plan, timings vary quite widely - one particular job gave us times varying between 112 and 153 seconds. The same job on the S3 "App Service" plan took between 117 and 119 seconds, and around 31 seconds on my workstation.

Timings on P3 were similar to S3, which is about what I expected as the CPU and RAM specs are the same.

So I have a few questions really:

Is there anything we can do to profile our application running on Azure, to identify where the bottlenecks might be?

Are we crazy to be trying to run such a heavy workload on Azure Functions?

Does anyone have any suggestions as to how we could get our code running on more powerful hardware without swallowing all the complexity of managing a farm of virtual machines?


问:
XIB with dynamic width, fix height in center - programmatically constraints seems not to work
I created a .xib with freeform and implement it like this

```<code>if let alertView = Bundle.main.loadNibNamed(Constants.XIB.titleImageLabelThreeButtonsAlertView, owner: self, options: nil)?.first as? TitleImageLabelThreeButtonsAlertView {

        view.addSubview(alertView)

        alertView.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY)

        view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 20))
        view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 20))

        alertView.autoresizingMask = [UIViewAutoresizing.flexibleLeftMargin, UIViewAutoresizing.flexibleRightMargin, UIViewAutoresizing.flexibleTopMargin, UIViewAutoresizing.flexibleBottomMargin]
        self.view.layoutIfNeeded()

  }
</code>```

I call this code in viewDidAppear. The center thing seems to work, but it seems that the trailing and leading don't have any effect. I want them with a distance of 20, my alertView should have a fixed height and appear in center.

The xib has always the same size (see screenshots)

My originally targeted was to get a xib  that I can implement in every view for every device. So what is the best way to get this?

my xib file

simulator iphone 7

simulator iphone 4

答:
You are mixing up auto layout and fixed placement (with autoresizing mask).  What you want to do is completely use auto layout so that the view will adjust its layout automatically.  You say you want a horizontal distance of 20, a fixed height and to be centred so I would do this:

```<code>if let alertView = Bundle.main.loadNibNamed(Constants.XIB.titleImageLabelThreeButtonsAlertView, owner: self, options: nil)?.first as? TitleImageLabelThreeButtonsAlertView {

    view.addSubview(alertView)

    // Start using auto layout
    alertView.translatesAutoresizingMaskIntoConstraints = false

    // Set the leading and trailing constraints for horizontal placement
    view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: -20))
    view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 20))

    // Centre it vertically
    view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0))

    // Set the fixed height constraint
    let fixedHeight: CGFloat = 100
    view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 0, constant: fixedHeight))
}
</code>```

That will get you what you want no matter how the device, superview, orientation, etc changes.

Body:
I created a .xib with freeform and implement it like this

if let alertView = Bundle.main.loadNibNamed(Constants.XIB.titleImageLabelThreeButtonsAlertView, owner: self, options: nil)?.first as? TitleImageLabelThreeButtonsAlertView {

        view.addSubview(alertView)

        alertView.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY)

        view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 20))
        view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 20))

        alertView.autoresizingMask = [UIViewAutoresizing.flexibleLeftMargin, UIViewAutoresizing.flexibleRightMargin, UIViewAutoresizing.flexibleTopMargin, UIViewAutoresizing.flexibleBottomMargin]
        self.view.layoutIfNeeded()

  }

I call this code in viewDidAppear. The center thing seems to work, but it seems that the trailing and leading don't have any effect. I want them with a distance of 20, my alertView should have a fixed height and appear in center.

The xib has always the same size (see screenshots)

My originally targeted was to get a xib  that I can implement in every view for every device. So what is the best way to get this?

my xib file

simulator iphone 7

simulator iphone 4

Body:
You are mixing up auto layout and fixed placement (with autoresizing mask).  What you want to do is completely use auto layout so that the view will adjust its layout automatically.  You say you want a horizontal distance of 20, a fixed height and to be centred so I would do this:

if let alertView = Bundle.main.loadNibNamed(Constants.XIB.titleImageLabelThreeButtonsAlertView, owner: self, options: nil)?.first as? TitleImageLabelThreeButtonsAlertView {

    view.addSubview(alertView)

    // Start using auto layout
    alertView.translatesAutoresizingMaskIntoConstraints = false

    // Set the leading and trailing constraints for horizontal placement
    view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: -20))
    view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 20))

    // Centre it vertically
    view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0))

    // Set the fixed height constraint
    let fixedHeight: CGFloat = 100
    view.addConstraint(NSLayoutConstraint(item: alertView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 0, constant: fixedHeight))
}

That will get you what you want no matter how the device, superview, orientation, etc changes.


问:
ASP.NET Core Get Json Array using IConfiguration
In appsettings.json

```<code>{
      "MyArray": [
          "str1",
          "str2",
          "str3"
      ]
}
</code>```

In Startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
{
     services.AddSingleton<IConfiguration>(Configuration);
}
</code>```

In HomeController

```<code>public class HomeController : Controller
{
    private readonly IConfiguration _config;
    public HomeController(IConfiguration config)
    {
        this._config = config;
    }

    public IActionResult Index()
    {
        return Json(_config.GetSection("MyArray"));
    }
}
</code>```

There is my code above. I got null.
How do I get the array?

答:
If you have array of complex JSON objects like this:

```<code>{
  "MySettings": {
    "MyValues": [
      { "Key": "Key1", "Value":  "Value1" },
      { "Key": "Key2", "Value":  "Value2" }
    ]
  }
}
</code>```

You can retrieve settings this way:

```<code>var valuesSection = configuration.GetSection("MySettings:MyValues");
foreach (IConfigurationSection section in valuesSection.GetChildren())
{
    var key = section.GetValue<string>("Key");
    var value = section.GetValue<string>("Value");
}
</code>```

Body:
In appsettings.json

{
      "MyArray": [
          "str1",
          "str2",
          "str3"
      ]
}

In Startup.cs

public void ConfigureServices(IServiceCollection services)
{
     services.AddSingleton<IConfiguration>(Configuration);
}

In HomeController

public class HomeController : Controller
{
    private readonly IConfiguration _config;
    public HomeController(IConfiguration config)
    {
        this._config = config;
    }

    public IActionResult Index()
    {
        return Json(_config.GetSection("MyArray"));
    }
}

There is my code above. I got null.
How do I get the array?

Body:
If you have array of complex JSON objects like this:

{
  "MySettings": {
    "MyValues": [
      { "Key": "Key1", "Value":  "Value1" },
      { "Key": "Key2", "Value":  "Value2" }
    ]
  }
}

You can retrieve settings this way:

var valuesSection = configuration.GetSection("MySettings:MyValues");
foreach (IConfigurationSection section in valuesSection.GetChildren())
{
    var key = section.GetValue<string>("Key");
    var value = section.GetValue<string>("Value");
}


问:
ng-style assign dynamic scope variable from $index
I'm trying to assign a scope variable's value to an ng-style directive but the name is not parsing.

What am I doing wrong? When you press the TEST button it should turn the text to RED but the scope variable is not parsing as it's name is dynamic. I've tried multiple different syntax which all didn't work.

Here is the html:

```<code><div ng-app="myApp" ng-controller="MyCtrl">
<button ng-click="Test()">test</button>
<div ng-repeat="item in items">
   <div ng-style="{{'DynamicVariable-'+$index}}">
    {{someone.name}}
   </div>
  </div>
</div>
</code>```

controller code

```<code>var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
  $scope.someone = {
    name: 'John'
  };
$scope.items=[1,2,3,4,5,6,7,8,9];
  $scope.mainId = 1;
  $scope.Test=function(){
      for(var i=0;i<$scope.items.length;i++){
    $scope["DynamicVariable-"+i]={color:'red'};
  }
  console.log($scope);
  };
}]);
</code>```

js fiddle that doesn't work:
http://jsfiddle.net/avboivin/0qov365b/4/

答:
It has a problem with '-', try to remove it

html:

```<code><div ng-app="myApp" ng-controller="MyCtrl">
    <button ng-click="Test()">test</button>
    <div ng-repeat="item in items">
        <div ng-style="{{'DynamicVariable'+$index}}">
            {{ someone.name }}
        </div>
    </div>
</div>
</code>```

controller:

```<code>var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function ($scope) {
    $scope.someone = {
        name: 'John'
    };
    $scope.items = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    $scope.mainId = 1;
    $scope.Test = function () {
        for (var i = 0; i < $scope.items.length; i++) {
            $scope["DynamicVariable" + i] = { color: 'red' };
        }
        console.log($scope);
    };
}]);
</code>```

fork

Body:
I'm trying to assign a scope variable's value to an ng-style directive but the name is not parsing.

What am I doing wrong? When you press the TEST button it should turn the text to RED but the scope variable is not parsing as it's name is dynamic. I've tried multiple different syntax which all didn't work.

Here is the html:

<button ng-click="Test()">test</button>

    {{someone.name}}

controller code

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
  $scope.someone = {
    name: 'John'
  };
$scope.items=[1,2,3,4,5,6,7,8,9];
  $scope.mainId = 1;
  $scope.Test=function(){
      for(var i=0;i<$scope.items.length;i++){
    $scope["DynamicVariable-"+i]={color:'red'};
  }
  console.log($scope);
  };
}]);

js fiddle that doesn't work:
http://jsfiddle.net/avboivin/0qov365b/4/

Body:
It has a problem with '-', try to remove it

html:

<div ng-app="myApp" ng-controller="MyCtrl">
    <button ng-click="Test()">test</button>
    <div ng-repeat="item in items">
        <div ng-style="{{'DynamicVariable'+$index}}">
            {{ someone.name }}
        </div>
    </div>
</div>

controller:

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function ($scope) {
    $scope.someone = {
        name: 'John'
    };
    $scope.items = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    $scope.mainId = 1;
    $scope.Test = function () {
        for (var i = 0; i < $scope.items.length; i++) {
            $scope["DynamicVariable" + i] = { color: 'red' };
        }
        console.log($scope);
    };
}]);

fork


问:
MySQL Error Code: 1300. Invalid utf8 character string: '' with '\' infront of unicode character
I have a bunch of csv-files and I came across a case where strangely enough '\' utf8 are in front of unicode characters e.g.

```<code>Tom;\Éscobar;123
</code>```

and when doing a bulk insert via:

```<code>LOAD DATA LOCAL INFILE 'test.csv'
INTO TABLE TEST_TABLE
CHARACTER SET 'utf8'
FIELDS TERMINATED BY ';'
ENCLOSED BY '"';
</code>```

the error: Invalid utf8 character string: '' is thrown.
I wonder if this is a bug in MySQL LOAD DATA or if I am missing something here.

```<code>MySQL-Version 5.7.16
</code>```

答:
If you can figure out what the pattern is, ...

load the CSV into VARBINARY or BLOB column(s).

run a SQL, probably using the REPLACE() function`, to cleanse the data (remove the blackslashes).

do a suitable ALTER, probably MODIFY COLUMN ... VARCHAR(...) CHARACTER SET utf8mb4 to get it into a text format.

Body:
I have a bunch of csv-files and I came across a case where strangely enough '\' utf8 are in front of unicode characters e.g.

Tom;\Éscobar;123

and when doing a bulk insert via:

LOAD DATA LOCAL INFILE 'test.csv'
INTO TABLE TEST_TABLE
CHARACTER SET 'utf8'
FIELDS TERMINATED BY ';'
ENCLOSED BY '"';

the error: Invalid utf8 character string: '' is thrown.
I wonder if this is a bug in MySQL LOAD DATA or if I am missing something here.

MySQL-Version 5.7.16


问:
Strongloop deploy on AWS EC2
I have instaled node.js and npm on EC2 through command line and also uploaded all my files for Strongloop project
When I'm running the server locally it is working fine but when I'm running the node server.js on EC2 command line. it is running  but saying:

Web server listening at: http://0.0.0.0:3001/
ENVIRONMENT : development

How could I start my server on AWS EC2... Can't figure it out.

My Config.json file

```<code>{
"restApiRoot": "/api",
"host": "0.0.0.0",
"port": 3001,
"remoting": {
"context": {
  "enableHttpContext": false
},
"rest": {
  "normalizeHttpPath": false,
  "xml": false
},
"json": {
  "strict": false,
  "limit": "100kb"
},
"urlencoded": {
  "extended": true,
  "limit": "100kb"
},
"cors": false,
"errorHandler": {
  "disableStackTrace": true
}
 },
 "legacyExplorer": false
}
</code>```

答:
Few possible things:

Make sure the port you are using is in your AWS Security Inbound Rules. Go to 'Security Groups', then select the group associated with your instance then click "Inbound". In your case, you have to add the port 3001 for HTTP protocol and the source 0.0.0.0/0.

You need to keep the service running even after you close the terminal/command-prompt window. To make the server start automatically and run in the background, you need to use something like 'systemctl' in ubuntu. Here is a step by step guide and tutorial: https://www.digitalocean.com/community/tutorials/how-to-use-systemctl-to-manage-systemd-services-and-units

Now try visiting your IPv4 Public IP or your associated domain name with the port number. e.g. 1.2.3.4:3001 or mywebsite.com:3001. The IP is written in the same row as your instance in AWS.

Title: Strongloop deploy on AWS EC2

Body:
I have instaled node.js and npm on EC2 through command line and also uploaded all my files for Strongloop project
When I'm running the server locally it is working fine but when I'm running the node server.js on EC2 command line. it is running  but saying:

Web server listening at: http://0.0.0.0:3001/
ENVIRONMENT : development

How could I start my server on AWS EC2... Can't figure it out.

My Config.json file

{
"restApiRoot": "/api",
"host": "0.0.0.0",
"port": 3001,
"remoting": {
"context": {
  "enableHttpContext": false
},
"rest": {
  "normalizeHttpPath": false,
  "xml": false
},
"json": {
  "strict": false,
  "limit": "100kb"
},
"urlencoded": {
  "extended": true,
  "limit": "100kb"
},
"cors": false,
"errorHandler": {
  "disableStackTrace": true
}
 },
 "legacyExplorer": false
}


问:
fgetc requires 'enter' key pressed twice on WINDOWS
I'm trying to make a password input mask function that's portable between windows, linux, and osx. So far I have code that works perfectly in linux and osx, but windows is giving me one issue.

Does anyone know why in windows fgetc requires me to press the enter key twice before it exits the while loop?

```<code>static int get_password(char *password, int mask)
{
    int max_pass_len = 512;

#ifdef _WIN32
    HANDLE hstdin = GetStdHandle(STD_INPUT_HANDLE);
    DWORD mode = 0;
    DWORD prev_mode = 0;
    GetConsoleMode(hstdin, &mode);
    GetConsoleMode(hstdin, &prev_mode);
    SetConsoleMode(hstdin, mode & ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT));
#else
    static struct termios prev_terminal;
    static struct termios terminal;

    tcgetattr(STDIN_FILENO, &prev_terminal);

    memcpy (&terminal, &prev_terminal, sizeof(struct termios));
    terminal.c_lflag &= ~(ICANON | ECHO);
    terminal.c_cc[VTIME] = 0;
    terminal.c_cc[VMIN] = 1;
    tcsetattr(STDIN_FILENO, TCSANOW, &terminal);
#endif

    size_t idx = 0;         /* index, number of chars in read   */
    int c = 0;

    const char BACKSPACE = 8;
    const char RETURN = 13;

    /* read chars from fp, mask if valid char specified */
    while (((c = fgetc(stdin)) != '\n' && c != RETURN && c != EOF && idx < max_pass_len - 1) ||
            (idx == max_pass_len - 1 && c == 127))
    {
        if (c != 127 && c != BACKSPACE) {
            if (31 < mask && mask < 127)    /* valid ascii char */
                fputc(mask, stdout);
            password[idx++] = c;
        } else if (idx > 0) {         /* handle backspace (del)   */
            if (31 < mask && mask < 127) {
                fputc(0x8, stdout);
                fputc(' ', stdout);
                fputc(0x8, stdout);
            }
            password[--idx] = 0;
        }
    }
    password[idx] = 0; /* null-terminate   */

// go back to the previous settings
#ifdef _WIN32
    SetConsoleMode(hstdin, prev_mode);
#else
    tcsetattr(STDIN_FILENO, TCSANOW, &prev_terminal);
#endif

    return idx; /* number of chars in passwd    */
}
</code>```

```

答:
Problem resolved using ReadConsole</p>

```<code>#ifdef _WIN32
    long unsigned int char_read = 0;
    while ((ReadConsole(hstdin, &c, 1, &char_read, NULL) && c != '\n' && c != RETURN && c != EOF && idx < max_pass_len - 1) ||
            (idx == max_pass_len - 1 && c == BACKSPACE))
#else
    while (((c = fgetc(stdin)) != '\n' && c != EOF && idx < max_pass_len - 1) ||
            (idx == max_pass_len - 1 && c == 127))
#endif
</code>```

Body:
I'm trying to make a password input mask function that's portable between windows, linux, and osx. So far I have code that works perfectly in linux and osx, but windows is giving me one issue.

Does anyone know why in windows fgetc requires me to press the enter key twice before it exits the while loop?

static int get_password(char *password, int mask)
{
    int max_pass_len = 512;

#ifdef _WIN32
    HANDLE hstdin = GetStdHandle(STD_INPUT_HANDLE);
    DWORD mode = 0;
    DWORD prev_mode = 0;
    GetConsoleMode(hstdin, &mode);
    GetConsoleMode(hstdin, &prev_mode);
    SetConsoleMode(hstdin, mode & ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT));
#else
    static struct termios prev_terminal;
    static struct termios terminal;

    tcgetattr(STDIN_FILENO, &prev_terminal);

    memcpy (&terminal, &prev_terminal, sizeof(struct termios));
    terminal.c_lflag &= ~(ICANON | ECHO);
    terminal.c_cc[VTIME] = 0;
    terminal.c_cc[VMIN] = 1;
    tcsetattr(STDIN_FILENO, TCSANOW, &terminal);
#endif

    size_t idx = 0;         /* index, number of chars in read   */
    int c = 0;

    const char BACKSPACE = 8;
    const char RETURN = 13;

    /* read chars from fp, mask if valid char specified */
    while (((c = fgetc(stdin)) != '\n' && c != RETURN && c != EOF && idx < max_pass_len - 1) ||
            (idx == max_pass_len - 1 && c == 127))
    {
        if (c != 127 && c != BACKSPACE) {
            if (31 < mask && mask < 127)    /* valid ascii char */
                fputc(mask, stdout);
            password[idx++] = c;
        } else if (idx > 0) {         /* handle backspace (del)   */
            if (31 < mask && mask < 127) {
                fputc(0x8, stdout);
                fputc(' ', stdout);
                fputc(0x8, stdout);
            }
            password[--idx] = 0;
        }
    }
    password[idx] = 0; /* null-terminate   */

// go back to the previous settings
#ifdef _WIN32
    SetConsoleMode(hstdin, prev_mode);
#else
    tcsetattr(STDIN_FILENO, TCSANOW, &prev_terminal);
#endif

    return idx; /* number of chars in passwd    */
}

```

Body:
Problem resolved using ReadConsole

#ifdef _WIN32
    long unsigned int char_read = 0;
    while ((ReadConsole(hstdin, &c, 1, &char_read, NULL) && c != '\n' && c != RETURN && c != EOF && idx < max_pass_len - 1) ||
            (idx == max_pass_len - 1 && c == BACKSPACE))
#else
    while (((c = fgetc(stdin)) != '\n' && c != EOF && idx < max_pass_len - 1) ||
            (idx == max_pass_len - 1 && c == 127))
#endif