Logrotate Not Deleting Compressed Logs

Question: I have a CentOS box running rsyslog and logrotate as my syslog server for a whole bunch of network devices.  I've been toying around with this for a while, the logrotate/compression piece is working ok, but I can't seem to get it to delete the old compressed .gz logs.  Here's the basic setup:
Logs are stored in: /var/log/syslog and each host creates a new sub-folder based on its IP address or hostname.  I have two particular hosts that are really chatty, so I have specific rules for them to truncate after 5 GB.  The idea is to compress and start a new log every day, and keep 60 days' worth of logs.
Here are my configs (most of these were not created by me, but I have maintained and modified several of them):

cat /etc/cron.hourly/logrotate

<code>#!/bin/sh`enter code here`
/usr/sbin/logrotate -s /var/lib/logrotate/logrotate.status /etc/logrotate.conf
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
    /usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi
exit 0
</code>

cat /etc/logrotate.d/syslog

<code>/var/log/cron
/var/log/maillog
/var/log/messages
/var/log/secure
/var/log/spooler
{
    compress
    daily
    #delaycompress
    dateext
    missingok
    rotate 60
    maxage 60
    sharedscripts
    postrotate
        /bin/kill -HUP `cat /var/run/syslogd.pid 2> /dev/null` 2> /dev/null || true
    endscript
}
</code>

cat /etc/logrotate.conf

<code>/var/log/syslog/*/*.log {
daily
rotate 60
maxage 60
compress
}

daily
rotate 60
create
dateext
compress
include /etc/logrotate.d

/var/log/wtmp {
    monthly
    create 0664 root utmp
        minsize 1M
    rotate 1
}

/var/log/btmp {
    missingok
    monthly
    create 0600 root utmp
    rotate 1
}

# system-specific logs may be also be configured here.
# Specific rule for HOST_A
/var/log/syslog/HOST_A/*.log {
daily
size 5G
rotate 30
maxage 30
compress
}

# Specific rule for HOST_B
/var/log/syslog/HOST_B/*.log {
daily
size 5G
rotate 30
maxage 30
compress
}
</code>
And here is an example of what I have in my \var\log\syslog\host_a folder:

ls /var/log/syslog/HOST_A/ | wc -l

<code>104
</code>

ls /var/log/syslog/HOST_A/ -lh

<code>-rw------- 1 root root  416M Jun 20 23:59 HOST_A_2018_06_20.log.1.gz
-rw------- 1 root root   64M Jun 20 16:18 HOST_A_2018_06_20.log.2.gz
-rw------- 1 root root  1.5G Jun 21 23:59 HOST_A_2018_06_21.log.1.gz
<many files redacted>
-rw------- 1 root root  1.6G Sep  4 23:59 HOST_A_2018_09_04.log.1.gz
-rw------- 1 root root  1.5G Sep  5 23:59 HOST_A_2018_09_05.log.1.gz
-rw------- 1 root root  7.7G Sep  6 10:58 HOST_A_2018_09_06.log
</code>
So, you can see above, it's not removing the old archived .gz logs after 60 days.  It's keeping them indefinitely.  I've had to go in periodically and manually delete older files to keep size down.  These files go from 6/20 to 9/6 (today), which is 104 days. I'm sure I have it misconfigured, but not sure quite what I'm missing.  Any help would be appreciated.
Comment: You might want to investigate the output of `logrotate -d /etc/logrotate.conf`.
Comment: Thanks, I actually have run that, and on every folder in my syslog folder, it basically says "log does not need rotating" because it hasn't been 1 day yet.
Answer: You're using two mechanisms for daiy logfiles, and they're not cooperating with each other.
On the one hand you let syslog generate daily files, on the other hand you let logrotate rotate files. Logrotate will treat each daily file as a separate unique set of files (it doesn't consider HOST_A_2018_09_05.log to be related to HOST_A_2018_09_06.log) to rotate, so it never gets to five files files per pattern.
It's better to either not include the date in the filename, or let syslog do its own pruning of old files.
Comment: I changed my /etc/rsyslog.conf file to no longer add dates.  I changed it to: $template RemoteHost,"/var/log/syslog/%HOSTNAME%/%HOSTNAME%.log"
 Then I went into my /etc/logrotate.conf and added parameters to add the date to my rotated log files, like this: dateext, dateyesterday, dateformat-%Y-%m-%d.  That seems to be working pretty well.  I'm still waiting for the 45 day mark for some of my older logs to start getting pruned.
Comment: Thanks for the insight.  I was wondering if that was might be the case.  So, the filename essentially has to be the same, with a numerical iteration, (e.g *.1.log, *.2.log, etc.)?  I want to be able to keep compressing them .gz files, so they don't take up so much space.  And keeping the dates in the names is also useful when looking back through the logs.  It seems like there should be a way to do that and have logrotate prune the old ones and still compress and rename the files.  Should I try to find a way in rsyslog to prune them? Create a cron.daily job to delete files older 60 days?
Comment: If you want to use logrotate, the file generated by syslog has to have the same name. Logrotate can append dates to filenames it rotates. So you log to HOST_A.log and when rotating, logrotate can compress and rename it to HOST_A.20180906.log.gz, see the dateext and datefmt parameters for logrotate.
Comment: This is the section in my /etc/rsyslog.conf file that writes the files:
$template RemoteHost,"/var/log/syslog/%HOSTNAME%/%HOSTNAME%_%$YEAR%_%$MONTH%_%$DAY%.log"

So, I could change that, then add the dateext and datefmt options to the logrotate settings to fix the problem?

Logrotate Not Deleting Compressed Logs


Is it possible to store a JavaScript function that returns a string in a php variable?

Question: something like :
<?php
   $phpVar = "";
?>

is that even possible? if no, is there a way to do same thing?
If Ajax is the only solution, how do I retrieve a value of an input and store it as a php variable?
I tried something like this and it doesn't work.
<input type=text value="hello" id="myInput">
<?php
    $phpVar = "";
?>

Comment: No! Remember javascript runs in the browser and PHP runs on the server. But you should lookup AJAX
Answer: you can store this string in variable. for php interpreter it will be just a text string, nothing else. but when browser receives this data, string will be recognized as js function.

UPDATE
in this case easiest way for send data from browser to server is use a form. there is many examples in the web how to do it.
Answer: PHP runs at server side and JS in the browser (apart node and related technologies).
Only way you can do something similar would be do to render from PHP in your HTML a tag  and add you JS function and executing it there.
Al thought I would definitely not suggest it.


ArrayIndexOutOfBoundsException inserting JTable data to SQL database

Question: I have made a project on railway management system and want to insert values from text fields and Java table to MySQL database. How can I get rid of this error? Please help!!
int rows = jTable1.getRowCount();
for(int row = 0; row<rows ; row++){
    int index=1;
    String S_No = (String) jTable1.getValueAt(row, 1);
    String Name = (String) jTable1.getValueAt(row, 2);
    String Age = (String) jTable1.getValueAt(row, 3);
    String Gender = (String) jTable1.getValueAt(row, 4);
    String berth_preference = (String) jTable1.getValueAt(row, 5);
    String Quota = (String) jTable1.getValueAt(row, 6);
    String tno =(String) cb1.getSelectedItem();
    String tname =(String) cb2.getSelectedItem();
    String clas =(String) cb3.getSelectedItem();
    String tic= tick.getText();
    String frms=frm.getText();
    String tos=to.getText();
    String boarding=bp.getText();
    String reser=ru.getText();
    String jdate=date.getText();
    String pnr=l1.getText();

    try{
        Class.forName("java.sql.Driver");
        con=DriverManager.getConnection("jdbc:mysql://localhost/railway","root","ridhi");
        st =con.prepareStatement("INSERT INTO pnr(pnr_no,Train_Number,Train_Name,From_m,T_o,Date,Class,Reserved_Upto,Boarding_Pt,no_tickets,S_No,Name,Age,Gender,berth_preference,Quota) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

        st.setString(1, S_No);
        st.setString(2, Name);
        st.setString(3, Age);
        st.setString(4, Gender);
        st.setString(5, berth_preference);
        st.setString(6, Quota);

        st.executeUpdate();
        index++;

        this.setVisible(true);
        new payment().setVisible(true);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null,e.getMessage());

    }
}

Error:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 6 >= 6
at java.util.Vector.elementAt(Vector.java:427)
at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277)
at javax.swing.JTable.convertColumnIndexToModel(JTable.java:2553)
at javax.swing.JTable.getValueAt(JTable.java:2695)
at reservation.reservationActionPerformed(reservation.java:341)
at reservation.access$100(reservation.java:21)
at reservation$2.actionPerformed(reservation.java:245)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6216)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5981)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4583)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4413)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4556)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4220)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4150)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2475)
at java.awt.Component.dispatchEvent(Component.java:4413)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

And now I am getting a new error:
java.sql.SQLException: Parameter index out of range (0 < 1 ).
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3283)
at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3272)
at com.mysql.jdbc.PreparedStatement.setString(PreparedStatement.java:4108)
at reservation.reservationActionPerformed(reservation.java:358)
at reservation.access$100(reservation.java:21)
at reservation$2.actionPerformed(reservation.java:245)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6216)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5981)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4583)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4413)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4556)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4220)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4150)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2475)
at java.awt.Component.dispatchEvent(Component.java:4413)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

Answer: change this to this jtable columns are zero index based.if you have 6 columns of jtable then max column index is 5 not 6 .error is because of this but care about row index 2 if you want to get first row then getValueAt(0, n); not getValueAt(1, n);
String S_No = (String) jTable1.getValueAt(row, 0);
String Name = (String) jTable1.getValueAt(row, 1);
String Age = (String) jTable1.getValueAt(row, 2);
String Gender = (String) jTable1.getValueAt(row, 3);
String berth_preference = (String) jTable1.getValueAt(row, 4);
String Quota = (String) jTable1.getValueAt(row, 5);// 5 not 6

you should have same column count in prepared statement also .
 st =con.prepareStatement("INSERT INTO pnr(pnr_no,Train_Number,Train_Name,From_m,T_o,Date,Class,Reserved_Upto,Boarding_Pt,no_tickets,S_No,Name,Age,Gender,berth_preference,Quota) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

...........................................................................................
 st.setString(1, S_No);
 st.setString(2, Name);
 st.setString(3, Age);
 st.setString(4, Gender);
 st.setString(5, berth_preference);
 st.setString(6, Quota);

you should have like, you have missed column phone number train number
 st.setString(1, pnr);
 st.setString(2, tno );

Comment: @ridhi after you change 6 to 5,can you post the new  error msg .also you can change `JOptionPane.showMessageDialog(null,e.getMessage());` to `e.printStackTrace();` to avoid popup
Comment: @ridhi if your mysql table have 10 columns then your prepared also should 10 prepared statement should have .in your code there is only 6 `st.setString()` you should add all columns like that where is setString or int for phone number ?train number
Comment: @ridhi yes of couse .but corresponding value to `st =con.prepareStatement("INSERT INTO pnr(pnr_no,Train_Number,Train_Name,From_m,T_o,Date,Class,Reserved_Upto,Boarding_Pt,no_tickets,S_No,Name,Age,Gender,berth_preference,Quota) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");`

st.setString(1,x) , x should be value of  pnr_no which is pnr
st.setString(2,x) , x should be value of  pTrain_Number which is tno
Comment: @ridhi  it's `st.setString(1,x)` because it's not jtable it's for prepared statement it's start with index 1
Comment: @ridhi yes sorry 6 columns mean column 0,1,2,3,4,5 not 1,2,3,4,5,6
Comment: @ridhi in which line ? how much rows exist in your jtable?can you show your jtable ?
Comment: S_no | name | age | gender |   Berth_preference |  quota
Comment: its not showing the line... when I click submit button the  error is shown   in  message dialog box.
Comment: S_no | name | age | gender |   Berth_preference |  quota
these are the columns of my jtable. n it has 6 rows but there's no restriction that all the rows should be filled .depends on the user how many tickets he wants to book.
Comment: I did change 6to 5 .after that only this error : parameter index out of range 0<1. pops up
Comment: @ridhi the new error is not came from jtable it came from sql .check columns of your mysql table
Comment: |pnr_no |(NO >PRI >NULL  >auto_increment )

|Train_Number
Train_Name
| Fro_m
| T_o
| Date
| Class
| Reserved_Upto
| Boarding_Pt
| no_tickets
| S_No
| Name
| Age
| Gender
| berth_preference
| Quota
Comment: u mean I should add prepared statement also for the columns I am inserting values through combo box and text feild
Comment: I wish I could post the screenshot here. it would have been lot more easier .
Comment: ohh I thought these int values areonly for values from jtable... one more thing here st.setString(0,x); or st.setString(1,x).
Answer: When ArrayIndexOutOfBoundsException is shown: If we request for an index that is either negative, or greater than or equal to the size of the array, an ArrayIndexOutOfBoundsException is thrown.
In your case, java.lang.ArrayIndexOutOfBoundsException: 6 >= 6.


How to have custom view template in add-on in CS-Cart?

Question: I simply want to replace the default view views/products/components/products_search_form.tpl with my own one. I could just replace it directly in the file structure but I want to do this via an add-on.
I've placed my customised template in: addon/my-addon/views/products/components/products_search_form.tpl but obviously that is not enough.
I've looked at the CS-Cart tutorials but none of them seem to quite relate to this case e.g. they are about hook templates or templates in blocks.
Thanks.
Update:
I found this documentation (for 4.0): http://docs.cs-cart.com/4.0.x/addons/hooking/tpl_hooks.html which says i can achieve this by placing a template with the same name under /overrides - matching the same file path as  the one I want to replace. However; this does not work. (I am on 4.3.10 but I doubt this is the problem).
Answer: OK. The answer was as above - and remember to clear the cache by appending: &ctpl&cc to the request.


Promise is skipping XMLHttpRequest

Question: I'm trying to do XMLHttpRequest with Promise.all
like this way
        Promise.all(image.map(imageUpload => {
            let xhr = new XMLHttpRequest()
            xhr.open('POST', MY_REQUEST_URL)
            xhr.onload = () => {
              alert('imageUpload.name')
            }
            xhr.onerror = (err) => {
               alert('error')
            }
            let formdata = new FormData();
            formdata.append('file', {uri: imageUpload.path, type: 'image/png', name: 'image.png'});
            xhr.send(formdata)
        })).then(async s => {
               alert('done')
        })

but the problem is Promise.all is not waiting until the xhr request finish, it just sends a request and alert, thats it!
any ideas?
Comment: because you're not returning a Promise in the map callback - easiest solution is to use fetch ... which returns a Promise - also the `async` in `.then(async s => ` is redundant as you're not using `await`
Comment: @JaromandaX sorry i didn't understand what u mean
Comment: Promise.all waits for an array of Promises to resolve ... where are the Promises? your .map callback doesn't even return anything, let alone a Promise
Comment: @JaromandaX so how can i solve that?
Comment: @JaromandaX actually its not redundant im using await but i did remove lines form the code cause its private API
Comment: Related: [Promise.all is returning an array of undefined and resolves before being done](/q/34813147/4642212), which is about forgetting to return a Promise in the `map` callback. Though in this case, there is nothing that _could_ be returned for `Promise.all` to work with.
Answer: Your callback to .map doesn't return anything - but it needs to return a Promise to work with Promise.all
Promise.all(image.map(imageUpload => new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    xhr.open('POST', MY_REQUEST_URL);
    xhr.addEventListener('load', resolve);
    xhr.addEventListener('error', reject);

    // if you must alert in a loop of XHR's add these
    // I've made this code separate because I think it's a terrible idea™
    xhr.addEventListener('load', () => alert('imageUpload.name'));
    xhr.addEventListener('error', () => alert('error'));

    let formdata = new FormData();
    formdata.append('file', {uri: imageUpload.path, type: 'image/png', name: 'image.png'});
    xhr.send(formdata);
}))).then(async s => {
    alert('done')
});

however, modern technique is to use fetch which is already a Promise based native API
Promise.all(image.map(imageUpload => {
    let formdata = new FormData();
    formdata.append('file', {uri: imageUpload.path, type: 'image/png', name: 'image.png'});
    return fetch(MY_REQUEST_URL, {
        method: "POST",
        body: formdata
    })
    // probably don't need this line, since you don't actually care about the response
    .then(response => response.text())
    // and if you must alert during a loop of asynchronous code ...
    // though I think it's a terrible idea™
    .then(() => alert('imageUpload.name'))
    .catch(err => {
        alert('error');
        throw err; // without this, the rest of the code thinks you've succeeded when you've failed
    });
})).then(async s => {
    alert('done');
})

Comment: resolve() => {
              alert('imageUpload.name')
    }
Comment: huh? why the heck do you want to alert inside an asynchronous function? I've edited the code to do as you think is wise
Comment: I've changed the code a bit to add your *alert*s even though they are very poor coding style™ especially with asynchronous code like this
Comment: thank you so much, actually i don't need the alerts i dont use them but they are just placeholders instead of axios.get and redux dispatches, actually i care about the response should i changed     .then(() => alert('imageUpload.name'))
to     .then((response) => console.log(response)) is that okay?
Comment: do whatever you need ... with fetch you'll need to process the response using response.text() (a promise) or something else depending on what the server is sending you - plenty of documentation for fetch on MDN

Promise is skipping XMLHttpRequest


For the time field of a table, how do I determine that it is continuous?

Question: with PLSQL,I have a table with a large amount of data,One of the fields is time, which is continuous, for example
time
2022/1/1
2022/1/2
2022/1/3
2022/1/4
.....
2023/1/1
2023/1/2
2023/1/3
.....

When the amount of data is large, how can I quickly find the time data that generated the breakpoint
for example
2023/2/1
2023/2/4

2023/2/2 2023/2/3  These two data are missing data how can i find them quickly?
I thought of two methods. The first one is visual inspection. The small amount of data is okay, but the large amount of data is too prone to errors.
The second one is to process the time field, intercept the year and month for grouping, and then check the data of each month. whether the number of days is the same
time    count
2022/1   31
2022/2   28
...

But I don't think the two methods are very good. I don't know if there is a better way. If you can help me, I will be very grateful
Answer: you can do it as follows

Create a table which will store continuous dates.
LEFT Outer Join this table on the date column with the date column of your table which you are checking the date.

-- untested
Create table dt_master as
SELECT TRUNC (SYSDATE - ROWNUM) chk_dt
  FROM DUAL CONNECT BY ROWNUM < 1000;

SELECT * FROM dt_master dm
LEFT OUTER JOIN CHK_DATE ON dm.chk_dt on chk_date.date_col = dm.chk_dt
WHERE  dm.chk_dt is  NULL;

Comment: Analytics like `LEAD` and `LAG` that others have suggested will show you that there is a gap, but this is the best way to see what the value of the gap is, especially if it can be larger than a single entry.
Answer: You can also use analytic function LEAD(): a hole is when the LEAD(time) <> time + 1, assuming your time column is a DATE without hours, if not you may need to CAST/CONVERT and TRUNC.
You can also use classical holes detection with MATCH_RECOGNIZE if you want a report of the [start;end] of the missing ranges.
Answer: Use LAG or LEAD:
SELECT *
  FROM (SELECT timecol,
               LAG(timecol) OVER (ORDER BY timecol) prev_timecol
          FROM table)
 WHERE timecol > prev_timecol + 1

For the time field of a table, how do I determine that it is continuous？


Inserting element into QSet class

Question: I have following class:
class UnionFuzzySet : public FuzzySet
{
public:
    UnionFuzzySet();
    void addActivatedFuzzySet(const ActivatedFuzzySet &set);
    double getValue(double value);

private:
    QSet<ActivatedFuzzySet> subConclusions;
};

And method addActivatedFuzzySet(...):
void UnionFuzzySet::addActivatedFuzzySet(const ActivatedFuzzySet &set)
{
    this->subConclusions << set;
}

It doesn't work with compiling error:
c:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include\QtCore\qhash.h:882: ошибка: C2665: 'qHash' : none of the 16 overloads could convert all the argument types
c:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include\QtCore/qhash.h(62): could be 'uint qHash(char)'
c:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include\QtCore/qhash.h(63): or       'uint qHash(uchar)'
c:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include\QtCore/qhash.h(64): or       'uint qHash(signed char)'
c:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include\QtCore/qhash.h(65): or       'uint qHash(ushort)'
c:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include\QtCore/qhash.h(66): or       'uint qHash(short)'
c:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include\QtCore/qhash.h(67): or       'uint qHash(uint)'
c:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include\QtCore/qhash.h(68): or       'uint qHash(int)'
c:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include\QtCore/qhash.h(69): or       'uint qHash(ulong)'
c:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include\QtCore/qhash.h(77): or       'uint qHash(long)'
c:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include\QtCore/qhash.h(78): or       'uint qHash(quint64)'
c:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include\QtCore/qhash.h(86): or       'uint qHash(qint64)'
c:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include\QtCore/qhash.h(87): or       'uint qHash(QChar)'
c:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include\QtCore/qhash.h(88): or       'uint qHash(const QByteArray &)'
c:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include\QtCore/qhash.h(89): or       'uint qHash(const QString &)'
c:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include\QtCore/qhash.h(90): or       'uint qHash(const QStringRef &)'
c:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include\QtCore/qhash.h(91): or       'uint qHash(const QBitArray &)'
while trying to match the argument list '(const ActivatedFuzzySet)'
Please, tell me, where have I made a mistake?
Answer: QSet uses hash table inside. But to store item in hash table, you should be able to calculate item's hash. qHash function does calculate hash for item.
As you can see, it is some predefined overloads, that allow you to calculate hash for standard types, but if you want to store ActivatedFuzzySet you should define function qHash that accepts your ActivatedFuzzySet, like that:
uint qHash(const ActivatedFuzzySet& value)
{
    //calculate hash here
}

Answer: all data type can t be set as template in a qhash.
please, read the qt documentation page : http://developer.qt.nokia.com/doc/qt-4.8/qset.html#details
If you set a pointer to your type instead of the type it should be ok
Comment: But he wants a set based on item equivalence, not on pointer equivalence.

Inserting element into QSet class


Problema no agendamento para envio de avisos por e-mail Spring e JavaMailSender

Question: Bom dia,
Estou usando o spring com o Scheduled, antes usava o quartz mas como fiz upload da versão do spring resolvi abandonar o quartz ja que a primeira opção era o suficiente para atender minha necessidade.
Resumindo, tenho uma tarefa que envia e-mails, esse abaixo é o evento.
@Configuration
@EnableScheduling
public class NotificacaoScheduler {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private NotificacaoService notificacao;
    @Scheduled(fixedRate = 3600000)//1800000
    public void scheduleFixedRateTask() {
        notificacao.analisar();
        logger.debug("Fixed rate task - " + LocalDateTime.now());
        notificacao.enviarPendentes();
        logger.debug("Send ok - " + LocalDateTime.now());
    }
}

Abaixo o service,
@Service
public class NotificacaoService {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private Notificacoes notificacao;
    @Autowired
    private NotificacoesEnvios envios;
    @Transactional
    public void analisar() {
        List<Notificacao> result = notificacao.buscarHoje();
        List<NotificacaoEnvio> notEnvios = new ArrayList<>();
        for(Notificacao n : result) {
            if(!notificacao.verSeExiste(n)) {
                NotificacaoEnvio ne = new NotificacaoEnvio();
                ne.setNotificacao(n);
                ne.setStatus(false);
                notEnvios.add(ne);
            }
        }
        if(!notEnvios.isEmpty()) envios.saveAll(notEnvios);
    }
    @Transactional
    public void enviarPendentes() {
        List<NotificacaoEnvio> ne = notificacao.notificacoesPendentes();
        List<NotificacaoEnvio> nList = new ArrayList<>();
        for (NotificacaoEnvio n : ne) {
            try {
                MimeMessage mail = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(mail);
                helper.setTo(n.getNotificacao().getPara().replace(" ", "").split(";"));
                if(!n.getNotificacao().getCc().trim().equals(""))
                    helper.setCc(n.getNotificacao().getCc().replace(" ", "").split(";"));
                if(!n.getNotificacao().getCo().trim().equals(""))
                    helper.setBcc(n.getNotificacao().getCo().replace(" ", "").split(";"));
                helper.setSubject(n.getNotificacao().getAssunto());
                helper.setText(n.getNotificacao().getModelo().getTexto(),true);
                helper.setFrom(n.getNotificacao().getDe(),n.getNotificacao().getAutor());
                mailSender.send(mail);
                n.setDataEnvio(Calendar.getInstance());
                n.setStatus(true);
                nList.add(n);
            } catch (NullPointerException | MailException | MessagingException | UnsupportedEncodingException e) {
                logger.error(e.getMessage());
            }
        }
        if(!nList.isEmpty()) envios.saveAll(nList);
    }
}

O que ocorre, que tenho notifição que é gerada em uma tabela de pendencias, que a cada 1 hora é enviado as notificações pendentes, o problema esta justamente ai, o metodo analisar() esta funcionando corretamente, porem o metodo enviarPendentes(), esta enviando a mesma notificação 2 vezes (não existe duas linhas do mesmo registro no meu banco). Durante os testes que fiz no eclipse, apenas uma vez era enviado, mas lá no servidor tomcat estou com esse problema.
Abaixo o metodo de consulta a base
@Override
public List<NotificacaoEnvio> notificacoesPendentes(){
    Criteria criteria = manager.unwrap(Session.class).createCriteria(NotificacaoEnvio.class);
    criteria.add(Restrictions.eq("data", Calendar.getInstance()));
    criteria.add(Restrictions.eq("status", false));
     return criteria.list();
}

Abraços e Feliz Ano novo a todos
Answer: Provavelmente seu problema está em múltiplas instâncias do seu Scheduler sendo executadas ao mesmo tempo.
Algumas considerações:

Se você configurar sua aplicação por meio de XML e annotations, pode ser que uma instância seja criada através das annotations e consequentemente uma nova instância criada após o XML ser considerado pelo contexto, como discutido no bug SPR-10830
Seu contexto de aplicação está sendo carregado duas vezes
Deploy duplicado no servidor

De qualquer forma, tente também executar seu Scheduler fora da classe de configuração, por exemplo:
@Configuration
@EnableScheduling
public class JobSchedulerConfig {}

A annotation @EnableScheduling faz o seguinte:

This enables detection of @Scheduled annotations on any Spring-managed bean in the container.

Desta forma você pode ter suas configurações de jobs fora da classe de configuração.
E seu job de notificação:
@Component
public class NotificacaoJob {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private NotificacaoService notificacao;

    @Scheduled(fixedRate = 3600000)
    public void doSchedule() {
        notificacao.analisar();
        logger.debug("Fixed rate task - " + LocalDateTime.now());
        notificacao.enviarPendentes();
        logger.debug("Send ok - " + LocalDateTime.now());
    }

}

Caso seu job não for localizado, você pode incluir a annotation @ComponentScan(basePackages="meu.pacote.scheduler") para indicar o Spring onde encontrá-los.
A referência relacionada à configuração do job pode ser encontrada na documentação do Spring, alguns dos pontos que mencionei podem ser encontrados também nesta thread do StackOverflow
Comment: obrigado pelas dicas, vou tentar o metodo que me sugeriu, so pra constar configurei apenas por annotations. So não entendo porque é executado duas vezes. Mesmo assim vou testar no projeto e dou um retorno. Muito obrigado
Comment: tentei fazer como mencionado, mas não deu certo, ainda continua enviando 2 vezes. se não der certo vou usar o quartz
Answer: Boa tarde, enfim consegui resolver, não entendi o problema, mas trocando a anotação @Scheduled(fixedRate = 3600000) por cron já não deu mais problema.
@Component
@EnableScheduling
public class NotificacaoJob{
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private NotificacaoService notificacao;
    @Autowired
    private JavaMailSender mailSender;
    @Scheduled(cron="0 0 * * * *")
    public void execute() {
    //restante do codigo aqui
    }
}


Convergence of conditional probability given convergence of the conditional event

Question: Consider a sequence of random variables $X_n$ that converges in probability to a random variable $X$. Is it true that for all measurable events $A$ we have the convergence:
$$\mathbb P(A | X, X_n) \rightarrow^p \mathbb P(A|X)$$
If not, what conditions do I need to make this true?
I would expect that it is true, but I am not sure what the exact argument is and if I am missing some subtle point.
To show the convergence, we need to show that for all $\epsilon >0$ we have that $\mathbb P( | \mathbb P(A | X, X_n) - \mathbb P(A|X) | > \epsilon) \rightarrow 0$. Here is my attempt:
$$\lim_{n\rightarrow \infty}\mathbb P( | \mathbb P(A | X, X_n) - \mathbb P(A|X) | > \epsilon) = \lim_{n\rightarrow \infty}\mathbb P( | \mathbb P(A | \delta_n, X) - \mathbb P(A|X) | > \epsilon)$$
where $\delta_n = X -X_n$. But $\delta_n \rightarrow^p 0$. From here I would want to bring the limit on the RHS inside the expectation, but for that I'm pretty sure I need convergence almost surely of $\delta_n$. After that I would be done. Am I missing something, or do I really need convergence almost surely?
Answer: No, this is not true.  Let $\mathbb{P}(A) \in (0,1)$ and consider the random variables $X_n := \frac 1n 1_A$.  Then $(X_n) \rightarrow 0$ a.s. and therefore also in probability, but $\mathbb{P}(A | X_n) = 1_A$ so $\mathbb{P}(A | X_n) \not \rightarrow \mathbb{P}(A|X) = \mathbb{P}(A)$.


How to add list of lists of string in PDF with iTextSharp?

Question: I have created 2D list of strings:
List<List<string>> questions = new List<List<string>>();

How can I add elements of this 2D list to my PDF file using iTextSharp?
if (pdfFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
     Document document = new Document(iTextSharp.text.PageSize.LETTER, 20, 20, 42, 35);
     PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfFile.FileName, FileMode.Create));
     document.Open();

     Paragraph paragraph = new Paragraph("Test");

     document.Add(paragraph);

     document.Close();

}
I have tried this with simply for loop and command:document.Add(questions[i]);
but it is not working.
Comment: Apart from the fact that you need an iTextSharp example and my answer has an iText example, your question is the exact duplicate of [How to create a table based on a two-dimensional array?](http://stackoverflow.com/questions/24404686/i-need-to-create-a-table-and-assign-the-values-into-the-table-in-pdf-using-javaf). You should really read [the documentation](http://pages.itextpdf.com/ebook-stackoverflow-questions.html) before asking questions as simple as this. This isn't even an iTextSharp question. It's about looping over a 2D array and using those values as data.
Answer: First let's take a look at the answer to the question C# What does List<List<string>> mean?
The accepted answer shows how you can output the contents of this 2D list:
List<List<string>> lists;
...
foreach (List<string> list in lists)
{
    foreach (string s in list)
    {
        Console.WriteLine(s);
    }
}

Now look at the answer to the question How to create a table based on a two-dimensional array?
It explains how to use the data of a List<List<string>> to construct a PdfPTable:
PdfPTable table = new PdfPTable(numColumns);
foreach (List<string> question in questions) {
    foreach (string field in question) {
        table.AddCell(field);
    }
}

Now all you have to do, is to add the table to the Document instance:
document.add(table);

Important: I don't know the value of numColumns. You should replace numColumns by the number of string values of a question object. As you create the questions object, you (and only you) know the answer to that question. Actually, you could ask the first element of the questions list for its size; that way you don't have to guess. Note that it is assumed that every question has the same amount of elements.
UPDATE: if you don't want a table, you should wrap the string values in paragraphs. For instance:
foreach (List<string> question in questions) {
    foreach (string field in question) {
        document.Add(new Paragraph(field));
    }
}

Comment: You missunderstood me. I don't want to add a table to my PDF. I just want to add groups of questions by numerical order (one after the another). I want it to look like a test in school.
Comment: In that case, you need to wrap the questions and answer in objects (such as `Paragraph`s). You really should do more effort, but I'll update my answer.
Comment: Sorry. I'm a beginner in C#. Thank you for your effort!


Creating line item of specific type programmatically

Question: Is there a way to create a line item of specific type (different from the default "Product" type) programmatically? The function commerce_product_line_item_new()creates a line item of type Product. I can't find a function that let's you specify an existing line item type other than the default Product one.
EDIT: Never mind. I just realized that the commerce_product_line_item_new() function has a $type parameter that defaults to Product. Not sure how to delete the question, but maybe it will help someone else.
Comment: This probably will help someone in the future - would you mind taking the resolution out of the question and putting it in an answer? Self-answering is encouraged here. Thanks!
Answer: Never mind. I just realized that the commerce_product_line_item_new() function has a $type parameter that defaults to Product. Not sure how to delete the question, but maybe it will help someone else.


PHPUnit - Command-line test drops down a line for no apparent reason?

Question: Normally the PHPUnit command-line runner gives output similar to following:
PHPUnit 3.6.12 by Sebastian Bergmann.

....

Time: 26 seconds, Memory: 10.00Mb

OK (4 tests, 84 assertions)

However, in one of my tests the following occurs:
PHPUnit 3.6.12 by Sebastian Bergmann.

.
...

Time: 26 seconds, Memory: 10.00Mb

OK (4 tests, 84 assertions)

It has something to do with one of the fixtures that's included. If I comment out the correct fixture this oddity does not show up. However, I've tried removing every part of the code in the fixture file itself and this still happens. It's not related to the first test. This happens regardless of which test is moved to the top of the test file. So it must be something with the model of the fixture itself. Yet, nothing stands out to me as being the culprit. It doesn't actually seem to affect the test in anyway, but it bothers me that this is happening anyway. Anyone have any suggestions/seen this before? Thank you much!
Answer: Something in your 2nd test outputs a carriage-return. I can reproduce your output with this simple file:
<?php
class EchoTest extends PHPUnit_Framework_TestCase{

function test1(){ $this->assertEquals(3,1+2); }
function test2(){ echo "\n";$this->assertEquals(3,1+2); }
function test3(){ $this->assertEquals(8,3+5); }
function test4(){ $this->assertEquals(11,5+6); }
}

If you don't see any obvious echos, and your tests are in multiple files, the classic cause would be a stray blank line before <?php or after the closing ?>.
Comment: Oops, I forgot to come back here to say I already found the answer. But yes it was stray blank line after the closing "?>". And don't worry, I already know that the closing tag is "optional". Thank you much!


Failing to find the right type arguments when using the bits parsers in nom 5.1.2

Question: I'm failing to find the correct syntax to do bit parsing in nom 5.
I'm trying this:
pub fn parse_normal_record_header(i: &[u8]) -> nom::IResult<&[u8], FitRecordHeader> {

     let (i, _) = nom::bits::bits(nom::bits::complete::tag(0x0, 1_usize))(i)?;
     ...
}

And getting this from the compiler:
error[E0283]: type annotations needed
   --> src/fitparsers.rs:658:18
    |
658 |     let (i, _) = nom::bits::bits(nom::bits::complete::tag(0x0, 1_usize))(i)?;
    |                  ^^^^^^^^^^^^^^^ cannot infer type for type parameter `E1` declared on the function `bits`
    |
   ::: /Users/djk/.cargo/registry/src/github.com-1ecc6299db9ec823/nom-5.1.2/src/bits/mod.rs:37:23
    |
37  | pub fn bits<I, O, E1: ParseError<(I, usize)>+ErrorConvert<E2>, E2: ParseError, P>(parser: P) -> impl Fn(I) -> IResult
    |                       ---------------------- required by this bound in `nom::bits`
    |
    = note: cannot satisfy `_: nom::error::ParseError<(&[u8], usize)>`
help: consider specifying the type arguments in the function call
    |
658 |     let (i, _) = nom::bits::bits::(nom::bits::complete::tag(0x0, 1_usize))(i)?;

I've tried various hideous things like this:
let (i, _) = nom::bits::bits(nom::bits::complete::tag::<&[u8], (&[u8], u8), usize, dyn nom::error::ParseError<(&[u8], usize)>>(0, 1_usize))(i)?;

... attempting to follow what I'm seeing in the nom source, but that's yielding different errors:
error[E0277]: the size for values of type `dyn nom::error::ParseError<(&[u8], usize)>` cannot be known at compilation time
   --> src/fitparsers.rs:662:34
    |
662 | ...om::bits::bits(nom::bits::complete::tag::<&[u8], (&[u8], u8), usize, dyn nom::error::ParseError<(&[u8], usize)>>(0, 1_usize))(i)?;
    |                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
    |
   ::: /Users/djk/.cargo/registry/src/github.com-1ecc6299db9ec823/nom-5.1.2/src/bits/complete.rs:57:21
    |
57  | pub fn tag<I, O, C, E: ParseError<(I, usize)>>(pattern: O, count: C) -> impl Fn((I, usize)) -> IResult<(I, usize), O, E>
    |                     - required by this bound in `nom::complete::tag`
    |
    = help: the trait `std::marker::Sized` is not implemented for `dyn nom::error::ParseError<(&[u8], usize)>`

What am I doing wrong?
Answer: This is a known problem. The following annotation would be enough:
nom::bits::complete::tag::<_, _, _, (_, _)>(0x0, 1_usize)

However, please note that you're likely making another mistake here. Yes, the bits combinator switches nom to bits mode, but only for the duration of the inner parser. On exit it drops the remaining part of the byte if it's incomplete. Thus the normal way of working with bits is to do
nom::bits::bits(nom::sequence::tuple::<_, _, (_, _), _>((
    /* a number of bitfields that add up to a whole number of bytes */
)))(i)?

or something equivalent to that. The inner parser does not need to be tuple, but it needs to be a bit-level parser that consumes a multiple of 8 bits, otherwise some bits will be dropped on exiting the bits context.


Parsing large HTML files with Nokogiri

Question: I'm trying to parse http://www.pro-medic.ru/index.php?ht=246&perpage=all with Nokogiri, but unfortunately I can't get all items from the page.
My simple test code is:
require 'open-uri'
require 'nokogiri'

html = Nokogiri::HTML open('http://www.pro-medic.ru/index.php?ht=246&perpage=all')
p html.css('ul.products-grid-compact li .goods_container').count

It returns only 83 items but the real count is about 186.
I thought that the problem could be in open, but it seems that function reads the HTML page correctly.
Has anybody faced the same problem?
Answer: The file seems to exceed Nokogiri's parser limits. You can relax the limits by adding the HUGE flag:
require 'open-uri'
require 'nokogiri'

url = 'http://www.pro-medic.ru/index.php?ht=246&perpage=all'
html = Nokogiri::HTML(open(url)) do |config|
  config.options |= Nokogiri::XML::ParseOptions::HUGE
end
html.css('ul.products-grid-compact li .goods_container').count
#=> 186

Note that |= is a bitwise OR assignment operator, don't confuse it with the logical operator ||=
According to Parse Options, you can also set this flag via config.huge
Comment: Note that for a single config option you can apply it far more simply by using the config method: `html = Nokogiri.HTML( open(url), &:huge )`
Comment: Sorry, no. Maybe the folks at http://softwarerecs.stackexchange.com can recommend a library.
Comment: Thank you so much Stefan! I supposed there must be some restriction about page size. But `html.css('ul.products-grid-compact li .goods_container').count` now takes too much time to compute. Is there some way to speed it up? Or it is just because of large page size and there is nothing to do with it?
Comment: A quick check reveals that the markup is broken. It results in a node tree with a depth of 571 and such a tree takes very long to traverse. You have to sanitize the page before feeding it into Nokogiri. I have used Safari to save a fixed version of the page and it took merely half a second to count the elements (without any config changes).
Comment: Stefan can you tell me how do you check markup? Is there any way to do it from code automatically?
Comment: I mean not to check from code but to sanitize.
Something like `source = open(url).sanitize`
Comment: @Phrogz nice catch, didn't think of that!

Parsing large HTML files with Nokogiri


Create a countdown in vuejs with momentjs

Question: I have a mixin that returns remaining time in this format HH:mm:ss.
Vue.mixin({
    methods: {

    remainingTime(){

      // some calculations based on current time and given time
      return timeLeft.toString();
    }
....

in component, I call the mixin to get the time
export default {
    ....
    data() {
        return {

           timeLeft: this.remainingTime(),
    ....

and in my template I call it {{timeLeft}} which returns something like 01:20:33 but I want to display this value as a countdown. So the moment it loads on the page, start counting down 1 second.
I tried to use a watcher but it doesnt work:
watch: {
        timeLeft: {
            handler(value) {
                if (value) {
                    setInterval(() => {
                        this.timeLeft;
                    }, 1000);
                }
            },
            immediate: true,
        },
    },

Answer: Keep time with a numeric value. Present time with a string value.  The watcher's job is to notice changes in the numeric time and convert it to a string.
It's definitely not a watcher's job to setInterval(). You'll end up starting new timers willy nilly.

Vue.config.productionTip = false;
Vue.config.devtools = false;

var app = new Vue({
  el: '#app',
  data: {
    timeLeft: 0,
    timeLeftString: '',
    timer: null
  },
  watch: {
    timeLeft: function (val) {
      const timeZero = moment("1900-01-01 00:00:00");
      this.timeLeftString = timeZero.add(val, 'seconds').format("HH:mm:ss")
    },
  },
  mounted() {
    this.timeLeft = 63;
    this.timer = setInterval(() => {
      if (this.timeLeft <= 0) {
        clearInterval(this.timer);
        alert('Done');
      } else {
        this.timeLeft--
      }
    }, 1000)
  }
})

    {{ timeLeftString }}

Comment: thanks, how can I keep `remainingTime` as numeric value when I get `01:20:33`?
Comment: Use two properties, one string one number.
Answer: Without momentjs:
You can use mod (%) to extract hour minutes and date.
Code taken from article at bottom of this post. Run the setInterval on mounted or whenever you get data for deadline date time

let countDownDate = new Date("Jan 01, 2023 00:00:00").getTime(); // The deadline
let x = setInterval(() => {
   let now = new Date().getTime();
   let distance = countDownDate - now;

   let days = Math.floor(distance / (1000 * 60 * 60 * 24));
   let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
   let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
   let seconds = Math.floor((distance % (1000 * 60)) / 1000);
   console.log(days + "d " + hours + "h " + minutes + "m " + seconds + "s"); // Countdown output

   if (distance < 0) {
      clearInterval(x);
      console.log("Too late!") // Text at the end of the countdown
   }
}, 1000)

You can check it here https://beetrootacademy.se/blog/front-end-development/js-countdown-timer-14-lines
Comment: I don't see where the OP uses mod or does any time formatting.
Comment: Me too. And that doesn't mean I can't point out about mod because IMO, for calculating countdown in vanilla js it is the key of the logic


CKEditor is missing when editing a page, but works fine when creating a new page

Question: On our drupal 7 site, we have CKEditor installed. It works fine when creating new content, but it doesn't activate properly when you go to edit the same page later. It acts like there is no editor installed and just gives a standard textbox with source.
If I click "Edit Summary", it will usually show up for the summary textbox (though not always).
Why isn't CKEditor showing up for the Body textbox?
Note that I am not selecting "switch to plain text editor". If I do, and if I see CKEditor on "Edit Summary", then clicking "switch to plain text editor" does properly hide the CKEditor for the Summary textfield. Clicking "switch to rich text editor" also restores CKEditor for the Summary, but the main Body textbox still acts like it uses a plain text editor.
New Page - CKEditor Showing

Edit Page - CKEditor Missing

Edit Page Summary - CKEditor Showing (but still missing for the body textbox - not shown in screenshot)

Edit: More details on the exact problem
I found that the reason a New Page loads ckeditor, while editing does not, is because the textbox is empty. If I add text to the new page, switch to 'plain text editor', then try to switch back to 'rich text editor', then CKEditor does not load.
Similarly, if I clear out the data in the textbox while editing a page, and switch text editors, CKEditor loads up.
There is a 500 error being returned, causing CKEditor to not load. When there is text, switching to 'rich text editor' causes an AJAX call to the server to validate or otherwise process the textbox data. Since it fails, CKEditor never loads.
But if there is nothing in the textbox, the AJAX call never happens (and thus no 500 is returned), so CKEditor loads up just fine. This is also why CKEditor loads in the Summary: it has no data.
Comment: What is the input format set to? Your screenshot is cropping it out. Also, any errors in your javascript console?
Comment: @CharlieS I did have a javascript error, which I mentioned in my edit. Firebug showed a 500 being returned when calling `mysite.com/ckeditor/xss`.
Comment: I have exactly the same problem. and I have searched for answers for many days now, and followed every solution that forums brougth me. I uninstalled wysiwyg and ckeditor, reinstalled ckeditor. No solution at all.
My provider upgraded php versions (5.3 to 5.4) on the webserver. Can that be the source of the problem?
Comment: @CharlieS The input format doesn't matter. Changing from "Full HTML" to "Filtered HTML" or any other resulted in the same problem.
Answer: The solution, in my situation, was two-fold.
Multiple CKEditor versions in different locations
First, the main reason was due to having multiple versions of CKEditor installed in different locations.
When you install the CKEditor module, you must also download the actual CKEditor code separately. It can be installed within the modules/ckeditor folder or in libraries. I had updated the module as well as the code, but the old version persisted in the libraries folder. Sometimes CKEditor would load, and other times it wouldn't. Likely it was due to one CKEditor library loading first.
Removing all duplicate references and clearing the cache worked. CKEditor loaded again on most of our sub-sites.
Buggy code on server causing a 500 error
The second problem was due to faulty php code on one of our subsites. For some reason, an unrelated page included other PHP and was somehow being called when CKEditor made the AJAX call to the server. The server responded with a 500 error, and the error logs shows that this unrelated page was somehow being called and failing.
I took out the reference to the buggy code, and CKEditor worked again for that page.
I still have no idea how that code was being called. It was a simple page with a single line of php, including a different file. Yet CKEditor failed to load on every page within the subsite, not just that page. I chalk it up to lacking enough understanding of Drupal internals.
Comment: I am encountering a similar issue with ckeditor. But when I view the console also find the same chosen errors
Answer: I had the same issue, ckeditor worked when creating new content but not when editing.
Doing a code inspect showed couple of chosen module errors (7.x-2.0-beta4)
Failed to load resource: the server responded with a status of 404 (Not Found) http://example.com/sites/all/libraries/chosen/chosen.jquery.min.js?v=1.1.0
Attr.specified is deprecated. Its value is always true. jquery.js?v=1.4.4:52
Uncaught TypeError: undefined is not a function chosen.js?v=1.1.0:60
My issue was I had extracted the Chosen.tar.gz file which doesnt have the .js file, you need the chosen.zip code in your libraries.
Comment: Yep broken chosen script. The knock-on effect to ckeditor is a surprice
Answer: Another thing that might cause this behaviour is having php code in the nodes, for example redirects performed with php code in the body field. If this is the case, you should use an external redirects module, because using php redirects in node fields will only cause trouble.
The issue seems to be also active in the module's issues queue.
Answer: I resolved this using the following;
I initially had the Default and Alternate jQuery settings @ 1.10 and no CKEditor in Full or Filtered.
Drupal 7.32
Bootstrap 7.x-3.0
CKEditor Module 7.x-1.16

No special settings

jQuery update Module 7.x-2.4

Default jQuery version 1.8
Alternate jQuery version 1.8
jQuery and jQuery UI CDN = jQuery, google or MS

Dropping to 1.8 was the trick.
shrug ... I don't know where to find the version I've got installed. :-)
Granitize me!
Answer: I fixed this issue by following bellow steps:
Go to Content type -> Basic page -> Manage fields -> body
Now select "Plain Text" under "Text processing" then save.
Again I changed from "Plain text" to "Filtered Text".
Now its working.
I think here main concept is just clicking "Save" button
Answer: Thanks for this. I had the same problem where my editor wasn't showing up on the node forms and neither was my chosen. Looking in firebug console I could see JS errors relating to some JS I was adding in with the following hook:
function module_page_build($page) {
  $node = menu_get_object();
  if ($node) {
    drupal_add_js(drupal_get_path('module', 'module') .'/some-js.js');
  }
}

My check for $node is obviously not enough as this is true on the node edit forms. My solution will be to add some extra checks here. Maybe just using is_admin().
Answer: I had this happen on some nodes but not others; the problem was a 403 error being triggered on some pages with the ajax call to /ckeditor/xss ... mod_security was throwing the 403 error because of the content in the post.  In my particular case, it was because of javascript snippets in the page content (widget loaders and sizers, etc), but it can be triggered by other things.
As a workaround, I could cut the content from the field, toggle to WYSIWYG mode, and then CKEditor would load.  Then I could toggle the "Source" button on CKEditor, and paste the code back in, then toggle back into WYSIWYG mode and edit as normal, and save.  Upon editing the next time, would have to do this again.
I think one solution could be to exclude the path /ckeditor/xss from mod_security filtering ... definitely don't disable mod_security altogether though, except for troubleshooting this issue.
Some other causes for this issue and workarounds are discussed here: https://www.drupal.org/node/2069871 ... thanks to "75th Trombone" on drupal.org for the suggestion about mod_security, which proved to be the cause in my case as well.


Let X be a non empty set equipped with the cofinite topology T. Is (X,T) compact? Is it connected?

Question: I have something, but I don't really know if they are strong enough (or correct) answers.
So; For proving it is compact.
In the cofinite topology, A is open if and only if X\A is finite.
Let C be any open covering of X and A be contained in C.
For every x in X\A there exists Ax in C since C is a covering.
Now, AU{Ax:x is in X\A} is a finite subcover since X\A is finite.
Hence we can say that the topology is compact.
And, I am not really sure about proving it is connected, just realised what I had written down was complete rubbish.
Thanks
Answer: For an open cover $\mathcal {C}$ of $X$

Take an element $A$ in $\mathcal{C}$ how many elements does $X/A$ have?
How many open sets do you need to cover $X/A$?

For connectedness

Can two distinct non-empty open sets of a cofinite topology ever be disjoint?
Comment: so what would be my first step?
Comment: your first step would be to think about the hints given above...


DTFT of odd function?

Question: I am confused about the result of an odd function being purely imaginary for the DTFT of an odd function. I was under the understanding that the result of a FT was amplitude and phase as a function of frequency, with phase information being imaginary and amplitude being real. The magnitude could then be calculated from this complex number.
However, in a purely odd function the DTFT is purely imaginary. Is there then no amplitude information? How is the magnitude found?
For instance, if $x[n] = \delta(n - \pi/2) - \delta(n - 3\pi/2)$, the DTFT could be found to be $X(jw) = exp(-jw(\pi/2)) - exp(-jw(3\pi/2))$. Even if this is simplified via symmetry I get $2jexp(-jw\pi)sin(w*\pi/2)$. This is purely imaginary and I am confused how the results are interpreted.
Comment: Of course there is amplitude/magnitude for a purely imaginary quantity. What is the magnitude of $j$?
Answer: There are two ways to represent the Fourier transform - in terms of sines and cosines, or in terms of complex exponentials with positive and negative weights on the exponent. This is based on two choices of basis for the space of solutions to $y''+y=0$; either $y=\sin t$ and $y=\cos t$ or $y=e^{it}$ and $y=e^{-it}$.
The two versions are related by a simple linear transformation. A real-valued odd function will have a transform which is odd and purely imaginary in the complex form, or that is pure sine (and pure real) in the real form. A real-valued even function will have a transform which is even and pure real in the complex form, or real and pure cosine in the real form.
In your "amplitude/phase" framework, the amplitude is the absolute value of that complex number $z$ and the phase is its angle $\arg z$.

DTFT of odd function?


CRC lookup table generated in C always gives different results

Question: I'm trying to create a function that generates a CRC lookup table. I'm working with an 8051 micro-controller, and I'd rather do the table lookup method but at the same time, I'd rather have my computer generate the values which then I can load directly into the micro-controller. Most of this source code has been borrowed from: http://www.rajivchakravorty.com/source-code/uncertainty/multimedia-sim/html/crc8_8c-source.html
I only added in the "main" function
#include <stdio.h>
#define GP  0x107
#define DI  0x07

static unsigned char crc8_table[256];
static int made_table=0;

static void init_crc8()
{
  int i,j;
  unsigned char crc;
  if (!made_table) {
    for (i=0; i<256; i++) {
      crc = i;
      for (j=0; j<8; j++)
        crc = (crc << 1) ^ ((crc & 0x80) ? DI : 0);
      crc8_table[i] = crc & 0xFF;
    }
    made_table=1;
  }
}

void crc8(unsigned char *crc, unsigned char m)
{
  if (!made_table)
    init_crc8();
  *crc = crc8_table[(*crc) ^ m];
  *crc &= 0xFF;
}

int main()
{
  unsigned char crc[1];
  crc8(crc,'S');
  printf("S=%x\n",crc[0]); //different hex code almost every time
  crc8(crc,'T');
  printf("T=%x\n",crc[0]); //different hex code almost every time
  return 0;
}

When I execute the program, I expected the same values on the screen but the hex codes after the printed equals signs changed on nearly every program execution.
What can I do to correct that issue? I don't want to be collecting incorrect CRC values.
Comment: Remember that local variable (including arrays) are by default *uninitialized*. Their values will be *indeterminate*. Now think about that in the context of the `crc` array in the `main` function.
Comment: On an unrelated note, you should probably learn about the address-of operator `&`.
Comment: @Somepro: Could you be more specific about the `&`?
Comment: Instead of using an array to be able to pass a pointer, use a simple `unsigned char crc;` and then use `&crc` to get a pointer. As in `crc8(&crc, 'S')`. An even better solution IMO would be to *not* emulate *pass by reference* and instead have the `crc8` function *return* the value.
Comment: @Someprogrammerdude Would anybody like to make an answer? Just to get this out of the list of unanswered questions.
Answer:
crc[0] is not initialized. You need crc[0] = 0; or *crc = 0; before calling crc8() with crc. Then you won't get random answers coming from the random initial contents of crc[0].
You don't need the *crc &= 0xff; in crc8(). If char is eight bits, then it does nothing. If you have an odd architecture where char is more than eight bits, then you need to do *crc = crc8_table[((*crc) ^ m) & 0xff]; to assure that you don't go outside the bounds of the table. (Only the low eight bits of m will be used in the CRC calculation.) The contents of the table have already been limited to eight bits, so in any case you don't need a final & 0xff.
You may need a different initial value than zero, and you may need to exclusive-or the final CRC value with something, depending on the definition of the CRC-8 that you want. In the RevEng catalog of CRC's, there are two 8-bit CRCs with that polynomial that are not reflected. Both happen to start with an initial value of zero, but one is exclusive-ored with 0x55 at the end. Also the CRC definition you need may be reflected, in which case the shift direction changes and the polynomial is flipped. If your CRC-8 needs to be interoperable with some other software, then you need to find out the full definition of the CRC being used.
Passing a pointer seems like an odd choice here. It would be more efficient to just pass and return the CRC value directly. E.g. unsigned crc8(unsigned crc, unsigned ch) {, which would apply the eight bits in ch to the CRC crc, and return the new value. Note that you do not need to make the CRC value a char. unsigned is generally what C routines most efficiently take as an argument and return. In fact usually the first argument is passed in a register and returned in the same register.
Usually one computes a CRC on a message consisting of a series of bytes. It would be more efficient to have a routine that does the whole message with a loop, so that you don't need to check to see if the table has been built yet for every single byte of the message.
Answer: In the main, crc[0] has not been initialized.  As a result, in crc8, *crc in the expression (*crc) ^ m is uninitialized, hence your random values.
Fix: initialize crc[0].  Something like
unsigned char crc[1] = { 0 };

Comment: That does work, but what I tried that didn't work was: `crc[0]='\0'; crc[1]='\0';` since it gave me a segmentation fault. I'm baffled as to why your solution works but apparently it does.
Comment: `crc[1] = '\0';` is _not_ the same as `unsigned char crc[1] = {0};`. The former is an out-of-bounds access since it tries to set the _second_ element of `crc[]`, but there is no second element since it was declared with one element. Such an access should result in a segmentation fault. The latter is an initialization of an one-element array with one value, which sets `crc[0]` to zero.


Why is $\sqrt x \times \sqrt y = \sqrt {xy}$

Question: Sorry I do not know latex. Why is $\sqrt x \times \sqrt y = \sqrt {xy}$? It also applies for division, but why not addition and subtraction? i.e., why is $\sqrt x + \sqrt y$ not equal to $\sqrt {x+y}$?
Thank you for editing and answering.
Comment: It is indeed not true that $\sqrt{x}+\sqrt{y}=\sqrt{x+y}$ in general, but it is true that [$\sqrt{x+y}\leq \sqrt{x}+\sqrt{y}$](https://math.stackexchange.com/questions/408177/proving-sqrtx-y-le-sqrtx-sqrty) for $x,y\in \mathbb{R}^+$, which is easy to prove.
Comment: $\sqrt x + \sqrt y\neq \sqrt{x+y}$ for the same reason as $(x+y)^2\neq x^2+y^2$.
Comment: You recieved 2 answers to your question. If any of them is what you need, you should **accept** it by clicking the grey tick mark below the question score. Otherwise, explain what is still missing in the answers!
Answer: You were told in the comments where to find an answer to your first question. Now, why is it not true that $\sqrt{x+y}=\sqrt x+\sqrt y$? Because, for instance, $\sqrt1+\sqrt1=2$, whereas $\sqrt{1+1}=\sqrt2<2$.
Answer: remember what $^2$ is:
$$u^2=u\cdot u\\\text{so: }\left(\sqrt{a}\cdot\sqrt{b}\right)^2=\sqrt{a}\cdot\sqrt{b}\cdot\sqrt{a}\cdot\sqrt{b}=\sqrt{a}\cdot\sqrt{a}\cdot\sqrt{b}\cdot\sqrt{b}=a\cdot b=\sqrt{ab}^2\implies\sqrt x \cdot\sqrt y = \sqrt {xy}\\\text{and you can do: }\left(\sqrt{a}+\sqrt{b}\right)^2=\left(\sqrt{a}+\sqrt{b}\right)\cdot\left(\sqrt{a}+\sqrt{b}\right)=\sqrt{a}^2+2\sqrt{a}\cdot\sqrt{b}+\sqrt{b}^2{=a+2\sqrt{a}\cdot\sqrt{b}+b}=\sqrt{a+2\sqrt{a}\cdot\sqrt{b}+b}^2\ne\sqrt{a+b}^2\implies\sqrt{a}+\sqrt{b}\ne\sqrt{a+b}$$


I got this error when I add a background-image in a vue.js project

Question: I got this error when I added a background-image in a vue.js project:
./src/assets/scss/argon.scss (./node_modules/css-loader??ref--8-oneOf-3-1!./node_modules/postcss-loader/src??ref--8-oneOf-3-2!./node_modules/sass-loader/dist/cjs.js??ref--8-oneOf-3-3!./src/assets/scss/argon.scss)
Module not found: Error: Can't resolve '../../../../public/img/theme/home.jpg' in 'D:\work\Aliens\Front\src\assets\scss'
I tried this command but no difference:
npm rebuild node-sass

Answer: Instead of:
'../../../../public/img/theme/home.jpg'

Try to use
'/img/theme/home.jpg'

on your argon.scss file.


What is Median Error Distance and how to calucalte it

Question: How to calculate Median Error Distance?
I'm looking at "Schulz A. et al. A Multi-Indicator Approach for Geolocalization of Tweets". They are calculating Median Error Distance.
But how they are do this?
Answer: From what I see, the terminology used in the paper is slightly incorrect. What MED means is Median Euclidean Distance. What AED means is Average Euclidean Distance.
Euclidean distance is calculated by the formula in the following link
http://en.wikipedia.org/wiki/Euclidean_distance
MED is calculated by taking median of all the euclidean distances between the actual and predicted points


Why is it justified to use squared and cubed terms in log specifications

Question: In the textbook, Introductory Econometrics (Wooldridge), the concept of specifying log/log, level/log ... , is explained as a tool to understand the relationships of the regerssors either in relative or absolute terms. Using log transformation is also explained as having desirable properties like capturing non-linear relationships in a linear regression, reducing the influence of outliers and so forth.
Question: My question mostly refers to the point on log capturing non-linear relationships. If log transforming captures non-linear relationships, why are there examples in the textbook and in the real world where we have both log and squared or cubed terms? something like:
<code>log(y) = c + log(x1) + log(x1^2) + log(xk) + u
</code>
Wooldridge also points out ambiguity in what log squared terms mean. It could be as above, or the one below (where we log first, then square the whole term):
<code> log(y) = c + log(x1) + log(x1)^2 + log(xk) + u
</code>
In either event, is it fair to say that log transforming alone does not adequately capture non-linear components, and thus we include squared/cubed terms? Or, perhaps using log is mainly for theory (relative/absolute inference) and including squared/cubed terms still is needed?
Comment: $\log(x_1^2) = 2\log(x_1)$ so as written this does not make a lot of sense - are you sure this formulation is what appears in the textbook (and in "the real world")?
Comment: @JuhoKokkala Is almost the same, I am inept at latex encoding, I'll try to fix though.
Answer: Logs certainly don't capture all nonlinear relationships. Sometimes a polynomial term is better, sometimes you really need something more flexible such as a spline.
And sometimes we want logs of variables because it makes substantive sense. We might, conceivably, even want a spline of a log term.
Comment: Time permitting, I would love to see an example specification using logs and splines together.
Comment: I don't have an example but, suppose income was one of the IVs and it was related in nonmonotonic ways to the DV. Then that would be a good candidate.


Distributing locks and keys so certain subsets of people can open all locks

Question: A vault can be opened by n number of keys. Five people, A, B, C, D, E are given some of the keys. Each key can be duplicated arbitrary number of times. Find the smallest number n and the distribution of the keys per person so the vault can be opened if and only if one of the following situations happened:

persons A and B are present together
persons A,C and D are present together
persons B,D and E are present together

Any ideas how this problem can be aprroached? I've tried with truth tables and Veicth diagrams but I only find my self going in a circle.
Comment: Related: https://math.stackexchange.com/questions/581461/what-is-the-minimum-number-of-locks-on-the-cabinet-that-would-satisfy-these-cond
Answer: The following logical statement determines which groups of people should be able to open the vault:
$$
(A\wedge B)\vee (A\wedge C\wedge D)\vee (B\wedge D\wedge E)
$$
This is in conjunctive normal form. If we convert this to disjunctive normal form, then we will have a list of clauses of the form $(X\vee Y\vee Z\vee \dots)$ which all must be simultaneously satisfied. But this corresponds exactly to a lock distribution solution. Each clause represents a lock, and all locks must be opened. The variables comprising each clause represent who is given a key to that lock, and at least one person with that key must be present.
So, we just need to convert that CNF to a DNF. This is a purely mechanical process, which is found by fully distributing about the CNF ($\vee$ distributes over $\wedge$), then eliminating redundant clauses. I made such a converter, available here, and the result is
$$
(A \vee B) \wedge (A \vee D) \wedge (A \vee E) \wedge (B \vee C) \wedge (B \vee D)
$$
This means that $5$ locks is optimal (since there are five clauses), and the key distribution is
<code>Lock 1:  A, B
Lock 2:  A, D
Lock 3:  A, E
Lock 4:  B, C
Lock 5:  B, D
</code>
Comment: Thanks a lot for the answer, I understood the part about converting CNF to DNF but I didn't get the distribution of keys per person. So you're saying that there are 5 keys? How are they distributed per person?
Comment: The DNF is $$(A \vee B) \wedge (A \vee D) \wedge (A \vee E) \wedge (B \vee C) \wedge (B \vee D)$$ Therefore, there are five **locks**. The keys to the first lock are given to $A$ and $B$, since the first clause is $(A\vee B)$. The keys to the second lock are given to $A$ and $D$, etc @syd
Comment: For the record, it seems obvious that this procedure should produce a minimal n, but I'm not sure how I would go about proving it.
Comment: @RichardRast It boils down to what I was saying in that first paragraph; a lock/key solution corresponds to a DNF exactly, so the # of clauses in the DNF equals the number of locks optimally. You have to make sure the DNF has no redundant terms, of course.


Sphinx suppress specific warnings?

Question: In building my documentation I'm running into a lot of warning messages such as the following:
/home/X/Y/src/core/include/math/bigintntl/transformntl.h:92: warning: documented empty return type of NTL::NumberTheoreticTransformNtl::ForwardTransformToBitReverseInPlace. I'd like to turn off the specific warnings related to X is not documented. How might I go about doing so? I'm building the documentation of a rather large library, and until we have time to go back and update the docs, this just adds a lot of noise to our builds.
The documenting line:
  /**
   * In-place forward transform in the ring Z_q[X]/(X^n+1) with prime q and
   * power-of-two n s.t. 2n|q-1. Bit reversing indexes. [Algorithm 1 in
   * https://eprint.iacr.org/2016/504.pdf]
   *
   * @param &rootOfUnityTable is the table with the n-th root of unity powers in
   * bit reverse order.
   * @param &element[in,out] is the input/output of the transform of type VecType and length n.
   * @return none
   */
  void ForwardTransformToBitReverseInPlace(
      const VecType& rootOfUnityTable, VecType* element);

from OpenFHE library
and the .rst file looks like the following (autodoxygenindex is a Breathe directive: https://breathe.readthedocs.io/en/latest/directives.html#autodoxygenindex):
Core Math Big Int NTL Documentation
=========================================

.. autodoxygenindex::
   :project: core_math_bigintntl

while the conf.py file is here.
Comment: Welcome to Stack Overflow. How are you documenting that missing member? It's hard to give a solution looking just at the warning.
Comment: I'm just looking to suppress the warning, not fix the documentation? Sorry, I must be misunderstanding what you mean
Comment: My question: how are you documenting the line that issues the warning? Your question doesn't have an example of the `.rst`.
Comment: Yes, I do use Breathe!
Comment: I haven't tried Doxygen and Breathe, but [try disabling the warnings individually on the Sphinx level](https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-suppress_warnings) there are also [these options to suppress warnings](https://stackoverflow.com/a/13109215) that I think work on a file level.
Answer: Looks like the issue for me was that breathe was regenerating the documentation because I was using a specific command. Unfortunately, this regeneration seemed to ignore the Doxyfile that was coming in. So, I had to manually pass in the relevant variables via breathe_doxygen_config_options See breathe config-values

Sphinx suppress specific warnings?


Continuity and Differentiability Question

Question: Suppose $F$ is monotone, continuous, and differentiable at all but countably many points. For all $x$ such that $F$ is differentiable at $x$, $F'(x) = 1/a$. Prove $F(x) = x/a + C$ for some $C \in \mathbb{R}$.
Answer: Hint: in each open interval $I_i$ where the function is differentiable, $F(x)=x/a+C_i$. Easy case: what happens between two contiguous intervals? (isolated point of nondifferentiablility) Harder case: what happens in a point of nondifferentiablility that is limit point of points of nondifferentiablility?
Comment: The case of isolated points is obvious.  I'm after the more general case (i.e., your "harder" part).  Do you have a more substantial hint for that?
Comment: Let be $x_0$ the point and $\epsilon>0$. Take  $I_i\cap(x_0-\epsilon,x_0)\ne\emptyset$, $I_j\cap(x_0,x_0+\epsilon)\ne\emptyset$, $C_i\ne C_j$.
Comment: Can you please provide a more complete solution?  I'm trying to use this fact but can't seem to prove it and your hints are less than helpful.
Comment: @asdf1234, is much easier: consider F(x)-x/a.


Finding a non-piece wise function that gives us the $i$'th largest number.

Question: A friend of mine was asked to find a non-piece wise function on four variables $i,a,b,c$ such that $f(i,a,b,c)$ is the $i$'th largest number among $\{a,b,c\}$. Using max and min or defining the function by pieces is prohibited.
The solution I found uses Lagrange Polynomials but to explain it I first had to find how to find the max, middle and min elements.
To find max I just use $$\frac{c+(\frac{a+b}{2}+\frac{|a-b|}{2})}{2}+\frac{|c-(\frac{a+b}{2}+\frac{|a-b|}{2})|}{2}$$
This is because the max of $a,b,c$ is $max(max(a,b),c)$
To find min I just use the same approach: $$\frac{c+(\frac{a+b}{2}-\frac{|a-b|}{2})}{2}-\frac{|c-(\frac{a+b}{2}-\frac{|a-b|}{2})|}{2}$$
To find the middle element I substract the maximum and minimum from $a+b+c$.
So it is $$a+b+c-(\frac{c+(\frac{a+b}{2}+\frac{|a-b|}{2})}{2}+\frac{|c-(\frac{a+b}{2}+\frac{|a-b|}{2})|}{2})-(\frac{c+(\frac{a+b}{2}-\frac{|a-b|}{2})}{2}-\frac{|c-(\frac{a+b}{2}-\frac{|a-b|}{2})|}{2})$$.
After having this I just build the lagrange polynomial so that
$$f(i,a,b,c)=\color\red{\frac{(2-i)(3-i)}{2}[\frac{c+(\frac{a+b}{2}+\frac{|a-b|}{2})}{2}+\frac{|c-(\frac{a+b}{2}+\frac{|a-b|}{2})|}{2}}]+\color{blue}{\frac{(1-i)(3-i)}{-1}[a+b+c-(\frac{c+(\frac{a+b}{2}+\frac{|a-b|}{2})}{2}+\frac{|c-(\frac{a+b}{2}+\frac{|a-b|}{2})|}{2})-(\frac{c+(\frac{a+b}{2}-\frac{|a-b|}{2})}{2}-\frac{|c-(\frac{a+b}{2}-\frac{|a-b|}{2})|}{2})}]+\color\green{\frac{(1-i)(2-i)}{2}[\frac{c+(\frac{a+b}{2}-\frac{|a-b|}{2})}{2}-\frac{|c-(\frac{a+b}{2}-\frac{|a-b|}{2})|}{2}}]$$
I would like this space to provide alternative constructions (If they could be simpler it would be better.
Thank you, regards.
Comment: Absolute value is allowed?  That's a piecewise function too.
Comment: Well, the question of whether something is piecewise or not is rather subjective. But my friend tells me absolute value is allowed.
Comment: The polynomial you constructed has four variables, but in your first sentence you want one in three variables. Which is it? Perhaps you want three separate functions: one for max, one for min, and one for middle. These would be in three variables.
Comment: Four variables.
Answer: That's about the way I would do it,
although I would split it up
into a number of
subsidiary functions
(the "b" prefix
stands for "bear"):
$bmin2(a, b)
=\frac12(a+b-|a-b|)
$,
$bmax2(a, b)
=\frac12(a+b+|a-b|)
$,
$bmin3(a, b, c)
=bmin2(bmin2(a, b), c)
$,
$bmax3(a, b, c)
=bmax2(bmax2(a, b), c)
$,
$bmid(a, b, c)
=a+b+c-bmax3(a, b, c)-bmin3(a, b, c)
$.
Then I would write
your interpolating polynomial
in terms of
the min, max, and mid
functions.
To do this
for four variables
seems harder.
We can get the
min and max as above
(with another level of calls),
and we can get the
sum of the middle two,
but how to separate that sum
into the
individual values
so we can we can decide which is smaller
is not immediately clear to me.
I think I'll propose it as a problem.
Comment: Please give me link to the question if you do.
Comment: http://math.stackexchange.com/questions/1100663/how-to-sort-4-or-more-values-with-non-piecewise-functions


Efficient/fast Mahalanobis distance computation

Question: Suppose I have $n$ data points $x_1,\dots,x_n$, each of which is $p$-dimensional. Let $\Sigma$ be the (non-singular) population covariance of these samples. With respect to $\Sigma$, what is the most efficient way known to compute the vector of squared Mahalanobis distances (from $\vec 0$) of the n data points.
That is we would like to compute the vector $(x_1^T\Sigma^{-1}x_1,\dots,x_n^T\Sigma^{-1}x_n)$.
Computing the inverse $\Sigma^{-1}$ seems to be quite slow for large matrices. Is there a faster way?
Comment: Can you give reference for this information please?
Answer:
Let $x$ be one of your data points.
Compute the Cholesky decomposition $\Sigma=LL^\top$.
Define $y=L^{-1}x$.
Compute $y$ by forward-substitution in $Ly=x$.
The Mahalanobis distance to the origin is the squared euclidean norm of $y$:

$$
\begin{align}
x^\top\Sigma^{-1}x &= x^\top(LL^\top)^{-1}x \\
&= x^\top(L^\top)^{-1}L^{-1}x \\
&= x^\top(L^{-1})^\top L^{-1}x \\
&= (L^{-1}x)^\top(L^{-1}x) \\
&= \|y\|^2.
\end{align}
$$
Comment: @Lepidopterist: I have answered this comment in the comments of the new question.
Comment: I had an issue with the accuracy of this proposed algorithm and created a new question: http://stats.stackexchange.com/questions/147654/cholesky-factorization-and-forward-substitution-less-accurate-than-inversion
Comment: Without wanting to take away anything from how insight full this answer is (I up-voted earlier); especially because the OP (@Lepidopteris) uses MATLAB I would argue that for *implementation purposes *only* one should use `x'* Sigma \ x` where effectively `Sigma \ x` will take care of the `inv(A) * x` (please never use this later command).
Comment: Why do you say for implementation purposes one should use x'* Sigma \ x? Why is chol not a good option in MATLAB?


Inter-experimental variation in survival experiment - how to estimate variability?

Question: In my animal experiments, I do survival studies, which generate Kaplan-Meier survival curves for each group, which I then compare with an appropriate log rank test.
My question is: If I have run a survival experiment with identical variables, say, five times, and the final outcome (in very layman's terms) happens to be slightly different each time, is there a test that I can do estimate the variability (variance) of my experimental runs?
One major confounding factor is the fact that survival is a continuous variable over time. Therefore, it is difficult to reduce it to a single statistic (that can then be compared with a test). A lot of people use the median survival (expressed in units of time) as a single statistic surrogate for survival, but it can often be misleading - depending upon the slope of the survival curve, and may not represent the true nature of the survival outcome.
Can someone here help? Please also let me know if further clarifications are needed.
Comment: Can you provide an example of the outcomes you consider in your experiments? What is your sample size (in each group)?
Comment: I'm a bit confused what the goal is as well. Is there a reason examining a plot of each of the 5 hazard functions (and/or their confidence intervals) is insufficient? Do you need a test statistic to state where the curves intersect? As chl suggested in a comment to Thylacoleo's answer pooling seems inappropriate with different outcomes.
Comment: Sorry about the late comment. I just received the book that Thylacoleo recommended. To answer your questions: Chl - the outcome is survival (i.e. no death) over a period of time. The sample size in each group varies from, say, 5-8. Andy - survival experiments suffer from inherent variabilities. I do indeed examine the Kaplan Meier plots of the groups by a log rank test. But I am more interested in finding out if there is a test that can evaluate inter-experimental variabilities of survival experiments.
Answer: I suggest you read Section 2.3 & 2.4 pp40-73 of Hosmer & Lemeshow's 1999 edition of Applied Survival Analysis. This gives variances of various statistics of survivorship functions, such as 1) each time (allowing confidence interval estimation), 2) mean survival, etc. I'm not clear from your question what aspect experimental variability you want to summarise.
You will be aware there are several test statistics which can be used to compare KM survival functions, such as the log-rank test you mention. They differ on the weighting applied to variance estimates of deaths at different survival times. However, the pooled result, which forms the test statistic, is not usually regarded as a variance estimate, in the same way that a chi-squared statistic is not a variance estimator, but a test of whether the sample distribution of the variance follows what is expected from the null hypothesis.
Comment: I was thinking of confidence intervals, but the question is not clear to me because there seems to be different outcomes each time (but may I don't understand the question) which would prevent from pooling anything at all.


Necessary & Sufficient Conditions for a set to be connected

Question: This question is based on Proposition 1.4.13 in Basic Complex Analysis, by Marsden.

Definition 1.4.12: A set $C \subset \mathbb{C}$ is not connected if there exists open sets $U$ and $V$ such that, a) $\, C \subset U \cup V$, b) $\, C \cap U \not = \emptyset$ and $\, C \cap V \not = \emptyset$, c) $(C \cap U) \cap (C \cap V) = \emptyset$.
If a set fails to be not-connected, then it's called connected.

Proposition 1.4.13: A set $C$ is connected iff the only subsets of $C$ that are both open and closed relative to $C$ are the empty set and $C$ itself.

I'm trying to prove this using proof by contradiction for both directions,
$\Rightarrow (PBC):$ If $\exists C^*$ such that $C^* \subset C$ (strict) & $C^*$ is both open & closed relative to $C$, then $C \subset C^* \cup V^*$ where $V^* = \mathbb{C} \backslash C^*$ is open and properties b) & c) hold, a contradiction. $\Leftarrow (PBC):$ If $\exists U,V$ which satisfy the conditions above. Then, $U \cap C$ is open relative to $C$ by $b)$ and $U \cap C$ is closed relative to $C$ by.. ?
I'm struggling to derive a contradiction in the last direction, in Munkres (topology) the author states U is non-empty and different from X and it's both open and closed in X. However, I don't understand why we can say it's closed??
Thanks in advance
Take care!
:)
Comment: I think there are a few spots here where there's some trouble with relative topologies. The the $\Rightarrow$ direction, it should be that $C^*$ is open relative to $C$ and closed relative to $C$, not that $C^*$ is open and closed.

For the second part, we don't say $U$ is open relative to $C$. $U\cap C$ is open relative to $C$. Then $U\cap C$ is closed relative to $C$ precisely because its complement relative to $C$ (which is $C\cap V$) is open relative to $C$.
Comment: By $a$, $$C=C\cap (U\cup V)=(C\cap U)\cup (C\cup V).$$ By $c$, $$(C\cap U)\cap (C\cap V)=\varnothing,$$ so $C\cap U$, $C\cap V$ partition $C$.
Comment: Thank you! I have addressed these typos in the problem statement, one last thing, how can we show that the complement of $ U \cap C$ relative to $C$ equals $C \cap V$? I've tried to evaluate $C \backslash (U \cap C) = ... = (C \cap U^c) \cup (C \cap V^c)$, but am unsure how to make the connection, am i missing something super simple, thanks in advance,
Comment: This helped me greatly, thank you!!
Answer: Suppose $C$ is not connected. Then there exist $U, V$, both open in $\mathbb{C}$, such that: (1) neither $C \cap U$ nor $C \cap V$ is empty, (2) $C \subseteq U \cup V$, and (3) $(C \cap U) \cap (C \cap V) = \emptyset$.
We claim that the set $C \cap U$ is both open and closed, relative to $C$.
It is trivial that $C \cap U$ is open relative to $C$, since $U$ is open in $\mathbb{C}$.
To see that $C \cap U$ is closed relative to $C$, it is enough to show that $C - (C \cap U)$ is open relative to $C$. First, we have that $C - (C \cap U) = C \cap (\mathbb{C} - U)$. We now show that $C \cap (\mathbb{C} - U) = C \cap V$, completing the proof.
Take $z \in C \cap (\mathbb{C} - U)$. Clearly, $z \in C$. From (2) above, this implies $z \in U$ or $z \in V$. But $z \notin U$, so it must be that $z \in V$. This shows $z \in C \cap V$.
Now take $w \in C \cap V$; in other words, $w \in C$ and $w \in V$. Suppose that further $w \in U$. Then $(C \cap U) \cap (C \cap V) = C \cap U \cap V$ contains $w$, which contradicts (3) above. So we must have that $w \notin U$, or $w \in \mathbb{C} - U$. This shows $w \in C \cap (\mathbb{C} - U)$.
Answer: We claim $C$ is not connected if and only if there exist relatively open non-empty $U', V' \subset C$ such that $U' \cup V = C$ and $U' \cap V' = \emptyset$.
Given $U, V$ as in the definition, simply take $U' = U \cap C$ and $V' = V \cap C$. Conversely, given $U', V'$ as above, there exist open $U, V \subset \mathbb C$ such that $U' = U \cap C$ and $V' = V \cap C$. These sets have the properties required in the definition.
The Proposition is equivalent to the following statement:

A set $C$ is not connected iff there exists a subset $W \subset C$ with $W \ne \emptyset, C$ which is both open and closed relative to $C$.

Given such $W$, the sets $U' = W, V' = C \setminus W$ have the properties in the above claim. Conversely, given $U', V'$ with these properties, take $W = U'$.


Sql Pai e Filhos na Mesma Tabela

Question: Estou com a seguinte questão, tenho uma tabela no banco que não pode ser alterada para facilitar o processo. Nesta tabela tenho registros pais e filhos com a possibilidade de até 8 níveis. Mais ou menos assim, como no esquema abaixo:

Neste exemplo, 123 é código original, que gera o 1015, depois o 1015 se torna origem e gera o 2016 e por ai vai, não sei se ficou claro? Meu problema está em buscar os valores, estou tentando criar um forma de buscar histórico o valor original até consegui algo, porém o usuário que buscar pelo destino e retornar a hierarquia na mesma forma que ele busca 123 e retorna todo o caminho até o 2016.
No meu caso o erro aconteceu quando o usuário tentou buscar o valor 3017 que é no exemplo o destino final, e não estou conseguindo criar um código retornar os valores finais.
Meu código até agora:
function get_origem($con,$origem){

   $sql = "SELECT * FROM tabela WHERE origem = '$origem'";

   $movimentacao = ifx_query($sql,$con) or die(ifx_errormsg());

   $row = ifx_fetch_row($movimentacao);

   // Aqui insiro os valores em uma tabela temporária e depois listo ela com JOIN com outras tabelas.
   // E chamo a função novamente para pegar o próximo filho.

   get_origem($con,$row['destino']);

}

Uso PHP e Informix.
Answer: Pelo que entendi você precisa que a pesquisa retorne toda a árvore, mesmo que o critério seja o item final, como no exemplo 3017.
O problema é que seu código apenas avança para os destinos e nunca testa se existe origem para um determinado ponto. Uma maneira seria adicionar uma função para pesquisar as origens a partir do destino.
Talvez isso funcione:

// FUNCAO PARA SIMPLIFICAR A CHAMADA DA PESQUISA DE AMBOS OS CAMINHOS
function get_origem_destino($criterio){

   // codigo para criar a conexao $con

   get_origem($con,$criterio);
   get_destino($con,$criterio);

}

// FUNCAO PARA PESQUISAR ORIGENS A PARTIR DO DESTINO
function get_origem($con,$destino){

   $sql = "SELECT * FROM tabela WHERE destino = '$destino'";

   $movimentacao = ifx_query($sql,$con) or die(ifx_errormsg());

   $row = ifx_fetch_row($movimentacao);

   // Aqui insiro os valores em uma tabela temporária e depois listo ela com JOIN com outras tabelas.
   // E chamo a função novamente para pegar o próximo PAI.

   get_origem($con,$row['origem']);

}

// SUA FUNCAO ORIGINAL MAS COM NOME DIFERENTE
// pois está buscando o destino a partir da origem
function get_destino($con,$origem){

   $sql = "SELECT * FROM tabela WHERE origem = '$origem'";

   $movimentacao = ifx_query($sql,$con) or die(ifx_errormsg());

   $row = ifx_fetch_row($movimentacao);

   // Aqui insiro os valores em uma tabela temporária e depois listo ela com JOIN com outras tabelas.
   // E chamo a função novamente para pegar o próximo filho.

   get_origem($con,$row['destino']);

}

Sql Pai e Filhos na Mesma Tabela


Change img source in React using onMouseEnter while having a default picture

Question: I am currently working on this where i have 4 buttons and each of them changes the image in a separate div. I have almost done it, though when the page reloads the image is blank and shows only when i hover over a button. I want the picture to be defaulted to the first option on page reload.
function App() {
  const [image, setImage] = useState('')

  return (

      <button type="button" onMouseEnter={() => setImage(image1) }></button>
      <button type="button" onMouseEnter={() => setImage(image2) }></button>
      <button type="button" onMouseEnter={() => setImage(image3) }></button>
      <button type="button" onMouseEnter={() => setImage(image4) }></button>

    );
  }
export default App;

Answer: Currently the default initial value is an empty string:
const [image, setImage] = useState('')

Change it to one of the values you want to use:
const [image, setImage] = useState(image1)


proper way to read user input from command line in java

Question: I was hoping to get some opinions regarding best practices and comments on the way I read user input from the command line. Is there a recommended way to do this, am I using the try/catch blocks properly?
My example here works fine, but would still like to hear if there is a 'cleaner' way to do this. Many thanks. For example are he return statements in each catch block necessary?
Or, should I put my logic (the conditionals) within the try block?
public class Client {
<code>public static void main(String[] args) {
    begin();
}

private static void begin(){
    Machine aMachine = new Machine();
    String select=null;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while(aMachine.stillRunning()){
        try {
            select = br.readLine();
        } catch (IOException ioe) {
            System.out.println("IO error trying to read your selection");
            return;
        }catch(Exception ex){
            System.out.println("Error trying to evaluate your input");
            return;
        }

        if (Pattern.matches("[rqRQ1-6]", select)) {
            aMachine.getCommand(select.toUpperCase()).execute(aMachine);
        }
        /*
         * Ignore blank input lines and simply
         * redisplay options
         */
        else if(select.trim().isEmpty()){
            aMachine.getStatus();
        }
        else {
            System.out.println(aMachine.badCommand()+select);
            aMachine.getStatus();
        }
    }
}
</code>
}
Answer: I typically perfer to use the Scanner class to read from the input line. With the scanner class you are able to request specific types (double, int, ..., string). This will do validation testing for you as well.
I wouldn't recommend writing the input parsing in a way you did. Catching a generic Exception will catch anything, from a MemoryError etc. Stick with specific exceptions and deal with them from there. A Scanner will through an InvalidInputException (or something to that affect) if the input does not match the expected type.
Comment: So scanner does not require use of try/catch blocks and exception handling?
Comment: It doesn't require it, but it will throw them on bad input.


when an area of trapezoid ABCD reaches maximum , sum of two length of diagonal =?

Question: When an area of trapezoid ABCD reaches maximum , what is length  of sum two diagonal ?
Comment: Which of the points $A,B,C,D$ can you adjust to maximize the area?
Comment: It looks since the 30 degrees is written in, that only B and C are allowed to move over the semicircle. But the OP should make this clear in the question, and also state what seems to be so that the figure is a semicircle atop the diagonal of the circle with one endpoint being D.
Answer: Hint: Suppose we only move point $B$ at first. At the maximum area, point $B$ must be at the midpoint of arc $ABC$ since the trapezoid area is the sum of areas of triangle $ACD$ (which is fixed for now) and triangle $ACB$ whose area is 1/2 times the base $AC$ times the altitude from vertex $B$ over side $AC,$ and that is the most when $B$ is at the midpoint of arc $ABC$ since the midpoint of the arc is the furthest away from the base when measured vertically to the base.
By a similar argument, if we only move point $C$ we find it must be at the midpoint of arc $BCD$ when the trapezoid area is maximal. Combining these two facts we see that the points $A,B,C,D$ must, at the maximal trapezoid area, be equally spaced along the arc $ABCD.$ Now since the coordinates of $A,D$ can be found, some trig can get the coordinates of $B,C$ also, and from there one can compute the lengths of the two diagonals, hence their sum.


Inject service(s) into Drupal unit test?

Question: I am writing a unit test upfront for a service that does not exist yet. Let's just say it is called ResponseFormatter.
I want to start adding unit tests for what I expect this service to do. How do I inject it to a UnitTestCase, or reference it?
Example, I am trying to do something like:
class FormatterTest extends UnitTestCase {

  /**
   * @dataProvider responses
   */
  public function testThisWorks($response, $expected) {
    // the following line I want to call a service,
    // ex. like $this->responseFormatter->format($string);
    $clean = html_entity_decode(strip_tags($response));
    $this->assertEquals($expected, $clean);
  }

  public function responses() {
    return [
      ['not-set', 'not-set'],
      ['foo', 'foo'],
      ['& #93 bar', '& #93 bar'],
    ];
  }
}

Answer: If your new service is sufficiently independent (it doesn't have any or many of it own dependencies), then just create it the setUp().  And then if you have dependencies, you set up mocks (also called doubles).
An example of a this in core is TimeTest::setUp() does:
protected function setUp() {
  parent::setUp();

  $this->requestStack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->getMock();
  $this->time = new Time($this->requestStack);
}

A mocked request stack is created, and the setup then directly instantiates the service class being tested (Time() in this case), passing in the mocked dependency to the constructor.
Then assertions in test methods are pretty simple
public function testGetRequestTime() {
  $expected = 12345678;

  $request = Request::createFromGlobals();
  $request->server->set('REQUEST_TIME', $expected);

  // Mocks a the request stack getting the current request.
  $this->requestStack->expects($this->any())
    ->method('getCurrentRequest')
    ->willReturn($request);

  $this->assertEquals($expected, $this->time->getRequestTime());
}

The mock simulates what the service's dependency would do, and then the service method is invoked directly.
If your service has a lot of dependencies, or mocking them is hard, then you should do a KernelTest instead of a TestCase or UnitTest.  However, that may be an indication that your service is too complicated and needs to be broken up (I am also having a problem thinking of a core service that is kernel tested and not unit tested).