text:
Q: Array diagonal neighbourhood analysis and sort I've been battling with this for some time and seem to be getting nowhere.  The set up is so; I have a 2D array.  For this array I need to iterate through each value and return the diagonal neighbours (5 values).  These neighbours will be put into a new 1D [5] array and bubblesorted.  The middle value (median) will then be returned and put into a new array of medians.
So far I have methods for extracting the diagonal neighbours:
    //get diagonals from original DEM

    double [] getDiagonals(int i, int j) {

        double [] tempArray = new double [5];

        tempArray[0] = data[i -1][j +1];
        tempArray[1] = data[i -1][j -1];
        tempArray[2] = data[i][j];
        tempArray[3] = data[i +1][j -1];
        tempArray[4] = data[i +1][j +1];

        return tempArray;
    }

I've then used this method in an iteration to get diagonals for each value in the original array:
        //get diagonals for each

    double [] []   bubbles(){

        double [] [] datap = new double [298] [298];

        for (int i = 1; i < data.length; i++){
            for (int j = 1; j < data[i].length; j++) {
                if ((i > 0) && (j > 0)) {
                    if ((i < data.length-1) && (j  < data.length-1)){

                         double [] tempArray = getDiagonals(i, j);
//do something with the tempArray

I think this is where I'm coming unstuck.  Through testing the getDiagonals method works fine. I'm struggling to get the tempArray out of the bubbles() method.  If I set the output to be the tempArray it only returns the 5 values calculated for the bottom right corner of the original array.
I've tried calling other methods into the bubbles() method in order to do all the processing there and return a new array:
    //get diagonals for each

    double [] []   bubbles(){

        double [] [] datap = new double [298] [298];

        for (int i = 1; i < data.length; i++){
            for (int j = 1; j < data[i].length; j++) {
                if ((i > 0) && (j > 0)) {
                    if ((i < data.length-1) && (j  < data.length-1)){

                         double [] tempArray = getDiagonals(i, j);
                         double sorted [] = sort(tempArray);
                         double median = sorted[2];

                            for (int z = 0; z < datap.length; z++){
                                for (int y = 0; y < datap[z].length; y++){
                                datap[z][y] = median;
                                }
                            }

                    }
                }
            }
        }
        return datap;
    }

Again this fails and the output datap is just zeros.  The sort() method above passed out the diagonals to a bubble sort method (which I know works on its
I guess my question is how to process within a method that is iterating and populate a new array?
I hope this makes sense but if you need more details please let me know.  And yes, the sort I'm using is a bubble sort.  I know they are rubbish but this is for a course I'm doing so it has to be used.  And yes, I'm pretty new to java.
Any help would be greatly appreciated (and I'll even reference you if I need to use some code you provide ;)

A: The main issue that I see, is that with each traversal through your inner loop of:
for (int i = 1; i < data.length; i++){
   for (int j = 1; j < data[i].length; j++) {

Where you call:
double [] tempArray = getDiagonals(i, j);

You are resetting all of the values of datap to be the current calculated median. To fix, you would need some way to indicate only the indices of the particular datap value that you want to populate.
You need to replace this section of your code:
for (int z = 0; z < datap.length; z++){
    for (int y = 0; y < datap[z].length; y++){
    datap[z][y] = median;
    }
}

You could declare int y, z at the top of the method and do something like this:
if (y < datap.length){
    if (z == datap.length[y] - 1){
        y++;
        z = 0;
    }

    datap[y][z] = median;
    z++;
}

That way you are only assigning to the specific index in datap that you are trying to reach, instead of resetting each of its values.

A: Finally cracked it. To populate the whole array the following code works a peach.
//Diagonal to 1dArray and sorting

double [] [] bubbles()
{
    double [][] tempArray = new double [300][300];

    int y = 0;
    int z = 0;
    double median = 0;

    for (int i = 0; i < data.length; i++)
    {
        for (int j = 0; j < data[i].length; j++)
        {
            if ((i > 0) && (j > 0))
            {
                if ((i +1 < data[i].length) && (j +1 < data[j].length))
                {
                    double [] diagonals = getDiagonals(i, j);

                    //Need to sort here
                    median = diagonals[2];
                    tempArray[i][j] = median;
                }
            }
        }
    }
    return tempArray;
}

The sorting was taken out and I haven't tested with it back in yet; but so far this is providing new values for all the cells in the temp array.


text:
Q: .next() is not working in ResultSet in Java .next() is not working in this code. I tried a lot but in vain. For example, if I have 10 rows in branch_issuance_g_item_vise (DB table name). This code prints 10 times the first row only.
void stockIssuance(String date) throws SQLException{
    report_table.setVisible(true);

    Statement s = db.conn().createStatement();
    ResultSet rs = s.executeQuery("SELECT * FROM branch_issuance_g_item_vise");

    DefaultTableModel dt = (DefaultTableModel) report_table.getModel();
    dt.setRowCount(0);

    Vector v = new Vector();
    if(!rs.next()){
        m.printError("No Data Found");
        rs.beforeFirst();
    }
    else{
        while(rs.next()){
            v.add(rs.getString("item_name"));
            v.add(rs.getString("qty"));

            dt.addRow(v);
        }
    }
}

Even, this is not working.
void stockIssuance(String date) throws SQLException{
    report_table.setVisible(true);

    Statement s = db.conn().createStatement();
    ResultSet rs = s.executeQuery("SELECT * FROM branch_issuance_g_item_vise");

    DefaultTableModel dt = (DefaultTableModel) report_table.getModel();
    dt.setRowCount(0);

    Vector v = new Vector();
    while(rs.next()){
        v.add(rs.getString("item_name"));
        v.add(rs.getString("qty"));

        dt.addRow(v);
    }
}

A: You should ceate a new vector v at the start of the while loop. As is, the rows will be appended to the vector but you only have two columns.
Furthermore, every time you call rs.next the resultset is advanced one step. Easiest fix would be to remove the check if the resultset is empty.

A: Add rs.beforeFirst before while, and move the Vector ArrayList creation inside loop
else {
    rs.beforeFirst();
    while(rs.next()) {
       ArrayList v = new ArrayList();

Moves the cursor to the front of this ResultSet object, just before the first row. This method has no effect if the result set contains no rows.

You should use ArrayList instead of Vector

A: First of all, you should call res.beforeFirst() before the else condition, because everytime the if statements checks the condition, you are doing rs.next() and when you are doing else condition you are skipping the first element by doing rs.next() again.
To solve your problem, I suggest you to do something like this, without using a vector:
ResultSet res=stat.executeQuery(query);
        while (res.next()){
            model.setRowCount(model.getRowCount() + 1);
            int currentRow = model.getRowCount() - 1;
            model.setValueAt(res.getString("param1"), currentRow, 0);
            model.setValueAt(res.getString("param2"), currentRow, 1);
            model.setValueAt(res.getString("param3"), currentRow, 2);
            model.setValueAt(res.getString("param4"), currentRow, 3);

        }

In this example I'm using a row counter and I have 4 fields, like "Name|Surname|Date|ID|" that's why you see 0,1,2,3. If you just have one column in your Table, just use
model.setValueAt(res.getString("something"), currentRow, 0);

If you keep want to use your vector, you need to init it everytime in the while loop:
Vector v;
while(rs.next()){
   v=new Vector();
   .....
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Existence of a finite set of sentences $\Delta$
Let $\Gamma_1, \Gamma_2$ be sets of sentences s.t. for any structure $M$ it holds that:
$M\vDash \Gamma_1 \iff M\not\vDash \Gamma_2 $
Show that exists a finite set of sentences $\Delta$ s.t. for any sentence $A$, it holds that $\Gamma_1 \vDash A \iff \Delta \vDash A$.

I got lost with all the iff's. I tried assuming towards contradiction but I could only contradict one case. I can't see how the information about $\Gamma_2$ is helpful, and I certainly can't come up with such $\Delta$ that have that property (and any $\Delta$ which is a subset of either $\Gamma_1$,$\Gamma_2$, or $\Gamma_1 \cup \Gamma_2$ seems not suitable). Would appreciate any hint.

A: In fact the desired $\Delta$ is indeed a subtheory of $\Gamma_1$ - which is reasonable, since being a subtheory of $\Gamma_1$ gives us one of our three "goal conditions" immediately, namely being entailed by $\Gamma_1$ itself.
I've broken my answer into a series of exercises:

As you say, the main difficulty with this problem comes from its phrasing, and the "nested implications" it contains. It helps to break things down as we go along. Let's start with the hypothesis in question, namely $$\forall M(M\models\Gamma_1\iff M\models\Gamma_2).$$
This has two pieces which are much easier to think about on their own:

*

*No structure can satisfy both $\Gamma_1$ and $\Gamma_2$ - that is, $\Gamma_1\cup\Gamma_2$ is unsatisfiable.

*On the other hand, every structure does have to satisfy one or the other.
Besides being individually simpler than the whole hypothesis itself, these sub-hypotheses can be considered one at a time, which helps us see how our argument should flow. Specifically, while the latter is a bit subtle, the first is very nice in that it suggests an immediate first step - namely, whenever we have an unsatisfiable theory (in this case $\Gamma_1\cup\Gamma_2$), we can get a subtheory $\Theta$ which is itself unsatisfiable but is "simpler" in a particular sense:

 The compactness theorem then says that there is some finite $\Theta\subseteq\Gamma_1\cup\Gamma_2$ which is itself unsatisfiable.

OK, so we have a "simple" (in the above sense) theory $\Theta\subseteq\Gamma_1\cup\Gamma_2$ which is unsatisfiable. This $\Theta$ has a "$\Gamma_1$-part" and a "$\Gamma_2$-part," namely $\Theta\cap \Gamma_1$ and $\Theta\cap \Gamma_2$ respectively. Now right off the bat we see from this decomposition a theory which is pretty close to what we want, and so which we'll choose as our $\Delta$:

 The theory $\Theta\cap\Gamma_1$ is finite, and we have $\Gamma_1\models\Theta\cap\Gamma_1$. So we'll set $\Delta=\Theta\cap\Gamma_1$.

Per the above, we only need to show that this $\Delta$ entails $\Gamma_1$ itself. The second bulletpoint gives an equivalent rephrasing of this, and consequently a different way to phrase our goal:

 Suppose no model of $\Delta$ satisfies $\Gamma_2$. Then every model of $\Delta$ must satisfy $\Gamma_1$, since every structure - and so a fortiori every model of $\Delta$ - satisfies one of $\Gamma_1$ and $\Gamma_2$. So all we need to prove is that $\Delta\cup\Gamma_2$ is unsatisfiable.

But this follows immediately from the definition of $\Delta$:

 We have $\Delta\cup\Gamma_2\supseteq\Theta$.


text:
Q: Ensuring Java classes do not import from certain packages I have packages like this:
com.example.pure
com.example.pure.internal
com.example.other

I want to ensure that the classes in the com.example.pure package do not have any dependencies on classes in the com.example.pure.internal or com.example.other packages.
Obviously, I can go through each file manually and eyeball the imports, but I'd like to automate it. I could write some code to do it, but it seems like it might be something that someone else has already solved.
I use Eclipse, so an Eclipse plugin that I could configure to enforce dependency directions would be absolutely ideal, but a command-line utility or Gradle plugin would be great too.

A: in Apache Lucene they use this handy tool called fobidden-apis to check that certain apis are not used. It is an Ant task so you can call this easily from inside eclipse

A: you can compile com.example.pure separately alone if it compiles successfully then it's not depends on any other package:
-cp path or -classpath path

or
javac -d bin -cp bin src\...\someclass.java


text:
Q: Swipe to go back in navigation controller on iOS 7 I've been looking through the iOS 7 / UIKIT framework, and although it looks quite different aesthetically it's really the same SDK underneath from what I can see.
My question, is there any extra code that needs to be included to get the draggable behaviour between pushed tableviews/views?
When you push a view onto a UINavigationController you can now drag back to the previous controller from the side rather than pressing the back button.
This behavior can be seen in mail.
How is this achieved, do I need to add any code to add it to my app?

A: This has nothing to do with UITableView or UITableViewController, but with UINavigationController. And yes, you get this behavior for free as long as the back button is visible.


text:
Q: How to make video player like native in android I want to make video player with next option to keep playing video after rotate device.
I created service with MediaPlayer and set SurfaceHolder of SurfaceView after rotate sceen. It works only for Android 4.x. For Android 2.3.X after replace second call setDisplay user doesn't see video, but hears sound of video.
Could you give me direction or example how to implement this option at custom player?
PS. Player shows streaming video.

A: Okay, I've found solution. It's so easy. I set configChanges="orientation|screenSize" for activity with custom player. In this case activity won't be recreated after rotate device it's changed on the same instance.
As result, I don't need service for keeping MediaPlayer and don't need replace SurfaceHolder.


text:
Q: arch linux strange message after installing xorg and virtualbox guest additions I'm brand new to arch linux.
I'm following the tutorial first part and got a linux environment working on virtualbox 5.1.6
After that I installed xorg-server, xorg-xinit, twm, xterm, xf86-video
-vesa virtualbox-guest-utils (virtualbox-guest-modules-arch)
rebooted and getting following message:

and after logged in, getting this:

The same occurred also with virtualbox 5.0.26 so I upgraded to 5.1.6 and still the problem with a new installation.
Does somebody know what could be the problem?


text:
Q: Creating a function that allows me to readRDS files? I just wanted to create a function which enables me to read a RDS file.. so I have the code below, and I would like for a1 to display the RDS file in Rstudio when I input test(example.RDS)
readRDS(paste0("C:/Users/Jack/Documents/","example.RDS")

works but when I try to turn it into a function, it does not work...
 test <- function (entry) {
        a1 <- readRDS(paste0("C:/Users/Jack/Documents/",entry))
        }

A: Are you looking for something like this?
saveRDS(diamonds, '~/diamonds.rds')
#> Error in saveRDS(diamonds, "~/diamonds.rds"): object 'diamonds' not found

test <- function(entry) {
  readRDS(paste0("~/", entry))
}

test('diamonds.rds')
#> # A tibble: 53,940 x 10
#>    carat cut       color clarity depth table price     x     y     z
#>    <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#>  1  0.23 Ideal     E     SI2      61.5    55   326  3.95  3.98  2.43
#>  2  0.21 Premium   E     SI1      59.8    61   326  3.89  3.84  2.31
#>  3  0.23 Good      E     VS1      56.9    65   327  4.05  4.07  2.31
#>  4  0.29 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63
#>  5  0.31 Good      J     SI2      63.3    58   335  4.34  4.35  2.75
#>  6  0.24 Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48
#>  7  0.24 Very Good I     VVS1     62.3    57   336  3.95  3.98  2.47
#>  8  0.26 Very Good H     SI1      61.9    55   337  4.07  4.11  2.53
#>  9  0.22 Fair      E     VS2      65.1    61   337  3.87  3.78  2.49
#> 10  0.23 Very Good H     VS1      59.4    61   338  4     4.05  2.39
#> # … with 53,930 more rows

#no need to pass string as an argument
test2 <- function(entry) {
  .string <- substitute(entry) |> as.character()
  readRDS(stringr::str_glue("~/{.string}"))
}

test2(diamonds.rds)
#> # A tibble: 53,940 x 10
#>    carat cut       color clarity depth table price     x     y     z
#>    <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#>  1  0.23 Ideal     E     SI2      61.5    55   326  3.95  3.98  2.43
#>  2  0.21 Premium   E     SI1      59.8    61   326  3.89  3.84  2.31
#>  3  0.23 Good      E     VS1      56.9    65   327  4.05  4.07  2.31
#>  4  0.29 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63
#>  5  0.31 Good      J     SI2      63.3    58   335  4.34  4.35  2.75
#>  6  0.24 Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48
#>  7  0.24 Very Good I     VVS1     62.3    57   336  3.95  3.98  2.47
#>  8  0.26 Very Good H     SI1      61.9    55   337  4.07  4.11  2.53
#>  9  0.22 Fair      E     VS2      65.1    61   337  3.87  3.78  2.49
#> 10  0.23 Very Good H     VS1      59.4    61   338  4     4.05  2.39
#> # … with 53,930 more rows

Created on 2021-06-28 by the reprex package (v2.0.0)


text:
Q: How to solve 'right-hand operand has no effect' error? I am currently working with Eclipse CDT, the ESP-IDF framework and the ESP32 Wrover DevKit.
I was looking for a C vector implementation and stumbled over rxi/vec on GitHub. I copied vec.h and vec.c to my project and tried to compile. I am getting the following error:
Error: right-hand operand of comma expression has no effect[-Werror=unused-value]

... at this line of code in vec.h:
#define vec_push(v, val)\
  ( vec_expand_(vec_unpack_(v)) ? -1 :\
    ((v)->data[(v)->length++] = (val), 0), 0 )

Any ideas how solve this issue or work around? Any alternative vector implementation for C ?

Update A
../main/tools/inc/vec.h:35:42: error: right-hand operand of comma expression has no effect [-Werror=unused-value]
   ( vec_expand_(vec_unpack_(v)) ? -1 :\
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     ((v)->data[(v)->length++] = (val), 0), 0 )
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~
../main/main.c:44:2: note: in expansion of macro 'vec_push'
  vec_push(&toc.items, item1);
  ^~~~~~~~
../main/tools/inc/vec.h:35:42: error: right-hand operand of comma expression has no effect [-Werror=unused-value]
   ( vec_expand_(vec_unpack_(v)) ? -1 :\
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     ((v)->data[(v)->length++] = (val), 0), 0 )
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~
../main/main.c:50:2: note: in expansion of macro 'vec_push'
  vec_push(&item1.elements, elem1);
  ^~~~~~~~
../main/tools/inc/vec.h:35:42: error: right-hand operand of comma expression has no effect [-Werror=unused-value]
   ( vec_expand_(vec_unpack_(v)) ? -1 :\
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     ((v)->data[(v)->length++] = (val), 0), 0 )
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~
../main/main.c:56:2: note: in expansion of macro 'vec_push'
  vec_push(&item1.elements, elem2);
  ^~~~~~~~
cc1: some warnings being treated as errors

Update B
#include <stdio.h>
#include <stdlib.h>
#include "vec.h"

typedef struct toc_element_t {
  uint16_t uid;
  char element[8];
  char type[8];
} toc_element_t;

typedef vec_t(toc_element_t) vec_toc_element_t;

typedef struct toc_item_t {
  char category[8];
  vec_toc_element_t elements;
} toc_item_t;

typedef vec_t(toc_item_t) vec_toc_item_t;

typedef struct toc_t {
    char description[8];
    vec_toc_item_t items;
} toc_t;

void app_main(void) {

    toc_t toc;
    strcpy(toc.description, "toc1");
    vec_init(&toc.items);

    toc_item_t item1;
    strcpy(item1.category, "cat1");
    vec_init(&item1.elements);
    vec_push(&toc.items, item1);

    toc_element_t elem1;
    elem1.uid=0;
    strcpy(elem1.element, "elem1");
    strcpy(elem1.type, "float");
    vec_push(&item1.elements, elem1);

    toc_element_t elem2;
    elem2.uid=1;
    strcpy(elem2.element, "elem2");
    strcpy(elem2.type, "float");
    vec_push(&item1.elements, elem2);

    printf("TOC [%s]:\n", toc.description);

    toc_item_t item; int index1;
    vec_foreach(&toc.items, item, index1) {
        printf(" - item[%d]=%s\n", index1, item.category);
        toc_element_t element; int index2;
        vec_foreach(&item.elements, element, index2) {
            printf("  - element[%d]=%s [%s]\n", index2, element.element, element.type);
        }
    }

    while(1);

}

Update C
Perhaps this issue is not related to this question, but since Eric mentioned the last commit with the log message "Fixed vec_insert() and vec_push() for structs" that inserted the 'fishy' ,0 that caused the problem discussed here, it may nonetheless be related.
When executing the code in section "Update B", I get the following output:
TOC [toc1]:
 - item[0]=cat1

But I would expect the following:
TOC [toc1]:
 - item[0]=cat1
  - element[0]=elem1
  - element[1]=elem2

Solved: Why does the inner vector not get printed out?

A: The compiler is right to warn you. Something is fishy there. The … ? -1 : (…, 0) part is designed to return a success/failure indication, and then the trailing , 0 throws that away. It is "valid code" in that it does not violate a rule of the C standard, but there is clearly a design or coding error there.
The extra , 0 was introduced in commit dd55e00e17d454f54b905fdcf6718ba0c1ed94b0, with the log message "Fixed vec_insert() and vec_push() for structs". It and the same change to vec_insert are the only changes in that commit:
--- a/src/vec.h
+++ b/src/vec.h
@@ -33,7 +33,7 @@

 #define vec_push(v, val)\
   ( vec_expand_(vec_unpack_(v)) ? -1 :\
-    ((v)->data[(v)->length++] = (val)), 0 )
+    ((v)->data[(v)->length++] = (val), 0), 0 )

 #define vec_pop(v)\
@@ -52,7 +52,7 @@

 #define vec_insert(v, idx, val)\
   ( vec_insert_(vec_unpack_(v), idx) ? -1 :\
-    ((v)->data[idx] = (val)), (v)->length++, 0 )
+    ((v)->data[idx] = (val), 0), (v)->length++, 0 )

I do not see how those changes comport with the log message. I think it is a mistake. Note that the pre-commit code was wrong; this code:
  ( vec_expand_(vec_unpack_(v)) ? -1 :\
    ((v)->data[(v)->length++] = (val)), 0 )

has the pattern (Test ? -1 : (Operation), 0). That always produces 0, since the comma operator is the lowest precedence. The commit changes it to (Test ? -1 : (Operation, 0), 0), which has equivalent behavior—on the : side, the operation is performed, but then the result is discarded, 0 is evaluated and discarded, and then there is another 0. If the commit had changed it to (Test ? -1 : (Operation, 0)), that would make sense. The commit would be fixing an error, in that the macro previously always produced 0 but would now produce 0 or −1 according to whether the operation was successful or not.
None of the tests in the repository check the "return" value of vec_push.
It should be safe to remove the , 0. The resulting expansion will continue to evaluate to zero in normal situations. It will change to evaluate to −1 if the push fails (because memory allocation fails), but that would seem to be desirable. Good code should be:
#define vec_push(v, val)\
  ( vec_expand_(vec_unpack_(v)) ? -1 :\
    ((v)->data[(v)->length++] = (val), 0))

Also make the same change to vec_insert and look for any similar code that needs to be fixed.


text:
Q: Mean Normalization in pandas I am trying to implement mean normalization of rows in pandas. Find the mean of every row in pandas, subtract the mean from each element for the particular row.
Code:
df = pd.DataFrame(np.random.randint(0,100,size=(4, 5)), columns=list('ABCDE'))
print (df)

    A   B   C   D   E
0  53  77  34  51  41
1  44  46   6  70  31
2  52  22  95  88  13
3  77  18  88  86  20

x = pd.DataFrame(df.mean(axis = 1),columns=['mean'])

for index,rows in df.iterrows():
  for i in range(len(x)):
     df.loc[index] = df.loc[index] - x.loc[i]
print (df)

op:

     A   B   C   D   E
  0 NaN NaN NaN NaN NaN
  1 NaN NaN NaN NaN NaN
  2 NaN NaN NaN NaN NaN
  3 NaN NaN NaN NaN NaN

Any suggestions on what's the mistake

A: You can just use apply in this way:
df = df.apply(lambda x: x - df.mean(axis = 1))

Output:
      A     B     C     D     E
0   1.8  25.8 -17.2  -0.2 -10.2
1   4.6   6.6 -33.4  30.6  -8.4
2  -2.0 -32.0  41.0  34.0 -41.0
3  19.2 -39.8  30.2  28.2 -37.8

A: You can perform this calculation in a vectorised fashion using numpy:
A = df.values
A = A - A.mean(axis=1)[:, None]

res = pd.DataFrame(A, index=df.index, columns=df.columns)

print(A)

array([[11, 31, 78, 55, 71],
       [89, 39, 39, 16, 45],
       [26, 10, 85, 68, 93],
       [55, 19, 78, 30, 41]])

print(res)

      A     B     C     D     E
0 -38.2 -18.2  28.8   5.8  21.8
1  43.4  -6.6  -6.6 -29.6  -0.6
2 -30.4 -46.4  28.6  11.6  36.6
3  10.4 -25.6  33.4 -14.6  -3.6


text:
Q: Python type hints: should I use more generic types? With Python 3 type hints, should I be using the more generic types as opposed to the more concrete ones?  For example
a: Sequence[str] = []

as opposed to:
a: List[str] = []

I'm thinking "yes".  Which leads to the question of when would I want to use the more concrete type?

A: I think I just answered my own question.
I had a Sequence declared like this:
a: Sequence[str] = []

but then I had a need to append items to it.  Sequence doesn't have this method defined for it and thus mypy complained.  So, I think the answer is "use the generic type by default and drop down to the concrete type when you need to".


text:
Q: SWT gc.setAdvanced(true) causes blocking state I have some heavy system resources image manipulation (need to zoom image really deep) and draw some part of zoomed image (let's call it viewport) to a canvas.
Because image resizing to such a huge dimensions would cause blocking UI for seconds, I've made backgroung thread which resize the image and when the image is ready it's used. Until then, paintevent gc and SWT transformations are used (they are fast, but about 10 times slower than viewport manipulation of already resized image).
But after I wrote the resizing thread it still blocks the UI. So I've made the SSCCE to proof that. Unfortunately it worked flawlessly. After few hours of debugging I've found that gc.setAdvanced(true); causes block of GC context.
import java.net.URL;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class ImageResizeTest {
    private Image bgImage;
    private Image imgToResize;
    private ImageResizeWorker worker;
    private Display display = new Display();
    private Shell shell = new Shell(display);

    public ImageResizeTest() {
        shell.setText("Image background resize test");

        Rectangle rect = new Rectangle(0, 0, 500, 500);
        bgImage = new Image(display, rect);
        paintImage(bgImage);

        shell.addPaintListener(new PaintListener() {
            @Override
            public void paintControl(PaintEvent e) {
                System.out.println("redraw start");
                e.gc.drawImage(bgImage, 0, 0);
                e.gc.setAdvanced(true);
                e.gc.fillRectangle(new Rectangle((int)(Math.random() * 100), (int)(Math.random() * 100), 20, 20));
                System.out.println("redraw stop");
            }
        });

        shell.addKeyListener(new KeyAdapter() {

            /* (non-Javadoc)
             * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
             */
            @Override
            public void keyPressed(KeyEvent e) {
                worker = new ImageResizeWorker(new Image(display, imgToResize, SWT.IMAGE_COPY));
                worker.start();
                display.asyncExec(new Runnable() {
                    @Override
                    public void run() {
                        shell.redraw();
                        try {
                            Thread.sleep(250);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (worker.isAlive()) display.asyncExec(this);
                    }
                });
            }
        });

        try {
            URL url = new URL("http://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1280px-Image_created_with_a_mobile_phone.png");
            imgToResize = new Image(display, url.openStream());
            paintImage(imgToResize);
        } catch (Exception e) {
            e.printStackTrace();
        }

        shell.setActive();
        shell.setBounds(rect);
        shell.setVisible(true);

        while(!shell.isDisposed()) {
            if(!display.readAndDispatch()) display.sleep();
        }

        shell.dispose();
    }

    private void paintImage(Image img) {
        Rectangle rect = img.getBounds();
        GC gc = new GC(img);
        for (int i = 0; i < 20; i++) {
            gc.drawLine((int)(Math.random() * rect.width), (int)(Math.random() * rect.height), (int)(Math.random() * rect.width), (int)(Math.random() * rect.height));
        }
        gc.dispose();
    }

    private class ImageResizeWorker extends Thread {
        private Image srcImage;

        public ImageResizeWorker(Image srcImage) {
            this.srcImage = srcImage;
        }

        /* (non-Javadoc)
         * @see java.lang.Thread#run()
         */
        @Override
        public void run() {
            System.out.println("resizing started");
        Image targetImage = new Image(new Display(), 31000, 15000);
        long time = System.currentTimeMillis();
        GC gc = new GC(targetImage);
        gc.setAdvanced(true);
        gc.setInterpolation(SWT.HIGH);
        gc.drawImage(srcImage, 0, 0, srcImage.getBounds().width, srcImage.getBounds().height, 0, 0, 31000, 15000);
        System.out.println("Took " + (System.currentTimeMillis() - time) + " ms");
        gc.dispose();
        bgImage = targetImage;
        }
    }

    public static void main(String[] args) {
        new ImageResizeTest();
    }
}

If both gc.setAdvanced(true); are commented out it works as it should.
Could someone tell my why that cause the block and how to avoid it? And yes, I need to have both threads (main and worker) in advanced mode, because I need to use antialiasing in main for line drawing and gc.setInterpolation(SWT.HIGH); in worker to have reasonable image quality after resize.


text:
Q: Colinearity in hypothesis testing. My lecture notes write the following about colinearity and I don't know why it's true:
If we reject the null hypothesis for an F-Test and fail to reject the null hypothesis for the T-test while also consequently having high $R^2$ (coefficient of determination), it signals we might have a colinearity problem.


text:
Q: How can I open a print dialog without a second window? I would like to give the user the opportunity to print out part of my page. Currently I do this by opening a new window and executing window.print(). Since Chrome was updated to version 90, the page hangs when you click the X button. Can you help me fix it?
Code Example:
var html = "";
html += "<title>Druckvorschau</title>"
html += "
Example
"
html += "";
var width = 600;
var height = 800;
var left = screen.width - 600;
var top = screen.height - 800;
var params = 'width=' + width + ', height=' + height;
params += ', top=' + top + ', left=' + left;
var printWin = window.open('', 'blank', params);
printWin.title = "Druckvorschau";
printWin.document.write(html);
printWin.document.close();
printWin.focus();
printWin.print();

A: You can create an iframe instead of a new window and then print the iframe:
var html = "";
html += "<title>Druckvorschau</title>"
html += "
Example
"
html += "";

var iframe = document.createElement('iframe');
document.body.appendChild(iframe)
var printWin = iframe.contentWindow;

printWin.title = "Druckvorschau";
printWin.document.write(html);
printWin.document.close();
printWin.focus();
printWin.print();

// And then delete it afterward:
document.body.removeChild(iframe)


text:
Q: My cloneFolderHTML is not defined I get an error like this.

ReferenceError: cloneFolderHTML is not defined

    initialCopy.push({
        clonefolder: cloneFolderHTML
      });

This made me unable to access the elements, and I had to reload the page so the code could work.
I just know when opening the console and it turns cloneFolderHTML not defined.
how to be able to call it outside the submitButton function?

jQuery :
$('.submitButton').click(function() {
  function copyFolderList(cloneFoldername) {
    var cloneFolder = /** HTMLCODE **/;
    return cloneFolder;
  }

  if ( /* code */ ) {
    // some code
  } else {
    var cloneFolder = JSON.parse(localStorage.getItem("copyList"));
    if (cloneFolder == null) {
      cloneFolder = [];
    }
    let cloneFolderHTML = copyFolderList(inputan);
    cloneFolder.push({
      clonefolder: cloneFolderHTML
    });
    localStorage.setItem("copyList", JSON.stringify(cloneFolder));
    $("#navcopyrow").append(cloneFolderHTML);
  }
}); // submitButton function

var cloneFolder = JSON.parse(localStorage.getItem("copyList"));
if (cloneFolder != null) {
  //get the nav reference in DOM
  let navcopy = $("#navcopyrow");

  //clear the html contents
  navcopy.html('');

  for (var i = 0; i < cloneFolder.length; i++) {
    var copyitem = cloneFolder[i];
    $("#navcopyrow").append(copyitem.clonefolder);
  }
} else {
  let initialCopy = [];
  initialCopy.push({
    clonefolder: cloneFolderHTML
  });
  localStorage.setItem("copyList", JSON.stringify(initialCopy));
}

Can I call cloneFolderHTML outside the submitButton function?

A: let cloneFolderHTML

let is an ECMAScript 6 reserved word that makes a variable block scoped.  Meaning it will only exist within the scope of it's immediately encapsulated {}.  Since the variable is in the {} of an else, it will only exist inside that else block.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let


text:
Q: How can you drop items in a `ICollection` without knowing its `TSource`? How can you drop items in a ICollection without knowing its TSource? I thought LINQ would be the best route for this, but I cannot figure out how it might be done with Reflection or any other method.
I am trying to implement this in a class that inherits System.Attribute so generic types are not permitted. And, the returned type information must be the same as the type information received on the value parameter of MutateValue. So obviously, generic would be a joy in this case, but is there another solution.
using System;
using System.Collections;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace Dado.ComponentModel.DataMutations
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class ApplyMaxLengthStackAttribute : MutationAttribute
    {
        private int _maxLength = -1;

        public object Mutate(object value, int maxLength, IMutationContext context = null)
        {
            _maxLength = maxLength;

            return Mutate(value, context);
        }

        protected override object MutateValue(object value, IMutationContext context)
        {
            if (value != null) {
                if (
                    value is string valueAsString &&
                    (
                        _maxLength > -1 || TryGetStringLengthAttributeValue(context, out _maxLength)
                    ) &&
                    valueAsString.Length > _maxLength
                ) {
                    value = valueAsString.Substring(0, _maxLength);
                }
                else if (
                    value is ICollection valueAsCollection &&
                    (
                        _maxLength > -1 || TryGetMaxLengthAttributeValue(context, out _maxLength)
                    ) &&
                    valueAsCollection.Count > _maxLength
                ) {
                    // Error CS1061
                    value = valueAsCollection.Take(_maxLength);
                }
            }

            _maxLength = -1;

            return value;
        }

        private bool TryGetStringLengthAttributeValue(IMutationContext context, out int maxLength)
        {
            var attribute = context?.Attributes.OfType<StringLengthAttribute>().FirstOrDefault();

            if (attribute != null) {
                maxLength = attribute.MaximumLength;

                return true;
            }

            return TryGetMaxLengthAttributeValue(context, out maxLength);
        }

        private bool TryGetMaxLengthAttributeValue(IMutationContext context, out int maxLength)
        {
            var attribute = context?.Attributes.OfType<MaxLengthAttribute>().FirstOrDefault();

            if (attribute != null) {
                maxLength = attribute.Length;

                return true;
            }

            maxLength = -1;

            return false;
        }
    }
}

You will see this code will not compile and throws this error:

Error CS1061: 'ICollection' does not contain a definition for 'Take' and  no extension method 'Take' accepting a first argument of type 'ICollection' could be found (are you missing a using directive or an assembly reference?)

This class is an extension to the Dado.ComponentModel.Mutations project. Definitions for other Dado.ComponentModel.Mutations member definitions should be sought there.

A: dynamic to the rescue!
value = Enumerable.Take((dynamic)value, _maxLength);

There are few valid reasons to use dynamic in a language with such a powerful type system as C#, but it does have its occasional shortcomings, where the language designers for whatever reason (usually lack of time/resources) didn't implement some way to express something that should be valid to express and possible for them to implement. However, when you hit what appears to be a rather arbitrary bump (or wall) that is simply an arbitrary limitation of the language, I think that is a perfectly valid reason to briefly abandon the type system, which is basically what dynamic lets you do. I believe you have hit one of those arbitrary limitations and you are perfectly justified in using dynamic in this situation.
If you want to make your code a little more "safe" or fool proof (should some collection that doesn't implement IEnumerable<> get passed in), you can amend your else if to check if value implements IEnumerable<> (which you'll have to do via reflection, unfortunately)

A: Many extension methods in LINQ work on type IEnumerable<T> rather than IEnumerable. Take is one such method. Try casting to IEnumerable<object> like this:
valueAsCollection.Cast<object>().Take(_maxLength)


text:
Q: Passing variables between files I am trying to send information between 2 files.
first file :
function findDepartment(codePostal,commune,deptId)
    {
        if (codePostal.length==5)
        {
        var fichier1 = "inclusions/ajax-cp-departement.php";
           $.ajax({
            url: fichier1,
            data: {codePostal: codePostal, commune: commune},
            success: function(response) {
                $(deptId).val(response);

            },
            error: function(xhr) {
                alert('Error!  Status = ' + xhr.status);
            }
        });
        }
    }

Second file : "inclusions/ajax-cp-departement.php"
$commune = $_REQUEST['commune'];
$commune = trim($commune);
$codePostal= $_REQUEST['codePostal'];
$codePostal= trim($codePostal);

if (strlen($commune)>0 && strlen($codePostal)>0)
{
    // Liste les communes du département demandé
    $query = "SELECT departement
    FROM commune_zone
    WHERE commune LIKE '$commune'
    AND code_postal LIKE '$codePostal'
    LIMIT 1";
}

this is how i call my function :
findDepartment(monCp,$("#ville_projet").val(), "#departement_projet");

the commune variable is not detected since it sends an empty result, when i remove commune it works, any ideas why do I have this problem ?


text:
Q: :focus on ie6 with csshover3.htc i try to use csshover3.htc on ie6  for input:focus but fail. Does :focus work on ie6 with csshover3.htc workaround?

A: There is no 100% acceptable solution and most fixes rely on Javascript to hack (fake) support into the browser. I'd recommend not bothering as the time taken to hack the support in for input:focus will not be worth it...besides IE6 is already in the "dying" phase of its lifetime.
But, if you are the peristent type then you might want to try IE7-js


text:
Q: how to create a template in XSL-FO for a table with changing no. of rows to generate a PDF? I am a newbie  to XSL-FO wants to know that how to  generate a PDF for balance sheet. So how should i create a template for that in XSL-FO as the no. of rows in the balance sheet table will vary according to the user record in the particular time duration. The records for balance sheet is coming from the API call in Java . I  just need a guidance how to create a Template in XSL-FO with variable number of rows as per user records.
Simple Example is to generate a PDF for a user having an account in any bank . The PDF will contains the transaction history of that user of previous months in a tabular format. So the no. of records in the table may vary in accordance to the no. of transaction done by different users.
And the transaction List is coming through a JAVA API call  which contains the records which need to be populated into TEMPLATE which is to created in XSl-FO.  So how that dynamic data is populated with variable no. of rows in XSL-FO ?????? An example will help
Thanks in advance

A: First, you must generate an xml document with all the data you want in your PDF. for instance:
<userData>
   <id>1234</id>
   <firstName>John</firstName>
   <lastName>Doe</lastName>
   ...
   <balance>3526.35</balance>

   ...
</userData>

Then you must write an XSL-FO template that will take such a structure as input. for instance:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:fo="http://www.w3.org/1999/XSL/Format"
        xmlns:xlink="http://www.w3.org/1999/xlink"
        xmlns:svg="http://www.w3.org/2000/svg">
    <xsl:output method="xml" encoding="UTF-8"/>
    <xsl:template match="userData">
        <fo:root>
            <fo:layout-master-set>
                <fo:simple-page-master master-name="only"
                        page-width="21cm" page-height="29.7cm"
                        margin-top="2.5cm" margin-bottom="1.5cm"
                        margin-left="4.5cm" margin-right="2.5cm">
                    <fo:region-body/>
                    <fo:region-after extent="1cm"/>
                </fo:simple-page-master>
            </fo:layout-master-set>
            <fo:page-sequence master-reference="only">
                <fo:flow flow-name="xsl-region-body">
                    <fo:wrapper font-size="12pt"
                            font-family="Arial, Geneva, Helvetica, sans-serif">
                        <fo:block font-weight="bold" space-before="1.5cm">
                            ID: <xsl:value-of select="id/text()"/>
                        </fo:block>
                        <fo:block font-weight="bold">
                            User: <xsl:value-of select="lastName/text()"/>, <xsl:value-of select="firstName/text()"/>
                        </fo:block>
                        <fo:block font-weight="bold">
                            Balance: <xsl:value-of select="balance/text()"/>
                        </fo:block>
                        <fo:table table-layout="fixed"
                                space-before="1.5cm"
                                space-after="1.5cm">
                            <fo:table-column column-width="2cm"/>
                            <fo:table-column column-width="5.5cm"/>
                            <fo:table-column column-width="5cm"/>
                            <fo:table-body>
                                <fo:table-row>
                                    <fo:table-cell>
                                        <fo:block font-weight="bold">
                                            Date
                                        </fo:block>
                                    </fo:table-cell>
                                    <fo:table-cell>
                                        <fo:block font-weight="bold">
                                            Label
                                        </fo:block>
                                    </fo:table-cell>
                                    <fo:table-cell>
                                        <fo:block font-weight="bold">
                                            Amount
                                        </fo:block>
                                    </fo:table-cell>
                                </fo:table-row>
                                <xsl:for-each select="scripture">
                                    <fo:table-row>
                                        <fo:table-cell>
                                            <fo:block>
                                                <xsl:value-of select="date/text()"/>
                                            </fo:block>
                                        </fo:table-cell>
                                        <fo:table-cell>
                                            <fo:block>
                                                <xsl:value-of select="label/text()"/>
                                            </fo:block>
                                        </fo:table-cell>
                                        <fo:table-cell>
                                            <fo:block>
                                                <xsl:value-of select="amount/text()"/>
                                            </fo:block>
                                        </fo:table-cell>
                                    </fo:table-row>
                                </xsl:for-each>
                            </fo:table-body>
                        </fo:table>
                    </fo:wrapper>
                </fo:flow>
            </fo:page-sequence>
        </fo:root>
    </xsl:template>
</xsl:stylesheet>


text:
Q: Apache as Load balancer - forcing a break in persistent connection I have setup a load balancer with Apache 2.2 via mod_proxy and mod_proxy_balancer. The load balancing works just fine, but there is one case I cannot find any configuration options for, namely, while using persistent connections to the backend servers, when one of them dies (shuts down, crashes, etc ), the existing connections to it still try to access it. Is there a way to configure the apache Load Balancer so that it quits or recreates connections to dead backend servers? In the LVS world the Ldirector has an option under Proc FS that governs just that:
/proc/sys/net/ipv4/vs/expire_quiescent_template

When this is set persisten sessions / connections ot a dead backend server will be flushed so that on the next client request they can be recreated.
Is there something similar to it in the Apache world?
Thanks in adavnce!
Cheers,
Konstantin Boyanov
P.S. In what manner does Apache check the status of the backend servers? Does it try to connect to some port or something like that? It would be great if someone can shed some ligjt on that too!
Here is my virtual host configuration file:

    ServerAdmin admin@mysite.com
    ServerName myapp.mysite.com
DocumentRoot /srv/www/vhosts/myapp.mysite.com

ErrorLog /var/log/apache2/myapp.mysite.com-error_log
CustomLog /var/log/apache2/myapp.mysite.com-access_log combined

HostnameLookups Off
UseCanonicalName Off
ServerSignature On
ScriptAlias /cgi-bin/ "/srv/www/vhosts/myapp.mysite.com/cgi-bin/"

<Location /balancer-manager>
    SetHandler balancer-manager
    Order Deny,Allow
    Deny from all
    Allow from all
</Location>

<Location /server-status>
    SetHandler server-status
    Order deny,allow
    Deny from all
    Allow from bmf.intern.netz
</Location>

Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED
<Proxy balancer://myapp>
    BalancerMember http://172.22.1.133:777/ loadfactor=10 route=1 connectiontimeout=200ms
    BalancerMember http://172.22.1.134:777/ loadfactor=10 route=2 connectiontimeout=200ms
    ProxySet stickysession=ROUTEID
    ProxySet lbmethod=byrequests
</Proxy>

ProxyPass /balancer-manager !
ProxyPass /server-status !
ProxyPass / balancer://myapp/ lbmethod=byrequests
ProxyPassReverse / balancer://myapp/

<Directory "/srv/www/vhosts/myapp.mysite.com/cgi-bin">
    AllowOverride None
    Options +ExecCGI -Includes
    Order allow,deny
    Allow from all
</Directory>

<IfModule mod_userdir.c>
    UserDir public_html
    Include /etc/apache2/mod_userdir.conf
</IfModule>

#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/srv/www/vhosts/myapp.mysite.com">

    Options Indexes FollowSymLinks
    AllowOverride None

    Order allow,deny
    Allow from all

</Directory>


text:
Q: Can't delete an iptables chain I'm having a problem on deleting a user-defined chain.
these the are rules I entered.
sudo iptables -t mangle -N internet
sudo iptables -t mangle -A PREROUTING -i eth1 -p tcp -m tcp --dport 80 -j internet
sudo iptables -t mangle -A internet -j MARK --set-mark 99
sudo iptables -t nat -A PREROUTING -i eth1 -p tcp -m mark --mark 99 -m tcp --dport 80 -j DNAT --to-destination 192.168.3.1

When i'm using -X or -D, it gives me this error
iptables: No chain/target/match by that name.

EDIT:
this is the command i used to delete the "internet" chain
iptables -F internet

i also tried using this:
iptables -D internet

and
iptables -X internet

but it still gives me the same message.

A: To flush ALL your rules use:
sudo iptables -P INPUT ACCEPT
sudo iptables -P FORWARD ACCEPT
sudo iptables -P OUTPUT ACCEPT
sudo iptables -F
sudo iptables -X
sudo iptables -t nat -F
sudo iptables -t nat -X
sudo iptables -t mangle -F
sudo iptables -t mangle -X


text:
Q: How to empty the GET values from a MySQL/jQuery ajax call If you do an ajax call to retrieve info from a MySQL database and you time the function so it runs every X seconds, I am a bit confused about where do the GET values reside, in order to empty them.
I have this code in  test.js:
var fill = function () {
    $.ajax({
    type: "GET",
    url: "refresh.php",
    dataType: "html",
    success: function( data ) {
    $( "#tb" ).append( data );
        setTimeout( fill, 5000);
        }
 });
 } ;

and in refresh.php I have the SQL query to retrieve the info. After the query, I setting the table like this:
    printf( "
".$row['name'].
"	".$row['surname'].
"	".$row['phone'].
"	".$row['date'].
"
");

How can I stop the table from populating the same row every 5 seconds? I can pass the $row['name'] values to regular php values if needed, but I don't fully get in which moment I should empty them.

A: There might be another solution to this, but I think that my problem could be easily solved by removing the contents of the table before adding another. For instance:
var fill = function () {
        $.ajax({
        type: "GET",
        url: "refresh.php",
        dataType: "html",
        success: function(data) {
            $('#tb').empty().append(data);
        }
     });
 };

 setInterval(fill, 5000);

You can also make use of setInterval() so that you don't need to define a timeout on every execution.
That will do.
Thanks!


text:
Q: Prevent button double click ionic2 I am using an button in ionic2 app, and using the (click). But if I press 2 times on the button, the same function (lets say open a modal) shows twice. How can we prevent the double click or incidental multiple clicks over a button, while it loads the async function.
I was hoping to have some dblclick event, and just prevent it, but I don't think ionic2 has that. I have tried using (tap) but it also accepts several and multiple clicks.
Do I need to deal with this manual/custom, and to set a boolean to true and false while using the async call, and use it as [disabled] property ?

A: You can use loading component just to achieve that.
import { LoadingController } from 'ionic-angular';

export class Util {
  public progressBarLoader : any;
  constructor(public loadingCtrl: LoadingController) {
  }

  showLoader(timeInMilliseconds) {
    let progressBarLoader = this.loadingCtrl.create({
      content: "Please wait...",
      duration: timeInMilliseconds
    });
    progressBarLoader.present();
  }

  hideLoader(){
    try{
      if(this.progressBarLoader != null || this.progressBarLoader != undefined){
        this.progressBarLoader.dismiss();
      }
    }catch(e){
      console.log("Busy Indecator not showing :: " + e.message);
    }
  }
}

when the button is tapped call showLoader() with very long time value, and when your async operation finished then you can call hideLoader(). This will avoid multiple tapping on the button and you dont have to deal with manually enabling/disabling the button.


text:
Q: Why does Style not work proper on Popup in WPF? I am not sure if i do not use the correct way, so I try to describe my case here. Please help to point out the detail.
The purpose of mine is to customize the WPF Popup class and implement a specific popup panel. I use the CustomControl to implement this as below:
Here is the Generic.xaml
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication3">

    <Style TargetType="{x:Type local:CCPopup}">
        <Setter Property="AllowsTransparency" Value="True" />
        <Setter Property="StaysOpen" Value="False" />
        <Setter Property="Placement" Value="Center" />
        <Setter Property="Child">
            <Setter.Value>
                <Border Background="Red"
                        Width="30"
                        Height="30" />
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

and the following is the code, which only register the meta style information:
public class CCPopup : Popup
{
    static CCPopup()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CCPopup), new FrameworkPropertyMetadata(typeof(CCPopup)));
    }
}

The problems I met until now can be summarized as below:
1) I try to write:
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication3">

    <Style TargetType="{x:Type local:CCPopup}"  BasedOn="{StaticResource {x:Type Popup}}">
        <Setter Property="AllowsTransparency" Value="True"/>
        <Setter Property="StaysOpen" Value="False" />
        <Setter Property="Placement" Value="Center" />
        <Setter Property="Child">
            <Setter.Value>
                <Border Background="Red"
                        Width="30"
                        Height="30" />
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

But this does not works, and I got the error {x:Type Popup} could not be resolved. Why?
About my MainWindow.xaml: I only add <CCPopup x:Key="popup" /> in its resource and create a button, when I click the button, I bind the popup's PlacementTarget to this button and set popup's IsOpen property to true in code.
2) When I create a instance of CCPopup in the code, such as CCPopup p = new CCPopup(), some of the Style does not works, such as AllowsTransparency and StaysOpen, will not be set to the value I give in the xaml Style. But when I create a instance from xaml <CCPopup x:Key="popup" /> and refer to it from resource in code, the style works correctly. Can you point out where I made a mistake ?
3) Just curious about why Popup class do not have Template property?
Thanks for your help.


text:
Q: How to insert database values into the template stylesheet? I have a pyramid app where I insert an entry in my database table on a Zope page template. The chameleon template engine renders it to html. What I want to do is move this entry over by the value column in the database associated with the entry. Here is what I would want to do.

${entry.name}

obviously this is incorrect. Is there a way to do this with JQuery custom css classes perhaps? I don't know how to integrate it with the pyramid framework or the sqlalchemy ORM.

A: Looks like it is exactly the same in the style sheet as it would be in the rest of the template. You just need to use ${} format. I am not sure what you would do if you wanted to put the css in a separate file though.


text:
Q: CustomView Styling I have a problem with styling customview.
I'd like to use different styles in different layouts. But my styles aren't applied.
CustomView layout:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
        <ImageView
                   android:id="@+id/img"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"/>

        <TextView
                  android:id="@+id/txt"
                  android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_gravity="bottom|center_horizontal"
</merge>

Definition in another layout:
<com.buka.customviews.Bukaview
         android:id="@+id/bukaId"
         android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             style="@style/BukaStyle1">

styles.xml
<style name="BukaStyle1">
        <item name="android:textSize">10sp</item>
</style>

<style name="BukaStyle2">
        <item name="android:textSize">20sp</item>
</style>

Thanks

A: You should create a custom attribute :
<attr name="BukaStyleTextSize" format="dimensions" />
Then in the TextView tag of your custom view layout, put :
android:textSize="?attr:BukaStyleTextSize"
And finally, in your styles in styles.xml put :
<item name="BukaStyleTextSize>10sp</item>


text:
Q: Two FIND_IN_SET in a single query is not working Below is the table structure (invite table):-
id   user_id   doc_name        discussion_topic     invited_friends  accepted_invitation

1     1        IEP Form-1.docx   first topic        2,3,4             NULL

Now:
When I did query:-
SELECT * from invite WHERE  (FIND_IN_SET(2,invited_friends) > 0)

I got this record perfectly(shown above).
But when I did:
SELECT * from invite WHERE  (FIND_IN_SET(2,invited_friends) > 0) AND (FIND_IN_SET(2,accepted_invitation) =0)

I didn't get the above record, not any error too.
Also when I did:
SELECT * from invite WHERE user_id <>1 AND (FIND_IN_SET(2,invited_friends) > 0) AND (FIND_IN_SET(2,accepted_invitation) =0)

Again I didn't get the above record, not any error too.
Actually the  scenario I have to check that a given id(example 2)  is not equal to user_id and must be in invite_friends(never be null) and not in accepted_invitation(accepted_invitation will be null or , separated id values).
What mistake I did in last two queries?
Note: I am using these query directly in phpmyadmin

A: You should use this
Replace '= 0' to 'is null'
SELECT * from invite WHERE  (FIND_IN_SET(2,invited_friends) > 0) AND (FIND_IN_SET(2,accepted_invitation) is null )

A: Use IFNULL for the column names:
SELECT *
FROM   invite
WHERE  user_id <> 1 AND
      (FIND_IN_SET(2, IFNULL(invited_friends, 0)) > 0)  AND
      (FIND_IN_SET(2, IFNULL(accepted_invitation, 0)) = 0);

Check the SQL Fiddle: http://sqlfiddle.com/#!9/98d95/9

A: To check your scenario use
SELECT * from invite WHERE user_id <>2// check user ID not equal to 2
AND (FIND_IN_SET(2, invited_friends) > 0)// 2 present in invited_friends
AND ((FIND_IN_SET(2, accepted_invitation) = 0)|| (FIND_IN_SET(2, accepted_invitation) IS NULL))// check 2 is null and not present in accepted_invitation


text:
Q: Inductance of a solenoid? My textbook is using Faraday's law to explain the self inductance that happens in a solenoid with changing current.
According to Wikipedia, Faraday's Law is:

The induced electromotive force in any closed circuit is equal to the negative of the time rate of change of the magnetic flux through the circuit.

The loops in a solenoid aren't closed - it's loops are "almost closed", but the beginning and end don't touch each other.
So how can Faraday's Law be used?

A: Faraday's law is given as follows
$$\oint \vec{E}\cdot\vec{dl} = -\frac{\mathrm{d} }{\mathrm{d} t}\iint_{ }^{ }\vec{B}\cdot\vec{dA}$$
Look at the R.H.S of the equation. It is the changing magnetic flux( w.r.t time ) that is responsible for the induced $E.M.F$. Although the coil of the solenoid does not consist of perfect conducting loops, the magnetic flux associated with the conducting loops depends on the $surface$ $area$ $enclosed$ by the coil of the solenoid.

You clearly see that the loop I have drawn encloses some area. The magnetic flux is associated with this area.

Here, I have drawn a loop somewhere in the middle of the solenoid. Although the loops are not perfect, they enclose some area. We are concerned about the area enclosed while calculating the magnetic flux.
In solenoids you'll find that the coil consists of loops that are tightly wound. This configuration can be approximately treated as loops arranged close together.

A: I suspect this is an approximation that works well.
Each piece of the coils is almost exactly aligned with the induced electric field $\vec{E}$ at that position. (To be more accurate, some are exactly aligned, but most aren't. Try imagining a coil wrapped around a cylinder.) In this way, the EMF $\oint \vec{E}\cdot d\vec{l}$ for the closed loop is nearly identical for a single "loop" of wire that is open.  This effect is minimized if the coils are tightly wound.

A: Inside the solenoid there's no (component of the) magnetic field that isn't perpendicular to the loops, so treating a solenoid as if it has closed loops is valid approximation.
Perhaps you can understand it better if you approach the solenoid as a single wire and see what the emf does from that point of view.


text:
Q: why Intent.EXTRA_INITIAL_INTENTS not working in android 10 I am trying to share some text, In Android 10 always show max 3 apps in my mobile have WhatsApp but this not displaying here
This code is properly working in below 10 devices but could not find the reason why in android 10 is filtering out.
fun onShareClick() {
        val intentShareList = ArrayList<Intent>()
        val shareIntent = Intent()
        shareIntent.action = Intent.ACTION_SEND
        shareIntent.type = "text/plain"
        val resolveInfoList = packageManager.queryIntentActivities(shareIntent, 0)
        for (resInfo in resolveInfoList) {
            val packageName = resInfo.activityInfo.packageName
            val name = resInfo.activityInfo.name
            if (packageName.contains("com.facebook") ||
                packageName.contains("com.twitter.android") ||
                packageName.contains("com.google.android.gm") ||
                packageName.contains("com.android.mms") ||
                packageName.contains("com.whatsapp")
            ) {
                val intent = Intent()
                intent.component = ComponentName(packageName, name)
                intent.action = Intent.ACTION_SEND
                intent.type = "text/plain"
                intent.putExtra(Intent.EXTRA_SUBJECT, "Your Subject")
                intent.putExtra(Intent.EXTRA_TEXT, "Your Content")
                intentShareList.add(intent)
            }
        }
        if (intentShareList.isEmpty()) {
            Toast.makeText(this@MainActivity, "No apps to share !", Toast.LENGTH_SHORT).show()
        } else {
            val chooserIntent = Intent.createChooser(intentShareList.removeAt(0), "Share via")
            chooserIntent.putExtra(
                Intent.EXTRA_INITIAL_INTENTS,
                intentShareList.toTypedArray()
            )
            startActivity(chooserIntent)
        }
    }

In the intentShareList contains WhatsApp info but not displaying

A: I had the same issue. It seems the problem is in some Android 10 devices (like Samsung), not all. I solved using Intent.EXTRA_EXCLUDE_COMPONENTS instead of Intent.EXTRA_INITIAL_INTENTS, and creating an array of ComponentName to be excluded. Refactoring your code:
fun onShareClick() {
    val excludedComponents = ArrayList<ComponentName>()
    val shareIntent = Intent()
    shareIntent.action = Intent.ACTION_SEND
    shareIntent.type = "text/plain"
    val resolveInfoList = packageManager.queryIntentActivities(shareIntent, 0)
    for (resInfo in resolveInfoList) {
        val packageName = resInfo.activityInfo.packageName
        val name = resInfo.activityInfo.name
        if (!(packageName.contains("com.facebook") ||
            packageName.contains("com.twitter.android") ||
            packageName.contains("com.google.android.gm") ||
            packageName.contains("com.android.mms") ||
            packageName.contains("com.whatsapp"))
        ) {
            excludedComponents.add(ComponentName(packageName, name))
        }
    }
    if (excludedComponents.size()==resolveInfoList.size()) {
        Toast.makeText(this@MainActivity, "No apps to share !", Toast.LENGTH_SHORT).show()
    } else {
        val chooserIntent = Intent.createChooser(shareIntent , "Share via")
        chooserIntent.putExtra(
            Intent.EXTRA_EXCLUDE_COMPONENTS,
            excludedComponents.toTypedArray()
        )
        startActivity(chooserIntent)
    }
}

A: I think you should create your chooser using the initial intent and add your intentShareList as extra, like this:
val chooserIntent = Intent.createChooser(shareIntent, "Share via")
        chooserIntent.putExtra(
            Intent.EXTRA_INITIAL_INTENTS,
            intentShareList.toTypedArray()
        )
        startActivity(chooserIntent)

I think it will bring what you want. Let me know if it helps :)
EDIT: Even if you put on your shareIntent a inicial EXTRA_INTENT and  a type, Android Q will ignore what you added on EXTRA_INITIAL_INTENTS, so it wont help
I was reading about this on that issue and I think it wont be fixed, take a look = https://issuetracker.google.com/issues/134367295
Also, there some information on documentation that says using EXTRA_INITIAL_INTENTS to personalized data is not recomended, and its was made to helping share links and it can reduce the apps who will appear, take a look = https://developer.android.com/training/sharing/send
Well, Im very sad about that, Idk what do to also, maybe a unique text... :(

A: My answer may not answer OP's question but if you want to exclude a specified package, you can refer to it. This solution also works on pre-Android 11 OS.
For me, EXTRA_INITIAL_INTENTS doesn't work on Android 11. So I handled 2 flows for 2 cases (Android 11 or later and pre-Android).
The below code will exclude Facebook out of share options.
1. Add the Facebook package to Android Manifest for expanding package visibility on Android 11. You can check out
<manifest ...>
...

    <queries>
        ...
        <package android:name="com.facebook.katana" />
    </queries>
...
</manifest>

2. Create an intent chooser:
   private fun getShareChooserWithoutFacebook(
        context: Context,
        template: Intent
    ): Intent {

        // get available share intents
        val targets: MutableList<Intent> = mutableListOf()
        val candidates: List<ResolveInfo> =
            context.packageManager.queryIntentActivities(template, 0)
        val excludedComponents = ArrayList<ComponentName>()

        // remove facebook which has a broken share intent
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.R) {
            for (candidate in candidates) {
                val packageName = candidate.activityInfo.packageName
                if (!packageName.equals("com.facebook.katana")) {
                    val target = Intent(Intent.ACTION_SEND)
                    target.type = "text/plain"
                    target.putExtra(
                        Intent.EXTRA_SUBJECT,
                        template.getStringExtra(Intent.EXTRA_SUBJECT)
                    )
                    target.putExtra(
                        Intent.EXTRA_TEXT,
                        template.getStringExtra(Intent.EXTRA_TEXT)
                    )
                    target.setPackage(packageName)
                    targets.add(target)
                }
            }
        } else {
            for (candidate in candidates) {
                val packageName = candidate.activityInfo.packageName
                val name = candidate.activityInfo.name
                if ((packageName.equals("com.facebook.katana"))) {
                    excludedComponents.add(ComponentName(packageName, name))
                }
            }
        }

        var chooserIntent = Intent.createChooser(template, context.getString(R.string.settings_send_via))

        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.R) {
            chooserIntent =
                Intent.createChooser(targets.removeAt(0), context.getString(R.string.settings_send_via))
            chooserIntent.putExtra(
                Intent.EXTRA_INITIAL_INTENTS,
                targets.toTypedArray()
            )
        } else {
            chooserIntent.putExtra(
                Intent.EXTRA_EXCLUDE_COMPONENTS,
                excludedComponents.toTypedArray()
            )
        }

        return chooserIntent

    }

3. Open the intent chooser
   fun openShareChooser(context: Context, title: String?, content: String?) {
        val template = Intent(Intent.ACTION_SEND)
        template.type = "text/plain"
        template.putExtra(Intent.EXTRA_SUBJECT, title)
        template.putExtra(Intent.EXTRA_TEXT, content)
        context.startActivity(
            getShareChooserWithoutFacebook(context, template)
        )
    }


text:
Q: C# 3.0 implicit cast error with class and interfaces with generic type I implemented a few dependencies (which are the part of MVP pattern). Now, when I try to perform casting, VS informs about an error.
Definitions:
interface IView
{
     void setPresenter(IPresenter<IView> presenter);
}

interface IViewA : IView
{
}

interface IPresenter<T> where T : IView
{
    void setView(T view);
}

class PresenterA : IPresenter<IViewA>
{
}

Implicit cast:
IPresenter<IView> presenter = new PresenterA();

Compile error:
Cannot implicitly convert type 'PresenterA' to 'IPresenter'. An explicit conversion exists (are you missing a cast?)
Explicit cast:
IPresenter<IView> presenter = (IPresenter<IView>)new PresenterA();

Run-time error: InvalidCastException
How can I solve it to keep this conception? Conception with generic type (my previous one is without it). I've tried variance and contravariance issue (in and out) as mentioned in the others posts, but there was errors too (under VS 2010).

A: The fact that IViewA derives from IView does not automatically mean that IPresenter<IViewA> derives from IPresenter<IView>. In fact IPresenter<IViewA> and IPresenter<IView> are two distinct types that do not have an inheritance relation between them. Their only common ancestor is object.
Let's look at an example. Assume that we have a class Animal, a class Cat deriving from Animal and a class Dog deriving from Animal. Now let's declare two lists
List<Animal> animals;
List<Cat> cats = new List<Cat>();

And let's also assume that the following assignment was possible:
animals = cats;
animals.Add(new Cat()); // OK
animals.Add(new Dog()); // Ooops!

The list is in reality a cats list and we are trying to add a dog! Therefore the two types List<Animal> and List<Cat> are not allowed to be assignment compatible.

A: This question is really about covariance and contravariance of generic types. We have

an IViewA is an IView

but that does not automatically mean that

an IPresenter<IViewA> is an IPresenter<IView>

When the conclusion holds, we say that IPresenter<T> is covariant in T. In C# one makes an interface covariant by putting an out keyword before the type parameter in question (here T), as in:
interface IPresenter<out T>  ...

Since you didn't put the out keyword, what you do is not allowed.
But it is only safe to make a type covariant in T if all the uses of T goes "out". For example it is okay to use T as return type of methods or as property type for get-only properties.
Your interface uses T in an "in" position, namely as a value parameter (i.e. a parameter without the ref (or out) modifier). So it would be illegal to make your interface covariant. See some of the other answers for examples of what could happen if this restriction wasn't there.
Then there's the notion of contravariance, which for IPresenter<> means that

an IViewA is an IView

implies that

an IPresenter<IView> is an IPresenter<IViewA>

Notice how the order changes with contravariance. Contravariance is only safe (and only allowed) when the type parameter is used in "in" positions, such as value parameters.
Based on the only member, it would be legat to declare your interface contravariant:
interface IPresenter<in T>  ...

where in means contravariant, of course. But it will reverse the "direction" in which implicit conversions are allowed.

A: By storing a PresenterA in an IPresenter<IView>, you're saying "this object has a method setView which accepts any IView".
However, PresenterA's method setView only accepts an IViewA. If you passed it an IViewSomethingElse, what would you expect to happen?
It won't work, so the compiler doesn't allow it.

A: What you're trying to do doesn't make sense. Imagine the following (including the one variance thingie that makes sense):
interface IView {}

interface IViewA : IView {}
class ViewA : IViewA {}

interface IViewB : IView {}
class ViewB : IViewB {}

interface IPresenter<in T> where T : IView
{
    void setView(T view);
}

class PresenterA : IPresenter<IViewA>
{
    public void setView(IViewA view) {}
}

class PresenterB : IPresenter<IViewB>
{
    public void setView(IViewA view) {}
}

Now, if the conversion you're trying to do were valid, you could do this:
IPresenter<IView> presenter = new PresenterA();
presenter.setView(new ViewB());

As you can see, this isn't typesafe. I.e. the relationship you believe exists between the types isn't there.
What variance lets you do is the opposite:
class Presenter : IPresenter<IView>
{
    public void setView(IView view) {}
}

IPresenter<IViewA> presenter = new Presenter();

Presenter.setView() can accept any IView parameter, therefore it can accept an IViewB. This is also why the compiler mentions an explicit conversion. It's to let you do the following:
IPresenter<IViewA> presenterA = new Presenter();
IPresenter<IView> presenter = (IPresenter<IView>) presenterA;

That is, to check if the value you're assigning to presenter at runtime happens to be one that's "generic enough", even if its compile-time type isn't.


text:
Q: Jquery ajax: object in data object I need to pass an object within the data object but it's not working
I use the following function I found on this very site, very useful, to convert form data to JSON
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

and then I need to pass the object as a sub-object, but it's not working. Filters isn't even showing up in the query string parameters in the inspector
var filters = $('.filtersForm').serializeObject();

$.ajax({
    type: 'GET',
    data: {script:'search',page:page,filters:filters},
    success: function(data){
    }
});

See how "filters" is missing in the picture
Can someone please explain why I can't pass an object like that?

A: Try this instead:
$.ajax({
  type: 'POST',
  data: JSON.stringify({
    script: 'search',
    page: page,
    filters: filters
  }),
  contentType: 'application/json'
});

*

*Changed type from GET to POST.  This will allow you to send a request body.

*Stringify your data parameter using the built-in JSON object to stringify your JS object to a JSON-formatted string.  (older browsers may not have this built-in object, in that case, add it using json2.js)

*Set contentType to application/json.  This basically states that the request-body is of this type... which it is because we just stringified it to JSON.

A: Try to specifiy your filters
For example in try :
jsonfilter = JSON.stringify(filters);
If youre using MVC and ASP.Net you can try
In your HTTPWebMethode which have a jsonResult as Return you can try to specifiy parameters
  public JsonResult myPostMethode(string script,object page,List<object> filters){

    //make some usefull
    var model = script;
    return(model,JsonRequestBehavior.AllowGet);
}


text:
Q: Escaping javascript apostrophe / quotation for eval function, so it still works as a selector? Following js code in a jsfiddle:
JS:
function myFunc(foo){
    $(foo).val("magic, it works!... NOT");
}

var x = "myFunc('input[name=\\'testme\\']')";

eval (x);

HTML:
<input name="testme" type="text" />

Someone got a clue what I could do?

A: You need to give this way:
function myFunc(foo){
    $(foo).val("magic, it works!... NOT");
}

var x = "(myFunc('input[name=\"testme\"]'))";

eval(x);

Combine them inside the (). But you need to also consider this. You need to give in No Wrap (body).
Fiddle: http://jsfiddle.net/praveenscience/243ur/2/

A: Don't use eval.
In your example, you are passing eval a constant string. This can be replaced with simply the contents of the string. That's all eval is actually doing, except using eval makes it impossible for JavaScript engines to optimise your code.
Your example can be replaced with:
function myFunc(foo){
    $(foo).val("magic, it works!... NOT");
}

myFunc('input[name=\'testme\']');


text:
Q: Como sincronizar duas TListViews? Estou trabalhando em um App para Android utilizando o Delphi XE8 e eu preciso sincronizar duas ListViews para que quando o usuário baixar uma, a outra baixe junto.
Como eu faço isso no Delphi?

A: Se utilizar uma versão superior ao Delphi XE 8, clica no events do listview1 e de seguida clica no evento OnScrollViewChange e adiciona o seguinte código:
Listview2.ScrollViewPos := Listview1.ScrollViewPos;

Feito isso a partir deste momento sempre que mexer na lista 1 a lista 2 fará scrool para a mesma localização que a primeira.


text:
Q: Print awk's current new line character How can I find what new line character is in my file when using awk?
I know the default is \n but this is what manual says. I want to see it with my own eyes.
I have just started learning awk and how to change the output record separator but first I want to see what the actual ORS is. The first 7 chapters of awk manual didn't address this.

A: You wouldn't use Awk for this, but rather od (octal dump)
For example, here is a simple text file created on a linux system with vi:
lizard:~tmp$ cat foo
This is a sentence.

Here is the output of od:
lizard:~tmp$ od -a foo
0000000   T   h   i   s  sp   i   s  sp   a  sp   s   e   n   t   e   n
0000020   c   e   .  nl  nl
0000025

Notice that this file contains a blank line below the sentence, as there are two nl's  (New Line = Line Feed = \n). "sp" represents a space character. If I dump a similar file created on a Windows system it would probably look like this:
lizard:~tmp$ od -a foo-dos
0000000   T   h   i   s  sp   i   s  sp   a  sp   s   e   n   t   e   n
0000020   c   e   .  cr  nl  cr  nl
0000027

This is exactly the same file, but created on a Windows system.
DOS/Windows files us \r\n (Carriage Return Line Feed) for text file line endings.

A: You can inspect it by, e.g.:
awk 'BEGIN { printf "%s", ORS }' | od -c


text:
Q: Calculating Value Count and Percentage I have a table
Currently Enrolled
The table is basically to get an idea of how many supporters, undecided, and opposition they were. Then once I get the count I wanted to then do another calculation to find out what that percentage was.
Essentially what I want to be able to do is:

*

*Count the total number of supporters:
SELECT count(*) AS 'SUPPORTERS' FROM CURRENTLY ENROLLED WHERE
status = 'Supporter'
results were 13

*Count the total number of opposition:
SELECT count(*) AS 'OPPOSITION' FROM CURRENTLY ENROLLED WHERE value = 'Opposition'
results were 11

*Count the total number of undecided persons using a similar statement:
SELECT count(*) AS 'UNDECIDED' FROM CURRENTLY ENROLLED WHERE value = 'Undecided'
results were 5
So with the count, I can see that they're 29 total individuals. I wanted to be able to get the percentage of each of them separately. Something like
13/29 * 100 = 44%
11/29 * 100 = 37%
5/29 * 100 = 17%
However, I am lost on how to write this query.
Hope I am making this clear as to the intentions.

A: Use a CTE for the total and group by status for the percentage:
with cte as (select count(*) as cnt from `currently enrolled`)
select status, sum(100)/cnt
from `currently enrolled`, cte
group by 1


text:
Q: Compare two tables and give the rows that are different I have two tables. There are two columns common in the tables. Table one is the parent table and table 2 is a subset of the primary table. I want to get the rows which they do not have in common.
Ex:

*

*table 1: a, b, c, d

*table 2: c

Expected result: a,b,d

A: This will get you what you want.
SELECT t1.val
FROM table1 t1, table2 t2
WHERE t1.val != t2.val

Output:
val
a
b
d

SQL Fiddle: http://sqlfiddle.com/#!3/97610/2/0

A: Try this solution, you don't need any extra ordinary query
SELECT tab1.val
FROM table1 tab1, table2 Tab2
WHERE tab1.FieldName <> tab2.FieldName

A: If your DBMS support MINUS statement you can use:
SELECT COL1
FROM TABLE1
MINUS
SELECT COL1
FROM TABLE2

Note that minus is positional. You won't get the same result switching the two SELECT statements.

A: Select    X.ID
From    Table1    X
Right    Join    Table2    Y    ON    (X.ID =  Y.ID)
Where     Y.ID   IS     NULL

There are two tables Table1 and Table2   having reference column  as  ID .   Above query  shows output where   Unmatched IDs in   table 1 are  showed.

A: Try this....
Referring c as the common column...
SELECT *
FROM Table1
WHERE c NOT IN
(SELECT c FROM Table2);


text:
Q: kubectl get hpa targets:unknow I have installed kubeadm. Heapster show me metrics, but hpa no
kubectl get hpa
NAME      REFERENCE          TARGETS          MINPODS   MAXPODS   REPLICAS   AGE

httpd     Deployment/httpd   <unknown> / 2%   2         5         2          19m

kubeadm version
kubeadm version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.6", GitCommit:"7fa1c1756d8bc963f1a389f4a6937dc71f08ada2", GitTreeState:"clean", BuildDate:"2017-06-16T18:21:54Z", GoVersion:"go1.7.6", Compiler:"gc", Platform:"linux/amd64"}

docker version
Client:
Version:      1.11.2
 API version:  1.23
 Go version:   go1.5.4
 Git commit:   b9f10c9
 Built:        Wed Jun  1 22:00:43 2016
 OS/Arch:      linux/amd64

A: I found the solution:
kubectl describe hpa

failed to get cpu utilization: missing request for cpu on container httpd in pod default/httpd-796666570-2h1c6

Change the yaml of deployment and add:
resources:
  requests:
    cpu:400m

Then kubectl describe hpa

failed to get cpu utilization: unable to get metrics for resource cpu: no metrics returned from heapster

Wait a few minutes and all works fine.

A: You may have had to enable a metrics-server. Heapster is now deprecated. Also make sure you have Kubernetes version greater than 1.7. You can check this buy typing kubectl get nodes.
You can enable the metrics server by looking at the minikube addons.
minikube addons list gives you the list of addons.
minikube addons enable metrics-server enables metrics-server.
Wait a few minutes, then if you type kubectl get hpa the percentage for the TARGETS <unknown> should appear.

A: In kubernetes it can say unknown for hpa. In this situation you should check several places.

*

*In K8s 1.9 uses custom metrics. so In order to work your k8s cluster

with heapster you should check kube-controller-manager.
Add these parameters.

*

*--horizontal-pod-autoscaler-use-rest-clients=false

*--horizontal-pod-autoscaler-sync-period=10s

based on https://github.com/kubernetes/kubernetes/issues/57673

*Case you should change your heapster deployment.

*

*--source=kubernetes:https://kubernetes.default?kubeletPort=10250&kubeletHttps=true&insecure=true parameter is enough.

I found this link very informative https://blog.inkubate.io/deploy-kubernetes-1-9-from-scratch-on-vmware-vsphere/

A: you have to enable the metrics server which you can do it using the helm chart
helm chart is easy way to add the metrics server
helm install stable/metrics-server

wait for 3-4 minutes after pods started running and you open kubectl get hpa you can check there target is showing values.

A: Make sure your spec has this part properly configured:
 metrics:
  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: {{ .Values.autoscaling.targetMemoryUtilizationPercentage}}

In my case I had name: Memory with uppercase M and that cost me a day to find out.


text:
Q: How do I print a book (A6 size), 4 times into an A4 size paper? I have a latex prepared doublesided pdf, it has 130 pages.
I just want a result where I can cut the A4 paper into 4 parts and get 4 separate a6 books. No need to set frames, just cut the paper in each half.
I now there are many instructions on how to insert certain size page into a pdf of other size, but none gives instructions on how to place the same document multiplied by four and with this x4 page order on each page.
So, the first A4 page should be seen with 4 times the first a6 page, and the second page the same, and so on.
1st page (with 4 a6 sized print)

*

*[1][1]

*[1][1]

2nd page (with 4 a6 sized print)

*

*[2][2]

*[2][2]

etc.

A: \documentclass{article}
\usepackage[a4paper,margin=0pt,nofoot,nohead]{geometry}
\usepackage{graphicx}
\newcommand{\fourplay}[2]% #1 = page number (text), #2 = file name
{\pagebreak\includegraphics[page=#1]{#2}\includegraphics[page=#1]{#2}\par
\includegraphics[page=#1]{#2}\includegraphics[page=#1]{#2}\par}
\parindent=0pt
\parskip=0pt
\begin{document}
\loop\fourplay{\thepage}{test5.pdf}
\ifnum\value{page}<2\relax \repeat% 2=number of pages
\end{document}

where the file test5.pdf was created using
\documentclass{article}
\usepackage[a6paper]{geometry}
\usepackage{lipsum}
\begin{document}
\lipsum[1-10]
\end{document}


text:
Q: How to detect tabs in PDFs? For example, say i want to extract all the clauses from this PDF, into individual excel cells for example.
Example PDF with clauses/tabs
If i can detect every time there is a tab i.e. the space between the clause number and the text, shown in the image, I think this will detect the start of every clause in the PDF, and i could just extract all the text between the start of clauses.

I've tried python pdf readers, i've tried converting the pdf to a word document and then using python docx readers. I haven't been able to consistently detect the tabs that are so clear in the PDF though.
Anyone know how i could do this?


text:
Q: Show a piecewise function is a continuous function. Let $f:[0,1]\to \Bbb R$ be  a function defined as follows:
$$f(x)= \begin{cases}
      mx & x\in \Bbb Q\Bbb\cap[0,1] \\
      m(x-1) & \text{Otherwise}
   \end{cases}$$ where $m>0.$ Discuss the continuity of $f$. Here is my attempt:
Claim: $f$ is discontinuous everywhere.  Let $c\neq 0$, we will show that $f$ is not continuous at $c..$ Conisder cases for $c$:
Case I: If $c$ is a rational number. By the density of irrational numbers, we can find a sequence $x_n$ of irrational numbers such that $x_n$ converges to $c.$   So, $f(x_n)=m(1-x_n)$ which converges to $m(1-c)$ but $f(c)=mc$ and   $m(1-c)\neq mc$.  So,that means, $f(x_n)$ does not converge to $f(c)$. Thus, $f$ is not at $c$.
Case II: If $c$ is an irrational number. The argument will quite similar.
Edit. There was an error in the OP and I changed based on Mr.
Andreas comment.
I think everything works well now.

A: Because of the density we can choose some sequences $x_n$ and $y_n$ that are in rational and irrational numbers in $[0, 1]$ respectively, such as both converge to some $x_0\in[0, 1]$. So if the function were continuous then the limits of $f(x_n)$ and $f(y_n) $ would be the same, but $mx_0=m(x_0-1) $ does not hold for any real number, thus is discontinuous at every point


text:
Q: False monochotomy? Dichotomy for one? I often see people complaining about a politician, e.g. "X is terrible". But instead of evaluating X in an absolute sense, X should be compared with the other available options. So if X was running against Y, the correct question to ask would be "How good/bad is X as opposed to Y?". Or even better "How is X compared to other candidates past or present?"
Would this be a false monochotomy?


text:
Q: Is eslint-config-airbnb-base@13.1.0 removed from npm? It is not getting installed While installing packages using npm on server, I am getting 404 error related to this module, eslint-config-airbnb-base@13.1.0. Can anyone help me resolve this?
I tried to install it separately too, but still got errors related to 404.
Here's the logs:
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: eslint-config-airbnb-base@13.1.0
npm ERR! Found: eslint@6.0.1
npm ERR! node_modules/eslint
npm ERR!   dev eslint@"6.0.1" from the root project
npm ERR!   peer eslint@"2.x - 6.x" from eslint-plugin-import@2.18.0
npm ERR!   node_modules/eslint-plugin-import
npm ERR!     dev eslint-plugin-import@"2.18.0" from the root project
npm ERR!     peer eslint-plugin-import@"^2.14.0" from eslint-config-airbnb-base@13.1.0
npm ERR!     node_modules/eslint-config-airbnb-base
npm ERR!       dev eslint-config-airbnb-base@"13.1.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer eslint@"^4.19.1 || ^5.3.0" from eslint-config-airbnb-base@13.1.0
npm ERR! node_modules/eslint-config-airbnb-base
npm ERR!   dev eslint-config-airbnb-base@"13.1.0" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: eslint@5.16.0
npm ERR! node_modules/eslint
npm ERR!   peer eslint@"^4.19.1 || ^5.3.0" from eslint-config-airbnb-base@13.1.0
npm ERR!   node_modules/eslint-config-airbnb-base
npm ERR!     dev eslint-config-airbnb-base@"13.1.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /root/.npm/eresolve-report.txt for a full report.

A: It was a peer dependency issue usually occurs in npm version => 7, hence we have to use a flag, and install, the command goes like
npm i --leagcy-peer-deps


text:
Q: How to hit the breakpoint at catch block when working with TPL
As I started understanding thru the TPL. I got stuck over in this code. I have 2 task. Task1 thows ArgumentOutOfRangeException and Task2 throws NullReferenceException.
Consider this below code:
static void Main(string[] args) {

            // create the cancellation token source and the token
            CancellationTokenSource tokenSource = new CancellationTokenSource();
            CancellationToken token = tokenSource.Token;

            // create a task that waits on the cancellation token
            Task task1 = new Task(() => {
                // wait forever or until the token is cancelled
                token.WaitHandle.WaitOne(-1);
                // throw an exception to acknowledge the cancellation
                throw new OperationCanceledException(token);
            }, token);

            // create a task that throws an exceptiono
            Task task2 = new Task(() => {
                throw new NullReferenceException();
            });

            // start the tasks
            task1.Start(); task2.Start();

            // cancel the token
            tokenSource.Cancel();

            // wait on the tasks and catch any exceptions
            try {
                Task.WaitAll(task1, task2);
            } catch (AggregateException ex) {
                // iterate through the inner exceptions using
                // the handle method
                ex.Handle((inner) => {
                    if (inner is OperationCanceledException) {
                        // ...handle task cancellation...
                        return true;
                    } else {
                        // this is an exception we don't know how
                        // to handle, so return false
                        return false;
                    }
                });
            }

            // wait for input before exiting
            Console.WriteLine("Main method complete. Press enter to finish.");
            Console.ReadLine();
        }

I have put the try catch block for Task.WaitAll(task1, task2). It should ideally hit the breakpoint in ex.handler statement inside Catch block. As I understand that whatever may be the result it should hit the catch block.
Same case is happening if I have task1.Result/task2.Result.
My Question is: In debug mode why isn't the breakpoint being hit at the catch block when I am intentionally throwing it from task as I want to examine the statements under catch block. It just puts yellow mark at saying "NullReferenceException unhandled by the user code".
Task task2 = new Task(() => {
                throw new NullReferenceException();
            });

How do I hit the break point at catch block???
Thanks for replying :)

A: As Arne Claassen explained in their comment, the debugger pauses execution at the point the original exception is thrown because the thread does not handle the exception. If you continue exceution (F5 or play button), the program should continue to the point where you are handling the exception in your continuation.


text:
Q: onBlur function - setState incorrect I am trying to run an unit test for the following code. I already test onClick and onChange and this.props
onBlur seems not to be working correctly based on the setState
Here is the method that onBlur is calling
 handleChange = (e) => {
let localState = Object.assign({}, this.state)
localState[e.target.name] = e.target.value
let settingsObj = {
  0: {
      matchValue: e.target.name,
      value: e.target.value,
      transformType: 'replaceElement'
  }
}
if(e.target.name === 'viewtitle'){
  this.props.updateViewName(e.target.value);
}
this.props.updateViewXMLValue(settingsObj)
this.setState(localState)
}

Here is the onBlur event:
Title
    </div>
    <div className='tab-input-container'>
     <input name='viewtitle' type='text' className="shape-dropdown" placeholder='Title' defaultValue={this.props.defaultData.viewtitle[0].length === 0 ? null : this.props.defaultData.viewtitle[0]} onBlur={this.handleChange}/>
    </div>

Here is my test file:
it('Testing onBlur event on ViewTitle', () => {
 baseProps.updateViewName.mockClear();
 wrapper.setProps({
   defaultData:{
    viewtitle:[ [] ],
   }
  });
 wrapper.setState({
    localState: "blur"
 });
 wrapper.update()
 wrapper.find('input[name="viewtitle"]').simulate('blur',
 {
   target: {
    value:'blur-Test',
    name:'viewtitle'
    }
});
  expect(baseProps.updateViewName).toHaveBeenCalled();
  expect(wrapper.state('localState')).toEqual('blur-Test');
});

It seems that target value does not interfere

A: According to your code: localState[e.target.name] = e.target.value the onBlur handler sets the state objects viewtitle key to whatever the input is.
So if your original state was {localState: "blur"}, the new state would be {localState: "blur", viewtitle: "blur-test" }, which your test will fail as it is looking at the localState key.


text:
Q: Как отформатировать и записать дату в БД? Дата после выбора в input имеет вид 31.12.2016, как мне записать её в бд, если там нужно чтобы она была в формате Y-m-d ?
$termin = $product['date_available']; //здесь я получаю дату в формате dd.mm.yyyy

$this->data['date_available'] = date("D-m-Y", strtotime($termin)); //сюда нужно передать дату в формате yyyy-mm-dd

A: Вариант 1 - привести датe к формату до записи в базу данных.
$this->data['date_available'] = date("D-m-Y", strtotime($termin));

замените на
$this->data['date_available'] = date("Y-m-d", strtotime($termin));

Вариант 2 - привести к нужному формату в запросе к бд:
STR_TO_DATE('29.10.2016','%d.%m.%Y')

A: $date = "31.12.2016";
echo date("Y-m-D", strtotime($date));
Вот так можно переформатировать дату

A: Мне кажется для таки вещей лучше использовать средства самого MySQL
INSERT INTO table_name VALUES ('', STR_TO_DATE(  '31.12.2016',  '%d.%m.%Y' ))


text:
Q: Is there a tool to know if a program is requesting WM_INPUT events? WM_INPUT events are the raw input events that windows translates directly from each device. E.g. you get a message with raw mouse deltas from each mouse you have plugged, instead of the windows cursor position that you get with the normal input events. A program has to register a callback, in order to receive those events.
I would like to know if a program, e.g. a videogame, has requested to get those events. A powershell script or bat would be fine.
https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-input

A: There're apps out there that can give this to you, I believe a popular albeit old one had something with 'spy' in the name. Vs also seems to have something integrated which is called Spy++.
Also Inspect;
https://learn.microsoft.com/en-us/windows/win32/winauto/inspect-objects?redirectedfrom=MSDN
Windows internals suite could also help, like procmon;
https://learn.microsoft.com/en-us/sysinternals/downloads/procmon
Here's a better list with some options:
https://stackoverflow.com/a/2425315/4122889