问:
Implement Android SearchView Suggestions like Google Play Store
How can I implement SearchView suggestions view which is overlaying other views like Google material SearchView using in many apps like Google Play Store?

答:
```<code>public class AutoSuggestAdapter extends ArrayAdapter {

private Context context;
private int resource;
private List<String> items;
private List<String> tempItems;
private List<String> suggestions;

public AutoSuggestAdapter(Context context, int resource, List<String> items) {
    super(context, resource, 0, items);

    this.context = context;
    this.resource = resource;
    this.items = items;
    tempItems = new ArrayList<String>(items);
    suggestions = new ArrayList<String>();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(resource, parent, false);
    }

    String item = items.get(position);

    if (item != null && view instanceof TextView) {
        ((TextView) view).setText(item);
    }

    return view;
}

@Override
public Filter getFilter() {
    return nameFilter;
}

Filter nameFilter = new Filter() {
    @Override
    public CharSequence convertResultToString(Object resultValue) {
        String str = (String) resultValue;
        return str;
    }

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        if (constraint != null) {
            suggestions.clear();
            for (String names : tempItems) {
                if (names.toLowerCase().contains(constraint.toString().toLowerCase())) {
                    suggestions.add(names);
                }
            }
            FilterResults filterResults = new FilterResults();
            filterResults.values = suggestions;
            filterResults.count = suggestions.size();
            return filterResults;
        } else {
            return new FilterResults();
        }
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        List<String> filterList = (ArrayList<String>) results.values;
        if (results != null && results.count > 0) {
            clear();
            for (String item : filterList) {
                add(item);
                notifyDataSetChanged();
            }
        }
    }
};
</code>```

This should be your custom adapter class that u make.
In your main u call this class using constructor and it will look like this.

```<code>public class MainActivity extends AppCompatActivity {
AutoCompleteTextView ACTV;
List<String> suggestions = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ACTV = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
}
public void AutocmpleteMeth() {
    // Hieronder is het code voor Autocomplete [BEGIN]
    AutoSuggestAdapter adapter = new AutoSuggestAdapter(this, android.R.layout.simple_dropdown_item_1line, suggestions);
    ACTV.setAdapter(adapter);
    ACTV.setThreshold(1);

}}
</code>```

Body:
public class AutoSuggestAdapter extends ArrayAdapter {

private Context context;
private int resource;
private List<String> items;
private List<String> tempItems;
private List<String> suggestions;

public AutoSuggestAdapter(Context context, int resource, List<String> items) {
    super(context, resource, 0, items);

    this.context = context;
    this.resource = resource;
    this.items = items;
    tempItems = new ArrayList<String>(items);
    suggestions = new ArrayList<String>();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(resource, parent, false);
    }

    String item = items.get(position);

    if (item != null && view instanceof TextView) {
        ((TextView) view).setText(item);
    }

    return view;
}

@Override
public Filter getFilter() {
    return nameFilter;
}

Filter nameFilter = new Filter() {
    @Override
    public CharSequence convertResultToString(Object resultValue) {
        String str = (String) resultValue;
        return str;
    }

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        if (constraint != null) {
            suggestions.clear();
            for (String names : tempItems) {
                if (names.toLowerCase().contains(constraint.toString().toLowerCase())) {
                    suggestions.add(names);
                }
            }
            FilterResults filterResults = new FilterResults();
            filterResults.values = suggestions;
            filterResults.count = suggestions.size();
            return filterResults;
        } else {
            return new FilterResults();
        }
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        List<String> filterList = (ArrayList<String>) results.values;
        if (results != null && results.count > 0) {
            clear();
            for (String item : filterList) {
                add(item);
                notifyDataSetChanged();
            }
        }
    }
};

This should be your custom adapter class that u make.
In your main u call this class using constructor and it will look like this.

public class MainActivity extends AppCompatActivity {
AutoCompleteTextView ACTV;
List<String> suggestions = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ACTV = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
}
public void AutocmpleteMeth() {
    // Hieronder is het code voor Autocomplete [BEGIN]
    AutoSuggestAdapter adapter = new AutoSuggestAdapter(this, android.R.layout.simple_dropdown_item_1line, suggestions);
    ACTV.setAdapter(adapter);
    ACTV.setThreshold(1);

}}


来源: stackexchange

问:
How to set a column value :position to the :id of the item when creating new item with form
I have a List controller/model/whatever-you-would-call-it and when I create a new one with a form, I want to set the :position column to its :id. I don't know how I would do this.

BTW position is of type Integer.

My Ideas:

In the controller: lists_controller.rb, in the new method, or maybe the create method, add some code.

Somewhere in the form when setting the other attributes, sneak that position puppy in there.
(I only want to set position to id when creating new list, not updating though)

In the model itself set it.
(I do not want to set the :position to the :id when I am updating/editing, (only when creating new), the item so I am pretty sure this is not going to work)

Here is some code to potentially help:

_form.html.erb

```<code><%= form_with(model: @list) do |form| %>
  <div class='addField'>
    <%= form.text_field :name, placeholder: "Name" %>
    <%= form.text_field :description, placeholder: "Description" %>
    <%= form.check_box :private,class: 'check_box' %>
  </div>
  <div class='addLabel'>
    <div>
      <%= form.label :name %>
    </div>
    <div>
      <%= form.label :description %>
    </div>
    <div>
      <%= form.label :private %>
    </div>
  </div>
  <div id='submitNew'>
    <%= form.submit 'Done', :class => 'btn btn-primary' %>
  </div>
<% end %>
</code>```

lists_controller.rb

```<code>class ListsController < ApplicationController

  def new
    @list = List.new
  end

  def create
    @list = List.new(list_params)

    if @list.save
      redirect_to @list
    else
      render 'new'
    end
  end

  private
  def list_params
    params.require(:list).permit(:name, :description, :private)
  end
end
</code>```

This is just a snippet of the controller.

If you can point me in the right direction, I would appreciate it.

答:
You can modify your List model to something like this:

list.rb

```<code>class List < ApplicationRecord
  after_create :set_position
  .... existing model code ...

  private
  def set_position
    self.update_attribute(:position, self.id)
  end
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a List controller/model/whatever-you-would-call-it and when I create a new one with a form, I want to set the :position column to its :id. I don't know how I would do this.

BTW position is of type Integer.

My Ideas:

In the controller: lists_controller.rb, in the new method, or maybe the create method, add some code.

Somewhere in the form when setting the other attributes, sneak that position puppy in there.
(I only want to set position to id when creating new list, not updating though)

In the model itself set it.
(I do not want to set the :position to the :id when I am updating/editing, (only when creating new), the item so I am pretty sure this is not going to work)

Here is some code to potentially help:

_form.html.erb

<%= form_with(model: @list) do |form| %>

    <%= form.text_field :name, placeholder: "Name" %>
    <%= form.text_field :description, placeholder: "Description" %>
    <%= form.check_box :private,class: 'check_box' %>

      <%= form.label :name %>

      <%= form.label :description %>

      <%= form.label :private %>

    <%= form.submit 'Done', :class => 'btn btn-primary' %>

<% end %>

lists_controller.rb

class ListsController < ApplicationController

  def new
    @list = List.new
  end

  def create
    @list = List.new(list_params)

    if @list.save
      redirect_to @list
    else
      render 'new'
    end
  end

  private
  def list_params
    params.require(:list).permit(:name, :description, :private)
  end
end

This is just a snippet of the controller.

If you can point me in the right direction, I would appreciate it.

Body:
You can modify your List model to something like this:

list.rb

class List < ApplicationRecord
  after_create :set_position
  .... existing model code ...

  private
  def set_position
    self.update_attribute(:position, self.id)
  end
end


问:
CORS - Status 200 but error in Chrome devtools console
I have a problem with CORS, the problem is my code is executed (status 200) but I have an error in Google Chrome developer console.

My code:

```<code>function callUrl(url) {
    var xmlhttp = null;

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (xmlhttp !== null) {
        xmlhttp.open("POST", url, true);
        xmlhttp.withCredentials = true;
        xmlhttp.send(JSON.stringify({
        }));
    } else {
        console.error("Your browser does not support XMLHTTP.");
    }
}

callUrl('https://www.website.com/tracking?etc...');
</code>```

XMLHttpRequest cannot load https://www.website.com/tracking?. The
  value of the 'Access-Control-Allow-Origin' header in the response must
  not be the wildcard '*' when the request's credentials mode is
  'include'. Origin 'http://localhost:8888' is therefore not allowed
  access. The credentials mode of requests initiated by the
  XMLHttpRequest is controlled by the withCredentials attribute.

The server configuration:

```<code>"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
</code>```

答:
in Firefox you will get this error to... even if it's working and got status 200.

you can read about it in https://developer.mozilla.org/en-US/docs/Web/HTTP/Server-Side_Access_Control.

If you use the xmlhttp.withCredentials = true; you need to specify specific origin that allowed in the PHP code. if any source can call your API ... remove this attribute so you will be able to use "Access-Control-Allow-Origin": "*"

Body:
I have a problem with CORS, the problem is my code is executed (status 200) but I have an error in Google Chrome developer console.

My code:

function callUrl(url) {
    var xmlhttp = null;

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (xmlhttp !== null) {
        xmlhttp.open("POST", url, true);
        xmlhttp.withCredentials = true;
        xmlhttp.send(JSON.stringify({
        }));
    } else {
        console.error("Your browser does not support XMLHTTP.");
    }
}

callUrl('https://www.website.com/tracking?etc...');

XMLHttpRequest cannot load https://www.website.com/tracking?. The
  value of the 'Access-Control-Allow-Origin' header in the response must
  not be the wildcard '*' when the request's credentials mode is
  'include'. Origin 'http://localhost:8888' is therefore not allowed
  access. The credentials mode of requests initiated by the
  XMLHttpRequest is controlled by the withCredentials attribute.

The server configuration:

"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,


问:
Java JTextField cannot type
I have looked around all the threads on this subject, and I could not find a way to fix my problem.

I have a list of JPanels with some containing a JTextField.
The other panels with JButtons and JCheckboxes work perfectly.

The JTextField is selecteable, but I can't type in it. Here is the code used to generate the panel

```<code>        setSize(new Dimension(450, 33));

        JLabel lblPrefix = new JLabel(propertyToEdit.prefix);
        lblPrefix.setBounds(12, 16, 56, 16);
        add(lblPrefix);

        JTextField stringInputField = new JTextField();
        stringInputField.setEnabled(true);
        stringInputField.setEditable(true);
        stringInputField.setBounds(80, 13, 135, 22);
        stringInputField.setColumns(10);
        add(stringInputField);
</code>```

Here's the code on Github for the foolhardy :)

See code on Github

答:
Found the answer! It was because of this code

```<code>KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher
</code>```

On github.

Title: Java JTextField cannot type

Body:
I have looked around all the threads on this subject, and I could not find a way to fix my problem.

I have a list of JPanels with some containing a JTextField.
The other panels with JButtons and JCheckboxes work perfectly.

The JTextField is selecteable, but I can't type in it. Here is the code used to generate the panel

        setSize(new Dimension(450, 33));

        JLabel lblPrefix = new JLabel(propertyToEdit.prefix);
        lblPrefix.setBounds(12, 16, 56, 16);
        add(lblPrefix);

        JTextField stringInputField = new JTextField();
        stringInputField.setEnabled(true);
        stringInputField.setEditable(true);
        stringInputField.setBounds(80, 13, 135, 22);
        stringInputField.setColumns(10);
        add(stringInputField);

Here's the code on Github for the foolhardy :)

See code on Github

Body:
Found the answer! It was because of this code

KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher

On github.


问:
Excel VBA 4 step macro not executing last step - Range Error
I have the below which is made of several queries that I want to run in order but it appears that when I get to the last one it doesn't delete (tho the delete by itself works) can anyone help with this?

Desired Behavior:
Take some data on multiple sheets
Then Freeze the first row
Then Format it as a Table
Then resize, center and wrap text
Then search through all sheets and delete any row where the word "completed" exists.

Specific Problem:
It appeared that it was not doing the final step (removing all rows with the word completed)
Actually it was erring on the row  rDelete.EntireRow.Delete by stating "range error"

Shortest Code to Reproduce:
I think the below is the shortest code, other than just eliminating all but the last macro, but I am not sure if that would create other errors when trying to reproduce results.

Hope this addresses Mat's Mug's Comment below and is in line with the Minimal, Complete, and Verifiable example.

```<code>Sub TEST()
'
' Freeze_Panes Macro
'
' This one Freezes Row 1 (under Header)
    Dim s As Worksheet
    Dim c As Worksheet
' store current sheet
    Set c = ActiveSheet
' Stop flickering...
    Application.ScreenUpdating = False
' Loop throught the sheets
    For Each s In ActiveWorkbook.Worksheets

' Have to activate - SplitColumn and SplitRow are properties of ActiveSheet
    s.Activate

    With ActiveWindow
        .SplitColumn = 0
        .SplitRow = 1
'   .SplitRow = 2 'Depending on if it has a header maybe?
        .FreezePanes = True
    End With

    Next
' Back to original sheet
    c.Activate
    Application.ScreenUpdating = True

    Set s = Nothing
    Set c = Nothing
Call Format_As_Table
End Sub
Private Sub Format_As_Table()
'
' Format_As_Table Macro
'
' Declaration
Dim Tbl As ListObject
Dim Rng As Range
Dim sh As Worksheet

Application.ScreenUpdating = False
' Loop Through All Sheets and Format All Data as Table, then Orient as Landscape
For Each sh In ActiveWorkbook.Sheets
    With sh
        Set Rng = .Range(.Range("A1"), .Range("A1").SpecialCells(xlLastCell))
        Set Tbl = .ListObjects.Add(xlSrcRange, Rng, , xlYes)
        Tbl.TableStyle = "TableStyleMedium15"

        .PageSetup.Orientation = xlLandscape
    End With

Next sh
Application.ScreenUpdating = False
Call Resize_Columns_And_Rows_No_Header
End Sub
Private Sub Resize_Columns_And_Rows_No_Header()
'
'Resize_Columns_And_Rows Macro
'
'Declaration
  Dim wkSt As String
  Dim wkBk As Worksheet
  Dim temp As Variant
  Dim lastCol As Long

  wkSt = ActiveSheet.Name
' This Loops Through All Sheets
  For Each wkBk In ActiveWorkbook.Worksheets
      On Error Resume Next
      wkBk.Activate
      lastCol = wkBk.Cells(1, Columns.Count).End(xlToLeft).Column
'This is only needed if you are wrapping the text
      wkBk.Rows.WrapText = True
'This is to center align all rows
      'wkBk.Rows.VerticalAlignment = xlCenter
      wkBk.Rows.HorizontalAlignment = xlCenter
'Resize Columns due to size
      wkBk.Columns("F:F").ColumnWidth = 50
      wkBk.Columns("G:G").ColumnWidth = 50
' Resize Rows
      wkBk.Rows.EntireRow.AutoFit
' Resize Columns
      wkBk.Columns.EntireColumn.AutoFit
  Next wkBk
  Sheets(wkSt).Select
Call TestDeleteRows
End Sub

Private Sub TestDeleteRows()
Dim rFind As Range
Dim rDelete As Range
Dim strSearch As String
Dim sFirstAddress As String
Dim sh As Worksheet

strSearch = "Completed"
Set rDelete = Nothing

Application.ScreenUpdating = False
For Each sh In ActiveWorkbook.Sheets
With sh.Columns("A:AO")
Set rFind = .Find(strSearch, LookIn:=xlValues, LookAt:=xlPart, SearchDirection:=xlNext, MatchCase:=False)
If Not rFind Is Nothing Then
    sFirstAddress = rFind.Address
    Do
        If rDelete Is Nothing Then
            Set rDelete = rFind
        Else
            Set rDelete = Application.Union(rDelete, rFind)
        End If
        Set rFind = .FindNext(rFind)
    Loop While Not rFind Is Nothing And rFind.Address <> sFirstAddress

    rDelete.EntireRow.Delete
    Set rDelete = Nothing
End If
End With
Next sh
Application.ScreenUpdating = False
End Sub
</code>```

答:
It seems like you are working out a solution in the comments already. However, I just thought I'd mention the following:

Excel does not like it when you overlap selections and attempt to delete them. If you have the word "Completed" in multiple cells on the same row, you end up with an overlap with rDelete.EntireRow.Delete. Instead of creating a union of each cell that has "Complete" you should simple create a union of each ROW.

This can be done easily by changing

Set rDelete = Application.Union(rDelete, rFind)

to

Set rDelete = Application.Union(rDelete, Range("A" & rFind.Row))

This ultimately results in trying to union A1 with A1 (or whichever row) and does not create a duplicated reference in the range rDelete.

Body:
I have the below which is made of several queries that I want to run in order but it appears that when I get to the last one it doesn't delete (tho the delete by itself works) can anyone help with this?

Desired Behavior:
Take some data on multiple sheets
Then Freeze the first row
Then Format it as a Table
Then resize, center and wrap text
Then search through all sheets and delete any row where the word "completed" exists.

Specific Problem:
It appeared that it was not doing the final step (removing all rows with the word completed)
Actually it was erring on the row  rDelete.EntireRow.Delete by stating "range error"

Shortest Code to Reproduce:
I think the below is the shortest code, other than just eliminating all but the last macro, but I am not sure if that would create other errors when trying to reproduce results.

Hope this addresses Mat's Mug's Comment below and is in line with the Minimal, Complete, and Verifiable example.

Sub TEST()
'
' Freeze_Panes Macro
'
' This one Freezes Row 1 (under Header)
    Dim s As Worksheet
    Dim c As Worksheet
' store current sheet
    Set c = ActiveSheet
' Stop flickering...
    Application.ScreenUpdating = False
' Loop throught the sheets
    For Each s In ActiveWorkbook.Worksheets

' Have to activate - SplitColumn and SplitRow are properties of ActiveSheet
    s.Activate

    With ActiveWindow
        .SplitColumn = 0
        .SplitRow = 1
'   .SplitRow = 2 'Depending on if it has a header maybe?
        .FreezePanes = True
    End With

    Next
' Back to original sheet
    c.Activate
    Application.ScreenUpdating = True

    Set s = Nothing
    Set c = Nothing
Call Format_As_Table
End Sub
Private Sub Format_As_Table()
'
' Format_As_Table Macro
'
' Declaration
Dim Tbl As ListObject
Dim Rng As Range
Dim sh As Worksheet

Application.ScreenUpdating = False
' Loop Through All Sheets and Format All Data as Table, then Orient as Landscape
For Each sh In ActiveWorkbook.Sheets
    With sh
        Set Rng = .Range(.Range("A1"), .Range("A1").SpecialCells(xlLastCell))
        Set Tbl = .ListObjects.Add(xlSrcRange, Rng, , xlYes)
        Tbl.TableStyle = "TableStyleMedium15"

        .PageSetup.Orientation = xlLandscape
    End With

Next sh
Application.ScreenUpdating = False
Call Resize_Columns_And_Rows_No_Header
End Sub
Private Sub Resize_Columns_And_Rows_No_Header()
'
'Resize_Columns_And_Rows Macro
'
'Declaration
  Dim wkSt As String
  Dim wkBk As Worksheet
  Dim temp As Variant
  Dim lastCol As Long

  wkSt = ActiveSheet.Name
' This Loops Through All Sheets
  For Each wkBk In ActiveWorkbook.Worksheets
      On Error Resume Next
      wkBk.Activate
      lastCol = wkBk.Cells(1, Columns.Count).End(xlToLeft).Column
'This is only needed if you are wrapping the text
      wkBk.Rows.WrapText = True
'This is to center align all rows
      'wkBk.Rows.VerticalAlignment = xlCenter
      wkBk.Rows.HorizontalAlignment = xlCenter
'Resize Columns due to size
      wkBk.Columns("F:F").ColumnWidth = 50
      wkBk.Columns("G:G").ColumnWidth = 50
' Resize Rows
      wkBk.Rows.EntireRow.AutoFit
' Resize Columns
      wkBk.Columns.EntireColumn.AutoFit
  Next wkBk
  Sheets(wkSt).Select
Call TestDeleteRows
End Sub

Private Sub TestDeleteRows()
Dim rFind As Range
Dim rDelete As Range
Dim strSearch As String
Dim sFirstAddress As String
Dim sh As Worksheet

strSearch = "Completed"
Set rDelete = Nothing

Application.ScreenUpdating = False
For Each sh In ActiveWorkbook.Sheets
With sh.Columns("A:AO")
Set rFind = .Find(strSearch, LookIn:=xlValues, LookAt:=xlPart, SearchDirection:=xlNext, MatchCase:=False)
If Not rFind Is Nothing Then
    sFirstAddress = rFind.Address
    Do
        If rDelete Is Nothing Then
            Set rDelete = rFind
        Else
            Set rDelete = Application.Union(rDelete, rFind)
        End If
        Set rFind = .FindNext(rFind)
    Loop While Not rFind Is Nothing And rFind.Address <> sFirstAddress

    rDelete.EntireRow.Delete
    Set rDelete = Nothing
End If
End With
Next sh
Application.ScreenUpdating = False
End Sub


问:
Identify duplicates in a List
I have a List of type Integer eg:

```<code>[1, 1, 2, 3, 3, 3]
</code>```

I would like a method to return all the duplicates eg:

```<code>[1, 3]
</code>```

What is the best way to do this?

答:
```<code>import java.util.Scanner;

public class OnlyDuplicates {
    public static void main(String[] args) {
        System.out.print(" Enter a set of 10 numbers: ");
        int[] numbers = new int[10];
        Scanner input = new Scanner(System.in);
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = input.nextInt();
        }
        numbers = onlyDuplicates(numbers);
        System.out.print(" The numbers are: ");
        for (int i = 0; i < numbers.length; i++) {
            System.out.print(numbers[i] + "");
        }
    }

    public static int[] onlyDuplicates(int[] list) {
        boolean flag = true;
        int[] array = new int[0];
        array = add2Array(array, list[0]);
        for (int i = 0; i < list.length; i++) {
            for (int j = 0; j < array.length; j++) {
                if (list[i] == array[j]) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                array = add2Array(array, list[i]);
            }
            flag = true;
        }
        return array;
    }
    // Copy numbers1 to numbers2
    // If the length of numbers2 is less then numbers2, return false
    public static boolean copyArray(int[] source, int[] dest) {
        if (source.length > dest.length) {
            return false;
        }

        for (int i = 0; i < source.length; i++) {
            dest[i] = source[i];
        }
        return true;
    }
    // Increase array size by one and add integer to the end of the array
    public static int[] add2Array(int[] source, int data) {
        int[] dest = new int[source.length + 1];
        copyArray(source, dest);
        dest[source.length] = data;
        return dest;
    }
}
</code>```

Title: Identify duplicates in a List

Body:
I have a List of type Integer eg:

[1, 1, 2, 3, 3, 3]

I would like a method to return all the duplicates eg:

[1, 3]

What is the best way to do this?


问:
Could not change the content type of a Document list item in a document library
I'm programatically changing the content type of a document in a document library. But document is getting added with the content type only.

Here is my coding:

```<code>SPFile ofile = oweb.GetFile(oweb.Url + '/' + oDocSet.Item.Url + '/' + refName);
ofile.Item["Content Type"] = octype.Name;
ofile.Item["Content Type ID"] = octype.Id;
ofile.Item.Update();
</code>```

when i traced the above coding the content type is getting changed when i assign them to the item but after I update the the item in the last line the content type of the item is getting set to the default content type.

答:
Shouldn't it be:

```<code>SPFile ofile = oweb.GetFile(oweb.Url + '/' + oDocSet.Item.Url + '/' + refName);
ofile.Item["ContentType"] = octype.Name;
ofile.Item["ContentTypeId"] = octype.Id;
ofile.Item.Update();
</code>```

Note the lack of spaces in the field names

P.S.: Is the content type actually allowed in the library?

Body:
I'm programatically changing the content type of a document in a document library. But document is getting added with the content type only.

Here is my coding:

SPFile ofile = oweb.GetFile(oweb.Url + '/' + oDocSet.Item.Url + '/' + refName);
ofile.Item["Content Type"] = octype.Name;
ofile.Item["Content Type ID"] = octype.Id;
ofile.Item.Update();

when i traced the above coding the content type is getting changed when i assign them to the item but after I update the the item in the last line the content type of the item is getting set to the default content type.

Body:
Shouldn't it be:

SPFile ofile = oweb.GetFile(oweb.Url + '/' + oDocSet.Item.Url + '/' + refName);
ofile.Item["ContentType"] = octype.Name;
ofile.Item["ContentTypeId"] = octype.Id;
ofile.Item.Update();

Note the lack of spaces in the field names

P.S.: Is the content type actually allowed in the library?

ContentLicense: CC BY-SA 2.5


问:
Object is not a constructor after react-native 0.49 update
After updating react native from 0.45.x to 0.50.3 (and renaming index.ios.js to index.js as indicated) I get this error in index.js (previous index.ios.js):
"Object is not a constructor (evaluating 'new _app2.default()')"

Here is my index.js file

```<code>import { AppRegistry } from 'react-native';
import App from './app/';

const app = new App();

AppRegistry.registerComponent('airand', () => app);
</code>```

And here is my app/index.js file:

```<code>import { Platform, Linking } from 'react-native'
import { Provider } from "react-redux"
import allReducers from "./reducers"
import { Navigation } from 'react-native-navigation'
import RCTSFSafariViewController from 'react-native-sfsafariviewcontroller'
import FontAwesome from 'react-native-vector-icons/FontAwesome'

import registerScreens from './screens/'
import Token from './services/token'
import Api from './services/api'
import configureStore from './store/configureStore'
// import { login, logout } from './reducers/app-root/actions'
import defaultFitlerData from './constants/nearby-cte.js'

const store = configureStore();

registerScreens(store, Provider);

export default class App {

    constructor() {
        this._populateTabBarIcons().then(() => {
            this._startApp();
            this._checkUserLoggedIn();
            store.subscribe(() => this._actionListener());
        });
        // handle linking
        Linking.getInitialURL().then((url) => {
            if (url) {
                this._handleOpenURL(url);
            }
        }).catch((e) => {})
        Linking.addEventListener('url', (event) => this._handleOpenURL(event.url));
    };
    _populateTabBarIcons () {
        return new Promise((resolve, reject) => {
            Promise.all([
                    FontAwesome.getImageSource('map-marker', 30),
                    FontAwesome.getImageSource('map-marker', 30),
                    FontAwesome.getImageSource('ellipsis-h', 30),
                    FontAwesome.getImageSource('ellipsis-h', 30),
                    FontAwesome.getImageSource('plus-square-o', 30),
                    FontAwesome.getImageSource('plus-square', 30),
                    FontAwesome.getImageSource('comment-o', 30),
                    FontAwesome.getImageSource('comment', 30),
                    FontAwesome.getImageSource('user-o', 30),
                    FontAwesome.getImageSource('user', 30)
            ]).then((values) => {
                this.tabBarIcons = [];
                this.selectedTabBarIcons = [];
                for (var i = 0; i < values.length; i += 2) {
                    this.tabBarIcons.push(values[i]);
                    this.selectedTabBarIcons.push(values[i+1]);
                }
                resolve(true);
            }).catch((error) => {
                reject(error);
            }).done();
        });
    };
    componentWillUnmount() {
        // TODO: find a way to call this
        Linking.removeEventListener('url', (event) => this._handleOpenURL(event.url));
    };
    _getParameterByName(name, url) {
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    };
    async _handleOpenURL(url) {
        const pathName = url.split('://')[1].split('?')[0];
        if (pathName.indexOf('login_successful') != -1) {
            const code = this._getParameterByName('code', url);
            if (code) {
                let response = await Api.getTokenFromCode(code);
                if (response.status == 200) {
                    this._checkUserLoggedIn();
                }
            }
        }
        RCTSFSafariViewController.close();
    };
    async _checkUserLoggedIn() {
        let isValid = await Token.isValidRefreshToken();
        if (isValid) {
          this._startApp('logged-in')
        } else {
          this._startApp('logged-out')
        }
    };
    _actionListener() {
        let currentRoot = store.getState().appRoot.root;
        if (currentRoot != lastRoot)
        this._startApp(currentRoot);
    };
    _getTabs() {
        const tabLabel = ['Nearby', 'Pending', 'New', 'Chat', 'Profile'];
        const screens = [
            'airand.NearbyServices',
            'airand.PendingServicesScreen',
            'airand.NewServiceScreen',
            'airand.ChatScreen',
            'airand.Profile'
        ];
        var tabs = [];
        for (var i = 0; i < screens.length; i++) {
            tabs.push({
                icon: this.tabBarIcons[i],
                selectedIcon: this.selectedTabBarIcons[i],
                screen: screens[i]
            });
        };
        return tabs;
    };
    async _startApp(root = null) {
      lastRoot = root
        switch(root) {
            case 'logged-in':
                self.logged_in = true
                Navigation.startTabBasedApp({
                    tabs: this._getTabs(),
                    animationType: 'slide-down',
                    title: 'Redux Example',
                    tabsStyle: {
                        tabBarButtonColor: '#979797',
                        tabBarSelectedButtonColor: '#f79100',
                    }
                });
                return
            case 'logged-out':
                Navigation.startSingleScreenApp({
                    screen: { screen: 'airand.LoginScreen' }
                });
                return
            default:
                Navigation.startSingleScreenApp({
                    screen: { screen: 'airand.LoadingScreen' }
                });
                return
        }
    };
}
</code>```

It seems like a stupid error but I've spent hours on this so please any help would be appreciated, I have tried commenting some stuff to almost everything in app/index.js but no luck.

Thank you!

答:
I think your problem is this...

```<code>const app = new App();
</code>```

It's telling you that App() is not a constructor function.

Try changing your {root}/index.js to this...

```<code>import { AppRegistry } from 'react-native';
import App from './app/';

AppRegistry.registerComponent('airand', () => App);
</code>```

Body:
After updating react native from 0.45.x to 0.50.3 (and renaming index.ios.js to index.js as indicated) I get this error in index.js (previous index.ios.js):
"Object is not a constructor (evaluating 'new _app2.default()')"

Here is my index.js file

import { AppRegistry } from 'react-native';
import App from './app/';

const app = new App();

AppRegistry.registerComponent('airand', () => app);

And here is my app/index.js file:

import { Platform, Linking } from 'react-native'
import { Provider } from "react-redux"
import allReducers from "./reducers"
import { Navigation } from 'react-native-navigation'
import RCTSFSafariViewController from 'react-native-sfsafariviewcontroller'
import FontAwesome from 'react-native-vector-icons/FontAwesome'

import registerScreens from './screens/'
import Token from './services/token'
import Api from './services/api'
import configureStore from './store/configureStore'
// import { login, logout } from './reducers/app-root/actions'
import defaultFitlerData from './constants/nearby-cte.js'

const store = configureStore();

registerScreens(store, Provider);

export default class App {

    constructor() {
        this._populateTabBarIcons().then(() => {
            this._startApp();
            this._checkUserLoggedIn();
            store.subscribe(() => this._actionListener());
        });
        // handle linking
        Linking.getInitialURL().then((url) => {
            if (url) {
                this._handleOpenURL(url);
            }
        }).catch((e) => {})
        Linking.addEventListener('url', (event) => this._handleOpenURL(event.url));
    };
    _populateTabBarIcons () {
        return new Promise((resolve, reject) => {
            Promise.all([
                    FontAwesome.getImageSource('map-marker', 30),
                    FontAwesome.getImageSource('map-marker', 30),
                    FontAwesome.getImageSource('ellipsis-h', 30),
                    FontAwesome.getImageSource('ellipsis-h', 30),
                    FontAwesome.getImageSource('plus-square-o', 30),
                    FontAwesome.getImageSource('plus-square', 30),
                    FontAwesome.getImageSource('comment-o', 30),
                    FontAwesome.getImageSource('comment', 30),
                    FontAwesome.getImageSource('user-o', 30),
                    FontAwesome.getImageSource('user', 30)
            ]).then((values) => {
                this.tabBarIcons = [];
                this.selectedTabBarIcons = [];
                for (var i = 0; i < values.length; i += 2) {
                    this.tabBarIcons.push(values[i]);
                    this.selectedTabBarIcons.push(values[i+1]);
                }
                resolve(true);
            }).catch((error) => {
                reject(error);
            }).done();
        });
    };
    componentWillUnmount() {
        // TODO: find a way to call this
        Linking.removeEventListener('url', (event) => this._handleOpenURL(event.url));
    };
    _getParameterByName(name, url) {
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    };
    async _handleOpenURL(url) {
        const pathName = url.split('://')[1].split('?')[0];
        if (pathName.indexOf('login_successful') != -1) {
            const code = this._getParameterByName('code', url);
            if (code) {
                let response = await Api.getTokenFromCode(code);
                if (response.status == 200) {
                    this._checkUserLoggedIn();
                }
            }
        }
        RCTSFSafariViewController.close();
    };
    async _checkUserLoggedIn() {
        let isValid = await Token.isValidRefreshToken();
        if (isValid) {
          this._startApp('logged-in')
        } else {
          this._startApp('logged-out')
        }
    };
    _actionListener() {
        let currentRoot = store.getState().appRoot.root;
        if (currentRoot != lastRoot)
        this._startApp(currentRoot);
    };
    _getTabs() {
        const tabLabel = ['Nearby', 'Pending', 'New', 'Chat', 'Profile'];
        const screens = [
            'airand.NearbyServices',
            'airand.PendingServicesScreen',
            'airand.NewServiceScreen',
            'airand.ChatScreen',
            'airand.Profile'
        ];
        var tabs = [];
        for (var i = 0; i < screens.length; i++) {
            tabs.push({
                icon: this.tabBarIcons[i],
                selectedIcon: this.selectedTabBarIcons[i],
                screen: screens[i]
            });
        };
        return tabs;
    };
    async _startApp(root = null) {
      lastRoot = root
        switch(root) {
            case 'logged-in':
                self.logged_in = true
                Navigation.startTabBasedApp({
                    tabs: this._getTabs(),
                    animationType: 'slide-down',
                    title: 'Redux Example',
                    tabsStyle: {
                        tabBarButtonColor: '#979797',
                        tabBarSelectedButtonColor: '#f79100',
                    }
                });
                return
            case 'logged-out':
                Navigation.startSingleScreenApp({
                    screen: { screen: 'airand.LoginScreen' }
                });
                return
            default:
                Navigation.startSingleScreenApp({
                    screen: { screen: 'airand.LoadingScreen' }
                });
                return
        }
    };
}

It seems like a stupid error but I've spent hours on this so please any help would be appreciated, I have tried commenting some stuff to almost everything in app/index.js but no luck.

Thank you!

Body:
I think your problem is this...

const app = new App();

It's telling you that App() is not a constructor function.

Try changing your {root}/index.js to this...

import { AppRegistry } from 'react-native';
import App from './app/';

AppRegistry.registerComponent('airand', () => App);


问:
Powershell Checkbox that selects other checkboxes
I have a basic form UI in powershell.  I have a series of 3 individual checkboxes with the following code:

```<code>    $CBlabel = New-Object System.Windows.Forms.Label
    $CBlabel .Location = New-Object System.Drawing.Point(10,125)
    $CBlabel .Size = New-Object System.Drawing.Size(280,20)
    $CBlabel .Text = "Select a box:"
    $form.Controls.Add($CBlabel )

    $cb1Checkbox = New-Object System.Windows.Forms.Checkbox
    $cb1Checkbox .Location = New-Object System.Drawing.Size(10,145)
    $cb1Checkbox .Size = New-Object System.Drawing.Size(280,20)
    $cb1Checkbox .Text = "Checkbox 1"
    $form.Controls.Add($cb1Checkbox )

    $cb2Checkbox = New-Object System.Windows.Forms.Checkbox
    $cb2Checkbox .Location = New-Object System.Drawing.Size(10,165)
    $cb2Checkbox .Size = New-Object System.Drawing.Size(280,20)
    $cb2Checkbox .Text = "Checkbox 2"
    $form.Controls.Add($cb2Checkbox )

    $cb3Checkbox = New-Object System.Windows.Forms.Checkbox
    $cb3Checkbox .Location = New-Object System.Drawing.Size(10,185)
    $cb3Checkbox .Size = New-Object System.Drawing.Size(280,20)
    $cb3Checkbox .Text = "Checkbox 3"
    $form.Controls.Add($cb3Checkbox )
</code>```

I would like to add a 4th checkbox below this that says "Select All" and have it be dynamic if possible.  If I select it, it automatically selects checkboxes 1, 2, and 3.  If I unselect checkbox 2 (or any other checkbox), it automatically unselects the "Select All" checkbox.  Is this possible?

答:
Maybe this is a possible solution?

```<code>$cb4Checkbox = New-Object System.Windows.Forms.Checkbox
$cb4Checkbox.Location = New-Object System.Drawing.Size(x,y)
$cb4Checkbox.Size = New-Object System.Drawing.Size(x,y)
$cb4Checkbox.Text = "Checkbox 4 - Select All"
$cb4Checkbox.Add_Click({
    If ($cb4CheckBox.Checked -eq $true){
        $cb1Checkbox.Checked = $true
        $cb2Checkbox.Checked = $true
        $cb3Checkbox.Checked = $true
    }
})
$form.Controls.Add($cb4Checkbox)
</code>```

For your request of unchecking the 'select all' checkbox, you would need to do a .add_click for all of your first three checkboxes that would cause the 'select all' checkbox to become unchecked. I believe a better way to do this would be to write a function that you could reference when any of the first three checkboxes are clicked on, and have it uncheck the 'select all' checkbox (see below)

```<code>function Uncheck-SelectAllBox
{
    $cb4Checkbox.Checked = $false
}

$CBlabel = New-Object System.Windows.Forms.Label
$CBlabel.Location = New-Object System.Drawing.Point(10,125)
$CBlabel.Size = New-Object System.Drawing.Size(280,20)
$CBlabel.Text = "Select a box:"
$form.Controls.Add($CBlabel)

$cb1Checkbox = New-Object System.Windows.Forms.Checkbox
$cb1Checkbox .Location = New-Object System.Drawing.Size(10,145)
$cb1Checkbox .Size = New-Object System.Drawing.Size(280,20)
$cb1Checkbox .Text = "Checkbox 1"
$cb1Checkbox.add_click({ Uncheck-SelectAllBox })
$form.Controls.Add($cb1Checkbox)

$cb2Checkbox = New-Object System.Windows.Forms.Checkbox
$cb2Checkbox .Location = New-Object System.Drawing.Size(10,165)
$cb2Checkbox .Size = New-Object System.Drawing.Size(280,20)
$cb2Checkbox .Text = "Checkbox 2"
$cb2Checkbox.add_click({ Uncheck-SelectAllBox })
$form.Controls.Add($cb2Checkbox)

$cb3Checkbox = New-Object System.Windows.Forms.Checkbox
$cb3Checkbox .Location = New-Object System.Drawing.Size(10,185)
$cb3Checkbox .Size = New-Object System.Drawing.Size(280,20)
$cb3Checkbox .Text = "Checkbox 3"
$cb3Checkbox.add_click({ Uncheck-SelectAllBox })
$form.Controls.Add($cb3Checkbox)

$cb4Checkbox = New-Object System.Windows.Forms.Checkbox
$cb4Checkbox.Location = New-Object System.Drawing.Size(x,y)
$cb4Checkbox.Size = New-Object System.Drawing.Size(x,y)
$cb4Checkbox.Text = "Checkbox 4 - Select All"
$cb4Checkbox.Add_Click({
    If ($cb4CheckBox.Checked -eq $true){
        $cb1Checkbox.Checked = $true
        $cb2Checkbox.Checked = $true
        $cb3Checkbox.Checked = $true
    }
})
$form.Controls.Add($cb4Checkbox)
</code>```

Body:
I have a basic form UI in powershell.  I have a series of 3 individual checkboxes with the following code:

    $CBlabel = New-Object System.Windows.Forms.Label
    $CBlabel .Location = New-Object System.Drawing.Point(10,125)
    $CBlabel .Size = New-Object System.Drawing.Size(280,20)
    $CBlabel .Text = "Select a box:"
    $form.Controls.Add($CBlabel )

    $cb1Checkbox = New-Object System.Windows.Forms.Checkbox
    $cb1Checkbox .Location = New-Object System.Drawing.Size(10,145)
    $cb1Checkbox .Size = New-Object System.Drawing.Size(280,20)
    $cb1Checkbox .Text = "Checkbox 1"
    $form.Controls.Add($cb1Checkbox )

    $cb2Checkbox = New-Object System.Windows.Forms.Checkbox
    $cb2Checkbox .Location = New-Object System.Drawing.Size(10,165)
    $cb2Checkbox .Size = New-Object System.Drawing.Size(280,20)
    $cb2Checkbox .Text = "Checkbox 2"
    $form.Controls.Add($cb2Checkbox )

    $cb3Checkbox = New-Object System.Windows.Forms.Checkbox
    $cb3Checkbox .Location = New-Object System.Drawing.Size(10,185)
    $cb3Checkbox .Size = New-Object System.Drawing.Size(280,20)
    $cb3Checkbox .Text = "Checkbox 3"
    $form.Controls.Add($cb3Checkbox )

I would like to add a 4th checkbox below this that says "Select All" and have it be dynamic if possible.  If I select it, it automatically selects checkboxes 1, 2, and 3.  If I unselect checkbox 2 (or any other checkbox), it automatically unselects the "Select All" checkbox.  Is this possible?

Body:
Maybe this is a possible solution?

$cb4Checkbox = New-Object System.Windows.Forms.Checkbox
$cb4Checkbox.Location = New-Object System.Drawing.Size(x,y)
$cb4Checkbox.Size = New-Object System.Drawing.Size(x,y)
$cb4Checkbox.Text = "Checkbox 4 - Select All"
$cb4Checkbox.Add_Click({
    If ($cb4CheckBox.Checked -eq $true){
        $cb1Checkbox.Checked = $true
        $cb2Checkbox.Checked = $true
        $cb3Checkbox.Checked = $true
    }
})
$form.Controls.Add($cb4Checkbox)

For your request of unchecking the 'select all' checkbox, you would need to do a .add_click for all of your first three checkboxes that would cause the 'select all' checkbox to become unchecked. I believe a better way to do this would be to write a function that you could reference when any of the first three checkboxes are clicked on, and have it uncheck the 'select all' checkbox (see below)

function Uncheck-SelectAllBox
{
    $cb4Checkbox.Checked = $false
}

$CBlabel = New-Object System.Windows.Forms.Label
$CBlabel.Location = New-Object System.Drawing.Point(10,125)
$CBlabel.Size = New-Object System.Drawing.Size(280,20)
$CBlabel.Text = "Select a box:"
$form.Controls.Add($CBlabel)

$cb1Checkbox = New-Object System.Windows.Forms.Checkbox
$cb1Checkbox .Location = New-Object System.Drawing.Size(10,145)
$cb1Checkbox .Size = New-Object System.Drawing.Size(280,20)
$cb1Checkbox .Text = "Checkbox 1"
$cb1Checkbox.add_click({ Uncheck-SelectAllBox })
$form.Controls.Add($cb1Checkbox)

$cb2Checkbox = New-Object System.Windows.Forms.Checkbox
$cb2Checkbox .Location = New-Object System.Drawing.Size(10,165)
$cb2Checkbox .Size = New-Object System.Drawing.Size(280,20)
$cb2Checkbox .Text = "Checkbox 2"
$cb2Checkbox.add_click({ Uncheck-SelectAllBox })
$form.Controls.Add($cb2Checkbox)

$cb3Checkbox = New-Object System.Windows.Forms.Checkbox
$cb3Checkbox .Location = New-Object System.Drawing.Size(10,185)
$cb3Checkbox .Size = New-Object System.Drawing.Size(280,20)
$cb3Checkbox .Text = "Checkbox 3"
$cb3Checkbox.add_click({ Uncheck-SelectAllBox })
$form.Controls.Add($cb3Checkbox)

$cb4Checkbox = New-Object System.Windows.Forms.Checkbox
$cb4Checkbox.Location = New-Object System.Drawing.Size(x,y)
$cb4Checkbox.Size = New-Object System.Drawing.Size(x,y)
$cb4Checkbox.Text = "Checkbox 4 - Select All"
$cb4Checkbox.Add_Click({
    If ($cb4CheckBox.Checked -eq $true){
        $cb1Checkbox.Checked = $true
        $cb2Checkbox.Checked = $true
        $cb3Checkbox.Checked = $true
    }
})
$form.Controls.Add($cb4Checkbox)


问:
While loop to repeat actionPerformed of a JButton
I've got a JFrame with some JButtons. The "update" button (named JButton1) executes a number of queries which fill a form.
Now I'd like another JButton to be the "automatic update" (named JButton2), so I would like it to loop inside the JButton1ActionPerformed method, until JButton2 is no longer selected.
When I press JButton2 the window freezes.

Is my code right? Do you think I would need a stop button?

```<code>private void jToggleButton2ActionPerformed(java.awt.event.ActionEvent evt) {

       long start = System.currentTimeMillis();
       if(jToggleButton2.isSelected()){
           start = System.currentTimeMillis();

            do{
                do{
                    jButton1ActionPerformed(evt);
                }
                while(System.currentTimeMillis()-start>3000);

            }
            while(jToggleButton2.isSelected());
       }

        if(jToggleButton2.isSelected()){
            jToggleButton2.setSelected(false);
        }

    }
</code>```

答:
Swing is:

Single threaded; this means that you should not perform any long running or blocking operations within the context of the Event Dispatching Thread

Not thread safe; this means you should not update the UI or anything the UI might depend on outside of the EDT. It's also risky to try and address UI elements outside the EDT, as the thread model might return false values

Without more context to your problem, I might suggest using a Swing Timer.  Two main reasons:

The ActionListener is called within the context of the EDT, making it safe to update the UI from within in

You can specify a delay between updates, which reduces the risk of overloading the EDT which will cause performance issues

For example...

```<code>private void jToggleButton2ActionPerformed(java.awt.event.ActionEvent evt) {

    long start = System.currentTimeMillis();
    if (jToggleButton2.isSelected()) {
        // You could use an instance field instead and determine
        // if the Timer is already running or not
        Timer timer = new Timer(100, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!jToggleButton2.isSelected()) {
                    ((Timer) e.getSource()).stop();
                    return;
                }
                jButton1ActionPerformed(evt);
            }
        });
        timer.start();

        // Just want to point out that this doesn't make sense
        // As if the button was selected, you'd still be in
        // your previous loop
        //if (jToggleButton2.isSelected()) {
        //  jToggleButton2.setSelected(false);
        //}
    }
}
</code>```

Another solution might be to use a SwingWorker, which provides you with a means to perform long running or blocking operations off the EDT, but which also provides functionality to update the UI safely from within the EDT.

Take a look at:

Concurrency in Swing

Worker Threads and SwingWorker

How to Use Swing Timers

for more details

Body:
I've got a JFrame with some JButtons. The "update" button (named JButton1) executes a number of queries which fill a form.
Now I'd like another JButton to be the "automatic update" (named JButton2), so I would like it to loop inside the JButton1ActionPerformed method, until JButton2 is no longer selected.
When I press JButton2 the window freezes.

Is my code right? Do you think I would need a stop button?

private void jToggleButton2ActionPerformed(java.awt.event.ActionEvent evt) {

       long start = System.currentTimeMillis();
       if(jToggleButton2.isSelected()){
           start = System.currentTimeMillis();

            do{
                do{
                    jButton1ActionPerformed(evt);
                }
                while(System.currentTimeMillis()-start>3000);

            }
            while(jToggleButton2.isSelected());
       }

        if(jToggleButton2.isSelected()){
            jToggleButton2.setSelected(false);
        }

    }

Body:
Swing is:

Single threaded; this means that you should not perform any long running or blocking operations within the context of the Event Dispatching Thread

Not thread safe; this means you should not update the UI or anything the UI might depend on outside of the EDT. It's also risky to try and address UI elements outside the EDT, as the thread model might return false values

Without more context to your problem, I might suggest using a Swing Timer.  Two main reasons:

The ActionListener is called within the context of the EDT, making it safe to update the UI from within in

You can specify a delay between updates, which reduces the risk of overloading the EDT which will cause performance issues

For example...

private void jToggleButton2ActionPerformed(java.awt.event.ActionEvent evt) {

    long start = System.currentTimeMillis();
    if (jToggleButton2.isSelected()) {
        // You could use an instance field instead and determine
        // if the Timer is already running or not
        Timer timer = new Timer(100, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!jToggleButton2.isSelected()) {
                    ((Timer) e.getSource()).stop();
                    return;
                }
                jButton1ActionPerformed(evt);
            }
        });
        timer.start();

        // Just want to point out that this doesn't make sense
        // As if the button was selected, you'd still be in
        // your previous loop
        //if (jToggleButton2.isSelected()) {
        //  jToggleButton2.setSelected(false);
        //}
    }
}

Another solution might be to use a SwingWorker, which provides you with a means to perform long running or blocking operations off the EDT, but which also provides functionality to update the UI safely from within the EDT.

Take a look at:

Concurrency in Swing

Worker Threads and SwingWorker

How to Use Swing Timers

for more details


问:
How to rotate custom marker in chart.js?
I have this problem - I want my chart to have custom markers (points) that rotate depending on the value from the dataset.
I have my custom markers (arrows), but I don't know how to rotate them.
I am using Chart.js

My JS Code:

```<code>    var canvas = document.getElementById('myChart');
    var ctx = canvas.getContext('2d');

    var yourImage = new Image(30, 30);
    yourImage.src = 'arrow.png';
    var myChart = new Chart(canvas, {
      type: 'scatter',
      data: {
       datasets: [{
        label: 'Scatter Dataset',
        data: [{
            x: 1,
            y: 1.45
            }, {
            x: 2,
            y: 0.25
            }, {
            x: 3,
            y: 2.56
            }, {
            x: 4,
            y: 1.65
           }],
           pointStyle: yourImage,
       }]
    },
    options: {
    scales: {
           xAxes: [{
               type: 'linear',
               position: 'bottom'
           }]
          }
       }
    });
</code>```

答:
It looks like you will need to add in code to the drawPoint function within helpers.canvas.js.  If the point is an image object, rotate the canvas as needed, draw the image, then rotate the context back to standard orientation.  An example of doing this is here.

I don't know enough about the library and the toolchain to be able to write functional code, but those 2 links should get you started.

Body:
I have this problem - I want my chart to have custom markers (points) that rotate depending on the value from the dataset.
I have my custom markers (arrows), but I don't know how to rotate them.
I am using Chart.js

My JS Code:

    var canvas = document.getElementById('myChart');
    var ctx = canvas.getContext('2d');

    var yourImage = new Image(30, 30);
    yourImage.src = 'arrow.png';
    var myChart = new Chart(canvas, {
      type: 'scatter',
      data: {
       datasets: [{
        label: 'Scatter Dataset',
        data: [{
            x: 1,
            y: 1.45
            }, {
            x: 2,
            y: 0.25
            }, {
            x: 3,
            y: 2.56
            }, {
            x: 4,
            y: 1.65
           }],
           pointStyle: yourImage,
       }]
    },
    options: {
    scales: {
           xAxes: [{
               type: 'linear',
               position: 'bottom'
           }]
          }
       }
    });


问:
How to properly test this controller action with Shoulda?
I have the following controller action and test.  I'm new to testing with Shoulda and I know there are areas of my controller that I can test further.  For example, my flash messages as well as verifying the renders.

So my question is, how would I properly test this controller action in Shoulda?

My controller action (names have been changed to protect the innocent):

```<code>def my_action
  return redirect_to(root_url) if @site.nil?
  @owner = current_site.owner
  if request.post?
    if params[:password].blank? || params[:email].blank?
      flash[:error] = "You must fill in both the e-mail and password fields"
      render :action => "my_action"
    else
      if @owner.authenticated?(params[:password])
        @owner.login = params[:email]
        @owner.save!
        @owner.do_some_method
        flash[:success] = "Success."
        render :action => "my_action"
      else
        flash[:error] = "Incorrect password"
        render :action => "my_action"
      end
    end
  end
end
</code>```

My test:

```<code>context "on POST to :my_action" do
  setup do
    Owner.any_instance().expects(:do_some_method)
    post :my_action, :email => 'foo@bar.com', :password => 'test'
  end
  should_assign_to :owner
  should "Change name and verify password and resend activation key" do
    assert_equal true, assigns(:owner).authenticated?('test')
    assert_equal 'foo@bar.com', assigns(:owner).login
  end
  should_respond_with :success
end
</code>```

答:
Right now, it appears that you're testing functionality specific to the model inside your controller, that should be in a unit test.

I would advise re-factoring your controller to include the required logic for updating the Owner's email inside the Owner model. By doing that, you should be able to simplify the controller down to a simple if update; else; end type statement and greatly simplify the controller test. Once you've moved the logic into the model, you can use built in Rails validations.

A couple of other things to consider:

Redirecting after your POST action completes, prevents the user from double-posting by accident (most browsers will complain when the user attempts it).

Move the checking for @site and also the assignment to @owner to before_filters if this is done more than once inside the controller.

You can avoid having to check if request.post? with either verify or creating a route in `config/routes.rb'.

References:

Skinny Controller, Fat Model

RailsConf Recap: Skinny Controllers

ActionController::Filters::ClassMethods

ActionController::Verification::ClassMethods

OwnerDisplayName: mwilliams

Body:
I have the following controller action and test.  I'm new to testing with Shoulda and I know there are areas of my controller that I can test further.  For example, my flash messages as well as verifying the renders.

So my question is, how would I properly test this controller action in Shoulda?

My controller action (names have been changed to protect the innocent):

def my_action
  return redirect_to(root_url) if @site.nil?
  @owner = current_site.owner
  if request.post?
    if params[:password].blank? || params[:email].blank?
      flash[:error] = "You must fill in both the e-mail and password fields"
      render :action => "my_action"
    else
      if @owner.authenticated?(params[:password])
        @owner.login = params[:email]
        @owner.save!
        @owner.do_some_method
        flash[:success] = "Success."
        render :action => "my_action"
      else
        flash[:error] = "Incorrect password"
        render :action => "my_action"
      end
    end
  end
end

My test:

context "on POST to :my_action" do
  setup do
    Owner.any_instance().expects(:do_some_method)
    post :my_action, :email => 'foo@bar.com', :password => 'test'
  end
  should_assign_to :owner
  should "Change name and verify password and resend activation key" do
    assert_equal true, assigns(:owner).authenticated?('test')
    assert_equal 'foo@bar.com', assigns(:owner).login
  end
  should_respond_with :success
end

OwnerDisplayName: Matt Haley


问:
phpmyadmin db connection to a form in php
I am having trouble connecting my php page to my database in PHPMyAdmin..
it is a sign up page, I am trying to insert the data into the table named admin but it is not working. And the output is as shown in the screenshot

output screenshot

```<code><?php

$q= mysqli_connect("localhost","root","","saramadani");
if (mysqli_connect_errno())
{
echo("Error In connection");
}
else
{
  echo("<center><h1>Database Connected</h1>");
}

$ufname=($_POST['ufname']);
$ulname=($_POST['ulname']);
$username=($_POST['username']);
$uemail=($_POST['uemail']);
$umobile=($_POST['umobile']);
$password=($_POST['password']);
$sql="INSERT INTO admin(ufname,ulname,username,uemail,umobile,password)VALUES('$ufname','$ulname','$username','$uemail','$umobile','$password')";

if(mysqli_query($q,$sql))
{echo "<center><h1>Record added successfully</h1>";}

else

{echo "error in insertion";}
mysqli_close($q);

**And here is the form part code where the post function:**

<form action="signup1.php" method="post">

          <input type="text" name="ufname" required>

          <input type="text" name="ulname" required>

          <input type="text"  name="username" required>

          <input type="email" name="uemail" required>

          <input type="phone" name="umobile" required>

          <input type="password" name="password" required>
          <button type="submit">Sign up</button>
      </form>
</code>```

答:
You are accessing the PHP file as a file:/// URL. PHP does not run in the browser - it needs an actual webserver. Since you're using XAMPP, it'll be somewhere at http://localhost/.

As a side note, phpMyAdmin has nothing to do with this. You're using MySQL - phpMyAdmin is just one (of many) ways to view/administrate a MySQL database.

Body:
I am having trouble connecting my php page to my database in PHPMyAdmin..
it is a sign up page, I am trying to insert the data into the table named admin but it is not working. And the output is as shown in the screenshot

output screenshot

<?php

$q= mysqli_connect("localhost","root","","saramadani");
if (mysqli_connect_errno())
{
echo("Error In connection");
}
else
{
  echo("
Database Connected
");
}

$ufname=($_POST['ufname']);
$ulname=($_POST['ulname']);
$username=($_POST['username']);
$uemail=($_POST['uemail']);
$umobile=($_POST['umobile']);
$password=($_POST['password']);
$sql="INSERT INTO admin(ufname,ulname,username,uemail,umobile,password)VALUES('$ufname','$ulname','$username','$uemail','$umobile','$password')";

if(mysqli_query($q,$sql))
{echo "
Record added successfully
";}

else

{echo "error in insertion";}
mysqli_close($q);

**And here is the form part code where the post function:**

<form action="signup1.php" method="post">

          <input type="text" name="ufname" required>

          <input type="text" name="ulname" required>

          <input type="text"  name="username" required>

          <input type="email" name="uemail" required>

          <input type="phone" name="umobile" required>

          <input type="password" name="password" required>
          <button type="submit">Sign up</button>
      </form>


问:
Printing certain values using Collections.frequency()
I have an array as follows:

```<code>int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};
</code>```

What I wanted to do was to find the duplicate values, and print them.

So my way of doing this was to convert to ArrayList, then to Set and use a stream on the Set.

```<code>ArrayList<Integer> list = new ArrayList<>(array.length);
for (int i = 0; i < array.length; i++) {
    list.add(array[i]);
}

Set<Integer> dup = new HashSet<>(list);
</code>```

I then used a stream to loop through it and print the values using Collections.frequency.

```<code>dup.stream().forEach((key) -> {
            System.out.println(key + ": " + Collections.frequency(list, key));
        });
</code>```

Which will of course print them all, even if the count is one.

I thought adding in if(key > 1) but it's the value I want not the key.

How can I get the value in this instance to print only where value > 2.

I could probably put in:

```<code>int check = Collections.frequency(list, key);
            if (check > 1) {
</code>```

but this then duplicates Collections.frequency(list, key) in the stream and is quite ugly.

答:
And yet another functional way:

```<code>HashMap<Integer, Long> result = Arrays.stream(array)
            .boxed()
            .collect(Collectors.collectingAndThen(Collectors.groupingBy(
                    Function.identity(),
                    HashMap::new,
                    Collectors.counting()),
                    map -> {
                        map.entrySet().removeIf(x -> x.getValue() == 1);
                        return map;
                    }));
</code>```

Btw the accepted answer - is probably the worst here, like every single suggestion to use Collections.frequency for each element (even if unique)

Body:
I have an array as follows:

int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};

What I wanted to do was to find the duplicate values, and print them.

So my way of doing this was to convert to ArrayList, then to Set and use a stream on the Set.

ArrayList<Integer> list = new ArrayList<>(array.length);
for (int i = 0; i < array.length; i++) {
    list.add(array[i]);
}

Set<Integer> dup = new HashSet<>(list);

I then used a stream to loop through it and print the values using Collections.frequency.

dup.stream().forEach((key) -> {
            System.out.println(key + ": " + Collections.frequency(list, key));
        });

Which will of course print them all, even if the count is one.

I thought adding in if(key > 1) but it's the value I want not the key.

How can I get the value in this instance to print only where value > 2.

I could probably put in:

int check = Collections.frequency(list, key);
            if (check > 1) {

but this then duplicates Collections.frequency(list, key) in the stream and is quite ugly.

Body:
And yet another functional way:

HashMap<Integer, Long> result = Arrays.stream(array)
            .boxed()
            .collect(Collectors.collectingAndThen(Collectors.groupingBy(
                    Function.identity(),
                    HashMap::new,
                    Collectors.counting()),
                    map -> {
                        map.entrySet().removeIf(x -> x.getValue() == 1);
                        return map;
                    }));

Btw the accepted answer - is probably the worst here, like every single suggestion to use Collections.frequency for each element (even if unique)


问:
Hibernate schema-validation error on SpringBootTest
Trying to get a unit test to run with @SpringBootTest annotation and I get this error from hibernate. All the information I can find online says to set "hibernate.id.new_generator_mappings" to false, but this does not fix my issue.

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = AppserverApp.class)
public class DummyTest {

    @Test
    public void dummyTest() {
        fail();
    }
}
</code>```

2017-11-17 13:20:28.885  WARN 11396 --- [           main]
  o.s.w.c.s.GenericWebApplicationContext   : Exception encountered
  during context initialization - cancelling refresh attempt:
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'entityManagerFactory' defined in class path
  resource
  [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]:
  Invocation of init method failed; nested exception is
  javax.persistence.PersistenceException: [PersistenceUnit: default]
  Unable to build Hibernate SessionFactory 2017-11-17 13:20:28.925  WARN
  11396 --- [           main] o.s.boot.SpringApplication               :
  Error handling failed (Error creating bean with name
  'delegatingApplicationListener' defined in class path resource
  [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]:
  BeanPostProcessor before instantiation of bean failed; nested
  exception is org.springframework.beans.factory.BeanCreationException:
  Error creating bean with name
  'org.springframework.cache.annotation.ProxyCachingConfiguration':
  Initialization of bean failed; nested exception is
  org.springframework.beans.factory.NoSuchBeanDefinitionException: No
  bean named
  'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry'
  available) 2017-11-17 13:20:28.951 ERROR 11396 --- [           main]
  o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'entityManagerFactory' defined in class path
  resource
  [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]:
  Invocation of init method failed; nested exception is
  javax.persistence.PersistenceException: [PersistenceUnit: default]
  Unable to build Hibernate SessionFactory  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at
  org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081)
    at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856)
    at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at
  org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
    at
  org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
    at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
    at
  org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
    at
  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at
  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    at
  org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at
  org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
    at
  org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
    at
  org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)  at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at
  org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)  at
  org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)   at
  org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)     at
  org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)   at
  org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)  at
  org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at
  org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)   at
  com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at
  com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at
  com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at
  com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
  Caused by: javax.persistence.PersistenceException: [PersistenceUnit:
  default] Unable to build Hibernate SessionFactory     at
  org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:967)
    at
  org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892)
    at
  org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
    at
  org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353)
    at
  org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370)
    at
  org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    ... 39 common frames omitted Caused by:
  org.hibernate.tool.schema.spi.SchemaManagementException:
  Schema-validation: missing sequence [hibernate_sequence]  at
  org.hibernate.tool.schema.internal.AbstractSchemaValidator.validateSequence(AbstractSchemaValidator.java:184)
    at
  org.hibernate.tool.schema.internal.AbstractSchemaValidator.performValidation(AbstractSchemaValidator.java:100)
    at
  org.hibernate.tool.schema.internal.AbstractSchemaValidator.doValidation(AbstractSchemaValidator.java:68)
    at
  org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:191)
    at
  org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)
    at
  org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:309)
    at
  org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:445)
    at
  org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:889)
    ... 45 common frames omitted

答: I am guessing you have hibernate validation enabled in test profile, but not in run profile.</p>

Body:
Trying to get a unit test to run with @SpringBootTest annotation and I get this error from hibernate. All the information I can find online says to set "hibernate.id.new_generator_mappings" to false, but this does not fix my issue.

@RunWith(SpringRunner.class)
@SpringBootTest(classes = AppserverApp.class)
public class DummyTest {

    @Test
    public void dummyTest() {
        fail();
    }
}

2017-11-17 13:20:28.885  WARN 11396 --- [           main]
  o.s.w.c.s.GenericWebApplicationContext   : Exception encountered
  during context initialization - cancelling refresh attempt:
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'entityManagerFactory' defined in class path
  resource
  [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]:
  Invocation of init method failed; nested exception is
  javax.persistence.PersistenceException: [PersistenceUnit: default]
  Unable to build Hibernate SessionFactory 2017-11-17 13:20:28.925  WARN
  11396 --- [           main] o.s.boot.SpringApplication               :
  Error handling failed (Error creating bean with name
  'delegatingApplicationListener' defined in class path resource
  [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]:
  BeanPostProcessor before instantiation of bean failed; nested
  exception is org.springframework.beans.factory.BeanCreationException:
  Error creating bean with name
  'org.springframework.cache.annotation.ProxyCachingConfiguration':
  Initialization of bean failed; nested exception is
  org.springframework.beans.factory.NoSuchBeanDefinitionException: No
  bean named
  'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry'
  available) 2017-11-17 13:20:28.951 ERROR 11396 --- [           main]
  o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'entityManagerFactory' defined in class path
  resource
  [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]:
  Invocation of init method failed; nested exception is
  javax.persistence.PersistenceException: [PersistenceUnit: default]
  Unable to build Hibernate SessionFactory  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at
  org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081)
    at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856)
    at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at
  org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
    at
  org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
    at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
    at
  org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
    at
  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at
  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    at
  org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at
  org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
    at
  org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
    at
  org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)  at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at
  org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)  at
  org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)   at
  org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)     at
  org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)   at
  org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)  at
  org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at
  org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)   at
  com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at
  com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at
  com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at
  com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
  Caused by: javax.persistence.PersistenceException: [PersistenceUnit:
  default] Unable to build Hibernate SessionFactory     at
  org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:967)
    at
  org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892)
    at
  org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
    at
  org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353)
    at
  org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370)
    at
  org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    ... 39 common frames omitted Caused by:
  org.hibernate.tool.schema.spi.SchemaManagementException:
  Schema-validation: missing sequence [hibernate_sequence]  at
  org.hibernate.tool.schema.internal.AbstractSchemaValidator.validateSequence(AbstractSchemaValidator.java:184)
    at
  org.hibernate.tool.schema.internal.AbstractSchemaValidator.performValidation(AbstractSchemaValidator.java:100)
    at
  org.hibernate.tool.schema.internal.AbstractSchemaValidator.doValidation(AbstractSchemaValidator.java:68)
    at
  org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:191)
    at
  org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)
    at
  org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:309)
    at
  org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:445)
    at
  org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:889)
    ... 45 common frames omitted


问:
"Conversion to Dalvik format failed with error 1" on external JAR
In my Android application in Eclipse, I get the following error.

UNEXPECTED TOP-LEVEL EXCEPTION:

java.lang.IllegalArgumentException: already added: Lorg/xmlpull/v1/XmlPullParser;

....

Conversion to Dalvik format failed with error 1

This error only appears when I add a specific external JAR file to my project. I searched for a long time for a possible solution, but none of them work.

I even tried to change to Android 1.6 instead of 1.5 (the current version I use).

答:
I had the same problem and none of these solutions worked.
Finally, I saw in the console that the error was due to duplicated class (one in the existing project, one in the added jar file) :

```<code>java.lang.IllegalArgumentException: already added: package/MyClassclass;
[2011-01-19 14:54:05 - ...]: Dx1 error; aborting
[2011-01-19 14:54:05 - ...] Conversion to Dalvik format failed with error 1
</code>```

So check if you are adding jar with duplicated classes in your project.
If yes, try removing one of them.

It worked for me.

ContentLicense: CC BY-SA 4.0

Body:
I had the same problem and none of these solutions worked.
Finally, I saw in the console that the error was due to duplicated class (one in the existing project, one in the added jar file) :

java.lang.IllegalArgumentException: already added: package/MyClassclass;
[2011-01-19 14:54:05 - ...]: Dx1 error; aborting
[2011-01-19 14:54:05 - ...] Conversion to Dalvik format failed with error 1

So check if you are adding jar with duplicated classes in your project.
If yes, try removing one of them.

It worked for me.


问:
Reading values from application.properties Spring Boot
My Spring boot app has this application structure:

src

main

java

resources

application.properties

This is my application.properties file:

```<code>logging.level.org.springframework=TRACE
logging.level.org.hibernate=ERROR
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
#spring.resources.chain.cache=false
#spring.resources.chain.html-application-cache=false
#spring.headers.cache=false
language=java
</code>```

I have a class which requires the use of that language=java property. This is how I am trying to use it:

```<code>public class EntityManager {

    @Value("${language}")
    private static String newLang;

    public EntityManager(){
        System.out.println("langauge is: " + newLang);
    }
}
</code>```

That printed value is always "null" for some reason! I have also tried putting this on top of the class declaration:

```<code>@PropertySource(value = "classpath:application.properties")
</code>```

答:
Sometimes, the classpath entry for src/main/resources contains an exclude tag. If application.properties is present in this list of excluded items then @PropertySource("classpath:application.properties") will not be able to find the property file.

Either remove the exclude entry from [.classpath][1] file for src/main/resources manually, or use the Configure build path option in Eclipse and go to Source tab. Then remove the exclude entry from src.

Body:
My Spring boot app has this application structure:

src

main

java

resources

application.properties

This is my application.properties file:

logging.level.org.springframework=TRACE
logging.level.org.hibernate=ERROR
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
#spring.resources.chain.cache=false
#spring.resources.chain.html-application-cache=false
#spring.headers.cache=false
language=java

I have a class which requires the use of that language=java property. This is how I am trying to use it:

public class EntityManager {

    @Value("${language}")
    private static String newLang;

    public EntityManager(){
        System.out.println("langauge is: " + newLang);
    }
}

That printed value is always "null" for some reason! I have also tried putting this on top of the class declaration:

@PropertySource(value = "classpath:application.properties")


问:
Getting data from my Database Handler to a Text View in my Activity
New to Android Studio so some help would go a long way!

Trying to do a search where the user inputs an email and if its in the database, then it shows up in a text view.

I think my select is correct but here's the method in my Database Handler class:

```<code>public String searchEmail(String email)
    {
        SQLiteDatabase db = this.getWritableDatabase();

        String fName;
        String sName;
        String selectQuery = "SELECT FIRSTNAME, SURNAME FROM friends_table WHERE EMAIL=? ";
        Cursor c = db.rawQuery(selectQuery, new String[] { email });
        if (c.moveToFirst()) {
            fName = c.getString(c.getColumnIndex("FIRSTNAME"));
            sName = c.getString(c.getColumnIndex("SURNAME"));
        }
        c.close();

        return email;
    }
</code>```

Then my search:

```<code>public void searchFriend(View v) {
        EditText emailSearch = (EditText) findViewById(R.id.emailSearch);

        String emailSearchString = emailSearch.getText().toString();
        myDB.searchEmail(emailSearchString);

    //I need to get the first name and surname from the db handler class
        TextView firstName = (TextView)findViewById(R.id.firstname);
        TextView surname = (TextView)findViewById(R.id.surname);

        firstName.setText("");
        surname.setText("");

    }
</code>```

I'm just finding to difficult to understand how I'll show the first name and surname if the email matches.

Thanks guys, I love you

答:
Create a new class User (with getters, setters) and try this:

```<code>public User searchEmail(String email) {
    SQLiteDatabase db = this.getWritableDatabase();

    User u = null;
    String selectQuery = "SELECT FIRSTNAME, SURNAME FROM friends_table WHERE EMAIL=? ";
    Cursor c = db.rawQuery(selectQuery, new String[] { email });
    if (c.moveToFirst()) {
        u = new User();
        u.setfName(c.getString(c.getColumnIndex("FIRSTNAME")));
        u.setsName(c.getString(c.getColumnIndex("SURNAME")));
    }
    c.close();

    return u;
}
</code>```

Display results in activity:

```<code>public void searchFriend(View v) {
    EditText emailSearch = (EditText) findViewById(R.id.emailSearch);
    TextView firstName = (TextView)findViewById(R.id.firstname);
    TextView surname = (TextView)findViewById(R.id.surname);

    String emailSearchString = emailSearch.getText().toString();
    User user = myDB.searchEmail(emailSearchString);

    firstName.setText(user.getfName());
    surname.setText(user.getsName());

}
</code>```

Body:
New to Android Studio so some help would go a long way!

Trying to do a search where the user inputs an email and if its in the database, then it shows up in a text view.

I think my select is correct but here's the method in my Database Handler class:

public String searchEmail(String email)
    {
        SQLiteDatabase db = this.getWritableDatabase();

        String fName;
        String sName;
        String selectQuery = "SELECT FIRSTNAME, SURNAME FROM friends_table WHERE EMAIL=? ";
        Cursor c = db.rawQuery(selectQuery, new String[] { email });
        if (c.moveToFirst()) {
            fName = c.getString(c.getColumnIndex("FIRSTNAME"));
            sName = c.getString(c.getColumnIndex("SURNAME"));
        }
        c.close();

        return email;
    }

Then my search:

public void searchFriend(View v) {
        EditText emailSearch = (EditText) findViewById(R.id.emailSearch);

        String emailSearchString = emailSearch.getText().toString();
        myDB.searchEmail(emailSearchString);

    //I need to get the first name and surname from the db handler class
        TextView firstName = (TextView)findViewById(R.id.firstname);
        TextView surname = (TextView)findViewById(R.id.surname);

        firstName.setText("");
        surname.setText("");

    }

I'm just finding to difficult to understand how I'll show the first name and surname if the email matches.

Thanks guys, I love you

Body:
Create a new class User (with getters, setters) and try this:

public User searchEmail(String email) {
    SQLiteDatabase db = this.getWritableDatabase();

    User u = null;
    String selectQuery = "SELECT FIRSTNAME, SURNAME FROM friends_table WHERE EMAIL=? ";
    Cursor c = db.rawQuery(selectQuery, new String[] { email });
    if (c.moveToFirst()) {
        u = new User();
        u.setfName(c.getString(c.getColumnIndex("FIRSTNAME")));
        u.setsName(c.getString(c.getColumnIndex("SURNAME")));
    }
    c.close();

    return u;
}

Display results in activity:

public void searchFriend(View v) {
    EditText emailSearch = (EditText) findViewById(R.id.emailSearch);
    TextView firstName = (TextView)findViewById(R.id.firstname);
    TextView surname = (TextView)findViewById(R.id.surname);

    String emailSearchString = emailSearch.getText().toString();
    User user = myDB.searchEmail(emailSearchString);

    firstName.setText(user.getfName());
    surname.setText(user.getsName());

}