问:
Using a Promise inside a Dexie iteration
I am not really a Promise Ninja and I understand that I'm doing something wrong. However I cannot find some particular/simular problem to what I am having.

The problem: I use the Dexie.js wrapper for IndexedDB which is asynchronous. I have a global database which leads to some other dexie databases.

```<code>function handleDatabases() {
    var result = [];

    db.jobs.orderBy('title').filter(function(job) {
        return job.someBooleanCondition;
    }).each(function(job, cursor) {
        let jobDetails = new Dexie(job.correspondingDB);
        jobDetails.version(1).stores({
            details: 'key,value1,value2'
        });
        jobDetails.details.get(someKey).then(function(detail) {
            result.push({job: job, detail: detail});
        })
    }).catch(function(error) {
        console.log(error);
    });
    handleResult(result);
}
</code>```

I have rewritten it for SO with a maybe strange form but the end goal is that i can use the array result to handle some update. However since it is asynchronous it is always empty until you inspect it in console where it is never empty. How can I rewrite this to be synchronous?

答:
You cannot expect to return the result when that result only becomes available asynchronously.

So you must stick with promises all the way (returning them each time), and let your function also return a promise. The caller must use then (or await if supported) to allow (asynchronous) access to the result.

Instead of pushing the {job: job, detail: detail} to a results variable, return it. It will become the promised value for jobDetails.details.get(..).then(..). If you return also that, you'll have an array of promises, which can then be resolved with Promise.all

Avoid to create new Promises as that usually leads to the promise constructor antipattern.

Also avoid using a variable (like results) that is used in several callbacks without being passed as argument. Instead try to construct and return that array as a promised value, so it can be used in the next then callback.

Here is the suggested (untested) code:

```<code>function handleDatabases() {
    db.jobs
    .orderBy('title')
    .filter(job => job.someBooleanCondition)
    .toArray(jobs =>
        jobs.map(job => {
            let jobDetails = new Dexie(job.correspondingDB);
            jobDetails.version(1).stores({
                details: 'key,value1,value2'
            });
            return jobDetails.details.get(someKey)
                   .then(detail => ({job: job, detail: detail}))
        }) // is returned
    )
    .then(result => Promise.all(result))
    .then(handleResult)
    .catch(error => console.log(error));
}
</code>```

Body:
I am not really a Promise Ninja and I understand that I'm doing something wrong. However I cannot find some particular/simular problem to what I am having.

The problem: I use the Dexie.js wrapper for IndexedDB which is asynchronous. I have a global database which leads to some other dexie databases.

function handleDatabases() {
    var result = [];

    db.jobs.orderBy('title').filter(function(job) {
        return job.someBooleanCondition;
    }).each(function(job, cursor) {
        let jobDetails = new Dexie(job.correspondingDB);
        jobDetails.version(1).stores({
            details: 'key,value1,value2'
        });
        jobDetails.details.get(someKey).then(function(detail) {
            result.push({job: job, detail: detail});
        })
    }).catch(function(error) {
        console.log(error);
    });
    handleResult(result);
}

I have rewritten it for SO with a maybe strange form but the end goal is that i can use the array result to handle some update. However since it is asynchronous it is always empty until you inspect it in console where it is never empty. How can I rewrite this to be synchronous?

Body:
You cannot expect to return the result when that result only becomes available asynchronously.

So you must stick with promises all the way (returning them each time), and let your function also return a promise. The caller must use then (or await if supported) to allow (asynchronous) access to the result.

Instead of pushing the {job: job, detail: detail} to a results variable, return it. It will become the promised value for jobDetails.details.get(..).then(..). If you return also that, you'll have an array of promises, which can then be resolved with Promise.all

Avoid to create new Promises as that usually leads to the promise constructor antipattern.

Also avoid using a variable (like results) that is used in several callbacks without being passed as argument. Instead try to construct and return that array as a promised value, so it can be used in the next then callback.

Here is the suggested (untested) code:

function handleDatabases() {
    db.jobs
    .orderBy('title')
    .filter(job => job.someBooleanCondition)
    .toArray(jobs =>
        jobs.map(job => {
            let jobDetails = new Dexie(job.correspondingDB);
            jobDetails.version(1).stores({
                details: 'key,value1,value2'
            });
            return jobDetails.details.get(someKey)
                   .then(detail => ({job: job, detail: detail}))
        }) // is returned
    )
    .then(result => Promise.all(result))
    .then(handleResult)
    .catch(error => console.log(error));
}


来源: stackexchange

问:
how to find the query executed when dynamic workbook exported from Dynamics CRM?
how to find the query executed when dynamic workbook exported from Dynamics CRM?

Basically we have Microsoft Dynamics CRM tool to track the requests received within our team.I have created a customized view with my requirement and had exported the data into a Dynamic Workbook so that each time the xml file is opened the data gets refreshed automatically.

I wanted to do the below:

Know which query is ran behind the scenes to update the data in the
workbook?

I wanted to export the xml into another worksheet of
another dynamic workbbook so that i have consolidated data

Could someone please help me in this ?

答:
I can't give you an answer for your second question, but for your first, create a retrieve multiple plugin that executes on all entities, and log the query expression that is found in the Plugin Context.

Shouldn't take too long to narrow it down...

ContentLicense: CC BY-SA 3.0


问:
MYSQL One connection for one class
I am learning about MySQL database and I cannot quite understand one concept. Lets say there are two methods in the same class as the one shown below. Now, do i have to use Connection connect = dbConnection.getDBConnection(); in each method or is there a different way to declare one connection and use it across multiple methods?:</p>

```<code>private void setUpdateButton(ActionEvent event) {
    try{
        Connection connect = dbConnection.getDBConnection();
        Statement stmt = connect.createStatement();

        if(txtID.getText().trim().isEmpty()||txtFirstName.getText().trim().isEmpty() || txtSecondName.getText().trim().isEmpty() ||
                txtGender.getText().trim().isEmpty() || txtAge.getText().trim().isEmpty() || txtHomeAddress.getText().trim().isEmpty() || txtPhoneNumber.getText().trim().isEmpty()) {
            showAlert("Invalid Input!", "All fields need to be populated before updating.");
        }else {
               String sqlQuery ="update student_information set Age ='"+Integer.parseInt(txtAge.getText())+"',Name ='"+txtFirstName.getText()+"',Surename='"+txtSecondName.getText()
            +"',Gender='"+txtGender.getText()+"',Address='"+txtHomeAddress.getText()+"',PhoneNumber='"+txtPhoneNumber.getText()+"'where ID="+Integer.parseInt(txtID.getText());
               stmt.executeLargeUpdate(sqlQuery);
               setTxtArea();
               showConfAlert("Update Completed!", "Record has been updated!");
</code>```

答:
Creating connections is a costly operation, so I think you should open the connection at the application startup, and close it on exit.

If your program is not multi thread you would be fine with a simple global object, otherwise other strategies should be used.

You can create a singleton for your app with a method returning the connection.

```<code>public class App {
    private static App self;

    private Connection connection;

    private App(){
    }

    public synchronized App getInstance(){
        if(self == null){
            self = new App();
        }
        return self;
    }

    public synchronized Connection getConnection()throws SQLException {
        if(connection==null || !isValid(connection)){
            // Create a new connection
        }
        return connection;
    }

    private boolean isValid(Connection conn) {
        // Check if the connection is valid otherwise return false
        return false;
    }

    public static synchronized void close(){
        try{
            self.connection.close();
        } catch (SQLException e){
            // Swallow exception
        } finally {
            self = null;
        }
    }

}
</code>```

You can get the connection anywhere like this:

```<code>Connection conn = App.getInstance().getConnection();
</code>```

You should make sure to close the connection on exit, maybe with a shutdown hook.

You could also, create a wrapper around your connection that forwards all connection methods to the original connection , with the exception of close that marks the connection available , this way you create something like 1 connection pool.

If the connection is available you return it otherwise you either wait or throw or do what is most appropriate for your application.

Title: MYSQL One connection for one class

Body:
I am learning about MySQL database and I cannot quite understand one concept. Lets say there are two methods in the same class as the one shown below. Now, do i have to use Connection connect = dbConnection.getDBConnection(); in each method or is there a different way to declare one connection and use it across multiple methods?:

private void setUpdateButton(ActionEvent event) {
    try{
        Connection connect = dbConnection.getDBConnection();
        Statement stmt = connect.createStatement();

        if(txtID.getText().trim().isEmpty()||txtFirstName.getText().trim().isEmpty() || txtSecondName.getText().trim().isEmpty() ||
                txtGender.getText().trim().isEmpty() || txtAge.getText().trim().isEmpty() || txtHomeAddress.getText().trim().isEmpty() || txtPhoneNumber.getText().trim().isEmpty()) {
            showAlert("Invalid Input!", "All fields need to be populated before updating.");
        }else {
               String sqlQuery ="update student_information set Age ='"+Integer.parseInt(txtAge.getText())+"',Name ='"+txtFirstName.getText()+"',Surename='"+txtSecondName.getText()
            +"',Gender='"+txtGender.getText()+"',Address='"+txtHomeAddress.getText()+"',PhoneNumber='"+txtPhoneNumber.getText()+"'where ID="+Integer.parseInt(txtID.getText());
               stmt.executeLargeUpdate(sqlQuery);
               setTxtArea();
               showConfAlert("Update Completed!", "Record has been updated!");

Body:
Creating connections is a costly operation, so I think you should open the connection at the application startup, and close it on exit.

If your program is not multi thread you would be fine with a simple global object, otherwise other strategies should be used.

You can create a singleton for your app with a method returning the connection.

public class App {
    private static App self;

    private Connection connection;

    private App(){
    }

    public synchronized App getInstance(){
        if(self == null){
            self = new App();
        }
        return self;
    }

    public synchronized Connection getConnection()throws SQLException {
        if(connection==null || !isValid(connection)){
            // Create a new connection
        }
        return connection;
    }

    private boolean isValid(Connection conn) {
        // Check if the connection is valid otherwise return false
        return false;
    }

    public static synchronized void close(){
        try{
            self.connection.close();
        } catch (SQLException e){
            // Swallow exception
        } finally {
            self = null;
        }
    }

}

You can get the connection anywhere like this:

Connection conn = App.getInstance().getConnection();

You should make sure to close the connection on exit, maybe with a shutdown hook.

You could also, create a wrapper around your connection that forwards all connection methods to the original connection , with the exception of close that marks the connection available , this way you create something like 1 connection pool.

If the connection is available you return it otherwise you either wait or throw or do what is most appropriate for your application.


问:
Sorting doesnt work c++
```<code>for (Dodavatel *a : zoznamDodavatelov) {
    for (Dodavatel *b : zoznamDodavatelov) {
        if (a->getNazov() < a->getNazov()) {
            Dodavatel *prem = a;
            a = b;
            b = prem;
        }
    }
}
</code>```

why doesn't this work, it can't sort my array called zoznamDodavatelov

答:
if (a->getNazov() getNazov()) {

this line will never be true.

Title: Sorting doesnt work c++

Body:
for (Dodavatel *a : zoznamDodavatelov) {
    for (Dodavatel *b : zoznamDodavatelov) {
        if (a->getNazov() getNazov()) {
            Dodavatel *prem = a;
            a = b;
            b = prem;
        }
    }
}

why doesn't this work, it can't sort my array called zoznamDodavatelov

Body:
if (a->getNazov() < a->getNazov()) {

this line will never be true.


问:
Unable to show PDF in p:media generated from streamed content in Primefaces
I'm trying to show inline PDF which is opened in new browser window. I have following scenario:

In some ActionListen which is called by ajax I generate PDF content, put data in session, and send Javascript to be executed (window.open to open new page to show PDF)

On opened page I just have p:media tag inside h:body with value pointing to StreamedContent:

Now, on that page my PDF is not generated. In log I can see these two lines:

```<code>org.primefaces.application.PrimeResourceHandler handleResourceRequest
SEVERE: Error in streaming dynamic resource. Expression cannot be null
</code>```

I started to debug and find out a few things.

First, I added breakpoint to @PostConstruct method of my RequestScoped bean. What is interesting is that breakpoint is reached twice, and to my big surprise after that PDF is shown perfectly?!

After some debugging through PrimeResourceHandler I figure out that in some cases ValueExpression is not calculated, in fact it throws NullPointerException, and again while debugging I saw that two requests are sent, and second request fails because dynamicContentId is removed in first request, and second call to handleResourceRequest doesn't have sense.

Through Firebug I can see two requests, first which is good with PDF data, and second which is also with content-type application/pdf but empty, with size 0.

xhtml page:

```<code><html>
  <h:head></h:head>
  <h:body>
    <p:media value="#{reportBean.streamedContent}" player="pdf" width="500" height="500"/>
  </h:body>
</html>
</code>```

backing bean:

```<code>@RequestScoped
public class StampaListeBackingBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private StreamedContent streamedContent;

    @PostConstruct
    public void init() {
        Map<String, Object> session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
        byte[] b = (byte[]) session.get("reportBytes");
        if (b != null) {
            streamedContent = new DefaultStreamedContent(new ByteArrayInputStream(b), "application/pdf");
        }
    }

    public StreamedContent getStreamedContent() {
        if (FacesContext.getCurrentInstance().getRenderResponse()) {
            return new DefaultStreamedContent();
        } else {
            return streamedContent;
        }
}

    public void setStreamedContent(StreamedContent streamedContent) {
        this.streamedContent = streamedContent;
    }
}
</code>```

I need to understand why two requests are sent on page with p:media tag, and to figure out how to make this work. Backing bean is request scoped, it creates StreamedContent in @PostConstruct method, and has getter and setter for that field. Primefaces version is 3.4.2, with Mojarra 2.1.14.

ADDED:

It is easy to reproduce my problem. If code in init method is replaced with following:

```<code>FileInputStream fis = new FileInputStream(new File("C:\\samplexxx.pdf"));
streamedContent = new DefaultStreamedContent(fis, "application/pdf");
</code>```

problem can be reproduced.

答:
I hope my little contribution can help  anyone who can't display pdf preview in Firefox. I was using Primefaces 6 + Spring and I had the same problem but maybe not due the same reason. Indeed, I tried the proposed solution by Balus C. It helped me to display the pdf in Chrome and IE11 but it still was not working in Firefox 52.

I noticed an error in the Firefox console: Load denied by X-Frame-Options: http://localhost:8080/myapp/ does not permit framing

In my case, it was because spring-security configuration and the solution was edit spring-context.xml in this way:

<sec:http ...>
...
<sec:headers>
         <sec:frame-options policy="SAMEORIGIN" />
</sec:headers>
...
</sec:http>```

Body:
I'm trying to show inline PDF which is opened in new browser window. I have following scenario:

In some ActionListen which is called by ajax I generate PDF content, put data in session, and send Javascript to be executed (window.open to open new page to show PDF)

On opened page I just have p:media tag inside h:body with value pointing to StreamedContent:

Now, on that page my PDF is not generated. In log I can see these two lines:

org.primefaces.application.PrimeResourceHandler handleResourceRequest
SEVERE: Error in streaming dynamic resource. Expression cannot be null

I started to debug and find out a few things.

First, I added breakpoint to @PostConstruct method of my RequestScoped bean. What is interesting is that breakpoint is reached twice, and to my big surprise after that PDF is shown perfectly?!

After some debugging through PrimeResourceHandler I figure out that in some cases ValueExpression is not calculated, in fact it throws NullPointerException, and again while debugging I saw that two requests are sent, and second request fails because dynamicContentId is removed in first request, and second call to handleResourceRequest doesn't have sense.

Through Firebug I can see two requests, first which is good with PDF data, and second which is also with content-type application/pdf but empty, with size 0.

xhtml page:

  <h:head></h:head>
  <h:body>

  </h:body>

backing bean:

@RequestScoped
public class StampaListeBackingBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private StreamedContent streamedContent;

    @PostConstruct
    public void init() {
        Map<String, Object> session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
        byte[] b = (byte[]) session.get("reportBytes");
        if (b != null) {
            streamedContent = new DefaultStreamedContent(new ByteArrayInputStream(b), "application/pdf");
        }
    }

    public StreamedContent getStreamedContent() {
        if (FacesContext.getCurrentInstance().getRenderResponse()) {
            return new DefaultStreamedContent();
        } else {
            return streamedContent;
        }
}

    public void setStreamedContent(StreamedContent streamedContent) {
        this.streamedContent = streamedContent;
    }
}

I need to understand why two requests are sent on page with p:media tag, and to figure out how to make this work. Backing bean is request scoped, it creates StreamedContent in @PostConstruct method, and has getter and setter for that field. Primefaces version is 3.4.2, with Mojarra 2.1.14.

ADDED:

It is easy to reproduce my problem. If code in init method is replaced with following:

FileInputStream fis = new FileInputStream(new File("C:\\samplexxx.pdf"));
streamedContent = new DefaultStreamedContent(fis, "application/pdf");

problem can be reproduced.


问:
Understanding TypeDescriptor/PropertyDescriptor/etc
See the code:

```<code>class DataItem
{
    public DataItem(int num, string s)
    {
        Number = num;
        Str = s;
    }
    public int Number { get; set; }
    public string Str { get; set; }
}

static void Main(string[] args)
{
    var data = new DataItem(2, "hi");

    var provider = TypeDescriptor.AddAttributes(typeof(DataItem),
                                               new SerializableAttribute());

    var another = provider.CreateInstance(null, typeof(DataItem),
                                 new Type[] { typeof(int), typeof(string) },
                                 new object[] { 100, "hello" }) as DataItem;

    var newProperty = TypeDescriptor.CreateProperty(another.GetType(), "Str",
                                      typeof(string),
                                      new DescriptionAttribute("new property"));
    //newProperty.SetValue(another, "new one");

    Console.WriteLine(newProperty.GetValue(another));
    Console.Read();
}
</code>```

And I have several questions for the code:

(1) I added a SerializableAttribute to the Type of DataItem, what is this "change" applied to? I can't get this attribute by typeof(DataItem).GetCustomAttributes(true).It seems that the change is not applied to the "essential DataItem", it is stored in the TypeDescriptionProvider temporarily?

(2) The instance another is created by the provider(where we added the attribute), I think now this variable is the same as the one created by the constructor of SerializableAttributed DataItem? even if we can't still get the attribute by another.GetType().GetCustomAttributes.

(3) Another reason I believe the change is temporarily stored in the provider is that I tried to create a property with its name Str and type string, which actually already exists in DataItem. The code will output hello. And if I uncomment the SetValue method, the output will be new one. Do I have any misunderstandings?

答: The attributes are added to the instance (data) not the type. Have you tried TypeDescriptor.AddAttributes(typeof(DataItem)) instead?</p>

ContentLicense: CC BY-SA 2.5

Body:
See the code:

class DataItem
{
    public DataItem(int num, string s)
    {
        Number = num;
        Str = s;
    }
    public int Number { get; set; }
    public string Str { get; set; }
}

static void Main(string[] args)
{
    var data = new DataItem(2, "hi");

    var provider = TypeDescriptor.AddAttributes(typeof(DataItem),
                                               new SerializableAttribute());

    var another = provider.CreateInstance(null, typeof(DataItem),
                                 new Type[] { typeof(int), typeof(string) },
                                 new object[] { 100, "hello" }) as DataItem;

    var newProperty = TypeDescriptor.CreateProperty(another.GetType(), "Str",
                                      typeof(string),
                                      new DescriptionAttribute("new property"));
    //newProperty.SetValue(another, "new one");

    Console.WriteLine(newProperty.GetValue(another));
    Console.Read();
}

And I have several questions for the code:

(1) I added a SerializableAttribute to the Type of DataItem, what is this "change" applied to? I can't get this attribute by typeof(DataItem).GetCustomAttributes(true).It seems that the change is not applied to the "essential DataItem", it is stored in the TypeDescriptionProvider temporarily?

(2) The instance another is created by the provider(where we added the attribute), I think now this variable is the same as the one created by the constructor of SerializableAttributed DataItem? even if we can't still get the attribute by another.GetType().GetCustomAttributes.

(3) Another reason I believe the change is temporarily stored in the provider is that I tried to create a property with its name Str and type string, which actually already exists in DataItem. The code will output hello. And if I uncomment the SetValue method, the output will be new one. Do I have any misunderstandings?


答:
Firstly, it appears to your containers store pointers of Dodavatel * types. However, in your cycles pointers a and b are declared as independent local variables. Swapping around pointers a and b does not affect the contents of your array.

So, the question is: what are you supposed to reorder in order to "sort" the array? The pointers? Or the objects these pointers point to?

In the former case in order to reorder the pointers you need to declare the cycle variables as references

```<code>for (Dodavatel *&a : zoznamDodavatelov) {
  for (Dodavatel *&b : zoznamDodavatelov) {
</code>```

In the latter case you can can keep the current declaration, but inside your if you have to swap *a and *b, not a, and b.

Secondly, your if makes no sense since it compares *a with itself.

Title: Sorting doesnt work c++

Body:
Firstly, it appears to your containers store pointers of Dodavatel * types. However, in your cycles pointers a and b are declared as independent local variables. Swapping around pointers a and b does not affect the contents of your array.

So, the question is: what are you supposed to reorder in order to "sort" the array? The pointers? Or the objects these pointers point to?

In the former case in order to reorder the pointers you need to declare the cycle variables as references

for (Dodavatel *&a : zoznamDodavatelov) {
  for (Dodavatel *&b : zoznamDodavatelov) {

In the latter case you can can keep the current declaration, but inside your if you have to swap *a and *b, not a, and b.

Secondly, your if makes no sense since it compares *a with itself.


问:
Merge PDF files
Is it possible, using Python, to merge separate PDF files?

Assuming so, I need to extend this a little further.  I am hoping to loop through folders in a directory and repeat this procedure.

And I may be pushing my luck, but is it possible to exclude a page that is contained in each of the PDFs (my report generation always creates an extra blank page).

答:
The pdfrw library can do this quite easily, assuming you don't need to preserve bookmarks and annotations, and your PDFs aren't encrypted.  cat.py is an example concatenation script, and subset.py is an example page subsetting script.

The relevant part of the concatenation script -- assumes inputs is a list of input filenames, and outfn is an output file name:

```<code>from pdfrw import PdfReader, PdfWriter

writer = PdfWriter()
for inpfn in inputs:
    writer.addpages(PdfReader(inpfn).pages)
writer.write(outfn)
</code>```

As you can see from this, it would be pretty easy to leave out the last page, e.g. something like:

```<code>    writer.addpages(PdfReader(inpfn).pages[:-1])
</code>```

Disclaimer:  I am the primary pdfrw author.

ContentLicense: CC BY-SA 4.0

Title: Merge PDF files

Body:
The pdfrw library can do this quite easily, assuming you don't need to preserve bookmarks and annotations, and your PDFs aren't encrypted.  cat.py is an example concatenation script, and subset.py is an example page subsetting script.

The relevant part of the concatenation script -- assumes inputs is a list of input filenames, and outfn is an output file name:

from pdfrw import PdfReader, PdfWriter

writer = PdfWriter()
for inpfn in inputs:
    writer.addpages(PdfReader(inpfn).pages)
writer.write(outfn)

As you can see from this, it would be pretty easy to leave out the last page, e.g. something like:

    writer.addpages(PdfReader(inpfn).pages[:-1])

Disclaimer:  I am the primary pdfrw author.


问:
Why is pre-processing causing me to lose dictionary keys?
Having a very peculiar problem. The extract function takes an XML file and produces a dict using restaurant reviews as keys. Here I am doing some basic preprocessing to the text as I'm using it for sentiment analysis: the text is tokenized, punctuation is removed and it is 'un-tokenized' before being reinserted into the dict.

```<code>import string
from nltk.tokenize import word_tokenize, RegexpTokenizer
tokenizer = RegexpTokenizer(r'\w+')

def preprocess(file):
    d = extract(file)
    for text in list(d.keys()):
        tokenized_text = tokenizer.tokenize(text)
        text2 = ''.join([" "+i if not i.startswith("'") and i not in string.punctuation else i for i in tokenized_text]).strip()
        d[text2] = d.pop(text)
    return d
</code>```

Of the 675 reviews, 2 are missing after this function has run. These are 'great service.' and 'Delicious'. I would expect these to be returned as they are, except the full stop should be taken away from the first.

For reference, the extract function:

```<code>from collections import OrderedDict, defaultdict
import xml.etree.ElementTree as ET

def extract(file):

    tree = ET.parse(file)
    root = tree.getroot()

    if file == 'EN_REST_SB1_TEST.xml':
        d = OrderedDict()
        for sentence in root.findall('.//sentence'):
            opinion = sentence.findall('.//Opinion')
            if opinion == []:
                text = sentence.find('text').text
                d[text] = 0

        return d
</code>```

If anybody is familiar with the SemEval ABSA tasks, you'll note I've done this in a somewhat roundabout way, not making use of the id tags in the XML but I'd prefer to stick to how I've done it.

答:
You're using the reviews as keys, which means you'll lose any duplicates. Evidently these very short reviews occurred twice.

I can't think of any reason to use the reviews as keys, especially if you care about holding on to duplicates. So why not just collect them into a list?

```<code>d = []
...
d.append(text)
</code>```

Body:
Having a very peculiar problem. The extract function takes an XML file and produces a dict using restaurant reviews as keys. Here I am doing some basic preprocessing to the text as I'm using it for sentiment analysis: the text is tokenized, punctuation is removed and it is 'un-tokenized' before being reinserted into the dict.

import string
from nltk.tokenize import word_tokenize, RegexpTokenizer
tokenizer = RegexpTokenizer(r'\w+')

def preprocess(file):
    d = extract(file)
    for text in list(d.keys()):
        tokenized_text = tokenizer.tokenize(text)
        text2 = ''.join([" "+i if not i.startswith("'") and i not in string.punctuation else i for i in tokenized_text]).strip()
        d[text2] = d.pop(text)
    return d

Of the 675 reviews, 2 are missing after this function has run. These are 'great service.' and 'Delicious'. I would expect these to be returned as they are, except the full stop should be taken away from the first.

For reference, the extract function:

from collections import OrderedDict, defaultdict
import xml.etree.ElementTree as ET

def extract(file):

    tree = ET.parse(file)
    root = tree.getroot()

    if file == 'EN_REST_SB1_TEST.xml':
        d = OrderedDict()
        for sentence in root.findall('.//sentence'):
            opinion = sentence.findall('.//Opinion')
            if opinion == []:
                text = sentence.find('text').text
                d[text] = 0

        return d

If anybody is familiar with the SemEval ABSA tasks, you'll note I've done this in a somewhat roundabout way, not making use of the id tags in the XML but I'd prefer to stick to how I've done it.

Body:
You're using the reviews as keys, which means you'll lose any duplicates. Evidently these very short reviews occurred twice.

I can't think of any reason to use the reviews as keys, especially if you care about holding on to duplicates. So why not just collect them into a list?

d = []
...
d.append(text)


问:
exe file not running (cx_Freeze + PySide)
After freezing my Python programs using cx_freeze, I tried to run exe file created but its not running.

PhoneBook.py

```<code>import  sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtUiTools import *

class PhoneBook:
  i=0;
  def __init__(self):
        loader = QUiLoader();
        file = QFile("PhoneBook.ui");
        file.open(QFile.ReadOnly);
        self.ui = loader.load(file);
        file.close();
        self.ui.setWindowIcon(QIcon('web.png'));
        self.ui.pushButton.clicked.connect(self.add);
        self.ui.pushButton_2.clicked.connect(self.load);

  def __del__ ( self ):
        self.ui = None;

  def add(self):
        loader1 = QUiLoader();
        file1 = QFile("Add.ui");
        file1.open(QFile.ReadOnly);
        self.ui2 = loader1.load(file1);
        file1.close();
        self.ui2.show();
        self.ui2.pushButton.clicked.connect(self.get);

  def show(self):
        self.ui.show();

  def clear1(self):
        self.ui.lineEdit.clear();

  def get(self):

        name1 = self.ui2.lineEdit.text();
        name2 = self.ui2.lineEdit_2.text();

        f = open('data','a' );
        f.write(name1);
        f.write('#');
        f.write(name2);
        f.write('\n');
        f.close();
        self.load();
        self.ui2.close();

  def load(self):
        f = open('data', 'r');
        for i in range(0, 10):
            string = f.readline();
            l=len(string);
            print(string);
            print(l);
            for  c in range(0, l-1):
                if string[c]=="#":
                   break;
                print(c);
                name1=string[0:c];
                name2=string[c+1:l-1];
                self.ui.tableWidget.setItem(i, 0, QTableWidgetItem(name1));
                self.ui.tableWidget.setItem(i, 1, QTableWidgetItem(name2));
                i =i+1;

  def sort(self):
        f=open('data', 'r');
        f.readlines().sort();

  if __name__ == '__main__':

        app = QApplication(sys.argv)
        app.setApplicationName('PhoneBook Application')

        w = PhoneBook();
        w.show();

        QObject.connect(app, SIGNAL('lastWindowClosed()'), app,SLOT('quit()'))

        sys.exit(app.exec_())
</code>```

setup.py

```<code>import sys
from cx_Freeze import setup,Executable

includefiles = ['Add.ui', 'PhoneBook.ui', 'data', 'web.png']
includes = ["re"]
base = None
if sys.platform == "win32":
   base = "Win32GUI"
setup(name="PhoneBook", version="3.0",description="Test",options = {'build_exe':  {'include_files':includefiles, 'includes' : includes}
</code>```

Is it because I am using QUILoader ? However on executing the Python code directly its showing correct results. Please help me.

答:
Another cause of error was that cx-freeze was using some dlls from PyQt.

And the dlls are not same in pyside and pyqt, so if you have pyqt insalled i would suggest adding PyQt4 to the excludes

```<code>excludes=['PyQt4', 'tcl', 'tk', 'ttk', 'tkinter', 'Tkconstants', 'Tkinter', "collections.sys", "collections._weakref"]
</code>```

Body:
After freezing my Python programs using cx_freeze, I tried to run exe file created but its not running.

PhoneBook.py

import  sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtUiTools import *

class PhoneBook:
  i=0;
  def __init__(self):
        loader = QUiLoader();
        file = QFile("PhoneBook.ui");
        file.open(QFile.ReadOnly);
        self.ui = loader.load(file);
        file.close();
        self.ui.setWindowIcon(QIcon('web.png'));
        self.ui.pushButton.clicked.connect(self.add);
        self.ui.pushButton_2.clicked.connect(self.load);

  def __del__ ( self ):
        self.ui = None;

  def add(self):
        loader1 = QUiLoader();
        file1 = QFile("Add.ui");
        file1.open(QFile.ReadOnly);
        self.ui2 = loader1.load(file1);
        file1.close();
        self.ui2.show();
        self.ui2.pushButton.clicked.connect(self.get);

  def show(self):
        self.ui.show();

  def clear1(self):
        self.ui.lineEdit.clear();

  def get(self):

        name1 = self.ui2.lineEdit.text();
        name2 = self.ui2.lineEdit_2.text();

        f = open('data','a' );
        f.write(name1);
        f.write('#');
        f.write(name2);
        f.write('\n');
        f.close();
        self.load();
        self.ui2.close();

  def load(self):
        f = open('data', 'r');
        for i in range(0, 10):
            string = f.readline();
            l=len(string);
            print(string);
            print(l);
            for  c in range(0, l-1):
                if string[c]=="#":
                   break;
                print(c);
                name1=string[0:c];
                name2=string[c+1:l-1];
                self.ui.tableWidget.setItem(i, 0, QTableWidgetItem(name1));
                self.ui.tableWidget.setItem(i, 1, QTableWidgetItem(name2));
                i =i+1;

  def sort(self):
        f=open('data', 'r');
        f.readlines().sort();

  if __name__ == '__main__':

        app = QApplication(sys.argv)
        app.setApplicationName('PhoneBook Application')

        w = PhoneBook();
        w.show();

        QObject.connect(app, SIGNAL('lastWindowClosed()'), app,SLOT('quit()'))

        sys.exit(app.exec_())

setup.py

import sys
from cx_Freeze import setup,Executable

includefiles = ['Add.ui', 'PhoneBook.ui', 'data', 'web.png']
includes = ["re"]
base = None
if sys.platform == "win32":
   base = "Win32GUI"
setup(name="PhoneBook", version="3.0",description="Test",options = {'build_exe':  {'include_files':includefiles, 'includes' : includes}

Is it because I am using QUILoader ? However on executing the Python code directly its showing correct results. Please help me.

Body:
Another cause of error was that cx-freeze was using some dlls from PyQt.

And the dlls are not same in pyside and pyqt, so if you have pyqt insalled i would suggest adding PyQt4 to the excludes

excludes=['PyQt4', 'tcl', 'tk', 'ttk', 'tkinter', 'Tkconstants', 'Tkinter', "collections.sys", "collections._weakref"]


问:
What does 'seed' do in in 'ldatuning' to determine LDA topic frequency (in R)?
I have been trying out different ways of determining topic frequency in LDA (in R) and have stumbled across the very useful-looking package ldatuning but cannot really figure out the control parameter and particularly the example value for seed.

Here is the example code from the website:

```<code>library("topicmodels")
data("AssociatedPress", package="topicmodels")
dtm <- AssociatedPress[1:10, ]

result <- FindTopicsNumber(
  dtm,
  topics = seq(from = 2, to = 15, by = 1),
  metrics = c("Griffiths2004", "CaoJuan2009", "Arun2010", "Deveaud2014"),
  method = "Gibbs",
  control = list(seed = 77),
  mc.cores = 2L,
  verbose = TRUE
)
</code>```

I played around with the parameters a little bit and noticed that changes in the value for seed change the output graphs quite significantly. Can someone please explain what the 77 in this case stands for and how the value for seed should be selected?

Also, I couldn't find any other options for what to enter for control and what effect that has on the result. If anyone can provide some guidance here that would be great.

答:
seed:
Object of class "integer"; used to set the seed in the external code for VEM estimation and to call set.seed for Gibbs sampling. For Gibbs sampling it can also be set to NA (default) to avoid changing the seed of the random number generator in the model fitting call.

Body:
I have been trying out different ways of determining topic frequency in LDA (in R) and have stumbled across the very useful-looking package ldatuning but cannot really figure out the control parameter and particularly the example value for seed.

Here is the example code from the website:

library("topicmodels")
data("AssociatedPress", package="topicmodels")
dtm <- AssociatedPress[1:10, ]

result <- FindTopicsNumber(
  dtm,
  topics = seq(from = 2, to = 15, by = 1),
  metrics = c("Griffiths2004", "CaoJuan2009", "Arun2010", "Deveaud2014"),
  method = "Gibbs",
  control = list(seed = 77),
  mc.cores = 2L,
  verbose = TRUE
)

I played around with the parameters a little bit and noticed that changes in the value for seed change the output graphs quite significantly. Can someone please explain what the 77 in this case stands for and how the value for seed should be selected?

Also, I couldn't find any other options for what to enter for control and what effect that has on the result. If anyone can provide some guidance here that would be great.


问:
create constructor for a class extending JsonRequest<JSONObject>
I have created a class in android studio which extends JsonRequest
but android studio gives me an error and wants me to create a constructor because there is no default constructor in the library (volley library) for that.
Actually I'm using volley library to parse a json file in a listview in android.
Cause the json is all Persian text I have created this class to change it to utf-8 encoding.
Please show me how the needed constructor should be like. I have tried some but wasn't correct.</p>

```<code>public class Utf8JsonRequest extends JsonRequest<JSONObject> {
    ...
    @Override
    protected Response<JSONObject> parseNetworkResponse (NetworkResponse   response) {
        try {
            String utf8String = new String(response.data, "UTF-8");
            return Response.success(new JSONObject(utf8String),   HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            // log error
            return Response.error(new ParseError(e));
        } catch (JSONException e) {
            // log error
            return Response.error(new ParseError(e));
        }
    }
}
</code>```

答:
Here's an example of a constructor:

// the constructor should have at least these parameters
// to be passed onto super()
public Utf8JsonRequest(int method,
                       String url,
                       String requestBody,
                       Response.Listener<JSONObject> listener,
                       Response.ErrorListener errorListener) {
    super(method, url, requestBody, listener, errorListener);

    // you can initialize other stuff if you wish
}
```

Body:
I have created a class in android studio which extends JsonRequest
but android studio gives me an error and wants me to create a constructor because there is no default constructor in the library (volley library) for that.
Actually I'm using volley library to parse a json file in a listview in android.
Cause the json is all Persian text I have created this class to change it to utf-8 encoding.
Please show me how the needed constructor should be like. I have tried some but wasn't correct.

public class Utf8JsonRequest extends JsonRequest<JSONObject> {
    ...
    @Override
    protected Response<JSONObject> parseNetworkResponse (NetworkResponse   response) {
        try {
            String utf8String = new String(response.data, "UTF-8");
            return Response.success(new JSONObject(utf8String),   HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            // log error
            return Response.error(new ParseError(e));
        } catch (JSONException e) {
            // log error
            return Response.error(new ParseError(e));
        }
    }
}


问:
Accessing array elements using the associative index and numbered index
Is it possible to define an array where I can access the elements via their string and numeric index?</p>

答:
PHP allows a mixture of string and numeric-indexed elements.

```<code>$array = array(0=>'hello','abc'=>'world');

echo $array[0]; // returns 'hello'
echo $array['0']; // returns 'hello'
echo $array['abc']; // returns 'world';
echo $array[1]; // triggers a PHP notice: undefined offset
</code>```

A closer look at the last item $array[1] reveals that it is not equivalent to the 2nd element of the array.

Body:
PHP allows a mixture of string and numeric-indexed elements.

$array = array(0=>'hello','abc'=>'world');

echo $array[0]; // returns 'hello'
echo $array['0']; // returns 'hello'
echo $array['abc']; // returns 'world';
echo $array[1]; // triggers a PHP notice: undefined offset

A closer look at the last item $array[1] reveals that it is not equivalent to the 2nd element of the array.


问:
ASP.NET (web forms) drop down menu show and hide on javascript function
I have a problem with use function on client side like drop down menu. My menu just shown and hide after function reload.
I think that my function is reload 2 Times.
...............................................................................

My code:

Aspx

```<code><asp:Button ID="advancedSearchOptions" runat="server" Text="Sz" CausesValidation="False"
                    Visible="true"   class="btn btn-primaryx dropdown-toggle" data-toggle="dropdown" aria-expanded="false" OnClientClick="myFunction2()" />
                            <div id="divShow" class="dropdown-menu dropdown-menu-right" role="menu">
                                <form class="form-horizontal" role="form">
                                  <div class="form-group">
                                    <label for="filter">Filter by</label>
                                    <select class="form-control">
                                        <option value="0" selected>All Snippets</option>
                                        <option value="1">Featured</option>
                                        <option value="2">Most popular</option>
                                        <option value="3">Top rated</option>
                                        <option value="4">Most commented</option>
                                    </select>
                                  </div>
                                  </form>
                            </div>
</code>```

Javascript:

```<code><script>
    /* When the user clicks on the button,
    toggle between hiding and showing the dropdown content */
    function myFunction2() {
        Load();
        document.getElementById("divShow").classList.toggle("show");

    }

    // Close the dropdown if the user clicks outside of it
    window.onclick = function (event) {
        matches = event.target.matches ? event.target.matches('.btn-primaryx') : event.target.msMatchesSelector('.btn-primaryx');
        if (!matches) {

            var dropdowns = document.getElementsByClassName("dropdown-menu");
            var i;
            for (i = 0; i < dropdowns.length; i++) {
                var openDropdown = dropdowns[i];
                if (openDropdown.classList.contains('show')) {
                    openDropdown.classList.remove('show');
                }
            }
        }
    }
</code>```

CSS(i use also bootstrap):

```<code>.dropdown-toggle
{
border-top-right-radius:0;
border-bottom-right-radius:0
}
.btn-primaryx
{
color:#fff;
background-color:#eaf5ff;
border-color:#2e6da4;
height:36px;
}
.dropdown-menu{
position:absolute;
top:100%;left:0;
z-index:1000;
display:none;
float:left;
min-width:160px;
padding:5px 0;
margin:2px 0 0;
font-size:14px;
text-align:left;
list-style:none;
background-color:#fff;
-webkit-background-clip:padding-box;
background-clip:padding-box;
border:1px solid #ccc;
border:1px solid rgba(0,0,0,.15);
border-radius:4px;
-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);
box-shadow:0 6px 12px rgba(0,0,0,.175)
}
.show {
display:block;
}
</code>```

Help please..

答:
On the <asp:Button>, change this:

```<code>OnClientClick="myFunction2()"
</code>```

to

```<code>OnClientClick="myFunction2(); return false;"
</code>```

I commented out the javascript Load() method as it wasn't defined and made the script crash.

What's happening is that when you click an <asp:Button> .NET first calls any OnClientClick methods and then proceeds to do normal button click handling (which includes a postback to the server). This happens with buttons even if you don't given them an OnClick method. You can stop the postback from happening by making sure the client script returns false.

Body:
I have a problem with use function on client side like drop down menu. My menu just shown and hide after function reload.
I think that my function is reload 2 Times.
...............................................................................

My code:

Aspx

<asp:Button ID="advancedSearchOptions" runat="server" Text="Sz" CausesValidation="False"
                    Visible="true"   class="btn btn-primaryx dropdown-toggle" data-toggle="dropdown" aria-expanded="false" OnClientClick="myFunction2()" />

                                <form class="form-horizontal" role="form">

                                    Filter by
                                    <select class="form-control">
                                        <option value="0" selected>All Snippets</option>
                                        <option value="1">Featured</option>
                                        <option value="2">Most popular</option>
                                        <option value="3">Top rated</option>
                                        <option value="4">Most commented</option>
                                    </select>

                                  </form>

Javascript:

Body:
On the <asp:Button>, change this:

OnClientClick="myFunction2()"

to

OnClientClick="myFunction2(); return false;"

I commented out the javascript Load() method as it wasn't defined and made the script crash.

What's happening is that when you click an <asp:Button> .NET first calls any OnClientClick methods and then proceeds to do normal button click handling (which includes a postback to the server). This happens with buttons even if you don't given them an OnClick method. You can stop the postback from happening by making sure the client script returns false.


问:
Compiling perl >5.10 on AIX version 5.3
I've been compiling OpenSSL (and thus Perl >5.10, as it is a dependency) on multiple platforms. I've managed to get 1.1.0b compiled on every single platform except AIX, which I can't even compile Perl. I've tried several versions and looked at the documentation Perl provides online. From what I can tell, it suggests version 5.12.2.

When I attempt to compile version 5.12.2,

I take the following from the documentation, and fill in a few local system variables, such as using XLC rv7.

```<code> export OBJECT_MODE=64

 ./Configure \
  -d \
  -Dcc=/usr/vac/bin/xlc_r7 \
  -Duseshrplib \
  -Duse64bitall \
  -Dprefix=`pwd`/../PERL
</code>```

Then I attempt to make as prompted, and get the following error:

```<code>        /usr/vac/bin/xlc_r7 -q64 -o miniperl -brtl -bdynamic -L/usr/local/lib -b64    gv.o toke.o perly.o pad.o regcomp.o dump.o util.o mg.o reentr.o mro.o hv.o av.o run.o pp_hot.o sv.o pp.o scope.o pp_ctl.o pp_sys.o doop.o doio.o regexec.o utf8.o taint.o deb.o universal.o globals.o perlio.o perlapi.o numeric.o mathoms.o locale.o pp_pack.o pp_sort.o    miniperlmain.o opmini.o perlmini.o -lbind -lnsl -ldl -lld -lm -lcrypt -lc
        LIBPATH=.../perl-5.12.2  ./miniperl -w -Ilib -MExporter -e '<?>' || make minitest
        LIBPATH=.../perl-5.12.2  ./miniperl -Ilib autodoc.pl
        /usr/bin/ln -s perl5122delta.pod pod/perldelta.pod
        LIBPATH=.../perl-5.12.2  ./miniperl -Ilib -Icpan/Cwd -Icpan/Cwd/lib pod/perlmodlib.PL -q
readdir(./../../../../..): Bad file number at lib/FindBin.pm line 116
stat(/pod/): No such file or directory at lib/FindBin.pm line 197
stat(/pod/): No such file or directory at lib/FindBin.pm line 200
Use of chdir('') or chdir(undef) as chdir() is deprecated at pod/perlmodlib.PL line 9.
No such file or directory at pod/perlmodlib.PL line 19.
make: The error code from the last command is 2.
</code>```

Taking a look at pod/perlmodlib.PL, we see the following:

```<code># MANIFEST itself is Unix style filenames, so we have to assume that Unix style
# filenames will work.

open (MANIFEST, "../MANIFEST") or die $!;
</code>```

In my desperation I tried to hack it up and avoid writing to the manifest, but then I get this issue:

```<code>Creating Makefile.PL in cpan/Archive-Extract for Archive::Extract

Running Makefile.PL in cpan/Archive-Extract
../../miniperl Makefile.PL INSTALLDIRS=perl INSTALLMAN1DIR=none INSTALLMAN3DIR=none PERL_CORE=1 LIBPERL_A=libperl.a
readdir(./../../../../../../..): No such file or directory at ../../lib/File/Find.pm line 610
Use of chdir('') or chdir(undef) as chdir() is deprecated at ../../lib/File/Find.pm line 773.
readdir(./../../..): No such file or directory at ../../cpan/Cwd/lib/File/Spec/Unix.pm line 483
Could not open 'lib/Archive/Extract.pm': No such file or directory at ../../cpan/ExtUtils-MakeMaker/lib/ExtUtils/MM_Unix.pm line 2588.
512 from cpan/Archive-Extract's Makefile.PL at make_ext.pl line 390.
Warning: No Makefile!
make: Cannot find a rule to create target config from dependencies.
Stop.
 make config PERL_CORE=1 LIBPERL_A=libperl.a failed, continuing anyway...
Making all in cpan/Archive-Extract
 make all PERL_CORE=1 LIBPERL_A=libperl.a
make: Cannot find a rule to create target all from dependencies.
Stop.
Unsuccessful make(cpan/Archive-Extract): code=512 at make_ext.pl line 449.
make: The error code from the last command is 2.
</code>```

The frequency of errors makes me feel like perhaps I don't have something configured right...

My next thought was to try the most updated version, which at the time of writing is 5.24. Using the same configuration and attempting to make I get the following issue:

```<code>Can't locate strict.pm in @INC (you may need to install the strict module) (@INC contains: /cpan/AutoLoader/lib /dist/Carp/lib /dist/PathTools /dist/PathTools/lib /cpan/ExtUtils-Install/lib /cpan/ExtUtils-MakeMaker/lib /cpan/ExtUtils-Manifest/lib /cpan/File-Path/lib /ext/re /dist/Term-ReadLine/lib /dist/Exporter/lib /ext/File-Find/lib /cpan/Text-Tabs/lib /dist/constant/lib /cpan/version/lib /lib .) at autodoc.pl line 25.
BEGIN failed--compilation aborted at autodoc.pl line 25.
make: The error code from the last command is 2.
</code>```

Which I know from other compilations means I need to edit the PERL5LIB variable.

If I keep adding all the modules to the path:

```<code>export PERL5LIB=`pwd`/dist/Exporter/lib:$PERL5LIB
export PERL5LIB=`pwd`/cpan/Text-Tabs/lib:$PERL5LIB
export PERL5LIB=`pwd`/ext/re:$PERL5LIB
export PERL5LIB=`pwd`/dist/constant/lib:$PERL5LIB
export PERL5LIB=`pwd`/cpan/ExtUtils-MakeMaker/lib:$PERL5LIB
export PERL5LIB=`pwd`/dist/Carp/lib:$PERL5LIB
export PERL5LIB=`pwd`/cpan/File-Path/lib:$PERL5LIB
export PERL5LIB=`pwd`/dist/PathTools:$PERL5LIB
export PERL5LIB=`pwd`/dist/PathTools/lib:$PERL5LIB
export PERL5LIB=`pwd`/ext/File-Find/lib:$PERL5LIB
</code>```

Even so, I'll still get an error for a module that isn't even present in the 5.24.0 source!

```<code>Can't locate ExtUtils/MakeMaker/version/vpp.pm in @INC (you may need to install the ExtUtils::MakeMaker::version::vpp module) (@INC contains: <removed from post>) at (eval 2) line 2.
BEGIN failed--compilation aborted at (eval 2) line 2.
Compilation failed in require at .../perl-5.24.0/cpan/ExtUtils-MakeMaker/lib/ExtUtils/MakeMaker.pm line 10.
BEGIN failed--compilation aborted at .../perl-5.24.0/cpan/ExtUtils-MakeMaker/lib/ExtUtils/MakeMaker.pm line 10.
Compilation failed in require at Makefile.PL line 7.
BEGIN failed--compilation aborted at Makefile.PL line 7.
Unsuccessful Makefile.PL(cpan/Archive-Tar): code=512 at make_ext.pl line 517.
make: The error code from the last command is 2.
</code>```

I have MakeMaker, but the 5.24 version does not contain vpp.pm! Again, in desperation I attempted to put it in there from a different source, and I get this error:

```<code>        LIBPATH=.../perl-5.24.0 ./miniperl -Ilib make_ext.pl cpan/Archive-Tar/pm_to_blib  MAKE="make" LIBPERL_A=libperl.a
readdir(./../../../../../../..): No such file or directory at .../perl-5.24.0/ext/File-Find/lib/File/Find.pm line 142.
Can't cd to : No such file or directory
Unsuccessful Makefile.PL(cpan/Archive-Tar): code=512 at make_ext.pl line 517.
make: The error code from the last command is 2.
</code>```

All of this makes me feel like perhaps I'm not configuring something right... Can anyone with some experience help me out with some cut and dry installation instructions for Perl on AIX? I'd be super grateful. Thanks!

Below is some information about my system:

```<code>> prtconf
System Model: IBM,8231-E1D
Machine Serial Number: Not Available
Processor Type: Not Available
Processor Implementation Mode: POWER 7
Processor Version: PV_7_Compat
Number Of Processors: 0
Processor Clock Speed: Not Available
CPU Type: 64-bit
Kernel Type: 64-bit
Memory Size: 10240 MB
Good Memory Size: Not Available
Platform Firmware level: Not Available
Firmware Version: IBM,AL770_092
Console Login: disable
Auto Restart: true
Full Core: false
</code>```

答:
I pull down and compile openssh and openssl frequently.  I use gcc and no real magic that I can recall.

Here is my script to build it.  I don't know which perl is native to AIX but it seems to work for me.

https://github.com/pedz/aix-build-scripts/blob/master/build-scripts/build-openssl

Title: Compiling perl >5.10 on AIX version 5.3

Body:
I've been compiling OpenSSL (and thus Perl >5.10, as it is a dependency) on multiple platforms. I've managed to get 1.1.0b compiled on every single platform except AIX, which I can't even compile Perl. I've tried several versions and looked at the documentation Perl provides online. From what I can tell, it suggests version 5.12.2.

When I attempt to compile version 5.12.2,

I take the following from the documentation, and fill in a few local system variables, such as using XLC rv7.

 export OBJECT_MODE=64

 ./Configure \
  -d \
  -Dcc=/usr/vac/bin/xlc_r7 \
  -Duseshrplib \
  -Duse64bitall \
  -Dprefix=`pwd`/../PERL

Then I attempt to make as prompted, and get the following error:

        /usr/vac/bin/xlc_r7 -q64 -o miniperl -brtl -bdynamic -L/usr/local/lib -b64    gv.o toke.o perly.o pad.o regcomp.o dump.o util.o mg.o reentr.o mro.o hv.o av.o run.o pp_hot.o sv.o pp.o scope.o pp_ctl.o pp_sys.o doop.o doio.o regexec.o utf8.o taint.o deb.o universal.o globals.o perlio.o perlapi.o numeric.o mathoms.o locale.o pp_pack.o pp_sort.o    miniperlmain.o opmini.o perlmini.o -lbind -lnsl -ldl -lld -lm -lcrypt -lc
        LIBPATH=.../perl-5.12.2  ./miniperl -w -Ilib -MExporter -e '<?>' || make minitest
        LIBPATH=.../perl-5.12.2  ./miniperl -Ilib autodoc.pl
        /usr/bin/ln -s perl5122delta.pod pod/perldelta.pod
        LIBPATH=.../perl-5.12.2  ./miniperl -Ilib -Icpan/Cwd -Icpan/Cwd/lib pod/perlmodlib.PL -q
readdir(./../../../../..): Bad file number at lib/FindBin.pm line 116
stat(/pod/): No such file or directory at lib/FindBin.pm line 197
stat(/pod/): No such file or directory at lib/FindBin.pm line 200
Use of chdir('') or chdir(undef) as chdir() is deprecated at pod/perlmodlib.PL line 9.
No such file or directory at pod/perlmodlib.PL line 19.
make: The error code from the last command is 2.

Taking a look at pod/perlmodlib.PL, we see the following:

# MANIFEST itself is Unix style filenames, so we have to assume that Unix style
# filenames will work.

open (MANIFEST, "../MANIFEST") or die $!;

In my desperation I tried to hack it up and avoid writing to the manifest, but then I get this issue:

Creating Makefile.PL in cpan/Archive-Extract for Archive::Extract

Running Makefile.PL in cpan/Archive-Extract
../../miniperl Makefile.PL INSTALLDIRS=perl INSTALLMAN1DIR=none INSTALLMAN3DIR=none PERL_CORE=1 LIBPERL_A=libperl.a
readdir(./../../../../../../..): No such file or directory at ../../lib/File/Find.pm line 610
Use of chdir('') or chdir(undef) as chdir() is deprecated at ../../lib/File/Find.pm line 773.
readdir(./../../..): No such file or directory at ../../cpan/Cwd/lib/File/Spec/Unix.pm line 483
Could not open 'lib/Archive/Extract.pm': No such file or directory at ../../cpan/ExtUtils-MakeMaker/lib/ExtUtils/MM_Unix.pm line 2588.
512 from cpan/Archive-Extract's Makefile.PL at make_ext.pl line 390.
Warning: No Makefile!
make: Cannot find a rule to create target config from dependencies.
Stop.
 make config PERL_CORE=1 LIBPERL_A=libperl.a failed, continuing anyway...
Making all in cpan/Archive-Extract
 make all PERL_CORE=1 LIBPERL_A=libperl.a
make: Cannot find a rule to create target all from dependencies.
Stop.
Unsuccessful make(cpan/Archive-Extract): code=512 at make_ext.pl line 449.
make: The error code from the last command is 2.

The frequency of errors makes me feel like perhaps I don't have something configured right...

My next thought was to try the most updated version, which at the time of writing is 5.24. Using the same configuration and attempting to make I get the following issue:

Can't locate strict.pm in @INC (you may need to install the strict module) (@INC contains: /cpan/AutoLoader/lib /dist/Carp/lib /dist/PathTools /dist/PathTools/lib /cpan/ExtUtils-Install/lib /cpan/ExtUtils-MakeMaker/lib /cpan/ExtUtils-Manifest/lib /cpan/File-Path/lib /ext/re /dist/Term-ReadLine/lib /dist/Exporter/lib /ext/File-Find/lib /cpan/Text-Tabs/lib /dist/constant/lib /cpan/version/lib /lib .) at autodoc.pl line 25.
BEGIN failed--compilation aborted at autodoc.pl line 25.
make: The error code from the last command is 2.

Which I know from other compilations means I need to edit the PERL5LIB variable.

If I keep adding all the modules to the path:

export PERL5LIB=`pwd`/dist/Exporter/lib:$PERL5LIB
export PERL5LIB=`pwd`/cpan/Text-Tabs/lib:$PERL5LIB
export PERL5LIB=`pwd`/ext/re:$PERL5LIB
export PERL5LIB=`pwd`/dist/constant/lib:$PERL5LIB
export PERL5LIB=`pwd`/cpan/ExtUtils-MakeMaker/lib:$PERL5LIB
export PERL5LIB=`pwd`/dist/Carp/lib:$PERL5LIB
export PERL5LIB=`pwd`/cpan/File-Path/lib:$PERL5LIB
export PERL5LIB=`pwd`/dist/PathTools:$PERL5LIB
export PERL5LIB=`pwd`/dist/PathTools/lib:$PERL5LIB
export PERL5LIB=`pwd`/ext/File-Find/lib:$PERL5LIB

Even so, I'll still get an error for a module that isn't even present in the 5.24.0 source!

Can't locate ExtUtils/MakeMaker/version/vpp.pm in @INC (you may need to install the ExtUtils::MakeMaker::version::vpp module) (@INC contains: <removed from post>) at (eval 2) line 2.
BEGIN failed--compilation aborted at (eval 2) line 2.
Compilation failed in require at .../perl-5.24.0/cpan/ExtUtils-MakeMaker/lib/ExtUtils/MakeMaker.pm line 10.
BEGIN failed--compilation aborted at .../perl-5.24.0/cpan/ExtUtils-MakeMaker/lib/ExtUtils/MakeMaker.pm line 10.
Compilation failed in require at Makefile.PL line 7.
BEGIN failed--compilation aborted at Makefile.PL line 7.
Unsuccessful Makefile.PL(cpan/Archive-Tar): code=512 at make_ext.pl line 517.
make: The error code from the last command is 2.

I have MakeMaker, but the 5.24 version does not contain vpp.pm! Again, in desperation I attempted to put it in there from a different source, and I get this error:

        LIBPATH=.../perl-5.24.0 ./miniperl -Ilib make_ext.pl cpan/Archive-Tar/pm_to_blib  MAKE="make" LIBPERL_A=libperl.a
readdir(./../../../../../../..): No such file or directory at .../perl-5.24.0/ext/File-Find/lib/File/Find.pm line 142.
Can't cd to : No such file or directory
Unsuccessful Makefile.PL(cpan/Archive-Tar): code=512 at make_ext.pl line 517.
make: The error code from the last command is 2.

All of this makes me feel like perhaps I'm not configuring something right... Can anyone with some experience help me out with some cut and dry installation instructions for Perl on AIX? I'd be super grateful. Thanks!

Below is some information about my system:

> prtconf
System Model: IBM,8231-E1D
Machine Serial Number: Not Available
Processor Type: Not Available
Processor Implementation Mode: POWER 7
Processor Version: PV_7_Compat
Number Of Processors: 0
Processor Clock Speed: Not Available
CPU Type: 64-bit
Kernel Type: 64-bit
Memory Size: 10240 MB
Good Memory Size: Not Available
Platform Firmware level: Not Available
Firmware Version: IBM,AL770_092
Console Login: disable
Auto Restart: true
Full Core: false


问:
How should I start designing an AI algorithm for an artillery warfare game?
Here's the background... in my free time I'm designing an artillery warfare game called Staker (inspired by the old BASIC games Tank Wars and Scorched Earth) and I'm programming it in MATLAB. Your first thought might be "Why MATLAB? There are plenty of other languages/software packages that are better for game design." And you would be right. However, I'm a dork and I'm interested in learning the nuts and bolts of how you would design a game from the ground up, so I don't necessarily want to use anything with prefab modules. Also, I've used MATLAB for years and I like the challenge of doing things with it that others haven't really tried to do.

Now to the problem at hand: I want to incorporate AI so that the player can go up against the computer. I've only just started thinking about how to design the algorithm to choose an azimuth angle, elevation angle, and projectile velocity to hit a target, and then adjust them each turn. I feel like maybe I've been overthinking the problem and trying to make the AI too complex at the outset, so I thought I'd pause and ask the community here for ideas about how they would design an algorithm.

Some specific questions:

Are there specific references for AI design that you would suggest I check out?

Would you design the AI players to vary in difficulty in a continuous manner (a difficulty of 0 (easy) to 1 (hard), all still using the same general algorithm) or would you design specific algorithms for a discrete number of AI players (like an easy enemy that fires in random directions or a hard enemy that is able to account for the effects of wind)?

What sorts of mathematical algorithms (pseudocode description) would you start with?

Some additional info: the model I use to simulate projectile motion incorporates fluid drag and the effect of wind. The "fluid" can be air or water. In air, the air density (and thus effect of drag) varies with height above the ground based on some simple atmospheric models. In water, the drag is so great that the projectile usually requires additional thrust. In other words, the projectile can be affected by forces other than just gravity.

答:
Loren's brute force solution is appealing as because it would allow easy "Intelligence adjustments" by adding more iterations. Also the adjustment factors for the iteration could be part of the intelligence as some value will make it converge faster.

Also for the basic system (no drag, wind, etc) there is a closed form solution that can be derived from a basic physics text. I would make the first guess be that and then do one or more iteration per turn. You might want to try and come up with an empirical correction correlation to improve the first shot (something that will make the first shot distributions average be closer to correct)

OwnerDisplayName: gnovice

LastEditorDisplayName: gnovice

OwnerDisplayName: BCS


问:
Generate plot of conditional mean of y, given continuous x in R / ggplot2
I would like to create a line plot in  R that shows the conditional mean of y for a given range of x, where x is uniformly distributed between 0 and 1. I would like to be able to specify the bin width to be 1% point wide, so my line would have 100 data points. I would particularly like to know how this can be done in ggplot2.

```<code>x=runif(10000,0,1)
y=rnorm(10000,50,10)
plot(x,y)
</code>```

Creating a scatter plot generates 10000 points, which makes interpretation hard.

答:
maybe using ggplot2::stat_smooth() with n = 100 (for evaluating at 100 evenly spread points) is enough for you here:

```<code>data <- data.frame(x,y)
ggplot(data, aes(x, y)) +
    geom_point() +
    stat_smooth(n = 100) # you can change the "method" argument for different fits see ?stat_smooth
</code>```

Body:
I would like to create a line plot in  R that shows the conditional mean of y for a given range of x, where x is uniformly distributed between 0 and 1. I would like to be able to specify the bin width to be 1% point wide, so my line would have 100 data points. I would particularly like to know how this can be done in ggplot2.

x=runif(10000,0,1)
y=rnorm(10000,50,10)
plot(x,y)

Creating a scatter plot generates 10000 points, which makes interpretation hard.

Body:
maybe using ggplot2::stat_smooth() with n = 100 (for evaluating at 100 evenly spread points) is enough for you here:

data <- data.frame(x,y)
ggplot(data, aes(x, y)) +
    geom_point() +
    stat_smooth(n = 100) # you can change the "method" argument for different fits see ?stat_smooth


问:
Electron JS + SQLite database
I have an Electron JS application that uses a local sqlite database. The sqlite database is a file within the project folder structure (lib folder). The application works just fine during testing, but when I build the app on Mac, and launch the .dmg file, it gets an error saying it cannot find the .sqlite database.

Is there a way to get this to work with the sqlite database I have in my project? Or is there a simpler way to do local storage in an Electron app?

Thank you.

答:
I found out this can be accomplished by writing the SQLite file to the local user's directory:</p>

```<code>const electron = require('electron');
const path = require('path');
const userDir = (electron.app || electron.remote.app).getPath('userData');
const dbPath = path.join(userDir, 'mydb.sqlite');
</code>```

Title: Electron JS + SQLite database

Body:
I found out this can be accomplished by writing the SQLite file to the local user's directory:

const electron = require('electron');
const path = require('path');
const userDir = (electron.app || electron.remote.app).getPath('userData');
const dbPath = path.join(userDir, 'mydb.sqlite');


问:
Xcode Interface Builder is showing "No selection" for all files
No matter what I've got selected in Interface Builder, the Inspector did apparently not register the selection and only showed "No selection".

I tried opening and closing files, restarting Xcode and even rebooting my Mac. No change! What the heck is going on?

Other projects work just fine. It's just this project...

答: In Xcode 8.3, the preferred solution doesn't appear to work. My solution, similar to travdu, was to click the "Show the version editor" button (the two arrows pointing left and right), then back to the "Show the Standard editor". Doing that fixed it for me.</p>


问:
In Elm, how would I express verbally function type defn: `route : Url.Parser (Route -> a) a`?
I'm trying to understand this code from url-parser:

```<code>route : Url.Parser (Route -> a) a
route =
    Url.oneOf
        [ Url.map Home top
        , Url.map BlogList (s "blog" <?> stringParam "search")
        , Url.map BlogPost (s "blog" </> int)
        ]
</code>```

Is it: "route is a function that takes 1) a Parser, 2) a function that takes a Route and returns an a, and 3) an a"?

This doesn't seem correct because if it's just listing the arguments, where is it expressing the return value of route itself?

I'm very new to elm, but what throws me off here is that the -> is contained within the parens, and then there's no -> at the end indicating what route returns.

答:
The easy answer is that route here is not really a function, but a constant: it represents a particular kind of Parser.

Now this, of course, raises the more difficult question of what kind of parser does it represent?

And that is a rather tricky one. I believe having some background on parser combinators could probably help here (https://en.wikipedia.org/wiki/Parser_combinator).

But either way,  it took me a while and I might still be getting it wrong.
These are the steps I went through:

Let's look at what you can do with a Parser. You can execute it using parsePath or parseHash. Each of which promising that if you provide a Parser of type Parser (a->a) a (where a is a generic type variable) then it will turn a Location into a Maybe a

Let's look at what kind of parser primitives you have. string for instance is a Parser (String -> a) a, while int is Parser (Int -> a) a.

Now, look at the combinators, especially </>, which is Parser a b -> Parser b c -> Parser a c. If you write string </> int, you will get a Parser (String -> Int -> c) c. This is possible, because the type variable in string can be substituted as Int -> c, so it becomes Parser (String -> Int -> c) (Int -> c).

Based on no.3. I would conclude that a Parser a b represents a parser that can parse part of a complex a to reduce it to a simpler b.

From a package user's perspective this goes the other way around though. If you represent your routes with the data type Route you must define a Parser (Route -> a) a to be able to turn the url into your internal representation. If one of your constructors for Route is something like MyTwoParamsRoute String Int, then you will first need to define myTwoParamsParser : Parser (String -> Int -> a) a using some of the combinators (</> or <?>) and then use map MyTwoParamsRoute myTwoParamsParse to actually apply the constructor function.

So the long answer to your original question: route : Parser (Route -> a) a represents a parser which can parse a Route out of some string (typically either the hash or the path part of the url) -- while offering the possibility that once the string is reduced by whatever Route represents, the remainder can be further parsed by a different parser.

Body:
I'm trying to understand this code from url-parser:

route : Url.Parser (Route -> a) a
route =
    Url.oneOf
        [ Url.map Home top
        , Url.map BlogList (s "blog" <?> stringParam "search")
        , Url.map BlogPost (s "blog" </> int)
        ]

Is it: "route is a function that takes 1) a Parser, 2) a function that takes a Route and returns an a, and 3) an a"?

This doesn't seem correct because if it's just listing the arguments, where is it expressing the return value of route itself?

I'm very new to elm, but what throws me off here is that the -> is contained within the parens, and then there's no -> at the end indicating what route returns.


问:
How do you emit a set of values over time with RXjs?
I'm looking to take a series of values emitted by an Observable like this, Rx.Observable.of(["add", "edit", "destroy"]), but I want each value to be emitted every 5 seconds.

Currently I'm faking this using setTimer() and a Subject like this.

```<code>const actions$ = new Rx.Subject();

setTimeout(() => { actions$.next("add");  }, 5 * 1000);
setTimeout(() => { actions$.next("edit"); }, 10 * 1000);
setTimeout(() => { actions$.next("destroy"); }, 15 * 1000);
</code>```

But it seems like there's probably a way to do this without as much handwaving. How can I do this without using setTimeout()?

答:
There are many ways you could do this with RxJS.

One would be to create an interval observable and use it together with zip to emit a name each time the interval observable emits.

The zip operator merges the emissions of the observables it's passed whenever each has emitted a value. And the optional selector is used here to ignore the incremental integers emitted by the interval observable.

const names = Rx.Observable.from(["add", "edit", "destroy"]);
const interval = Rx.Observable.interval(500);
Rx.Observable
  .zip(names, interval, (name, i) => name)
  .subscribe(name => console.log(name));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

```

And I've reduced the interval to 500 because I'm impatient.

Body:
I'm looking to take a series of values emitted by an Observable like this, Rx.Observable.of(["add", "edit", "destroy"]), but I want each value to be emitted every 5 seconds.

Currently I'm faking this using setTimer() and a Subject like this.

const actions$ = new Rx.Subject();

setTimeout(() => { actions$.next("add");  }, 5 * 1000);
setTimeout(() => { actions$.next("edit"); }, 10 * 1000);
setTimeout(() => { actions$.next("destroy"); }, 15 * 1000);

But it seems like there's probably a way to do this without as much handwaving. How can I do this without using setTimeout()?

Body:
There are many ways you could do this with RxJS.

One would be to create an interval observable and use it together with zip to emit a name each time the interval observable emits.

The zip operator merges the emissions of the observables it's passed whenever each has emitted a value. And the optional selector is used here to ignore the incremental integers emitted by the interval observable.

const names = Rx.Observable.from(["add", "edit", "destroy"]);
const interval = Rx.Observable.interval(500);
Rx.Observable
  .zip(names, interval, (name, i) => name)
  .subscribe(name => console.log(name));

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>

And I've reduced the interval to 500 because I'm impatient.


问:
Using ffmpeg to generate thumbnails every minute at the first frame in the interval
Granted, the minute may be different (e.g. 30 seconds or 2 minutes), but the logic of the issue remains the same. I currently have three solutions, all with their own drawbacks.

My first solution uses the fps selection as follows:

```<code>ffmpeg -i <input> -vf scale=320:-1,fps=1/60 "img%04d.jpg"
</code>```

This goes through the video once, however the selection for the frames isn't the first frame every 60 seconds, but instead the middle frame for them. This produces frames at 0:30, 1:30, 2:30... and so on.

My second solution calculates the number of thumbnails via bash, and uses the ss option in order to manually seek the thumbnail and retrieve it:

```<code>#durRaw: interval in seconds (this case: 60)
#end: the end index for the number of thumbnails needed
for t in $(seq 0 $end)
do
    local time=$(bc -l <<< "(( $t * $durRaw ))")
    ffmpeg -i <input> -ss $time -vframes 1 -vf scale=320:-1 "img$(printf "%04d" $t).jpg"
done
</code>```

This results in accurate frames, but too many video reads, as it will generally have to seek through the entire video 30-60 times in order to generate the necessary thumbnails.

Finally, my third solution, which happens to be fast and accurate, suffers from a quality degradation as the video progresses (artifacts will start becoming visible and the filesize drops to about 25% of comparable files). I understand the video is scaled, but the quality drops even further than what I have scaled to. I used the select filter and fed the framerate calculation into it:

```<code>getFrameRate() {
    ffmpeg -i "$1" 2>&1 | sed -n "s/.*, \(.*\) fp.*/\1/p"
}
local fr=$(getFrameRate <input>)
local sel=$(bc -l <<< "(( $fr * $durRaw ))") #in actual code, sel is floored
ffmpeg -i <input> -vf "scale=320:-1,select='not(mod(n,$sel))',setpts='N/($fr*TB)'" "img%04d.jpg"
</code>```

I can't seem to generate thumbnails without having some sort of massive drawback. Due to the number of videos I need to run this through, solution 2 (while being optimal) would take weeks to actually finalize processing for all the videos needed. Solution 3 would be ideal if there was no degradation involved, and online guides seem to all point back to the same solutions I have tried. In short, I need to be able to generate thumbnails reasonably quickly (aka in a single passthrough) without unreasonably losing quality.

答:
Use the -ss parameter from solution #2 before the input (-i), in order to read the input much faster. As an excerpt:

ss before:

The input will be parsed using keyframes, which is very fast.

ss after:

Here, the input will be decoded (and discarded) until it reaches the position given by -ss. This will be done very slowly

https://trac.ffmpeg.org/wiki/Seeking

Took the time to generate information from a matter of minutes/hours to milliseconds/seconds.

Body:
Granted, the minute may be different (e.g. 30 seconds or 2 minutes), but the logic of the issue remains the same. I currently have three solutions, all with their own drawbacks.

My first solution uses the fps selection as follows:

ffmpeg -i <input> -vf scale=320:-1,fps=1/60 "img%04d.jpg"

This goes through the video once, however the selection for the frames isn't the first frame every 60 seconds, but instead the middle frame for them. This produces frames at 0:30, 1:30, 2:30... and so on.

My second solution calculates the number of thumbnails via bash, and uses the ss option in order to manually seek the thumbnail and retrieve it:

#durRaw: interval in seconds (this case: 60)
#end: the end index for the number of thumbnails needed
for t in $(seq 0 $end)
do
    local time=$(bc -l <<< "(( $t * $durRaw ))")
    ffmpeg -i <input> -ss $time -vframes 1 -vf scale=320:-1 "img$(printf "%04d" $t).jpg"
done

This results in accurate frames, but too many video reads, as it will generally have to seek through the entire video 30-60 times in order to generate the necessary thumbnails.

Finally, my third solution, which happens to be fast and accurate, suffers from a quality degradation as the video progresses (artifacts will start becoming visible and the filesize drops to about 25% of comparable files). I understand the video is scaled, but the quality drops even further than what I have scaled to. I used the select filter and fed the framerate calculation into it:

getFrameRate() {
    ffmpeg -i "$1" 2>&1 | sed -n "s/.*, \(.*\) fp.*/\1/p"
}
local fr=$(getFrameRate <input>)
local sel=$(bc -l <<< "(( $fr * $durRaw ))") #in actual code, sel is floored
ffmpeg -i <input> -vf "scale=320:-1,select='not(mod(n,$sel))',setpts='N/($fr*TB)'" "img%04d.jpg"

I can't seem to generate thumbnails without having some sort of massive drawback. Due to the number of videos I need to run this through, solution 2 (while being optimal) would take weeks to actually finalize processing for all the videos needed. Solution 3 would be ideal if there was no degradation involved, and online guides seem to all point back to the same solutions I have tried. In short, I need to be able to generate thumbnails reasonably quickly (aka in a single passthrough) without unreasonably losing quality.


问:
Does platforms like Solaris, HP-UX, IBM-AIX etc support Unix Domain Socket without need for socket file, like Linux?
I am working on a project which runs on different platforms including Linux, Solaris, HP-UX & IBM-AIX.

When we create a new socket using socket(), system creates pathname socket and also, creates a file in some temp directory. I am trying to set up an environment where this file doesn't get created.

I have found a solution for Linux. In Linux, there is notion of 'Abstract Socket'. An abstract socket address is distinguished (from a pathname socket) by the fact that sun_path[0] is a null byte ('\0'). For more info, please refer the man page - http://man7.org/linux/man-pages/man7/unix.7.html

I am trying to find out similar solution i.e. 'no file should be created for a socket' for other platforms namely Solaris, HP-UX & IBM-AIX.

答:
For AIX, I am pretty sure that there is no equivalent as abstract socket.  There is shared memory and other interprocess communication facilities.

For unix domain socket, I believe it is the file system that provides the security / protection if that is desired.  e.g. you can restrict the path to a particular group and then the file system will make sure that only that uses in that group (as in /etc/group) can access that path.


问:
Convert word2vec bin file to text
From the word2vec site I can download GoogleNews-vectors-negative300.bin.gz.  The .bin file (about 3.4GB) is a binary format not useful to me.  Tomas Mikolov assures us that "It should be fairly straightforward to convert the binary format to text format (though that will take more disk space). Check the code in the distance tool, it's rather trivial to read the binary file."  Unfortunately, I don't know enough C to understand http://word2vec.googlecode.com/svn/trunk/distance.c.

Supposedly gensim can do this also, but all the tutorials I've found seem to be about converting from text, not the other way.

Can someone suggest modifications to the C code or instructions for gensim to emit text?

答:
If you get the Error:

```<code>ImportError: No module named models.word2vec
</code>```

then it is because there was an API update. This will work:

```<code>from gensim.models.keyedvectors import KeyedVectors

model = KeyedVectors.load_word2vec_format('./GoogleNews-vectors-negative300.bin', binary=True)
model.save_word2vec_format('./GoogleNews-vectors-negative300.txt', binary=False)
</code>```

Title: Convert word2vec bin file to text

Body:
If you get the Error:

ImportError: No module named models.word2vec

then it is because there was an API update. This will work:

from gensim.models.keyedvectors import KeyedVectors

model = KeyedVectors.load_word2vec_format('./GoogleNews-vectors-negative300.bin', binary=True)
model.save_word2vec_format('./GoogleNews-vectors-negative300.txt', binary=False)


问:
ValueError: invalid literal for int() with base 10: 'NULL'
When I run python manage.py migrate on my file, this ValueError shows up.

```<code>Operations to perform:
  Apply all migrations: admin, auth, cms, contenttypes, sessions
Running migrations:
  Applying cms.0002_auto_20170401_2307...Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\sndys\project\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "C:\Users\sndys\project\lib\site-packages\django\core\management\__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\sndys\project\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\sndys\project\lib\site-packages\django\core\management\base.py", line 345, in execute
    output = self.handle(*args, **options)
  File "C:\Users\sndys\project\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "C:\Users\sndys\project\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Users\sndys\project\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Users\sndys\project\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Users\sndys\project\lib\site-packages\django\db\migrations\migration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Users\sndys\project\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards
    field,
  File "C:\Users\sndys\project\lib\site-packages\django\db\backends\sqlite3\schema.py", line 231, in add_field
    self._remake_table(model, create_fields=[field])
  File "C:\Users\sndys\project\lib\site-packages\django\db\backends\sqlite3\schema.py", line 113, in _remake_table
    self.effective_default(field)
  File "C:\Users\sndys\project\lib\site-packages\django\db\backends\base\schema.py", line 221, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "C:\Users\sndys\project\lib\site-packages\django\db\models\fields\related.py", line 909, in get_db_prep_save
    return self.target_field.get_db_prep_save(value, connection=connection)
  File "C:\Users\sndys\project\lib\site-packages\django\db\models\fields\__init__.py", line 755, in get_db_prep_save
    prepared=False)
  File "C:\Users\sndys\project\lib\site-packages\django\db\models\fields\__init__.py", line 938, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Users\sndys\project\lib\site-packages\django\db\models\fields\__init__.py", line 946, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: 'NULL'
</code>```

My models.py file:

```<code>from django.db import models
from django.contrib.auth.models import User
import markdown

# Create your models here.
class Tag(models.Model):
    name = models.CharField(max_length=32)
    slug = models.SlugField()

    def __str__(self):
        return self.name

class Category(models.Model):
    name = models.CharField(max_length=32)
    slug = models.SlugField()
    description = models.TextField()
    image = models.ImageField()

    def __str__(self):
        return self.name

class Image(models.Model):
    name = models.CharField(max_length=32)
    slug = models.SlugField()
    alt_text = models.CharField(max_length=255)
    image = models.ImageField()

    def __str__(self):
        return self.name

class Gallery(models.Model):
    name = models.CharField(max_length=32)
    slug = models.SlugField()
    images = models.ManyToManyField(Image)
    description = models.TextField()
    layout = models.CharField(
        max_length=5,
        choices=(
            ('LINK', 'Linked'),
            ('HORI', 'Horizontal'),
            ('VERT', 'Vertical')))

    def __str__(self):
        return self.name

class Article(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField()
    author = models.ForeignKey(User)
    content = models.TextField()
    creation_date = models.DateTimeField(auto_now_add=True)
    edit_date = models.DateTimeField(auto_now=True)
    featured_image = models.ImageField(null=True, blank=True)
    publish_status = models.BooleanField(default=False)
    category = models.ForeignKey(Category)
    tags = models.ManyToManyField(Tag)

    @property
    def content_html(self):
        return markdown.markdown(self.content)
    def __str__(self):
        return self.title

    class Meta:
        verbose_name_plural = 'Articles'
        ordering = ['creation_date']`enter code here`
</code>```

When I did python manage.py makemigrations, this showed up:

You are trying to add a non-nullable field 'category' to article without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:

1) Provide a one-off default now (will be set on all existing rows with a null value for this column)

2) Quit, and let me add a default in models.py

Select an option:

I selected 1 and gave the default value "NULL" and I think this is the mistake I may have made. After this "python manage.py makemigrations" ran successfully but "python manage.py migrate" is giving an error.
After this I tried to give the category foreign key in Article class a default value = 1 but same error occurs on migrate.

Can anyone tell me where is the problem and how to fix it.

答: You aren't supposed to give the value you want the DB to receive. You give the value in Python. However you would only get that message if null=True wasn't set on the field. Delete the migration and set null=True on the field.</p>

Body:
When I run python manage.py migrate on my file, this ValueError shows up.

Operations to perform:
  Apply all migrations: admin, auth, cms, contenttypes, sessions
Running migrations:
  Applying cms.0002_auto_20170401_2307...Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\sndys\project\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "C:\Users\sndys\project\lib\site-packages\django\core\management\__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\sndys\project\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\sndys\project\lib\site-packages\django\core\management\base.py", line 345, in execute
    output = self.handle(*args, **options)
  File "C:\Users\sndys\project\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "C:\Users\sndys\project\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Users\sndys\project\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Users\sndys\project\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Users\sndys\project\lib\site-packages\django\db\migrations\migration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Users\sndys\project\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards
    field,
  File "C:\Users\sndys\project\lib\site-packages\django\db\backends\sqlite3\schema.py", line 231, in add_field
    self._remake_table(model, create_fields=[field])
  File "C:\Users\sndys\project\lib\site-packages\django\db\backends\sqlite3\schema.py", line 113, in _remake_table
    self.effective_default(field)
  File "C:\Users\sndys\project\lib\site-packages\django\db\backends\base\schema.py", line 221, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "C:\Users\sndys\project\lib\site-packages\django\db\models\fields\related.py", line 909, in get_db_prep_save
    return self.target_field.get_db_prep_save(value, connection=connection)
  File "C:\Users\sndys\project\lib\site-packages\django\db\models\fields\__init__.py", line 755, in get_db_prep_save
    prepared=False)
  File "C:\Users\sndys\project\lib\site-packages\django\db\models\fields\__init__.py", line 938, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Users\sndys\project\lib\site-packages\django\db\models\fields\__init__.py", line 946, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: 'NULL'

My models.py file:

from django.db import models
from django.contrib.auth.models import User
import markdown

# Create your models here.
class Tag(models.Model):
    name = models.CharField(max_length=32)
    slug = models.SlugField()

    def __str__(self):
        return self.name

class Category(models.Model):
    name = models.CharField(max_length=32)
    slug = models.SlugField()
    description = models.TextField()
    image = models.ImageField()

    def __str__(self):
        return self.name

class Image(models.Model):
    name = models.CharField(max_length=32)
    slug = models.SlugField()
    alt_text = models.CharField(max_length=255)
    image = models.ImageField()

    def __str__(self):
        return self.name

class Gallery(models.Model):
    name = models.CharField(max_length=32)
    slug = models.SlugField()
    images = models.ManyToManyField(Image)
    description = models.TextField()
    layout = models.CharField(
        max_length=5,
        choices=(
            ('LINK', 'Linked'),
            ('HORI', 'Horizontal'),
            ('VERT', 'Vertical')))

    def __str__(self):
        return self.name

class Article(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField()
    author = models.ForeignKey(User)
    content = models.TextField()
    creation_date = models.DateTimeField(auto_now_add=True)
    edit_date = models.DateTimeField(auto_now=True)
    featured_image = models.ImageField(null=True, blank=True)
    publish_status = models.BooleanField(default=False)
    category = models.ForeignKey(Category)
    tags = models.ManyToManyField(Tag)

    @property
    def content_html(self):
        return markdown.markdown(self.content)
    def __str__(self):
        return self.title

    class Meta:
        verbose_name_plural = 'Articles'
        ordering = ['creation_date']`enter code here`

When I did python manage.py makemigrations, this showed up:

You are trying to add a non-nullable field 'category' to article without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:

1) Provide a one-off default now (will be set on all existing rows with a null value for this column)

2) Quit, and let me add a default in models.py

Select an option:

I selected 1 and gave the default value "NULL" and I think this is the mistake I may have made. After this "python manage.py makemigrations" ran successfully but "python manage.py migrate" is giving an error.
After this I tried to give the category foreign key in Article class a default value = 1 but same error occurs on migrate.

Can anyone tell me where is the problem and how to fix it.


问:
Table content held within a div will not print over several pages
I have some tabular content that is held within a div thus..

```<code><div class="someDiv">
   <table>
       <tr>...</tr>
       ....
       ....
       <tr>...</tr>
   </table>
</div>
</code>```

When I print using a print stylesheet with all items set to float:none !important; and height:auto !important; the table will only print one page worth of information as opposed to about 10 or so.

Has anyone come across this before?

答:
The fix was to add </p>

```<code>* { overflow:visible ! important; }
</code>```

Body:
I have some tabular content that is held within a div thus..

...

       ....
       ....

...

When I print using a print stylesheet with all items set to float:none !important; and height:auto !important; the table will only print one page worth of information as opposed to about 10 or so.

Has anyone come across this before?

Body:
The fix was to add

* { overflow:visible ! important; }