text:
Q: Use Boost to compute ECMA-128 64bit CRC With the following program I'm trying to compute a 64bit CRC as per the ECMA-128 standard.
The test data is "123456789" and I'm trying to match the same data provided here which suggests that the result for CRC-64/ECMA-182 should be 62ec59e3f1a4f00a. Unfortunately I get 9d13a61c0e5b0ff5 which is the CRC-64/WE result.
I started with the sample code provided here. I created the 64 bit hashes with the normal polynomial representation of 0x42F0E1EBA9EA3693 for the ECMA-128 64bit crc.

I get the following VS warning: C4293: '<<': shift count negative or too big, undefined behavior. It is for this macro:
BOOST_STATIC_CONSTANT( least, sig_bits = (~( ~(least( 0u )) << Bits )) );

As far as I can tell the 0 is being bit shifted by the full range of 64 bits which is undefined behavior. I'm surprised I don't see this warning for the 32bit crc.

How can this program be corrected to calculate an ECMA-128 64bit crc correctly without undefined behavior?
// from https://www.boost.org/doc/libs/1_67_0/libs/crc/crc.html#usage
#include <boost/crc.hpp>      // for boost::crc_basic, boost::crc_optimal
#include <boost/cstdint.hpp>  // for boost::uint16_t
#include <algorithm>  // for std::for_each
#include <cassert>    // for assert
#include <cstddef>    // for std::size_t
#include <iostream>   // for std::cout
#include <ostream>    // for std::endl

//#define SHOW_ERROR

#if defined( SHOW_ERROR )
#define CRC ecma_crc // expected
#else
#define CRC other_crc // actually received
#endif

int main()
{
    // This is "123456789" in ASCII
    unsigned char const  data[] = {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39};
    std::size_t const    data_len = sizeof(data) / sizeof(data[0]);

    // The expected CRC for the given data
    boost::uint16_t const  expected = 0x29B1;
    // Expected CRCs for "123456789" as per https://www.nitrxgen.net/hashgen/
    long long const  other_crc = 0x9D13A61C0E5B0FF5; // Wolfgang Ehrhardt http://www.wolfgang-ehrhardt.de/crchash_en.html
    long long const  ecma_crc = 0x62EC59E3F1A4F00A; // CRC-64-ECMA-128 https://en.wikipedia.org/wiki/Cyclic_redundancy_check

    // Simulate CRC-CCITT
    boost::crc_basic<16>  crc_ccitt1(0x1021, 0xFFFF, 0, false, false);
    crc_ccitt1.process_bytes(data, data_len);
    assert(crc_ccitt1.checksum() == expected);

    // Repeat with the optimal version (assuming a 16-bit type exists)
    boost::crc_optimal<16, 0x1021, 0xFFFF, 0, false, false>  crc_ccitt2;
    crc_ccitt2 = std::for_each(data, data + data_len, crc_ccitt2);
    assert(crc_ccitt2() == expected);

    // Attempt 64 bit CRC
    boost::crc_basic<64>  crc_64_ecma1(0x42F0E1EBA9EA3693, 0xFFFFFFFFFFFFFFFF, 0, false, false);
    crc_64_ecma1.process_bytes(data, data_len);
    assert(crc_64_ecma1.checksum() == CRC);

    boost::crc_optimal<64, 0x42F0E1EBA9EA3693, 0xFFFFFFFFFFFFFFFF, 0, false, false>  crc_64_ecma2;
    crc_64_ecma2 = std::for_each(data, data + data_len, crc_64_ecma2);
    assert(crc_64_ecma2() == CRC);

    std::cout << "All tests passed." << std::endl;
    return 0;
}

A: Look carefully at 62ec59e3f1a4f00a and 9d13a61c0e5b0ff5, digit by digit. Do you see a relation between those two?
Update:
Good! You saw it. (I hate to deprive others the joy of discovery.) As to why, you can look to Greg Cook's CRC catalog for the definition of the ECMA-182 CRC, referred to as simply CRC-64 there:
width=64 poly=0x42f0e1eba9ea3693 init=0x0000000000000000 refin=false refout=false xorout=0x0000000000000000 check=0x6c40df5f0b497347 residue=0x0000000000000000 name="CRC-64"

This defines the CRC with an initial value of zero, and a final exclusive-or of zero, i.e. no change. This is not common for CRCs, since it results in a string of zeros of any length having the same CRC, equal to zero.
CRC-64/WE is also defined there, which gives:
width=64 poly=0x42f0e1eba9ea3693 init=0xffffffffffffffff refin=false refout=false xorout=0xffffffffffffffff check=0x62ec59e3f1a4f00a residue=0xfcacbebd5931a992 name="CRC-64/WE"

This is more common, with an initialization and exclusive-or both with all ones, since the CRC of a string of zeros will depend on the length of the string, and the CRC of a zero length message is zero.
However that disagrees with the calculation at the link you provided. The link you provided calculated it with an initial value of zero, whereas the definition in Greg's catalog initializes the CRC with all ones. Only one of them is correct.
Update 2:
Greg's catalog is correct. The linked on-line hash calculator is wrong. I verified the CRC definition by looking at Wolfgang Ehrhardt's (the "WE" in CRC-64/WE) source code (a zip file). The linked calculator is doubly wrong, in that it gives the CRC-64/WE check value 62ec... as the CRC-64/ECMA-182 result, and it gives a result for CRC-64/WE that matches neither CRC-64. Beware of what you find on the interwebs.

A: Correct parameters for CRC
Boost has the following typedef for CRC-32/B/BZIP2/AAL5/DECT-B:
typedef crc_optimal<32, 0x04C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, true, true>
  crc_32_type;

Similarly the ECMA-128 64bit CRC requires a final xor value (3rd parameter):
boost::crc_basic<64>  crc_64_ecma1(0x42F0E1EBA9EA3693, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, false, false);
                                                                           ^^^^^^^^^^^^^^^^^^

Reason for warning message
The following template
template < std::size_t Bits >
class crc_basic

uses
template < std::size_t Bits >
struct mask_uint_t

and this mask_uint_t has been specialized for various numbers of bits:

*

*unsigned char  -> BOOST_STATIC_CONSTANT( least, sig_bits = (~( least(0u) )) );

*unsigned short -> BOOST_STATIC_CONSTANT( least, sig_bits = (~( least(0u) )) );

*unsigned int   -> BOOST_STATIC_CONSTANT( least, sig_bits = (~( least(0u) )) );
But the unspecialized version is different and triggers the undefined behavior warning:

*

*BOOST_STATIC_CONSTANT( least, sig_bits = (~( ~(least( 0u )) << Bits )));

On MSVC it still yields the correct value, but it should probably not be relied upon.


text:
Q: Optimize data calling in JDBC onto JTable currently I have data in MySQL server and I am calling the datas onto the JTable through JDBC. However there are 1369 rows and it seems that it has too much data for it to load. It usually takes 5 minutes to load. Are there anyways to optimize the process? This is my code(I apologize in advance for a messy code):
public class DataTable {
private String databaseName = "*****";
private String tableName = "******";
public void showDatabase(){
    Connection conn = null;
    DatabaseMetaData meta = null;
    Statement stmt = null;
    ResultSet rs = null;
    int k = 0;
    try{
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        String connectionUrl = "jdbc:mysql://localhost:3306/" + databaseName;
        String connectionUser = "*****";
        String connectionPassword = "*****";
        conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
        stmt = conn.createStatement();
        meta = conn.getMetaData();
        dataSets(stmt, meta);

    }catch(Exception e){
        e.printStackTrace();
    } finally{
        try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
        try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
        try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
    }
}

//return the column size of the table
public int getColumnNumber(DatabaseMetaData meta, Statement stmt) throws SQLException
{
    //ResultSet rs = meta.getColumns(null, null, "practiceexample", null);
    ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName);
    ResultSetMetaData rsmd = rs.getMetaData();
    int columnsNumber = rsmd.getColumnCount();
    return columnsNumber;
}

//return the rowNumber of the tables
public int getRowNumber(Statement stmt) throws SQLException
{
    ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName);
    int rowCount = 0;
    while(rs.next()){
        rowCount = rs.getInt(1);
    }

    return rowCount;
}

public void dataSets(Statement stmt, DatabaseMetaData meta) throws SQLException
{
    String[] columnNames = new String[getColumnNumber(meta, stmt)];
    String[][] dataSets = new String[getRowNumber(stmt)][columnNames.length];

    ResultSet column = meta.getColumns(null, null, tableName, null);

    int i = 0;
    while(column.next())
    {
        columnNames[i] = column.getString("COLUMN_NAME");
        //columnNames.add(i, column.getString("COLUMN_NAME"));
        i++;
    }

    for(int j = 0; j < dataSets.length; j++)
    {
        String[] singleRowData = new String[columnNames.length];
        ResultSet data = null;
        for(int k = 0; k < columnNames.length; k++)
        {
            String columnName = columnNames[k];
            data = stmt.executeQuery("SELECT " + columnName +
                    " FROM " + tableName + " LIMIT " + j + ", " + 1);
            while(data.next())
            {
                singleRowData[k] = data.getString(columnName);
            }

        }

        dataSets[j] = singleRowData;
    }

    SimpleTable table = new SimpleTable(columnNames, dataSets);
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            table.createAndShowGUI();
        }
    });
}

class SimpleTable{
    String[] columns;
    String[][] dataSets;

    public SimpleTable(String[] columns, String[][] dataSets){
        this.columns = columns;
        this.dataSets = dataSets;
    }

    public void createAndShowGUI(){
        JPanel gui = new JPanel(new BorderLayout(3, 3));

        final JTable table = new JTable(new DefaultTableModel(dataSets, columns));
        final JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
                , JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        Dimension dimension = table.getPreferredSize();
        scrollPane.setPreferredSize(new Dimension(dimension.width, table.getRowHeight() * 30));

        JPanel navigation = new JPanel(new FlowLayout(FlowLayout.CENTER));

        JButton next = new JButton(">");
        next.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                int height = table.getRowHeight() * (20-1);
                JScrollBar bar = scrollPane.getVerticalScrollBar();
                bar.setValue(bar.getValue() + height);
            }
        });

        JButton previous = new JButton("<");
        previous.addActionListener( new ActionListener(){
            public void actionPerformed(ActionEvent ae) {
                int height = table.getRowHeight()*(20-1);
                JScrollBar bar = scrollPane.getVerticalScrollBar();
                bar.setValue( bar.getValue()-height );
            }
        } );

        navigation.add(previous);
        navigation.add(next);

        gui.add(scrollPane, BorderLayout.CENTER);
        gui.add(navigation, BorderLayout.SOUTH);

        JOptionPane.showMessageDialog(null, gui);
    }
}

}

A: IMHO the root of the bad permormance is you unnecessarily query the database mutliple times to get the data (columns, rows, rows number, columns number, etc) you need:
To get columns number:
ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName);

To get rows number:
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName);

To get rows (this is the worst beacuse it's inside a loop):
data = stmt.executeQuery("SELECT " + columnName + " FROM " + tableName + " LIMIT " + j + ", " + 1);

How to solve it
Just query the database once. A single ResultSet and its associated ResultSetMetaData should be enough to accomplish your goal. Additionaly, and as already suggested, use a SwingWorker to do database calls in a separate thread. For example:
final JTable table = new JTable();

SwingWorker<Void, TableModel> worker = new SwingWorker<Void, TableModel> () {

    @Override
    protected Void doInBackground() throws Exception {

        ResultSet resultSet = stmt.executeQuery("SELECT * FROM " + tableName);
        ResultSetMetaData metaData = resultSet.getMetaData();

        int columnCount = metaData.getColumnCount(); // columns number
        String[] columnNames = new String[columnCount];
        for (int i = 1; i <= columnCount; i++) {
            columnNames[i] = metaData.getColumnName(i); // fill columns names
        }

        resultSet.last();
        int rowCount = resultSet.getRow(); // get rows number
        resultSet.beforeFirst();

        Object[][] data = new Object[rowCount][columnCount];
        int currentRow = 0;
        while (resultSet.next()) {
            for (int currentColumn = 1; currentColumn <= columnCount; currentColumn++) {
                data[currentRow][currentColumn - 1] = resultSet.getObject(currentColumn); // fill data set
             }
             currentRow++;
        }

        TableModel model = new DefaultTableModel(data, columnNames);
        publish(model);

        return null;
    }

    @Override
    protected void process(List<TableModel> chunks) {
        TableModel model = chunks.get(0);
        table.setModel(model);
    }
}

worker.execute();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Validating a string with given conditions I am asked to create a function that takes a string to check whether the string is valid or not.
A valid string has the following conditions.
Exactly 4 or 6 characters.
Only numerical characters (0-9).
No whitespace
My solution does not work.

function test(num){
  return num.length === 4 || num.length === 6;
}

console.log(test("123445"),true);

console.log(test("801264"),true);

console.log(test("451352"),true);

console.log(test("881234"),true);

console.log(test("as89abc1"),false);

console.log(test("    "),false);

console.log(test(" 4983 "),false);

console.log(test("123 "),false);

A: You are only checking the length of the string, and not if it consists of only digits.
You might also use a pattern to check for 4 or 6 digits

const test = num => /^(?:\d{4}|\d{6}$)/.test(num);

[
  "123445",
  "801264",
  "451352",
  "881234",
  "as89abc1",
  "    ",
  " 4983 ",
  "123 "
].forEach(s => console.log(`${s} ==> ${test(s)}`));


text:
Q: Android Keyhash for Facebook issues I along with my friend are developing a App which has login with Facebook. We both generated our own key hash and gave it while generating the AppId.
The problem is I can sign in through Facebook but my friend cannot. The login works perfectly for me but my friend is unable to login.I use Windows and my friends uses a Mac.
Does Facebook take only one key hash?
What may be the problem ?

A: Please check in the App Settings (in App Dashboard), that Sandbox Mode is disabled
Keyhash is not the issue if it is working for one user.


text:
Q: C# Generics typecast List to List< BaseType> How can i typecast List<Car> to  List<MyBaseClass>, In my code instance of List will go as an object (program requirement not intentional), by doing this i will retrieve vehicleId..
 public Form1()
    {
        List<Car> lstCar = new List<Car>();
        lstCar.Add(new Car() { Make = "tootay", Model = "camry", VechicleId = 1 });
        lstCar.Add(new Car() { Make = "honda", Model = "civic", VechicleId = 2 });
        VehicleConverter(lstCar);
    }
    public void VehicleConverter(object obj)
    {
      //Want to typecast it to List<MyBaseClass>
    }
}

public class MyBaseClass
{
    public int VechicleId { get; set; }
}

public class Car:MyBaseClass
{
    public string Make { get; set; }
}

public class Bike : MyBaseClass
{
    public int CC { get; set; }
}

A: This is not possible.
Had it been possible, you would be able to write the following:
List<Car> carList = new List<Car>();
List<BaseClass> baseList = (List<BaseClass>)carList;
baseList.Add(new Bike());    //I just put a Bike into a List<Car>!

Alternatives:

*

*Declare the list as List<BaseCLass>

*Cast to a non-generic IList (not recommended)

*Cast to IEnumerable<BaseClass>, using .Net 4's covariance

*Pass a typed copy of the list:
VehicleConverter(lstCar.ConvertAll(c => (BaseClass)c));

A: You didn't mention if you're using .NET 4.0 or earlier, but if you are using .NET 4.0 then the new co-variance/contra-variance feature for generic interfaces may help you.
You've discovered that you can't cast List<Car> as List<MyBaseClass>, but with .NET 4.0 you can cast IEnumerable<Car> as IEnumerable<MyBaseClass>.
You could then call functions that require an IEnumerable<MyBaseClass> with your List<Car> as the parameter without doing any special conversion or casting code.
For example, this code works in .NET 4.0:
List<Car> lstCar = new List<Car>();
lstCar.Add(new Car() { Make = "tootay", Model = "camry", VechicleId = 1 });
lstCar.Add(new Car() { Make = "honda", Model = "civic", VechicleId = 2 });

VehicleConverter(lstCar);

public void VehicleConverter(IEnumerable<MyBaseClass> vehicles)
{
    var found = vehicles.Where(v => v.VechicleId == 123);
}

I hope this helps.

A: And the reason why this is not possible is because you could runtime errors like this:
var cars = new List<Car>();
var vehicles = (List<MyBaseClass>)cars; // Not possible, but assume it was
vehicles.Add(new Bike());  // Runtime fail because now you are trying to add a bike to a list of cars

A: public List<MyBaseClass> VehicleConverter<T>(List<T> obj)
    where T : MyBaseClass
{
    return obj.Cast<MyBaseClass>().ToList();
}

A: You could try using the "IEnumerable.Cast<T>()" extension method from the System.Linq namespace.
Here is a link to the msdn documentation: http://msdn.microsoft.com/en-us/library/bb341406.aspx
Here is an example:
public void VehicleConverter(IEnumerable obj)
{
     IEnumerable<MyBaseClass> enumerable = obj.Cast<MyBaseClass>();
     List<MyBaseClass> list = enumerable.ToList();
}

A: This works
if (obj is List<Car>)
{
    List<MyBaseClass> c = ((List<Car>)obj).ToList<MyBaseClass>();
}

But you would need to do it for each type.  Ideally you should cast before passing to VehicleConverter.
Seems like an odd requirement though and would suggest @yodaj007 option if you are allowed to use that.

A: Even though i could not convert it to BaseClass, but i achieved my objective of retrieving the vehicleId by Casting & Reflection.
    public void VehicleConverter(object obj)
    {

        Type t = obj.GetType().GetGenericArguments()[0].GetType();
        IList lstVec = ((IList)obj);
        foreach (var k in lstVec)
        {
            PropertyInfo[] p = k.GetType().GetProperties();
            foreach (PropertyInfo pi in p)
                if (pi.Name == "VechicleId")
                    MessageBox.Show(Convert.ToString(pi.GetValue(k, null)));
        }
    }


text:
Q: How do i reduce the transparency of color for one group in ggpubr? How do I change the transparency of a group in ggpubr plots.
example dataset
library(ggpubr)
# Load data
data("mtcars")
df <- mtcars
df$cyl <- as.factor(df$cyl)
head(df[, c("wt", "mpg", "cyl")], 3)

data is:
               wt    mpg    cyl
              <dbl> <dbl>   <fct>
Mazda RX4     2.620  21.0   6
Mazda RX4 Wag 2.875  21.0   6
Datsun 710    2.320  22.8   4

I tried to create the plot with regression line using following code:
ggscatter(df, x = "wt", y = "mpg",
          add = "reg.line", add.params = list(color = "white", fill = "blue"),
          conf.int = TRUE, # Add confidence interval
          cor.coef = TRUE, # Add correlation coefficient
          cor.coeff.args = list(method = "pearson"),
          color = "cyl", shape = "cyl",
          palette = c("#FF0000", "#0000FF", "#00FF00"),
          ellipse = TRUE
         )
# ggsave('test.png', width=6, height=6, units="in", dpi=300)

It gave me an output as follows:

I want to make red color more transparent from this figure.

A: This is an interesting one. There is an ellipse.alpha argument which should allow you to assign a vector of values. However, if you create a column of alpha values with df$ellipse_alpha  <- ifelse(df$cyl==4, 0.01, 0.2) and try to assign this to ellipse.alpha it throws an error:
`geom_smooth()` using formula 'y ~ x'
Error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (156): alpha

I am not entirely sure where 156 comes from as the data is 32 rows. However, we can get around this by editing the underlying plot data with ggplot_build():
# Assign plot (same code as yours) to p
p  <- ggscatter(df, x = "wt", y = "mpg",
          add = "reg.line", add.params = list(color = "white", fill = "blue"),
          conf.int = TRUE, # Add confidence interval
          cor.coef = TRUE, # Add correlation coefficient
          cor.coeff.args = list(method = "pearson"),
          color = "cyl", shape = "cyl",
          palette = c("#FF0000", "#0000FF", "#00FF00"),
          ellipse = TRUE
         )

# Look at each layer and find the one which is
# stat_ellipse - in this case [[3]]
print(p$layers)
# [[3]]
# mapping: x = ~wt, y = ~mpg, colour = ~cyl, group = ~cyl, fill = ~cyl
# geom_polygon: na.rm = FALSE
# stat_ellipse: type = norm, level = 0.95, segments = 51, na.rm = FALSE
# position_identity

Once we know which layer it is we need to edit we can change the alpha of the underlying data:
# Get data
plot_data  <- ggplot_build(p)

# Edit the alpha in the desired group (1 in this case)
plot_data[["data"]][[3]]$alpha  <- ifelse(
    plot_data[["data"]][[3]]$group == 1,
    0.02,
    0.2
)

# Convert to grob
grob  <- ggplot_gtable(plot_data)

# Draw grob as plot
as_ggplot(grob)

A: You can change the alpha by changing the ggplot object itself rather than changing the grobs after the plot is built. This keeps the legend consistent with the plot, and allows you to modify theme elements, scales etc
library(ggpubr)

data("mtcars")
df <- mtcars
df$cyl <- as.factor(df$cyl)

p <- ggscatter(df, x = "wt", y = "mpg",
          add = "reg.line", add.params = list(color = "white", fill = "blue"),
          conf.int = TRUE, # Add confidence interval
          cor.coef = TRUE, # Add correlation coefficient
          cor.coeff.args = list(method = "pearson"),
          color = "cyl", shape = "cyl",
          palette = c("#FF0000", "#0000FF", "#00FF00"),
          ellipse = TRUE
         )

p$layers[[3]]$aes_params <- list()
p$layers[[3]]$mapping <- aes(wt, mpg, color = cyl, fill = cyl, group = cyl,
                             alpha = cyl)
p <- p + scale_alpha_manual(values = c(0.02, 0.2, 0.2), name = "cyl")

p


text:
Q: MySQL - IF statement to hide a column I have a form that uses a radio button, this button decides if it shows a piece of data or not:
<input type="radio" name="IncludeData" value="1" />Yes
<input type="radio" name="IncludeData" value="0" />No

Yes = 1 and No = 0.
I'm then using this query to call the data:
$IncludeData = $_POST['IncludeData'];
$sql = "SELECT data1, data2, data3, IF($IncludeData='0',Null,data4), data4, data5 FROM Database ORDER BY data1 asc";

I've tried following the answer from this question: MYSQL hide field data if value in another field is set.
However, it always seems to keep the data no matter what I select on the radio button. Any help would be greatly appreciated.
This is where I grab the data from:
<td>
Sort table on =
<select name="Sort">
<option value="data1" selected="selected">Example1</option>
<option value="data2">Example2</option>
<option value="data3">Example3</option>
<option value="data4">Example4</option>
<option value="data5">Example5</option>
</select>
</td>

A: What about something like this?:
$IncludeData = $_POST['IncludeData'] ? 'data4, ' : '';
$sql = "SELECT data1, data2, data3, $IncludeData data5 FROM Table ORDER BY data1 ASC";


text:
Q: Print to client side on window.load I'm trying to print to the client's printer immediately upon a page loading, using the following:
function openWin() {
    var printWindow = window.open();
    printWindow.document.write('<title>Test Page</title>');
    printWindow.document.write('');
    printWindow.document.write("Name: <?php echo $firstname . " " . $lastname; ?>
Spouse: <?php echo $sfirstname . " " . $slastname; ?>
Address: <?php echo $_POST['address'] ?>
City/State/Zip:  <?php echo $_POST['city'] . ", " . $_POST['state'] . " " . $_POST['zip'] ?>
");
    printWindow.document.write('');
    printWindow.document.close();
    printWindow.focus();
    printWindow.print();
    printWindow.close();
}

To get the function to fire, I'm using
$(window).load(function(){
    openWin();
});

When the document opens, nothing prints - i.e., the openWin() function doesn't fire.  I've tried creating a button for it and using trigger to click the button when the window loads. I've also tried setTimeout() to delay a while so the page can continue loading, etc.   Nothing works.
I get this error at the console:

application2.php:240 Uncaught TypeError: Cannot read property 'document' of null

BUT, when I simply enter openWin() at the console, the print page opens properly.
Any help would be appreciated.

A: Keep in mind that most browsers blocks popups when these are not triggered by an user action like a click.
A way to do it, is calling the 'window.print' in the load event and finally make a redirect to some page that you need.
<!DOCTYPE html>

    <title></title>

A: It worked when for me when i replaced $(window).load with $(document).ready. $(window).load works when dom loaded completely. and $(document).ready works when everything is loaded (img etc...)


text:
Q: How do you set an environment variable? Please explain how to set environment variables. I need to point an environment variable to a xml file.

A: In the sh type of shell:
 YOURVARIABLE='/path/to/file'
 export YOURVARIABLE

In a csh type of shell:
 setenv YOURVARIABLE '/path/to/file'

A: To set System-wide environment variables add name-value pair in /etc/environment file(YOUR_VARIABLE=/path/to/file).
Source: http://www.eguys.org/2012/04/system-wide-environment-variables.html


text:
Q: Webkit ignores vertical-align for inline-blocks containing line-boxes When Webkit (Safari, Chrome) encounters an inline-block where...

*

*the line-height height is specified

*the content is rendered using multiple line-boxes

...the inline-block element ignores the specified vertical-align.
To help illustrate the problem, I have a small test case:
http://arther.net/lab/webkit-vertical-align-test.html#test

Firefox 3.6, Opera 10.53, and IE7+ treat these inline-blocks like inline elements, and vertical align works as expected. Webkit browsers (and Opera 10.10) treat the inline-blocks in this situation like block-level elements, thus ignoring vertical-align. So, who is right, and who is buggy?
I can see this going either way. On one hand, you can say that all inline elements — even inline-blocks — should position themselves properly within the containing line-box as per vertical-align. On the other hand, inline elements usually define a single inline-box and don't have line-boxes of their own. Anything wrapping multiple line-boxes should be a block-level element. In that case, the inline-block should be treated as a block, which would thus ignore vertical-align.
Given the current behavior, I figure that one of the following is true:

*

*this is a Webkit bug

*this is a bug in all other rendering engines

*the spec is vague about handling this particular situation, and different approaches are being taken

If anyone could provide some clarification on the issue and what the expected behavior should be, I would greatly appreciate it.

A: This looks like a bug, since it works when the section takes only one line.
Chrome and Safari has a function where you can Report bugs to help their developers fix it.


text:
Q: Unable to run test in Chrome with Specflow I am trying to run my specflow test in Chrome Browser. Every time I runs, following error comes:

Autofac.Core.DependencyResolutionException : An exception was thrown while invoking the constructor 'Void .ctor()' on type 'ChromeDriver'. ---> unknown error: unrecognized Blink revision: 3b3c00f2d95c45cca18ab944acced413fb759311
    (Driver info: chromedriver=2.10.267521,platform=Windows NT 6.3 x86_64) (See inner exception for details.)
    ----> System.InvalidOperationException : unknown error: unrecognized Blink revision: 3b3c00f2d95c45cca18ab944acced413fb759311
    (Driver info: chromedriver=2.10.267521,platform=Windows NT 6.3 x86_64)
  TearDown : System.NullReferenceException : Object reference not set to an instance of an object.

However when I ran the same script for IE, it runs fine. Only with Chrome driver it gives an error. Also every dependency (all *.dlls), chromedriver.exe  are part of the solution. I am running my test in VS 2013.
Does anyone have the idea what could be the crux of this issue?

A: I had the same problem this morning. It appears there may have been an update to Chrome making the driver non-compatible. I downloaded and replaced the Chrome driver with the latest one here

A: When firsttime i try ChromeDriver i also get that error message. The problems because when using nuget to install ChromeDrvier. i choose wrong one. When you search ChromeDriver there may be 4 or 5 items has same name. **Select "Chromium.ChromeDrier" version 2.21.0 is work for me**
Update: I'm not use Specflow. I use visual studio - selenium. But i think this error will same


text:
Q: PersistentRef of keychain item on macOS catalyst Background
I'm trying to build an app that connects to VPN using native IKEv2 implementation. The app should be built for iOS but run on macOS as well by using Catalyst platform.
Situation
When connecting to VPN using native IKEv2 implementation in iOS/macOS - to use username and password authentication, app has to pass a persistent keychain reference to a keychain item containing the password. (Reference)
Problem
On iOS it works perfectly, but when initiating VPN connection on Catalyst platform, VPN service cannot retrieve the password using given persistent reference. Console prints:
[] (null): Failed to copy content, SecKeychainItemCopyContent returned The contents of this item cannot be retrieved.

The keychain item is stored in the keychain, persistent reference is not nil, but for some reason, OS's VPN service couldn't retrieve the password.
If I try to retrieve the password using that same persistent reference - everything works as expected and the password is retrieved.
let query: [String: Any] = [
    kSecClass as String: kSecClassGenericPassword,
    kSecAttrPersistentReference as String: persistentRef,
    kSecReturnData as String: true
]

var item: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &item)

Any information will be highly appreciated. Maybe some flags should be added when saving password to keychain? Maybe some flags should be added when retrieving the persistent reference from keychain specifically on Catalyst platform?

A: I asked this question directly through Apple's feedback support, the answer I was given is:


text:
Q: Cant delete or rename folder or excel file after it opens How to find what is blocking file or folder from being deleted or renamed?
After i open my Excel file and when close it i cant delete or rename nor folder nor this excel file.
Unlocker 1.9.2 do not find locking decriptor.
There are any ways to unblock file or folder or find which program is using it?
I cant restart PC after each time i opening the file.

I just installed Proccess Explorer and search for my folder name
it shows me what fonts which i attach on workbook open is locked by System
Private Sub Workbook_Open()
    AddFontResource ThisWorkbook.Path & "\AGENCYR.TTF"
    AddFontResource ThisWorkbook.Path & "\AGENCYB.TTF"

End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
    RemoveFontResource ThisWorkbook.Path & "\AGENCYR.TTF"
    RemoveFontResource ThisWorkbook.Path & "\AGENCYB.TTF"
End Sub

And my folder is locked by explorer.exe
So how to unblock thoose decriptor on Excel closing?


text:
Q: why does function() need to be typed before the function name when using onkeydown in javascript? I'm pretty new to javascript, and I was practicing a bit with events on W3Schools. In their tutorial, they show this line of code:

document.getElementById("demo").onkeydown = function() {myFunction()};

function myFunction() {
  document.getElementById("demo").style.backgroundColor = "red";
}

I don't understand why you have to type function() {function name()} rather than just typing the function you are trying to call. Basically, I'm not understanding the logic behind that line of code. Can someone please explain it to me?

A: You don't need function, you can just put the function name there.

document.getElementById("demo").onkeydown = myFunction;

function myFunction() {
  document.getElementById("demo").style.backgroundColor = "red";
}
<input id="demo">

You would need to wrap it inside another function if you wanted to do more than just call the function directly.

document.getElementById("demo").onkeydown = function() {
  console.log("Keydown");
  myFunction();
};

function myFunction() {
  document.getElementById("demo").style.backgroundColor = "red";
}
<input id="demo">

A: You can do it, you must pass it as reference:
document.getElementById("demo").onkeydown = myFunction(); - myFunction will be called immediately and not as callback. Callback would be return value of myFunction.
You them assign it as reference:
document.getElementById("demo").onkeydown = myFunction - note that you can't pass parameters at runtime here!

A: In the example you give:

document.getElementById("demo").onkeydown = function() {myFunction()};

function myFunction() {
  document.getElementById("demo").style.backgroundColor = "red";
}

the value of the onkeydown property of an element must be a function - not a call to a function. So you could not have for example:
  document.getElementById("demo").onkeydown = myFunction();

What that would do would be to try to run myFunction and put the result from that into the onkeydown property.
Actually it would fail as at the time the system tried to run it that function doesn't yet exist.
What you could do is declare the function first and then use that as the value for the assignment.
function myFunction() {
  document.getElementById("demo").style.backgroundColor = "red";
}
document.getElementById("demo").onkeydown = myFunction;


text:
Q: is there any other way to avoid redrawing for the 2nd viewport? I have to add a second viewport (= like splitscreen) to allow the player to see an event somewhere else on the current level.
Is there any possibility to draw the event area without redrawing every things already drew ?
[EDIT]
RenderTarget2D is the key. Thx User1459910 for all.
It almost worked.
New questions :

*

*I've searched for a while and still don't find a tutorial about "Xna 2D camera with source and destination rectangle" if you have a link, i'd like to see it, please ♥

*Currently, the drawing code looks like this :
protected override void Draw(GameTime gameTime)
{

   /*
   ...
   here is the code to "draw" in the renderTarget2D renderAllScene object
   ...
   */

   //Let's draw into the 2 viewports
   spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, null, null, null, camera1.transform);
   spriteBatch.Draw(renderAllScene, viewport1.Bounds, Color.White);
   spriteBatch.End();
   if (EventIsRunning)
   {
      spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, null, null, null, camera2.transform);
      spriteBatch.Draw(renderAllScene, viewport2.Bounds, Color.White);
      spriteBatch.End();
   }

*The Viewport 1 is great. The camera follows the character but after moving the camera for a short distance, the map is cutted at 1280pixels i think. so it drew only 1280pixels of all the map. I don't know why. Maybe because i failed when i created renderAllScene = new RenderTarget2D. :x
        renderAllScene = new RenderTarget2D(GraphicsDevice, GraphicsDevice.PresentationParameters.BackBufferWidth, GraphicsDevice.PresentationParameters.BackBufferHeight);

*For the Viewport 2 : I need the source rectangle. I'll try it tomorrow.

A: I'll assume you are making a 2D game with NOTHING 3D at all.
Here is what you could do:
You need to render the whole map, and all game objects that appear on it, on a Texture. If you don't know how to render to a Texture, here is the procedure:

*

*Create a RenderTarget2D object

*On the Draw function, before you render anything, you must call the graphicsDevice.SetRenderTarget() method, and set the RenderTarget2D you created.

*After you are done rendering, call graphicsDevice.SetRenderTarget(null) to reset the render target to the default one. You must do it or you'll have problems!

*To render the RenderTarget2D, simply use SpriteBatch.Draw((Texture2D)renderTarget2D, position, color), being "renderTarget2D" of course the name of the RenderTarget2D you created.

Then, you use two 2D Cameras. One will display where the hero is, and the other one will display the event area.
A 2D camera is basically a trick with Source and Destination rectangles. The trick is to use a Source Rectangle to define the area that displays the hero and the area around it and use the main Viewport as the Destination Rectangle, and use another Source Rectangle to define the event area and another Destination Rectangle as the second Viewport.
If you have doubts, google about "XNA 2D Camera", and research about Source and Destination rectangles on the MSDN's article for SpriteBatch.Draw().


text:
Q: My browser doesn't load my images and js files in my symfony project I have a symfony project but the browser fail to load images and js files.
Here is how i call my js and images
<img width="300" src="{{ asset('assets/images/logos/logo.png') }}">

<script src="{{ asset('assets/js/Temp/iCheck/icheck.min.js') }}"></script>

and here is my assetic in config.yml
assetic:
    debug:          '%kernel.debug%'
    use_controller: '%kernel.debug%'
    filters:
        cssrewrite: ~
    assets:
        plugins_css:
            inputs:
                - '@TemplateBundle/Resources/assets/css/bootstrap.min.css'
                - '@TemplateBundle/Resources/assets/css/AdminLTE.min.css'
        plugins_js:
            inputs:
                - '@TemplateBundle/Resources/assets/js/jQuery-2.1.4.min.js'
                - '@TemplateBundle/Resources/assets/js/bootstrap.min.js'
                - '@TemplateBundle/Resources/assets/js/app.min.js'
                - '@TemplateBundle/Resources/assets/js/dashboard.js'

But the project works fine in the internet Explorer but not in chrome or Mozilla. have anyone faced the same problem ? am i missing something


text:
Q: Hidden functions in cells I have an Excel form with some hidden functions. I'm not an Excel person so I'm translating it into another program code but I need help in understanding how Excel converts dates and time to make an arithmetic operations.
Here is an example:
 Cell B5: 11/9/12
 Function
     =B5                =0.1/24           =D2+2415018.5+E2-$B$5/24
 D2: 11/9/12    E2: 0:06:00   F2: 2456240.96

So my problem is that I don't understand how Excel coverts D2 and E2 in the equation:
D2+2415018.5+E2-$B$5/24 so that I can write it in python code.
Would appreciate some clarification please!

A: I don't follow your example, but what you need to know is that Excel stores dates as the number of days since January 0, 1900 (not a typo). An hour is 1/24 of a day, a minute is 1/24/60, etc. See this for more.


text:
Q: Prove that LM is parallel to AB the question is the following:

The problem is equivalent to show that $M$ is a midpoint of arc $\widehat{AB}$. I made a diagram on geogebra (points $C$ and $P$ got confused, sorry):

It is not hard to prove $AMYX$ is cyclic. I was hoping to find some congruent triangles that would help, but it didn't quite work: $AM=MB$ and $MY=MT$ so I put my hope of finding congruence there. I didn't want to work with the second meeting of $PB$ and the left circle, because it seems unnecessary. Got a lot of stuff going on here: $C$ is the circumcenter of $\triangle MTY$, $AT \perp TX$
EDIT: we got a Protassov configuration! I think the incenter of $\triangle ABC$ (in the top image, $\triangle ABP$ in the bottom) has a nice alignment with $T$ and a midpoint of arc $AB$

A: Mirror the blue circle in the line $LM$. Then the line $BC$ is simply another common tangent line of two circles. In other words, we are really trying to show that the dashed line defined by the red lines in the picture below is parallel to the symmetry axis.
The key point is to show that two of the common tangent lines (the green and one of the reds in the picture below) intersect on the circle.

The first step is to apply circle inversion with respect to the dashed circle in the picture below. I have indicated the corresponding old and new objects with like colours.

We are left to show that the green circle, defined to touch one of the lines and one of the blue circles while going through the point of symmetry, touches the line in precisely the intersection point of the red circle with the line.
I have included a clearer picture below and gave some points names.
Starting with the rectangle, construct the red circle and hence the point $X$. Let $P$ be the projection of $B$ on $XC$ and define the green circle to be the circumcircle of $X$, $P$ and $M$. By Thales, to show that this satisfies all we want of the green circle, it suffices to show equality between the blue angles.

The proof is surprisingly short. Since $YD$ touches the red circle, we have $|YD|^2 = |YM||YX|$. By symmetry $|YD| = |XB|$, so we even have that $|XB|^2 = |XM||XY|$.
From the similarity between triangles $XPB$ and $XBC$, we get that $|XB|^2 = |XP||XC|$. Combining this with the previous, gives us that $|XP||XC| = |XM||XY|$. In other words, we have shown that $YMPC$ are all on a circle. We immediately find $\angle BXC = \angle YCP = \angle PMX$, as was to be shown.

A: Given two circles with centers $K$, $L$, externally tangent at $E$, with common tangent $AH$ and tangent $LM$, join $MA$, make chord $MB=MA$, and draw $BD$ tangent to the other circle.
Since triangle $ABM$ is isosceles, then $\angle BAM=\angle MBA$. And since $\angle LMA$ between chord and tangent is equal to $\angle MBA$ in the alternate segment, then$$\angle LMA=\angle BAM$$Therefore$$LM\parallel AB$$
Note: On this interpretation of the question and its conditions, tangents $AH$ and $BD$ are extraneous.  But even if the tangents are included, and $A$ is therefore not random, $B$ cannot be supposed random, but must be chosen such that triangle $ABM$ is isosceles. In other words, $M$ is the midpoint of arc $AMB$. Otherwise $LM$, which is given in position for the given circles, will not be parallel to $AB$. A fuller statement of the conditions in this question would be helpful.

Addendum:
In light of the clarifying comments, that the above solution misinterprets the question, let me offer at least a proof for the special case of equal circles.
In the figure below, with $F$ as the intersection of the tangent at $E$ with tangent $LM$, it is clear by symmetry that tangent $CBFD$ passes through center $K$.
Since hypotenuse $KL=2KM$, then $\angle MKL=60^o$.
And since $\angle FKL=\angle KLF=30^o$, therefore exterior $\angle KFM=60^o$.
Further, since $\angle AKB= 90^o-30^o=60^o$, then $\triangle AKB$ is equilateral, $$\angle ABK=60^o=\angle KFM$$and$$LM\parallel AB$$And it is clear in this case that $M$ is the midpoint of arc $AMB$.


text:
Q: Sorting Core Data I have some data with mixed of String and Integer like,
"003G"
"002P"
"001P"
"018P"
"002G"
"019P"
"001G"
"020P"
"012P"
"011P"
"012G"
"013P"
"007P"
"011G"
"010P"
"009P"
"008P"
"005P"
"006P"
"014P"
"007G"
"010G"
"009G"
"008G"
"015P"
"006G"
"005Ga"
"004P"
"016P"
"005G"
"004G"
"003P"
"017P"

Need output like :
"001P"
"002P"
"003P"
"004P"
"005P"
"006P"
"007P"
"008P"
"009P"
"010P"
"011P"
"012P"
"013P"
"014P"
"015P"
"016P"
"017P"
"018P"
"019P"
"020P"
"001G"
"002G"
"003G"
"004G"
"005G"
"005Ga"
"006G"
"007G"
"008G"
"009G"
"010G"
"011G"
"012G"

Same time Android done the sorting with *[0-9,0P-9P,0G-9G]

A: That's a very unusual sorting order. You have to write custom descriptors using a Comparator
Two descriptors are needed.

*

*Sort the fourth character descending
let sortDescriptor1 = NSSortDescriptor(key: "referenceNo", ascending: false) { (obj1, obj2)  -> ComparisonResult in
    let string1 = obj1 as! String
    let string2 = obj2 as! String
    let fourthChar1 = string1.index(string1.startIndex, offsetBy: 3)
    let fourthChar2 = string2.index(string2.startIndex, offsetBy: 3)
    return String(string1[fourthChar1]).compare(String(string2[fourthChar2]))
}

*Sort the first 3 characters ascending with numeric option and consider the xxxxa case
let sortDescriptor2 = NSSortDescriptor(key: "referenceNo", ascending: true) { (obj1, obj2)  -> ComparisonResult in
    let string1 = obj1 as! String
    let string2 = obj2 as! String
    let fourthChar1 = string1.index(string1.startIndex, offsetBy: 3)
    let fourthChar2 = string2.index(string2.startIndex, offsetBy: 3)
    let orderedResult = string1.substring(to: fourthChar1).compare(string2.substring(to: fourthChar2), options: .numeric)
    if orderedResult == .orderedSame {
        return string1.characters.count < string2.characters.count ? .orderedAscending : .orderedDescending
    } else {
        return orderedResult
    }
}

Of course this assumes that the values are strings with always 4 characters and more in the ASCII range.

A: NSArray *keysArray;  // your strings

Put every strings into an array and use code below
NSArray *sortedArray = [keysArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

Apple provides several selectors for alphabetic sorting:
compare:
caseInsensitiveCompare:
localizedCompare:
localizedCaseInsensitiveCompare:
localizedStandardCompare:

A: If you are using NSFetchRequest to query core data, then go ahead and add sort descriptor on fetchRequest like below :
fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"referenceNo" ascending:YES selector:@selector(caseInsensitiveCompare:)]];


text:
Q: Developing trading strategy using Pandas and Matplotlib I am trying to identify a bullish point, based upon the following formula:
Bullish  Bar  =  Today's  Low  <  Lowest  (Low  ,  13  Days)  AND  Today's  Close  >  (((Todays  High  –  Todays  Low)  /  2)  +  Today  Low)

Additionally, I want to calculate the average 2 day returns of a stock for a given time period ( say, 2010 to 2017 ). For example:
( Close ( Day 2 ) - Open ( Day 1 ) )/ Open ( Day1 )

I am using Pandas to source the data. This is how the data frame looks like:
              Date   Close      High       Low    Open     Volume
Symbol
SPY     2010-01-01  111.44  112.8000  111.3900  112.77          0
SPY     2010-01-04  113.33  113.3900  111.5100  112.37  118944600
SPY     2010-01-05  113.63  113.6800  112.8500  113.26  111579900

My objective is to create a separate column where, along side the date, the bullish point is indicated, so that I can plot it with a green arrow.
Currently, I am converting everything to lists, and am using the indices of the lists to calculate the returns; however, it is pretty tedious.
Is there a way to get this done in a simpler way?

A: If your dataframe is called df, and you want your result to be in a new column Return, you can use the following code to calculate the return:
df['Return'] = (df.Close.shift(2) - df.Open.shift(1)) / df.Open.shift(1)

To calculate the bullish signal, you can use the following method:
    df['bullishSignal'] = (df.Low < df.Low.shift(1).rolling(13).min()) &
                              (df.Close > ((df.High - df.Low) / 2 + df.Low))


text:
Q: What is the name of the data set used to calibrate FPR and FNR for a model? In spam classification domain, we often train the models on different sets than the production. Then we are faced with the problem of calibrating the models with ROC curves to find a proper cut-off point, and then contemplate the FPR and FNR.
What is the name of the labelled random sample from production that is used for such calibration? Internally I call it a "calibration dataset", but I have doubts if this is the established name. Google turned out empty.


text:
Q: Javascript compiler in C? I'm looking for a simple (preferably C-based) Javascript compiler that I can use to determine if a chunk of Javascript contains any syntax errors, and the location (line number) of those errors. Is there a small library that anyone knows of that I can use to do something like this?

A: The V8 isn't good enough for you?

A: You could also try SpiderMonkey by Mozilla


text:
Q: Android browser's drag event target not updating When I attach a handler to the drag event (I'm using Sencha Touch) on Android,
the event's target does not reflect the current element I'm pointing above,
For example, if my drag started on element1 and during the drag, I moved to element2,
the event does not reflect this change.
While desktop browsers do reflect it (Chrome, Safari)...
I tried probing these attributes of the event (ev):
ev.event.target.id
ev.targetTouches[0].target.id
ev.target.id
ev.touches[0].target.id
ev.browserEvent.target.id
ev.gesture.target.id
All of which work perfectly fine on the desktop...
Any idea how can I extract the identity of the element I'm currently dragging above?
Thanks!


text:
Q: preg_replace to change image path I need to replace in a php file some text from DB with preg_replace. The string to replace is:
images/

and change it to
cms/images/

I know it's simple but I just can't understand this syntax.

A: $new_string = str_replace('images/', 'cms/images/', $string);

A: Since the OP requested a solution using preg_replace() here's one. Otherwise the solution of @genesis is more than suitable.
$new_string = preg_replace('#images/#i', 'cms/images/', $string);
The above simply replaces images/ with cms/images/ in $string. The # symbols are delimiters which separate the expression from the modifiers. In this case the images/ and i respectively. The i makes it case insensitive.


text:
Q: SDK Location is not a directory I am using eclipse Kepler
Google app engine 1.8.8
Maven 3.1
I wanted to start working on my first Google App Engine (GAE) project in Eclipse. As always, I wanted to stick to maven with its great dependency management and WAR deployment. Unfortunately,
I got this error message.
So my question why eclipse cannot find SDK? I dont want to add external sdk.

A: I would suggest to try out the following:

*

*Go to your Eclipse Preferences -> Google -> App Engine. Make sure you are using the App Engine plugin SDK.

*Go to Java Project -> Properties. In the Order and Export, make sure that the Eclipse app Engine SDK is higher than the one that your Maven repository is pointing too.
Check this out : How to run maven project on google app engine


text:
Q: tcsh prompt acting weird I've got this line my .cshrc.user (using tcsh)
set prompt = "%{\033[36m%}%m%{\033[32m]%}{`echo $CLEARCASE_ROOT | cut -d / -f 3`}%{\033[0m%}> "

And it's working nicely with the colors and everything. But when I try this:
echo $prompt

It just gives me either
Missing ].

or
Missing }.

depending on wether a clearcase view is set or not.

A: At a guess, I'd say that the variable CLEARCASE_ROOT has a [ or a { character. Try quoting the variable when performing the echo? i.e.:
echo "$prompt"


text:
Q: Refreshing Form to update and save new entry in a combobox in Visual Studio/C# I have set up my program so that the user can enter a new line into the combo box via a text box on a separate form (Popup form). So far the program allows the new entry and closes the popup form when the user presses the "Accept" button however the entry does not appear in the combobox and the entry is not saved.
Currently the only way to view the new entry is by the .ShowDialog(); function which opens a second instance of the first form.
Form 2
namespace RRAS
{
    public partial class NewRFRPopup : Form
    {
        public NewRFRPopup()
        {
            InitializeComponent();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAccept_Click(object sender, EventArgs e)
        {
            formRRAS main = new formRRAS();
            string newRFR = txtNewRFR.Text;
            main.AddRFR(newRFR);
            this.Close();
            main.ShowDialog();
        }

        private void NewRFRPopup_Load(object sender, EventArgs e)
        {

        }
    }
}

AddRFR in Form 1
 public void AddRFR(object item)
        {
            cmbRFR.Items.Add(item);
        }

A: you are creating a new instance of your form1 in the accept handler:
formRRAS main = new formRRAS();

(which is why when you call showdialog you get another formRRAS appearing).
You need to pass the original formRRAS to the popup and call AddRFR on the instance passed through.  I'd pass it on the constructor of the popup - i.e.
public partial class NewRFRPopup : Form
{
formRRAS _main;

 public NewRFRPopup(formRRAS main)
 {
  InitializeComponent();
  _main = main;
 }

and then in your Accept handler:
 string newRFR = txtNewRFR.Text;
 _main.AddRFR(newRFR);
 this.Close();

and of course to show the popup from formRRAS
NewRFRPopup popup = new NewRFRPopup (this);
popup.ShowDialog();


text:
Q: Pillow image colors looking weird Pillow is pasting the profile picture on the base image, but the colors are looking weird. Here's the code:
from discord import file
from discord.client import Client
from discord.ext import commands
import discord
from PIL import Image
from io import BytesIO

class Test(commands.Cog):
    def __init__(self, client):
        self.client = client
    @commands.command()
    async def test(self, ctx, user: discord.Member = None):
        if user == None:
            user = ctx.author

        msg = await ctx.send('Generating profile, please wait!')
        img = Image.open('card.png')
        asset = user.avatar_url_as(size=128)
        data = BytesIO(await asset.read())
        pfp = Image.open(data).convert('RGB')
        pfp = pfp.resize((100,100))
        img.paste(pfp, (75,71))
        img.save('profile.png')

        file = discord.File('profile.png', filename='profile.png')
        await msg.delete()
        await ctx.send(file=file)

 This is the base image.
 This is the image after running the command.
Any help is appreciated


text:
Q: Open a new window for emacs from terminal in mac How do I get the emacs "graphical window" to pop up in a separate window when i type in 'emacs' in the terminal on Mac OSX? On linux when you type in emacs in an xterm window, it pops up a new window, but in OSX it opens in the terminal window.
For example, when I type in 'emacs SomeFile' it opens up/creates SomeFile within terminal when I'd like it to pop up a separate window like this:

A: I think the problem is that emacs for OS X doesn't have X window support in the version that is shipped.
So, alternatively, there's emacs for OS X. Or maybe you want Aquamacs, which is a bit more integrated into OS X.

Based on GNU Emacs, Aquamacs integrates perfectly with OS X thanks to its specially adapted user interface.


text:
Q: UITableview showing only certain rows All,
I have one table view it only shows the top 3 results. I have done this in XCODE by doing row size and tableview height.
I to be able to press a button (which is fine) and opened another view controller which is fine also and show another tableview without the top 3 results. So it only wants to show the reminder of the table rows. So if there is 20 in the array it needs to show 4 - 20. Anyone know how to do this ?

A: Just create a new array based on the existing one:
-(void)viewDidLoad{

    [super viewDidLoad];
    // TRIM THE ORIGINAL ARRAY HERE
    tableDataArray = [self arrayWithContentsOfArray:originalArray afterIndex:3];

}

-(NSMutableArray*)arrayWithContentsOfArray:(NSArray*)originalArray afterIndex:(int)index{

    NSMutableArray *desiredResultsArray = [NSMutableArray new];

    for ( int i = index; i < [originalArray count]; i++ ) {
        [desiredResultsArray addObject:[originalArray objectAtIndex:i]];
    }

    return desiredResultsArray;

}


text:
Q: Minimum normal form of a relation with all prime attributes If all the attributes of a relation are prime (part of a candidate key), which normal form would it be at least? 1NF, 2NF, 3NF or BCNF.
The question was already solved in slides as BCNF, but I don't understand why BCNF and not 3nf.


text:
Q: finite difference equations i havent had a response to this question in a while, could someone please help me. Im struggling to understand the concepts of forward/backward/central differences on finite difference equations.
i have formulas for:
first order with respect to x (spatial)- forward (explicit), backward(implicit) and central
second order with respect to x- forward (explicit), backward(implicit) and central
first order with respect to t (time)- forward (explicit), backward(implicit) and central
what are the formulas for second order with respect to t- forward (explicit), backward(implicit) and central?
i have a one second order equation for time but not sure what it specifys- is it the forward (explicit)?:
$$ \frac{d^2u}{dt^2} = \frac{u_{i}(m+1)-2u_{i}(m)+u_{i}(m-1)}{(\delta t)^2} $$
i know how to solve questions just need the second order equations with respect to time. thanks in advance for any help- been looking all over the web but not really getting a grasp. thanks.

A: From what I understood of your question, that is quite confusing.
A simple reference for formulas for finite differences, or their coeficientes, is found here in Wiki , for backward, forward and central.
Regarding being explicit, implicit:

*

*You didn't say where you want to apply those finite difference discretizations. What is the equation, depending on what you choose backward/forward/central for each term of your equation you get a implicit or explicit schema.
If you specify the equation will be easier, for example for the heat equation:
$$ U_t = \alpha U_{xx} $$
Using a forward difference at time and a second-order central difference for the space derivative at position $u_j$ (FTCS) we get explicit schema:
$$ \frac{u_j^{t+1}-u_j^t}{\Delta t} = \alpha \frac{u_{j+1}^t - 2u_j^t + u_{j-1}^t}{h^2} $$
where $ \Delta t $ is the discretization in time and $ h $ in space.


text:
Q: How to get legacy COM path from Interop assembly I have interop assembly from I wolud like to get path to orginal COM dll. How this can be done?
Edit:
Here is similar question with post marked as answer but it is so brief that I still don't know what to do.
I have created object from interop dll and used GetModuleHandle( "mycomserver.dll" ) and 0 results returned.
Code looks like that:
class Program
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern IntPtr GetModuleHandle(string libname);

    static void Main(string[] args)
    {
        IntPtr result = GetModuleHandle(typeof(InteropClass).Module.Name);
        Console.WriteLine(result);
    }
}

Regards,
jotbek


text:
Q: Preg match question I'm sure someone already asked this question, but after searching for more than 1 hour on google, I decided to ask my question here.
I want to itterate over an array excisting of different strings/texts.
These texts contain strings with both ##valuetoreplace## and #valuetoreplace#
I want to make to preg_matches:
$pattern = '/^#{1}+(\w+)+#{1}$/';
if(preg_match($pattern, $value, $matches, PREG_OFFSET_CAPTURE))
{
   // do something with the #values#
}

AND
$pattern = '/^#{2}+(\w+)+#{2}$/';
if(preg_match($pattern, $value, $matches, PREG_OFFSET_CAPTURE))
{
   //do something with the ##value##
}

This works great.
Now my only problem is as follows:
When i have a string like
$valueToMatch = 'proceding text #value#';

My preg_match cant find my value anymore (as i used a ^ and a $).
Question: how can i find the #value# and the ##value##, without having to worry if these words are in the middle of a (multi-line) value?
*In addition:
What i want is to find patterns and replace the #value# with a db value and a ##value## with a array value.
For example:
$thingsToReplace = 'Hello #firstname# #lastname#,
How nice you joined ##namewebsite##.';

should be
'Hello John Doe,
How nice you joined example.com.'

A: Try this: /##([^#]+)##/ and /#([^#]+)#/, in that order.

A: Maybe nice to know for other visitors how i did it:
foreach($personalizeThis as $key => $value)
{
   //Replace ##values##
   $patternIniData = '/#{2}+(\w+)#{2}/';
   $return = 'website'; //testdata
   $replacedIniData[$key] = preg_replace($patternIniData, $return, $value);

   //Replace #values#
   $pattern = '/#{1}+(\w+)#{1}/';
   $return = 'ASD'; //testdata
   $replacedDbData[$key] = preg_replace($pattern, $return, $replacedIniData[$key]);
}

return $replacedDbData;


text:
Q: How Does Formal Derivative Algebraically Affect the Roots of Polynomial? So it's easy to say that if $\alpha\in\mathbb{A}$ is a repeated root of $f(x)\in\mathbb{A}[x]$ then $\gcd(f',f)(\alpha)=0$. Conversely, also easy to verify that if $\beta$ is a simple root then it will no longer be a root of $f'$. For characteristic-p field, e.g. $\bar{\mathbb{F_q}}$, assuming the multiplicity not divisible by $p$ is sufficient for the equivalence to hold.
However, by degree counting, there might be some other $\gamma$ that is a root of $f'$ but not $f$. As long as the total number of original root decrease by more than 1, we will inevitably get new roots (under closure). Specifically, for characteristic-p field, the multiplicity is p multiple if and only if the $f'$ multiplicity will decrease. Otherwise, there might be additional multiplicities introduced through derivative of another component. For characteristic 0 field, the newly introduced roots is up to the number of irreducibles minus one, with multiplicity counted.

Getting here, one natural question to ask is that. Which roots exactly are being introduced by derivative? Is there an algebraically canonical way to describe them in terms of the original roots? Usually with topology added in, we could have geometric interpretation for this, but for general case it just not work.


text:
Q: How to add items from fragment to sql and spinner in android Please help, can't solve this. I can't add items from fragment to my sql database and to spinner in another class. The main idea is to add items permanently to spinner (or until I manually delete it) so when I close my app and open it again it should be there. I am beginner and I can't find solution to this problem. I checked lots of similar posts but I am really confused and don't know how to make it work. Here is some of my code:
I created spinner in my main activity:
spinner= (Spinner)findViewById(R.id.spinner);
    spinner.setOnItemSelectedListener(this);
    loadSpinnerData();

    public void loadSpinnerData() {
            MyDBHandler db = new MyDBHandler (getApplication());
            ArrayList<projectNames> list = db.getAllLabels();
            ArrayAdapter<projectNames> adapterFrom = new ArrayAdapter<projectNames>(this,android.R.layout.simple_spinner_item, list)
            {
                @Override
                public View getView(int position, View convertView, ViewGroup parent)
                {
                View view = super.getView(position, convertView, parent);

                // Get item at position
                projectNames model = getItem(position);
                // Set textview's value with the category name
                TextView textView = (TextView) view.findViewById(android.R.id.text1);
                textView.setText(model.get_name());

                return view;
                }
            };
            adapterFrom.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(adapterFrom);
     }

Now when I open new dialog fragment I want on buttonclick to add items to spinner in previous class and to my SQL database (or to my SQL and then from it to spinner - whatever is better/easyer):
Code for Sql:
public class MyDBHandler extends SQLiteOpenHelper{

 private static final int DATABASE_VERSION=1;
    private static final String DATABASE_NAME="projects.db";
    private static final String TABLE_PRODUCTS="projects";
    private static final String COLUMN_ID="_id";
    private static final String COLUMN_PRODUCTNAME="name";

    public MyDBHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

I got rest of regular methods for Sql but don't want to post it here atm becouse it will be bunch of code. If something is needed, please ask.
Code I have so far for adding items to spinner from fragment:
MainActivity newSpinner = new MainActivity();
                addThisToSpinner = newSpinner.spinner;
                newSpinner.loadSpinnerData();

I tried to instantiate my new activity and to call it and to add dynamically one item to spinner but don't know how exactly. Adding items if they are in the same class is not a problem. Problem is how to call handler(spinner) from another activity (fragment). How does it effect adapter options?
Please help

A: Spinner can use SimpleCursorAdapter as Adapter. When you want to add new value to your spinner, you add new value to DB, then refresh the adapter cursor, it will load new value to your spinner.


text:
Q: How to reset GridFilter in extjs This is what I am doing:
this.TabPanel.Grid.getStore().clearFilter (false);
alert(this.TabPanel.Grid.getStore().isFiltered());

and the alert shows: false. When I go on the page, I see that the filter is still selected(checked) and the results are also fitlered. What I am missing?
EDIT:Can I get a handle to the gridfilter object through my store? If yes, I can call the gridfilter.clearFilters().

A: How is that code running? Can you post a more complete example? If you have some component that is a user is using to set the filter(like some check box or something), you will still need to clear that manually as well.


text:
Q: TaskList of GitHub Flavored Markdown doesnt support ordered lists I noticed that there is a way to add tasklist in GFM, as mentioned in their blogpost here, https://github.com/blog/1375-task-lists-in-gfm-issues-pulls-comments
However it doesnt show any examples for task list for a ordered list. Is it supported? If so, can somebody share an example.

A: No, it's not supported. You can write an ordered list of checkboxes like this:
1. [ ] Foo
2. [ ] Bar

It renders as an ordered list in HTML (
), but their stylesheet removes the numbers.
So while you can express the list as an ordered list, you would need your own stylesheet to render it as such.

A: Note: since the introduction of nested task list (May 2014), numbered task list are still not supported, even though the following would still be rendered with
 elements:
1. [ ] Figure out wormholes
  1. [ ] Call @arfon
  2. [ ] Research ([docs](http://en.wikipedia.org/wiki/Wormhole#Time_travel))
  3. [ ] Build prototype #15
  4. [ ] Test run #43 @world-domination/time-travel
2. [ ] ...?
3. [ ] Profit!

And that would give:

As in:

        <input class="task-list-item-checkbox" type="checkbox" disabled=""></input>

         Figure out wormholes


text:
Q: Using Workbook.Sheets.Range to reference file path in Excel First, is what I'm doing here logical?
Second, I keep getting an error on my single quote that begins my filepath.
stuff = Workbooks('\\public\Documents\Amazon Retail\Analysis\[US Retail Quick Reference.xlsx]').Sheets("Quick Reference").Range("A1")

A: Assuming you have a single instance of Excel, and are not using multiple instances of Excel:
If that file is already open, you have to reference it by its name only, not the full path. If the file isn't yet open, you need to open it first (and then refer to it by its name only).
Change this:
stuff = Workbooks('\\public\Documents\Amazon Retail\Analysis\[US Retail Quick Reference.xlsx]').Sheets("Quick Reference").Range("A1")

To This:
stuff = Workbooks("US Retail Quick Reference.xlsx").Sheets("Quick Reference").Range("A1")

Ensure stuff is declared as a String or possibly as a Variant type (in case A1 might contain non-text or error values).
If you don't know at runtime whether the file is or may be open, then you can fancify your code like so:
Function IsWorkbookOpen(path as String, name as String) As Boolean
    Dim wb as Workbook
    On Error Resume Next
    Set wb = Workbooks(name)
    If wb.FullName = path & name Then
        IsWorkbookOpen = True
    End If
End Function

And then do like:
Dim path as String, fileName as String
path = "\\public\Documents\Amazon Retail\Analysis\"
fileName = "US Retail Quick Reference.xlsx"
If (IsWorkbookOpen(path & fileName)) Then
    stuff = Workbooks(fileName).Sheets("Quick Reference").Range("A1").Value
Else
    ' Do Something Else // UNTESTED:
    stuff = ExecuteExcel4Macro("'" & path & "[" & fileName & "]" & _
          "Quick Reference'!" & Range("A1").Address(True, True, -4150))

    ' or:
    ' Dim wb as Workbook
    ' Set wb = Workbooks.Open(path + fileName)
    ' stuff = wb.Sheets("Quick Reference").Range("A1").Value
    ' wb.Close

End If

For the "Something Else", I'd recommend using the ExecuteExcel4Macro method for obtaining value from a closed workbook.


text:
Q: Allow only one slide toggle div to show at a time I am working on a site where I have 4 expandable divs using jquery's slide toggle. All works fine but I don't want more than 1 of those divs expanded at a time. In other words: when a div is expanded, other divs that are expanded should close. Accordion isn't an option I think because all the div's styling is different. Below is my code.
$(document).ready(function(){
// slidetoggles

    $("#tgx-window").hide();
        $("#tgx-button").show();
        $("#tgs-window").hide();
        $("#tgs-button").show();
        $("#tgm-window").hide();
        $("#tgm-button").show();
        $("#tgl-window").hide();
        $("#tgl-button").show();

    $('#tgx-button').click(function(){
    $('#tgx-button').toggleClass('closebutton');
    $("#tgx-window").slideToggle();
    });

    $('#tgs-button').click(function(){
    $('#tgs-button').toggleClass('closebutton');
    $("#tgs-window").slideToggle();
    });

    $('#tgm-button').click(function(){
    $('#tgm-button').toggleClass('closebutton');
    $("#tgm-window").slideToggle();
    });

    $('#tgl-button').click(function(){
    $('#tgl-button').toggleClass('closebutton');
    $("#tgl-window").slideToggle();
    });

HTML:
<a onclick="" class="show_hide" id="<?=strtolower($service['title']);?>-button">
        <div class="slidingDiv" id="<?=strtolower($service['title']);?>-window">
            <?
            $infoBox = '
'.$service['subtitel'].'
';
            $infoBox .= $service['description'];
            echo replaceTags($infoBox);
            ?>

A: It's a bit hard to answer this question without knowing your HTML but here is a solution I hope;
HTML (I presume):

tgx window

tgs window

tgm window

tgl window

<button id="tgx-button">Show tgx</button>
<button id="tgs-button">Show tgs</button>
<button id="tgm-button">Show tgm</button>
<button id="tgl-button">Show tgl</button>

JavaScript:
jQuery(function($) {
    var $windows = $('#tgx-window,#tgs-window,#tgm-window,#tgl-window'),
        $buttons = $('#tgx-button,#tgs-button,#tgm-button,#tgl-button');
    $windows.hide();

    $buttons.on('click', function(e) {
        var $id;
        e.preventDefault();
        $buttons.removeClass('closebutton');
        $id = $('#' + this.id.split('-')[0] + '-window');// Get window id
        $windows.slideUp();
        if(! $id.is(':visible') ) {
            $id.slideDown();
            $(this).addClass('closebutton');
        }
    });
});

You can see a working example here.

A: Use class instead of id of button and probably its parent .tgx-window
$('.tgx-button').click(function(){
    $(this).toggleClass('closebutton');
    $(this).closest(".tgx-window").slideToggle();
});


text:
Q: Python unittest - Ran 0 tests in 0.000s So I want to do this code Kata for practice.
I want to implement the kata with tdd in separate files:
The algorithm:
# stringcalculator.py
def Add(string):
   return 1

and the tests:
# stringcalculator.spec.py
from stringcalculator import Add
import unittest

class TestStringCalculator(unittest.TestCase):
    def add_returns_zero_for_emptyString(self):
        self.assertEqual(Add(' '), 0)

if __name__ == '__main__':
    unittest.main()

When running the testfile, I get:
Ran 0 tests in 0.000s

OK

It should return one failed test however. What do I miss here?

A: As stated in the python unittest doc:

The simplest TestCase subclass will simply implement a test method
  (i.e. a method whose name starts with test)

So you will need to change your method name to something like this:
def test_add_returns_zero_for_emptyString(self):
    self.assertEqual(Add(' '), 0)

A: I had a similar problem. My root cause was that I had placed the execution block for unittest.main inside the Test class. This kept messaging RAN 0 tests. Moving it outside of class work.
if __name__ == '__main__':
    unittest.main()

A: Sidenote: Also, the name of the file in which all the tests are there should start with 'test_'

A: Same symptoms, but different problem. Make sure you're not mixing up tabs and spaces for indentation. The problem may occur when you copy the code from an online resource and update it to your needs. Since tabs and spaces look very much alike in most editors, the test function may simply not be defined correctly.

A: In my case, I added __init__.py to the current test directory and the problem goes away.

A: class TestStringCalculator(unittest.TestCase):
    def add_returns_zero_for_emptyString(self):
        self.assertEqual(Add(' '), 0)

 if __name__ == '__main__':
     unittest.main()

After considering above two points in above written code,
I got below error due to prefix space at line ( if __name__ == '__main__')
python3 test_flaskr.py
  File "test_flaskr.py", line 66
    if __name__ == '__main__':
                             ^

Ensure that there is no prefix space and you need to write code at 1st column as below:
if __name__ == '__main__':
   unittest.main()

A: Do not define __init__; per that link, use def setUp(self) instead and unittest will call it.  Also, do not define run; I renamed mine to _run and the problem finally went away.


text:
Q: Event receiver on external list Recently I am working on a project to set event receiver on external list.
Below list what we have done

*

*Create trigger to capture data change in database and log them into data table

*Implement subscribe/unsubscribe function for BDC model

*Implement subscribe function in SharePoint UI (A separate RESTful endpoint is created for each subscribed event and subscription id is stored in database, we call the endpoint delivery address),Successful without any error

*Implement event receiver and attached it to external list

*Invoke delivery address through console application. Successful with "Success" in return XML.
Our expectation is when the delivery address is invoked, the event receiver will be fired. But it doesn't fired.
We suspect the reason would be

*

*The way we bind event receiver
    string assembly = this.GetType().Assembly.FullName;
string className = typeof(CustomeTSNBER).FullName;

try
    {
        using (SPSite site = new SPSite(siteUrl))
        {
            using (SPWeb web = site.OpenWeb())
            {
                SPList list = web.Lists[listTitle];
                list.EventReceivers.Add(SPEventReceiverType.ItemAdded,
                   assembly, className);

                list.Update();
            }
        }
    }
catch (Exception e)
{
        throw e;
}

*The way we invoke the delivery address (below is message send to delivery address), and I notice one thing is no matter what I send to delivery address, it return "Success" in returned XML.

Could anyone suggest what am I doing wrong?


text:
Q: MySQL | PARTITION BY Clause - Not working on XAMP There is an article published by Geeks for Geeks on the MySQL Partition clause at https://www.geeksforgeeks.org/mysql-partition-by-clause/.
But the same query not working after creating the same table in my XAAMP MySQL. It's giving me the syntax error to use near '(partition by challenge_id....)
Can anyone help?

A: Maybe the issue is your mysql version. the partition by is in version 5.7 and the dense_rank() can be use only in version 8.
try to use mysql v8 and it will be work fine
DB_Fiddle


text:
Q: How to typedef for call CreateThread, LPTHREAD_START_ROUTINE, lpStartAddress, ThreadProc WARNING: THIS IS AN EXAMPLE CODE.
I need to define this typedef and this definitions to get the code to compile well.
I have the following code and I need to know what should be in __WHAT_HERE1 and __WHAT_HERE2:
    #include <windows.h>
    #include <winbase.h>

_ifdef _WIN32_
    typedef ____WHAT_HERE1 THREAD_TYPE;
_endif

_ifdef _LINUX_
    typedef void (*THREAD_TYPE);
_endif

    THREAD_TYPE thread_function( void * )
    {

    }

    class ThreadInfo {
    public:
_ifdef _WIN32_
        ____WHAT_HERE2 func;
        LPVOID args;
_endif
_ifdef _LINUX_
    void *(*func) (void*);
    void *args;
_endif
    }

    ThreadInfo *infoThread;

    CreateThread(
        NULL,
        0,
        (LPTHREAD_START_ROUTINE) infoThread->func,
        infoThread->args,
        0,
        NULL
    );

A: You can deduce the type from the code you pasted:

*

*According to the CreateThread documentation, the third argument is of type LPTHREAD_START_ROUTINE. You're apparently aware of this already, as you cast infoThread->func to that.

*Hence, ____WHAT_HERE2 (the type of infoThread->func) should be LPTHREAD_START_ROUTINE.

*Since you will probably assign the address of the thread_function function to infoThread->func, the return value of the function (denoted by ____WHAT_HERE1 in your code sketch) should be the return type as indicated by LPTHREAD_START_ROUTINE. Checking the LPTHREAD_START_ROUTINE documentation shows that this is DWORD.
However, this will not be sufficient since on Windows, a thread procedure uses the __stdcall calling convention. You need to take that into account when defining your thread_function.


text:
Q: Is the convolution an invertible operation? I have a signal $f(x,y)$, which is discrete. I convolve this signal with a kernel $h(x,y)$:
$y(x,y) = f(x,y) \star h(x,y)$ (where $\star$ is the convolution operator)
Can I obtain $f(x,y)$ given only $y(x,y)$ and $h(x,y)$ ?
Note: Even though this may be a signal processing question I would like to know the answer (invertibility) from a Mathematical point of view.

A: Consider the convolution theorem, $\operatorname{Four}\{f\star g\}=\operatorname{Four}\{f\}\operatorname{Four}\{g\}.$ It's clear the original frequency space representation of f can only be recovered by division if the zeros of $\operatorname{Four}\{g\}$ are a subset of the zeros of $\operatorname{Four}\{f \star g\}$.
But in general, convolution of functions is almost a ring (there's no exact identity element). The linear space of compactly supported distributions forms an actual ring under convolution, and so it has a group of units. These are distributions whose convolutions are always reversible. One could consider invertibility in a neighborhood, by localizing this ring, in the same way you consider x to be invertible to 1/x in a neighborhood not containing x=0.

A: If convolution still makes sense with improper integrals then I believe the following shows that the answer is "No".
Consider the 1d case, with
$ f(t) = \frac{1}{1+t^2}\quad\text{and}\quad h(t) = 1,$
so then
$y(t) = f \star h = \int_{-\infty}^{\infty}\ f(\tau)h(t-\tau)\ d\tau = \int_{-\infty}^{\infty}\ f(\tau)\ d\tau = \pi $
Assume if $f$ were recoverable from $y$ and $h$, then for any $g$ such that $g \star h = y$, we must have $g=f$.
Consider,
$g(t) = \sqrt{\pi}e^{-t^2} \neq f(t) \longrightarrow g \star h = \pi = y(t)$
Contradiction!


text:
Q: Issue implementing google autocomplete in vue.js I'm trying to use google auto complete in vue.js with laravel but it is giving me error :

[Vue warn]: Error in mounted hook: "ReferenceError: google is not defined"
found in
---> <VueGoogleAutocomplete> at /src/components/VueGoogleAutocomplete.vue
       <App> at /src/App.vue

         <Root>

here is the link to the code which i'm trying to implement:
https://codesandbox.io/s/nifty-bardeen-5eock

A: After checking your codesandbox, I noticed that you didn't include the Google Maps Places API in the head tag of your public/index.html.
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE&libraries=places"></script>


text:
Q: EclipseLink MOXy: Superclass fields are not set when unmarshaling I would expect the fields of a superclass to be unmarshaled in the scenario below, but they are not. What is to do to make it work?
Input:
<?xml version="1.0" encoding="UTF-8"?>
my text

Binding:
<?xml version="1.0"?>
<xml-bindings
 xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
 package-name="test">

<java-types>
  <java-type name="SubClass">
    <xml-root-element name="a"/>
    <java-attributes>
        <xml-element java-attribute="text" xml-path="text()" />
    </java-attributes>
  </java-type>
</java-types>

</xml-bindings>

Classes:
public class SuperClass {

 private String text;

 public String getText() {
    return text;
 }

 public void setText(String text) {
    this.text = text;
 }
}

public class SubClass extends SuperClass { }

Demo:
Map<String, Object> jaxbContextProperties = new HashMap<String, Object>(1);
jaxbContextProperties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "bindings.xml");
JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[] {SuperClass.class}, jaxbContextProperties);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
SuperClass superClass = (SuperClass)unmarshaller.unmarshal(new File("input.xml"));
System.out.println(superClass.getText());

Output:
[EL Warning]: 2013-07-31 15:09:16.602--Ignoring attribute [text] on class [SubClass] as no Property was generated for it.
null

A: The mapping needs to be made on the class it belongs to.
OPTION #1 - Map SuperClass Property On SubClass
If you want to map the super class properties as part of the child you need to mark the parent class transient on the java-type element.
bindings.xml
<?xml version="1.0"?>
<xml-bindings
    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
    package-name="forum17981925">
    <java-types>
        <java-type name="SuperClass" xml-transient="true"/>
        <java-type name="SubClass">
            <xml-root-element/>
            <java-attributes>
                <xml-element java-attribute="text" xml-path="text()" />
            </java-attributes>
        </java-type>
    </java-types>
</xml-bindings>

OPTION #2 - Map SuperClass Property On SuperClass
Alternatively you could map the text property on SuperClass, this mapping with then be inherited by SubClass.
bindings.xml
<?xml version="1.0"?>
<xml-bindings
    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
    package-name="forum17981925">
    <java-types>
        <java-type name="SuperClass">
            <java-attributes>
                <xml-element java-attribute="text" xml-path="text()" />
            </java-attributes>
        </java-type>
        <java-type name="SubClass">
            <xml-root-element/>
        </java-type>
    </java-types>
</xml-bindings>

Demo Code
The following demo code can be run to prove that both options work:
input.xml
<subClass>Hello World</subClass>

Demo
import java.io.File;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
import org.eclipse.persistence.jaxb.JAXBContextProperties;

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> jaxbContextProperties = new HashMap<String, Object>(1);
        jaxbContextProperties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "bindings.xml");
        JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[] {SuperClass.class}, jaxbContextProperties);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        SuperClass superClass = (SuperClass)unmarshaller.unmarshal(new File("input.xml"));
        System.out.println(superClass.getText());
    }

}

Output
Hello World

A: Also the SuperClass's field could be null - because your SuperClass doesn't have a Setter for his field,
because Unmarshaller uses Default constructor with no arguments and Setters to initialize his fields. Or SuperClass doesn't have @XmlRootElement and @XmlElement annotations


text:
Q: Facebook Page Plugin width doesn't apply I'm trying to implement the Facebook Page Plugin. I set the width to 500, but it always stays at 280px.

What am I doing wrong?

A: Case of poor documentation:
the parent element can override the plugin width in only one direction - by squeezing it. Set the data-width="500" (max) and make your wrapper element smaller ex: width: 280px;

A: The Page Plugin tries to fit in smaller containers/screens

*

*The plugin renders at a smaller width (to fit in smaller screens) automatically, if the container is of slimmer than the configured width.

*It tries to render nicely on smaller screens assuming the container squeezes for mobile.
So probably, in your case the container holding the plugin is smaller than configured width i.e. 500px.

A: Though it is hard to test this without the rest of your code, you should be able to adjust the width of the div class by adding width="500px" directly into your HTML.
This method has worked for me espically with different embeds, including the facebook plugin.
If you choose to add it using CSS, try adding:
.fb-page zdepth-1 {width:500px;}

A: Try using
.fb-page zdepth-1 {width:500px !important;}

A: Somehow
.fb_iframe_widget {width:500px !important;}

only works sometimes for me. But I finally figured out what really caused the problem. I had the plugin wrapped in a div with display set to none. I changed it to inline-block and it works now.


text:
Q: Cost Analysis - Log Transform and Smearing I am completing a cost analysis using a log transformation I.E. log(cost) = treatment + var1 + var2. I am interested in testing for the marginal difference between treatments. I can easily find the marginal log(cost) for each treatment group. Three questions:

*

*If I exponentiate the marginal log(cost) for each treatment, is that a biased estimator of cost?

*Can I exponentiate the log(cost) for each treatment and find the difference to estimate the difference between treatments?

*If either 1 or 2 is biased, how do I use a smearing estimator?

I have the stata code below. The top table is the stata output followed by my work to exponentiate the log(cost) for each treatment and calculating the difference. Appreciate the help.
regress log_cost i.treatment i.var1 i.var2
  margins treatment


text:
Q: Problem with keyboard and mouse in gdm3 and lightdm Linux anarki 3.2.0-2-amd64 #1 SMP Fri Jun 1 17:49:08 UTC 2012 x86_64 GNU/Linux

Distributor ID: LinuxMint
Description:    Linux Mint Debian Edition
Release:        1
Codename:       debian

When my laptop boots I need to enter a harddrive password. I also have to manually skip the memory test during POST with the escape key so I know my keyboard works.
After booting into Linux I get to GDM3 or LightDM (tried both) login screen but my keyboard and mouse won't work. This includes a mouse and keyboard that have been connected via USB. When I unplug the USB keyboard and mouse and plug them in again, they work, but not the internal keyboard and trackpad, because I can't unplug/plug those. The numlock and capslock keys don't even light up when I press them. CTRL-ALT-F1 does not work.
I have found problem descriptions on the internet from 2011, with solutions like renaming /var/run/udev or /run/udev. There also was a proposed solution of removing the keyboard and mouse settings from xorg.conf because that is handled by evdev now, but all of these solutions didn't work.
The problem does not occur when I start in recovery mode. The keyboard works fine in the terminal, but as soon as I start X by doing startx or starting gdm3 or lightdm the keyboard and mouse cease to work. In the scenario of going through the recovery boot option the screen also stays blank when I start X.
I will be browsing through stackexchange looking for other possible solutions to try out.

A: I'm having the same problem. I've tried everything in the Mint LMDE thread. The only thing that works is unplugging and replugging in the mouse and keyboard. However no way to do this on the internal laptop ones so it's pretty much dead as a laptop.


text:
Q: Should a metric always map into $\mathbf{R}$? Typically you see the definition of a metric as a function which maps $X\times X\to\mathbf{R},$ but does this always have to be the case?
Motivating example: When you complete $\mathbf{Q}$ with the Archimedean metric you think of it as mapping into $\mathbf{R},$ but if you were to choose the $p$-adic metric instead it can only take values in $\{0\}\cup p^\mathbf{Z}$. These are elements of $\mathbf{Q}_p$ as well as $\mathbf{R}.$ The difference is then that either your metric maps into an ordered field or one where you can't define any ordering (but you still know that the distances can have different values).
Does not mapping a metric into $\mathbf{R}$ always lead to problems? And are the issues of the example above avoidable?

A: It depends on what you want for your "metric". It makes perfect sense as far as the definition goes to replace $\mathbb{R}$ by any totally ordered abelian group. But of course the properties won't be the same...
First note that when you suggest to interpret $|x|_p = p^{-v_p(x)}$ as an element of $\mathbb{Q}_p$, this has the pretty annoying inconvenient that if $x_n\to 0$ in $\mathbb{Q}_p$ then $|x|_p\to \infty$, so this interpretation does not give the $p$-adic topology.
Then let's assume that you define a metric as a map $X\times X \to \Gamma$ where $\Gamma$ is a totally ordered abelian group, with the usual axioms for metrics. This does give you a topology on $X$ by defining open balls as usual, and taking them as a basis for the topology.
But in general this topology need not be secound countable : this strongly uses the fact that  in $\mathbb{R}$ there is a sequence $(\varepsilon_n)$ such that $\varepsilon_n>0$ and every $x>0$ satisfies $x<\varepsilon_n$ for some $n$ (take $\varepsilon_n = \frac{1}{n}$). So if you want to keep this very crucial property of metric spaces, you need to assume that such a sequence $\varepsilon_n$ exists in $\Gamma$.
More importantly, if you want that $X$ is the union of the open balls $B(a,n)$ with $n\in \mathbb{N}$ for any $a\in X$, then you need that $\Gamma$ is archimedian (ie for any $\varepsilon>0$ and any $x\in \Gamma$ there in $n\in \mathbb{N}$ such that $n\varepsilon>x$). But that actually implies that $\Gamma$ can be embedded in $\mathbb{R}$ as an ordered group. So if you want that property for metric spaces, then you may assume $\Gamma = \mathbb{R}$ without loss of generality.


text:
Q: Does dotliquid support sub-templates and nested templates? please consider this class :
var dep =
            new Department
            {
                Name = "Jack",
                Employees = new List<Employee>
                {
                   new Employee()
                   {
                       Name = "E1",
                       Kids = new List<Kid>()
                       {
                           new Kid
                           {
                               Name = "K1"
                           },
                           new Kid
                           {
                               Name = "K2"
                           },
                           new Kid
                           {
                               Name = "K3"
                           },
                           new Kid
                           {
                               Name = "K4"
                           }
                       }
                   },
                   new Employee()
                   {
                       Name = "E2",
                       Kids = new List<Kid>()
                       {
                           new Kid
                           {
                               Name = "K5"
                           },
                           new Kid
                           {
                               Name = "K6"
                           }
                       }
                   },
                   new Employee()
                   {
                       Name = "E3",
                       Kids = new List<Kid>()
                       {
                           new Kid
                           {
                               Name = "K7"
                           }
                       }
                   }
                }
            };

so I need to define sub-template something like :
{{ Name }}
{% for e in Employee %}
  {{ EmployeeTemplate e }} // a Template can be an object for itself as input
{% endfor %}

EmployeeTemplate :
{% for k in Kids %}
  {{ KidTemplate k }}
{% endfor %}

KidTemplate :
{% for o in OBJECT %}
  {{Name}}
{% endfor %}

and result :
Jack
E1
K1
K2
K3
K4
E2
K5
K6
E3
K7

I need template as standalone block of strings so I want to know dotliquid support it or not ?
if standalone templates support so Can we define nested templates or not ?


text:
Q: XML declaration allowed only at the start of the document Sitemap Error Our website is using Salient theme in WordPress and we recently discovered this error in our sitemap: "error on line 2 at column 6: XML declaration allowed only at the start of the document"
We think it might be an issue with the theme or a plugin but we've deactivated plugins and searched the theme and cannot seem to fix the sitemap error.
Can someone please help?


text:
Q: type does not provide a call operator I have this function, order, which returns vector<Node*>
vector<Node*> order(vector<string> nodes, vector<pair<string, string>> dependencies) {
             Graph graph = buildGraph(nodes, dependencies);
             vector<Node*> order = buildOrder(graph.getNodes());
             return order;
}

and I call it like this:
vector<Node*> order2 = order(nodes, deps);

However, the compiler gives this error:
error: type 'std::__1::vector<Node *, std::__1::allocator<Node *> >' does not provide a call operator
        vector<Node*> order2 = order(nodes, deps);
                               ^~~~~
1 error generated.

What is going wrong? 'std::__1::vector<Node *, std::__1::allocator<Node *> >' seems to suggest that there is a vector<Node*, <Node*>> or something going on, but I can't seem to figure this out.

A: It's a bit hard to tell without your posting more complete code, but consider the following:
int order(int j, int k)
{
    return 3;
}

int main(int argc, char *argv[])
{
    char order;

    // order(2, 3);
}

This code builds fine. However, uncommenting
    // order(2, 3);

causes it to fail, as within main, order is a character, not a function. From the error message, it looks like you might have some similar problem.


text:
Q: My corporate proxy doesn't support web sockets, which makes Stack Exchange a pain to use The corporate proxy at my work doesn't support web sockets and as I understand, as informed by Wikipedia, this is pretty common.
Whenever a Stack Exchange page loads, in Firefox, I have to click through six proxy authentication messages before I can do anything.
It doesn't look like Stack Exchange uses websockets on other browsers.
While others in a similar situation and I can just use another browser, it would be useful if Stack Exchange can disable websockets for a session if they're failing.

A: I had the same problem on Firefox, what worked for me was adding an exception on my proxy settings for sockets.ny.stackexchange.com that way it just fails silently for that address instead of asking for authentication.

A: Now that Firefox has removed the preference that would allow a user to disable WebSockets, I decided to tackle this problem on my own and wrote WebSocket Disabler — a Firefox add-on that does exactly what its name suggests.
After installation, it adds a menu item to the Web Developer menu that can instantly enable or disable WebSockets:

A: It is possible to completely disable WebSockets in Firefox (in about:config put network.websocket.enabled to false).
This will solve the issue without touching the proxy settings.


text:
Q: что не так с syntax mysql в sh скрипте есть такой код
export wp_and_db_user="${VESTACP_USER}_${HOST_PREFIX}"
export wp_and_db_pass=${VESTACP_PASS}

mysql -u${wp_and_db_user} -p${wp_and_db_pass} << EOF
use ${wp_and_db_user}

UPDATE `wp_users` SET
`ID` = '1',
`user_login` = '${wp_and_db_user}',
`user_pass` = md5('${wp_and_db_pass}'),
`user_nicename` = '${wp_and_db_user}',
`user_email` = 'timemail@test.com',
`user_url` = '',
`user_registered` = '2019-05-19 11:28:16',
`user_activation_key` = '',
`user_status` = '0',
`display_name` = '${wp_and_db_user}'
WHERE `ID` = '1';

EOF

а вот сама ошибка
ERROR 1064 (42000) at line 3: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET = '1', = 'admin_resour', = md5('ODUyNzJmYmEyMmZhMzNmMj'), = 'admin_resour', ' at line 1

хотя эти команды я проверял в phpmyadmin и они работают, почему я получаю ошибку

A: В данном случае, вы используете HEREDOC с интерполяцией, он ведёт себя подобно строке в двойных кавычках, в частности воспринимает строки в бэктиках(``) как команды, результат выполнения которых попадает в итоговую строку:
$ cat << EOF
Date: `date`
EOF
Date: Чт июн 27 20:52:13 +07 2019

Существует другой синтаксис HEREDOC, без интерполяции:
$ cat << 'EOF'
String: `date`
EOF
String: `date`

Обратите внимание на апострофы вокруг EOF.