问:
Thymeleaf select getting selected object
I have a Thymeleaf form.  with a select field .

```<code><form th:object="${contactForm}" th:action="@{/contact}" method="post">
<select th:field="*{cityId}">
        <option th:each="item : ${cityList}"
                th:value="${item.id}" th:text="${item.description}">
</select>
</code>```

When I submit the form, I can get the city id in city field. Is it possible to get the city id and description as a object. if I have a city object in my contactForm.

答:
Current Code

I'm just assuming that you are using the following classes based on your html, so lets take them as a starting point.

```<code>/* This may be called City in your code */
public class Item {
    private Long id;
    private String description;

    // getter/setter/constructor here...
}

public class ContactForm {
    private Long cityId;

    // getter/setter/constructor here...
}
</code>```

Now what can we do to solve your Problem?

Spring provides a simple way for adding converters for specific classes, so that you dont have to worry about converting a String to a Year object for example. The same technique can be used for other classes like your Item class as well! Let's look into it:

```<code>import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

@Component
public class StringToItemConverter implements Converter<String, Item> {
    @Override
    public Item convert(String source) {
        if(source != null) {
            try {
                Long id = Long.parseLong(source);
                return /* insert your logic for getting an item by it's id here */;
            } catch(Exception e) {
                return null;
            }
        }
        return null;
    }
}
</code>```

The above code is automatically executed by Spring whenever it tries to convert a String (from your form input) to an actual java field with the type Item. So if we change your ContactForm-class a little bit, spring will automatically asign the Item object for the given id.

```<code>public class ContactForm {
    /* Note that cityId now has all the information you need (id and description) You should however consider renaming it to city. Don't forget to change the th:field name too! ;) */
    private Item cityId;

    // getter/setter/constructor here...
}
</code>```

Are you working with Spring Repositories?

If you are storing your Items in a database you most likely use a CrudRepository for that. In that case the code could look like this. Let's assume that your Repository class is named ItemRepository.

```<code>@Component
public class StringToItemConverter implements Converter<String, Item> {
    private ItemRepository itemRepository;

    @Autowired
    public void setItemRepository (ItemRepository itemRepository) {
        this.itemRepository = itemRepository;
    }

    @Override
    public Item convert(String source) {
        if(source != null) {
            try {
                Long id = Long.parseLong(source);
                return itemRepository.findOne(id);
            } catch(Exception e) {
                return null;
            }
        }
        return null;
    }
}
</code>```

The above code would try to convert the String from the form to an actual Item-Object by looking the id up in the database. So we either get the Item or null if anything goes wrong (for example if there is no item for that id or the String could not be parsed as long).

Body:
I have a Thymeleaf form.  with a select field .

<form th:object="${contactForm}" th:action="@{/contact}" method="post">
<select th:field="*{cityId}">
        <option th:each="item : ${cityList}"
                th:value="${item.id}" th:text="${item.description}">
</select>

When I submit the form, I can get the city id in city field. Is it possible to get the city id and description as a object. if I have a city object in my contactForm.

Body:
Current Code

I'm just assuming that you are using the following classes based on your html, so lets take them as a starting point.

/* This may be called City in your code */
public class Item {
    private Long id;
    private String description;

    // getter/setter/constructor here...
}

public class ContactForm {
    private Long cityId;

    // getter/setter/constructor here...
}

Now what can we do to solve your Problem?

Spring provides a simple way for adding converters for specific classes, so that you dont have to worry about converting a String to a Year object for example. The same technique can be used for other classes like your Item class as well! Let's look into it:

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

@Component
public class StringToItemConverter implements Converter<String, Item> {
    @Override
    public Item convert(String source) {
        if(source != null) {
            try {
                Long id = Long.parseLong(source);
                return /* insert your logic for getting an item by it's id here */;
            } catch(Exception e) {
                return null;
            }
        }
        return null;
    }
}

The above code is automatically executed by Spring whenever it tries to convert a String (from your form input) to an actual java field with the type Item. So if we change your ContactForm-class a little bit, spring will automatically asign the Item object for the given id.

public class ContactForm {
    /* Note that cityId now has all the information you need (id and description) You should however consider renaming it to city. Don't forget to change the th:field name too! ;) */
    private Item cityId;

    // getter/setter/constructor here...
}

Are you working with Spring Repositories?

If you are storing your Items in a database you most likely use a CrudRepository for that. In that case the code could look like this. Let's assume that your Repository class is named ItemRepository.

@Component
public class StringToItemConverter implements Converter<String, Item> {
    private ItemRepository itemRepository;

    @Autowired
    public void setItemRepository (ItemRepository itemRepository) {
        this.itemRepository = itemRepository;
    }

    @Override
    public Item convert(String source) {
        if(source != null) {
            try {
                Long id = Long.parseLong(source);
                return itemRepository.findOne(id);
            } catch(Exception e) {
                return null;
            }
        }
        return null;
    }
}

The above code would try to convert the String from the form to an actual Item-Object by looking the id up in the database. So we either get the Item or null if anything goes wrong (for example if there is no item for that id or the String could not be parsed as long).


来源: stackexchange

问:
Sending latitude and longitude to server from android app
I tried sending latitude and longitude using the following code

```<code>package com.example.john.bustrackgps;

import android.Manifest;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity implements LocationListener {

    LocationManager locationManager;
    String mprovider;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();

        mprovider = locationManager.getBestProvider(criteria, false);

        if (mprovider != null && !mprovider.equals("")) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            Location location = locationManager.getLastKnownLocation(mprovider);
            locationManager.requestLocationUpdates(mprovider, 15000, 1, this);

            if (location != null)
                onLocationChanged(location);
            else
                Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
        }
    }

    public void onLocationChanged(Location location) {
        TextView longitude = (TextView) findViewById(R.id.textView);
        TextView latitude = (TextView) findViewById(R.id.textView1);

        longitude.setText("Current Longitude: " + location.getLongitude());
        latitude.setText("Current Latitude: " + location.getLatitude());

        Response.Listener<String> responseListener = new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonResponse = new JSONObject(response);
                    boolean success = jsonResponse.getBoolean("success");
                    if (success) {
                        Intent intent = new Intent(MainActivity.this, ServerUpload.class);
                        MainActivity.this.startActivity(intent);
                    } else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setMessage("Upload failed")
                                .setNegativeButton("Retry", null)
                                .create()
                                .show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };

        ServerUpload registerRequest = new ServerUpload(latitude,longitude,responseListener);
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        queue.add(registerRequest);

    }

    public void onStatusChanged(String s,int i,Bundle bundle)
    {}

    public void onProviderEnabled(String s)
    {}

    public void onProviderDisabled(String s)
    {}
}
</code>```

This is my ServerUpload class

```<code>package com.example.john.bustrackgps;

import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;

public class ServerUpload extends StringRequest {
    private static final String REGISTER_REQUEST_URL = "http://192.168.169.2/serverfiles/bts.php";
    private Map<String, String> params;

    public ServerUpload(TextView latitude, TextView longitude, Response.Listener<String> listener){

        super(Method.POST, REGISTER_REQUEST_URL, listener, null);

        final String latitude1 =latitude.toString();
        final String longitude1 =longitude.toString();
        params = new HashMap<>();
        params.put("latitude", latitude1);
        params.put("longitude", longitude1);
    }

    @Override
    public Map<String, String> getParams() {
        return params;
    }
}
</code>```

This is my bts.php code

```<code><?php

$con = mysqli_connect("127.0.0.1", "root", "", "bustrack");

$latitude = $_POST["latitude"];

$longitude = $_POST["longitude"];

$statement = mysqli_prepare($con, "INSERT INTO updates (latitude, longitude) VALUES (?, ?)");

mysqli_stmt_bind_param($statement, "ss", $latitude, $longitude);

mysqli_stmt_execute($statement);

$response = array();

$response["success"] = true;

echo json_encode($response);
</code>```

The problem is that data does not get entered into the database. Its either 0,0 or "android.extends...."

I am very new to android and not sure were the problem is. Any help would be appreciated!!!

答:
Fix this bug in your ServerUpload method .

```<code> final String latitude1 =latitude.getText().toString();
final String longitude1 =longitude.getText().toString();
</code>```

Try this

```<code> public ServerUpload(TextView latitude, TextView longitude, Response.Listener<String> listener){

    super(Method.POST, REGISTER_REQUEST_URL, listener, null);

    final String latitude1 =latitude.getText().toString();
    final String longitude1 =longitude.getText().toString();
    params = new HashMap<>();
    params.put("latitude", latitude1);
    params.put("longitude", longitude1);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I tried sending latitude and longitude using the following code

package com.example.john.bustrackgps;

import android.Manifest;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity implements LocationListener {

    LocationManager locationManager;
    String mprovider;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();

        mprovider = locationManager.getBestProvider(criteria, false);

        if (mprovider != null && !mprovider.equals("")) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            Location location = locationManager.getLastKnownLocation(mprovider);
            locationManager.requestLocationUpdates(mprovider, 15000, 1, this);

            if (location != null)
                onLocationChanged(location);
            else
                Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
        }
    }

    public void onLocationChanged(Location location) {
        TextView longitude = (TextView) findViewById(R.id.textView);
        TextView latitude = (TextView) findViewById(R.id.textView1);

        longitude.setText("Current Longitude: " + location.getLongitude());
        latitude.setText("Current Latitude: " + location.getLatitude());

        Response.Listener<String> responseListener = new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonResponse = new JSONObject(response);
                    boolean success = jsonResponse.getBoolean("success");
                    if (success) {
                        Intent intent = new Intent(MainActivity.this, ServerUpload.class);
                        MainActivity.this.startActivity(intent);
                    } else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setMessage("Upload failed")
                                .setNegativeButton("Retry", null)
                                .create()
                                .show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };

        ServerUpload registerRequest = new ServerUpload(latitude,longitude,responseListener);
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        queue.add(registerRequest);

    }

    public void onStatusChanged(String s,int i,Bundle bundle)
    {}

    public void onProviderEnabled(String s)
    {}

    public void onProviderDisabled(String s)
    {}
}

This is my ServerUpload class

package com.example.john.bustrackgps;

import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;

public class ServerUpload extends StringRequest {
    private static final String REGISTER_REQUEST_URL = "http://192.168.169.2/serverfiles/bts.php";
    private Map<String, String> params;

    public ServerUpload(TextView latitude, TextView longitude, Response.Listener<String> listener){

        super(Method.POST, REGISTER_REQUEST_URL, listener, null);

        final String latitude1 =latitude.toString();
        final String longitude1 =longitude.toString();
        params = new HashMap<>();
        params.put("latitude", latitude1);
        params.put("longitude", longitude1);
    }

    @Override
    public Map<String, String> getParams() {
        return params;
    }
}

This is my bts.php code

<?php

$con = mysqli_connect("127.0.0.1", "root", "", "bustrack");

$latitude = $_POST["latitude"];

$longitude = $_POST["longitude"];

$statement = mysqli_prepare($con, "INSERT INTO updates (latitude, longitude) VALUES (?, ?)");

mysqli_stmt_bind_param($statement, "ss", $latitude, $longitude);

mysqli_stmt_execute($statement);

$response = array();

$response["success"] = true;

echo json_encode($response);

The problem is that data does not get entered into the database. Its either 0,0 or "android.extends...."

I am very new to android and not sure were the problem is. Any help would be appreciated!!!

Body:
Fix this bug in your ServerUpload method .

 final String latitude1 =latitude.getText().toString();
final String longitude1 =longitude.getText().toString();

Try this

 public ServerUpload(TextView latitude, TextView longitude, Response.Listener<String> listener){

    super(Method.POST, REGISTER_REQUEST_URL, listener, null);

    final String latitude1 =latitude.getText().toString();
    final String longitude1 =longitude.getText().toString();
    params = new HashMap<>();
    params.put("latitude", latitude1);
    params.put("longitude", longitude1);
}


问:
How to reduce time of algorithm execution
I have to wirte an algorithm, which finding two nearest points on earth. I wrote the code below and it works for my tests, but the time of execution is too long. I tried to modify the code, but it didn't help. Maybe someone will have an idea what should I do?

```<code>struct Points
{
    std::string key;
    double latitude;
    char latSign;
    double longitude;
    char longSign;
};

typedef std::pair<std::pair<std::string, std::string>, double> myType;

double toFraction(short deegres, short minutes)
{
    return (double)deegres + (minutes / 60.0);
}

double orthodroma(const Points &a, const Points &b)
{
    double radian = M_PI / 180;
    return acos((cos((90 - a.latitude) * radian) *
                 cos((90 - b.latitude) * radian)) +
                (sin((90 - a.latitude) * radian) *
                 sin((90 - b.latitude) * radian) *
                 cos((a.longitude - b.longitude) * radian))) *
           (180 / M_PI);
}

bool sortByLatitude(const Points &a, const Points &b)
{
    return a.latitude > b.latitude;
}

myType bruteForce(const std::vector<Points> &vec, int begin, int n)
{
    myType result;
    double min = 1000000;
    int _i, _j;
    if(n > 300)
    {
    }
    for(int i = begin; i < (n + begin) - 1; i++)
    {
        for(int j = i + 1; j < n + begin; j++)
        {
            double tmp;
            tmp = orthodroma(vec[i], vec[j]);
            if(tmp < min)
            {
                min = tmp;
                _i = i;
                _j = j;
            }
        }
    }
    result.first.first = vec[_i].key;
    result.first.second = vec[_j].key;
    result.second = min;
    return result;
}

myType divideAndConquer(std::vector<Points> &vec, int begin, int n)
{
    if(n <= 3)
    {
        return bruteForce(vec, begin, n);
    }
    std::sort(vec.begin(), vec.end(), sortByLatitude);
    int middle = n / 2;
    Points point = vec[middle];
    myType left = divideAndConquer(vec, begin, middle);
    myType right = divideAndConquer(vec, middle, (n - middle));
    bool which;
    double minDist = std::min(left.second, right.second);
    if(left.second < right.second)
        which = false;
    else
        which = true;
    std::vector<Points> arr;
    for(int i = 0; i < n; i++)
    {
        if(abs(vec[i].latitude - point.latitude) < minDist)
        {
            arr.push_back(vec[i]);
        }
    }
    int size = arr.size();
    if(size < 2)
    {
        if(which)
            return right;
        else
            return left;
    }
    else
    {
        myType one = bruteForce(arr, 0, size);
        if(which)
        {
            if(one.second < right.second)
                return one;
            else
                return right;
        }
        else
        {
            if(one.second < left.second)
                return one;
            else
                return left;
        }
    }
}
</code>```

PS. I have to use divide an conquer method.

答:
A few ideas that might improve the performance a little bit:

sort the array only once (before the first recursive call to the divide and conquer method).

when adding points into the arr vector, you can start from the middle position, first moving forward, and afterwards moving backward. The advantage is that you can break each of these loops as soon as one point is far enough from the middle point. Since the array is sorted by latitude, it is guaranteed that the rest of the points will be outside the desired range.

you can pass an additional parameter to the divideAndConquer method, representing the minimum distance known so far. This can lead to smaller arr arrays, quicker to process. Currently, it might be the case that we get a very small distance for the left sub-array. However, when solving the right sub-array, the recursive calls currently have no information about that small distance already found.

Body:
I have to wirte an algorithm, which finding two nearest points on earth. I wrote the code below and it works for my tests, but the time of execution is too long. I tried to modify the code, but it didn't help. Maybe someone will have an idea what should I do?

struct Points
{
    std::string key;
    double latitude;
    char latSign;
    double longitude;
    char longSign;
};

typedef std::pair<std::pair<std::string, std::string>, double> myType;

double toFraction(short deegres, short minutes)
{
    return (double)deegres + (minutes / 60.0);
}

double orthodroma(const Points &a, const Points &b)
{
    double radian = M_PI / 180;
    return acos((cos((90 - a.latitude) * radian) *
                 cos((90 - b.latitude) * radian)) +
                (sin((90 - a.latitude) * radian) *
                 sin((90 - b.latitude) * radian) *
                 cos((a.longitude - b.longitude) * radian))) *
           (180 / M_PI);
}

bool sortByLatitude(const Points &a, const Points &b)
{
    return a.latitude > b.latitude;
}

myType bruteForce(const std::vector<Points> &vec, int begin, int n)
{
    myType result;
    double min = 1000000;
    int _i, _j;
    if(n > 300)
    {
    }
    for(int i = begin; i < (n + begin) - 1; i++)
    {
        for(int j = i + 1; j < n + begin; j++)
        {
            double tmp;
            tmp = orthodroma(vec[i], vec[j]);
            if(tmp < min)
            {
                min = tmp;
                _i = i;
                _j = j;
            }
        }
    }
    result.first.first = vec[_i].key;
    result.first.second = vec[_j].key;
    result.second = min;
    return result;
}

myType divideAndConquer(std::vector<Points> &vec, int begin, int n)
{
    if(n <= 3)
    {
        return bruteForce(vec, begin, n);
    }
    std::sort(vec.begin(), vec.end(), sortByLatitude);
    int middle = n / 2;
    Points point = vec[middle];
    myType left = divideAndConquer(vec, begin, middle);
    myType right = divideAndConquer(vec, middle, (n - middle));
    bool which;
    double minDist = std::min(left.second, right.second);
    if(left.second < right.second)
        which = false;
    else
        which = true;
    std::vector<Points> arr;
    for(int i = 0; i < n; i++)
    {
        if(abs(vec[i].latitude - point.latitude) < minDist)
        {
            arr.push_back(vec[i]);
        }
    }
    int size = arr.size();
    if(size < 2)
    {
        if(which)
            return right;
        else
            return left;
    }
    else
    {
        myType one = bruteForce(arr, 0, size);
        if(which)
        {
            if(one.second < right.second)
                return one;
            else
                return right;
        }
        else
        {
            if(one.second < left.second)
                return one;
            else
                return left;
        }
    }
}

PS. I have to use divide an conquer method.


问:
How can I get vc++ and g++ to behave the same regarding typename for dependent qualified types?
Is there a switch I can supply to cl.exe that will enable a warning or error when a typename is missing from a qualified dependent type?

I'm working in an environment where developers tend to work one one platform, either Windows or Linux, and the code is ultimately built on both platforms nightly.  We've encountered a problem with people forgetting to use typename on qualified dependent types on Windows, where Visual C++ 2008 will automatically insert a missing typename if possible.  When they check in the code like this, it breaks the build on Linux, where g++ requires the typename.  It would be desirable to tweak the Makefile such that we can expect the same typename behaviour on Windows and Linux to mitigate the likelihood of the build breaking.  I prefer the g++ behaviour, but anything that would help the two platforms behave the same would be much appreciated.

See also Why do I need to use typedef typename in g++ but not VS?

答:
There is no check like this in Visual Studio 2005 or 2008. The reason behind this is the compiler internals (the way templates are processed) are different between VS and GCC, and VS does much less processing until templates are instantiated. Pretty much everything seems to be explained in the question you have linked.

I think you may consider this a Visual Studio bug.

I am not sure what the status of this is in VS 2010 - I did not test it yet.

ContentLicense: CC BY-SA 2.5


问:
nodejs route.get to SEND a post request
The get to this route works fine.

But how do I take my route.get() and make it do a post?
If the post is written in jquery, or express, or something else I don't care.  Below I just used the jquery as an example.

```<code>router.get('/', function (req, res, next) {
    var url = 'blabla'
    $.post('anotherBlaBla'
        , { app: url }
    );
});
</code>```

答:
You can use http client axios

Performing a POST request

```<code> var axios = require('axios');

 axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
 })
 .then(function (response) {
    console.log(response);
 })
 .catch(function (error) {
    console.log(error);
 });
</code>```

Title: nodejs route.get to SEND a post request

Body:
The get to this route works fine.

But how do I take my route.get() and make it do a post?
If the post is written in jquery, or express, or something else I don't care.  Below I just used the jquery as an example.

router.get('/', function (req, res, next) {
    var url = 'blabla'
    $.post('anotherBlaBla'
        , { app: url }
    );
});

Body:
You can use http client axios

Performing a POST request

 var axios = require('axios');

 axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
 })
 .then(function (response) {
    console.log(response);
 })
 .catch(function (error) {
    console.log(error);
 });


问:
Twilio 30005 (Error: 30005) Unknown destination handset
I'm doing a simple integration of Twilio to send an outbound text with our App download links when user fills in his/her phone number.

I have verified my phone number on the trial account and am using this one to receive the message on.

When I trigger it on my website I see it in the logs but with error message 30005 even though this is the exact same number as the one I validated as "verified number".

Am I missing something here?

Simple call:

```<code>def send_sms(number)
  provided_number = ENV['provided_twilio_number']
  @client = Twilio::REST::Client.new ENV['my_code'] ENV['my_key']

  message = @client.account.messages.create(
    :from => provided_number,
    :to => number,
    :body => "my message"
  )
end
</code>```

The output of 'number' is an exact match of what is displayed in my verified caller ID's.

答:
Even though my phone number is correct when I tried with a colleagues number it worked just fine. Very strange that twilio thinks this is a faulty number even though they can verify it just fine.
So trying with another number, not changing anything in code and it works ..</p>

Body:
I'm doing a simple integration of Twilio to send an outbound text with our App download links when user fills in his/her phone number.

I have verified my phone number on the trial account and am using this one to receive the message on.

When I trigger it on my website I see it in the logs but with error message 30005 even though this is the exact same number as the one I validated as "verified number".

Am I missing something here?

Simple call:

def send_sms(number)
  provided_number = ENV['provided_twilio_number']
  @client = Twilio::REST::Client.new ENV['my_code'] ENV['my_key']

  message = @client.account.messages.create(
    :from => provided_number,
    :to => number,
    :body => "my message"
  )
end

The output of 'number' is an exact match of what is displayed in my verified caller ID's.


问:
onClick is not working in chrome?
I have a slider menu which I want by clicking on that another page loaded. in firefox its works but I want to works my HTML in any browsers? could you please help me? thanks.

index.html:

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>
<div >
    <a href="#" id="link1" >Vertical link 1</a>
</div>
<div id="content"></div>
<script>
    $("#link1").on("click", function () {
    $("#content").load("test.html");
    });
</script>
</body>
</html>
</code>```

test.html:

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<div>
    <table>
        <thead>
            <tr>
                <th scope="col">A</th>
                <th scope="col">B</th>
                <th scope="col">C</th>
                <th scope="col">D</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>2</td>
                <td>3</td>
                <td>4</td>
            </tr>
        </tbody>
    </table>
</div>
</body>
</html>
</code>```

答:
I think this has to work!</p>

```<code><div class="wrapper">
    <a href="#" id="link1" >Vertical link 1</a>
    <a href="#" id="link2" >Vertical link 2</a>
    <a href="#" id="link3" >Vertical link 3</a>
    <a href="#" id="link4" >Vertical link 4</a>
</div>
<div id="content"></div>

<script>
    $('document').ready(function () {
       $('.wrapper').children().on('click', function (e) {
          e.preventDefault();
          $('#content').load($(this).attr('href'));
       });
    });
</script>
</code>```

Title: onClick is not working in chrome?

Body:
I have a slider menu which I want by clicking on that another page loaded. in firefox its works but I want to works my HTML in any browsers? could you please help me? thanks.

index.html:

<!DOCTYPE html>

    <title></title>

    Vertical link 1

test.html:

<!DOCTYPE html>

    <title></title>

                A
                B
                C
                D

                1
                2
                3
                4

Body:
I think this has to work!

<div class="wrapper">
    <a href="#" id="link1" >Vertical link 1</a>
    <a href="#" id="link2" >Vertical link 2</a>
    <a href="#" id="link3" >Vertical link 3</a>
    <a href="#" id="link4" >Vertical link 4</a>
</div>
<div id="content"></div>

<script>
    $('document').ready(function () {
       $('.wrapper').children().on('click', function (e) {
          e.preventDefault();
          $('#content').load($(this).attr('href'));
       });
    });
</script>


问:
WatchKit + Swift 3.1: Cannot override 'handleAction' which has been marked unavailable
Prior to Swift 3.1, the following code did compile and work without any issues:

```<code>import WatchKit
import WatchConnectivity
import Foundation
import UserNotifications

class InterfaceController: WKInterfaceController, WCSessionDelegate {

    override func handleAction(withIdentifier identifier: String?, for notification: UNNotification) {

    // Do something

    }
}
</code>```

However, when compiling in Xcode 8.3 with Swift 3.1 and WatchKit version 3.0, I get the following compiler error:

Cannot override 'handleAction' which has been marked unavailable

Removing override from the code gives another compiler error:

Overriding declaration requires an 'override' keyword

According to the documentation, method handleAction with UNNotification is still a valid non-deprecated method of WKInterfaceController, so the code above should be valid and compilable. Setting the WatchKit version to 3.1 or 3.2 does not change anything.

Any ideas to get this working with Swift 3.1?

答:
With thanks to Nycen, who pushed me to look again at the UNUserNotificationCenterDelegate, I ended up with implementing the UNUserNotificationCenterDelegate in the ExtensionDelegate of my WatchKit project, to handle UNNotifications in the root controller, like this:</p>

```<code>import WatchKit
import UserNotifications

class ExtensionDelegate: NSObject, WKExtensionDelegate, UNUserNotificationCenterDelegate {

    func applicationDidFinishLaunching() {
        UNUserNotificationCenter.current().delegate = self
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        if let controller = WKExtension.shared().rootInterfaceController as? InterfaceController {
            // Call to a custom method in the root interface controller to handle the notification
            controller.handleAction(notification: response.notification)
            completionHandler()
        }
    }
}
</code>```

Body:
Prior to Swift 3.1, the following code did compile and work without any issues:

import WatchKit
import WatchConnectivity
import Foundation
import UserNotifications

class InterfaceController: WKInterfaceController, WCSessionDelegate {

    override func handleAction(withIdentifier identifier: String?, for notification: UNNotification) {

    // Do something

    }
}

However, when compiling in Xcode 8.3 with Swift 3.1 and WatchKit version 3.0, I get the following compiler error:

Cannot override 'handleAction' which has been marked unavailable

Removing override from the code gives another compiler error:

Overriding declaration requires an 'override' keyword

According to the documentation, method handleAction with UNNotification is still a valid non-deprecated method of WKInterfaceController, so the code above should be valid and compilable. Setting the WatchKit version to 3.1 or 3.2 does not change anything.

Any ideas to get this working with Swift 3.1?

Body:
With thanks to Nycen, who pushed me to look again at the UNUserNotificationCenterDelegate, I ended up with implementing the UNUserNotificationCenterDelegate in the ExtensionDelegate of my WatchKit project, to handle UNNotifications in the root controller, like this:

import WatchKit
import UserNotifications

class ExtensionDelegate: NSObject, WKExtensionDelegate, UNUserNotificationCenterDelegate {

    func applicationDidFinishLaunching() {
        UNUserNotificationCenter.current().delegate = self
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        if let controller = WKExtension.shared().rootInterfaceController as? InterfaceController {
            // Call to a custom method in the root interface controller to handle the notification
            controller.handleAction(notification: response.notification)
            completionHandler()
        }
    }
}


问:
ScriptedSandbox64.exe has stopped working when opening word add-in dialog
I'm currently making a Word Web Add-in using Visual Studio 2017 Community Edition (developing on Windows Server 2016 Standard - with RDP).

I need to add a dialog window to my application, because I need a little more screen estate for a part of my application.

So I'm showing a dialog as it's been explained over here:
https://dev.office.com/docs/add-ins/develop/dialog-api-in-office-add-ins

```<code>Office.context.ui.displayDialogAsync(window.location.protocol + '//' + window.location.host + '/TestDialog.html');
</code>```

TestDialog.html:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <title>Test Dialog</title>
    <script src="https://www.promisejs.org/polyfills/promise-7.0.4.min.js"></script>
    <script src="Scripts/jquery-1.9.1.js" type="text/javascript"></script>
    <script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js" type="text/javascript"></script>

    <link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/2.1.0/fabric.min.css">
    <link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/2.1.0/fabric.components.min.css">
</head>
<body>
    Test dialog
</body>
</html>
</code>```

The dialog pops up succesfully, but right after that I get a windows error "ScriptedSandbox64.exe has stopped working". Also, after that, when I execute any code to sync the document, I get the error:

GeneralException: An internal error occured

I suppose this is caused by the crashed ScriptedSandbox.exe.
When I do a console.log() of the exception, and I try to look at the exception information in VisualStudio, I also get the ScriptedSandbox.exe error.

I tried the solution from this stackoverflow issue, but this does help in my case:
ScriptedSandbox64.exe has stopped working - Visual Studio 2015

In the windows event log, I see the following:

When I get the error in Office:

Fault bucket , type 0 Event Name: VisualStudioNonFatalErrors2
  Response: Not available Cab Id: 0 Problem signature: P1:
  ScriptedSandbox64.exe P2: 15.0.26228.9 D15RTWSVC P3:
  VS/ScriptedHost/Dom Version:1.0 P4: Title:Dom Version:1.0 Domain:
  microsoft.com P5: 15.0.26228.0 P6: 58b562f7 P7: res://c:\program files
  (x86)\microsoft visual
  studio\2017\community\common7\ide\commonextensions\microsoft\webclient\diagnostics\toolwindows\vsresources.dll/#23/console/ConsoleMerged.js
  P8: 5938 P9: Target already added: uid0 P10: ScriptedPluginHost
  Attached files: \?\C:\Users\ADMINI~1\AppData\Local\Temp\2\SPE9F38.tmp
  These files may be available here: Analysis symbol:  Rechecking for
  solution: 0 Report Id: 66676cbf-1228-11e7-85c1-d8d385e237a2 Report
  Status: 262144 Hashed bucket:

When I get the error in Visual Studio, upon trying to get the exception information:

Fault bucket 127830074891, type 5 Event Name:
  VisualStudioNonFatalErrors2 Response: Not available Cab Id: 0 Problem
  signature: P1: ScriptedSandbox64.exe P2: 15.0.26228.9 D15RTWSVC P3:
  VS/ScriptedHost/Dom Version:1.0 P4: Title:Dom Version:1.0
  Domain:microsoft.com P5: 15.0.26228.0 P6: 58b562f7 P7:
  res://c:\program files (x86)\microsoft visual
  studio\2017\community\common7\ide\commonextensions\microsoft\webclient\diagnostics\toolwindows\vsresources.dll/#23/console/ConsoleMerged.js
  P8: 3632 P9: Unable to get property 'channel' of undefined or null
  reference P10: ScriptedPluginHost Attached files:
  \?\C:\Users\ADMINI~1\AppData\Local\Temp\2\SPE862B.tmp
  \?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER86C1.tmp.WERInternalMetadata.xml
  These files may be available here:
  C:\ProgramData\Microsoft\Windows\WER\ReportArchive\Critical_ScriptedSandbox6_f7aa31cc56162be295698083cac29769faeb4a7_00000000_17ac8f0e
  Analysis symbol:  Rechecking for solution: 0 Report Id:
  b0b5bb75-1228-11e7-85c1-d8d385e237a2 Report Status: 1 Hashed bucket:
  558ba9ae3c60bfdc002e0f1b9732736d

Does anyone have any idea of what the issue might be, or how I could work around it?

答:
As I suspected, these are indeed 2 seperate issues.

It seems that it's impossible to sync to the document from within an add-in dialog. To fix this, I'm now passing the information back to the main user interface using this code:

```<code>    Office.context.ui.messageParent(JSON.stringify({
        type: 'myCustomType',
        data: myData
    }))
</code>```

The other problem, the message "ScriptedSandbox64.exe has stopped working", it only appears when you're using Visual Studio, not in the published version. I just click it away now.

Body:
I'm currently making a Word Web Add-in using Visual Studio 2017 Community Edition (developing on Windows Server 2016 Standard - with RDP).

I need to add a dialog window to my application, because I need a little more screen estate for a part of my application.

So I'm showing a dialog as it's been explained over here:
https://dev.office.com/docs/add-ins/develop/dialog-api-in-office-add-ins

Office.context.ui.displayDialogAsync(window.location.protocol + '//' + window.location.host + '/TestDialog.html');

TestDialog.html:

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <title>Test Dialog</title>

    <link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/2.1.0/fabric.min.css">
    <link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/2.1.0/fabric.components.min.css">

    Test dialog

The dialog pops up succesfully, but right after that I get a windows error "ScriptedSandbox64.exe has stopped working". Also, after that, when I execute any code to sync the document, I get the error:

GeneralException: An internal error occured

I suppose this is caused by the crashed ScriptedSandbox.exe.
When I do a console.log() of the exception, and I try to look at the exception information in VisualStudio, I also get the ScriptedSandbox.exe error.

I tried the solution from this stackoverflow issue, but this does help in my case:
ScriptedSandbox64.exe has stopped working - Visual Studio 2015

In the windows event log, I see the following:

When I get the error in Office:

Fault bucket , type 0 Event Name: VisualStudioNonFatalErrors2
  Response: Not available Cab Id: 0 Problem signature: P1:
  ScriptedSandbox64.exe P2: 15.0.26228.9 D15RTWSVC P3:
  VS/ScriptedHost/Dom Version:1.0 P4: Title:Dom Version:1.0 Domain:
  microsoft.com P5: 15.0.26228.0 P6: 58b562f7 P7: res://c:\program files
  (x86)\microsoft visual
  studio\2017\community\common7\ide\commonextensions\microsoft\webclient\diagnostics\toolwindows\vsresources.dll/#23/console/ConsoleMerged.js
  P8: 5938 P9: Target already added: uid0 P10: ScriptedPluginHost
  Attached files: \?\C:\Users\ADMINI~1\AppData\Local\Temp\2\SPE9F38.tmp
  These files may be available here: Analysis symbol:  Rechecking for
  solution: 0 Report Id: 66676cbf-1228-11e7-85c1-d8d385e237a2 Report
  Status: 262144 Hashed bucket:

When I get the error in Visual Studio, upon trying to get the exception information:

Fault bucket 127830074891, type 5 Event Name:
  VisualStudioNonFatalErrors2 Response: Not available Cab Id: 0 Problem
  signature: P1: ScriptedSandbox64.exe P2: 15.0.26228.9 D15RTWSVC P3:
  VS/ScriptedHost/Dom Version:1.0 P4: Title:Dom Version:1.0
  Domain:microsoft.com P5: 15.0.26228.0 P6: 58b562f7 P7:
  res://c:\program files (x86)\microsoft visual
  studio\2017\community\common7\ide\commonextensions\microsoft\webclient\diagnostics\toolwindows\vsresources.dll/#23/console/ConsoleMerged.js
  P8: 3632 P9: Unable to get property 'channel' of undefined or null
  reference P10: ScriptedPluginHost Attached files:
  \?\C:\Users\ADMINI~1\AppData\Local\Temp\2\SPE862B.tmp
  \?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER86C1.tmp.WERInternalMetadata.xml
  These files may be available here:
  C:\ProgramData\Microsoft\Windows\WER\ReportArchive\Critical_ScriptedSandbox6_f7aa31cc56162be295698083cac29769faeb4a7_00000000_17ac8f0e
  Analysis symbol:  Rechecking for solution: 0 Report Id:
  b0b5bb75-1228-11e7-85c1-d8d385e237a2 Report Status: 1 Hashed bucket:
  558ba9ae3c60bfdc002e0f1b9732736d

Does anyone have any idea of what the issue might be, or how I could work around it?

Body:
As I suspected, these are indeed 2 seperate issues.

It seems that it's impossible to sync to the document from within an add-in dialog. To fix this, I'm now passing the information back to the main user interface using this code:

    Office.context.ui.messageParent(JSON.stringify({
        type: 'myCustomType',
        data: myData
    }))

The other problem, the message "ScriptedSandbox64.exe has stopped working", it only appears when you're using Visual Studio, not in the published version. I just click it away now.


问:
Angular2 How to switch baseURL between prodmode and test mode
Hi I am currently testing my app in development mode and i have baseURL globally set but now I want to enable production mode and I want to use a different baseURL in production mode and switch two baseURLs between two mode (dev mode and prod mode)

How can I do this?

I am using npm run dev-start command to run dev mode.

答:
It's too easy with angular cli. Firstly, go to your .angular-cli.json file and edit environments;

```<code>"environments": {
     "dev": "environment/environment.ts",
     "prod": "environments/environment.prod.ts",
     "yourCustomEnv": "environments/environment.yourCustomEnv.ts"
}
</code>```

Secondly, add api url as a property in environment.yourCustomEnv.ts file;

```<code>export const environment = {
     production: ...,
     apiUrl: 'youApiUrl'
}
</code>```

Afterwards, use environment variable wherever you want to set the api url;

```<code>import { environment } from 'pathTo/environments/environment';
export class XService {
     apiUrl = environment.apiUrl;
     ...
}
</code>```

Finally, build your application with the following commands;

```<code>ng build --env=yourCustomEnv ...
</code>```

Angular-cli automatically use environment.yourCustomEnv.ts file at every place where you import environment.

By the way, be sure that your all environment variables have same properties.

Body:
It's too easy with angular cli. Firstly, go to your .angular-cli.json file and edit environments;

"environments": {
     "dev": "environment/environment.ts",
     "prod": "environments/environment.prod.ts",
     "yourCustomEnv": "environments/environment.yourCustomEnv.ts"
}

Secondly, add api url as a property in environment.yourCustomEnv.ts file;

export const environment = {
     production: ...,
     apiUrl: 'youApiUrl'
}

Afterwards, use environment variable wherever you want to set the api url;

import { environment } from 'pathTo/environments/environment';
export class XService {
     apiUrl = environment.apiUrl;
     ...
}

Finally, build your application with the following commands;

ng build --env=yourCustomEnv ...

Angular-cli automatically use environment.yourCustomEnv.ts file at every place where you import environment.

By the way, be sure that your all environment variables have same properties.


问:
Update existence record in sql table from excel file
I am developing a web application in which i am importing records from external file i.e Ms Excel to sql server database table i want to check sql table records if it exists update that record otherwise insert new records from excel file
i am using asp.new mvc 5 entity 6
my controller code is:</p>

```<code>public JsonResult UploadExcel(Student student, HttpPostedFileBase FileUpload)
{
    List<string> data = new List<string>();
    if (FileUpload != null)
    {
        if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        {
            string filename = FileUpload.FileName;
            string targetpath = Server.MapPath("~/Doc/");
            FileUpload.SaveAs(targetpath + filename);
            string pathToExcelFile = targetpath + filename;
            var connectionString = "";
            var ds = new DataSet();
            DataTable dtable = ds.Tables["ExcelTable"];
            string sheetName = "Sheet1";
            var excelFile = new ExcelQueryFactory(pathToExcelFile);
            var studentname = from a in excelFile.Worksheet<Student>(sheetName) select a;
            var artistAlbums = from a in excelFile.Worksheet<Student>(sheetName) select a;

            if (filename.EndsWith(".xls"))
            {
                connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", pathToExcelFile);
            }
            else if (filename.EndsWith(".xlsx"))
            {
                connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", pathToExcelFile);
            }
            var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);
            adapter.Fill(ds, "ExcelTable");
            foreach (var a in artistAlbums)
            {
                try
                {
                    if (a.STUDENTNAME != "" && a.COURSEID != null && a.TEACHERID != null && a.PHOTOID != null)
                    {
                        Student TU = new Student();
                        TU.STUDENTID = a.STUDENTID;
                        TU.STUDENTNAME = a.STUDENTNAME;
                        TU.COURSEID = a.COURSEID;
                        TU.TEACHERID = a.TEACHERID;
                        TU.PHOTOID = a.PHOTOID;
                        db.Students.Add(TU);
                        db.SaveChanges();
                    }
                    else
                    {
                        data.Add("<ul>");
                        if (a.STUDENTNAME == "") data.Add("<li> Name is required</li>");
                        if (a.COURSEID == null) data.Add("<li> CourseId is required</li>");
                        if (a.TEACHERID == null) data.Add("<li> TeacherId is required</li>");
                        if (a.PHOTOID == null) data.Add("<li> PhotoId is required</li>");
                        data.Add("</ul>");
                        data.ToArray();
                        return Json(data, JsonRequestBehavior.AllowGet);
                    }
                }
                catch (DbEntityValidationException ex)
                {
                    foreach (var entityValidationErrors in ex.EntityValidationErrors)
                    {

                        foreach (var validationError in entityValidationErrors.ValidationErrors)
                        {

                            Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);

                        }
                    }
                }
            }
            if ((System.IO.File.Exists(pathToExcelFile)))
            {
                System.IO.File.Delete(pathToExcelFile);
            }
            return Json("success", JsonRequestBehavior.AllowGet);
        }
        else
        {
            data.Add("<ul>");
            data.Add("<li>Only Excel file format is allowed</li>");
            data.Add("</ul>");
            data.ToArray();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
    }
    else
    {
        data.Add("<ul>");
        if (FileUpload == null) data.Add("<li>Please choose Excel file</li>");
        data.Add("</ul>");
        data.ToArray();
        return Json(data, JsonRequestBehavior.AllowGet);
    }
}
</code>```

答:
```<code>if (a.STUDENTNAME != "" && a.COURSEID != null && a.TEACHERID != null && a.PHOTOID != null)
{
    var TU = db.Students.FirstOrDefault(p => p.STUDENTID == a.STUDENTID);
    if (TU != null)
    {
        TU.STUDENTNAME = a.STUDENTNAME;
        TU.COURSEID = a.COURSEID;
        TU.TEACHERID = a.TEACHERID;
        TU.PHOTOID = a.PHOTOID;
        db.Students.Update(TU);
    }
    else
    {
        TU = new Student();
        TU.STUDENTID = a.STUDENTID;
        TU.STUDENTNAME = a.STUDENTNAME;
        TU.COURSEID = a.COURSEID;
        TU.TEACHERID = a.TEACHERID;
        TU.PHOTOID = a.PHOTOID;
        db.Students.Add(TU);
    }

    db.SaveChanges();
}
</code>```

Body:
I am developing a web application in which i am importing records from external file i.e Ms Excel to sql server database table i want to check sql table records if it exists update that record otherwise insert new records from excel file
i am using asp.new mvc 5 entity 6
my controller code is:

public JsonResult UploadExcel(Student student, HttpPostedFileBase FileUpload)
{
    List<string> data = new List<string>();
    if (FileUpload != null)
    {
        if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        {
            string filename = FileUpload.FileName;
            string targetpath = Server.MapPath("~/Doc/");
            FileUpload.SaveAs(targetpath + filename);
            string pathToExcelFile = targetpath + filename;
            var connectionString = "";
            var ds = new DataSet();
            DataTable dtable = ds.Tables["ExcelTable"];
            string sheetName = "Sheet1";
            var excelFile = new ExcelQueryFactory(pathToExcelFile);
            var studentname = from a in excelFile.Worksheet<Student>(sheetName) select a;
            var artistAlbums = from a in excelFile.Worksheet<Student>(sheetName) select a;

            if (filename.EndsWith(".xls"))
            {
                connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", pathToExcelFile);
            }
            else if (filename.EndsWith(".xlsx"))
            {
                connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", pathToExcelFile);
            }
            var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);
            adapter.Fill(ds, "ExcelTable");
            foreach (var a in artistAlbums)
            {
                try
                {
                    if (a.STUDENTNAME != "" && a.COURSEID != null && a.TEACHERID != null && a.PHOTOID != null)
                    {
                        Student TU = new Student();
                        TU.STUDENTID = a.STUDENTID;
                        TU.STUDENTNAME = a.STUDENTNAME;
                        TU.COURSEID = a.COURSEID;
                        TU.TEACHERID = a.TEACHERID;
                        TU.PHOTOID = a.PHOTOID;
                        db.Students.Add(TU);
                        db.SaveChanges();
                    }
                    else
                    {
                        data.Add("
");
                        if (a.STUDENTNAME == "") data.Add("
 Name is required
");
                        if (a.COURSEID == null) data.Add("
 CourseId is required
");
                        if (a.TEACHERID == null) data.Add("
 TeacherId is required
");
                        if (a.PHOTOID == null) data.Add("
 PhotoId is required
");
                        data.Add("
");
                        data.ToArray();
                        return Json(data, JsonRequestBehavior.AllowGet);
                    }
                }
                catch (DbEntityValidationException ex)
                {
                    foreach (var entityValidationErrors in ex.EntityValidationErrors)
                    {

                        foreach (var validationError in entityValidationErrors.ValidationErrors)
                        {

                            Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);

                        }
                    }
                }
            }
            if ((System.IO.File.Exists(pathToExcelFile)))
            {
                System.IO.File.Delete(pathToExcelFile);
            }
            return Json("success", JsonRequestBehavior.AllowGet);
        }
        else
        {
            data.Add("
");
            data.Add("
Only Excel file format is allowed
");
            data.Add("
");
            data.ToArray();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
    }
    else
    {
        data.Add("
");
        if (FileUpload == null) data.Add("
Please choose Excel file
");
        data.Add("
");
        data.ToArray();
        return Json(data, JsonRequestBehavior.AllowGet);
    }
}


问:
Custom factorial function not working as expected
Here is a simple factorial calculator. I have called the function factorial with three different arguments to test it. For some reason, the function is not returning the expected values:

```<code>#include <iostream>
using namespace std;

int factorial(int a) {
  int result = 1;
  for (int i = 0; i < a; i++) {
    result *= result + 1;
  }
  return result;
}

int main() {
  cout << factorial(4) << endl; // returns 1806, expected 24
  cout << factorial(5) << endl; // returns 3263442, expected 120
  cout << factorial(6) << endl; // returns -1461943274, expected 720
  return 0;
}
</code>```

答:
I would use a while loop in your function instead of a for loop:

```<code>int factorial(int a)
{
   int result = 1;
   while (a > 0)
   {
      result *= a;
      a--;
    }
  return result;
 }
</code>```

Edit:
One issue with your code is that you are not decreasing i in your for loop: It should be like this:

```<code> int factorial(int a) {
   int result = 1;
   for (int i = a; i > 0; i--)
   }
    result *= i;
   return result;
 }
</code>```

Body:
Here is a simple factorial calculator. I have called the function factorial with three different arguments to test it. For some reason, the function is not returning the expected values:

#include <iostream>
using namespace std;

int factorial(int a) {
  int result = 1;
  for (int i = 0; i < a; i++) {
    result *= result + 1;
  }
  return result;
}

int main() {
  cout << factorial(4) << endl; // returns 1806, expected 24
  cout << factorial(5) << endl; // returns 3263442, expected 120
  cout << factorial(6) << endl; // returns -1461943274, expected 720
  return 0;
}

Body:
I would use a while loop in your function instead of a for loop:

int factorial(int a)
{
   int result = 1;
   while (a > 0)
   {
      result *= a;
      a--;
    }
  return result;
 }

Edit:
One issue with your code is that you are not decreasing i in your for loop: It should be like this:

 int factorial(int a) {
   int result = 1;
   for (int i = a; i > 0; i--)
   }
    result *= i;
   return result;
 }


问:
warning 10 : this expression should have type unit
I'm writing a program in ocaml containing some loops "for", my problem is that for each of these cycles you receive this message: "warning 10 : this expression should have type unit. "

Example :

```<code>    let f q p rho=

       let x = [] in
       if q > p then
          for i=0 to rho do
              x= q :: x
          done;
    x;;
</code>```

this every time I use a cycle "for" ,how can I solve this problem?

答:
This kind of loop is probably best expressed using recursion:

```<code>let f q p rho=
  let rec loop i =
    if i > rho then
      []
    else
      q::(loop (i+1))
   in
   if q > p then
      loop 0
   else
      [];;
</code>```

Or we can make it tail recursive:

```<code>let f q p rho=
  let rec loop i acc =
    if i > rho then
      acc
    else
      loop (i+1) (q::acc)
   in
   if q > p then
      loop 0 []
   else
      [];;
</code>```

Body:
I'm writing a program in ocaml containing some loops "for", my problem is that for each of these cycles you receive this message: "warning 10 : this expression should have type unit. "

Example :

    let f q p rho=

       let x = [] in
       if q > p then
          for i=0 to rho do
              x= q :: x
          done;
    x;;

this every time I use a cycle "for" ,how can I solve this problem?

Body:
This kind of loop is probably best expressed using recursion:

let f q p rho=
  let rec loop i =
    if i > rho then
      []
    else
      q::(loop (i+1))
   in
   if q > p then
      loop 0
   else
      [];;

Or we can make it tail recursive:

let f q p rho=
  let rec loop i acc =
    if i > rho then
      acc
    else
      loop (i+1) (q::acc)
   in
   if q > p then
      loop 0 []
   else
      [];;


问:
Java JDBC types and code snippets
There are four types of JDBC Drivers.

JDBC-ODBC

JDBC-NATIVE

JDBC-NETWORK

PURE JAVA (Without middleware)

My Question is if JDBC-ODBC driver uses:

```<code>Class.forname("sun.jdbc.odbc.JdbcOdbcDriver");
</code>```

Then what can be use for other three driver types..??

答:
There are not "other three drivers", these are driver types. The other JDBC types require a vendor implementation of a JDBC driver. For example for Firebird the driver Jaybird (which I maintain) provides both a type 2 and type 4 implementation to access Firebird. Similarly, Oracle also has a JDBC driver that provides both a type 2 and a type 4 implementation to access Oracle. Most databases provide at least a type 4 driver.

Type 3 drivers are relatively rare (or at least: last time I've seen/used one was +/- 10 years ago), but they involve a driver part and a middleware server.

Note that the type 1 driver sun.jdbc.odbc.JdbcOdbcDriver has been removed from Java 8 and is no longer available.

Title: Java JDBC types and code snippets

Body:
There are four types of JDBC Drivers.

JDBC-ODBC

JDBC-NATIVE

JDBC-NETWORK

PURE JAVA (Without middleware)

My Question is if JDBC-ODBC driver uses:

Class.forname("sun.jdbc.odbc.JdbcOdbcDriver");

Then what can be use for other three driver types..??


问:
Get the value of the lowest array key
I have an array which returns this:

```<code>    Array (
            [122] => value
            [43] => value1
            [654645] => value2
            [34634] => value3
            [3] => value4  // I want this
            [550] => value5
    )
</code>```

How can I return value4 from the lowest key [3], I have read http://php.net/manual/en/array.sorting.php and attempted some of the sort by key examples with no luck.

答:
to get the minimum array count

```<code>array_search(min($array), $array);
</code>```

to get the value of minimum array

```<code>echo $array[array_search(min($array), $array)];
</code>```

Title: Get the value of the lowest array key

Body:
I have an array which returns this:

    Array (
            [122] => value
            [43] => value1
            [654645] => value2
            [34634] => value3
            [3] => value4  // I want this
            [550] => value5
    )

How can I return value4 from the lowest key [3], I have read http://php.net/manual/en/array.sorting.php and attempted some of the sort by key examples with no luck.

Body:
to get the minimum array count

array_search(min($array), $array);

to get the value of minimum array

echo $array[array_search(min($array), $array)];


问:
Slick carousel images not fitting on screen vertically and not centered vertically
I'm using the Slick jquery carousel library to display single images that are lazy loaded.

Images are loading and displaying OK, and they are fitting the screen horizontally and centered horizontally.

The issue I'm having is I cannot get the images to shrink to fit the screen vertically (when they are larger than the screen height) and cannot get them to center vertically (when they are shorter than the screen height.)

Ideally I would like Slick to responsively fit itself to a parent div.

```<code>    $(document).ready(function() {

      $('.image-slider').slick({
        lazyLoad: 'ondemand',
        slidesToShow: 1,
        slidesToScroll: 1,
        initialSlide: 1,
        centerMode: true,
        arrows: false,
        dots: true,
      });

    });
</code>```

I have a JS Fiddle of the code here...
JS Fiddle code

答:
If i got your question right, you want Slick carousel to adapt to the height of the images.

To do that you can edit the Javascript and add this line adaptiveHeight: true

The new JavaScript should look like this:

```<code>$(document).ready(function() {
  $('.image-slider').slick({
    lazyLoad: 'ondemand',
    slidesToShow: 1,
    slidesToScroll: 1,
    initialSlide: 1,
    centerMode: true,
    arrows: false,
    dots: true,
    adaptiveHeight: true //add this line
  });
});
</code>```

Here's the working jsfiddle: http://jsfiddle.net/gfspwcyo/17/

Body:
I'm using the Slick jquery carousel library to display single images that are lazy loaded.

Images are loading and displaying OK, and they are fitting the screen horizontally and centered horizontally.

The issue I'm having is I cannot get the images to shrink to fit the screen vertically (when they are larger than the screen height) and cannot get them to center vertically (when they are shorter than the screen height.)

Ideally I would like Slick to responsively fit itself to a parent div.

    $(document).ready(function() {

      $('.image-slider').slick({
        lazyLoad: 'ondemand',
        slidesToShow: 1,
        slidesToScroll: 1,
        initialSlide: 1,
        centerMode: true,
        arrows: false,
        dots: true,
      });

    });

I have a JS Fiddle of the code here...
JS Fiddle code

Body:
If i got your question right, you want Slick carousel to adapt to the height of the images.

To do that you can edit the Javascript and add this line adaptiveHeight: true

The new JavaScript should look like this:

$(document).ready(function() {
  $('.image-slider').slick({
    lazyLoad: 'ondemand',
    slidesToShow: 1,
    slidesToScroll: 1,
    initialSlide: 1,
    centerMode: true,
    arrows: false,
    dots: true,
    adaptiveHeight: true //add this line
  });
});

Here's the working jsfiddle: http://jsfiddle.net/gfspwcyo/17/


问:
SlideShow with toggle button(auto/step)
I have a problem with my slideshow homework in javascript and css(no jquery or anything else).

This slideshow should have two modes an i)automatic where it shows pictures on its own and a ii)step where i manually change them. The button should change respectively.
Both modes work fine but my toggle button doesn't...

any help appreciated!

Here's my code:

CSS

```<code>   <style type="text/css">
   body { padding-top: 2%; }
   div {border:solid red 1px; width:550px; padding:10px ; text-align:center;}
   textarea {background-color: #ccc;}
   .Slides {display : none; }
   </style>
</code>```

HTML

```<code><form id="form1" name="form1" method = "GET" action="">
    <input type = "text" id="current" name="s" value=""   />
    <input type = "button" value="PREVIOUS" onclick="myClick_previous()" />
    <input type = "button" value="NEXT" onclick="myClick()" />
    <!-- <input type = "button" value="STEP" id="step" onclick="ToggleButton" /> -->
    <button class="controls" id="pause">Pause</button>

</form>
<div id="container" >
simple SLIDE SHOW
    <img id="Slide001" class="Slides" src="slides/Slide001.jpg" />
    <img id="Slide002" class="Slides" src="slides/Slide002.jpg" />
    <img id="Slide003" class="Slides" src="slides/Slide003.jpg" />
    <img id="Slide004" class="Slides" src="slides/Slide004.jpg" />
    <img id="Slide005" class="Slides" src="slides/Slide005.jpg" />
    <img id="Slide006" class="Slides" src="slides/Slide006.jpg" />
    <textarea id="TimeLineInfos" name="TimeLineInfos" rows="4" cols="50" ></textarea>
</div>
</code>```

Javascript

```<code><script>
var currentSlide = 1;
document.getElementById('Slide001').style.display = "inline" ;
document.getElementById('current').value = 'Slide00' + (currentSlide +0);
document.getElementById('TimeLineInfos').value = 'Slide00'+currentSlide + ' : ' + TimeEst() + '\n';

function myClick(){
    var t = TimeEst()
    currentSlide += 1 ;
    if ( currentSlide != 7 ) {
        var currentID  = 'Slide00'+currentSlide ;
        var previousID = 'Slide00'+(currentSlide - 1) ;
    }
    if ( currentSlide == 7 ) {
        currentSlide = 1
        var currentID  = 'Slide001'
        var previousID = 'Slide006'
    }
    document.getElementById(previousID).style.display = "none" ;
    document.getElementById(currentID).style.display = "inline" ;
    document.getElementById('current').value = currentID;
    document.getElementById('TimeLineInfos').value += currentID + ' : ' + t + '\n';
    //sendTimeLine(currentID,t);
    //document.form1.submit();
}

function myClick_previous(){
    var t = TimeEst()
    currentSlide -= 1 ;
    if ( currentSlide != 0 ) {
        var currentID  = 'Slide00'+currentSlide ;
        var previousID = 'Slide00'+(currentSlide + 1) ;
    }
    if ( currentSlide == 0 ) {
        currentSlide = 6
        var currentID  = 'Slide006'
        var previousID = 'Slide001'
    }
    document.getElementById(previousID).style.display = "none" ;
    document.getElementById(currentID).style.display = "inline" ;
    document.getElementById('current').value = currentID;
    document.getElementById('TimeLineInfos').value += currentID + ' : ' + t + '\n';

}

var myIndex = 0;
slide();
var timer;

function slide() {
    var i;
    var x = document.getElementsByClassName("Slides");
    for (i = 0; i < x.length; i++) {
       x[i].style.display = "none";
    }
    myIndex++;
    if (myIndex > x.length) {myIndex = 1}
    x[myIndex-1].style.display = "block";
   timer=setTimeout(slide, 3000); // Change image every 3seconds
}

   //from down here is my problematic code
var playing = true;
var pauseButton = document.getElementById('pause');

function pauseSlideshow(){
    pauseButton.innerHTML = 'Play';
    playing = false;
    clearInterval(timer);
}

function playSlideshow(){
    pauseButton.innerHTML = 'Pause';
    playing = true;
    slideInterval = setInterval(slide,3000);
}

pauseButton.onclick = function(){
    if(playing){ pauseSlideshow(); }
    else{ slide(); }
};

function TimeEst(){
    var d = new Date();
    var t = d.getTime() ;// + "." + d.getMilliseconds();
    return t;
}
</script>
</code>```

答:
I finally found it...the answer was easier than I thought!(I am just posting it in case someone needs it as an example...)

HTML,CSS remains the same,only the Javascript is changed!

Here we go:

```<code><script>
var currentSlide = 1;
var flag=1;
document.getElementById('Slide001').style.display = "inline" ;
document.getElementById('current').value = 'Slide00' + (currentSlide +0);
document.getElementById('TimeLineInfos').value = 'Slide00'+currentSlide + ' : ' + TimeEst() + '\n';

var timer = setInterval(function(){ myClick_next(); }, 3000);
var playing=true;

function toggle()
{
    if(playing==true)
    {
        playing=false;
        clearInterval(timer);
        document.getElementById("STEP").value = "AUTO";
    }
    else
    {
        playing=true;
        timer=setInterval(function(){ myClick_next(); }, 3000);
        document.getElementById("STEP").value = "STEP";
    }
}

document.getElementById("BACK").disabled = true;

function myClick_next(){
    var t = TimeEst()
    currentSlide += 1 ;
    document.getElementById("BACK").disabled = false;
    if ( currentSlide != 7 ) {
        var currentID  = 'Slide00'+currentSlide ;
        var previousID = 'Slide00'+(currentSlide - 1) ;
    }
    if ( currentSlide == 7 ) {
        currentSlide = 1
        var currentID  = 'Slide001'
        var previousID = 'Slide006'
    }
    document.getElementById(previousID).style.display = "none" ;
    document.getElementById(currentID).style.display = "inline" ;
    document.getElementById('current').value = currentID;
    document.getElementById('TimeLineInfos').value += currentID + ' : ' + t + '\n';
    //sendTimeLine(currentID,t);
    //document.form1.submit();
}

function myClick_previous(){
    var t = TimeEst()
    currentSlide -= 1 ;
    if ( currentSlide != 0 ) {
        var currentID  = 'Slide00'+currentSlide ;
        var previousID = 'Slide00'+(currentSlide + 1) ;
    }
    if ( currentSlide == 1 ) {
        document.getElementById("BACK").disabled = true;
        //currentSlide = 6
        //var currentID  = 'Slide006'
        //var previousID = 'Slide001'
    }
    document.getElementById(previousID).style.display = "none" ;
    document.getElementById(currentID).style.display = "inline" ;
    document.getElementById('current').value = currentID;
    document.getElementById('TimeLineInfos').value += currentID + ' : ' + t + '\n';
    //sendTimeLine(currentID,t);
    //document.form1.submit();
}

function TimeEst(){
    var d = new Date();
    var t = d.getTime() ;// + "." + d.getMilliseconds();
    return t;
}

</script>
</code>```

Title: SlideShow with toggle button(auto/step)

Body:
I have a problem with my slideshow homework in javascript and css(no jquery or anything else).

This slideshow should have two modes an i)automatic where it shows pictures on its own and a ii)step where i manually change them. The button should change respectively.
Both modes work fine but my toggle button doesn't...

any help appreciated!

Here's my code:

CSS

HTML

<form id="form1" name="form1" method = "GET" action="">
    <input type = "text" id="current" name="s" value=""   />
    <input type = "button" value="PREVIOUS" onclick="myClick_previous()" />
    <input type = "button" value="NEXT" onclick="myClick()" />

    <button class="controls" id="pause">Pause</button>

</form>

simple SLIDE SHOW

    <textarea id="TimeLineInfos" name="TimeLineInfos" rows="4" cols="50" ></textarea>

Javascript

Body:
I finally found it...the answer was easier than I thought!(I am just posting it in case someone needs it as an example...)

HTML,CSS remains the same,only the Javascript is changed!

Here we go:

<script>
var currentSlide = 1;
var flag=1;
document.getElementById('Slide001').style.display = "inline" ;
document.getElementById('current').value = 'Slide00' + (currentSlide +0);
document.getElementById('TimeLineInfos').value = 'Slide00'+currentSlide + ' : ' + TimeEst() + '\n';

var timer = setInterval(function(){ myClick_next(); }, 3000);
var playing=true;

function toggle()
{
    if(playing==true)
    {
        playing=false;
        clearInterval(timer);
        document.getElementById("STEP").value = "AUTO";
    }
    else
    {
        playing=true;
        timer=setInterval(function(){ myClick_next(); }, 3000);
        document.getElementById("STEP").value = "STEP";
    }
}

document.getElementById("BACK").disabled = true;

function myClick_next(){
    var t = TimeEst()
    currentSlide += 1 ;
    document.getElementById("BACK").disabled = false;
    if ( currentSlide != 7 ) {
        var currentID  = 'Slide00'+currentSlide ;
        var previousID = 'Slide00'+(currentSlide - 1) ;
    }
    if ( currentSlide == 7 ) {
        currentSlide = 1
        var currentID  = 'Slide001'
        var previousID = 'Slide006'
    }
    document.getElementById(previousID).style.display = "none" ;
    document.getElementById(currentID).style.display = "inline" ;
    document.getElementById('current').value = currentID;
    document.getElementById('TimeLineInfos').value += currentID + ' : ' + t + '\n';
    //sendTimeLine(currentID,t);
    //document.form1.submit();
}

function myClick_previous(){
    var t = TimeEst()
    currentSlide -= 1 ;
    if ( currentSlide != 0 ) {
        var currentID  = 'Slide00'+currentSlide ;
        var previousID = 'Slide00'+(currentSlide + 1) ;
    }
    if ( currentSlide == 1 ) {
        document.getElementById("BACK").disabled = true;
        //currentSlide = 6
        //var currentID  = 'Slide006'
        //var previousID = 'Slide001'
    }
    document.getElementById(previousID).style.display = "none" ;
    document.getElementById(currentID).style.display = "inline" ;
    document.getElementById('current').value = currentID;
    document.getElementById('TimeLineInfos').value += currentID + ' : ' + t + '\n';
    //sendTimeLine(currentID,t);
    //document.form1.submit();
}

function TimeEst(){
    var d = new Date();
    var t = d.getTime() ;// + "." + d.getMilliseconds();
    return t;
}

</script>


问:
Rails :include vs. :joins
This is more of a "why do things work this way" question rather than a "I don't know how to do this" question...

So the gospel on pulling associated records that you know you're going to use is to use :include because you'll get a join and avoid a whole bunch of extra queries:

```<code>Post.all(:include => :comments)
</code>```

However when you look at the logs, there's no join happening:

```<code>Post Load (3.7ms)   SELECT * FROM "posts"
Comment Load (0.2ms)   SELECT "comments.*" FROM "comments"
                       WHERE ("comments".post_id IN (1,2,3,4))
                       ORDER BY created_at asc)
</code>```

It is taking a shortcut because it pulls all of the comments at once, but it's still not a join (which is what all the documentation seems to say). The only way I can get a join is to use :joins instead of :include:

```<code>Post.all(:joins => :comments)
</code>```

And the logs show:

```<code>Post Load (6.0ms)  SELECT "posts".* FROM "posts"
                   INNER JOIN "comments" ON "posts".id = "comments".post_id
</code>```

Am I missing something? I have an app with half a dozen associations and on one screen I display data from all of them. Seems like it would be better to have one join-ed query instead of 6 individuals. I know that performance-wise it's not always better to do a join rather than individual queries (in fact if you're going by time spent, it looks like the two individual queries above are faster than the join), but after all the docs I've been reading I'm surprised to see :include not working as advertised.

Maybe Rails is cognizant of the performance issue and doesn't join except in certain cases?

答:
In addition to a performance considerations, there's a functional difference too.
When you join comments, you are asking for posts that have comments- an inner join by default.
When you include comments, you are asking for all posts- an outer join.</p>

Title: Rails :include vs. :joins

Body:
This is more of a "why do things work this way" question rather than a "I don't know how to do this" question...

So the gospel on pulling associated records that you know you're going to use is to use :include because you'll get a join and avoid a whole bunch of extra queries:

Post.all(:include => :comments)

However when you look at the logs, there's no join happening:

Post Load (3.7ms)   SELECT * FROM "posts"
Comment Load (0.2ms)   SELECT "comments.*" FROM "comments"
                       WHERE ("comments".post_id IN (1,2,3,4))
                       ORDER BY created_at asc)

It is taking a shortcut because it pulls all of the comments at once, but it's still not a join (which is what all the documentation seems to say). The only way I can get a join is to use :joins instead of :include:

Post.all(:joins => :comments)

And the logs show:

Post Load (6.0ms)  SELECT "posts".* FROM "posts"
                   INNER JOIN "comments" ON "posts".id = "comments".post_id

Am I missing something? I have an app with half a dozen associations and on one screen I display data from all of them. Seems like it would be better to have one join-ed query instead of 6 individuals. I know that performance-wise it's not always better to do a join rather than individual queries (in fact if you're going by time spent, it looks like the two individual queries above are faster than the join), but after all the docs I've been reading I'm surprised to see :include not working as advertised.

Maybe Rails is cognizant of the performance issue and doesn't join except in certain cases?


问:
GSON & Volley => Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
This error drove me crazy I tried using different kind of Volley requests such as JsonArrayRequest and JsonObjectRequest but no luck !!

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

Here's the JSON response link => http://www.mocky.io/v2/58df83a80f00005922eaf4e1

Here's my model class

```<code> public class Order {

@SerializedName("status")
@Expose
private String status; //status

@SerializedName("total")
@Expose
private float price; //total

@SerializedName("created_at")
@Expose
private Date time;

@SerializedName("line_items")
@Expose
public List<ItemsNum> lineItems = new ArrayList<ItemsNum>();

@SerializedName("sub_orders")
@Expose
public List<OrdersNum> subOrders = new ArrayList<OrdersNum>();

@SerializedName("shipping_address")
@Expose
public CusAddress cusAdress;

@SerializedName("customer")
@Expose
public Customer customer;

public Order(Customer customer, String status, float price, String cusPicURL, String firstName, String lastName, Date time, List<ItemsNum> lineItems, List<OrdersNum> subOrders, CusAddress cusAdress) {
    this.status = status;
    this.price = price;
    this.customer = customer;
    this.time = time;
    this.lineItems = lineItems;
    this.subOrders = subOrders;
    this.cusAdress = cusAdress;
}

public Date getTime() {
    return time;
}

public void setTime(Date time) {
    this.time = time;
}

public List<ItemsNum> getLineItems() {
    return lineItems;
}

public void setLineItems(List<ItemsNum> lineItems) {
    this.lineItems = lineItems;
}

public List<OrdersNum> getSubOrders() {
    return subOrders;
}

public void setSubOrders(List<OrdersNum> subOrders) {
    this.subOrders = subOrders;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public float getPrice() {
    return price;
}

public void setPrice(float price) {
    this.price = price;
}

public CusAddress getCusAdress() {
    return cusAdress;
}

public void setCusAdress(CusAddress cusAdress) {
    this.cusAdress = cusAdress;
}

// //////////// Inner-Classes

public class Customer {

    @SerializedName("avatar_url")
    @Expose
    private String cusPicURL; //avatar_url

    @SerializedName("first_name")
    @Expose
    private String firstName; //first_name

    @SerializedName("last_name")
    @Expose
    private String lastName; //last_name

    public String getCusPicURL() {
        return cusPicURL;
    }

    public void setCusPicURL(String cusPicURL) {
        this.cusPicURL = cusPicURL;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

public class CusAddress {

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @SerializedName("address_1")
    @Expose
    public String address;

    @SerializedName("city")
    @Expose
    public String city;

    @SerializedName("state")
    @Expose
    public String state;

    @SerializedName("country")
    @Expose
    public String country;
}

public class ItemsNum {

    @SerializedName("id")
    @Expose
    public Integer id;
}

public class OrdersNum {

    @SerializedName("id")
    @Expose
    public Integer id;
 }
}
</code>```

My Adapter

```<code>  public class OrdersDataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

public Context context;
private int num;
ArrayList<Order> orders;

public OrdersDataAdapter(ArrayList<Order> orders, Context context) {
    this.orders = orders;

    this.context = context;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_card, parent, false);

    return new NewOrderVH(v);

}

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
    final Order order = this.orders.get(position);
    final NewOrderVH vh1 = (NewOrderVH) holder;
    vh1.setData(orders.get(position));

}

@Override
public int getItemCount() {
    return orders.size();
}

public class NewOrderVH extends RecyclerView.ViewHolder {

    private ImageView cusPic;
    private TextView cusName;
    private TextView CusAdress;
    private TextView vendorsNum;
    private TextView itemsNum;
    private TextView time;

    public NewOrderVH(View itemView) {
        super(itemView);

        orderCard = (CardView) itemView.findViewById(R.id.OrderCard);
        cusPic = (ImageView) itemView.findViewById(R.id.cusPic);
        cusName = (TextView) itemView.findViewById(R.id.cusName);
        CusAdress = (TextView) itemView.findViewById(R.id.CusAdress);
        vendorsNum = (TextView) itemView.findViewById(R.id.vendorsNum);
        itemsNum = (TextView) itemView.findViewById(R.id.itemsNum);
        time = (TextView) itemView.findViewById(R.id.time);

    }

    public void setData(final Order data) {

        cusName.setText(data.customer.getFirstName() + "" + data.customer.getLastName());
        Picasso.with(context).load(data.customer.getCusPicURL()).into(cusPic);
        time.setText(data.getTime().getMinutes());
        vendorsNum.setText(data.getSubOrders().size());
        itemsNum.setText(data.getLineItems().size());
        CusAdress.setText(data.cusAdress.getAddress() + "" + data.cusAdress.getCity() + "" + data.cusAdress.getCountry() + "" + data.cusAdress.getState());

    }

}
</code>```

}

Request Method inside a Fragment

```<code>private void fetchPosts() {

    requestQueue = Volley.newRequestQueue(getActivity());

    StringRequest jRequest = new StringRequest(Request.Method.GET, ENDPOINT, onPostsLoaded, onPostsError);

    requestQueue.add(jRequest);

}

private final Response.Listener<String> onPostsLoaded = new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {

        Gson gson = new Gson();
        Type listType = new TypeToken<List<Order>>() {}.getType();
        modelData = gson.fromJson(response, listType);

        adapter = new OrdersDataAdapter((ArrayList<Order>) modelData, getActivity());
        recyclerView.setAdapter(adapter);
        adapter.setMode(Attributes.Mode.Single);

    }
};

private final Response.ErrorListener onPostsError = new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e("PostActivity", error.toString());
    }
};
</code>```

答:
here's the correct answer, I was using wrong type of request..!</p>

```<code>  JsonObjectRequest jsObjRequest = new
  JsonObjectRequest(Request.Method.GET,ENDPOINT,null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    Gson gson = new Gson();
                    Type listType = new TypeToken<List<Order>>() {}.getType();
                    try {

                        List<Order> o = new ArrayList<>();
                        o = gson.fromJson(response.getJSONArray("orders").toString(), listType);
                        if(o != null && !o.isEmpty()){

                            modelData.addAll(o);
                            adapter.notifyDataSetChanged();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

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

                }
            });

    requestQueue.add(jsObjRequest);

}
</code>```

Body:
This error drove me crazy I tried using different kind of Volley requests such as JsonArrayRequest and JsonObjectRequest but no luck !!

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

Here's the JSON response link => http://www.mocky.io/v2/58df83a80f00005922eaf4e1

Here's my model class

 public class Order {

@SerializedName("status")
@Expose
private String status; //status

@SerializedName("total")
@Expose
private float price; //total

@SerializedName("created_at")
@Expose
private Date time;

@SerializedName("line_items")
@Expose
public List<ItemsNum> lineItems = new ArrayList<ItemsNum>();

@SerializedName("sub_orders")
@Expose
public List<OrdersNum> subOrders = new ArrayList<OrdersNum>();

@SerializedName("shipping_address")
@Expose
public CusAddress cusAdress;

@SerializedName("customer")
@Expose
public Customer customer;

public Order(Customer customer, String status, float price, String cusPicURL, String firstName, String lastName, Date time, List<ItemsNum> lineItems, List<OrdersNum> subOrders, CusAddress cusAdress) {
    this.status = status;
    this.price = price;
    this.customer = customer;
    this.time = time;
    this.lineItems = lineItems;
    this.subOrders = subOrders;
    this.cusAdress = cusAdress;
}

public Date getTime() {
    return time;
}

public void setTime(Date time) {
    this.time = time;
}

public List<ItemsNum> getLineItems() {
    return lineItems;
}

public void setLineItems(List<ItemsNum> lineItems) {
    this.lineItems = lineItems;
}

public List<OrdersNum> getSubOrders() {
    return subOrders;
}

public void setSubOrders(List<OrdersNum> subOrders) {
    this.subOrders = subOrders;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public float getPrice() {
    return price;
}

public void setPrice(float price) {
    this.price = price;
}

public CusAddress getCusAdress() {
    return cusAdress;
}

public void setCusAdress(CusAddress cusAdress) {
    this.cusAdress = cusAdress;
}

// //////////// Inner-Classes

public class Customer {

    @SerializedName("avatar_url")
    @Expose
    private String cusPicURL; //avatar_url

    @SerializedName("first_name")
    @Expose
    private String firstName; //first_name

    @SerializedName("last_name")
    @Expose
    private String lastName; //last_name

    public String getCusPicURL() {
        return cusPicURL;
    }

    public void setCusPicURL(String cusPicURL) {
        this.cusPicURL = cusPicURL;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

public class CusAddress {

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @SerializedName("address_1")
    @Expose
    public String address;

    @SerializedName("city")
    @Expose
    public String city;

    @SerializedName("state")
    @Expose
    public String state;

    @SerializedName("country")
    @Expose
    public String country;
}

public class ItemsNum {

    @SerializedName("id")
    @Expose
    public Integer id;
}

public class OrdersNum {

    @SerializedName("id")
    @Expose
    public Integer id;
 }
}

My Adapter

  public class OrdersDataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

public Context context;
private int num;
ArrayList<Order> orders;

public OrdersDataAdapter(ArrayList<Order> orders, Context context) {
    this.orders = orders;

    this.context = context;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_card, parent, false);

    return new NewOrderVH(v);

}

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
    final Order order = this.orders.get(position);
    final NewOrderVH vh1 = (NewOrderVH) holder;
    vh1.setData(orders.get(position));

}

@Override
public int getItemCount() {
    return orders.size();
}

public class NewOrderVH extends RecyclerView.ViewHolder {

    private ImageView cusPic;
    private TextView cusName;
    private TextView CusAdress;
    private TextView vendorsNum;
    private TextView itemsNum;
    private TextView time;

    public NewOrderVH(View itemView) {
        super(itemView);

        orderCard = (CardView) itemView.findViewById(R.id.OrderCard);
        cusPic = (ImageView) itemView.findViewById(R.id.cusPic);
        cusName = (TextView) itemView.findViewById(R.id.cusName);
        CusAdress = (TextView) itemView.findViewById(R.id.CusAdress);
        vendorsNum = (TextView) itemView.findViewById(R.id.vendorsNum);
        itemsNum = (TextView) itemView.findViewById(R.id.itemsNum);
        time = (TextView) itemView.findViewById(R.id.time);

    }

    public void setData(final Order data) {

        cusName.setText(data.customer.getFirstName() + "" + data.customer.getLastName());
        Picasso.with(context).load(data.customer.getCusPicURL()).into(cusPic);
        time.setText(data.getTime().getMinutes());
        vendorsNum.setText(data.getSubOrders().size());
        itemsNum.setText(data.getLineItems().size());
        CusAdress.setText(data.cusAdress.getAddress() + "" + data.cusAdress.getCity() + "" + data.cusAdress.getCountry() + "" + data.cusAdress.getState());

    }

}

}

Request Method inside a Fragment

private void fetchPosts() {

    requestQueue = Volley.newRequestQueue(getActivity());

    StringRequest jRequest = new StringRequest(Request.Method.GET, ENDPOINT, onPostsLoaded, onPostsError);

    requestQueue.add(jRequest);

}

private final Response.Listener<String> onPostsLoaded = new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {

        Gson gson = new Gson();
        Type listType = new TypeToken<List<Order>>() {}.getType();
        modelData = gson.fromJson(response, listType);

        adapter = new OrdersDataAdapter((ArrayList<Order>) modelData, getActivity());
        recyclerView.setAdapter(adapter);
        adapter.setMode(Attributes.Mode.Single);

    }
};

private final Response.ErrorListener onPostsError = new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e("PostActivity", error.toString());
    }
};

Body:
here's the correct answer, I was using wrong type of request..!

  JsonObjectRequest jsObjRequest = new
  JsonObjectRequest(Request.Method.GET,ENDPOINT,null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    Gson gson = new Gson();
                    Type listType = new TypeToken<List<Order>>() {}.getType();
                    try {

                        List<Order> o = new ArrayList<>();
                        o = gson.fromJson(response.getJSONArray("orders").toString(), listType);
                        if(o != null && !o.isEmpty()){

                            modelData.addAll(o);
                            adapter.notifyDataSetChanged();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

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

                }
            });

    requestQueue.add(jsObjRequest);

}


问:
Sharetribe: Change "Minimal Order (quantity)" to "Minimal Order"
In views app/views/listings/show.haml, I have this code:

```<code>- if @listing.price
  .row
    .col-12
      .listing-price
        %span.listing-price-amount
          = humanized_money_with_symbol(@listing.price).upcase
        - with_quantity_text(@current_community, @listing) do |text|
          %span.listing-price-quantity
            = text
</code>```

On the product show page, it displays the text:

Minimal Order (quantity)

How can I change this text to just "Minimal Order"?

答:
Depending on how much you've customised Sharetribe, you should find this string in /config/locales/en.yml under the key listings.show.price.per_quantity_unit.

with_quantity_text ends up here, and uses I18n to grab the string. YMMV if you've customised any of the helpers here though.

Body:
In views app/views/listings/show.haml, I have this code:

- if @listing.price
  .row
    .col-12
      .listing-price
        %span.listing-price-amount
          = humanized_money_with_symbol(@listing.price).upcase
        - with_quantity_text(@current_community, @listing) do |text|
          %span.listing-price-quantity
            = text

On the product show page, it displays the text:

Minimal Order (quantity)

How can I change this text to just "Minimal Order"?