问:
Subtracting min and max values from ListBox to find range
I can't seem to subtract the max from the min does anyone know how I can fix this.

Code:

```<code>Do While (rngNumbers < lstSize - 1)
    rngNumbers += 1
    If CBool(CDbl(lstAverage.Items(CInt(rngNumbers > max)))) Then
        max = CInt(lstAverage.Items(rngNumbers))
    ElseIf CBool(CDbl(lstAverage.Items(CInt(rngNumbers < min)))) Then
        min = CInt(lstAverage.Items(rngNumbers))
    End If
Loop
grdRange = max - min
txtRange.Text = grdRange.ToString
</code>```

答:
That doesn't look like very good code besides but I think that this:

```<code>If CBool(CDbl(lstAverage.Items(CInt(rngNumbers > max)))) Then
</code>```

should be this:

```<code>If CDbl(lstAverage.Items(rngNumbers)) > max Then
</code>```

This is a scenario that is more suited to a For Each loop:

```<code>For Each num As Double In lstAverage.Items
    If num > max Then
        max = num
    ElseIf num < min Then
        min = num
    End If
Next
</code>```

You're using CDbl and CInt in your original code so I don't know whether you're working with Double or Integer values.  I've used Double in that example but it will work the same with Integer if your ListBox contains Integers.  Hopefully it does contain one or the other and not Strings.

Body:
I can't seem to subtract the max from the min does anyone know how I can fix this.

Code:

Do While (rngNumbers < lstSize - 1)
    rngNumbers += 1
    If CBool(CDbl(lstAverage.Items(CInt(rngNumbers > max)))) Then
        max = CInt(lstAverage.Items(rngNumbers))
    ElseIf CBool(CDbl(lstAverage.Items(CInt(rngNumbers < min)))) Then
        min = CInt(lstAverage.Items(rngNumbers))
    End If
Loop
grdRange = max - min
txtRange.Text = grdRange.ToString

Body:
That doesn't look like very good code besides but I think that this:

If CBool(CDbl(lstAverage.Items(CInt(rngNumbers > max)))) Then

should be this:

If CDbl(lstAverage.Items(rngNumbers)) > max Then

This is a scenario that is more suited to a For Each loop:

For Each num As Double In lstAverage.Items
    If num > max Then
        max = num
    ElseIf num < min Then
        min = num
    End If
Next

You're using CDbl and CInt in your original code so I don't know whether you're working with Double or Integer values.  I've used Double in that example but it will work the same with Integer if your ListBox contains Integers.  Hopefully it does contain one or the other and not Strings.


来源: stackexchange

答:
For this you can use a "correlated subquery"

```<code>select
   `date`
  , (select count(*) from yourtable t2
     where t2.`date`>= date_sub(t1.`date - INTERVAL 1 HOUR) and t2.`date` <= t1.`date`
    ) as `count`
from yourtable t1
</code>```

note, if you want to strictly count rows "in the past" use less than, not less than or equal in the query.

ContentLicense: CC BY-SA 3.0

Title: Count rows that have timestamps within past hour of that row

Body:
Trying to find a way to count rows together without grouping them. Because if I group per hour like hour(date) then it just shrinks the result down. Instead I wish to count the row and add any rows to that count that are within the past hour of that row.

Data:

date
-------------------
2017-11-01 03:43:00
2017-11-01 03:45:00
2017-11-04 14:14:00
2017-11-04 15:01:00
2017-11-04 15:08:00
2017-11-04 15:12:00
2017-11-04 15:16:00

Result:

date                    count
-------------------     -------------------
2017-11-01 03:43:00     1
2017-11-01 03:45:00     2
2017-11-04 14:14:00     1
2017-11-04 15:01:00     2
2017-11-04 15:08:00     3
2017-11-04 15:12:00     4
2017-11-04 15:16:00     3

Body:
For this you can use a "correlated subquery"

select
   `date`
  , (select count(*) from yourtable t2
     where t2.`date`>= date_sub(t1.`date - INTERVAL 1 HOUR) and t2.`date` <= t1.`date`
    ) as `count`
from yourtable t1

note, if you want to strictly count rows "in the past" use less than, not less than or equal in the query.


问:
Currency Mask jqgrid
I am new to jqGrid, and having trouble with achieving a couple of tasks. Any guidance will be a huge help.

Issue1# I need to perform following jquery masking on my rate field in the create form,

$('#Rate').priceFormat({ prefix: '', thousandsSeparator: '' }); How could I achieve this in jqGrid?

Thanks a lot.

This is what I have right now:

```<code>JQGridColumn RATEColumn = CapitationsGrid.Columns.Find(c => c.DataField == "RATE");
            RATEColumn.Editable = true;
            RATEColumn.EditType = EditType.TextBox;
            RATEColumn.EditDialogLabel = "Rate";
            RATEColumn.DataType = typeof(float);
            RATEColumn.EditClientSideValidators.Add(new RequiredValidator());
            RATEColumn.EditClientSideValidators.Add(new NumberValidator());
            RATEColumn.Formatter = new CurrencyFormatter
            {
                DecimalPlaces = 1,
                DecimalSeparator = ".",
                Prefix = "$",
                Suffix = " USD",
                ThousandsSeparator = ","
            };
</code>```

答:
This covers your problem. Have a look.

```<code>name: 'Currency',

width: 75,

formatter: 'currency',

formatoptions: { decimalSeparator: '.', decimalPlaces: 1, suffix: ' USD', thousandsSeparator: ',', prefix: '$' }
</code>```

http://www.guriddo.net/demo/guriddojs/functionality/formatters_built_in/index.html

Title: Currency Mask jqgrid

Body:
I am new to jqGrid, and having trouble with achieving a couple of tasks. Any guidance will be a huge help.

Issue1# I need to perform following jquery masking on my rate field in the create form,

$('#Rate').priceFormat({ prefix: '', thousandsSeparator: '' }); How could I achieve this in jqGrid?

Thanks a lot.

This is what I have right now:

JQGridColumn RATEColumn = CapitationsGrid.Columns.Find(c => c.DataField == "RATE");
            RATEColumn.Editable = true;
            RATEColumn.EditType = EditType.TextBox;
            RATEColumn.EditDialogLabel = "Rate";
            RATEColumn.DataType = typeof(float);
            RATEColumn.EditClientSideValidators.Add(new RequiredValidator());
            RATEColumn.EditClientSideValidators.Add(new NumberValidator());
            RATEColumn.Formatter = new CurrencyFormatter
            {
                DecimalPlaces = 1,
                DecimalSeparator = ".",
                Prefix = "$",
                Suffix = " USD",
                ThousandsSeparator = ","
            };

Body:
This covers your problem. Have a look.

name: 'Currency',

width: 75,

formatter: 'currency',

formatoptions: { decimalSeparator: '.', decimalPlaces: 1, suffix: ' USD', thousandsSeparator: ',', prefix: '$' }

http://www.guriddo.net/demo/guriddojs/functionality/formatters_built_in/index.html


问:
How can i write SQL search name?
how can i write SQL to search name in database? Example name : Brul Nol
Note: I can search Brul Nol or Nol Brul and then i get the same result </p>

答:
You can achieve using LIKE operator, like wise
For search

select Name from TABLE_NAME where Name like 'Brul%'
[Finds any values that starts with "Brul"]

select Name from TABLE_NAME where Name like '%nol'
[Finds any values that ends with "nol"]

select Name from TABLE_NAME where Name like 'Brul%nol'
[Finds any values that starts with "Brul" and ends with "nol"]

Title: How can i write SQL search name?


问:
BLE scan timeout in iOS app
I am having an app in which I start and perform a BLE scan. Every thing is fine. I just want to know that is there a feature for creating a timeout for the scanning process.
So that if BLE scan cannot find any device for a certain period of time, I can show an alert or popup to the user.

Any suggestions are appreciated.

答:
swift 3

```<code>var timer: Timer!
var countTime: Int = 0
var bleCentralManager: CBCentralManager!

override func viewWillAppear(_ animated: Bool) {

    self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateScanningStatus), userInfo: nil, repeats: true)
}

func updateScanningStatus(){

    if self.count >= 60{

        bleCentralManager.stopScan()

        timer.invalidate()

        timer = nil
    } else {
        count += 1
    }
}
</code>```

after 1 min BLE scanning is stop.

Title: BLE scan timeout in iOS app

Body:
swift 3

var timer: Timer!
var countTime: Int = 0
var bleCentralManager: CBCentralManager!

override func viewWillAppear(_ animated: Bool) {

    self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateScanningStatus), userInfo: nil, repeats: true)
}

func updateScanningStatus(){

    if self.count >= 60{

        bleCentralManager.stopScan()

        timer.invalidate()

        timer = nil
    } else {
        count += 1
    }
}

after 1 min BLE scanning is stop.

ContentLicense: CC BY-SA 4.0


问:
Rails: Where to define a helper method that will be available to several controllers?
I would like to define a helper method, my_method, that will be available inside BuyersController methods (like index, create, e.t.c.).

I tried to define it in app/helpers/application_helper.rb but it didn't work:

```<code>undefined method `my_method' for #<BuyersController:0x26df468>
</code>```

It should be in some shared place because I want to use it in other controllers also. This is why I tried app/helpers/application_helper.rb.

What is the right place to define it ?

答:
It should be in app/controllers/application_controller.rb

The app/helpers/application_helper.rb is for shared view helpers.

ContentLicense: CC BY-SA 2.5

Body:
I would like to define a helper method, my_method, that will be available inside BuyersController methods (like index, create, e.t.c.).

I tried to define it in app/helpers/application_helper.rb but it didn't work:

undefined method `my_method' for #<BuyersController:0x26df468>

It should be in some shared place because I want to use it in other controllers also. This is why I tried app/helpers/application_helper.rb.

What is the right place to define it ?


问:
How to print the numbers separately (comma-seperated) using Python?
I want to print the following numbers in line-by-line in sorted order using Python.

119, 671, 207, 2484, 6, 941, 2138, 806, 1851, 2509, 1264, 701, 2802, 319, 1603, 98, 347, 525, 1521, 269, 1681, 1885, 1731, 2828, 2543, 2011, 720, 2359, 2248, 22, 1637

My code looks likes

```<code>>>> fo = open("cr.txt", "r")
>>> fo1 = fo.readlines()
>>> fo2 = fo1.split(',')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'split'
</code>```

When I was trying to split the numbers using split, it shows the error as list object has no attribute split.

答:
fo.readlines() returns a list of lines.  If your text file only contains one line, then you can use this, which selects the first line in the file.

```<code>fo = open("cr.txt", "r")
fo1 = fo.readlines()[0]
fo2 = fo1.split(',')
</code>```

If your file contain more than one line then use this, which joins all lines together with ',' before splitting all values by comma.

```<code>fo = open("cr.txt", "r")
fo1 = ','.join(fo.readlines())
fo2 = fo1.split(',')
</code>```

Body:
I want to print the following numbers in line-by-line in sorted order using Python.

119, 671, 207, 2484, 6, 941, 2138, 806, 1851, 2509, 1264, 701, 2802, 319, 1603, 98, 347, 525, 1521, 269, 1681, 1885, 1731, 2828, 2543, 2011, 720, 2359, 2248, 22, 1637

My code looks likes

>>> fo = open("cr.txt", "r")
>>> fo1 = fo.readlines()
>>> fo2 = fo1.split(',')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'split'

When I was trying to split the numbers using split, it shows the error as list object has no attribute split.

Body:
fo.readlines() returns a list of lines.  If your text file only contains one line, then you can use this, which selects the first line in the file.

fo = open("cr.txt", "r")
fo1 = fo.readlines()[0]
fo2 = fo1.split(',')

If your file contain more than one line then use this, which joins all lines together with ',' before splitting all values by comma.

fo = open("cr.txt", "r")
fo1 = ','.join(fo.readlines())
fo2 = fo1.split(',')


问:
Reverse for '' with no arguments not found when passing and retrieving parameters between views
Django version: 1.10
Basically, I want users who have logged in to go to the page with their own data.
So, when the user provides login credentials, redirect to some other page bypassing 'pk' so the page will have only data related to that 'pk'.

I have seen other posts in StackOverflow about Reverse for '' with no arguments not found but I don't know why this is not working for me so many insights and solutions are highly appreciated

In urls.py of the main project:

```<code>urlpatterns = [
    url(r'^admin/', admin.site.urls,name='admin'),
    url(r'^basic_app/',include('basic_app.urls',namespace='basic_app')),]
</code>```

And I have an app named basic-app which contains urls.py as

from django.conf.urls import url
from basic_app import views

app_name = 'basic_app'

urlpatterns = [
         url(r'^login/$', views.user_login, name='user_login'),
         url(r'^class/(?P<pk>\d+)/$',views.ClassroomView,name='classroom_list'), ]
```
<p>In views.py, I have a user login view that should send parameters as</p>
<pre class="lang-py prettyprint-override"><code>def user_login(request):

    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user:
            if user.is_active:
                login(request,user)
                # then send the user to Classroom view with 'pk' as parameter
                return redirect(reverse('basic_app:classroom_list'), {'pk': user.id})
</code>```

I should get 'pk' from LoginView in the following ClassroomView:

def ClassroomView(request,pk):

        classroom_list = Classroom.objects\
                            .filter(school__user=User.objects.get(pk=request.session.get('user_id','0')))
        class_dict = {'class_records': classroom_list}
        return render(request, 'basic_app/classroom_list.html', context=class_dict)
```
<p>But, it says</p>
```Reverse for 'classroom_list' with no arguments not found. 1 pattern(s) tried: ['basic_app/class/(?P<pk>\\d+)/$']
```
<p>And, the url shows the following without 'pk'</p>
<p>http://127.0.0.1:8000/basic_app/login/</p>
<p>The problem, I think lies in <strong>return redirect()</strong>. If I just write the following:
<code>return redirect('basic_app:classroom_list', {'pk': user.id})</code></p>
<p>It gives the following error:</p>
```NoReverseMatch at /basic_app/login/
Reverse for 'classroom_list' with arguments '({'pk': 2},)' not found. 1 pattern(s) tried: ['basic_app/class/(?P<pk>\\d+)/$']
```
<p>So, how can I link to the URL below by passing the argument?</p>
<pre class="lang-py prettyprint-override"><code>url(r'^class/(?P<pk>\d+)/$',views.ClassroomView,name='classroom_list')
</code>```

答:
syntax is:

```<code>reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None)
</code>```

so

```<code>return redirect(reverse('basic_app:classroom_list', kwargs={'pk': user.id}))
</code>```

Body:
Django version: 1.10
Basically, I want users who have logged in to go to the page with their own data.
So, when the user provides login credentials, redirect to some other page bypassing 'pk' so the page will have only data related to that 'pk'.

I have seen other posts in StackOverflow about Reverse for '' with no arguments not found but I don't know why this is not working for me so many insights and solutions are highly appreciated

In urls.py of the main project:

urlpatterns = [
    url(r'^admin/', admin.site.urls,name='admin'),
    url(r'^basic_app/',include('basic_app.urls',namespace='basic_app')),]

And I have an app named basic-app which contains urls.py as

from django.conf.urls import url
from basic_app import views

app_name = 'basic_app'

urlpatterns = [
         url(r'^login/$', views.user_login, name='user_login'),
         url(r'^class/(?P<pk>\d+)/$',views.ClassroomView,name='classroom_list'), ]

In views.py, I have a user login view that should send parameters as

def user_login(request):

    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user:
            if user.is_active:
                login(request,user)
                # then send the user to Classroom view with 'pk' as parameter
                return redirect(reverse('basic_app:classroom_list'), {'pk': user.id})

I should get 'pk' from LoginView in the following ClassroomView:

def ClassroomView(request,pk):

        classroom_list = Classroom.objects\
                            .filter(school__user=User.objects.get(pk=request.session.get('user_id','0')))
        class_dict = {'class_records': classroom_list}
        return render(request, 'basic_app/classroom_list.html', context=class_dict)

But, it says

Reverse for 'classroom_list' with no arguments not found. 1 pattern(s) tried: ['basic_app/class/(?P<pk>\\d+)/$']

And, the url shows the following without 'pk'

http://127.0.0.1:8000/basic_app/login/

The problem, I think lies in return redirect(). If I just write the following:
return redirect('basic_app:classroom_list', {'pk': user.id})

It gives the following error:

NoReverseMatch at /basic_app/login/
Reverse for 'classroom_list' with arguments '({'pk': 2},)' not found. 1 pattern(s) tried: ['basic_app/class/(?P<pk>\\d+)/$']

So, how can I link to the URL below by passing the argument?

url(r'^class/(?P<pk>\d+)/$',views.ClassroomView,name='classroom_list')

Body:
syntax is:

reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None)

so

return redirect(reverse('basic_app:classroom_list', kwargs={'pk': user.id}))


问:
Other ways to search a ListView
I am trying to use TextChangedListener to implement search functionality on my ListView. But after adding some character in EditText; the ListView goes blank. I have implemented filter method in my ArrayAdapter class.

I am getting my data from JSON.

My Logcat shows: getSlotFromBufferLocked: unknown buffer

Is there any other way to search ListView?

Here's my code:

UserList.java

```<code>public class UserList extends AppCompatActivity {

private ListView listView;
private ArrayList<MyDataModel> list;
private MyArrayAdapter adapter;
private EditText search;

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

    search = (EditText) findViewById(R.id.search);

    //Array List for Binding Data from JSON to this List
    list = new ArrayList<>();

    //Binding that List to Adapter
    adapter = new MyArrayAdapter(this, list);

    //Getting List and Setting List Adapter
    listView = (ListView) findViewById(R.id.listView);
    listView.setAdapter(adapter);

    listView.setTextFilterEnabled(true);
    search.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            String text = search.getText().toString().toLowerCase(Locale.getDefault());
            adapter.filter(text);
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

    //Checking Internet Connection
    if (InternetConnection.checkConnection(getApplicationContext())) {
        new GetDataTask().execute();
    } else {
        Snackbar.make(findViewById(R.id.parentLayout),"Internet Connection Not Available", Snackbar.LENGTH_LONG).show();
    }
}

//Creating Get Data Task for Getting Data From Web
class GetDataTask extends AsyncTask<Void, Void, Void> {

    ProgressDialog dialog;
    int jIndex;
    int x;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //Progress Dialog for User Interaction
        x=list.size();

        if(x==0)
            jIndex=0;
        else
            jIndex=x;

        dialog = new ProgressDialog(UserList.this);
        dialog.setTitle("Please Wait..."+x);
        dialog.setMessage("Retrieving Data");
        dialog.show();

    }

    @Nullable
    @Override
    protected Void doInBackground(Void... params) {

        //Getting JSON Object from Web Using okHttp
        JSONObject jsonObject = JSONParser.getDataFromWeb();

        try {

            if (jsonObject != null) {

                if(jsonObject.length() > 0) {

                    JSONArray array = jsonObject.getJSONArray(Keys.KEY_CONTACTS);

                    //Check Length of Array...
                    int lenArray = array.length();
                    if(lenArray > 0) {
                        for( ; jIndex < lenArray; jIndex++) {

                            //Creating Every time New Object and adding to List
                            MyDataModel model = new MyDataModel();

                            JSONObject innerObject = array.getJSONObject(jIndex);
                            String name = innerObject.getString(Keys.KEY_NAME);

                            model.setName(name);
                            list.add(model);
                        }
                    }
                }
            } else {

            }
        } catch (JSONException je) {
            Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        dialog.dismiss();

        //Checking if List size if more than zero then update ListView
        if(list.size() > 0) {
            adapter.notifyDataSetChanged();

        } else {
            Snackbar.make(findViewById(R.id.parentLayout), "No Data Found", Snackbar.LENGTH_LONG).show();
        }

    }
}
}
</code>```

I have implemented the filter method in my ArrayAdapter class.

Here's my ArrayAdapter class:

MyArrayAdapter.java

```<code>public class MyArrayAdapter extends ArrayAdapter<MyDataModel> implements Filterable{

List<MyDataModel> modelList;
Context context;
private LayoutInflater mInflater;
private ArrayList<MyDataModel> arrayList;

public MyArrayAdapter(Context context, List<MyDataModel> objects) {
    super(context, 0, objects);
    this.context = context;
    this.mInflater = LayoutInflater.from(context);
    modelList = objects;

    this.arrayList = new ArrayList<MyDataModel>();
    this.arrayList.addAll(modelList);
}

@Override
public MyDataModel getItem(int position) {
    return modelList.get(position);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final ViewHolder vh;
    if (convertView == null) {
        View view = mInflater.inflate(R.layout.layout_row_view, parent, false);
        vh = ViewHolder.create((RelativeLayout) view);
        view.setTag(vh);
    } else {
        vh = (ViewHolder) convertView.getTag();
    }

    MyDataModel item = getItem(position);

    vh.textViewName.setText(item.getName());
    return vh.rootView;
}

private static class ViewHolder {
    public final RelativeLayout rootView;

    public final TextView textViewName;

    private ViewHolder(RelativeLayout rootView, TextView textViewName) {
        this.rootView = rootView;
        this.textViewName = textViewName;
    }

    public static ViewHolder create(RelativeLayout rootView) {
        TextView textViewName = (TextView) rootView.findViewById(R.id.textViewName);
        return new ViewHolder(rootView, textViewName);
    }
}

// Filter Class
public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    modelList.clear();
    if (charText.length() == 0) {
        modelList.addAll(arrayList);
    } else {
        for (MyDataModel wp : arrayList) {
            if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
                modelList.add(wp);
            }
        }
    }
    notifyDataSetChanged();
}
</code>```

答:
Try,

```<code>modelList = new ArrayList<MyDataModel>;
</code>```

Write this line after  modelList.clear();  and check.

Title: Other ways to search a ListView

Body:
I am trying to use TextChangedListener to implement search functionality on my ListView. But after adding some character in EditText; the ListView goes blank. I have implemented filter method in my ArrayAdapter class.

I am getting my data from JSON.

My Logcat shows: getSlotFromBufferLocked: unknown buffer

Is there any other way to search ListView?

Here's my code:

UserList.java

public class UserList extends AppCompatActivity {

private ListView listView;
private ArrayList<MyDataModel> list;
private MyArrayAdapter adapter;
private EditText search;

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

    search = (EditText) findViewById(R.id.search);

    //Array List for Binding Data from JSON to this List
    list = new ArrayList<>();

    //Binding that List to Adapter
    adapter = new MyArrayAdapter(this, list);

    //Getting List and Setting List Adapter
    listView = (ListView) findViewById(R.id.listView);
    listView.setAdapter(adapter);

    listView.setTextFilterEnabled(true);
    search.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            String text = search.getText().toString().toLowerCase(Locale.getDefault());
            adapter.filter(text);
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

    //Checking Internet Connection
    if (InternetConnection.checkConnection(getApplicationContext())) {
        new GetDataTask().execute();
    } else {
        Snackbar.make(findViewById(R.id.parentLayout),"Internet Connection Not Available", Snackbar.LENGTH_LONG).show();
    }
}

//Creating Get Data Task for Getting Data From Web
class GetDataTask extends AsyncTask<Void, Void, Void> {

    ProgressDialog dialog;
    int jIndex;
    int x;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //Progress Dialog for User Interaction
        x=list.size();

        if(x==0)
            jIndex=0;
        else
            jIndex=x;

        dialog = new ProgressDialog(UserList.this);
        dialog.setTitle("Please Wait..."+x);
        dialog.setMessage("Retrieving Data");
        dialog.show();

    }

    @Nullable
    @Override
    protected Void doInBackground(Void... params) {

        //Getting JSON Object from Web Using okHttp
        JSONObject jsonObject = JSONParser.getDataFromWeb();

        try {

            if (jsonObject != null) {

                if(jsonObject.length() > 0) {

                    JSONArray array = jsonObject.getJSONArray(Keys.KEY_CONTACTS);

                    //Check Length of Array...
                    int lenArray = array.length();
                    if(lenArray > 0) {
                        for( ; jIndex < lenArray; jIndex++) {

                            //Creating Every time New Object and adding to List
                            MyDataModel model = new MyDataModel();

                            JSONObject innerObject = array.getJSONObject(jIndex);
                            String name = innerObject.getString(Keys.KEY_NAME);

                            model.setName(name);
                            list.add(model);
                        }
                    }
                }
            } else {

            }
        } catch (JSONException je) {
            Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        dialog.dismiss();

        //Checking if List size if more than zero then update ListView
        if(list.size() > 0) {
            adapter.notifyDataSetChanged();

        } else {
            Snackbar.make(findViewById(R.id.parentLayout), "No Data Found", Snackbar.LENGTH_LONG).show();
        }

    }
}
}

I have implemented the filter method in my ArrayAdapter class.

Here's my ArrayAdapter class:

MyArrayAdapter.java

public class MyArrayAdapter extends ArrayAdapter<MyDataModel> implements Filterable{

List<MyDataModel> modelList;
Context context;
private LayoutInflater mInflater;
private ArrayList<MyDataModel> arrayList;

public MyArrayAdapter(Context context, List<MyDataModel> objects) {
    super(context, 0, objects);
    this.context = context;
    this.mInflater = LayoutInflater.from(context);
    modelList = objects;

    this.arrayList = new ArrayList<MyDataModel>();
    this.arrayList.addAll(modelList);
}

@Override
public MyDataModel getItem(int position) {
    return modelList.get(position);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final ViewHolder vh;
    if (convertView == null) {
        View view = mInflater.inflate(R.layout.layout_row_view, parent, false);
        vh = ViewHolder.create((RelativeLayout) view);
        view.setTag(vh);
    } else {
        vh = (ViewHolder) convertView.getTag();
    }

    MyDataModel item = getItem(position);

    vh.textViewName.setText(item.getName());
    return vh.rootView;
}

private static class ViewHolder {
    public final RelativeLayout rootView;

    public final TextView textViewName;

    private ViewHolder(RelativeLayout rootView, TextView textViewName) {
        this.rootView = rootView;
        this.textViewName = textViewName;
    }

    public static ViewHolder create(RelativeLayout rootView) {
        TextView textViewName = (TextView) rootView.findViewById(R.id.textViewName);
        return new ViewHolder(rootView, textViewName);
    }
}

// Filter Class
public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    modelList.clear();
    if (charText.length() == 0) {
        modelList.addAll(arrayList);
    } else {
        for (MyDataModel wp : arrayList) {
            if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
                modelList.add(wp);
            }
        }
    }
    notifyDataSetChanged();
}

Body:
Try,

modelList = new ArrayList<MyDataModel>;

Write this line after  modelList.clear();  and check.


问:
remove link from the l() function in drupal after the first click
How does one remove the hyperlink from the l() function after the first click. A working example would be helpful.
 My link is of the form

  l(25,$_GET['q'],array('query'=>array("itemcount"=>"25")));

答: You can use a JQuery Plugin called one_time_action to implement this behavior.</p>


问:
Python Selenium, Scraping dynamic drop down
I am using Selenium and python for web scraping and the page that i am using for testing this link

But the problem is i am not able to handle the dynamic content of the drop down, here is the problem arises

While selecting the state, the city is loaded based on the state, Some Php and js are going in the back end as far as i know.

So, i searched the web and came with a solution to wait for the sometime please use this link as reference.

The following is a part of my code

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

chrome_path = r"E:\chromedriver.exe"

driver = webdriver.Chrome(chrome_path)

driver.get("http://www.blooddonors.in")
select = Select(driver.find_element_by_xpath('/html/body/table[3]/tbody/tr/td[2]/table[1]/tbody/tr/td/form/table/tbody/tr[2]/td[1]/select'))

select.select_by_visible_text('Tamil Nadu')
driver.implicitly_wait(60)
drop = Select(driver.find_element_by_xpath('//*[@id="div_city"]/select'))
select.select_by_visible_text('Coimbotore')
</code>```

I am using a windows sys and i tried using CMD. It doesn't need a wait function it works fine without it.

The error that i am facing is:

```<code>raise NoSuchElementException("Could not locate element with visible text: %s" % text)
selenium.common.exceptions.NoSuchElementException: Message: Could not locate element with visible text: Coimbotore
</code>```

But their it is actually their.

If someone can help me resolve the issue it would be great and i can move on to the next.

Thanks

答:
To select Tamilnadu and then select Coimbotore you can use the following code block :

```<code>driver.get("http://www.blooddonors.in")
select = Select(driver.find_element_by_name('select'))
select.select_by_visible_text('Tamil Nadu')
drop = Select(driver.find_element_by_name('city'))
city_option = WebDriverWait(driver, 5).until(lambda x: x.find_element_by_xpath("//select[@name='city']/option[text()='Coimbotore']"))
city_option.click()
</code>```

Body:
I am using Selenium and python for web scraping and the page that i am using for testing this link

But the problem is i am not able to handle the dynamic content of the drop down, here is the problem arises

While selecting the state, the city is loaded based on the state, Some Php and js are going in the back end as far as i know.

So, i searched the web and came with a solution to wait for the sometime please use this link as reference.

The following is a part of my code

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

chrome_path = r"E:\chromedriver.exe"

driver = webdriver.Chrome(chrome_path)

driver.get("http://www.blooddonors.in")
select = Select(driver.find_element_by_xpath('/html/body/table[3]/tbody/tr/td[2]/table[1]/tbody/tr/td/form/table/tbody/tr[2]/td[1]/select'))

select.select_by_visible_text('Tamil Nadu')
driver.implicitly_wait(60)
drop = Select(driver.find_element_by_xpath('//*[@id="div_city"]/select'))
select.select_by_visible_text('Coimbotore')

I am using a windows sys and i tried using CMD. It doesn't need a wait function it works fine without it.

The error that i am facing is:

raise NoSuchElementException("Could not locate element with visible text: %s" % text)
selenium.common.exceptions.NoSuchElementException: Message: Could not locate element with visible text: Coimbotore

But their it is actually their.

If someone can help me resolve the issue it would be great and i can move on to the next.

Thanks

Body:
To select Tamilnadu and then select Coimbotore you can use the following code block :

driver.get("http://www.blooddonors.in")
select = Select(driver.find_element_by_name('select'))
select.select_by_visible_text('Tamil Nadu')
drop = Select(driver.find_element_by_name('city'))
city_option = WebDriverWait(driver, 5).until(lambda x: x.find_element_by_xpath("//select[@name='city']/option[text()='Coimbotore']"))
city_option.click()


问:
How to pass mutliple $scope values in ng-repeat angularjs?
This is my json data:

```<code>{
    "seendata": {
        "count": 2,
        "rows": [
            {
                "id": 8,
                "contactCount": 2,
                "group": {
                    "id": 7,
                    "groupname": "group1",
                    "createdAt": "2017-11-16T10:53:12.000Z",
                    "updatedAt": "2017-11-16T10:53:12.000Z"
                }
            }
        ]
    },
    "alldata": [
        {
            "id": 7,
            "groupname": "group1",
            "createdAt": "2017-11-16T10:53:12.000Z",
            "updatedAt": "2017-11-16T10:53:12.000Z"
        },
        {
            "id": 8,
            "groupname": "group2",
            "createdAt": "2017-11-16T10:54:41.000Z",
            "updatedAt": "2017-11-16T10:54:41.000Z"
        }
    ]
}
</code>```

My api code:

```<code>exports.getNewGroup = function (req, res) {
var globalObj={};
    ContactGroup.findAndCountAll({
        attributes: ['id', [sequelize.fn('COUNT', sequelize.col('group.id')),
            'contactCount'
        ]],
        include: [{
            model: Group,
        }],
    }).then(seenData => { globalObj.seendata=seenData;return Group.findAll();})
    .then(function (data) {
globalObj.alldata=data;
        return res.status(200).send(globalObj);
    }).catch(function (err) {
        return res.status(400).send(err.message);
    });
};
</code>```

And my angular client side controller code:

```<code>$http({
        method: 'GET',
        url: '/api/getnewgroup'
      })
      .then(function (response) {
        $scope.groups = response.data.seendata.rows;
        $scope.alldata = response.data.alldata;
        console.log($scope.groups);
      }, function (response) {
        window.location.href = '/';
      });
</code>```

And my Jade file:

```<code>tr(ng-repeat='group in groups')
 td {{group.groupname}}
 td {{group.contactCount}}
</code>```

I want to display contactCount value as well as i want to display alldata.groupname values in my front end?

Help me!

I am getting {{group.contactCount}} correctly, but i am not getting {{group.groupname}} coming from alldata.groupname

How to get? both values and how to pass multiple scopes and to be used in ng-repeat?

答:
Better take allData in to $scope.alldata = response.data.alldata;

```<code>    $http({
      method: 'GET',
      url: '/api/getnewgroup'
    })
    .then(function (response) {
      $scope.groups = response.data.seendata.rows;
      $scope.allData = response.data.alldata;
      console.log($scope.groups);
    }, function (response) {
      window.location.href = '/';
    });
</code>```

And in your Jade file

```<code><tr ng-repeat='group in groups track by $index'>
  <td>
    <span ng-repeat='data in alldata'>data.groupname</span>
  </td>
  <td>group.contactCount</td>
</tr>
</code>```

With help of rows $index you can fetch the data of allData also. Hope it will work

Body:
This is my json data:

{
    "seendata": {
        "count": 2,
        "rows": [
            {
                "id": 8,
                "contactCount": 2,
                "group": {
                    "id": 7,
                    "groupname": "group1",
                    "createdAt": "2017-11-16T10:53:12.000Z",
                    "updatedAt": "2017-11-16T10:53:12.000Z"
                }
            }
        ]
    },
    "alldata": [
        {
            "id": 7,
            "groupname": "group1",
            "createdAt": "2017-11-16T10:53:12.000Z",
            "updatedAt": "2017-11-16T10:53:12.000Z"
        },
        {
            "id": 8,
            "groupname": "group2",
            "createdAt": "2017-11-16T10:54:41.000Z",
            "updatedAt": "2017-11-16T10:54:41.000Z"
        }
    ]
}

My api code:

exports.getNewGroup = function (req, res) {
var globalObj={};
    ContactGroup.findAndCountAll({
        attributes: ['id', [sequelize.fn('COUNT', sequelize.col('group.id')),
            'contactCount'
        ]],
        include: [{
            model: Group,
        }],
    }).then(seenData => { globalObj.seendata=seenData;return Group.findAll();})
    .then(function (data) {
globalObj.alldata=data;
        return res.status(200).send(globalObj);
    }).catch(function (err) {
        return res.status(400).send(err.message);
    });
};

And my angular client side controller code:

$http({
        method: 'GET',
        url: '/api/getnewgroup'
      })
      .then(function (response) {
        $scope.groups = response.data.seendata.rows;
        $scope.alldata = response.data.alldata;
        console.log($scope.groups);
      }, function (response) {
        window.location.href = '/';
      });

And my Jade file:

tr(ng-repeat='group in groups')
 td {{group.groupname}}
 td {{group.contactCount}}

I want to display contactCount value as well as i want to display alldata.groupname values in my front end?

Help me!

I am getting {{group.contactCount}} correctly, but i am not getting {{group.groupname}} coming from alldata.groupname

How to get? both values and how to pass multiple scopes and to be used in ng-repeat?

Body:
Better take allData in to $scope.alldata = response.data.alldata;

    $http({
      method: 'GET',
      url: '/api/getnewgroup'
    })
    .then(function (response) {
      $scope.groups = response.data.seendata.rows;
      $scope.allData = response.data.alldata;
      console.log($scope.groups);
    }, function (response) {
      window.location.href = '/';
    });

And in your Jade file

<tr ng-repeat='group in groups track by $index'>
  <td>
    <span ng-repeat='data in alldata'>data.groupname</span>
  </td>
  <td>group.contactCount</td>
</tr>

With help of rows $index you can fetch the data of allData also. Hope it will work


问:
Integrating GIT repository with Jenkins
When I am trying to give the Git URL in Jenkins source code management, I am getting this error:

```<code>Failed to connect to repository : Error performing command: git.exe ls-remote -h https://github.com/shivnathr/DevOPS1 HEAD
</code>```

How can I avoid it?

答:
Make sure your Jenkins is running as your account, and not as a service with a technical account.

That way, Jenkins will benefit from the same configuration as your account.

But first, check if you can, with your account, in a simple CMD shell session, execute that same command successfully:

```<code> git.exe ls-remote -h https://github.com/shivnathr/DevOPS1 HEAD
</code>```

Title: Integrating GIT repository with Jenkins

Body:
When I am trying to give the Git URL in Jenkins source code management, I am getting this error:

Failed to connect to repository : Error performing command: git.exe ls-remote -h https://github.com/shivnathr/DevOPS1 HEAD

How can I avoid it?

Body:
Make sure your Jenkins is running as your account, and not as a service with a technical account.

That way, Jenkins will benefit from the same configuration as your account.

But first, check if you can, with your account, in a simple CMD shell session, execute that same command successfully:

 git.exe ls-remote -h https://github.com/shivnathr/DevOPS1 HEAD


问:
Unique elements on basis of keys
I want to find unique elements in a which do not exist in b on the basis of name property

```<code>EXPECTED OUTPUT
var data= [{"name":"rashffffish","color":"blue" }];
</code>```

```<code>var a =[{"name":"sam","color":"red" }, {"name":"rash","color":"blue" },{"name":"rashffffish","color":"blue" }];

var b = [{"name":"sam","color":"red" },{"name":"rash","color":"red" }];

var data = [];
b.map((n)=>{
  for(i=0;i<a.length;i++) {
    if(n.name!= a[i].name){
      data.push(a[i]);
    }
  }
})

console.log(data);
</code>```

答:
From your code...

var a = [{
  "name": "sam",
  "color": "red"
}, {
  "name": "rash",
  "color": "blue"
}, {
  "name": "rashffffish",
  "color": "blue"
}];

var b = [{
  "name": "sam",
  "color": "red"
}, {
  "name": "rash",
  "color": "red"
}];

var data = a;
b.forEach((n) => {
  for (i = 0; i < data.length; i++) {
    if (n.name === a[i].name) {
      var ind= data.indexOf(a[i]);
      data.splice(ind, 1);
    }
  }
})
console.log(data);```

Title: Unique elements on basis of keys

Body:
I want to find unique elements in a which do not exist in b on the basis of name property

EXPECTED OUTPUT
var data= [{"name":"rashffffish","color":"blue" }];

var a =[{"name":"sam","color":"red" }, {"name":"rash","color":"blue" },{"name":"rashffffish","color":"blue" }];

var b = [{"name":"sam","color":"red" },{"name":"rash","color":"red" }];

var data = [];
b.map((n)=>{
  for(i=0;i<a.length;i++) {
    if(n.name!= a[i].name){
      data.push(a[i]);
    }
  }
})

console.log(data);


问:
UIGestureRecognizer didn't respond swift 3.0
When I pan on the view it didn't react. The following code shows how I setup the gesture recognizer. What's wrong with my code?</p>

```<code>class MyViewController : UIViewController {
    override func loadView() {
        self.view.addGestureRecognizer(gestureRecognizerForSetCardFace)
    }

    var gestureRecognizerForSetCardFace: UIPanGestureRecognizer = {
        let recognizer = UIPanGestureRecognizer(target: self, action: #selector(handleSetGesture(gesture:)))
        recognizer.maximumNumberOfTouches = 1
        return recognizer
    }()

     @objc func handleSetGesture(gesture: UIPanGestureRecognizer){
        print("pan")
    }
}
</code>```

答:
Couple of things you need to add -

Add Lazy var for your gesture.

Lazy properties are useful when the initial value for a property is
  dependent on outside factors whose values are not known until after an
  instance’s initialization is complete.

```<code>lazy var gestureRecognizerForSetCardFace: UIPanGestureRecognizer = {
        let recognizer = UIPanGestureRecognizer(target: self, action: #selector(handleSetGesture(gesture:)))
        recognizer.maximumNumberOfTouches = 1
        return recognizer
    }()
</code>```

Add gesture recogniser in viewdidLoad

Called after the controller's view is loaded into memory.

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    self.view.addGestureRecognizer(gestureRecognizerForSetCardFace)
}
</code>```

Body:
When I pan on the view it didn't react. The following code shows how I setup the gesture recognizer. What's wrong with my code?

class MyViewController : UIViewController {
    override func loadView() {
        self.view.addGestureRecognizer(gestureRecognizerForSetCardFace)
    }

    var gestureRecognizerForSetCardFace: UIPanGestureRecognizer = {
        let recognizer = UIPanGestureRecognizer(target: self, action: #selector(handleSetGesture(gesture:)))
        recognizer.maximumNumberOfTouches = 1
        return recognizer
    }()

     @objc func handleSetGesture(gesture: UIPanGestureRecognizer){
        print("pan")
    }
}

Body:
Couple of things you need to add -

Add Lazy var for your gesture.

Lazy properties are useful when the initial value for a property is
  dependent on outside factors whose values are not known until after an
  instance’s initialization is complete.

lazy var gestureRecognizerForSetCardFace: UIPanGestureRecognizer = {
        let recognizer = UIPanGestureRecognizer(target: self, action: #selector(handleSetGesture(gesture:)))
        recognizer.maximumNumberOfTouches = 1
        return recognizer
    }()

Add gesture recogniser in viewdidLoad

Called after the controller's view is loaded into memory.

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.addGestureRecognizer(gestureRecognizerForSetCardFace)
}


问:
web request from the user browser
is it possible to send a web request from the user browser to another api and then process the result sent back??

im trying the following ajax code but its not working, i was wondering whether is it possible or not and if its a yes how can i implement it ...

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

        $.ajax({
            type: "GET",
            url: "http://api.ipinfodb.com/v2/ip_query.php?key=a9a2b0ec2c4724dd95286761777b09f1c8e82894de277a5b9d7175fa5275f2da&ip=&output=xml",
            dataType: "xml",
            success: function(xml) {
                alert("sucess");
                $(xml).find('Ip').each(function() {
                    var ip = $(this).find('Ip').text();
                    alert(ip);

                });
            }
        });

    });
</code>```

答:
Should be possible, I have done the same.

BUT you have to have the pages on the same server, you cannot send a request to another server, in that case you would have to use a proxy on your server to relay the call.

Title: web request from the user browser

Body:
is it possible to send a web request from the user browser to another api and then process the result sent back??

im trying the following ajax code but its not working, i was wondering whether is it possible or not and if its a yes how can i implement it ...

$(document).ready(function() {

        $.ajax({
            type: "GET",
            url: "http://api.ipinfodb.com/v2/ip_query.php?key=a9a2b0ec2c4724dd95286761777b09f1c8e82894de277a5b9d7175fa5275f2da&ip=&output=xml",
            dataType: "xml",
            success: function(xml) {
                alert("sucess");
                $(xml).find('Ip').each(function() {
                    var ip = $(this).find('Ip').text();
                    alert(ip);

                });
            }
        });

    });


问:
How to save and retrieve Array of Objects value from Dictionary in Swift iOS?
I am newly to Swift programming. I am developing an app where I have an array of Objects that I need to save it into one Dictionary, means for Dictionary 'Array of Objects' should be my Value and 'ID' should be my Key.

Here 2 elements contains in my Array, how can I save and retrieve from Dictionary using any unique Key. Please suggest me. Thank you!

答:
You can do it by

```<code>var myDict = Dictionary<String, Any>()
myDict = ["myKey": myArrayObjectName as! VideoRangeInfo]
</code>```

Now you can access you array by use "myKey" of dictionary like below,

```<code>print("My array = \(myDict["myKey"] as! VideoRangeInfo)")
</code>```

UPDATED: I think your array is objective c NSMutableArray not swift Array so

```<code>var myDic = NSMutableDictionary()
myDic.setObject(myArrayObjectName, forKey: "myKey")
</code>```

And

```<code>print("My array = \(myDic.object(forKey: "MyKey") as! VideoRangeInfo)")
</code>```

Body:
You can do it by

var myDict = Dictionary<String, Any>()
myDict = ["myKey": myArrayObjectName as! VideoRangeInfo]

Now you can access you array by use "myKey" of dictionary like below,

print("My array = \(myDict["myKey"] as! VideoRangeInfo)")

UPDATED: I think your array is objective c NSMutableArray not swift Array so

var myDic = NSMutableDictionary()
myDic.setObject(myArrayObjectName, forKey: "myKey")

And

print("My array = \(myDic.object(forKey: "MyKey") as! VideoRangeInfo)")


问:
Regex - grabbing all
 tags
Let's say that I have a string as so (not HTML-- from backend, I am recieving as string. I just formatted this way to be easier to read the dom tree):

```<code><ul>
    <li>
        <a href="link1">Link1</a>
        <a href="link2>Link2</a>
    </li>
    <li>
        <a href="link3">Link3</a>
        <a href="link4>Link4</a>
    </li>
</ul>
</code>```

How can I get grab inside li tags and retrieve as so :

```<code>[
    [<a href="link1">Link1</a>, <a href="link2>Link2</a>],
    [<a href="link3">Link3</a>,  <a href="link4>Link4</a>]
]
</code>```

I am assuming you need regex to achieve this (no jQuery).

答:
Try below code :-

I have given id to ul.

After that used query selector to get li of ul.

Then used query selector to get anchor tags of li.

var list = document.getElementById("list");
var li = list.querySelectorAll("li");
//console.log(li);
var result = [];
for(var i = 0; i < li.length; i++){
  var temp = [];
  var anchors = li[i].querySelectorAll("a");
  for(var j = 0; j < anchors.length; j++){
    temp.push(anchors[j].outerHTML);
  }
  result.push(temp);
}
console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="list">
    <li>
        Link1
        Link2
    </li>
    <li>
        Link3
        Link4
    </li>
</ul></code>```

Title: Regex - grabbing all <li> tags

Body:
Let's say that I have a string as so (not HTML-- from backend, I am recieving as string. I just formatted this way to be easier to read the dom tree):

        Link1
        Link2

        Link3
        Link4

How can I get grab inside li tags and retrieve as so :

[
    [Link1, Link2],
    [Link3,  Link4]
]

I am assuming you need regex to achieve this (no jQuery).

Body:
Try below code :-

I have given id to ul.

After that used query selector to get li of ul.

Then used query selector to get anchor tags of li.

var list = document.getElementById("list");
var li = list.querySelectorAll("li");
//console.log(li);
var result = [];
for(var i = 0; i < li.length; i++){
  var temp = [];
  var anchors = li[i].querySelectorAll("a");
  for(var j = 0; j < anchors.length; j++){
    temp.push(anchors[j].outerHTML);
  }
  result.push(temp);
}
console.log(result);

<ul id="list">
    <li>
        <a href="link1">Link1</a>
        <a href="link2">Link2</a>
    </li>
    <li>
        <a href="link3">Link3</a>
        <a href="link4">Link4</a>
    </li>
</ul>


问:
JPanel doesn't update in real time when using delays
I am creating a GUI program to solve a maze. I already got the maze solving algorithm down, but weird stuff happens when I try to add a delay.

The code is pretty long, so here's something that does the same in terms of GUI delays.

```<code>import java.awt.*;
import javax.swing.*;

public class Example extends JPanel {
    JButton[] buttons = new JButton[4];
    public Example() {
    setLayout(new GridLayout(1, 4));
    for(int i = 0; i < 4; i++)
        add(buttons[i] = new JButton());
    }

    public static class SubClass extends JPanel {
        Example example;
        JButton start;

        public SubClass() {
            setLayout(new BorderLayout());
            add(example = new Example(), BorderLayout.CENTER);
            start = new JButton("Start");
            start.addActionListener(e -> {
                for(int i = 0; i < 4; i++) {
                    //insert delays here
                    example.buttons[i].setBackground(Color.BLACK);
                }
            });
            add(start, BorderLayout.SOUTH);
        }
    }

    public static void main(String[] args){
        JFrame frame = new JFrame("Title");
        frame.setSize(500, 500);
        frame.setLocation(500, 250);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new SubClass());
        frame.setVisible(true);
    }
}
</code>```

When I run the code without any delays, it works perfectly. However, whenever I try to add a delay, rather than the buttons updating one at a time, the whole window just freezes until all of the buttons are done updating, and then the entire thing updates at once.

I tried using java.util.Timer, javax.swing.Timer, and Thread.sleep, but none of them seemed to work.

Also, when I don't have the enclosing panel (SubClass) and just change the inner panel (Example) directly from the main method, it does work, and the buttons update in real time like they're supposed to.

For example, if I changed the main method to

```<code>    public static void main(String[] args){
        Example ex = new Example();
        JFrame frame = new JFrame("Title");
        frame.setSize(500, 500);
        frame.setLocation(500, 250);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(ex);
        frame.setVisible(true);

        for(int i = 0; i < 4; i++) {
            //insert delays here
            ex.buttons[i].setBackground(Color.BLACK);
        }
    }
</code>```

Looking back on it, I should have made the panels in reverse order, switching the subclass and the enclosing class, but at this point I'm done writing my program, and it works in all aspects except this one, so I don't want to do too much extra work and rewrite a bunch of stuff. I also don't know if that would solve the problem anyway.

Edit: Here is the full code:

```<code>import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.util.*;
import javax.swing.border.LineBorder;

public class StackGUIMaze extends JPanel {
    public static final String SET_START = "setStart";
    public static final String SET_END = "setEnd";
    public static final String BUILD = "build";
    public static final String RUNNING = "running";
    private static final char OPEN = 'O'; //Open
    private static final char CLOSED = 'X'; //Closed
    private static final char TRIED = '*';
    private static final char SUCCEEDED = '+';
    private static final char FAILED = '#';
    private static final char POINTER = '^';
    private static final char END = 'E';
    private static final char START = 'S';
    private static final int DELAY = 0;
    private static final Direction NORTH = Direction.NORTH;
    private static final Direction SOUTH = Direction.SOUTH;
    private static final Direction EAST = Direction.EAST;
    private static final Direction WEST = Direction.WEST;
    private static final Direction[] DIRECTIONS = {SOUTH, EAST, NORTH, WEST};
    private final int ROWS;
    private final int COLUMNS;
    private Space pointer;
    private Space end;
    private Branch moves = new Branch(null, null);
    private Space[][] buttons;
    private String mode = "";
    private Space start;
    private Timer timer = new Timer(DELAY, e -> {
        step();
        if(pointer == end) {
            this.timer.stop();
        }
    });

    public StackGUIMaze(int r, int c) {
        ROWS = r;
        COLUMNS = c;
        setLayout(new GridLayout(ROWS, COLUMNS));
        buttons = new Space[ROWS][COLUMNS];
        for(int i = 0; i < ROWS; i++) {
            buttons[i] = new Space[COLUMNS];
            for(int j = 0; j < COLUMNS; j++) {
                buttons[i][j] = new Space(OPEN, i, j);
                buttons[i][j].setBackground(Color.WHITE);
                buttons[i][j].setContentAreaFilled(false);
                buttons[i][j].setBorder(new LineBorder(new Color(100, 100, 100)));
                buttons[i][j].setOpaque(true);
                buttons[i][j].addActionListener(e -> {
                    if(e.getSource() instanceof Space) {
                        switch(mode) {
                            case BUILD:
                                ((Space) e.getSource()).setStatus(((Space) e.getSource()).getStatus() == OPEN ? CLOSED : OPEN); //Toggles state of space
                                break;
                            case SET_START:
                                ((Space) e.getSource()).setStatus(START);
                                break;
                            case SET_END:
                                ((Space) e.getSource()).setStatus(END);
                                break;
                        }
                    }
                });
                add(buttons[i][j]);
            }
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Title");
                frame.setSize(500, 500);
                frame.setLocation(500, 250);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(new FullPanel(12, 12));
                frame.setVisible(true);
        });
    }

    private static void delay(int n) {
        try {Thread.sleep(n);} catch(InterruptedException ignored) {}
    }

    private void setEnd(int r, int c) {
        end = null;
        buttons[r][c].setStatus(END);
    }

    public Space getPointer() {
        return pointer;
    }

    public Space getEnd() {
        return end;
    }

    private void backtrack(){
        while(openMoves().isEmpty()) {
            pointer.setStatus(FAILED);
            move(lastMove().getDirection().opposite());
            lastMove().getParent().pop();
        }
    }

    private Space to(Direction d) {
        try {
            switch (d) { //No breaks necessary, since each case ends in a return statement
                case NORTH:
                    return buttons[pointer.getRow() - 1][pointer.getCol()];
                case SOUTH:
                    return buttons[pointer.getRow() + 1][pointer.getCol()];
                case EAST:
                    return buttons[pointer.getRow()][pointer.getCol() + 1];
                case WEST:
                    return buttons[pointer.getRow()][pointer.getCol() - 1];
                default:
                    System.out.println("I don't know how you got here, somehow a nonexistent direction was called");
                    return null;
            }
        } catch(ArrayIndexOutOfBoundsException e) {
            return null;
        }
    }

    public void setPointer(int r, int c) {
        pointer = buttons[r][c];
    }

    private Branch lastMove() {
        Branch temp = moves;
        while(!temp.isEmpty()) {
            temp = temp.peek();
        }
        return temp;
    }

    private boolean go(Direction d) {
        boolean b = checkOpen(d);
        pointer.setStatus(TRIED);
        if (checkOpen(d)) {
            move(d);
            if(pointer.getStatus() == OPEN) pointer.setStatus(TRIED);
            lastMove().push(new Branch(lastMove(), d));
            return true;
        } else {
            return false;
        }
    }

    private void move(Direction d) {
        delay(50);
        switch(d) { //No breaks necessary, since each case ends in a return statement
            case NORTH:
                buttons[pointer.getRow() - 1][pointer.getCol()].setStatus(POINTER);
                break;
            case SOUTH:
                buttons[pointer.getRow() + 1][pointer.getCol()].setStatus(POINTER);
                break;
            case EAST:
                buttons[pointer.getRow()][pointer.getCol() + 1].setStatus(POINTER);
                break;
            case WEST:
                buttons[pointer.getRow()][pointer.getCol() - 1].setStatus(POINTER);
                break;
            default:
                System.out.println("I don't know how you got here, somehow a nonexistent direction was called");
        }
    }

    private ArrayList<Direction> openMoves() {
        ArrayList<Direction> arr = new ArrayList<>();
        for(Direction d : DIRECTIONS) {
            if(checkOpen(d)) arr.add(d);
        }
        return arr;
    }

    private boolean checkOpen(Direction d) {
        try {
            char s;
            switch (d) { //No breaks necessary, since each case ends in a return statement
                case NORTH:
                    s = buttons[pointer.getRow() - 1][pointer.getCol()].getStatus();
                    break;
                case SOUTH:
                    s = buttons[pointer.getRow() + 1][pointer.getCol()].getStatus();
                    break;
                case EAST:
                    s = buttons[pointer.getRow()][pointer.getCol() + 1].getStatus();
                    break;
                case WEST:
                    s = buttons[pointer.getRow()][pointer.getCol() - 1].getStatus();
                    break;
                default:
                    System.out.println("I don't know how you got here, somehow a nonexistent direction was called");
                    return false;
            }
            return s == OPEN || s == END || s == START;
        } catch(ArrayIndexOutOfBoundsException e) {
            return false;
        }
    }

    private boolean isSolved() {
        return end == pointer;
    }

    public void step() {
        while(pointer != end) {
            if(openMoves().isEmpty() && pointer != start) backtrack();
            while(!openMoves().isEmpty()) {
                for(Direction d : DIRECTIONS) {
                    if(pointer == end) return;
                    go(d);
                }
            }
        }
    }

    private enum Direction {
        NORTH, SOUTH, EAST, WEST;
        Direction opposite() {
            switch(this) {
                case NORTH:
                    return SOUTH;
                case SOUTH:
                    return NORTH;
                case EAST:
                    return WEST;
                case WEST:
                    return EAST;
                default:
                    System.out.println("How did you even get here? There are only 4 directions.");
                    return null;
            }
        }
    }

    public static class FullPanel extends JPanel {
        StackGUIMaze maze;
        JButton start;
        JPanel subPanel;

        public FullPanel(int r, int c) {
            maze = new StackGUIMaze(r, c);
            setLayout(new BorderLayout());
            add(maze, BorderLayout.CENTER);

            JButton start = new JButton();
            start.setText("Start");
            start.addActionListener(e -> {
                if(maze.getPointer() == null || maze.getEnd() == null) {
                    System.out.println("Could not solve, as the start/end is missing.");
                } else {
                    for (Space[] sp : maze.buttons) {
                        for (Space s : sp) {
                            s.setEnabled(false);
                        }
                    }
                    maze.timer.start();
                }
            });

            JButton setEnd = new JButton("Set end");
            setEnd.addActionListener(e -> maze.mode = SET_END);

            JButton setStart = new JButton("Set start");
            setStart.addActionListener(e -> maze.mode = SET_START);

            JButton buildButton = new JButton("Build maze");
            buildButton.addActionListener(e -> maze.mode = BUILD);

            subPanel = new JPanel();
            subPanel.add(setStart);
            subPanel.add(setEnd);
            subPanel.add(buildButton);
            subPanel.add(start);
            add(subPanel, BorderLayout.SOUTH);
        }
    }

    private class Branch extends Stack<Branch> {
        Branch parent;
        private Direction direction;

        public Branch(Branch b, Direction d) {
            parent = b;
            direction = d;
        }

        public Direction getDirection() {
            return direction;
        }

        public Branch getParent() {
            return parent;
        }
    }

    private class Space extends JButton {
        int row;
        int col;
        private char status;

        public Space(char status, int row, int col) {
            this.status = status;
            this.row = row;
            this.col = col;
        }

        public char getStatus() {
            return status;
        }

        public void setStatus(char s) {
            char st = status;
            this.status = s;
            switch(s) {
                case OPEN:
                    setBackground(Color.WHITE);
                    break;
                case CLOSED:
                    setBackground(Color.BLACK);
                    break;
                case TRIED:
                    if(st == FAILED) status = FAILED;
                    else setBackground(Color.LIGHT_GRAY);
                    break;
                case FAILED:
                    setBackground(Color.RED);
                    break;
                case SUCCEEDED:
                    setBackground(Color.GREEN);
                    break;
                case POINTER:
                    if(pointer != null && !mode.equals(RUNNING)) pointer.setStatus(TRIED);
                    else if(pointer != null) pointer.setStatus(OPEN);
                    setBackground(Color.GRAY);
                    pointer = this;
                    break;
                case END:
                    if(end != null) end.setStatus(OPEN);
                    setBackground(Color.CYAN);
                    end = this;
                    break;
                case START:
                    if(start != null) pointer.setStatus(START);
                    setBackground(Color.MAGENTA);
                    start = this;
                    pointer = start;
                    break;
                default:
                    System.out.println("Invalid status passed to method setStatus()");
            }
        }

        public int getRow() {
            return row;
        }

        public void setRow(int row) {
            this.row = row;
        }

        public int getCol() {
            return col;
        }

        public void setCol(int col) {
            this.col = col;
        }
    }
}
</code>```

I realize that it probably isn't optimal, but I just want to get it to work before I start trying to refine it.

答:
So, you have two basic problems:

You're blocking the Event Dispatching Thread inside the ActionListener. The UI won't be updated until after the actionPerformed method returns

Setting the background of JButton is a little more complicated the other components.  To start with, I disabled the contentAreaFilled and borderPainted properties and made the button opaque which allowed them to become filled.

For example..

```<code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Example extends JPanel {

    JButton[] buttons = new JButton[4];

    public Example() {
        setLayout(new GridLayout(1, 4));
        for (int i = 0; i < 4; i++) {
            add(buttons[i] = new JButton());
            buttons[i].setContentAreaFilled(false);
            buttons[i].setBorderPainted(false);
            buttons[i].setOpaque(true);
        }
    }

    public static class SubClass extends JPanel {

        Example example;
        JButton start;

        private int counter = 0;

        public SubClass() {
            setLayout(new BorderLayout());
            add(example = new Example(), BorderLayout.CENTER);
            start = new JButton("Start");
            start.addActionListener(e -> {
                counter = 0;
                Timer timer = new Timer(200, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if (counter >= 4) {
                            ((Timer) e.getSource()).stop();
                            return;
                        }
                        example.buttons[counter].setBackground(Color.BLACK);
                        counter++;
                    }
                });
                timer.start();
            });
            add(start, BorderLayout.SOUTH);
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Title");
                frame.setSize(500, 500);
                frame.setLocation(500, 250);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(new SubClass());
                frame.setVisible(true);
            }
        });
    }
}
</code>```

Body:
I am creating a GUI program to solve a maze. I already got the maze solving algorithm down, but weird stuff happens when I try to add a delay.

The code is pretty long, so here's something that does the same in terms of GUI delays.

import java.awt.*;
import javax.swing.*;

public class Example extends JPanel {
    JButton[] buttons = new JButton[4];
    public Example() {
    setLayout(new GridLayout(1, 4));
    for(int i = 0; i < 4; i++)
        add(buttons[i] = new JButton());
    }

    public static class SubClass extends JPanel {
        Example example;
        JButton start;

        public SubClass() {
            setLayout(new BorderLayout());
            add(example = new Example(), BorderLayout.CENTER);
            start = new JButton("Start");
            start.addActionListener(e -> {
                for(int i = 0; i < 4; i++) {
                    //insert delays here
                    example.buttons[i].setBackground(Color.BLACK);
                }
            });
            add(start, BorderLayout.SOUTH);
        }
    }

    public static void main(String[] args){
        JFrame frame = new JFrame("Title");
        frame.setSize(500, 500);
        frame.setLocation(500, 250);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new SubClass());
        frame.setVisible(true);
    }
}

When I run the code without any delays, it works perfectly. However, whenever I try to add a delay, rather than the buttons updating one at a time, the whole window just freezes until all of the buttons are done updating, and then the entire thing updates at once.

I tried using java.util.Timer, javax.swing.Timer, and Thread.sleep, but none of them seemed to work.

Also, when I don't have the enclosing panel (SubClass) and just change the inner panel (Example) directly from the main method, it does work, and the buttons update in real time like they're supposed to.

For example, if I changed the main method to

    public static void main(String[] args){
        Example ex = new Example();
        JFrame frame = new JFrame("Title");
        frame.setSize(500, 500);
        frame.setLocation(500, 250);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(ex);
        frame.setVisible(true);

        for(int i = 0; i < 4; i++) {
            //insert delays here
            ex.buttons[i].setBackground(Color.BLACK);
        }
    }

Looking back on it, I should have made the panels in reverse order, switching the subclass and the enclosing class, but at this point I'm done writing my program, and it works in all aspects except this one, so I don't want to do too much extra work and rewrite a bunch of stuff. I also don't know if that would solve the problem anyway.

Edit: Here is the full code:

import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.util.*;
import javax.swing.border.LineBorder;

public class StackGUIMaze extends JPanel {
    public static final String SET_START = "setStart";
    public static final String SET_END = "setEnd";
    public static final String BUILD = "build";
    public static final String RUNNING = "running";
    private static final char OPEN = 'O'; //Open
    private static final char CLOSED = 'X'; //Closed
    private static final char TRIED = '*';
    private static final char SUCCEEDED = '+';
    private static final char FAILED = '#';
    private static final char POINTER = '^';
    private static final char END = 'E';
    private static final char START = 'S';
    private static final int DELAY = 0;
    private static final Direction NORTH = Direction.NORTH;
    private static final Direction SOUTH = Direction.SOUTH;
    private static final Direction EAST = Direction.EAST;
    private static final Direction WEST = Direction.WEST;
    private static final Direction[] DIRECTIONS = {SOUTH, EAST, NORTH, WEST};
    private final int ROWS;
    private final int COLUMNS;
    private Space pointer;
    private Space end;
    private Branch moves = new Branch(null, null);
    private Space[][] buttons;
    private String mode = "";
    private Space start;
    private Timer timer = new Timer(DELAY, e -> {
        step();
        if(pointer == end) {
            this.timer.stop();
        }
    });

    public StackGUIMaze(int r, int c) {
        ROWS = r;
        COLUMNS = c;
        setLayout(new GridLayout(ROWS, COLUMNS));
        buttons = new Space[ROWS][COLUMNS];
        for(int i = 0; i < ROWS; i++) {
            buttons[i] = new Space[COLUMNS];
            for(int j = 0; j < COLUMNS; j++) {
                buttons[i][j] = new Space(OPEN, i, j);
                buttons[i][j].setBackground(Color.WHITE);
                buttons[i][j].setContentAreaFilled(false);
                buttons[i][j].setBorder(new LineBorder(new Color(100, 100, 100)));
                buttons[i][j].setOpaque(true);
                buttons[i][j].addActionListener(e -> {
                    if(e.getSource() instanceof Space) {
                        switch(mode) {
                            case BUILD:
                                ((Space) e.getSource()).setStatus(((Space) e.getSource()).getStatus() == OPEN ? CLOSED : OPEN); //Toggles state of space
                                break;
                            case SET_START:
                                ((Space) e.getSource()).setStatus(START);
                                break;
                            case SET_END:
                                ((Space) e.getSource()).setStatus(END);
                                break;
                        }
                    }
                });
                add(buttons[i][j]);
            }
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Title");
                frame.setSize(500, 500);
                frame.setLocation(500, 250);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(new FullPanel(12, 12));
                frame.setVisible(true);
        });
    }

    private static void delay(int n) {
        try {Thread.sleep(n);} catch(InterruptedException ignored) {}
    }

    private void setEnd(int r, int c) {
        end = null;
        buttons[r][c].setStatus(END);
    }

    public Space getPointer() {
        return pointer;
    }

    public Space getEnd() {
        return end;
    }

    private void backtrack(){
        while(openMoves().isEmpty()) {
            pointer.setStatus(FAILED);
            move(lastMove().getDirection().opposite());
            lastMove().getParent().pop();
        }
    }

    private Space to(Direction d) {
        try {
            switch (d) { //No breaks necessary, since each case ends in a return statement
                case NORTH:
                    return buttons[pointer.getRow() - 1][pointer.getCol()];
                case SOUTH:
                    return buttons[pointer.getRow() + 1][pointer.getCol()];
                case EAST:
                    return buttons[pointer.getRow()][pointer.getCol() + 1];
                case WEST:
                    return buttons[pointer.getRow()][pointer.getCol() - 1];
                default:
                    System.out.println("I don't know how you got here, somehow a nonexistent direction was called");
                    return null;
            }
        } catch(ArrayIndexOutOfBoundsException e) {
            return null;
        }
    }

    public void setPointer(int r, int c) {
        pointer = buttons[r][c];
    }

    private Branch lastMove() {
        Branch temp = moves;
        while(!temp.isEmpty()) {
            temp = temp.peek();
        }
        return temp;
    }

    private boolean go(Direction d) {
        boolean b = checkOpen(d);
        pointer.setStatus(TRIED);
        if (checkOpen(d)) {
            move(d);
            if(pointer.getStatus() == OPEN) pointer.setStatus(TRIED);
            lastMove().push(new Branch(lastMove(), d));
            return true;
        } else {
            return false;
        }
    }

    private void move(Direction d) {
        delay(50);
        switch(d) { //No breaks necessary, since each case ends in a return statement
            case NORTH:
                buttons[pointer.getRow() - 1][pointer.getCol()].setStatus(POINTER);
                break;
            case SOUTH:
                buttons[pointer.getRow() + 1][pointer.getCol()].setStatus(POINTER);
                break;
            case EAST:
                buttons[pointer.getRow()][pointer.getCol() + 1].setStatus(POINTER);
                break;
            case WEST:
                buttons[pointer.getRow()][pointer.getCol() - 1].setStatus(POINTER);
                break;
            default:
                System.out.println("I don't know how you got here, somehow a nonexistent direction was called");
        }
    }

    private ArrayList<Direction> openMoves() {
        ArrayList<Direction> arr = new ArrayList<>();
        for(Direction d : DIRECTIONS) {
            if(checkOpen(d)) arr.add(d);
        }
        return arr;
    }

    private boolean checkOpen(Direction d) {
        try {
            char s;
            switch (d) { //No breaks necessary, since each case ends in a return statement
                case NORTH:
                    s = buttons[pointer.getRow() - 1][pointer.getCol()].getStatus();
                    break;
                case SOUTH:
                    s = buttons[pointer.getRow() + 1][pointer.getCol()].getStatus();
                    break;
                case EAST:
                    s = buttons[pointer.getRow()][pointer.getCol() + 1].getStatus();
                    break;
                case WEST:
                    s = buttons[pointer.getRow()][pointer.getCol() - 1].getStatus();
                    break;
                default:
                    System.out.println("I don't know how you got here, somehow a nonexistent direction was called");
                    return false;
            }
            return s == OPEN || s == END || s == START;
        } catch(ArrayIndexOutOfBoundsException e) {
            return false;
        }
    }

    private boolean isSolved() {
        return end == pointer;
    }

    public void step() {
        while(pointer != end) {
            if(openMoves().isEmpty() && pointer != start) backtrack();
            while(!openMoves().isEmpty()) {
                for(Direction d : DIRECTIONS) {
                    if(pointer == end) return;
                    go(d);
                }
            }
        }
    }

    private enum Direction {
        NORTH, SOUTH, EAST, WEST;
        Direction opposite() {
            switch(this) {
                case NORTH:
                    return SOUTH;
                case SOUTH:
                    return NORTH;
                case EAST:
                    return WEST;
                case WEST:
                    return EAST;
                default:
                    System.out.println("How did you even get here? There are only 4 directions.");
                    return null;
            }
        }
    }

    public static class FullPanel extends JPanel {
        StackGUIMaze maze;
        JButton start;
        JPanel subPanel;

        public FullPanel(int r, int c) {
            maze = new StackGUIMaze(r, c);
            setLayout(new BorderLayout());
            add(maze, BorderLayout.CENTER);

            JButton start = new JButton();
            start.setText("Start");
            start.addActionListener(e -> {
                if(maze.getPointer() == null || maze.getEnd() == null) {
                    System.out.println("Could not solve, as the start/end is missing.");
                } else {
                    for (Space[] sp : maze.buttons) {
                        for (Space s : sp) {
                            s.setEnabled(false);
                        }
                    }
                    maze.timer.start();
                }
            });

            JButton setEnd = new JButton("Set end");
            setEnd.addActionListener(e -> maze.mode = SET_END);

            JButton setStart = new JButton("Set start");
            setStart.addActionListener(e -> maze.mode = SET_START);

            JButton buildButton = new JButton("Build maze");
            buildButton.addActionListener(e -> maze.mode = BUILD);

            subPanel = new JPanel();
            subPanel.add(setStart);
            subPanel.add(setEnd);
            subPanel.add(buildButton);
            subPanel.add(start);
            add(subPanel, BorderLayout.SOUTH);
        }
    }

    private class Branch extends Stack<Branch> {
        Branch parent;
        private Direction direction;

        public Branch(Branch b, Direction d) {
            parent = b;
            direction = d;
        }

        public Direction getDirection() {
            return direction;
        }

        public Branch getParent() {
            return parent;
        }
    }

    private class Space extends JButton {
        int row;
        int col;
        private char status;

        public Space(char status, int row, int col) {
            this.status = status;
            this.row = row;
            this.col = col;
        }

        public char getStatus() {
            return status;
        }

        public void setStatus(char s) {
            char st = status;
            this.status = s;
            switch(s) {
                case OPEN:
                    setBackground(Color.WHITE);
                    break;
                case CLOSED:
                    setBackground(Color.BLACK);
                    break;
                case TRIED:
                    if(st == FAILED) status = FAILED;
                    else setBackground(Color.LIGHT_GRAY);
                    break;
                case FAILED:
                    setBackground(Color.RED);
                    break;
                case SUCCEEDED:
                    setBackground(Color.GREEN);
                    break;
                case POINTER:
                    if(pointer != null && !mode.equals(RUNNING)) pointer.setStatus(TRIED);
                    else if(pointer != null) pointer.setStatus(OPEN);
                    setBackground(Color.GRAY);
                    pointer = this;
                    break;
                case END:
                    if(end != null) end.setStatus(OPEN);
                    setBackground(Color.CYAN);
                    end = this;
                    break;
                case START:
                    if(start != null) pointer.setStatus(START);
                    setBackground(Color.MAGENTA);
                    start = this;
                    pointer = start;
                    break;
                default:
                    System.out.println("Invalid status passed to method setStatus()");
            }
        }

        public int getRow() {
            return row;
        }

        public void setRow(int row) {
            this.row = row;
        }

        public int getCol() {
            return col;
        }

        public void setCol(int col) {
            this.col = col;
        }
    }
}

I realize that it probably isn't optimal, but I just want to get it to work before I start trying to refine it.

Body:
So, you have two basic problems:

You're blocking the Event Dispatching Thread inside the ActionListener. The UI won't be updated until after the actionPerformed method returns

Setting the background of JButton is a little more complicated the other components.  To start with, I disabled the contentAreaFilled and borderPainted properties and made the button opaque which allowed them to become filled.

For example..

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Example extends JPanel {

    JButton[] buttons = new JButton[4];

    public Example() {
        setLayout(new GridLayout(1, 4));
        for (int i = 0; i < 4; i++) {
            add(buttons[i] = new JButton());
            buttons[i].setContentAreaFilled(false);
            buttons[i].setBorderPainted(false);
            buttons[i].setOpaque(true);
        }
    }

    public static class SubClass extends JPanel {

        Example example;
        JButton start;

        private int counter = 0;

        public SubClass() {
            setLayout(new BorderLayout());
            add(example = new Example(), BorderLayout.CENTER);
            start = new JButton("Start");
            start.addActionListener(e -> {
                counter = 0;
                Timer timer = new Timer(200, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if (counter >= 4) {
                            ((Timer) e.getSource()).stop();
                            return;
                        }
                        example.buttons[counter].setBackground(Color.BLACK);
                        counter++;
                    }
                });
                timer.start();
            });
            add(start, BorderLayout.SOUTH);
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Title");
                frame.setSize(500, 500);
                frame.setLocation(500, 250);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(new SubClass());
                frame.setVisible(true);
            }
        });
    }
}


问:
Granting read access to the Authenticated Users group for a file
How do I grant read access to the Authenticated Users group for a file? I'm using s3cmd and want to do it while uploading but I'm just focusing directly on changing the acl. What should I put in for http://acs.amazonaws.com/groups/global/AuthenticatedUsers? I have tried every combination of AuthenticatedUsers possible.

./s3cmd setacl
--acl-grant=read:http://acs.amazonaws.com/groups/global/AuthenticatedUsers
s3://BUCKET/FILE

./s3cmd setacl
--acl-grant=read:AuthenticatedUsers
s3://BUCKET/FILE

答:
If you want to do it at bucket level you can do -

```<code>aws s3api put-bucket-acl --bucket bucketname --grant-full-control uri=http://acs.amazonaws.com/groups/global/AuthenticatedUsers
</code>```

Docs - http://docs.aws.amazon.com/cli/latest/reference/s3api/put-bucket-acl.html

Body:
If you want to do it at bucket level you can do -

aws s3api put-bucket-acl --bucket bucketname --grant-full-control uri=http://acs.amazonaws.com/groups/global/AuthenticatedUsers

Docs - http://docs.aws.amazon.com/cli/latest/reference/s3api/put-bucket-acl.html


问:
Isolated Storage in Environment.SpecialFolder
I want to understand what should I use if I need to save a file in standard isolated storage.
For iOS I have "Documents" and "Library". "Documents" can I use to see it in iTunes, "Library" is "isolated". (Xamarin documentation)
I found, that "Documents" I can use as

Environment.SpecialFolder.MyDocuments

and "Library" as

Environment.SpecialFolder.Resources

But for Android I have an error, if i use Environment.SpecialFolder.Resources because it's not exists in Android.

What should I use to save my files in "isolated" storage for Android? Environment.SpecialFolder.MyDocuments? Or something else?

What I found for iOS:

Desktop= /Documents/Desktop

  MyDocuments= /Documents

  MyDocuments= /Documents

  Favorites= /Library/Favorites

  MyMusic= /Documents/Music

  MyVideos= /Documents/Videos

  DesktopDirectory= /Documents/Desktop

  Fonts= /Documents/.fonts

  Templates= /Documents/Templates

  ApplicationData= /Documents/.config

  LocalApplicationData= /Documents

  InternetCache= /Library/Caches

  CommonApplicationData= /usr/share

  ProgramFiles= /Applications

  MyPictures= /Documents/Pictures

  CommonTemplates= /usr/share/templates

  Resources= /Library

答:
In Android:

Personal & MyDocuments Special folders map to: /data/data/@PACKAGE_NAME@/files

We can store files in any of the above directories. None of them can be accessed by other app, nor user can access them outside the world unless the phone is rooted.

For more detail on this, please have a look at my answer here.


问:
Schedule PHP script on Synology Server
I have a php script that connects to a database to run a query. This works fine when running the script by browsing to it. The problem I have is when I use the Task Scheduler within the Synology server's control panel. For some reason I am getting the following error:

PHP Fatal error:  Call to undefined function mysqli_connect() in /volume1/web/bimotech/check_ip.php on line 13

As mentioned, this works fine when running from the browser but not when scheduled.

Any ideas?

Thanks,

John

答:
You have to define the full path of your php, synology maybe using different version of php.

For example your php executable is installed on /usr/bin/php

you have to do something like

```<code>/usr/bin/php /path/to/script.php
</code>```

Title: Schedule PHP script on Synology Server

Body:
You have to define the full path of your php, synology maybe using different version of php.

For example your php executable is installed on /usr/bin/php

you have to do something like

/usr/bin/php /path/to/script.php


问:
django-filter: only show filter options contained in queryset
I'm using the excellent django-filter app to filter a queryset of model objects. However, when I .exclude() objects from the queryset in the view, the filter selectors in the template still show all available options - even those of objects I excluded from the queryset. Let's say my model and view look as follows:

```<code>#model
[...]
class Animal(models.Model):
    REGION_CHOICES = (
        (0, 'Africa'),
        (1, 'Europe'),
    )

    name = models.CharField(max_length=100)
    region = models.CharField(choices=REGION_CHOICES, max_length=100)
[...]

#view
[...]
qs = Animal.objects.all()
filter = AnimalFilter(request.GET, qs)
[...]
</code>```

Assuming there are two animals in the database:

```<code>zebra = Animal(name='Zebra', region='Africa')
frog = Animal(name='Frog', region'Europe')
</code>```

When I render the filter in the template, I correctly get a selector for region which contains the two options Europe and Africa.
But if I use some logic in the view to .exclude() objects from the queryset like this:

```<code>#view
[...]
qs = Animal.objects.all().exclude(name='Frog')
filter = AnimalFilter(request.GET, qs)
[...]
</code>```

Now if I render the filter in the template I still get the two options Europe and Africa for region although the queryset only contains one animal which has the region Africa.
Any ideas how I could get the correct options for the region field rendered in the template? Any help is greatly appreciated.

答:
You could override the choices in your FilterSet.__init__() to ensure that the region choices are limited to the regions based on the provided queryset.

class AnimalFilter(FilterSet):
    def __init__(self, *args, **kwargs):
        super(AnimalFilter, self).__init__(*args, **kwargs)

        regions = self.queryset.values('region').distinct()
        region_choices = [(k, v) for k, v in REGION_CHOICES if k in regions]
        self.filters['region'].choices = region_choices
```

Note: I haven't tested this, but should hopefully be enough to point you in the right direction.

Body:
I'm using the excellent django-filter app to filter a queryset of model objects. However, when I .exclude() objects from the queryset in the view, the filter selectors in the template still show all available options - even those of objects I excluded from the queryset. Let's say my model and view look as follows:

#model
[...]
class Animal(models.Model):
    REGION_CHOICES = (
        (0, 'Africa'),
        (1, 'Europe'),
    )

    name = models.CharField(max_length=100)
    region = models.CharField(choices=REGION_CHOICES, max_length=100)
[...]

#view
[...]
qs = Animal.objects.all()
filter = AnimalFilter(request.GET, qs)
[...]

Assuming there are two animals in the database:

zebra = Animal(name='Zebra', region='Africa')
frog = Animal(name='Frog', region'Europe')

When I render the filter in the template, I correctly get a selector for region which contains the two options Europe and Africa.
But if I use some logic in the view to .exclude() objects from the queryset like this:

#view
[...]
qs = Animal.objects.all().exclude(name='Frog')
filter = AnimalFilter(request.GET, qs)
[...]

Now if I render the filter in the template I still get the two options Europe and Africa for region although the queryset only contains one animal which has the region Africa.
Any ideas how I could get the correct options for the region field rendered in the template? Any help is greatly appreciated.

Body:
You could override the choices in your FilterSet.__init__() to ensure that the region choices are limited to the regions based on the provided queryset.

class AnimalFilter(FilterSet):
    def __init__(self, *args, **kwargs):
        super(AnimalFilter, self).__init__(*args, **kwargs)

        regions = self.queryset.values('region').distinct()
        region_choices = [(k, v) for k, v in REGION_CHOICES if k in regions]
        self.filters['region'].choices = region_choices

Note: I haven't tested this, but should hopefully be enough to point you in the right direction.