问:
java.sql.SQLException: Invalid value for getShort() - ' '
I want to auto filter the search using the DocumentListener in my java code
but the code shows

error java.sql.SQLException: Invalid value for getShort() - ''

with matching value in the 'single quote' ie. the program shows the error (  java.sql.SQLException: Invalid value for getShort() - 'Rabin Karki' )
when I enter (' r ') in the search text field

My database table is 'staff' and contains following columns

Name varchar(40), Designation varchar(40), Salary int(), Address
  varchar(40), Contact int(), Email varchar(40), BirthDate date(),
  JoinDate()

```<code>import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.*;
import javax.swing.text.Document;

public class Test extends JFrame implements ActionListener{

    JTextField txt;
    JButton btn;

    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);

    Connection con;
    Statement stmt;
    PreparedStatement pstmt;
    ResultSet rs;

    public Test(){
        txt = new JTextField();
        btn = new JButton("Search");

        setLayout(null);

        add(txt);
        txt.setBounds(320,20,100,20);

        add(btn);
        btn.setBounds(500,20,80,20);

        txt.getDocument().addDocumentListener(new MyDocumentListener());

        try{
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/salarymanagement","root","");
            stmt = con.createStatement();
            rs = stmt.executeQuery("select * from staff");

            model.addColumn("Name");
            model.addColumn("Designation");
            model.addColumn("Salary");
            model.addColumn("Address");
            model.addColumn("Contact");
            model.addColumn("Email");
            model.addColumn("Birth Date");
            model.addColumn("Join Date");

            while(rs.next()){
                model.addRow(new Object[] { rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8)});
            }

            int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
            int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;

            JScrollPane scrollPane = new JScrollPane(table,v,h);
            add(scrollPane, BorderLayout.CENTER);
            scrollPane.setBounds(5,60,1000,1000);

            table.updateUI();
        }
        catch(Exception ex){
            System.out.println("ERROR :"+ex);
        }
        setSize(1200,1200);
        setVisible(true);
        setTitle("Test of search filter");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    class MyDocumentListener implements DocumentListener{

        public void update(DocumentEvent de){
            Document doc = (Document)de.getDocument();
            int length = doc.getLength();
            String str = null;

            try{
                str = doc.getText(0,length);
            }
            catch(Exception ex){
                System.out.println("error"+ex);
            }

            try{
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/salarymanagement","root","");
                pstmt = con.prepareStatement("select * from staff where Name like '"+str+"%' order by Name");
                rs = pstmt.executeQuery();

                model.setRowCount(0);

                while(rs.next()){
                    model.addRow(new Object[] {rs.getShort(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8) });
                }
                pstmt.close();
                con.close();
            }
            catch(Exception exc){
                System.out.println("error "+exc);
            }
        }

        @Override
        public void insertUpdate(DocumentEvent de) {
            update(de);
        }

        @Override
        public void removeUpdate(DocumentEvent de) {
            update(de);
        }

        @Override
        public void changedUpdate(DocumentEvent de) {
            update(de);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
    public static void main(String[] args) {
        new Test();
    }
}
</code>```

答:
select * from Returns the columns in order they are created by the create Statement.
In your case Name will be the fiorst column. Which you read with rs.getShort(1) from the resultset. You have to use String here:

```<code>               model.addRow(new Object[] {rs.getString(1...
</code>```

You should better add the columns to the select to define the order.

Body:
I want to auto filter the search using the DocumentListener in my java code
but the code shows

error java.sql.SQLException: Invalid value for getShort() - ''

with matching value in the 'single quote' ie. the program shows the error (  java.sql.SQLException: Invalid value for getShort() - 'Rabin Karki' )
when I enter (' r ') in the search text field

My database table is 'staff' and contains following columns

Name varchar(40), Designation varchar(40), Salary int(), Address
  varchar(40), Contact int(), Email varchar(40), BirthDate date(),
  JoinDate()

import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.*;
import javax.swing.text.Document;

public class Test extends JFrame implements ActionListener{

    JTextField txt;
    JButton btn;

    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);

    Connection con;
    Statement stmt;
    PreparedStatement pstmt;
    ResultSet rs;

    public Test(){
        txt = new JTextField();
        btn = new JButton("Search");

        setLayout(null);

        add(txt);
        txt.setBounds(320,20,100,20);

        add(btn);
        btn.setBounds(500,20,80,20);

        txt.getDocument().addDocumentListener(new MyDocumentListener());

        try{
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/salarymanagement","root","");
            stmt = con.createStatement();
            rs = stmt.executeQuery("select * from staff");

            model.addColumn("Name");
            model.addColumn("Designation");
            model.addColumn("Salary");
            model.addColumn("Address");
            model.addColumn("Contact");
            model.addColumn("Email");
            model.addColumn("Birth Date");
            model.addColumn("Join Date");

            while(rs.next()){
                model.addRow(new Object[] { rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8)});
            }

            int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
            int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;

            JScrollPane scrollPane = new JScrollPane(table,v,h);
            add(scrollPane, BorderLayout.CENTER);
            scrollPane.setBounds(5,60,1000,1000);

            table.updateUI();
        }
        catch(Exception ex){
            System.out.println("ERROR :"+ex);
        }
        setSize(1200,1200);
        setVisible(true);
        setTitle("Test of search filter");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    class MyDocumentListener implements DocumentListener{

        public void update(DocumentEvent de){
            Document doc = (Document)de.getDocument();
            int length = doc.getLength();
            String str = null;

            try{
                str = doc.getText(0,length);
            }
            catch(Exception ex){
                System.out.println("error"+ex);
            }

            try{
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/salarymanagement","root","");
                pstmt = con.prepareStatement("select * from staff where Name like '"+str+"%' order by Name");
                rs = pstmt.executeQuery();

                model.setRowCount(0);

                while(rs.next()){
                    model.addRow(new Object[] {rs.getShort(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8) });
                }
                pstmt.close();
                con.close();
            }
            catch(Exception exc){
                System.out.println("error "+exc);
            }
        }

        @Override
        public void insertUpdate(DocumentEvent de) {
            update(de);
        }

        @Override
        public void removeUpdate(DocumentEvent de) {
            update(de);
        }

        @Override
        public void changedUpdate(DocumentEvent de) {
            update(de);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
    public static void main(String[] args) {
        new Test();
    }
}

Body:
select * from Returns the columns in order they are created by the create Statement.
In your case Name will be the fiorst column. Which you read with rs.getShort(1) from the resultset. You have to use String here:

               model.addRow(new Object[] {rs.getString(1...

You should better add the columns to the select to define the order.


来源: stackexchange

问:
ADF Mobile app deployed into Android emulator. Error: "Failed to initialize the AdfcContext"
I have the SKD Android Emulator. It was extremely slow, so I installed the Intel Hardware Accelerated Execution Manager (HAXM) and now it works really fast.

I have a very simple ADF Mobile application with 2 simple features, a "hello world" html page and a "hello world" amx page.

I deployed my app into the Android emulator in release mode, then I opened my app and it never stopped loading so I got out of the app. I tried to enter to the app again and I could enter to my html feature, but then when I tried to see my axm feature an alert popped up. It started loading and I don't know if it was going to finish loading, and then in a while:

```<code>"Failed to initialize the AdfcContext: {classname: oracle.adfmf.framework.api.Model; method: pushPageFlowScope; params: ;}"
</code>```

When I deploy the Application I get this log warning:

```<code>"WARNING: No Resource Catalog enabled ADF components found to package"
</code>```

I realized that I get this warning when I use the "Intel Atom (x86)" CPU in the Emulator. If I use the "ARM(armeabi-v7a)" CPU the axm page takes a really long time to load, but it works fine.

答:
That's right. Adf mobile does have dependency with ARM.
Because when I try to install an adf mobile app into genymotion (another android emulator) , an error page shows that:

```<code>the app contains ARM native code...You should either build your code to x86 or install an ARM translation tool in your device.
</code>```

Per my test, an emulator created by Android Studio is quite slow, too hard to use.
Finally I fix this issue by this:ARM_Translation

ContentLicense: CC BY-SA 3.0

Body:
I have the SKD Android Emulator. It was extremely slow, so I installed the Intel Hardware Accelerated Execution Manager (HAXM) and now it works really fast.

I have a very simple ADF Mobile application with 2 simple features, a "hello world" html page and a "hello world" amx page.

I deployed my app into the Android emulator in release mode, then I opened my app and it never stopped loading so I got out of the app. I tried to enter to the app again and I could enter to my html feature, but then when I tried to see my axm feature an alert popped up. It started loading and I don't know if it was going to finish loading, and then in a while:

"Failed to initialize the AdfcContext: {classname: oracle.adfmf.framework.api.Model; method: pushPageFlowScope; params: ;}"

When I deploy the Application I get this log warning:

"WARNING: No Resource Catalog enabled ADF components found to package"

I realized that I get this warning when I use the "Intel Atom (x86)" CPU in the Emulator. If I use the "ARM(armeabi-v7a)" CPU the axm page takes a really long time to load, but it works fine.

Body:
That's right. Adf mobile does have dependency with ARM.
Because when I try to install an adf mobile app into genymotion (another android emulator) , an error page shows that:

the app contains ARM native code...You should either build your code to x86 or install an ARM translation tool in your device.

Per my test, an emulator created by Android Studio is quite slow, too hard to use.
Finally I fix this issue by this:ARM_Translation


问:
How do I convert percent encoded slug fields to unicode when migrating from WordPress to Django?
I am migrating Wordpress Data into Django. The current site title, content, slug are in Hindi.

I am using wordpress_xmlrpc to import data from WordPress via xmlrpc.

All the content title, content are in Hindi as well, and they are accessed and saved Okay.

```<code>    instance.name = post.title
    instance.content = post.content
</code>```

While there is issue with Django slugs.

Have the tried the following, does not work.

```<code>    instance.slug = unicode(post.slug)
    instance.slug = post.slug
</code>```

For not working, in one case, slug is saved as

```<code>     %e0%a4%9c%e0%a4%b2%e0%a5%8d%e0%a4%a6-%e0%a4%b8%e0%a4%bf%e0%a4%b2%e0%a5%8d%e0%a4%b5%e0%a4%b0-%e0%a4%b8%e0%a5%8d%e0%a4%95%e0%a5%8d%e0%a4%b0%e0%a5%80%e0%a4%a8-%e0%a4%aa%e0%a4%b0-%e0%a4%a6%e0%a4%bf
</code>```

It is not accessible either.

Getting 404, Page not found for

```<code> http://localhost:8010/%E0%A4%9C%E0%A4%B2%E0%A5%8D%E0%A4%A6-%E0%A4%B8%E0%A4%BF%E0%A4%B2%E0%A5%8D%E0%A4%B5%E0%A4%B0-%E0%A4%B8%E0%A5%8D%E0%A4%95%E0%A5%8D%E0%A4%B0%E0%A5%80%E0%A4%A8-%E0%A4%AA%E0%A4%B0-%E0%A4%A6%E0%A4%BF/
</code>```

The WordPress has slug like
       /तापसी-पन्नू-ने-अक्षय-कुमा/

Does anybody know how to resolve this issue.

答:
To convert percent encoding in the migration, you can use django's built in uri_to_iri function.

```<code>>>> from django.utils.encoding import uri_to_iri
>>> old_slug = '%e0%a4%9c%e0%a4%b2%e0%a5%8d%e0%a4%a6-%e0%a4%b8%e0%a4%bf'
>>> new_slug = uri_to_iri(old_slug)
>>> print(old_slug, '->', new_slug)

%e0%a4%9c%e0%a4%b2%e0%a5%8d%e0%a4%a6-%e0%a4%b8%e0%a4%bf -> जल्द-सि
</code>```

This should convert the wordpress slug to unicode:

```<code>instance.slug = uri_to_iri(post.slug)
</code>```

Body:
I am migrating Wordpress Data into Django. The current site title, content, slug are in Hindi.

I am using wordpress_xmlrpc to import data from WordPress via xmlrpc.

All the content title, content are in Hindi as well, and they are accessed and saved Okay.

    instance.name = post.title
    instance.content = post.content

While there is issue with Django slugs.

Have the tried the following, does not work.

    instance.slug = unicode(post.slug)
    instance.slug = post.slug

For not working, in one case, slug is saved as

     %e0%a4%9c%e0%a4%b2%e0%a5%8d%e0%a4%a6-%e0%a4%b8%e0%a4%bf%e0%a4%b2%e0%a5%8d%e0%a4%b5%e0%a4%b0-%e0%a4%b8%e0%a5%8d%e0%a4%95%e0%a5%8d%e0%a4%b0%e0%a5%80%e0%a4%a8-%e0%a4%aa%e0%a4%b0-%e0%a4%a6%e0%a4%bf

It is not accessible either.

Getting 404, Page not found for

 http://localhost:8010/%E0%A4%9C%E0%A4%B2%E0%A5%8D%E0%A4%A6-%E0%A4%B8%E0%A4%BF%E0%A4%B2%E0%A5%8D%E0%A4%B5%E0%A4%B0-%E0%A4%B8%E0%A5%8D%E0%A4%95%E0%A5%8D%E0%A4%B0%E0%A5%80%E0%A4%A8-%E0%A4%AA%E0%A4%B0-%E0%A4%A6%E0%A4%BF/

The WordPress has slug like
       /तापसी-पन्नू-ने-अक्षय-कुमा/

Does anybody know how to resolve this issue.

Body:
To convert percent encoding in the migration, you can use django's built in uri_to_iri function.

>>> from django.utils.encoding import uri_to_iri
>>> old_slug = '%e0%a4%9c%e0%a4%b2%e0%a5%8d%e0%a4%a6-%e0%a4%b8%e0%a4%bf'
>>> new_slug = uri_to_iri(old_slug)
>>> print(old_slug, '->', new_slug)

%e0%a4%9c%e0%a4%b2%e0%a5%8d%e0%a4%a6-%e0%a4%b8%e0%a4%bf -> जल्द-सि

This should convert the wordpress slug to unicode:

instance.slug = uri_to_iri(post.slug)


问:
Why need synchronizedMap() if there is ConcurrentHashMap?
I read an article about thread safe maps and got a question. Collections.synchronizedMap() proxies underlying map with adding synchronized blocks on each method. On the other hand ConcurrentHashMap doesn't lock the whole map on read/write operations. Which means all operations in multi thread system are faster.

So what are the benefits of using synchronizedMap() nowadays? I see the only:

it's available since java 1.2 (vs java 1.5 for ConcurrentHashMap)

can store nullable values (if underlying map can do it)

Are there any other situations when synchronizedMap() is better?

答:
There is pros and cons associated with both Collections.synchronizedMap(map) and ConcurrentHashMap.

synchronizedMap is useful when you want data consistency. Each accessing thread will have an update view of the map which is achieved by blocking the map which in turn degrades it performance.

ConcurrentHashMap is useful when you needs to modify map frequently. Since it works on segmentation/partition of map several thread work simultaneously on it. But there is possibility that an accessing thread might not have an update view of map. Other advantage is that it is fail-safe. ConcurrentHashMap does not allow null keys or values.

Use ConcurrentHashMapif performance is high concern then data consistency.


问:
the running application have different layout than the preview
While running the application the design layout is not same as in the preview as all the widgets are overlapping at the top-left corner no matter where I place them.

答:
can you provide you xml code.
and in my case i faced the same issue. when i using the relative layout. just use linear layout and check it again...</p>


问:
Git error remote: Empty password
I'm trying to clone my git repo from bitbucket, and when I enter this command:

```<code>git clone https://naor_shoyhat@bitbucket.org/naor_shoyhat/hello-world.git
</code>```

The bash then prompts me a window with areas to enter username and password.

I enter them and then I receive this error:

```<code>remote: Empty password
fatal: Authentication failed for 'https://naor_shoyhat@bitbucket.org/naor_shoyhat/hello-world.git/'
</code>```

答: I'm using  git(2.12.2) 64-bit on Windows 10. My solution is simply close the login window which you have to type account and password, and a SSh window will pop out, then you type your password. </p>

Title: Git error remote: Empty password

Body:
I'm trying to clone my git repo from bitbucket, and when I enter this command:

git clone https://naor_shoyhat@bitbucket.org/naor_shoyhat/hello-world.git

The bash then prompts me a window with areas to enter username and password.

I enter them and then I receive this error:

remote: Empty password
fatal: Authentication failed for 'https://naor_shoyhat@bitbucket.org/naor_shoyhat/hello-world.git/'


问:
Missing variables from $_SERVER
In the PHP source code, I echo out $_SERVER in one of my domain on server A and got returns me a list of data include DOCUMENT_ROOT and GATEWAY_INTERFACE and etc. However, in the another domain in server B didn't return me anything when I echo out same things. Can I know why?

答:
Just summarizing the comments, including my own.

The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here.

from PHP manual on $_SERVER

While most servers will provide at least certain values within $_SERVER, there are no guarantees. Either design your code in a way that does not depend on the content of $_SERVER, or make sure that the very server you are going to use in production does in fact provide the values you need.

Title: Missing variables from $_SERVER


问:
match columns in 2 tab-delimited text files
I have two tab-delimited .txt files

file1 has 20 million lines and the following structure

```<code>col1    col2    col3    col4    col5
1       x       x       A       x
2       y       y       A       x
3       z       z       A       x
4       x       x       B       x
5       x       y       B       x
6       x       y       E       x
7       x       z       F       x
</code>```

file2 has 3000 lines and the following structure

```<code>col1
A
B
C
D
</code>```

Now I want to extract from file1 the lines where there is a match between col1 from file2 and col4 of file1

So the new file3 should look like this

```<code>col1    col2    col3    col4    col5
1       x       x       A       x
2       y       y       A       x
3       z       z       A       x
4       x       x       B       x
5       x       y       B       x
</code>```

How can I do this with perl or bash?

答:
You can use standard awk command to join 2 files:</p>

```<code>awk 'BEGIN{FS=OFS="\t"} FNR == NR { a[$1]; next } $4 in a' file2 file1
</code>```

Body:
I have two tab-delimited .txt files

file1 has 20 million lines and the following structure

col1    col2    col3    col4    col5
1       x       x       A       x
2       y       y       A       x
3       z       z       A       x
4       x       x       B       x
5       x       y       B       x
6       x       y       E       x
7       x       z       F       x

file2 has 3000 lines and the following structure

col1
A
B
C
D

Now I want to extract from file1 the lines where there is a match between col1 from file2 and col4 of file1

So the new file3 should look like this

col1    col2    col3    col4    col5
1       x       x       A       x
2       y       y       A       x
3       z       z       A       x
4       x       x       B       x
5       x       y       B       x

How can I do this with perl or bash?

Body:
You can use standard awk command to join 2 files:

awk 'BEGIN{FS=OFS="\t"} FNR == NR { a[$1]; next } $4 in a' file2 file1


问:
Angular directive throws Error: [$injector:unpr]
I am working on an project and need to modify some code to resolve an error

directive:

```<code>(function () {
    'use strict';

    angular.module('myApp').directive("myDirective", function ($filter) {
        return {
            // code
        };
    });
})();
</code>```

This throws an error with the minified version only.
I am using angular 1.5.9

I think I need to define $filter somewhere.

答:
When you are using minified version of angular you need to inject the dependencies as a separate string array. Otherwise, dependency injector unable to identify which is which</p>

```<code>(function () {
    'use strict';

    angular.module('myApp')
      .directive("myDirective",myDirective);

    myDirective.$inject = ['$filter'];

    function myDirective($filter) {
        return {
            // code
        };
    }

})();
</code>```

Body:
I am working on an project and need to modify some code to resolve an error

directive:

(function () {
    'use strict';

    angular.module('myApp').directive("myDirective", function ($filter) {
        return {
            // code
        };
    });
})();

This throws an error with the minified version only.
I am using angular 1.5.9

I think I need to define $filter somewhere.

Body:
When you are using minified version of angular you need to inject the dependencies as a separate string array. Otherwise, dependency injector unable to identify which is which

(function () {
    'use strict';

    angular.module('myApp')
      .directive("myDirective",myDirective);

    myDirective.$inject = ['$filter'];

    function myDirective($filter) {
        return {
            // code
        };
    }

})();


问:
List passed by ref - help me explain this behaviour
Take a look at the following program:

```<code>class Test
{
    List<int> myList = new List<int>();

    public void TestMethod()
    {
        myList.Add(100);
        myList.Add(50);
        myList.Add(10);

        ChangeList(myList);

        foreach (int i in myList)
        {
            Console.WriteLine(i);
        }
    }

    private void ChangeList(List<int> myList)
    {
        myList.Sort();

        List<int> myList2 = new List<int>();
        myList2.Add(3);
        myList2.Add(4);

        myList = myList2;
    }
}
</code>```

I assumed myList would have passed by ref, and the output would

```<code>3
4
</code>```

The list is indeed "passed by ref", but only the sort function takes effect. The following statement myList = myList2; has no effect.

So the output is in fact:

```<code>10
50
100
</code>```

Can you help me explain this behavior? If indeed myList is not passed-by-ref (as it appears from myList = myList2 not taking effect), how does myList.Sort() take effect?

I was assuming even that statement to not take effect and the output to be:

```<code>100
50
10
</code>```

答:
C# just does a shallow copy when it passes by value unless the object in question executes ICloneable (which apparently the List class does not).

What this means is that it copies the List itself, but the references to the objects inside the list remain the same; that is, the pointers continue to reference the same objects as the original List.

If you change the values of the things your new List references, you change the original List also (since it is referencing the same objects).  However, you then change what myList references entirely, to a new List, and now only the original List is referencing those integers.

Read the Passing Reference-Type Parameters section from this MSDN article on "Passing Parameters" for more information.

"How do I Clone a Generic List in C#" from StackOverflow talks about how to make a deep copy of a List.

Body:
Take a look at the following program:

class Test
{
    List<int> myList = new List<int>();

    public void TestMethod()
    {
        myList.Add(100);
        myList.Add(50);
        myList.Add(10);

        ChangeList(myList);

        foreach (int i in myList)
        {
            Console.WriteLine(i);
        }
    }

    private void ChangeList(List<int> myList)
    {
        myList.Sort();

        List<int> myList2 = new List<int>();
        myList2.Add(3);
        myList2.Add(4);

        myList = myList2;
    }
}

I assumed myList would have passed by ref, and the output would

3
4

The list is indeed "passed by ref", but only the sort function takes effect. The following statement myList = myList2; has no effect.

So the output is in fact:

10
50
100

Can you help me explain this behavior? If indeed myList is not passed-by-ref (as it appears from myList = myList2 not taking effect), how does myList.Sort() take effect?

I was assuming even that statement to not take effect and the output to be:

100
50
10


问:
change localhost directory to domain name through /etc/hosts
I was wondering whether anyone could please advise how I can point a domain to a directory within my localhost instead of the root of my localhost?

For example in my hosts file:

127.0.0.1 www.domain.com

This works

127.0.0.1/directory/ www.domain.com

This doesn't work? But is the directory that I need to view when going to that domain?

Or is there a better way to set up multiple sites within your localhost, as I am setting up each site within their own directory?

Any help would be appreciated

Thanks

答:
You need to use virtual hosts:</p>

```<code><VirtualHost *:80>

  # Admin email, Server Name (domain name) and any aliases
  ServerAdmin webmaster@domain1.com
  ServerName  domain1.com
  ServerAlias www.domain1.com

  # Index file and Document Root (where the public files are located)
  DirectoryIndex index.html
  DocumentRoot /home/demo/public_html/domain1.com/public

  # Custom log file locations
  LogLevel warn
  ErrorLog /var/log/apache2/error-mydomainname.com.log
  CustomLog /var/log/apache2/access-mydomainname.com.log combined

</VirtualHost>
</code>```

Body:
You need to use virtual hosts:

<VirtualHost *:80>

  # Admin email, Server Name (domain name) and any aliases
  ServerAdmin webmaster@domain1.com
  ServerName  domain1.com
  ServerAlias www.domain1.com

  # Index file and Document Root (where the public files are located)
  DirectoryIndex index.html
  DocumentRoot /home/demo/public_html/domain1.com/public

  # Custom log file locations
  LogLevel warn
  ErrorLog /var/log/apache2/error-mydomainname.com.log
  CustomLog /var/log/apache2/access-mydomainname.com.log combined

</VirtualHost>


问:
Auto Hot Key: Strange behavior on ControlClick after Gui Submit
I have the following script that sends ControlClick + ControlSend to a window in background (while I'm working in another window). It works ok as expected.

```<code>SetTitleMatchMode 2

$F1::
sleep 1000

ControlClick, x400 y470, Notepad
ControlSend,, text, Notepad

return
</code>```

The problem is: when I add a Gui on the script, the ControlClick behavior becomes odd once I close the Gui (with Submit or Destroy): If I'm working in a window A (Chrome for example) the ControlClick don't work in background anymore: it activates the window B (Notepad) like in the WinActivate command instead.

Here's the script with the issue (same as the previous one but with a simple Gui):

```<code>SetTitleMatchMode 2

Gui, Add, Text,, box
Gui, Add, Button, default, OK
Gui, Show, W300 H300
return

GuiClose:
ButtonOK:
Gui, Submit
return

$F1::
sleep 1000

ControlClick, x400 y470, Notepad
ControlSend,, text, Notepad

return
</code>```

I'm on Windows Vista 32 bits, Autohotkey v1.1.25.01

I can't understand why the Gui Submit is changing the ControlClick bahavior. How can I fix this and let the ControlClick run in background just like it was without the Gui Submit/Destroy?

ps: both windows were maximized.

答:
ControlClick is known to not be very reliable in certain cases. Take a look at the Reliability section in the ControlClick documentation, there are some things you can try:

To improve reliability -- especially during times when the user is
  physically moving the mouse during the ControlClick -- one or both of
  the following may help:

Use SetControlDelay -1 prior to ControlClick. This avoids holding
  the mouse button down during the click, which in turn reduces
  interference from the user's physical movement of the mouse.

Specify the string NA anywhere in the sixth parameter (Options) as
  shown below:

```<code>SetControlDelay -1
ControlClick, Toolbar321, WinTitle,,,, NA
</code>```

NA avoids marking the target window as active and avoids
  merging its input processing with that of the script, which may
  prevent physical movement of the mouse from interfering (but usually
  only when the target window is not active). However, this method might
  not work for all types of windows and controls.

Body:
I have the following script that sends ControlClick + ControlSend to a window in background (while I'm working in another window). It works ok as expected.

SetTitleMatchMode 2

$F1::
sleep 1000

ControlClick, x400 y470, Notepad
ControlSend,, text, Notepad

return

The problem is: when I add a Gui on the script, the ControlClick behavior becomes odd once I close the Gui (with Submit or Destroy): If I'm working in a window A (Chrome for example) the ControlClick don't work in background anymore: it activates the window B (Notepad) like in the WinActivate command instead.

Here's the script with the issue (same as the previous one but with a simple Gui):

SetTitleMatchMode 2

Gui, Add, Text,, box
Gui, Add, Button, default, OK
Gui, Show, W300 H300
return

GuiClose:
ButtonOK:
Gui, Submit
return

$F1::
sleep 1000

ControlClick, x400 y470, Notepad
ControlSend,, text, Notepad

return

I'm on Windows Vista 32 bits, Autohotkey v1.1.25.01

I can't understand why the Gui Submit is changing the ControlClick bahavior. How can I fix this and let the ControlClick run in background just like it was without the Gui Submit/Destroy?

ps: both windows were maximized.

Body:
ControlClick is known to not be very reliable in certain cases. Take a look at the Reliability section in the ControlClick documentation, there are some things you can try:

To improve reliability -- especially during times when the user is
  physically moving the mouse during the ControlClick -- one or both of
  the following may help:

Use SetControlDelay -1 prior to ControlClick. This avoids holding
  the mouse button down during the click, which in turn reduces
  interference from the user's physical movement of the mouse.

Specify the string NA anywhere in the sixth parameter (Options) as
  shown below:

SetControlDelay -1
ControlClick, Toolbar321, WinTitle,,,, NA

NA avoids marking the target window as active and avoids
  merging its input processing with that of the script, which may
  prevent physical movement of the mouse from interfering (but usually
  only when the target window is not active). However, this method might
  not work for all types of windows and controls.


问:
How does the :type field get populated in Single Table Inheritance?
I asked a question earlier about how to structure the data in a simple app I am building to manage content. The answer was to look at Single Table Inheritance and I think it's going to be the ticket.

I've read quite a few examples but one thing that always seems to be left out is how the :type column is actually populated? Do I include a form field w/ a drop down so the user can select the types?

I believe I fully understand how STI works now (the type field takes on the class name) but am still missing something very basic (and probably very obvious, but I'm missing it). Can someone fill me in?

I have a content table like so:

```<code>id
type
name
desc
</code>```

And the different types would be "Site", "Blog", "Photo".

答:
Guessing that you stores all "Site", "Blog", "Photo" information in contents table. When you initiates any object by Content.new, it does not have assigned any value to type field.

But if you initiate any class from "Site", "Blog" or "Photo" which have been actually inherited from "Content" model by-
Site.new or Site.create then it automatically assigns model_name(in this case- Site) in the type field

Similarly if you do Blog.new it will assign Blog in type column and so on.

ContentLicense: CC BY-SA 2.5

Body:
I asked a question earlier about how to structure the data in a simple app I am building to manage content. The answer was to look at Single Table Inheritance and I think it's going to be the ticket.

I've read quite a few examples but one thing that always seems to be left out is how the :type column is actually populated? Do I include a form field w/ a drop down so the user can select the types?

I believe I fully understand how STI works now (the type field takes on the class name) but am still missing something very basic (and probably very obvious, but I'm missing it). Can someone fill me in?

I have a content table like so:

id
type
name
desc

And the different types would be "Site", "Blog", "Photo".


问:
Elastic search creating new mapping rather than joining the one already defined?
I created a index with mapping given below. And the index is empty

```<code>{
  "content": {
    "mappings": {
      "university": {
        "properties": {
          "state": {
            "type": "nested",
            "properties": {
              "pincode": {
                "type": "long"
              },
              "region": {
                "type": "string",
                "index": "not_analyzed"
              }
            }
          }
        }
      }
    }
  }
}
</code>```

When i am inserting a document like this :

```<code>PUT content/university/1
    {
      "university": [
        {
          "state": {
            "region": "usa",
            "pincode": 5693
          }
        }
      ]
    }
</code>```

It is creating a new mapping rather than joining in the one that defined previously.

```<code>{
  "content": {
    "mappings": {
      "university": {
        "properties": {
          "state": {
            "type": "nested",
            "properties": {
              "pincode": {
                "type": "long"
              },
              "region": {
                "type": "string",
                "index": "not_analyzed"
              }
            }
          },
          "university": {
            "properties": {
              "state": {
                "properties": {
                  "pincode": {
                    "type": "long"
                  },
                  "region": {
                    "type": "string"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</code>```

How i can avoid this in elasticsearch?

Whether i have to use inline scripts for this?

答:
I think your mapping should be this:

{
  "content": {
    "mappings": {
      "university": {
        "type": "nested",
        "properties": {
          "state": {
            "properties": {
              "pincode": {
                "type": "long"
              },
              "region": {
                "type": "string",
                "index": "not_analyzed"
              }
            }
          }
        }
      }
    }
  }
}
```

<p>If <code>university</code> is the object that is going to have nested properties like <code>state</code> then you need to declare the <code>type</code> of <code>university</code> field to be <code>nested</code> and not of <code>state</code>.
If however, you want the state to be of type nested, in that case i think you should try indexing documents like: </p>

<pre class="lang-json prettyprint-override"><code>{
  "university": {
    "state": [
      {
        "region": "usa",
        "pincode": 5693
      }
    ]
  }
}
</code>```

For you reference:
https://www.elastic.co/guide/en/elasticsearch/reference/2.0/nested.html

Body:
I created a index with mapping given below. And the index is empty

{
  "content": {
    "mappings": {
      "university": {
        "properties": {
          "state": {
            "type": "nested",
            "properties": {
              "pincode": {
                "type": "long"
              },
              "region": {
                "type": "string",
                "index": "not_analyzed"
              }
            }
          }
        }
      }
    }
  }
}

When i am inserting a document like this :

PUT content/university/1
    {
      "university": [
        {
          "state": {
            "region": "usa",
            "pincode": 5693
          }
        }
      ]
    }

It is creating a new mapping rather than joining in the one that defined previously.

{
  "content": {
    "mappings": {
      "university": {
        "properties": {
          "state": {
            "type": "nested",
            "properties": {
              "pincode": {
                "type": "long"
              },
              "region": {
                "type": "string",
                "index": "not_analyzed"
              }
            }
          },
          "university": {
            "properties": {
              "state": {
                "properties": {
                  "pincode": {
                    "type": "long"
                  },
                  "region": {
                    "type": "string"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

How i can avoid this in elasticsearch?

Whether i have to use inline scripts for this?

Body:
I think your mapping should be this:

{
  "content": {
    "mappings": {
      "university": {
        "type": "nested",
        "properties": {
          "state": {
            "properties": {
              "pincode": {
                "type": "long"
              },
              "region": {
                "type": "string",
                "index": "not_analyzed"
              }
            }
          }
        }
      }
    }
  }
}

If university is the object that is going to have nested properties like state then you need to declare the type of university field to be nested and not of state.
If however, you want the state to be of type nested, in that case i think you should try indexing documents like:

{
  "university": {
    "state": [
      {
        "region": "usa",
        "pincode": 5693
      }
    ]
  }
}

For you reference:
https://www.elastic.co/guide/en/elasticsearch/reference/2.0/nested.html


问:
how to create a jenkins job for a java project
I have a java project which executes successfully in my local machine. I need to execute the same using a JOB via Jenkins. Your answers are highly appreciated.</p>

答:
This is well documented on the Jenkins website, and elsewhere.

Please see Building a software project in particular, but also the Tutorials Point Jenkins tutorial (there is a dedicated section for setting up build jobs, as well as sections on configuring Maven etc).


问:
Json response parser for Array or Object
I am writing a library to consume a Json API and I am facing a design problem when using Gson as the parsing library.

One of the endpoints returns an array of objects if everything goes well like so:

```<code>[
  {
   "name": "John",
   "age" : 21
  },
  {
   "name": "Sarah",
   "age" : 32
  },
]
</code>```

However, the error schema for all the endpoints in the API is an json object instead of an array.

```<code>{
  "errors": [
     {
       "code": 1001,
       "message": "Something blew up"
     }
  ]
}
</code>```

The problem arises when modeling this in POJOs. Because the error schema is common for all the API endpoints, I decided to have an abstract ApiResponse class which will only map the errors attribute

```<code>public abstract class ApiResponse{

  @SerializedName("errors")
  List<ApiResponseError> errors;
}

public class ApiResponseError {

  @SerializedName("code")
  public Integer code;

  @SerializedName("message")
  public String message;
}
</code>```

Now I would like to inherit from ApiResponse to have the error mapping "for free" and a POJO per API endpoint response. However, the top level json object for this response is an array (if the server succeeds to execute the request), so I can not create a new class to map it like I would like it.

I decided to still create a class extending ApiResponse:

```<code>public class ApiResponsePerson extends ApiResponse {

  List<Person> persons;
}
</code>```

And implemented a custom deserializer to correctly parse the json depending on the type of the top level object, and setting it to the correct field on the following class:

```<code>public class DeserializerApiResponsePerson implements JsonDeserializer<ApiResponsePerson> {

  @Override
  public ApiResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

    ApiResponsePerson response = new ApiResponsePerson();
    if (json.isJsonArray()) {
      Type personType = new TypeToken<List<Person>>() {}.getType();
      response.persons = context.deserialize(json, personType);
      return response;
    }
    if (json.isJsonObject()) {
      JsonElement errorJson = json.getAsJsonObject().get("errors");
      Type errorsType = new TypeToken<List<ApiResponseError>>() {}.getType();
      response.errors = context.deserialize(errorJson, errorsType);
      return response;
    }
    throw new JsonParseException("Unexpected Json for 'ApiResponse'");
  }
}
</code>```

Which I will then add to the Gson

```<code>Gson gson = new GsonBuilder()
    .registerTypeAdapter(ApiResponsePerson.class, new DeserializerApiResponsePerson())
    .create();
</code>```

Is there any way to model this POJOs and have Gson recognize this structure without having to manually handle this scenario?
Is there any better way to accomplish this?
Am I missing any scenario where the deserializer might fail or not work as expected?

Thanks

答:
In your error-free case, since the top-level element is an array rather than an object, you have to use custom deserializers. You cannot escape from that. (I assume you cannot change the response formats.)

The best attempt to make the code cleaner, as far as I can see, is to create an abstract top-level deserializer class and check for error here. If there is no error, delegate parsing fields to some abstract method which will be implemented in custom serializers that you have written for each class.

Body:
I am writing a library to consume a Json API and I am facing a design problem when using Gson as the parsing library.

One of the endpoints returns an array of objects if everything goes well like so:

[
  {
   "name": "John",
   "age" : 21
  },
  {
   "name": "Sarah",
   "age" : 32
  },
]

However, the error schema for all the endpoints in the API is an json object instead of an array.

{
  "errors": [
     {
       "code": 1001,
       "message": "Something blew up"
     }
  ]
}

The problem arises when modeling this in POJOs. Because the error schema is common for all the API endpoints, I decided to have an abstract ApiResponse class which will only map the errors attribute

public abstract class ApiResponse{

  @SerializedName("errors")
  List<ApiResponseError> errors;
}

public class ApiResponseError {

  @SerializedName("code")
  public Integer code;

  @SerializedName("message")
  public String message;
}

Now I would like to inherit from ApiResponse to have the error mapping "for free" and a POJO per API endpoint response. However, the top level json object for this response is an array (if the server succeeds to execute the request), so I can not create a new class to map it like I would like it.

I decided to still create a class extending ApiResponse:

public class ApiResponsePerson extends ApiResponse {

  List<Person> persons;
}

And implemented a custom deserializer to correctly parse the json depending on the type of the top level object, and setting it to the correct field on the following class:

public class DeserializerApiResponsePerson implements JsonDeserializer<ApiResponsePerson> {

  @Override
  public ApiResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

    ApiResponsePerson response = new ApiResponsePerson();
    if (json.isJsonArray()) {
      Type personType = new TypeToken<List<Person>>() {}.getType();
      response.persons = context.deserialize(json, personType);
      return response;
    }
    if (json.isJsonObject()) {
      JsonElement errorJson = json.getAsJsonObject().get("errors");
      Type errorsType = new TypeToken<List<ApiResponseError>>() {}.getType();
      response.errors = context.deserialize(errorJson, errorsType);
      return response;
    }
    throw new JsonParseException("Unexpected Json for 'ApiResponse'");
  }
}

Which I will then add to the Gson

Gson gson = new GsonBuilder()
    .registerTypeAdapter(ApiResponsePerson.class, new DeserializerApiResponsePerson())
    .create();

Is there any way to model this POJOs and have Gson recognize this structure without having to manually handle this scenario?
Is there any better way to accomplish this?
Am I missing any scenario where the deserializer might fail or not work as expected?

Thanks


问:
Laravel: Undefined variable in blade view
This is AdminController.php:

<?php

namespace App\Http\Controllers;

use Response;

use Illuminate\Support\Facades\DB;
use App\Caption;
use App\Image;
use App\Http\Controllers\Controller;

class AdminController extends Controller
{
    public function admin() {
        $images = Image::paginate();

        return view('admin',[ '$images' => $images]);
    }
}
```

<p>And this is <code>admin.blade.php</code>:</p>

```@extends('template')

@section('title')
    Admin Page
@endsection

@section('header')
@endsection

@section('main')
    @if (Auth::check())
        @foreach ($images as $image)

id}}'>{{$image->content}}

            <form action="image/{{$image->id}}/delete" method="post">
                <button type="submit">Delete caption</button>
            </form>
            <form action="image/{{$image->id}}/approve" method="post">
                <button type="submit">Accept image</button>
            </form>
        @endforeach
    @else

Login first

    @endif
@endsection

@section('footer')
@endsection
```

Why do I get the following error?

ErrorException in 408148d5409ae6eebf768dc5721bd0d1d9af48af.php line 9:
  Undefined variable: images (View: /Users/sahandz/Documents/School/Singapore/CS3226/backend/resources/views/admin.blade.php)

$imagesis clearly defined in my controller.

答:
You may use this method also to pass your data to view

```<code> return view('admin',compact('images'));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is AdminController.php:

<?php

namespace App\Http\Controllers;

use Response;

use Illuminate\Support\Facades\DB;
use App\Caption;
use App\Image;
use App\Http\Controllers\Controller;

class AdminController extends Controller
{
    public function admin() {
        $images = Image::paginate();

        return view('admin',[ '$images' => $images]);
    }
}

And this is admin.blade.php:

@extends('template')

@section('title')
    Admin Page
@endsection

@section('header')
@endsection

@section('main')
    @if (Auth::check())
        @foreach ($images as $image)

id}}'>{{$image->content}}

            <form action="image/{{$image->id}}/delete" method="post">
                <button type="submit">Delete caption</button>
            </form>
            <form action="image/{{$image->id}}/approve" method="post">
                <button type="submit">Accept image</button>
            </form>
        @endforeach
    @else

Login first

    @endif
@endsection

@section('footer')
@endsection

Why do I get the following error?

ErrorException in 408148d5409ae6eebf768dc5721bd0d1d9af48af.php line 9:
  Undefined variable: images (View: /Users/sahandz/Documents/School/Singapore/CS3226/backend/resources/views/admin.blade.php)

$imagesis clearly defined in my controller.

Body:
You may use this method also to pass your data to view

 return view('admin',compact('images'));


问:
Mocking Objects Containing SubObjects With Rhino Mocks
Assuming an IMouvement Object which contains some subobjects like ITache, IStockPalette.

```<code>public interface IMouvement : IObjectBase<Guid>
{
        ITache Tache { get; set; }
        IStockPalette StockPalOrigine { get; set; }
}
</code>```

How can I Mock this using Rhino Mocks ?

Assuming this test, what's wrong with this ?

```<code>[TestMethod]
public void Can_Validate_EmplacementTransitoireRule()
{
    var mocks = new MockRepository();
    var mouvement = mocks.StrictMock<IMouvement>();
    var manager = mocks.StrictMock<ValidationManager>();

    mouvement.Tache = mocks.StrictMock<ITache>();
    mouvement.StockPalOrigine = mocks.StrictMock<IStockPalette>();
    mouvement.ID = Guid.NewGuid();

    var rule = new EmplacementTransitoireRule(mouvement);
    manager.AddRule(rule);

    Expect.Call(manager.ValidateAll()).Return(true);

    mocks.ReplayAll();

    var all = manager.ValidateAll();

    mocks.VerifyAll();

    Assert.IsTrue(all);
}
</code>```

this Test always fails ..

答:
Typically I would set up expectations on the mock objects instead of merely assigning their properties.

```<code> Tache tache = mocks.StrictMock<Tache>();
 Expect.Call( mouvement.Tache ).Return( tache );
</code>```

Also, you may want to use the AAA (Arrange-Act-Assert) syntax for RhinoMocks -- I believe that StrictMock has been deprecated.

```<code> Mouvement mouvement = MockRepository.GenerateMock<Mouvement>();
 Tache tache = MockRepository.GenerateMock<Tache>();

 mouvement.Expect( m => m.Tache ).Return( tache );
 tache.Expect( t => t.Value ).Return( 100 );  // or whatever

 ... test code...

 tache.VerifyAllExpectations();
 mouvement.VerifyAllExpectations();
</code>```

OwnerDisplayName: Yoann. B

Body:
Assuming an IMouvement Object which contains some subobjects like ITache, IStockPalette.

public interface IMouvement : IObjectBase<Guid>
{
        ITache Tache { get; set; }
        IStockPalette StockPalOrigine { get; set; }
}

How can I Mock this using Rhino Mocks ?

Assuming this test, what's wrong with this ?

[TestMethod]
public void Can_Validate_EmplacementTransitoireRule()
{
    var mocks = new MockRepository();
    var mouvement = mocks.StrictMock<IMouvement>();
    var manager = mocks.StrictMock<ValidationManager>();

    mouvement.Tache = mocks.StrictMock<ITache>();
    mouvement.StockPalOrigine = mocks.StrictMock<IStockPalette>();
    mouvement.ID = Guid.NewGuid();

    var rule = new EmplacementTransitoireRule(mouvement);
    manager.AddRule(rule);

    Expect.Call(manager.ValidateAll()).Return(true);

    mocks.ReplayAll();

    var all = manager.ValidateAll();

    mocks.VerifyAll();

    Assert.IsTrue(all);
}

this Test always fails ..

Body:
Typically I would set up expectations on the mock objects instead of merely assigning their properties.

 Tache tache = mocks.StrictMock<Tache>();
 Expect.Call( mouvement.Tache ).Return( tache );

Also, you may want to use the AAA (Arrange-Act-Assert) syntax for RhinoMocks -- I believe that StrictMock has been deprecated.

 Mouvement mouvement = MockRepository.GenerateMock<Mouvement>();
 Tache tache = MockRepository.GenerateMock<Tache>();

 mouvement.Expect( m => m.Tache ).Return( tache );
 tache.Expect( t => t.Value ).Return( 100 );  // or whatever

 ... test code...

 tache.VerifyAllExpectations();
 mouvement.VerifyAllExpectations();

OwnerDisplayName: tvanfosson


问:
Android Play store upload apk production error
Hi guys I was trying to upload apk for production however I got this error message: "You don't have rights to modify the application."

I was invited by as a user in the team. I'm guessing that it has something to do with that? Anyone here experienced the same error?

答:
In order to upload an APK for another account you need one of these:

Manage Production APKs

Manage Alpha & Beta APKs

In case this is the first APK that's being uploaded for this app, then you will also need the permission:

Create & edit draft apps


问:
Splitting a list into N parts of approximately equal length
What is the best way to divide a list into roughly equal parts? For example, if the list has 7 elements and is split it into 2 parts, we want to get 3 elements in one part, and the other should have 4 elements.

I'm looking for something like even_split(L, n) that breaks L into n parts.

```<code>def chunks(L, n):
    """ Yield successive n-sized chunks from L.
    """
    for i in range(0, len(L), n):
        yield L[i:i+n]
</code>```

The code above gives chunks of 3, rather than 3 chunks.  I could simply transpose (iterate over this and take the first element of each column, call that part one, then take the second and put it in part two, etc), but that destroys the ordering of the items.

答:
Here's a generator that can handle any positive (integer) number of chunks. If the number of chunks is greater than the input list length some chunks will be empty. This algorithm alternates between short and long chunks rather than segregating them.

I've also included some code for testing the ragged_chunks function.

```<code>''' Split a list into "ragged" chunks

    The size of each chunk is either the floor or ceiling of len(seq) / chunks

    chunks can be > len(seq), in which case there will be empty chunks

    Written by PM 2Ring 2017.03.30
'''

def ragged_chunks(seq, chunks):
    size = len(seq)
    start = 0
    for i in range(1, chunks + 1):
        stop = i * size // chunks
        yield seq[start:stop]
        start = stop

# test

def test_ragged_chunks(maxsize):
    for size in range(0, maxsize):
        seq = list(range(size))
        for chunks in range(1, size + 1):
            minwidth = size // chunks
            #ceiling division
            maxwidth = -(-size // chunks)
            a = list(ragged_chunks(seq, chunks))
            sizes = [len(u) for u in a]
            deltas = all(minwidth <= u <= maxwidth for u in sizes)
            assert all((sum(a, []) == seq, sum(sizes) == size, deltas))
    return True

if test_ragged_chunks(100):
    print('ok')
</code>```

We can make this slightly more efficient by exporting the multiplication into the range call, but I think the previous version is more readable (and DRYer).

```<code>def ragged_chunks(seq, chunks):
    size = len(seq)
    start = 0
    for i in range(size, size * chunks + 1, size):
        stop = i // chunks
        yield seq[start:stop]
        start = stop
</code>```

Body:
What is the best way to divide a list into roughly equal parts? For example, if the list has 7 elements and is split it into 2 parts, we want to get 3 elements in one part, and the other should have 4 elements.

I'm looking for something like even_split(L, n) that breaks L into n parts.

def chunks(L, n):
    """ Yield successive n-sized chunks from L.
    """
    for i in range(0, len(L), n):
        yield L[i:i+n]

The code above gives chunks of 3, rather than 3 chunks.  I could simply transpose (iterate over this and take the first element of each column, call that part one, then take the second and put it in part two, etc), but that destroys the ordering of the items.

Body:
Here's a generator that can handle any positive (integer) number of chunks. If the number of chunks is greater than the input list length some chunks will be empty. This algorithm alternates between short and long chunks rather than segregating them.

I've also included some code for testing the ragged_chunks function.

''' Split a list into "ragged" chunks

    The size of each chunk is either the floor or ceiling of len(seq) / chunks

    chunks can be > len(seq), in which case there will be empty chunks

    Written by PM 2Ring 2017.03.30
'''

def ragged_chunks(seq, chunks):
    size = len(seq)
    start = 0
    for i in range(1, chunks + 1):
        stop = i * size // chunks
        yield seq[start:stop]
        start = stop

# test

def test_ragged_chunks(maxsize):
    for size in range(0, maxsize):
        seq = list(range(size))
        for chunks in range(1, size + 1):
            minwidth = size // chunks
            #ceiling division
            maxwidth = -(-size // chunks)
            a = list(ragged_chunks(seq, chunks))
            sizes = [len(u) for u in a]
            deltas = all(minwidth <= u <= maxwidth for u in sizes)
            assert all((sum(a, []) == seq, sum(sizes) == size, deltas))
    return True

if test_ragged_chunks(100):
    print('ok')

We can make this slightly more efficient by exporting the multiplication into the range call, but I think the previous version is more readable (and DRYer).

def ragged_chunks(seq, chunks):
    size = len(seq)
    start = 0
    for i in range(size, size * chunks + 1, size):
        stop = i // chunks
        yield seq[start:stop]
        start = stop


问:
Multiple class selecting in CSS
```<code>.upload header {...}
</code>```

Styling will be applied to any header that is a child of any element with class of '.upload'.

Is it possible to do this?

```<code>.upload header, form {...}
</code>```

Or will I have to specify the class for every type selector ?

答:
You can't do that. The comma for selector works like the following:

```<code>div > nav,
p {
   display: block;
}
</code>```

Is exactly the same as writting

```<code>div > nav { display: block; }
p { display: block; }
</code>```

The comma is used to re-use rules, but each selector is global, and does not use the same parent.

In your case, if you want to make the rule only apply to those form elements that are children of .upload, you would have to do

```<code>.upload header, .upload form {...}
</code>```

Title: Multiple class selecting in CSS

Body:
.upload header {...}

Styling will be applied to any header that is a child of any element with class of '.upload'.

Is it possible to do this?

.upload header, form {...}

Or will I have to specify the class for every type selector ?

Body:
You can't do that. The comma for selector works like the following:

div > nav,
p {
   display: block;
}

Is exactly the same as writting

div > nav { display: block; }
p { display: block; }

The comma is used to re-use rules, but each selector is global, and does not use the same parent.

In your case, if you want to make the rule only apply to those form elements that are children of .upload, you would have to do

.upload header, .upload form {...}


问:
how to print the information in file descriptor in C.
```<code>(gdb) print* data_out_file[0]
$1 = {_flags = -1, _IO_read_ptr = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_read_end = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_read_base = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_write_base = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_write_ptr = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_write_end = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_buf_base = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_buf_end = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_save_base = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_backup_base = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_save_end = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>, _markers = 0xffffffffffffffff, _chain = 0x11004147ffffffff,
  _fileno = 498074112, _flags2 = 12648704, _old_offset = 135392766359363840, _cur_column = 240, _vtable_offset = 66 'B', _shortbuf = "á",
  _lock = 0xecfc392019202004, _offset = -35, __pad1 = 0xffffffffffffffff, __pad2 = 0xffffffffffffffff, __pad3 = 0xffffffffffffffff,
  __pad4 = 0xffffffffffffffff, __pad5 = 18446744073709551615, _mode = -1, _unused2 = 'ÿ' <repeats 20 times>}
</code>```

in GDB if we print the file pointer we get the descriptor.
just wondering how do we do it in C code like printf ?

答:
Assuming you want the int file descriptor value associated with a valid FILE * stream object, you use the fileno() function:

NAME

fileno - map a stream pointer to a file descriptor

SYNOPSIS

```<code>#include <stdio.h>

int fileno(FILE *stream);
</code>```

DESCRIPTION

The fileno() function shall return the integer file descriptor
  associated with the stream pointed to by stream.

RETURN VALUE

Upon successful completion, fileno() shall return the integer value
  of the file descriptor associated with stream. Otherwise, the value
  -1 shall be returned and errno set to indicate the error.

You do not dereference the FILE * stream object itself.  Doing so results in fragile, non-portable code that's prone to breakage.  On some implementations, the FILE * structure simply can not be dereferenced.

Body:
(gdb) print* data_out_file[0]
$1 = {_flags = -1, _IO_read_ptr = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_read_end = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_read_base = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_write_base = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_write_ptr = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_write_end = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_buf_base = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_buf_end = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_save_base = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_backup_base = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>,
  _IO_save_end = 0xffffffffffffffff <Address 0xffffffffffffffff out of bounds>, _markers = 0xffffffffffffffff, _chain = 0x11004147ffffffff,
  _fileno = 498074112, _flags2 = 12648704, _old_offset = 135392766359363840, _cur_column = 240, _vtable_offset = 66 'B', _shortbuf = "á",
  _lock = 0xecfc392019202004, _offset = -35, __pad1 = 0xffffffffffffffff, __pad2 = 0xffffffffffffffff, __pad3 = 0xffffffffffffffff,
  __pad4 = 0xffffffffffffffff, __pad5 = 18446744073709551615, _mode = -1, _unused2 = 'ÿ' <repeats 20 times>}

in GDB if we print the file pointer we get the descriptor.
just wondering how do we do it in C code like printf ?

Body:
Assuming you want the int file descriptor value associated with a valid FILE * stream object, you use the fileno() function:

NAME

fileno - map a stream pointer to a file descriptor

SYNOPSIS

#include <stdio.h>

int fileno(FILE *stream);

DESCRIPTION

The fileno() function shall return the integer file descriptor
  associated with the stream pointed to by stream.

RETURN VALUE

Upon successful completion, fileno() shall return the integer value
  of the file descriptor associated with stream. Otherwise, the value
  -1 shall be returned and errno set to indicate the error.

You do not dereference the FILE * stream object itself.  Doing so results in fragile, non-portable code that's prone to breakage.  On some implementations, the FILE * structure simply can not be dereferenced.


问:
I keep getting an error when trying to insert data into SQLite database with java
I keep  getting the error "error in setting data!", please could you see if there is any obvious problem. I am running the database through sqlite. Please could you help to see what the problem is, thanks.

The sql database strusture:

package parts_system;

```<code>import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
/**
 *
 * @author bened_000
 */
public class FXMLDocumentController implements Initializable {

    @FXML
    private Label label;
    @FXML
    private TextArea AddPartCostStock;
    @FXML
    private TextArea AddPartDescriptionStock;
    @FXML
    private TableView<?> StockTable;
    @FXML
    private Button AddToStock;
    @FXML
    private Button RemoveFromStock;
    @FXML
    private Button EditVehicle;
    @FXML
    private TextArea VPAddVehicleReg;
    @FXML
    private Button AddToVehicle;
    @FXML
    private TextArea AddPartAmountStock;
    @FXML
    private TextArea SearchStock;
    @FXML
    private TextArea VPAddCustomerName;
    @FXML
    private TableView<?> VehiclePartTable;
    @FXML
    private TextArea VPAddPartName;
    @FXML
    private TextArea VPAddPartID;
    @FXML
    private TextArea SearchVehicle;
    @FXML
    private ChoiceBox<?> SearchOptionsVehicle;
    @FXML
    private TextArea VPAddDateInstall;
    @FXML
    private Button Exit;

   private ObservableList<stock> stocklist=FXCollections.observableArrayList();
   private  ObservableList<part> list2=FXCollections.observableArrayList();
   private final ObservableList comboOption =FXCollections.observableArrayList();

   @FXML
    private TextArea AddPartNameStock;
    @FXML
    private TableColumn<?, ?> sName;
    @FXML
    private TableColumn<?, ?> sAmount;
    @FXML
    private TableColumn<?, ?> sCost;
    @FXML
    private TableColumn<?, ?> sDescription;
    @FXML
    private TableColumn<?, ?> vPartID;
    @FXML
    private TableColumn<?, ?> vName;
    @FXML
    private TableColumn<?, ?> vCost;
    @FXML
    private TableColumn<?, ?> vDescription;
    @FXML
    private TableColumn<?, ?> vVehicleReg;
    @FXML
    private TableColumn<?, ?> vCustomerName;
    @FXML
    private TableColumn<?, ?> vInstallationDate;
    @FXML
    private TableColumn<?, ?> vWarrantyExpires;
    @FXML
    private TableColumn<?, ?> vRepairID;
    @FXML
    private TextArea VPAddRepairID;

    @FXML void addStock(ActionEvent event) throws IOException{
        try{
               Class.forName("org.sqlite.JDBC");
               Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\bened_000\\Documents\\NetBeansProjects\\garage\\SE35-master\\scratch\\Benedict\\parts_System\\src\\parts_system\\new.sqlite");

 String sql= "INSERT INTO stock(name,numberofparts,cost,description)VALUES(?,?,?,?)";

        PreparedStatement stmt1 =conn.prepareStatement(sql);

       stmt1.setString(2, AddPartNameStock.getText());
       stmt1.setDouble(3, Double.parseDouble(AddPartAmountStock.getText()));
       stmt1.setDouble(4, Double.parseDouble(AddPartCostStock.getText()));
       stmt1.setString(5, AddPartDescriptionStock.getText());

        stmt1.execute();
        stmt1.close();
        conn.close();

    } catch (Exception e) {
                System.out.println("error in setting data!");
            }

    }
</code>```

答:
You have to start setting your fields from 1 and not 2:

```<code>stmt1.setString(1, AddPartNameStock.getText());
stmt1.setDouble(2, Double.parseDouble(AddPartAmountStock.getText()));
stmt1.setDouble(3, Double.parseDouble(AddPartCostStock.getText()));
stmt1.setString(4, AddPartDescriptionStock.getText());
</code>```

For the second problem :

```<code>error :java.lang.ClassNotFoundException:
</code>```

This already answerd here
java.lang.ClassNotFoundException: org.sqlite.JDBC error in Sample.java program from xerial

Body:
I keep  getting the error "error in setting data!", please could you see if there is any obvious problem. I am running the database through sqlite. Please could you help to see what the problem is, thanks.

The sql database strusture:

package parts_system;

import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
/**
 *
 * @author bened_000
 */
public class FXMLDocumentController implements Initializable {

    @FXML
    private Label label;
    @FXML
    private TextArea AddPartCostStock;
    @FXML
    private TextArea AddPartDescriptionStock;
    @FXML
    private TableView<?> StockTable;
    @FXML
    private Button AddToStock;
    @FXML
    private Button RemoveFromStock;
    @FXML
    private Button EditVehicle;
    @FXML
    private TextArea VPAddVehicleReg;
    @FXML
    private Button AddToVehicle;
    @FXML
    private TextArea AddPartAmountStock;
    @FXML
    private TextArea SearchStock;
    @FXML
    private TextArea VPAddCustomerName;
    @FXML
    private TableView<?> VehiclePartTable;
    @FXML
    private TextArea VPAddPartName;
    @FXML
    private TextArea VPAddPartID;
    @FXML
    private TextArea SearchVehicle;
    @FXML
    private ChoiceBox<?> SearchOptionsVehicle;
    @FXML
    private TextArea VPAddDateInstall;
    @FXML
    private Button Exit;

   private ObservableList<stock> stocklist=FXCollections.observableArrayList();
   private  ObservableList<part> list2=FXCollections.observableArrayList();
   private final ObservableList comboOption =FXCollections.observableArrayList();

   @FXML
    private TextArea AddPartNameStock;
    @FXML
    private TableColumn<?, ?> sName;
    @FXML
    private TableColumn<?, ?> sAmount;
    @FXML
    private TableColumn<?, ?> sCost;
    @FXML
    private TableColumn<?, ?> sDescription;
    @FXML
    private TableColumn<?, ?> vPartID;
    @FXML
    private TableColumn<?, ?> vName;
    @FXML
    private TableColumn<?, ?> vCost;
    @FXML
    private TableColumn<?, ?> vDescription;
    @FXML
    private TableColumn<?, ?> vVehicleReg;
    @FXML
    private TableColumn<?, ?> vCustomerName;
    @FXML
    private TableColumn<?, ?> vInstallationDate;
    @FXML
    private TableColumn<?, ?> vWarrantyExpires;
    @FXML
    private TableColumn<?, ?> vRepairID;
    @FXML
    private TextArea VPAddRepairID;

    @FXML void addStock(ActionEvent event) throws IOException{
        try{
               Class.forName("org.sqlite.JDBC");
               Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\bened_000\\Documents\\NetBeansProjects\\garage\\SE35-master\\scratch\\Benedict\\parts_System\\src\\parts_system\\new.sqlite");

 String sql= "INSERT INTO stock(name,numberofparts,cost,description)VALUES(?,?,?,?)";

        PreparedStatement stmt1 =conn.prepareStatement(sql);

       stmt1.setString(2, AddPartNameStock.getText());
       stmt1.setDouble(3, Double.parseDouble(AddPartAmountStock.getText()));
       stmt1.setDouble(4, Double.parseDouble(AddPartCostStock.getText()));
       stmt1.setString(5, AddPartDescriptionStock.getText());

        stmt1.execute();
        stmt1.close();
        conn.close();

    } catch (Exception e) {
                System.out.println("error in setting data!");
            }

    }

Body:
You have to start setting your fields from 1 and not 2:

stmt1.setString(1, AddPartNameStock.getText());
stmt1.setDouble(2, Double.parseDouble(AddPartAmountStock.getText()));
stmt1.setDouble(3, Double.parseDouble(AddPartCostStock.getText()));
stmt1.setString(4, AddPartDescriptionStock.getText());

For the second problem :

error :java.lang.ClassNotFoundException:

This already answerd here
java.lang.ClassNotFoundException: org.sqlite.JDBC error in Sample.java program from xerial


问:
Workaround for Fragment URLs not allowed with Google Redirect URI
I use mac to develop a MEAN stack project. My web pages https://localhost:3000/#/login and https://localhost:3000/#/new work (note that all my pages need to have /#/ in the middle to work). https://localhost:3000/#/new has a button that leads to a google login by passportjs. In my routes ==> index.js I set

```<code>var express = require('express');
var router = express.Router();
... ...

router.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
router.get('/auth/google/callback',
  passport.authenticate('google', { successRedirect: '/login',
                                    failureRedirect: '/login' }));
</code>```

In Google APIs ==> Credentials, when I set https://localhost:3000/auth/google/callback as Authorized redirect URIs. Clicking on the login button on my page returns an error

```<code>Error: redirect_uri_mismatch

The redirect URI in the request, https://localhost:3000/auth/facebook/callback, does not match the ones authorized for the OAuth client. Visit https://console.developers.google.com/apis/credentials/oauthclient/367100934152-7csfhcdnkapil4obku1pr2cnrsmthk61.apps.googleusercontent.com?project=367100934152 to update the authorized redirect URIs.
</code>```

I guess it is because https://localhost:3000/auth/facebook/callback is not a valid URI for my app, but if I set https://localhost:3000/#/auth/facebook/callback in the setting page, it is NOT allowed: Invalid Redirect: https://localhost:3000/#/auth/google/callback cannot contain a fragment.

So, does anyone know if I could modify my app to work without #, so that https://localhost:3000/login and https://localhost:3000/new, etc. will work? As a result, https://localhost:3000/auth/facebook/callback will be a valid URI too...

Edit 1:

Following the answer of @Sevran and the doc how to configure your server to work with html5mode, I did the following:

1) added $locationProvider.html5Mode(true) in app.config

2) added <base href="/" /> in index.ejs (note I don't have index.html in the project)

3) keeps .state('new', url: '/new', ... in app.config

4) did NOTHING in httpd-vhosts.conf, which has <VirtualHost *:80> and <VirtualHost *:433>, because I think my server is controlled by express.js rather than httpd-vhosts.conf, and the port is 3000.

5) did NOT add .htaccess in the project like this answer

6) added in app.js the following, I also tried to change index.html to index.ejs.

```<code>app.use('/js', express.static(__dirname + '/js'));
app.use('/dist', express.static(__dirname + '/../dist'));
app.use('/css', express.static(__dirname + '/css'));
app.use('/partials', express.static(__dirname + '/partials'));

app.all('/*', function(req, res, next) {
    // Just send the index.html for other files to support HTML5Mode
    res.sendFile('index.html', { root: __dirname });
});
</code>```

The tests shows

entering https://localhost:3000/#/new in the URL bar becomes https://localhost:3000/new, and it loads the corresponding page.

entering https://localhost:3000/new in the URL bar raises a not found 404 error.

entering https://localhost:3000/auth/google in the URL bar raises the Error: redirect_uri_mismatch as above.

To conclude, I think the rewriting (of a url without #) should be managed by express, but the code I posted did not do the job. Regarding .htaccess, I tried also to put it in the DocumentRoot of httpd-vhosts.conf or the root folder of the project, it did not help.

答:
You can remove the hash from your URL using the HTML5 mode:

```<code>appModule.config(['$locationProvider', function($locationProvider) {
    $locationProvider.html5Mode(true);
}]);
</code>```

Don't forget to set the base in your  tag:

```<code><head>
    <base href="/">
    ...
</head>
</code>```

Note that if you are using Angular 1.6, you also need to change the hashPrefix:

```<code>appModule.config(['$locationProvider', function($locationProvider) {
    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix(''); // remove the ! from URL
}]);
</code>```

More info about the changelog here.

Body:
I use mac to develop a MEAN stack project. My web pages https://localhost:3000/#/login and https://localhost:3000/#/new work (note that all my pages need to have /#/ in the middle to work). https://localhost:3000/#/new has a button that leads to a google login by passportjs. In my routes ==> index.js I set

var express = require('express');
var router = express.Router();
... ...

router.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
router.get('/auth/google/callback',
  passport.authenticate('google', { successRedirect: '/login',
                                    failureRedirect: '/login' }));

In Google APIs ==> Credentials, when I set https://localhost:3000/auth/google/callback as Authorized redirect URIs. Clicking on the login button on my page returns an error

Error: redirect_uri_mismatch

The redirect URI in the request, https://localhost:3000/auth/facebook/callback, does not match the ones authorized for the OAuth client. Visit https://console.developers.google.com/apis/credentials/oauthclient/367100934152-7csfhcdnkapil4obku1pr2cnrsmthk61.apps.googleusercontent.com?project=367100934152 to update the authorized redirect URIs.

I guess it is because https://localhost:3000/auth/facebook/callback is not a valid URI for my app, but if I set https://localhost:3000/#/auth/facebook/callback in the setting page, it is NOT allowed: Invalid Redirect: https://localhost:3000/#/auth/google/callback cannot contain a fragment.

So, does anyone know if I could modify my app to work without #, so that https://localhost:3000/login and https://localhost:3000/new, etc. will work? As a result, https://localhost:3000/auth/facebook/callback will be a valid URI too...

Edit 1:

Following the answer of @Sevran and the doc how to configure your server to work with html5mode, I did the following:

1) added $locationProvider.html5Mode(true) in app.config

2) added <base href="/" /> in index.ejs (note I don't have index.html in the project)

3) keeps .state('new', url: '/new', ... in app.config

4) did NOTHING in httpd-vhosts.conf, which has <VirtualHost *:80> and <VirtualHost *:433>, because I think my server is controlled by express.js rather than httpd-vhosts.conf, and the port is 3000.

5) did NOT add .htaccess in the project like this answer

6) added in app.js the following, I also tried to change index.html to index.ejs.

app.use('/js', express.static(__dirname + '/js'));
app.use('/dist', express.static(__dirname + '/../dist'));
app.use('/css', express.static(__dirname + '/css'));
app.use('/partials', express.static(__dirname + '/partials'));

app.all('/*', function(req, res, next) {
    // Just send the index.html for other files to support HTML5Mode
    res.sendFile('index.html', { root: __dirname });
});

The tests shows

entering https://localhost:3000/#/new in the URL bar becomes https://localhost:3000/new, and it loads the corresponding page.

entering https://localhost:3000/new in the URL bar raises a not found 404 error.

entering https://localhost:3000/auth/google in the URL bar raises the Error: redirect_uri_mismatch as above.

To conclude, I think the rewriting (of a url without #) should be managed by express, but the code I posted did not do the job. Regarding .htaccess, I tried also to put it in the DocumentRoot of httpd-vhosts.conf or the root folder of the project, it did not help.

Body:
You can remove the hash from your URL using the HTML5 mode:

appModule.config(['$locationProvider', function($locationProvider) {
    $locationProvider.html5Mode(true);
}]);

Don't forget to set the base in your <head> tag:

<head>
    <base href="/">
    ...
</head>

Note that if you are using Angular 1.6, you also need to change the hashPrefix:

appModule.config(['$locationProvider', function($locationProvider) {
    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix(''); // remove the ! from URL
}]);

More info about the changelog here.


问:
How to hide save order button in woocommerce edit orders?
How to hide save order button from admin in woocommerce edit orders if specific role is logged in?</p>

答:
Orders menu is protected by ‘edit_shop_orders’ capability. It’s possible to prohibit new order creation if you activate ‘create’ capability at User Role Editor Settings.

But ‘edit_shop_orders’ capability is enough to ‘process’ and ‘complete’ the order. The only way to allow a read-only access to the WooCommerce orders is to use this filter from WooCommerce code:

```<code>$actions = apply_filters( 'woocommerce_admin_order_actions', $actions, $the_order );
</code>```

Your function for this filter should return empty $actions array for ‘editor’ role in order to make for them read-only access.

Let me know if you need further help.

Add This piece of code to function which gets executed ONLY for "specific" role:

```<code>function add_my_action($actions, $the_order){

    return array();
}
add_filter( 'woocommerce_admin_order_actions', 'add_my_action', 10, 2);**
</code>```

Body:
Orders menu is protected by ‘edit_shop_orders’ capability. It’s possible to prohibit new order creation if you activate ‘create’ capability at User Role Editor Settings.

But ‘edit_shop_orders’ capability is enough to ‘process’ and ‘complete’ the order. The only way to allow a read-only access to the WooCommerce orders is to use this filter from WooCommerce code:

$actions = apply_filters( 'woocommerce_admin_order_actions', $actions, $the_order );

Your function for this filter should return empty $actions array for ‘editor’ role in order to make for them read-only access.

Let me know if you need further help.

Add This piece of code to function which gets executed ONLY for "specific" role:

function add_my_action($actions, $the_order){

    return array();
}
add_filter( 'woocommerce_admin_order_actions', 'add_my_action', 10, 2);**


问:
How to rename id field in an entity using with elasticsearch?
Hi friends i am using elastic search with spring boot project and my primary database is mysql. My project is running fine with default configuration . Suppose my entity is CancelReason.java

```<code>@Entity
@Table(name = "cancel_reason")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "cancelreason")
public class CancelReason implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotNull
    @Size(max = 10)
    @Column(name = "reason_code", length = 10, nullable = false)
    private String reasonCode;
    .......
}
</code>```

Now with this configuration my project is running and elastic search is working fine but my requirment is to make reasonCode primary key instead of id so i want to remove

```<code>    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
</code>```

this code. as i remove id field and make reasonCode primarykey and when i run my project it gives me this error:

```<code>[WARN] org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cancelReasonManager': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private in.megacabs.repository.search.CancelReasonSearchRepository in.megacabs.manager.CancelReasonManager.cancelReasonSearchRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cancelReasonSearchRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No id property found for class in.megacabs.domain.CancelReason!
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) ~[spring-context-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) ~[spring-context-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) [spring-boot-1.2.5.RELEASE.jar:1.2.5.RELEASE]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686) [spring-boot-1.2.5.RELEASE.jar:1.2.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:320) [spring-boot-1.2.5.RELEASE.jar:1.2.5.RELEASE]
        at in.megacabs.Application.main(Application.java:77) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private in.megacabs.repository.search.CancelReasonSearchRepository in.megacabs.manager.CancelReasonManager.cancelReasonSearchRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cancelReasonSearchRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No id property found for class in.megacabs.domain.CancelReason!
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
</code>```

Though mysql is working fine entity is beign created in mysql database but not in elasticsearch.
Please help!

答:
Try adding this annotations in the primary key field:

```<code>@Id
@org.springframework.data.annotation.Id
</code>```

Regards.

Body:
Hi friends i am using elastic search with spring boot project and my primary database is mysql. My project is running fine with default configuration . Suppose my entity is CancelReason.java

@Entity
@Table(name = "cancel_reason")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "cancelreason")
public class CancelReason implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotNull
    @Size(max = 10)
    @Column(name = "reason_code", length = 10, nullable = false)
    private String reasonCode;
    .......
}

Now with this configuration my project is running and elastic search is working fine but my requirment is to make reasonCode primary key instead of id so i want to remove

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

this code. as i remove id field and make reasonCode primarykey and when i run my project it gives me this error:

[WARN] org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cancelReasonManager': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private in.megacabs.repository.search.CancelReasonSearchRepository in.megacabs.manager.CancelReasonManager.cancelReasonSearchRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cancelReasonSearchRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No id property found for class in.megacabs.domain.CancelReason!
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) ~[spring-context-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) ~[spring-context-4.1.7.RELEASE.jar:4.1.7.RELEASE]
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) [spring-boot-1.2.5.RELEASE.jar:1.2.5.RELEASE]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686) [spring-boot-1.2.5.RELEASE.jar:1.2.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:320) [spring-boot-1.2.5.RELEASE.jar:1.2.5.RELEASE]
        at in.megacabs.Application.main(Application.java:77) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private in.megacabs.repository.search.CancelReasonSearchRepository in.megacabs.manager.CancelReasonManager.cancelReasonSearchRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cancelReasonSearchRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No id property found for class in.megacabs.domain.CancelReason!
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]

Though mysql is working fine entity is beign created in mysql database but not in elasticsearch.
Please help!

Body:
Try adding this annotations in the primary key field:

@Id
@org.springframework.data.annotation.Id

Regards.