问:
OptionalDataException with no apparent reason
I am using following class to serialize and deserialize my classes.

```<code>import java.io.*;

public final class Serialization {

    public static void writeObject(Object obj, String path){
        try (ObjectOutputStream oos =
                     new ObjectOutputStream(new FileOutputStream(path))) {

            oos.writeObject(obj);
            //System.out.println("Done");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static Object readObject(String path){
        Object obj = null;
        FileInputStream fin = null;
        ObjectInputStream ois = null;

        try {
            fin = new FileInputStream(path);
            ois = new ObjectInputStream(fin);
            obj = ois.readObject();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return obj;
    }
}
</code>```

I have a class that implements the Serializable interface: TextCategorizator. I am trying to use this class as a classification model. So, to serialize this class' object, I use

```<code>TextCategorizator tc = new TextCategorizator(trainingFiles, vecFile);
Serialization.writeObject(tc, MODEL_PATH);
</code>```

And then when I try to read this serialized object with

```<code>TextCategorizator model = (TextCategorizator) Serialization.readObject(MODEL_PATH);
</code>```

I got the following exception trace:

```<code>java.io.OptionalDataException
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1373)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373)
at java.util.HashMap.readObject(HashMap.java:1402)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1058)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1909)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1808)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1353)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2018)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1942)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1808)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1353)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373)
at utils.Serialization.readObject(Serialization.java:27)
at Main.main(Main.java:33)
</code>```

The part that raises the exception is:

```<code>obj = ois.readObject();
</code>```

When I look at reference page of this exception, it says there are two options which indicated with the eof flag and length variable in this exception.
I printed them to see. eof is true, length is 0. This means, according to reference page,

An attempt was made to read past the end of data consumable by a class-defined readObject or readExternal method. In this case, the OptionalDataException's eof field is set to true, and the length field is set to 0.

I used these methods before and I did not face with this exception. What's wrong and what exactly the "read past" means?

EDIT : TextCategorizator class is here:

```<code>import utils.FileUtils;

import java.io.File;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

public class TextCategorizator implements Serializable {
    private Map<String, String> wordVectors;
    private Map<File, List<List<Double>>> docVectors;
    private Map<File, String> trainingFiles;
    private Set<String> classes;

    public TextCategorizator(Map<File, String> trainingFiles, String trainedVectors) {
        wordVectors = new HashMap<>();
        docVectors = new HashMap<>();
        classes = new HashSet<>();

        this.trainingFiles = trainingFiles;
        List<String> lines = FileUtils.readFileAsList(new File(trainedVectors));

        System.out.println("> Reading word vector file.");
        lines.parallelStream().forEach(line -> {
            String name = line.substring(0, line.indexOf(' '));
            wordVectors.put(name, line);
        });

        train(trainingFiles);
    }

    private void train(Map<File, String> trainingFiles) {
        System.out.println("> Starting training parallel.");
        trainingFiles.entrySet().parallelStream().forEach(entry -> {
            docVectors.put(entry.getKey(), getVectorsOfDoc(entry.getKey()));
            classes.add(entry.getValue());
        });
    }

    private List<List<Double>> getVectorsOfDoc(File doc) {
        List<List<Double>> lists = new ArrayList<>();

        List<Double> resultVecAvg = new ArrayList<>();
        List<Double> resultVecMax = new ArrayList<>();
        List<Double> resultVecMin = new ArrayList<>();
        int vecSize = 100;

        for (int i = 0; i < vecSize; i++) {
            resultVecAvg.add(0.0);
            resultVecMax.add(0.0);
            resultVecMin.add(0.0);
        }

        String[] words = FileUtils.readWords(doc);
        for (String word : words) {
            String line = wordVectors.get(word);
            if (line != null) {
                List<Double> vec = new ArrayList<>();
                String[] tokens = line.split(" ");
                for (int i = 1; i < tokens.length; i++) {
                    vec.add(Double.parseDouble(tokens[i]));
                }

                for (int i = 0; i < vec.size(); i++) {
                    resultVecAvg.set(i, resultVecAvg.get(i) + (vec.get(i) / vecSize));
                    resultVecMax.set(i, Math.max(resultVecMax.get(i), vec.get(i)));
                    resultVecMin.set(i, Math.min(resultVecMin.get(i), vec.get(i)));
                }
            }
        }

        lists.add(resultVecAvg); lists.add(resultVecMax); lists.add(resultVecMin);

        return lists;
    }

    private void getCosineSimilarities(List<Double> givenVec, int option, Map<File, Double> distances) {
        for (Map.Entry<File, List<List<Double>>> entry : docVectors.entrySet()) {
            List<Double> vec = null;
            if (option == 1) // AVG
                vec = entry.getValue().get(0);
            else if (option == 2) // MAX
                vec = entry.getValue().get(1);
            else if (option == 3) // MIN
                vec = entry.getValue().get(2);

            distances.put(entry.getKey(), cosSimilarity(givenVec, vec));
        }
    }

    private double cosSimilarity(List<Double> vec1, List<Double> vec2) {
        double norm1 = 0.0;
        double norm2 = 0.0;
        double dotProduct = 0.0;
        for (int i = 0; i < vec1.size(); i++) {
            norm1 += Math.pow(vec1.get(i), 2);
            norm2 += Math.pow(vec2.get(i), 2);
            dotProduct += vec1.get(i) * vec2.get(i);
        }
        return dotProduct / (Math.sqrt(norm1) * Math.sqrt(norm2));
    }

    // from http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java
    private <K, V extends Comparable<? super V>> Map<K, V>
    sortByValue(Map<K, V> map, boolean reverse) {
        return map.entrySet()
                .stream()
                .sorted((reverse ?
                        Map.Entry.comparingByValue(Collections.reverseOrder()) :
                        Map.Entry.comparingByValue()))
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1,
                        LinkedHashMap::new
                ));
    }

    private int countClass(List<File> files, String c) {
        int counter = 0;
        for (File file : files) {
            if (trainingFiles.get(file).equals(c))
                ++counter;
        }
        return counter;
    }

    public Map.Entry<String, Integer> classifyKnn(File file, int k, int option) {
        List<List<Double>> vecs = getVectorsOfDoc(file);
        List<Double> vec = getProperVector(vecs, option);

        Map<File, Double> distances = new HashMap<>();

        getCosineSimilarities(vec, option, distances);
        distances = sortByValue(distances, true);

        List<File> sortedFiles = new ArrayList<>(distances.keySet());
        sortedFiles = sortedFiles.subList(0, k);
        Map<String, Integer> counts = new HashMap<>();
        for (String category : classes) {
            counts.put(category, countClass(sortedFiles, category));
        }

        ArrayList<Map.Entry<String, Integer>> resultList =
                new ArrayList(sortByValue(counts, true).entrySet());

        return resultList.get(0);
    }

    private List<Double> getProperVector(List<List<Double>> lists, int option) {
        List<Double> vec = null;
        if (option == 1) // AVG
            vec = lists.get(0);
        else if (option == 2) // MAX
            vec = lists.get(1);
        else if (option == 3) // MIN
            vec = lists.get(2);

        return vec;
    }

    public Map.Entry<String, Double> classifyRocchio(File file, int option) {
        List<List<Double>> vecs = getVectorsOfDoc(file);
        List<Double> vec = getProperVector(vecs, option);

        Map<File, Double> distances = new HashMap<>();
        getCosineSimilarities(vec, option, distances);

        distances = sortByValue(distances, true);
        List<Map.Entry<File, Double>> sortedFiles =
                new ArrayList<>(distances.entrySet());

        return new AbstractMap.SimpleEntry<>
                (trainingFiles.get(sortedFiles.get(0).getKey()),
                        sortedFiles.get(0).getValue());
    }
}
</code>```

答:
Finally I got this working. The problem was the size of the objects that I was trying to serialize and deserialize (i.e wordVectors is 480 MB).

To fix this, I used synchronized map. So

```<code>wordVectors = new HashMap<>();
</code>```

is changed to

```<code>wordVectors = Collections.synchronizedMap(new HashMap<>());
</code>```

I got the idea from here.

Body:
I am using following class to serialize and deserialize my classes.

import java.io.*;

public final class Serialization {

    public static void writeObject(Object obj, String path){
        try (ObjectOutputStream oos =
                     new ObjectOutputStream(new FileOutputStream(path))) {

            oos.writeObject(obj);
            //System.out.println("Done");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static Object readObject(String path){
        Object obj = null;
        FileInputStream fin = null;
        ObjectInputStream ois = null;

        try {
            fin = new FileInputStream(path);
            ois = new ObjectInputStream(fin);
            obj = ois.readObject();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return obj;
    }
}

I have a class that implements the Serializable interface: TextCategorizator. I am trying to use this class as a classification model. So, to serialize this class' object, I use

TextCategorizator tc = new TextCategorizator(trainingFiles, vecFile);
Serialization.writeObject(tc, MODEL_PATH);

And then when I try to read this serialized object with

TextCategorizator model = (TextCategorizator) Serialization.readObject(MODEL_PATH);

I got the following exception trace:

java.io.OptionalDataException
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1373)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373)
at java.util.HashMap.readObject(HashMap.java:1402)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1058)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1909)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1808)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1353)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2018)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1942)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1808)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1353)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373)
at utils.Serialization.readObject(Serialization.java:27)
at Main.main(Main.java:33)

The part that raises the exception is:

obj = ois.readObject();

When I look at reference page of this exception, it says there are two options which indicated with the eof flag and length variable in this exception.
I printed them to see. eof is true, length is 0. This means, according to reference page,

An attempt was made to read past the end of data consumable by a class-defined readObject or readExternal method. In this case, the OptionalDataException's eof field is set to true, and the length field is set to 0.

I used these methods before and I did not face with this exception. What's wrong and what exactly the "read past" means?

EDIT : TextCategorizator class is here:

import utils.FileUtils;

import java.io.File;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

public class TextCategorizator implements Serializable {
    private Map<String, String> wordVectors;
    private Map<File, List<List<Double>>> docVectors;
    private Map<File, String> trainingFiles;
    private Set<String> classes;

    public TextCategorizator(Map<File, String> trainingFiles, String trainedVectors) {
        wordVectors = new HashMap<>();
        docVectors = new HashMap<>();
        classes = new HashSet<>();

        this.trainingFiles = trainingFiles;
        List<String> lines = FileUtils.readFileAsList(new File(trainedVectors));

        System.out.println("> Reading word vector file.");
        lines.parallelStream().forEach(line -> {
            String name = line.substring(0, line.indexOf(' '));
            wordVectors.put(name, line);
        });

        train(trainingFiles);
    }

    private void train(Map<File, String> trainingFiles) {
        System.out.println("> Starting training parallel.");
        trainingFiles.entrySet().parallelStream().forEach(entry -> {
            docVectors.put(entry.getKey(), getVectorsOfDoc(entry.getKey()));
            classes.add(entry.getValue());
        });
    }

    private List<List<Double>> getVectorsOfDoc(File doc) {
        List<List<Double>> lists = new ArrayList<>();

        List<Double> resultVecAvg = new ArrayList<>();
        List<Double> resultVecMax = new ArrayList<>();
        List<Double> resultVecMin = new ArrayList<>();
        int vecSize = 100;

        for (int i = 0; i < vecSize; i++) {
            resultVecAvg.add(0.0);
            resultVecMax.add(0.0);
            resultVecMin.add(0.0);
        }

        String[] words = FileUtils.readWords(doc);
        for (String word : words) {
            String line = wordVectors.get(word);
            if (line != null) {
                List<Double> vec = new ArrayList<>();
                String[] tokens = line.split(" ");
                for (int i = 1; i < tokens.length; i++) {
                    vec.add(Double.parseDouble(tokens[i]));
                }

                for (int i = 0; i < vec.size(); i++) {
                    resultVecAvg.set(i, resultVecAvg.get(i) + (vec.get(i) / vecSize));
                    resultVecMax.set(i, Math.max(resultVecMax.get(i), vec.get(i)));
                    resultVecMin.set(i, Math.min(resultVecMin.get(i), vec.get(i)));
                }
            }
        }

        lists.add(resultVecAvg); lists.add(resultVecMax); lists.add(resultVecMin);

        return lists;
    }

    private void getCosineSimilarities(List<Double> givenVec, int option, Map<File, Double> distances) {
        for (Map.Entry<File, List<List<Double>>> entry : docVectors.entrySet()) {
            List<Double> vec = null;
            if (option == 1) // AVG
                vec = entry.getValue().get(0);
            else if (option == 2) // MAX
                vec = entry.getValue().get(1);
            else if (option == 3) // MIN
                vec = entry.getValue().get(2);

            distances.put(entry.getKey(), cosSimilarity(givenVec, vec));
        }
    }

    private double cosSimilarity(List<Double> vec1, List<Double> vec2) {
        double norm1 = 0.0;
        double norm2 = 0.0;
        double dotProduct = 0.0;
        for (int i = 0; i < vec1.size(); i++) {
            norm1 += Math.pow(vec1.get(i), 2);
            norm2 += Math.pow(vec2.get(i), 2);
            dotProduct += vec1.get(i) * vec2.get(i);
        }
        return dotProduct / (Math.sqrt(norm1) * Math.sqrt(norm2));
    }

    // from http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java
    private <K, V extends Comparable<? super V>> Map<K, V>
    sortByValue(Map<K, V> map, boolean reverse) {
        return map.entrySet()
                .stream()
                .sorted((reverse ?
                        Map.Entry.comparingByValue(Collections.reverseOrder()) :
                        Map.Entry.comparingByValue()))
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1,
                        LinkedHashMap::new
                ));
    }

    private int countClass(List<File> files, String c) {
        int counter = 0;
        for (File file : files) {
            if (trainingFiles.get(file).equals(c))
                ++counter;
        }
        return counter;
    }

    public Map.Entry<String, Integer> classifyKnn(File file, int k, int option) {
        List<List<Double>> vecs = getVectorsOfDoc(file);
        List<Double> vec = getProperVector(vecs, option);

        Map<File, Double> distances = new HashMap<>();

        getCosineSimilarities(vec, option, distances);
        distances = sortByValue(distances, true);

        List<File> sortedFiles = new ArrayList<>(distances.keySet());
        sortedFiles = sortedFiles.subList(0, k);
        Map<String, Integer> counts = new HashMap<>();
        for (String category : classes) {
            counts.put(category, countClass(sortedFiles, category));
        }

        ArrayList<Map.Entry<String, Integer>> resultList =
                new ArrayList(sortByValue(counts, true).entrySet());

        return resultList.get(0);
    }

    private List<Double> getProperVector(List<List<Double>> lists, int option) {
        List<Double> vec = null;
        if (option == 1) // AVG
            vec = lists.get(0);
        else if (option == 2) // MAX
            vec = lists.get(1);
        else if (option == 3) // MIN
            vec = lists.get(2);

        return vec;
    }

    public Map.Entry<String, Double> classifyRocchio(File file, int option) {
        List<List<Double>> vecs = getVectorsOfDoc(file);
        List<Double> vec = getProperVector(vecs, option);

        Map<File, Double> distances = new HashMap<>();
        getCosineSimilarities(vec, option, distances);

        distances = sortByValue(distances, true);
        List<Map.Entry<File, Double>> sortedFiles =
                new ArrayList<>(distances.entrySet());

        return new AbstractMap.SimpleEntry<>
                (trainingFiles.get(sortedFiles.get(0).getKey()),
                        sortedFiles.get(0).getValue());
    }
}

Body:
Finally I got this working. The problem was the size of the objects that I was trying to serialize and deserialize (i.e wordVectors is 480 MB).

To fix this, I used synchronized map. So

wordVectors = new HashMap<>();

is changed to

wordVectors = Collections.synchronizedMap(new HashMap<>());

I got the idea from here.


来源: stackexchange

问:
MKMapView centerCoordinate not returning proper values
In my app, I am saving coordinates from an MKMapView into a property list. After the user hits "save" I set the center coordinate of the selection view to that on the main view, and then save the mapView.centerCoodinate.latitude and longitude into a pList. However, this gives me a value like "1078114215" which the map says is not a vail coordinate. What am I doing wrong?</p>

答:
Sounds like you're accidentally mis-typing your double variable. When you add it to your dictionary to be stored as a plist be sure to transform it from a double to an NSNumber like this:

```<code>[myDictionary addObject:[NSNumber numberWithDouble:latitude] forKey:@"latitude"];
</code>```

and when you retrieve it, transform it from an NSNumber to a double:

```<code>double latitude = [[myDictionary objectForKey:@"latitude"] doubleValue];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Sounds like you're accidentally mis-typing your double variable. When you add it to your dictionary to be stored as a plist be sure to transform it from a double to an NSNumber like this:

[myDictionary addObject:[NSNumber numberWithDouble:latitude] forKey:@"latitude"];

and when you retrieve it, transform it from an NSNumber to a double:

double latitude = [[myDictionary objectForKey:@"latitude"] doubleValue];


问:
Why does this rails query behave differently depending on timezone?
I have a rails time-based query which has some odd timezone sensitive behaviour, even though as far as I know I'm using UTC. In a nutshell, these queries give different answers:

```<code>>> Model.find(:all,:conditions=>['created_at<=?',(Time.now-1.hours).gmtime]).length
=> 279
>> Model.find(:all,:conditions=>['created_at<=?',(Time.now-1.hours)]).length
=> 280
</code>```

Where the DB actually does contain one model created in the last hour, and the total number of models is 280. So only the first query is correct.

However, in environment.rb I have:

```<code>config.time_zone = 'UTC'
</code>```

The system time zone (as reported by 'date') is BST (which is GMT+1) - so somehow this winds up getting treated as UTC and breaking queries.

This is causing me all sorts of problems as I need to parameterise the query passing in different times to an action (which are then converted using Time.parse()), and even though I send in UTC times, this 'off by one hour' DST issue crops a lot. Even using '.gmtime()' doesn't always seem to fix it.

Obviously the difference is caused somehow by an implicit conversion somewhere resulting in BST being incorrectly treated as UTC, but why? Doesn't rails store the timestamps in UTC? Isn't the Time class timezone aware? I am using Rails 2.2.2

So what is going on here - and what is the safe way to program around it?

edit, some additional info to show what the DB and Time class are doing:

```<code>>> Model.find(:last).created_at
=> Tue, 11 Aug 2009 20:31:07 UTC +00:00
>> Time.now
=> Tue Aug 11 22:00:18 +0100 2009
>> Time.now.gmtime
=> Tue Aug 11 21:00:22 UTC 2009
</code>```

答:
```<code>start_date_format = DateTime.strptime(@start_date, date_format)
start_date_format_with_hour =
DateTime.strptime((start_date_format.to_i + timezone_offset*60*60).to_s,'%s').strftime(date_format)

end_date_format = DateTime.strptime(@end_date, date_format)
end_date_format_with_hour = DateTime.strptime((end_date_format.to_i + timezone_offset*60*60).to_s,'%s').strftime(date_format)

@filters_date = "invoices.created_at >= ? AND invoices.created_at < ?", start_date_format_with_hour, end_date_format_with_hour
</code>```

Body:
I have a rails time-based query which has some odd timezone sensitive behaviour, even though as far as I know I'm using UTC. In a nutshell, these queries give different answers:

>> Model.find(:all,:conditions=>['created_at<=?',(Time.now-1.hours).gmtime]).length
=> 279
>> Model.find(:all,:conditions=>['created_at<=?',(Time.now-1.hours)]).length
=> 280

Where the DB actually does contain one model created in the last hour, and the total number of models is 280. So only the first query is correct.

However, in environment.rb I have:

config.time_zone = 'UTC'

The system time zone (as reported by 'date') is BST (which is GMT+1) - so somehow this winds up getting treated as UTC and breaking queries.

This is causing me all sorts of problems as I need to parameterise the query passing in different times to an action (which are then converted using Time.parse()), and even though I send in UTC times, this 'off by one hour' DST issue crops a lot. Even using '.gmtime()' doesn't always seem to fix it.

Obviously the difference is caused somehow by an implicit conversion somewhere resulting in BST being incorrectly treated as UTC, but why? Doesn't rails store the timestamps in UTC? Isn't the Time class timezone aware? I am using Rails 2.2.2

So what is going on here - and what is the safe way to program around it?

edit, some additional info to show what the DB and Time class are doing:

>> Model.find(:last).created_at
=> Tue, 11 Aug 2009 20:31:07 UTC +00:00
>> Time.now
=> Tue Aug 11 22:00:18 +0100 2009
>> Time.now.gmtime
=> Tue Aug 11 21:00:22 UTC 2009

ContentLicense: CC BY-SA 3.0


问:
jQuery help: trying to set placeholder values for input fields
So, here's my jQuery code:

```<code> if($('#quotation_request_payment_option_lease').is(':checked')){
    $('#quotation_request_down_payment').attr('placeholder', "1300");
  }

 else if($('#quotation_request_payment_option_finance').is(':checked'))
  {
    $('#quotation_request_down_payment').attr('placeholder', "1500");
  }
</code>```

If the quotation_request_payment_option_lease checkbox is checked, then I want to set the placeholder in the quotation_request_down_payment input field to 1300.

And if the quotation_request_payment_option_finance checkbox is checked, then I want to set the placeholder in the quotation_request_down_payment input field to 1500.

Right now, the default for the page is that the quotation_request_payment_option_lease checkbox is checked, so when I load the page, the placeholder for the quoation_request_down_payment input field is set to 1300 (which is what I want).

The problem I'm having is that when I check the quotation_request_payment_option_finance checkbox (note: it's set so that only one of the two checkboxes can be checked at once), the placeholder remains 1300, it doesn't change to 1500.

Can anyone think of a way to fix this?

答:
(note: it's set so that only one of the two checkboxes can be checked
  at once)

Substitute <input type="radio"> elements for <input type="checkbox"> elements with each having name attribute set to "quotation_request_down_payment"
. Set class attribute of two <input type="text"> elements to "quotation_request_down_payment" at html instead of single element having id. Toggle the display of the <input type="text"> elements' from inline-block to none utilizing css :checked, adjacent sibling selector + and  :not().

#quotation_request_payment_option_lease:checked
+ input + input {
  display: inline-block;
}

#quotation_request_payment_option_lease:not(:checked)
+ input + input,
#quotation_request_payment_option_lease:checked
+ input + input + input {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <input type="radio"
         id="quotation_request_payment_option_lease"
         name="quotation_request_payment_option"
         value="finance" checked>
  <input type="radio"
         id="quotation_request_payment_option_finance"
         name="quotation_request_payment_option"
         value="finance">
  <input type="text"
         name="quotation_request_payment_option_lease"
         placeholder="1300"
         class="quotation_request_down_payment"
         value="1300">
  <input type="text"
         name="quotation_request_payment_option_finance"
         placeholder="1500"
         class="quotation_request_down_payment"
         value="1500">
</form></code>```

Body:
So, here's my jQuery code:

 if($('#quotation_request_payment_option_lease').is(':checked')){
    $('#quotation_request_down_payment').attr('placeholder', "1300");
  }

 else if($('#quotation_request_payment_option_finance').is(':checked'))
  {
    $('#quotation_request_down_payment').attr('placeholder', "1500");
  }

If the quotation_request_payment_option_lease checkbox is checked, then I want to set the placeholder in the quotation_request_down_payment input field to 1300.

And if the quotation_request_payment_option_finance checkbox is checked, then I want to set the placeholder in the quotation_request_down_payment input field to 1500.

Right now, the default for the page is that the quotation_request_payment_option_lease checkbox is checked, so when I load the page, the placeholder for the quoation_request_down_payment input field is set to 1300 (which is what I want).

The problem I'm having is that when I check the quotation_request_payment_option_finance checkbox (note: it's set so that only one of the two checkboxes can be checked at once), the placeholder remains 1300, it doesn't change to 1500.

Can anyone think of a way to fix this?

Body:
(note: it's set so that only one of the two checkboxes can be checked
  at once)

Substitute <input type="radio"> elements for <input type="checkbox"> elements with each having name attribute set to "quotation_request_down_payment"
. Set class attribute of two <input type="text"> elements to "quotation_request_down_payment" at html instead of single element having id. Toggle the display of the <input type="text"> elements' from inline-block to none utilizing css :checked, adjacent sibling selector + and  :not().

#quotation_request_payment_option_lease:checked
+ input + input {
  display: inline-block;
}

#quotation_request_payment_option_lease:not(:checked)
+ input + input,
#quotation_request_payment_option_lease:checked
+ input + input + input {
  display: none;
}

<form>
  <input type="radio"
         id="quotation_request_payment_option_lease"
         name="quotation_request_payment_option"
         value="finance" checked>
  <input type="radio"
         id="quotation_request_payment_option_finance"
         name="quotation_request_payment_option"
         value="finance">
  <input type="text"
         name="quotation_request_payment_option_lease"
         placeholder="1300"
         class="quotation_request_down_payment"
         value="1300">
  <input type="text"
         name="quotation_request_payment_option_finance"
         placeholder="1500"
         class="quotation_request_down_payment"
         value="1500">
</form>


问:
Comparing objects and enum class?
I have enum class, something like this:

```<code>public enum ProductCategory {
    FOOD("FOOD"),
    BEVERAGE("BEVERAGE"),
    DEFAULT("DEFAULT");

    private final String label;

    private ProductCategory(String label) {
        this.label = label;
    }

    public String getLabel() {
        return label;
    }
}
</code>```

And I want to write method that will compare two objects based on the ProductCategory. So if two objects have the same category (for example: FOOD), the method will return true.

```<code>public boolean searchFilterFunction(Object firstObject, Object secondObject) {
    if(firstObject==null || secondObject==null)
        return false;

    //code?
    return true;
}
</code>```

Enum class is in one package, and the method I want to write is in another. Can someone give me some hint?

答:
Enum constants are singletons and, in such a case, they can be conveniently tested for equality using the '==' operator (because, for singletons, value can never be separated from identity ... this is not true for ordinary object instances). For example:

```<code>if (thisEnum == ProductCategory.FOOD) System.out.println("It's a food");
</code>```

If you have a need to test arbitrary objects of any type for equality with an enum, then you don't need to re-invent the wheel.  There is already a null safe method in the convenience class Objects that will do this:

```<code>if (Objects.equals(myEnum, ProductCategory.FOOD)) System.out.println("It's a food");
</code>```

Title: Comparing objects and enum class?

Body:
I have enum class, something like this:

public enum ProductCategory {
    FOOD("FOOD"),
    BEVERAGE("BEVERAGE"),
    DEFAULT("DEFAULT");

    private final String label;

    private ProductCategory(String label) {
        this.label = label;
    }

    public String getLabel() {
        return label;
    }
}

And I want to write method that will compare two objects based on the ProductCategory. So if two objects have the same category (for example: FOOD), the method will return true.

public boolean searchFilterFunction(Object firstObject, Object secondObject) {
    if(firstObject==null || secondObject==null)
        return false;

    //code?
    return true;
}

Enum class is in one package, and the method I want to write is in another. Can someone give me some hint?

Body:
Enum constants are singletons and, in such a case, they can be conveniently tested for equality using the '==' operator (because, for singletons, value can never be separated from identity ... this is not true for ordinary object instances). For example:

if (thisEnum == ProductCategory.FOOD) System.out.println("It's a food");

If you have a need to test arbitrary objects of any type for equality with an enum, then you don't need to re-invent the wheel.  There is already a null safe method in the convenience class Objects that will do this:

if (Objects.equals(myEnum, ProductCategory.FOOD)) System.out.println("It's a food");


问:
Handling soft-deletes with Spring JPA
I have a table Stuff defined as...

```<code>id, <fields>..., active
</code>```

Active is the soft-delete flag and is always 1 or 0. Long term this may go away in favor of a historical table.

```<code>public interface StuffRepository extends JpaRepository<StuffEntity, Long> {}
</code>```

In code, we always  use active records. Is there any way to get Spring to always append an active=1 condition to queries generated for this repository? Or more ideally allow me to extend the grammar used to generate the queries?

I understand that I can create named @queues everywhere but then I lose the convenience of the generated queries. I also want to avoid polluting the interface with "active" methods.

I am using Hibernate 4.2 as my JPA implementation if that matters.

答:
Based on 易天明 answer I've created CrudRepository implementation with overriden methods for soft delete:

```<code>@NoRepositoryBean
public interface SoftDeleteCrudRepository<T extends BasicEntity, ID extends Long> extends CrudRepository<T, ID> {
  @Override
  @Transactional(readOnly = true)
  @Query("select e from #{#entityName} e where e.isActive = true")
  List<T> findAll();

  @Override
  @Transactional(readOnly = true)
  @Query("select e from #{#entityName} e where e.id in ?1 and e.isActive = true")
  Iterable<T> findAll(Iterable<ID> ids);

  @Override
  @Transactional(readOnly = true)
  @Query("select e from #{#entityName} e where e.id = ?1 and e.isActive = true")
  T findOne(ID id);

  //Look up deleted entities
  @Query("select e from #{#entityName} e where e.isActive = false")
  @Transactional(readOnly = true)
  List<T> findInactive();

  @Override
  @Transactional(readOnly = true)
  @Query("select count(e) from #{#entityName} e where e.isActive = true")
  long count();

  @Override
  @Transactional(readOnly = true)
  default boolean exists(ID id) {
      return findOne(id) != null;
  }

  @Override
  @Query("update #{#entityName} e set e.isActive=false where e.id = ?1")
  @Transactional
  @Modifying
  void delete(Long id);

  @Override
  @Transactional
  default void delete(T entity) {
      delete(entity.getId());
  }

  @Override
  @Transactional
  default void delete(Iterable<? extends T> entities) {
      entities.forEach(entitiy -> delete(entitiy.getId()));
  }

  @Override
  @Query("update #{#entityName} e set e.isActive=false")
  @Transactional
  @Modifying
  void deleteAll();
}
</code>```

It could be used with BasicEntity:

```<code>@MappedSuperclass
public abstract class BasicEntity {
  @Column(name = "is_active")
  private boolean isActive = true;

  public abstract Long getId();

  // isActive getters and setters...
}
</code>```

And final entity:

```<code>@Entity
@Table(name = "town")
public class Town extends BasicEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "town_id_seq")
    @SequenceGenerator(name = "town_id_seq", sequenceName = "town_id_seq", allocationSize = 1)
    protected Long id;

    private String name;

    // getters and setters...
}
</code>```

Title: Handling soft-deletes with Spring JPA

Body:
I have a table Stuff defined as...

id, <fields>..., active

Active is the soft-delete flag and is always 1 or 0. Long term this may go away in favor of a historical table.

public interface StuffRepository extends JpaRepository<StuffEntity, Long> {}

In code, we always  use active records. Is there any way to get Spring to always append an active=1 condition to queries generated for this repository? Or more ideally allow me to extend the grammar used to generate the queries?

I understand that I can create named @queues everywhere but then I lose the convenience of the generated queries. I also want to avoid polluting the interface with "active" methods.

I am using Hibernate 4.2 as my JPA implementation if that matters.

Body:
Based on 易天明 answer I've created CrudRepository implementation with overriden methods for soft delete:

@NoRepositoryBean
public interface SoftDeleteCrudRepository<T extends BasicEntity, ID extends Long> extends CrudRepository<T, ID> {
  @Override
  @Transactional(readOnly = true)
  @Query("select e from #{#entityName} e where e.isActive = true")
  List<T> findAll();

  @Override
  @Transactional(readOnly = true)
  @Query("select e from #{#entityName} e where e.id in ?1 and e.isActive = true")
  Iterable<T> findAll(Iterable<ID> ids);

  @Override
  @Transactional(readOnly = true)
  @Query("select e from #{#entityName} e where e.id = ?1 and e.isActive = true")
  T findOne(ID id);

  //Look up deleted entities
  @Query("select e from #{#entityName} e where e.isActive = false")
  @Transactional(readOnly = true)
  List<T> findInactive();

  @Override
  @Transactional(readOnly = true)
  @Query("select count(e) from #{#entityName} e where e.isActive = true")
  long count();

  @Override
  @Transactional(readOnly = true)
  default boolean exists(ID id) {
      return findOne(id) != null;
  }

  @Override
  @Query("update #{#entityName} e set e.isActive=false where e.id = ?1")
  @Transactional
  @Modifying
  void delete(Long id);

  @Override
  @Transactional
  default void delete(T entity) {
      delete(entity.getId());
  }

  @Override
  @Transactional
  default void delete(Iterable<? extends T> entities) {
      entities.forEach(entitiy -> delete(entitiy.getId()));
  }

  @Override
  @Query("update #{#entityName} e set e.isActive=false")
  @Transactional
  @Modifying
  void deleteAll();
}

It could be used with BasicEntity:

@MappedSuperclass
public abstract class BasicEntity {
  @Column(name = "is_active")
  private boolean isActive = true;

  public abstract Long getId();

  // isActive getters and setters...
}

And final entity:

@Entity
@Table(name = "town")
public class Town extends BasicEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "town_id_seq")
    @SequenceGenerator(name = "town_id_seq", sequenceName = "town_id_seq", allocationSize = 1)
    protected Long id;

    private String name;

    // getters and setters...
}


问:
make dep: Nothing to be done for 'depend'
I have been trying to compile the PJSIP library for an iOS project which needs SIP. Following this tutorial, I have been able to run the configure-iphone script. The next step would to run the make dep for the dependencies, but sadly it fails bcs of some error, unknown to me. I have also tried to edit the makefile, so it points directly to the file, but I still get the error, so it can find the file.

```<code>/Applications/Xcode.app/Contents/Developer/usr/bin/make -f Samples.mak depend
make[2]: Nothing to be done for `depend'.
</code>```

is the error I get.

The make file:

```<code>include ../../build.mak
include $(PJDIR)/build/common.mak

export LIBDIR := ../lib
export BINDIR := ../bin

RULES_MAK := $(PJDIR)/build/rules.mak
SAMPLES_MAK := $(PJDIR)/pjsip-apps/build/Samples.mak

###############################################################################
# Gather all flags.
#
export _CFLAGS  := $(CC_CFLAGS) $(OS_CFLAGS) $(HOST_CFLAGS) $(M_CFLAGS) \
           $(PJ_CFLAGS) $(CFLAGS) $(CC_INC)../../pjsip/include \
           $(CC_INC)../../pjlib/include \
           $(CC_INC)../../pjlib-util/include \
           $(CC_INC)../../pjnath/include \
           $(CC_INC)../../pjmedia/include
export _CXXFLAGS:= $(_CFLAGS) $(CC_CXXFLAGS) $(OS_CXXFLAGS) $(M_CXXFLAGS) \
           $(HOST_CXXFLAGS) $(CXXFLAGS)
export _LDFLAGS := $(CC_LDFLAGS) $(OS_LDFLAGS) $(M_LDFLAGS) $(HOST_LDFLAGS) \
           $(APP_LDFLAGS) $(APP_LDLIBS) $(LDFLAGS)

###############################################################################
# Defines for building PJSUA
#
export PJSUA_SRCDIR = ../src/pjsua
export PJSUA_OBJS += $(OS_OBJS) $(M_OBJS) $(CC_OBJS) $(HOST_OBJS) \
            main.o pjsua_app.o pjsua_app_cli.o pjsua_app_common.o \
            pjsua_app_config.o pjsua_app_legacy.o
export PJSUA_CFLAGS += $(PJ_CFLAGS) $(CFLAGS)
export PJSUA_CXXFLAGS += $(PJ_CXXFLAGS) $(CFLAGS)
export PJSUA_LDFLAGS += $(PJ_LDFLAGS) $(PJ_LDLIBS) $(LDFLAGS)
export PJSUA_EXE:=pjsua-$(TARGET_NAME)$(HOST_EXE)

###############################################################################
# Defines for building pjsystest
#
export PJSYSTEST_SRCDIR = ../src/pjsystest
export PJSYSTEST_OBJS += $(OS_OBJS) $(M_OBJS) $(CC_OBJS) $(HOST_OBJS) \
            systest.o main_console.o
export PJSYSTEST_CFLAGS += $(PJ_CFLAGS) $(CFLAGS)
export PJSYSTEST_CXXFLAGS += $(PJ_CXXFLAGS) $(CFLAGS)
export PJSYSTEST_LDFLAGS += $(PJ_LDFLAGS) $(PJ_LDLIBS) $(LDFLAGS)
export PJSYSTEST_EXE:=pjsystest-$(TARGET_NAME)$(HOST_EXE)

export CC_OUT CC AR RANLIB HOST_MV HOST_RM HOST_RMDIR HOST_MKDIR OBJEXT LD LDOUT

TARGETS := $(PJSUA_EXE) $(PJSYSTEST_EXE) samples

all: $(TARGETS)

swig:
    $(MAKE) -C ../src/swig

doc:

dep: depend
distclean: realclean

.PHONY: all dep depend clean realclean distclean
.PHONY: $(TARGETS)
.PHONY: $(PJSUA_EXE) $(PJSYSTEST_EXE)

pjsua: $(PJSUA_EXE)
$(PJSUA_EXE):
    $(MAKE) -f $(RULES_MAK) APP=PJSUA app=pjsua $(subst /,$(HOST_PSEP),$(BINDIR)/$@)
    @if echo "$(TARGET_NAME)" | grep -q "apple-darwin_ios$$"; then \
      for F in $(filter %$(TARGET_NAME).a,$(PJ_LIBXX_FILES)); do \
        if test -f $$F; then \
          tmp=`echo $${F##*/} | sed -e "s/\-$(TARGET_NAME)\.a/.a/"`; \
          ln -sf $$F ../src/pjsua/ios/$$tmp; \
        fi; \
      done; \
    fi;

pjsystest: $(PJSYSTEST_EXE)
$(PJSYSTEST_EXE):
    $(MAKE) -f $(RULES_MAK) APP=PJSYSTEST app=pjsystest $(subst /,$(HOST_PSEP),$(BINDIR)/$@)

samples:
    $(MAKE) -f $(SAMPLES_MAK)

.PHONY: pjsua.ko
pjsua.ko:
    $(MAKE) -f $(RULES_MAK) APP=PJSUA app=pjsua $(subst /,$(HOST_PSEP),$(LIBDIR)/$@)

clean depend realclean:
    $(MAKE) -f $(RULES_MAK) APP=PJSUA app=pjsua $@
    $(MAKE) -f $(RULES_MAK) APP=PJSYSTEST app=pjsystest $@
    #Problem happens in the next row!
    $(MAKE) -f $(SAMPLES_MAK) $@
    @if test "$@" = "depend"; then \
      echo '$(BINDIR)/$(PJSUA_EXE): $(APP_LIB_FILES)' >> .pjsua-$(TARGET_NAME).depend; \
      echo '$(BINDIR)/$(PJSYSTEST_EXE): $(APP_LIB_FILES)' >> .pjsystest-$(TARGET_NAME).depend; \
    fi
    @if echo "$(TARGET_NAME)" | grep -q "apple-darwin_ios$$"; then \
      for F in $(filter %$(TARGET_NAME).a,$(PJ_LIBXX_FILES)); do \
        tmp=`echo $${F##*/} | sed -e "s/\-$(TARGET_NAME)\.a/.a/"`; \
        rm -f ../src/pjsua/ios/$$tmp; \
      done; \
    fi;
</code>```

Like I said, I added the SAMPLES_MAK variable, but sadly it didn't help. I also found out which line is giving me the error, it's close to the end of the file $(MAKE) -f $(SAMPLES_MAK) $@.

答:
Usually this means you've accidentally (?) created a file or directory  named depend in your working directory.  So, make sees that file or directory and, since the makefile doesn't list any prerequisites of the depend target, it believe the target is up to date.

This is why generally you declare these types of helper targets to be .PHONY, but apparently that makefile doesn't do this.

Body:
I have been trying to compile the PJSIP library for an iOS project which needs SIP. Following this tutorial, I have been able to run the configure-iphone script. The next step would to run the make dep for the dependencies, but sadly it fails bcs of some error, unknown to me. I have also tried to edit the makefile, so it points directly to the file, but I still get the error, so it can find the file.

/Applications/Xcode.app/Contents/Developer/usr/bin/make -f Samples.mak depend
make[2]: Nothing to be done for `depend'.

is the error I get.

The make file:

include ../../build.mak
include $(PJDIR)/build/common.mak

export LIBDIR := ../lib
export BINDIR := ../bin

RULES_MAK := $(PJDIR)/build/rules.mak
SAMPLES_MAK := $(PJDIR)/pjsip-apps/build/Samples.mak

###############################################################################
# Gather all flags.
#
export _CFLAGS  := $(CC_CFLAGS) $(OS_CFLAGS) $(HOST_CFLAGS) $(M_CFLAGS) \
           $(PJ_CFLAGS) $(CFLAGS) $(CC_INC)../../pjsip/include \
           $(CC_INC)../../pjlib/include \
           $(CC_INC)../../pjlib-util/include \
           $(CC_INC)../../pjnath/include \
           $(CC_INC)../../pjmedia/include
export _CXXFLAGS:= $(_CFLAGS) $(CC_CXXFLAGS) $(OS_CXXFLAGS) $(M_CXXFLAGS) \
           $(HOST_CXXFLAGS) $(CXXFLAGS)
export _LDFLAGS := $(CC_LDFLAGS) $(OS_LDFLAGS) $(M_LDFLAGS) $(HOST_LDFLAGS) \
           $(APP_LDFLAGS) $(APP_LDLIBS) $(LDFLAGS)

###############################################################################
# Defines for building PJSUA
#
export PJSUA_SRCDIR = ../src/pjsua
export PJSUA_OBJS += $(OS_OBJS) $(M_OBJS) $(CC_OBJS) $(HOST_OBJS) \
            main.o pjsua_app.o pjsua_app_cli.o pjsua_app_common.o \
            pjsua_app_config.o pjsua_app_legacy.o
export PJSUA_CFLAGS += $(PJ_CFLAGS) $(CFLAGS)
export PJSUA_CXXFLAGS += $(PJ_CXXFLAGS) $(CFLAGS)
export PJSUA_LDFLAGS += $(PJ_LDFLAGS) $(PJ_LDLIBS) $(LDFLAGS)
export PJSUA_EXE:=pjsua-$(TARGET_NAME)$(HOST_EXE)

###############################################################################
# Defines for building pjsystest
#
export PJSYSTEST_SRCDIR = ../src/pjsystest
export PJSYSTEST_OBJS += $(OS_OBJS) $(M_OBJS) $(CC_OBJS) $(HOST_OBJS) \
            systest.o main_console.o
export PJSYSTEST_CFLAGS += $(PJ_CFLAGS) $(CFLAGS)
export PJSYSTEST_CXXFLAGS += $(PJ_CXXFLAGS) $(CFLAGS)
export PJSYSTEST_LDFLAGS += $(PJ_LDFLAGS) $(PJ_LDLIBS) $(LDFLAGS)
export PJSYSTEST_EXE:=pjsystest-$(TARGET_NAME)$(HOST_EXE)

export CC_OUT CC AR RANLIB HOST_MV HOST_RM HOST_RMDIR HOST_MKDIR OBJEXT LD LDOUT

TARGETS := $(PJSUA_EXE) $(PJSYSTEST_EXE) samples

all: $(TARGETS)

swig:
    $(MAKE) -C ../src/swig

doc:

dep: depend
distclean: realclean

.PHONY: all dep depend clean realclean distclean
.PHONY: $(TARGETS)
.PHONY: $(PJSUA_EXE) $(PJSYSTEST_EXE)

pjsua: $(PJSUA_EXE)
$(PJSUA_EXE):
    $(MAKE) -f $(RULES_MAK) APP=PJSUA app=pjsua $(subst /,$(HOST_PSEP),$(BINDIR)/$@)
    @if echo "$(TARGET_NAME)" | grep -q "apple-darwin_ios$$"; then \
      for F in $(filter %$(TARGET_NAME).a,$(PJ_LIBXX_FILES)); do \
        if test -f $$F; then \
          tmp=`echo $${F##*/} | sed -e "s/\-$(TARGET_NAME)\.a/.a/"`; \
          ln -sf $$F ../src/pjsua/ios/$$tmp; \
        fi; \
      done; \
    fi;

pjsystest: $(PJSYSTEST_EXE)
$(PJSYSTEST_EXE):
    $(MAKE) -f $(RULES_MAK) APP=PJSYSTEST app=pjsystest $(subst /,$(HOST_PSEP),$(BINDIR)/$@)

samples:
    $(MAKE) -f $(SAMPLES_MAK)

.PHONY: pjsua.ko
pjsua.ko:
    $(MAKE) -f $(RULES_MAK) APP=PJSUA app=pjsua $(subst /,$(HOST_PSEP),$(LIBDIR)/$@)

clean depend realclean:
    $(MAKE) -f $(RULES_MAK) APP=PJSUA app=pjsua $@
    $(MAKE) -f $(RULES_MAK) APP=PJSYSTEST app=pjsystest $@
    #Problem happens in the next row!
    $(MAKE) -f $(SAMPLES_MAK) $@
    @if test "$@" = "depend"; then \
      echo '$(BINDIR)/$(PJSUA_EXE): $(APP_LIB_FILES)' >> .pjsua-$(TARGET_NAME).depend; \
      echo '$(BINDIR)/$(PJSYSTEST_EXE): $(APP_LIB_FILES)' >> .pjsystest-$(TARGET_NAME).depend; \
    fi
    @if echo "$(TARGET_NAME)" | grep -q "apple-darwin_ios$$"; then \
      for F in $(filter %$(TARGET_NAME).a,$(PJ_LIBXX_FILES)); do \
        tmp=`echo $${F##*/} | sed -e "s/\-$(TARGET_NAME)\.a/.a/"`; \
        rm -f ../src/pjsua/ios/$$tmp; \
      done; \
    fi;

Like I said, I added the SAMPLES_MAK variable, but sadly it didn't help. I also found out which line is giving me the error, it's close to the end of the file $(MAKE) -f $(SAMPLES_MAK) $@.


问:
condition not working properly in google map javaScript for marker
I am trying to plot different markers on google maps taking data from a csv file. I am using parsecsv-0.4.3-beta to read the csv. Everything is working just fine except when I compare two fields and try to change the marker according to that. It is changing the marker but for few fields it's giving the wrong marker. I think I have made some mistake in the condition.

```<code><?php
# include parseCSV class.
require_once('../parsecsv.lib.php');
# create new parseCSV object.
$csv = new parseCSV();
# Parse '_books.csv' using automatic delimiter detection...
$csv->auto('latlang.csv');
# ...or if you know the delimiter, set the delimiter character
# if its not the default comma...
// $csv->delimiter = "\t";   # tab delimited
# ...and then use the parse() function.
// $csv->parse('_books.csv');
//print_r ($csv->data);
?>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    </style>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCWPvg5SpuPqRnY0Ldhlz2QhLgrCqnlYFM&sensor=false"></script>
<script type="text/javascript">
    var markers = <?php print json_encode($csv->data); ?>;
    window.onload = function () {
        LoadMap();
    }
    function LoadMap() {
        var mapOptions = {
            center: new google.maps.LatLng(markers[1].Latitude, markers[1].Longtitude),
            zoom: 7,
            styles: [{"stylers": [{ "saturation": -100 }]}],
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);

        //Create and open InfoWindow.
        var infoWindow = new google.maps.InfoWindow();

        for (var i = 0; i < markers.length; i++) {
            var data = markers[i];
            var myLatlng = new google.maps.LatLng(data.Latitude, data.Longtitude);
            var image1 = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
            var image2 = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
            **if (data.CL < data.DL) {
                var image = image2;
            }else {
                var image = image1;
            };**

            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: data.Station,
                icon:image,
            });
            //Attach click event to the marker.
            (function (marker, data) {
                google.maps.event.addListener(marker, "click", function (e) {
                    //Wrap the content inside an HTML DIV in order to set height and width of InfoWindow.
                    infoWindow.setContent("<div style = 'width:200px;min-height:40px'>" + "<p>" + "<b>Station:</b> " + data.Station + "<br>"+ "CL:" + data.CL + "<br>" + "<b>River Name: </b>" + data.RiverName + "<br>" + "<b>DL(mPWD): </b>" + data.DL +"<br>" + "<b>HRWL(mPWD):</b> "+ data.HRWL +"</p>"+"</div>");
                    infoWindow.open(map, marker);
                });
            })(marker, data);
        }
    }
</script>
<div id="dvMap" style="width: 900px; height: 500px">
</div>
</body>
</html>
</code>```

Here is a sample of the csv file:

In most cases it shows the right marker... some markers do not meet the condition.

答:
Please add these lines in your code:

```<code>data.CL = Number(data.CL);
data.DL = Number(data.DL);
if (data.CL < data.DL) {
    var image = image2;
}else {
    var image = image1;
};
</code>```

Your data was coming in string, but we are using < operator to check that so in some case it might fail. Better to convert and then check for greater or less.

Body:
I am trying to plot different markers on google maps taking data from a csv file. I am using parsecsv-0.4.3-beta to read the csv. Everything is working just fine except when I compare two fields and try to change the marker according to that. It is changing the marker but for few fields it's giving the wrong marker. I think I have made some mistake in the condition.

<?php
# include parseCSV class.
require_once('../parsecsv.lib.php');
# create new parseCSV object.
$csv = new parseCSV();
# Parse '_books.csv' using automatic delimiter detection...
$csv->auto('latlang.csv');
# ...or if you know the delimiter, set the delimiter character
# if its not the default comma...
// $csv->delimiter = "\t";   # tab delimited
# ...and then use the parse() function.
// $csv->parse('_books.csv');
//print_r ($csv->data);
?>

    <title></title>
    </style>

Here is a sample of the csv file:

In most cases it shows the right marker... some markers do not meet the condition.

Body:
Please add these lines in your code:

data.CL = Number(data.CL);
data.DL = Number(data.DL);
if (data.CL < data.DL) {
    var image = image2;
}else {
    var image = image1;
};

Your data was coming in string, but we are using < operator to check that so in some case it might fail. Better to convert and then check for greater or less.


问:
Load text file content using ajax
I have a HTML and CSS tab where i want to load the text content under each tab using ajax request from a .txt file. It means when we click on any tab then it loads the text content from .txt file. Content will be loaded first time a tabs get activated. First tab is already activated and text content loaded and showing under first tab but my issue is but when i click on second or third tab then it doesn't load the text content.
Code is live here: http://testweb.epizy.com/ajax-load/index.html

答:
If you set IDs of the radio buttons the same as file names, i.e. tab1, tab2 and tab3, the result JavaScript code can look like:

```<code>$(document).ready(function () {
  const SELECTOR = '[type=radio]';

  function loadData(tabId) {
    $.ajax({
      url: `${tabId}.txt`,
      dataType: "text",
      async: false,
      success: (data) => {
        $(`.${tabId}`).html(data);
      }
    });
  }

  const checkedTabId = $(`${SELECTOR}:checked`).prop('id');
  loadData(checkedTabId);

  $(SELECTOR).change(function () {
    if (this.checked) {
      loadData(this.id);
    }
  });
});
</code>```

It's just a brief example of how your code could be improved.

JSFiddle example

Title: Load text file content using ajax

Body:
If you set IDs of the radio buttons the same as file names, i.e. tab1, tab2 and tab3, the result JavaScript code can look like:

$(document).ready(function () {
  const SELECTOR = '[type=radio]';

  function loadData(tabId) {
    $.ajax({
      url: `${tabId}.txt`,
      dataType: "text",
      async: false,
      success: (data) => {
        $(`.${tabId}`).html(data);
      }
    });
  }

  const checkedTabId = $(`${SELECTOR}:checked`).prop('id');
  loadData(checkedTabId);

  $(SELECTOR).change(function () {
    if (this.checked) {
      loadData(this.id);
    }
  });
});

It's just a brief example of how your code could be improved.

JSFiddle example


问:
How I can simulate response variable from a model already fitted?
I already fitted a regression model with JAGS

```<code>model{
    for(i in 1:n) {
        y[i] ~ dbeta(alpha[i], beta[i])
        alpha[i] <- mu[i] * phi[i]
        beta[i]  <- (1 - mu[i]) * phi[i]
        log(phi[i]) <- -inprod(X2[i, ], delta[])
        cloglog(mu[i]) <- inprod(X1[i, ], B[])
    }

    for (j in 1:p){
        B[j] ~ dnorm(0, .001)
    }

    for(k in 1:s){
        delta[k] ~ dnorm(0, .001)
    }
}
</code>```

But I need to simulate 50 samples of response variable where each one have size, to do some plots. How can I do it?

I found this thread a litle help Estimating unknown response variable in JAGS - unsupervised learning

Should I run the chain again given the values of posterior estimates that I already have as inits?

答: Yes, you can do exactly as you described, as long as you first create a new dataset with 50 observations and the variables Y, X1, and X2 as described by StatnMap (viz., 50 values for both X1 and X2 and 50 NAs for Y), but you will not need to rerun your model, as implied by StatnMap.  Just to be clear: you can, but you do not need.

Body:
I already fitted a regression model with JAGS

model{
    for(i in 1:n) {
        y[i] ~ dbeta(alpha[i], beta[i])
        alpha[i] <- mu[i] * phi[i]
        beta[i]  <- (1 - mu[i]) * phi[i]
        log(phi[i]) <- -inprod(X2[i, ], delta[])
        cloglog(mu[i]) <- inprod(X1[i, ], B[])
    }

    for (j in 1:p){
        B[j] ~ dnorm(0, .001)
    }

    for(k in 1:s){
        delta[k] ~ dnorm(0, .001)
    }
}

But I need to simulate 50 samples of response variable where each one have size, to do some plots. How can I do it?

I found this thread a litle help Estimating unknown response variable in JAGS - unsupervised learning

Should I run the chain again given the values of posterior estimates that I already have as inits?


问:
How to get user Seller ID, Marketplace ID and MWS token?
I am not familiar with amazon API's. I am building web app and I want to get user Seller ID, Marketplace ID and MWS token when he/she register on my web app. On time of register he and she will redirect to this site where user can login and submit agreement and then redirect to my web site with information of Seller ID, Marketplace ID and MWS token.</p>

答: The MWS FAQ describes both how to get your own IDs and tokens, as well as the process of adding a third-party web application to your Amazon Merchant account.</p>


问:
Laravel Middleware not working in laravel 5.4
I have following code

```<code><?php

namespace App\Http\Middleware;

use Closure;
use Session;

class CheckLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(!Session::has('userAuthDetail')){
            // return redirect('login');
            // return redirect()->guest('/login');
        } else {
            return $next($request);
        }
    }
}
</code>```

in web.php

```<code>Route::get('/login', ['as' => 'login', 'uses' => 'Auth\LoginController@login']);

Route::group(['middleware' => ['login']], function () {
    Route::post('/add','MyController@submitData');
});
</code>```

Login Controller

```<code>public function postLogin(Request $request) {
     //    print_r($request->all());

     $data['email']=$request->email;
     $data['password']=$request->password;
     $response=  ApiModel::userLogin($data);
     if($response->msg=='success'){
         session(['userAuthDetail' => $response->data[0]]);
         return redirect('/');
    } else if($response->msg=='failed'){
         return redirect('/');
    }
}
</code>```

if i add if else condition in middleware then website throwing error

ErrorException in VerifyCsrfToken.php line 156: Trying to get property
  of non-object

if i remove if else and add just

```<code>public function handle($request, Closure $next)
{
   if(!Session::has('userAuthDetail')){

   }
   return $next($request);
}
</code>```

then working fine but if credentials failed then its redirecting to dashboard.

Note: i cant use laravel auth since i am communicating with the api which is written in core php

Updated;

kernal.php

```<code><?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \App\Http\Middleware\CheckLogin::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'login' => \App\Http\Middleware\CheckLogin::class,
    ];
}
</code>```

答:
Line 156 of VerifyCsrfToken.php shows that it attempts to call $response->headers->setCookie(...). Your error indicates that $response is null, and that is what would happen in your CheckLogin middleware in the if(!Session::has('userAuthDetail')) { ... } scenario.

Basically, you have a middleware that is returning null (or nothing at all, which kind-of is treated as null in the PHP world). This is not allowed, a middleware must always return a response of some kind (or throw an exception).

TL;DR: Your middleware must return a response for all execution paths.

Body:
I have following code

<?php

namespace App\Http\Middleware;

use Closure;
use Session;

class CheckLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(!Session::has('userAuthDetail')){
            // return redirect('login');
            // return redirect()->guest('/login');
        } else {
            return $next($request);
        }
    }
}

in web.php

Route::get('/login', ['as' => 'login', 'uses' => 'Auth\LoginController@login']);

Route::group(['middleware' => ['login']], function () {
    Route::post('/add','MyController@submitData');
});

Login Controller

public function postLogin(Request $request) {
     //    print_r($request->all());

     $data['email']=$request->email;
     $data['password']=$request->password;
     $response=  ApiModel::userLogin($data);
     if($response->msg=='success'){
         session(['userAuthDetail' => $response->data[0]]);
         return redirect('/');
    } else if($response->msg=='failed'){
         return redirect('/');
    }
}

if i add if else condition in middleware then website throwing error

ErrorException in VerifyCsrfToken.php line 156: Trying to get property
  of non-object

if i remove if else and add just

public function handle($request, Closure $next)
{
   if(!Session::has('userAuthDetail')){

   }
   return $next($request);
}

then working fine but if credentials failed then its redirecting to dashboard.

Note: i cant use laravel auth since i am communicating with the api which is written in core php

Updated;

kernal.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \App\Http\Middleware\CheckLogin::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'login' => \App\Http\Middleware\CheckLogin::class,
    ];
}


问:
Decoding ble hci snoop logs in Android
I am debugging an android disconnection issue and have gathered bluetooth hci snoop logs and have browsed it via wireshark tool but i am not able to understand the datapackets being shown in the logs. Is there any official /non official documentation for understanding these hci snoop logs?</p>

答: It's the Bluetooth HCI protocol. You can download the manual at https://www.bluetooth.com/specifications/adopted-specifications. Press "Core Version 5.0" to download the current version (5). If you check out Vol 2 Part E chapter 7, you will see all kind of packets. The ACL data packets depend on what kind of data it is (higher layer specification). For example GATT, you will find the documentation in Vol 3 Part G.</p>

Title: Decoding ble hci snoop logs in Android


问:
How to use python 2.7 packages in Anaconda python 2.7 environment
I am trying to have two environments in anaconda, one with python 3.4 and one with python 2.7. I already had everything working for python 3.4 and created a new environment with:

```<code>conda create -n python2 python=2.7 anaconda
</code>```

and i activated this with:

```<code>activate python2
</code>```

When i then run python, it still uses packages from C:\anaconda3\lib. Here are the standard packages for python 3.4 located (I think). This will give errors when using python 2.7. How can i make sure the python 2.7 environment uses al standard packages for python 2.7?

I tried manually copying the files to C:\Anaconda3\envs\python2\lib, but without success.

答:
From: Using Python in Windows

If you have multiple versions of Python installed (e.g., 2.7 and 3.6)
  you will have noticed that Python 3.6 was started - to launch Python
  2.7, try the command:
  py -2.7

And:

If the launcher is run with no explicit Python version specification, and a virtual environment (created with the standard library venv module or the external virtualenv tool) active, the launcher will run the virtual environment’s interpreter rather than the global one. To run the global interpreter, either deactivate the virtual environment, or explicitly specify the global Python version.

So, I think solution for you is create isolated environment using virtualenv with specific python version:

Install pip instructions are detailed here

pip install virtualenv

virtualenv venv

(venv is virtual environment name)

\path\to\env\Scripts\activate

For better instructions

Validate your python version by python -V

If version is 3.4, start your anaconda.

Body:
I am trying to have two environments in anaconda, one with python 3.4 and one with python 2.7. I already had everything working for python 3.4 and created a new environment with:

conda create -n python2 python=2.7 anaconda

and i activated this with:

activate python2

When i then run python, it still uses packages from C:\anaconda3\lib. Here are the standard packages for python 3.4 located (I think). This will give errors when using python 2.7. How can i make sure the python 2.7 environment uses al standard packages for python 2.7?

I tried manually copying the files to C:\Anaconda3\envs\python2\lib, but without success.


问:
Change code to use block RAMs
I want to implement in Verilog the following Matlab code:

```<code>symBuf = [symBuf(numFFT/2+1:end); zeros(numFFT/2,1)];
symBuf(KF+(1:KF)) = symBuf(KF+(1:KF)) + txSymb;
</code>```

It is a simple overlap and add operation.

Here is my implementation:

```<code>module overlap
#(K = 3,
FFT = 128
)
(
input signed [15:0] symbInReal      ,
input signed [15:0] symbInImag      ,
input clock                         ,
input reset                         ,
input readyIn                       ,
input validIn                       ,
input lastIn                        ,
output signed [15:0] outReal        ,
output signed [15:0] outImag        ,
output reg lastOut                  ,
output wire readyOut                ,
output reg validOut
);

reg signed [15:0] previousSymbolReal [2*FFT*K-1:0]      ;
reg signed [15:0] previousSymbolImag [2*FFT*K-1:0]      ;
reg signed [15:0] txSymbolBuffReal [K*FFT-1:0]          ;
reg signed [15:0] txSymbolBuffImag [K*FFT-1:0]          ;
reg [15:0] counter                                      ;
reg [1:0] state                                         ;
reg [3:0] nextstate                                     ;
reg [15:0] clockcount                                   ;
reg signed [15:0] outputValueReal                       ;
reg signed [15:0] outputValueImag                       ;
reg [15:0] buffcount                                    ;
reg [7:0] symboutcount                                  ;
reg [7:0] symbincount                                   ;
reg last                                                ;
reg lastvalidout                                        ;

wire lastout                                            ;

  integer i;
  initial begin
    for (i=0; i<2*FFT*K ; i = i + 1) begin
            previousSymbolReal[i] = 0;
            previousSymbolImag[i] = 0;
    end
end

always@(posedge clock) begin
    if(~reset) begin
        counter <= 0;
    end else begin
        counter <= counter +1;
        if(nextstate != state)
            counter <= 0;
    end
end

always@(*) begin
    if(~reset) begin
        nextstate = 0;
    end else begin
        nextstate = state;
        if(readyIn) begin
            case(state)
                4'd0: begin
                        if(validIn || last) begin
                            nextstate = 1;
                        end
                      end
                4'd1: begin
                          if (counter == (FFT*K-2)) begin
                            nextstate = 2;
                          end
                  end
                4'd2: begin
                            nextstate = 0;
                      end
            endcase
        end
    end
end

always@(posedge clock) begin
    if(~reset) begin
        state <= 0;
    end else begin
        if(readyIn)
            state <= nextstate;
    end
end

always@(posedge clock) begin
    if(~reset) begin
        clockcount <= 0;
        symboutcount <= 0;
        lastOut <= 0;
    end else begin
        if(readyIn) begin
            clockcount <= clockcount +1 ;
            case(state)
                4'd0: begin
                        validOut <= 0;
                        clockcount <= 0;
                        lastOut <= 0;
                      end
                4'd1: begin
                        if(~lastvalidout)
                            validOut <= 1;
                        outputValueReal <= previousSymbolReal[clockcount+ FFT/2];
                        outputValueImag <= previousSymbolImag[clockcount+ FFT/2];
                      end
                4'd2: begin
                        outputValueReal <= previousSymbolReal[clockcount + FFT/2];
                        outputValueImag <= previousSymbolImag[clockcount + FFT/2];
                        clockcount <= 0;
                        if(~lastvalidout)
                            validOut <= 1;
                        if(symboutcount == symbincount + 1 && last)
                            lastOut <= 1;
                        symboutcount <= symboutcount +1 ;
                      end
             endcase
         end
     end
 end

assign readyOut = readyIn;

 genvar M;
 generate
    for(M=0;M<K*FFT;M=M+1) begin
        always@(posedge clock) begin
            if(state==2) begin
                previousSymbolReal[M] <= previousSymbolReal[M+FFT/2];
                previousSymbolImag[M] <= previousSymbolImag[M+FFT/2];
            end
        end
    end
    for(M=K*FFT;M<2*K*FFT-FFT/2;M=M+1) begin
        always@(posedge clock) begin
            if(state==2) begin
                previousSymbolReal[M] <= previousSymbolReal[M+FFT/2]+txSymbolBuffReal[M-K*FFT];
                previousSymbolImag[M] <= previousSymbolImag[M+FFT/2]+txSymbolBuffImag[M-K*FFT];
            end
        end
    end
    for(M=2*K*FFT-FFT/2;M<2*K*FFT;M=M+1) begin
        always@(posedge clock) begin
            if(state==2) begin
                previousSymbolReal[M] <= txSymbolBuffReal[M-K*FFT];
                previousSymbolImag[M] <= txSymbolBuffImag[M-K*FFT];
            end
        end
    end
 endgenerate

 always@(posedge clock) begin
    if(~reset) begin
        buffcount <= 0;
        symbincount <= 0;
        last <= 0;
    end else begin
        if(validIn) begin
            txSymbolBuffReal[buffcount] <= symbInReal;
            txSymbolBuffImag[buffcount] <= symbInImag;
            buffcount <= buffcount +1;
            if(buffcount == K*FFT-1) begin
                symbincount <= symbincount + 1;
                buffcount <= 0;
            end
            if(lastIn)
                last <= 1;
        end
    end
 end

 always@(posedge clock) begin
    if(~reset)
        lastvalidout <= 0;
    else begin
        if(last && lastOut)
            lastvalidout <= 1;
    end
 end

 assign outReal = outputValueReal;
 assign outImag = outputValueImag;

endmodule
</code>```

The problem here is that I have 4 huge arrays which take up to 4 times what is available in my FPGA.
Hence, I want to be able to use block RAMs. However, I don't think it's possible due to the number of read and write operations performed.

Does anyone have a solution for this?

答:
However, I don't think it's possible due to the number of read and write operations performed.

Correct. At least, not without major changes to your design.

A typical block RAM element can only read or write one (or sometimes two) values per clock cycle, but your generate loops are trying to update every element in the RAM at once!

To make this operation use a block RAM, you will need to implement a state machine to update one element per clock cycle, and to sequence operations such that other states wait until the updates have completed.

If you want to accelerate this, you may be able to split the array into multiple block RAMs so that multiple values can be updated in parallel. (You will need to carefully consider which elements need to be read/written to avoid conflicts.)

Title: Change code to use block RAMs

Body:
I want to implement in Verilog the following Matlab code:

symBuf = [symBuf(numFFT/2+1:end); zeros(numFFT/2,1)];
symBuf(KF+(1:KF)) = symBuf(KF+(1:KF)) + txSymb;

It is a simple overlap and add operation.

Here is my implementation:

module overlap
#(K = 3,
FFT = 128
)
(
input signed [15:0] symbInReal      ,
input signed [15:0] symbInImag      ,
input clock                         ,
input reset                         ,
input readyIn                       ,
input validIn                       ,
input lastIn                        ,
output signed [15:0] outReal        ,
output signed [15:0] outImag        ,
output reg lastOut                  ,
output wire readyOut                ,
output reg validOut
);

reg signed [15:0] previousSymbolReal [2*FFT*K-1:0]      ;
reg signed [15:0] previousSymbolImag [2*FFT*K-1:0]      ;
reg signed [15:0] txSymbolBuffReal [K*FFT-1:0]          ;
reg signed [15:0] txSymbolBuffImag [K*FFT-1:0]          ;
reg [15:0] counter                                      ;
reg [1:0] state                                         ;
reg [3:0] nextstate                                     ;
reg [15:0] clockcount                                   ;
reg signed [15:0] outputValueReal                       ;
reg signed [15:0] outputValueImag                       ;
reg [15:0] buffcount                                    ;
reg [7:0] symboutcount                                  ;
reg [7:0] symbincount                                   ;
reg last                                                ;
reg lastvalidout                                        ;

wire lastout                                            ;

  integer i;
  initial begin
    for (i=0; i<2*FFT*K ; i = i + 1) begin
            previousSymbolReal[i] = 0;
            previousSymbolImag[i] = 0;
    end
end

always@(posedge clock) begin
    if(~reset) begin
        counter <= 0;
    end else begin
        counter <= counter +1;
        if(nextstate != state)
            counter <= 0;
    end
end

always@(*) begin
    if(~reset) begin
        nextstate = 0;
    end else begin
        nextstate = state;
        if(readyIn) begin
            case(state)
                4'd0: begin
                        if(validIn || last) begin
                            nextstate = 1;
                        end
                      end
                4'd1: begin
                          if (counter == (FFT*K-2)) begin
                            nextstate = 2;
                          end
                  end
                4'd2: begin
                            nextstate = 0;
                      end
            endcase
        end
    end
end

always@(posedge clock) begin
    if(~reset) begin
        state <= 0;
    end else begin
        if(readyIn)
            state <= nextstate;
    end
end

always@(posedge clock) begin
    if(~reset) begin
        clockcount <= 0;
        symboutcount <= 0;
        lastOut <= 0;
    end else begin
        if(readyIn) begin
            clockcount <= clockcount +1 ;
            case(state)
                4'd0: begin
                        validOut <= 0;
                        clockcount <= 0;
                        lastOut <= 0;
                      end
                4'd1: begin
                        if(~lastvalidout)
                            validOut <= 1;
                        outputValueReal <= previousSymbolReal[clockcount+ FFT/2];
                        outputValueImag <= previousSymbolImag[clockcount+ FFT/2];
                      end
                4'd2: begin
                        outputValueReal <= previousSymbolReal[clockcount + FFT/2];
                        outputValueImag <= previousSymbolImag[clockcount + FFT/2];
                        clockcount <= 0;
                        if(~lastvalidout)
                            validOut <= 1;
                        if(symboutcount == symbincount + 1 && last)
                            lastOut <= 1;
                        symboutcount <= symboutcount +1 ;
                      end
             endcase
         end
     end
 end

assign readyOut = readyIn;

 genvar M;
 generate
    for(M=0;M<K*FFT;M=M+1) begin
        always@(posedge clock) begin
            if(state==2) begin
                previousSymbolReal[M] <= previousSymbolReal[M+FFT/2];
                previousSymbolImag[M] <= previousSymbolImag[M+FFT/2];
            end
        end
    end
    for(M=K*FFT;M<2*K*FFT-FFT/2;M=M+1) begin
        always@(posedge clock) begin
            if(state==2) begin
                previousSymbolReal[M] <= previousSymbolReal[M+FFT/2]+txSymbolBuffReal[M-K*FFT];
                previousSymbolImag[M] <= previousSymbolImag[M+FFT/2]+txSymbolBuffImag[M-K*FFT];
            end
        end
    end
    for(M=2*K*FFT-FFT/2;M<2*K*FFT;M=M+1) begin
        always@(posedge clock) begin
            if(state==2) begin
                previousSymbolReal[M] <= txSymbolBuffReal[M-K*FFT];
                previousSymbolImag[M] <= txSymbolBuffImag[M-K*FFT];
            end
        end
    end
 endgenerate

 always@(posedge clock) begin
    if(~reset) begin
        buffcount <= 0;
        symbincount <= 0;
        last <= 0;
    end else begin
        if(validIn) begin
            txSymbolBuffReal[buffcount] <= symbInReal;
            txSymbolBuffImag[buffcount] <= symbInImag;
            buffcount <= buffcount +1;
            if(buffcount == K*FFT-1) begin
                symbincount <= symbincount + 1;
                buffcount <= 0;
            end
            if(lastIn)
                last <= 1;
        end
    end
 end

 always@(posedge clock) begin
    if(~reset)
        lastvalidout <= 0;
    else begin
        if(last && lastOut)
            lastvalidout <= 1;
    end
 end

 assign outReal = outputValueReal;
 assign outImag = outputValueImag;

endmodule

The problem here is that I have 4 huge arrays which take up to 4 times what is available in my FPGA.
Hence, I want to be able to use block RAMs. However, I don't think it's possible due to the number of read and write operations performed.

Does anyone have a solution for this?


问:
Aligning elements left and center with flexbox
I'm using flexbox to align my child elements. What I'd like to do is center one element and leave the other aligned to the very left. Normally I would just set the left element using margin-right: auto. The problem is that pushes the center element off center. Is this possible without using absolute positioning?

HTML & CSS

#parent {
  align-items: center;
  border: 1px solid black;
  display: flex;
  justify-content: center;
  margin: 0 auto;
  width: 500px;
}
#left {
  margin-right: auto;
}
#center {
  margin: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="parent">
  <span id="left">Left</span>
  <span id="center">Center</span>
</div></code>```

答:
Add third empty element:

Left

Center

```

<p>And the following style:</p>

<pre class="lang-css prettyprint-override"><code>.parent {
  display: flex;
}
.left, .right {
  flex: 1;
}
</code>```

Only left and right are set to grow and thanks to the facts that...

there are only two growing elements (doesn't matter if empty) and

that both get same widths (they'll evenly distribute the available space)

...center element will always be perfectly centered.

This is much better than accepted answer in my opinion because you do not have to copy left content to right and hide it to get same width for both sides, it just magically happens (flexbox is magical).

In action:

.parent {
  display: flex;
}

.left,
.right {
  flex: 1;
}

/* Styles for demonstration */
.parent {
  padding: 5px;
  border: 2px solid #000;
}
.left,
.right {
  padding: 3px;
  border: 2px solid red;
}
.center {
  margin: 0 3px;
  padding: 3px;
  border: 2px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="left">Left</div>
  <div class="center">Center</div>
  <div class="right"></div>
</div></code>```

Body:
I'm using flexbox to align my child elements. What I'd like to do is center one element and leave the other aligned to the very left. Normally I would just set the left element using margin-right: auto. The problem is that pushes the center element off center. Is this possible without using absolute positioning?

HTML & CSS

#parent {
  align-items: center;
  border: 1px solid black;
  display: flex;
  justify-content: center;
  margin: 0 auto;
  width: 500px;
}
#left {
  margin-right: auto;
}
#center {
  margin: auto;
}

  Left
  Center

Body:
Add third empty element:

<div class="parent">
  <div class="left">Left</div>
  <div class="center">Center</div>
  <div class="right"></div>
</div>

And the following style:

.parent {
  display: flex;
}
.left, .right {
  flex: 1;
}

Only left and right are set to grow and thanks to the facts that...

there are only two growing elements (doesn't matter if empty) and

that both get same widths (they'll evenly distribute the available space)

...center element will always be perfectly centered.

This is much better than accepted answer in my opinion because you do not have to copy left content to right and hide it to get same width for both sides, it just magically happens (flexbox is magical).

In action:

.parent {
  display: flex;
}

.left,
.right {
  flex: 1;
}

/* Styles for demonstration */
.parent {
  padding: 5px;
  border: 2px solid #000;
}
.left,
.right {
  padding: 3px;
  border: 2px solid red;
}
.center {
  margin: 0 3px;
  padding: 3px;
  border: 2px solid blue;
}

<div class="parent">
  <div class="left">Left</div>
  <div class="center">Center</div>
  <div class="right"></div>
</div>


问:
Rails where() and timezones
I am attempting to find 'entries' create today (in my current timezone) using the following:

```<code>Entry.where("DATE(created_at) = DATE(?) AND email = ?", Time.now, email)
</code>```

Time.now is giving me the time in the current zone, but the query seems like it is searching against the UTC time of each entry's created_at column.

Any ideas how I can find entries created today in the server's timezone?

答:
First, you should get timezone then timezone offset.
For example current_time_zone is

America/Los_Angeles

Time zone offset find :

```<code> Time.now.in_time_zone(current_time_zone).utc_offset / 3600) * -1
</code>```

7

In contoller :

```<code> start_date_format = DateTime.strptime(@start_date, date_format)
 start_date_format_with_hour =
 DateTime.strptime((start_date_format.to_i + timezone_offset*60*60).to_s,'%s').strftime(date_format)

 end_date_format = DateTime.strptime(@end_date, date_format)
 end_date_format_with_hour = DateTime.strptime((end_date_format.to_i + timezone_offset*60*60).to_s,'%s').strftime(date_format)

 @filters_date = "invoices.created_at >= ? AND invoices.created_at < ?", start_date_format_with_hour, end_date_format_with_hour
</code>```

Title: Rails where() and timezones

Body:
I am attempting to find 'entries' create today (in my current timezone) using the following:

Entry.where("DATE(created_at) = DATE(?) AND email = ?", Time.now, email)

Time.now is giving me the time in the current zone, but the query seems like it is searching against the UTC time of each entry's created_at column.

Any ideas how I can find entries created today in the server's timezone?

Body:
First, you should get timezone then timezone offset.
For example current_time_zone is

America/Los_Angeles

Time zone offset find :

 Time.now.in_time_zone(current_time_zone).utc_offset / 3600) * -1

7

In contoller :

 start_date_format = DateTime.strptime(@start_date, date_format)
 start_date_format_with_hour =
 DateTime.strptime((start_date_format.to_i + timezone_offset*60*60).to_s,'%s').strftime(date_format)

 end_date_format = DateTime.strptime(@end_date, date_format)
 end_date_format_with_hour = DateTime.strptime((end_date_format.to_i + timezone_offset*60*60).to_s,'%s').strftime(date_format)

 @filters_date = "invoices.created_at >= ? AND invoices.created_at < ?", start_date_format_with_hour, end_date_format_with_hour


问:
wpf user control blocking styles
I am making a wpf class library with some user controls in it.  Some of my controls are not styled and so whatever style is defined in the app that hosts my control is applied to my controls.  This creates a bad mix of looks.

I need my user control to specify that all controls need to use just the default wpf look and feel regardless of what the parent form is doing.

答: try style="{x:null}"</p>

Title: wpf user control blocking styles

Body: try style="{x:null}"


问:
AngularJS: get previous state using $transition.onSuccess
I am a newbie of angularjs using angularjs1.6.4 version with angular-ui-router version 1.0.3. I have seen a lot of posts getting previous state by using $stateChangeSuccess but this event is deprecated above ui-router version 1.0.0 (reference from here) so for that i have to use $transitions.onSuccess but i don't get it how to get previous state. So far i have written this and its displaying message "stateChange success" when state change. But i need some example to proceed further.

App.js:

```<code>.run(function ($transitions) {
    $transitions.onSuccess({}, function () {
        console.log("statechange success");
    });
</code>```

答:
This is what i want. An example for going back to a previous state with a refresh using $transitions.onSuccess instead of $stateChangeSuccess</p>

```<code>.run(function ($transitions, $state) {
    var previousState;
    var previousStateParameters;
    $transitions.onSuccess({}, function (transition) {
        previousState = transition.from().name;
        previousStateParameters = transition.params('from');
    });
    $transitions.back = function () {
        $state.go(previousState, previousStateParameters, { reload: true });
    }
});
</code>```

Body:
I am a newbie of angularjs using angularjs1.6.4 version with angular-ui-router version 1.0.3. I have seen a lot of posts getting previous state by using $stateChangeSuccess but this event is deprecated above ui-router version 1.0.0 (reference from here) so for that i have to use $transitions.onSuccess but i don't get it how to get previous state. So far i have written this and its displaying message "stateChange success" when state change. But i need some example to proceed further.

App.js:

.run(function ($transitions) {
    $transitions.onSuccess({}, function () {
        console.log("statechange success");
    });

Body:
This is what i want. An example for going back to a previous state with a refresh using $transitions.onSuccess instead of $stateChangeSuccess

.run(function ($transitions, $state) {
    var previousState;
    var previousStateParameters;
    $transitions.onSuccess({}, function (transition) {
        previousState = transition.from().name;
        previousStateParameters = transition.params('from');
    });
    $transitions.back = function () {
        $state.go(previousState, previousStateParameters, { reload: true });
    }
});


问:
How do I take the squared difference of two Keras tensors?
I have a Keras Model which calculates two tensors, r1 and r2 of the same shape. I would like to have the model calculate (r1 - r2)**2.

I can take the sum of these tensors with keras.layers.add(r1, r2). I can take a product with keras.layers.multiply(r1, r2). If there was a subtract function, I'd write

```<code>r = keras.layers.subtract(r1, r2)
square_diff = keras.layers.multiply(r, r)
</code>```

but there doesn't appear to be a keras.layers.subtract function.

In lieu of that I've been trying to figure out how to multiply one of my inputs by a constant -1 tensor and then adding, but I can't figure out how to create that -1 tensor. I've tried a number of variants on

```<code>negative_one = keras.backend.constant(np.full(r1.get_shape()), -1)
</code>```

none of which work. Presumably because the dimensionality of r1 is (?, 128) (i.e. the first dimension is a batch size, and the second represents 128 hidden elements.)

What is the correct way in Keras to take the difference of two tensors?

答:
As dhinckley mentioned, you should use Lambda layer. But I would suggest to define your custom function first. With this code will a little bit more clear:</p>

```<code>import keras.backend as K
from keras.layers import Lambda

def squared_differences(pair_of_tensors):
    x, y = pair_of_tensors
    return K.square(x - y)

square_diff = Lambda(squared_differences)([r1, r2])
</code>```

Body:
I have a Keras Model which calculates two tensors, r1 and r2 of the same shape. I would like to have the model calculate (r1 - r2)**2.

I can take the sum of these tensors with keras.layers.add(r1, r2). I can take a product with keras.layers.multiply(r1, r2). If there was a subtract function, I'd write

r = keras.layers.subtract(r1, r2)
square_diff = keras.layers.multiply(r, r)

but there doesn't appear to be a keras.layers.subtract function.

In lieu of that I've been trying to figure out how to multiply one of my inputs by a constant -1 tensor and then adding, but I can't figure out how to create that -1 tensor. I've tried a number of variants on

negative_one = keras.backend.constant(np.full(r1.get_shape()), -1)

none of which work. Presumably because the dimensionality of r1 is (?, 128) (i.e. the first dimension is a batch size, and the second represents 128 hidden elements.)

What is the correct way in Keras to take the difference of two tensors?

Body:
As dhinckley mentioned, you should use Lambda layer. But I would suggest to define your custom function first. With this code will a little bit more clear:

import keras.backend as K
from keras.layers import Lambda

def squared_differences(pair_of_tensors):
    x, y = pair_of_tensors
    return K.square(x - y)

square_diff = Lambda(squared_differences)([r1, r2])