text:
Q: Passing Arrays and a Range to Excel's .sort Algorithm There are essentially 2 questions:
For excel's .sort function: How do I add keys when I do not know how many keys (headers) a given sheet is going to have? (See Below)
I want to pass a number of predefined arrays, containing information on how to sort a given selection, to excel's .sort algorithm... How do I do this correctly?
Problem Description:
I have a sheet that lists headers in the first row. The headers are different names and there can be a variable number of headers present in the first row. The headers describe different details of metrics listed in the rows below on the sheet (one metric/row).
I need to write a code such that I can sort certain bound-together rows, not the entire sheet.  For instance, I might need to sort the 28th-35th row. This will be passed to this program by the variable inRange.  However, I also want to be able to configure the sort priority and how each column gets sorted everytime I run the macro. (note that a row can only change position as a whole, individual cells within the row cannot change position)
I have the following Global arrays which describe the headers:
headRow - contains an array of the header names as strings listed in order of the column
prLst - contains an array of integers (input as strings) that determine priority of each of the headers.  The position of the integers in the array is the column number which they describe.
colIsString - contains Boolean determining if items listed in a given column are strings or integers.  True = string, False =  Integer. Again, position position of booleans in the array is the column number which they describe.
sortOrder - containing booleans specifying orientation of sort. "True" - ascending.  "False" - descending.  Yet again, position position of booleans in the array is the column number which they describe.***
With the data in the arrays already etablished, I have the following code to feed  these arrays to .sort:
Dim numHdrs, finalNumHdrs, count As Integer, newArray As Variant
For numHdrs = 1 To UBound(headRow)
    If colIsString(numHdrs) = True Then
        sortOrder(numHdrs) = xlAscending
    ElseIf colIsString(numHdrs) = False Then
        sortOrder(numHdrs) = xlDescending
    End If
Next numHdrs

newArray = CombineArrays(headRow, prLst, sortOrder)

For finalNumHdrs = 1 To UBound(headRow)
    If headRow(finalNumHdrs) And prLst(finalNumHdrs) And sortOrder(finalNumHdrs) <> "N/A" Then
        'ActiveSheet.Sort.SortFields.Add Key(headRow(finalNumHdrs)):= finalNumHdrs
        'ActiveSheet.Sort.SortFields.Add Order(finalNumHdrs):=sortOrder(finalNumHdrs)
    End If
Next finalNumHdrs

With ActiveSheet.Sort
    .SetRange inRange
    .Apply
End With

I am having trouble adding the sort fields appropriately, using the data I have in the array:
'ActiveSheet.Sort.SortFields.Add Key(headRow(finalNumHdrs)):= finalNumHdrs
'ActiveSheet.Sort.SortFields.Add Order(finalNumHdrs):=sortOrder(finalNumHdrs)

This is obviously not correct. So I created a function to concatenate headRow, prLst, and sortOrder to make it easier to feed into .sort:
Function CombineArrays(arr1 As Variant, arr2 As Variant, arr3 As Variant)
Dim arr4 As Variant
ReDim arr4(1 To UBound(arr2), 1 To 2)

Dim i, j As Integer
For i = 0 To UBound(arr1)
    arr4(arr2(i), 1) = arr1(i)
    arr4(arr2(i), 2) = arr3(i)
Next i
CombineArrays = arr4
End Function

Since arr2 is specifying the sort priority of a given column, I need to feed it to .sort in such a way that arr2 specifies the key number. As in if arr2 = 3, key3:= arr4(3,1), order3:= arr4(3,2). I am assuming that the order in which I elements to arr4 will not matter. (as in if I add arr4(4,1) before arr4(3,1) they will still be listed in the appropriate order)
This boils down to two questions:
For excel's .sort function: How do I add keys when I do not know how many keys (headers) a given sheet is going to have?
Am I doing this correctly?
*** Note I would have used collection objects had I heard about them earlier.  However, since I am new to VBA, this is how I established the program.  It would be too difficult given the code I have already written to go back and change all the arrays to collection objects.
NOTE: This is part of a larger program, whose description can be found here: Sorting Groups of Rows Excel VBA Macro

A: I think you expect the sort method to accept an array of sorting keys and orders which it can't do. The sort is limited to a max of 3 sorting columns (just like it is in the User interface)
You will need to make use of the trick that you can end up with the same sorting results by doing it column by column from the least important one to most important one. The next code is incomplete and won't exactly be what you need but is intended to explain the general idea
' Assuming you have some array which lists the order in which to sort from most important to least important named priorityArr
For i = UBound(priortyArr) To LBound(prioryArr)
  ActiveSheet.Sort.SortFields.Add Key:= headRow(i) Order:=sortOrder(i)
  ' do the rest you need to do and apply the sort
Next


text:
Q: C/C++ preprocessor directive for handing compilation errors The title might be somewhat confusing, so I'll try to explain.
Is there a preprocessor directive that I can encapsulate a piece of code with, so that if this piece of code contains a compilation error, then some other piece of should be compiled instead?
Here is an example to illustrate my motivation:
#compile_if_ok
    int a = 5;
    a += 6;
    int b = 7;
    b += 8;
#else
    int a = 5;
    int b = 7;
    a += 6;
    b += 8;
#endif

The above example is not the problem I am dealing with, so please do not suggest specific solutions.
UPDATE:
Thank you for all the negative comments down there.
Here is the exact problem, perhaps someone with a little less negative approach will have an answer:
I'm trying to decide during compile-time whether some variable a is an array or a pointer.
I've figured I can use the fact that, unlike pointers, an array doesn't have an L-value.
So in essence, the following code would yield a compilation error for an array but not for a pointer:
int a[10];
a = (int*)5;

Can I somehow "leverage" this compilation error in order to determine that a is an array and not a pointer, without stopping the compilation process?
Thanks

A: No.
It's not uncommon for large C++ (and other-language) projects to have a "configuration" stage designed into their build system to attempt compilation of different snippets of code, generating a set of preprocessor definitions indicating which ones worked, so that the compilation of the project proper can then use the preprocessor definitions in #ifdef/#else/#endif statements to select between alternatives.  For many UNIX/Linux software packages, running the "./configure" script coordinates this.  You can read about the autoconf tool that helps create such scripts at http://www.gnu.org/software/autoconf/

A: This is not supported in standard C. However, many command shells make this fairly simple. For example, in bash, you can write a script such as:
#!/bin/bash

# Try to compile the program with Code0 defined.
if cc -o program -DCode0= "$*"; then
    # That worked, do nothing extra. (Need some command here due to bash syntax.)
    /bin/true
else
    # The first compilation failed, try without Code0 defined.
    cc -o program "$*"
fi

./program

Then your source code can test whether Code0 is defined:
#if defined Code0
    foo bar;
#else
    #include <stdio.h>
    int main(void)
    {
        printf("Hello, world.\n");
        return 0;
    }
#endif

However, there are usually better ways to, in effect, make source code responsive to the environment or the target platform.

A: C11 _Generic macros might be able to handle this. If not, though, you're screwed in C.
Not in the C++ preprocessor. In C++ you can easily use overload resolution or a template or even expression SFINAE or anything like that to execute a different function depending on if a is an array or not. That is still occurring after preprocessing though.
If you need one that is both valid C and valid C++, the best you can do is #ifdef __cplusplus and handle it that way. Their common subset (which is mostly C89) definitely does not have something that can handle this at any stage of compilation.

A: On the updated question :
If you're writing C++, use templates...
Specifically, to test the type of a variable you have helpers : std::enable_if, std::is_same, std::is_pointer, etc
See the type support module : http://en.cppreference.com/w/cpp/types

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fatal Exception: java.lang.NoSuchMethodError I am dealing with that problem:
Fatal Exception: java.lang.NoSuchMethodError
No virtual method getActiveNetwork()Landroid/net/Network; in class Landroid/net/ConnectivityManager; or its super classes (declaration of 'android.net.ConnectivityManager' appears in /system/framework/framework.jar:classes2.dex)

There is my code:
 public boolean isNetworkAvailable() {

        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager != null) {

            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
                NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
                if (capabilities != null) {
                    if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {

                        return true;
                    } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {

                        return true;
                    } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {

                        return true;
                    }
                }
            }
        }

    return false;}

there is the stacktrace:
Fatal Exception: java.lang.NoSuchMethodError: No virtual method getActiveNetwork()Landroid/net/Network; in class Landroid/net/ConnectivityManager; or its super classes (declaration of 'android.net.ConnectivityManager' appears in /system/framework/framework.jar:classes2.dex)
   at com.olgazelenko.esofer.MainMenu.isNetworkAvailable(MainMenu.java:307)
   at com.olgazelenko.esofer.MainMenu.onCreate(MainMenu.java:75)
   at android.app.Activity.performCreate(Activity.java:6178)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2648)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2769)
   at android.app.ActivityThread.access$900(ActivityThread.java:177)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:135)
   at android.app.ActivityThread.main(ActivityThread.java:5910)
   at java.lang.reflect.Method.invoke(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:372)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)

does someone know how that can be fixed?

A: This Error occurs often when you have compiled with one version of your dependency but are running the code with a different version.
Here, it looks that com.olgazelenko.esofer.MainMenu.isNetworkAvailable(MainMenu.java:307)  calls a method from android which is not found during your execution.
This method, getActiveNetwork, seemed to be added in Android SDK API Level 23. You maybe try to use it in a older version. see https://developer.android.com/reference/android/net/ConnectivityManager#getActiveNetwork(). Try to upgrade your minSdkVersion : https://developer.android.com/guide/topics/manifest/uses-sdk-element


text:
Q: Android TextView SingleLine field hides long text I have a TextView which sits on the left side of the screen and is set with gravity="right" and it is set with SingleLine = "true."
If by some chance the text in this view gets too long I want it to simply disappear off the left hand side of the view. I thought the configuration below would do that but what actually happens is the the long string disappears completely, presumably down and outside of the view somewhere.
How can I create a simple text view that contains a single line of text and keeps its layout even when something unexpected happens? ... or even something predictable.
<TextView
    android:id="@+id/tempF"
    android:text="@string/tempF"
    android:layout_width="146dp"
    android:layout_height="wrap_content"
    android:textColor="#cccccc"
    android:textStyle="bold"
    android:textSize="92dp"
    android:fontFamily="serif"
    android:gravity="right"
    android:layout_marginTop="60dp"
    android:layout_gravity="top|left"
    android:singleLine="true"
    />

A: You should play with ellipsize attribute of the TextView.Check below:
<TextView
    android:id="@+id/tempF"
    android:text="@string/tempF"
    android:layout_width="146dp"
    android:layout_height="wrap_content"
    android:textColor="#cccccc"
    android:textStyle="bold"
    android:textSize="92dp"
    android:fontFamily="serif"
    android:gravity="right"
    android:layout_marginTop="60dp"
    android:layout_gravity="top|left"
    android:singleLine="true"
    android:ellipsize="end"
    />

A: This is the purpose of "ellipsize" - truncating a portion of text to indicate additional text.
In you case, you may simply need to add something like:
android:ellipsize="end"

or you might need to go deeper:
Automatically ellipsize a string in Java
Or look at this:
android ellipsize multiline textview
The idea behind extending the class is that you can customize the behavior of the TextView when the text content exceeds the space provided. For example, you can give it the appearance the it "bleeds over" by removing padding, etc. An ellipsis is an indicator that is commonly used to explain "there's more text that you can't see" - this is how it would look:
This is really a really long...
(the 3 periods are the ellipsis - your text goes the opposite direction, but it should still work)
With a custom TextView, you could change the "..." to nothing or anything else you want (even an image, which I've done).
You could also marquee the text:
TextView Marquee not working

A: Add 2 properties in xml
android:singleLine="true"

android:ellipsize="end"

A: <TextView
    android:id="@+id/tv_desc"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/colorGray"
    android:textSize="@dimen/_18dp"
    android:padding="@dimen/_2dp"
    android:singleLine="true"
    android:ellipsize="end"
    android:text="@string/desc" />

A: Since android:singleLine is deprecated. We can use this line android:maxLines
Can do like this.
android:ellipsize="end"
android:maxLines="1"

A: <View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="#000000" />

It works.


text:
Q: Create logical GUI components group using windows builder I am writing a GUI app in WindowsBuilder eclipse java and have some questions:

*

*I have a check button that if it's checked some controls are enabled. Is there an elgant way to allow all of them by one command? I mean that I dont want to enable them one by one, just enable them at once - is it possible to define a logical group that will allow me to do it?

*Is there any common design pattern to write Java GUI applications?

I am new in Java, so will appriciate any guidance in these queastion.
Thanks!

A: There is no build-in function to check/uncheck them all with one command.
The "easiest" way that comes to mind is to store them all in a List and create a function that iterates over that list and checks/unchecks everything.
private List<Button> buttons = new ArrayList<Button>();

// ADD YOUR BUTTONS

private void setSelectionForButtons(boolean enabled)
{
    for(Button button : buttons)
        button.setSelection(enabled);
}

Then you can check/uncheck them all by calling:
setSelectionForButtons(true);

or
setSelectionForButtons(false);

As for the "design patterns": There is an excellent tutorial for writing SWT applications here.


text:
Q: SQL table structure - Reseller pricing How to change the below structure to allow each account to check his sales and his profit, the scenario is when the a child account buy an item that's mean each parent account make his margin. maybe we should add a new table, I'm not sure
Account table:
 AccountId   ParentId
 ----------- -----------
 5136        Null
 3126        5136
 2123        3126

Pricing table: (this is the buying price for each account)
 AccountId   ItemId      Price
 ----------- ----------- -------------
 5136        211         0.14
 3126        211         0.175
 2123        211         0.19

Sales table:
  id   AccountId   ItemId       SellingDate
  --   ----------- -----------  ------------
   1   2123        211          2019-01-01 09:23:45
   2   2126        211          2019-01-01 10:07:21

A: I think you need to add two new columns in your sales table
 Quantity and SellingPrice.
  id   AccountId   ItemId       SellingDate             Quantity        SellingPrice
  --   ----------- -----------  ------------           ----------       ------------
   1   2123        211          2019-01-01 09:23:45         1               0.20
   2   2126        211          2019-01-01 10:07:21         1               0.30

A: If the maximum level depth between a child and it's top parent is unknown.
Then not sure it requires a change to the tables.
For a given parent account you can use a recursive CTE to get it's children.
Then use that to get the sales and prices for the parent, including it's children.
WITH RCTE AS
(
   SELECT AccountId as BaseAccountId, 0 as Lvl, AccountId, ParentId
   FROM Account
   WHERE AccountId IN (5136, 3126, 2123)

   UNION ALL

   SELECT c.BaseAccountId, c.Lvl + 1, r.AccountId, r.ParentId
   FROM RCTE c
   JOIN Account r ON r.ParentId = c.AccountId
)
SELECT
 c.BaseAccountId AS AccountId,
 COUNT(s.ItemId) AS TotalItems,
 SUM(p.Price) AS TotalPrice
FROM RCTE c
LEFT JOIN Sales s ON s.AccountId = c.AccountId
LEFT JOIN Pricing p ON p.ItemId = s.ItemId AND p.AccountId = c.BaseAccountId
GROUP BY c.BaseAccountId
ORDER BY c.BaseAccountId;

But then there better be an index on Account.ParentId


text:
Q: Problems using Text Input Component I am trying to create a math game, in Adobe Animate, where there is a question and the user types the answer into a text input bar.
I have created my submit button, and added an event listener, however, i am not sure how to compare the input text, and the result, using an If statement.
I have named my text input "myname" and here is my code so far:
this.submit.addEventListener("click", check);
function check()
{}

How do i get the input text and compare it to the answer?

A: Try using the Equality == operator to check if they are same (equal)...
function check()
{
    if (myname.text == "your result text")
    {
        trace("user input (myname) is matching...");
    }

}

regarding...

"Sorry but this doesn't seem to be working it's not showing any errors it's just no showing the result or printing."

I wonder if this line is causing a problem:
this.submit.addEventListener("click", check);

If you have a Sprite or MovieClip object called (instance name) "submit" then setup code like this:
submit.buttonMode = true;
submit.addEventListener(MouseEvent.CLICK, check);

Then let the compiler know that function check is supposed to handle mouse events.
function check (evt:MouseEvent)
{
    if (myname.text == "your result text")
    {
        trace("user input (myname) is matching...");
    }

}

PS: I personally don't use this. in front of variable names, but maybe your program setup means you have no choice. In such case, try using this.submit.addEvent... and this.myname.text ==... when trying to make it work.


text:
Q: In DocBlocks, should I always use a single line notation when writing one line? Let's say I have one line of summary, must I right it like that:
/** summary */

or can I write it like this:
/**
 * summary
 */

I prefer the second option, but is that required to use the first option?

A: According to the documentation, "DocComments may be a single line in size but may also span multiple lines" (emphasis mine.)
So, you can do it either way.


text:
Q: QT how to check table widget type I have added a checkbox to my QTableWidget like this:
     QWidget *checkBoxWidget = new QWidget();
     QCheckBox *checkBox = new QCheckBox();      // We declare and initialize the checkbox
     QHBoxLayout *layoutCheckBox = new QHBoxLayout(checkBoxWidget); // create a layer with reference to the widget
     layoutCheckBox->addWidget(checkBox);            // Set the checkbox in the layer
     layoutCheckBox->setAlignment(Qt::AlignCenter);  // Center the checkbox
     layoutCheckBox->setContentsMargins(0,0,0,0);    // Set the zero padding
    checkBox->setChecked(true);
   ui->my_table_view->setCellWidget(0,1, checkBoxWidget); //

The problem is when I read that table cell how I will know that the cell holds a checkbox, a radio-button or a text.
Currently, my getValuesAt function can read text from the cell but I am not sure how to check the checkbox's state
getValuesAt(int row_number, int column_number)
{
    if(!ui->my_table_view->item(row_number,column_number)){
        return "";
    }else{
        return ui->my_table_view->item(row_number,column_number)->text();
    }
}

I tried to read widget type like this but it returns 0
QTableWidgetItem::ItemType res = ui->my_table_view->item(row_number,column_number)->Type;

A: Please notice that, if you put a widget in a cell, the corresponding item will be null unless you don't explicitly add one:
tableWidget->setCellWidget(0, 0, new QCheckBox());
qDebug() << tableWidget->item(0, 0); //yields 0x0

When inspecting a cell, you could first check if it has a widget and, if it doesn't, check if the underlying item is null or not:
for(int column=0; column<columns; ++column)
{
    QWidget * cellWidget = tableWidget->cellWidget(row, column);
    if(cellWidget != nullptr)
    {
        QCheckBox * checkbox = dynamic_cast<QCheckBox*>(cellWidget);
        if(checkbox != nullptr)
        {
            qDebug() << checkbox->isChecked();
        }
        else
        {
           //some other widget type ...
        }
    }
    else
    {
        QTableWidgetItem * item = tableWidget->item(row, column);
        if(item != nullptr)
        {
            qDebug() << item->text();
        }
        else
        {
           //this is an empty cell
        }
    }
}

A: You can access class name of any QObject derived class by
QString className(someObject->metaObject()->className());

For you example it would be like
QString className(ui->my_table_view->item(row_number,column_number)->metaObject()->className());

A: You can cast a pointer of a QWidget instance to a concrete type pointer, eg. QCheckBox* and check the result to be not nullptr. If it is not nullptr, it is an instance of that type.
QWidget *widget = new QCheckBox();
if (dynamic_cast<QCheckBox*>(widget) != widget) {
  // widget is a QCheckBox
}

if (dynamic_cast<QRadioButton*>(widget) == nullptr) {
  // widget is not a QRadioButton
}

You can use other casting options as well. Like qobject_cast or static_cast.
This method is useful not only for Qt classes. You can check whether the coming pointer (no matter where it comes from) is an instance of this or that class (or inherited class). But in other cases, you might not have a qobject_cast option, because it is Qt specific. But others remain applicable.


text:
Q: AWS Cloudfront returning Missing Key-Pair-Id query parameter or cookie value I have the code that returns the Cloud Front Signed Cookie Values.
CookiesForCustomPolicy signedCookiesUrl = AmazonCloudFrontCookieSigner.GetCookiesForCustomPolicy("https://example.cloudfront.net/movies/nature.mp4", new StreamReader(File.OpenRead(Path.Combine(AppContext.BaseDirectory, "pk-2.pem"))),"APKEXAMPLEKEYID", DateTime.Now.AddDays(10), DateTime.Now, null);

I use the returned values to request the object, however returns the
<Error>
MissingKey
<Message>
Missing Key-Pair-Id query parameter or cookie value
</Message>
</Error>.

I test this through the PostMan tool putting the headers and direct request through Chrome browser and still getting the same error.
I have use the correct Cloudfront Key Pair and correct resource URL. My objects are private and cloudfront have access to it. Is there any thing else that i need to work on to get this working?

A:
Add Header Key Pair

These aren't raw headers, they're cookies.  Although I don't use postman, it sounds like this is your issue:
Based on what you've said, you wouldn't add them like this:
[CloudFront-Key-Pair-Id, APKEXAMPLEQQ]

Instead it should look more like this:
[Cookie, CloudFront-Key-Pair-Id=APKEXAMPLEQQ]

A: Here is the example for Signed URL in C#.
http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CreateSignatureInCSharp.html
When you return the signed keys, you can return with query string parameter or Cookies.
You can return cookies to API Gateway in two ways, Do with ANY Integration and return the headers as it is.
If you do any other method, you need to return json data and map json data to headers in API Gateway.
http://docs.aws.amazon.com/apigateway/latest/developerguide/request-response-data-mappings.html#mapping-response-parameters
Hope it helps.

A: When we use PUBLIC_KEY and PRIVATE_KEY then we get Key-Pair-Id missing. We should use Access Key Id instead of PUBLIC_KEY then it will work perfectly.


text:
Q: Java selenium headless mode download PDF issue Below code I have try to download PDF from chrome browser using selenium.
public static void main(String args[]) throws InterruptedException, AWTException, IOException, DocumentException {

    System.setProperty("webdriver.chrome.driver", "/home/sejalj/OtherProj/webDrivers/chromedriver_64");
    ChromeOptions ChromeOptions = new ChromeOptions();
    ChromeOptions.addArguments("--headless", "window-size=1024,768", "--no-sandbox");

    WebDriver driver = new ChromeDriver(ChromeOptions);

    String baseUrl = "http://url.com/";

    driver.get(baseUrl);

    driver.findElement(By.name("wl_user_name")).sendKeys("uname");
    driver.findElement(By.name("wl_user_password")).sendKeys("password");
    driver.findElement(By.cssSelector("input[value=Login]")).click();

    String pdfUrl = "https://www.pdfurl.com/displayImageDocs.php?
    f=MjAxODA3MjQxMDUwNzA4Ni5QREY=&p=aW1hZ2UuaW1hZ2ViYW5rLmJsdsaddhbmsxLjIwMTgwNy4yMDE4MDcyNA==&a=MTAwMjM0&POL_NUM=AAS06036999";";

    // Opens pdf of specific URL
    driver.get(pdfUrl);

    Actions a = new Actions(driver);

    // To press CTRL+S
    a.keyUp(Keys.CONTROL).sendKeys("s").build().perform();

    Robot robot = new java.awt.Robot();
    robot.keyPress(KeyEvent.VK_BACK_SPACE);
    robot.keyRelease(KeyEvent.VK_BACK_SPACE);
    int keyInput[] = {KeyEvent.VK_A, KeyEvent.VK_A, KeyEvent.VK_A, KeyEvent.VK_A, KeyEvent.VK_UNDERSCORE,
                      KeyEvent.VK_P, KeyEvent.VK_O, KeyEvent.VK_L, KeyEvent.VK_I, KeyEvent.VK_C, KeyEvent.VK_Y
                     };

    for (int i = 0; i < keyInput.length; i++) {
          robot.keyPress(keyInput[i]);
          robot.keyRelease(keyInput[i]);
    }

    // To press ENTER
    robot.keyPress(KeyEvent.VK_ENTER);
    Thread.sleep(1000);
    robot.keyRelease(KeyEvent.VK_ENTER);

    System.out.println("Preparing Policies document...Please wait");
    System.out.println("Document prepared..");
}

Above code working fine while chrome run without --headless mode.
But in --headless mode above code not working.
Robot class does not support in headless mode.
Please guide.

Solution that has been mark as working can be found here:
  Download files in Java, Selenium using ChromeDriver and headless mode

A: Try this one and remove  code after driver.get(pdfUrl);
         this may help you using HashMap of string with objects,
<-- language: lang-java -->
HashMap<String, Object> prefs = new HashMap<>();
prefs.put("plugins.always_open_pdf_externally", true);
ChromeOptions.setExperimentalOption("prefs", prefs);

A: I got the solution after referring the below link:
Download files in Java, Selenium using ChromeDriver and headless mode
Here is the working code to download PDF file in headless mode.
public static void main(String args[]) throws InterruptedException, AWTException, IOException, DocumentException {

    System.setProperty("webdriver.chrome.driver", "/home/OtherProj/webDrivers/chromedriver_64");

    String downloadPath = "/home/Downloads/AAAA/";
    File file = new File(downloadPath);
    if(!file.exists())
        file.mkdirs();

    ChromeOptions chromeOptions = new ChromeOptions();

    HashMap<String, Object> prefs = new HashMap<>();
    prefs.put("plugins.always_open_pdf_externally", true);

    chromeOptions.addArguments("--test-type");
    chromeOptions.addArguments("--disable-extensions");
    chromeOptions.setExperimentalOption("prefs", prefs);
    chromeOptions.setHeadless(true);

    String pdfUrl = "https://www.dummyurl.com/prod/displayImageDocs.php?f=MjAxODsafdfgsdjhgsjkA3MjQxMDUwNzA4Ni5QREY=&p=aW1hZ2UuaW1hZ2ViYW5rLmJhbmsxLjIwMTgwNy4yMDE4MDcyNA==&a=MTAwMsgsdjM0&POL_NUM=AAS06036999";

    ChromeDriverService driverService = ChromeDriverService.createDefaultService();
    WebDriver driver = new ChromeDriver(driverService, chromeOptions);

    // Saves the file on the given path
    PDFDemo.downloadFile(downloadPath, driverService, driver, pdfUrl);
    logger.debug("File Downloded Start");

    long fileSizeOne;
    long fileSizeTwo;

    do {

           File downlodedFolder = new File(downloadPath);
           File downlodedFile = downlodedFolder.listFiles()[0];

           fileSizeOne = downlodedFile.length();
           logger.debug("fileSizeOne " + fileSizeOne);
           Thread.sleep(1500);
           fileSizeTwo = downlodedFile.length();
           logger.debug("fileSizeTwo " + fileSizeTwo);
    } while (fileSizeTwo != fileSizeOne);

    logger.debug("File Downloded Completed");
    System.out.println("Document Downloaded..");
}

private static void downloadFile(String downloadPath, ChromeDriverService driverService, WebDriver driver, String pdfUrl) throws ClientProtocolException, IOException, InterruptedException {

    Map<String, Object> commandParams = new HashMap<>();
    commandParams.put("cmd", "Page.setDownloadBehavior");
    Map<String, String> params = new HashMap<>();
    params.put("behavior", "allow");
    params.put("downloadPath", downloadPath);
    commandParams.put("params", params);
    HttpClient httpClient = HttpClientBuilder.create().build();

    ObjectMapper objectMapper = new ObjectMapper();
    String command = objectMapper.writeValueAsString(commandParams);
    String u = driverService.getUrl().toString() + "/session/" + ((RemoteWebDriver) driver).getSessionId() + "/chromium/send_command";
    HttpPost request = new HttpPost(u);
    request.addHeader("content-type", "application/pdf");
    request.setEntity(new StringEntity(command));
    httpClient.execute(request);

    // Opens pdf of specific URL
    driver.get(pdfUrl);
}


text:
Q: Kafka Connect JDBC Sink Connector I am trying to write data from a topic (json data) into a MySql Database.  I believe I want a JDBC Sink Connector.
How do I configure the connector to map the json data in the topic to how to insert data into the database.
The only documentation I can find is this.

"The sink connector requires knowledge of schemas, so you should use a
  suitable converter e.g. the Avro converter that comes with Schema
  Registry, or the JSON converter with schemas enabled. Kafka record
  keys if present can be primitive types or a Connect struct, and the
  record value must be a Connect struct. Fields being selected from
  Connect structs must be of primitive types. If the data in the topic
  is not of a compatible format, implementing a custom Converter may be
  necessary."

But how do you configure?  Any examples?

A:
I assume that means you need to use Confluent Schema Registry?

For "better" schema support, then yes. But no, it is not required.
You can use the JsonConverter with schemas.enable=true
Your JSON messages will need to look like this though,
{
   "schema" : {
      ... data that describes the payload
   },
   "payload": {
      ... your actual data
   }
}

For reference to this format, you can see this blog
You can use Kafka Streams or KSQL to more easily convert "schemaless" JSON to a schema-d Avro payload


text:
Q: Facebook Graph Api check if a loggedin user likes a post I'm working on a app in which i need to check if the current logged In user liked a post from a particular page. So that i can show the appropriate like/liked button.
(I don't want to get all the likes of a post and iterate over them)
Alternatively i could use the FBSDKLikeControl, but my problem is i want to show custom like/liked buttons.

A: use :
THE_POST_ID?fields=likes.summary(true).fields(name).limit(1)

And in the results check the "summary" dictionary you will get :
total_count,
can_like,
has_liked  <----this
(tested with graph api 2.5)

A: Right now, there is not a direct way using the GraphAPI to know if a user has liked an specific post or not besides going through all the post likes:
https://developers.facebook.com/docs/graph-api/reference/v2.3/object/likes


text:
Q: Random walk with 3 cases. Let the walking start be at $x=0$. With probability $p_1$ new $x=x+1$, with probability $p_2$: $x=x-1$ and with probability $1-p_1-p_2 \geq 0$ walking ends.
The question is what is the probability of ending on point $n$.
I've computed it numerically and getting something close to normal distribution with peak at zero, but with different dispersion on sides of $x=0$. How to get it analytically?
The provided answer seems ok, but I hope I can find some smooth function for it. Maybe with another type of solution.
Upd: my idea of solution.
$$P_{n+1} (x) = p_1 P_{n} (x-\delta x) + p_2 P_{n} (x + \delta x)$$
$$P_{n+1} (x) - P_{n} (x) = p_1 [P_n(x-\delta x) - P_n(x)] + p_2 [P_n(x+\delta x) - P_n(x)] - q\cdot P_{n}(x)$$
Dividing by $\delta n$ and $\delta x$ getting something like:
$$\frac{\partial P(n,x)}{\partial n}= \frac{\delta x}{\delta n}\left[ (p_2 + p_1) \frac{\partial P(n,x)}{\partial x} - (1 - p_2 - p_1)\cdot P(n,x)\right]$$
Solving it leads to something like this:
$$P(n,x) = Ae^{\frac{-q x}{p_1 + p_2}}(n + \frac{x}{p_1 + p_2})$$
I'm not sure yet  if it means something.

A:
We derive a closed formula and show the following is valid for $n\geq 0$
  \begin{align*}
\sum_{k=0}^\infty\binom{n+2k}{k}x^k&=
\frac{1}{\sqrt{1-4x}}
\left(\frac{1-\sqrt{1-4x}}{2x}\right)^n\tag{1}\\
\end{align*}

Note that
\begin{align*}
c(x)=\frac{1-\sqrt{1-4x}}{2x}=1+x+2x^2+5x^3+14x^4+\cdots
\end{align*}
is the generating function of the ubiquitous Catalan numbers.
We use the coefficient of operator $[w^k]$ to denote the coefficient of $w^k$ in a series. This way we can write e.g.
\begin{align*}
[w^k](1+w)^n=\binom{n}{k}
\end{align*}

We obtain
  \begin{align*}
\color{blue}{\sum_{k=0}^{\infty}\binom{n+2k}{k}x^k}
&=\sum_{k=0}^\infty[w^{k}](1+w)^{n+2k}x^k\tag{2}\\
&=[w^0](1+w)^n\sum_{k=0}^\infty\left(\frac{x(1+w)^2}{w}\right)^k\tag{3}\\
&=[w^0]\frac{(1+w)^n}{1-\frac{x(1+w)^2}{w}}\tag{4}\\
&=-[w^{-1}]\frac{(1+w)^n}{x+(2x-1)w+xw^2}\\
&=-[w^{-1}]\frac{\left(1+w\right)^n}{x(w-w_0(x))(w-w_1(x))}\tag{5}\\
&=\frac{\left(1+w_0(x)\right)^n}{x(w_1(x)-w_0(x))}\tag{6}\\
&\color{blue}{=\frac{1}{\sqrt{1-4x}}\left(\frac{1-\sqrt{1-4x}}{2x}\right)^n}\tag{7}
\end{align*}
  and the claim (1) follows.

Comment:

*

*In (2) we apply the coefficient of operator.

*In (3) we use the linearity of the coefficient of operator and apply the rule
\begin{align*}
[w^{p+q}]A(w)=[w^p]w^{-q}A(w)
\end{align*}

*In (4) we apply the geometric series expansion.

*In (5) we represent the denominator with poles $w_0(x)$ and $w_1(x)$.
\begin{align*}
w_0(x)&=\frac{1-\sqrt{1-4x}}{2x}-1\tag{8}\\
w_1(x)&=\frac{1+\sqrt{1-4x}}{2x}-1\\
\end{align*}

*In (6) we calculate the residual of the simple pole at $w=w_0(x)$ using
\begin{align*}
\operatorname{res}_{w=a}f(w)=\lim_{w\to a}(w-a)f(w)
\end{align*}

*In (7) we use the representation from (8).

A: First of all, it is easy to observe that the walking can only end after $n+2k$ steps, where $k \in \mathbb{N}$.
Now, let $P_k$ be the probability that we end after exactly $n+2k$ steps. Then:
$$P_k = \binom{n+2k}{k}  p_1^{n+k}p_2^{k} (1-p_1 - p_2) $$
This is because in order to end the walk at exactly $n$, we need to spend (any) $k$ steps going "left" and (the remaining) $n+k$ steps going right. And after that we need to stop.
Thus, the total probability $P$ should be given by:
$$P = \sum\limits_{k=0}^{\infty}P_k = (1-p_1 - p_2)\sum\limits_{k=0}^{\infty}\binom{n+2k}{k} p_1^{n+k}p_2^{k}$$

A: Pellenthor's solution is probably the best you can obtain. You can simplify it just slightly more:
$$\begin{align}
P^+(n) =&\; (1-p_1 - p_2)\cdot\sum\limits_{k=0}^{\infty}\binom{n+2k}{k} p_1^{n+k}p_2^{k}=\\
=&\; p_1^n\cdot(1-p_1 - p_2)\cdot\sum\limits_{k=0}^{\infty}\binom{n+2k}{k} (p_1p_2)^{k} =\\
=&\; p_1^n\cdot(1-p_1 - p_2)\cdot {_2F_1}\left(\frac{n+1}{2},\frac{n+2}{2};n+1;4p_1p_2 \right)
\end{align}$$
where $_2F_1$ is the hypergeometric function (it is likely that the previous line looks more friendly!). Please note that this expression is valid for "destinations" on the right, i.e. for $n\gt 0$ (you might include here $n=0$, but I like to keep this case on its own). For "destinations" on the left replace every $n$ with $|n|$ and put $p_2^{|n|}$ at the beginning.
I've tested a couple of particular cases. For $p_1 = p_2 = 2/5$ (so $p_{stop}=1/5$) we have
$$
\sum\limits_{n=-1}^{-\infty}P^-(n) \; + P(0) \; + \sum\limits_{n=1}^{\infty}P^+(n) = \frac{1}{3} \; + \; \frac{1}{3} \; + \; \frac{1}{3} = 1
$$
which respects symmetry and the correct sum to $1$. For $p_1=1/2$, $p_2=1/3$, $p_{stop}=1/6$:
$$
\sum\limits_{n=-1}^{-\infty}P^-(n) \; + P(0) \; + \sum\limits_{n=1}^{\infty}P^+(n) = \frac{3-\sqrt{3}}{6} \; + \; \frac{\sqrt{3}}{6} \; + \; 0.5 = 1
$$
as expected unbalanced towards right. I don't think that anything better can be done. See the amazing answer from Markus Scheuer to see the closed form of the general term!


text:
Q: MySQL move one of the returned results the bottom I'm having an issue with a MySQL query any help would be good.
Basically the project I'm doing is to record and display golf scores. I have a query that gets all the players morning score and afternoon score adds them together and displays lowest score at the top.
I have an extra field for priority which checks if two plays are on the same score and I can assign a number to display them above the other. All this works fine, the issue I have is if a player only plays the morning or afternoon they are displayed at the top because they have the lowest score. I need to add something to check if they have played both morning and afternoon if not then they go to the bottom of the list. Hope that make sense.
My database fields are
player_id,
player_name,
player_morning_score,
player_afternoon_score,
player_priority,
player_no_return

I was hoping to put a 1 in the player_no_return and then my query would check for this and move them to the bottom of my results. But I'm not sure how to go about it.
Here's my query for currently displaying them.
SELECT player_id, player_name, (player_morning_score + player_afternoon_score) AS total
FROM players
ORDER BY 'total,player_priority', 'ASC','player_afternoon_score', 'DESC'

At the minute my results look like this
Craig    10

Steve    15

Julie    21

Alex     21

Bob      25

Craig has only played the morning so would need moving to the bottom.

A: Check IF statement in SELECT. 'IF' in 'SELECT' statement - choose output value based on column values
You can select column if player played in the morning or not placing 1 or 0 value. Then order by this field and total

A: You are sorting by strings, which means you are not sorting , use back ticks for columns/aliasing : ` and not single quote mark that represent a string. Although you don't even need them(they are used for more then 1 word alias , or reserved words) :
SELECT player_id, player_name,
       player_morning_score + player_afternoon_score AS total
FROM players
ORDER BY CASE WHEN player_afternoon_score > 0 AND player_morning_score > 0 THEN 1 ELSE 0 END DESC,
          `total`,player_priority,player_afternoon_score DESC

ORDER BY default is ASC , so you don't have to write it down, only when you want DESC.
I added you requirment (if he didn't play both, he will be on the bottom of the list) using CASE EXPRESSION in the ORDER BY clause.


text:
Q: Undefined index in collected array I have an array stored in my Laravel cache, which looks like this:
Illuminate\Support\Collection {#1058
     all: [
       [
         "name" => "The National",
         "plays" => "7",
         "key" => "the-national",
         "image_paths" => [
           "small" => [
             "path" => "music/artists/the-national",
             "fn" => "170-ea644e846aab551777d3a1ca9b49bdb6.webp",
           ],
           "medium" => [
             "path" => "music/artists/the-national",
             "fn" => "300-ea644e846aab551777d3a1ca9b49bdb6.webp",
           ],
           "large" => [
             "path" => "music/artists/the-national",
             "fn" => "770-ea644e846aab551777d3a1ca9b49bdb6.webp",
           ],
         ],
       ],
       // ...
    ]
}

When I retrieve it and collect it, I can get the path of the medium image:
$artists = collect(Cache::get('recentArtists'));
echo $artists[0]['image_paths']['medium']['path'];

But when I try to reference it in blade:
{{ $artist['image_paths']['small']['path'] }}

I get Undefined index: medium.
I've also tried mapping the collection in my controller, but with the same error:
$artists->map(function($item, $key) {
    return [
        'name' => $item['name'],
        'img' => $item['image_paths']['medium'],
    ];
});

// Undefined index: medium

If I try to return the array_keys in the map, I get them as expected:
=> [
    "tiny",
    "small",
    "medium",
    "large",
],


text: Q: Site Column in Content Type Hub is not visible in subscriber site collection I have created Site Column say "mycolumn" in my Content Type Hub and associated a content type -say myCT - and this content type is published and ran the 2 timer jobs.Though the content type is visible in subscriber site collection,the  column "mycolumn" is not visible in Subscriber Site Collection. am surprised and  not able to understand why its not visible in my subscriber site's site columns gallery.This is happening on my  Production Environment.In my staging  environment  this works perfectly.


text:
Q: Chrome on Windows not honoring hosts file, yet other browsers do What is happening
I have a simple Apache server set up on my machine, accessible via localhost on port 80. When accessing the following addresses :

*

*http://localhost/

*http://[::1]/
It does work on Chrome/Firefox and other browsers
ping/curl to localhost works and returns a 200 response.
After adding an entry to my hosts file, to point a host name to localhost, it seems Chrome is not honoring the entries in the hosts file.
Let me explain, my hosts file looks like this now :
# localhost name resolution is handled within DNS itself.
# 127.0.0.1       localhost
# ::1 localhost

::1 mydomain.local

When accessing the host name mydomain.local with Firefox/Edge/Other browsers it returns the default page of my Apache server as a 200 response.
ping/curl to mydomain.local checks out successfully and shows it is actually pointing to localhost at the ::1 ipv6 version of localhost.
Yet somehow, Chrome throws an DNS_PROBE_FINISHED_NXDOMAIN error on that host name.
What has been tried

*

*Fresh Chrome install

*Flushing Windows DNS cache with ipconfig

*Flushing Chrome DNS cache through chrome://net-internals/

*Disabling all DNS prefetching and protection settings (I just went through and disabled everything on Chrome https://imgur.com/a/okB3ofG)

*Running Chrome with the following flags

*

*--dns-prefetch-disable

*--disable-preconnect

*--incognito

*--start-maximized

*--disable-async-dns

All attempts unsuccessful
System setup

*

*Windows 10 Pro x64 (1809)

*Chrome Version 74.0

*Firefox Quantum 66.0.3

--
Edit I know that Chrome doesn't play well with some TLDs, I have tried different options, like .loc .test .localhost without success
--
Edit 2
The referenced possible duplicate is 3 years old, and doesn't provide a solution. If there's no solution for this issue, is this behavior documented from Chromium ? That it doesn't allow hosts entries ?

A: I figured out how to "fix" that, posting it here for future readers.
How did I fix it ?
How did I get Chrome to actually point a host name to localhost ? Actually it's some funky behavior here. Simply by changing the TLD I'm using to .localhost
From Chromium's guidelines, and since the introduction of .dev as a legit TLD, there are some reserved TLDs.

To safely satisfy these needs, four domain names are reserved as listed and described below.

*

*.test

*.example

*.invalid

*.localhost

".test" is recommended for use in testing of current or new DNS related code.
".example" is recommended for use in documentation or as examples.
".invalid" is intended for use in online construction of domain names that are sure to be invalid and which it is obvious at a glance are invalid.
The ".localhost" TLD has traditionally been statically defined in host DNS implementations as having an A record pointing to the loop back IP address and is reserved for such use.  Any other use would conflict with widely deployed code which assumes this use.

Read more here
Yet Chrome didn't point to localhost when I tried using .test it is just ... weird, it should've worked. If anyone has any input on this, please be my guest.
Beware Although this solution worked on my system, it is believed to cause some unexpected behavior on OSX systems.
As of this answer, on Chrome 74, it not possible to disable Chrome's own DNS host resolver, and aside those TLDs, all hosts entries will be ignored


text:
Q: SVD decomposition representation Let $x=A^T(AA^T)^{-1}b$ given that $A_{m\times n}$ is a full row rank matrix and $b$ is a vector. By $SVD$ decomposition $A=U\Sigma V^T$.
How can I express $x$ with $U,V,b$ and the addition of the partial matrix $\Sigma_{m\times m}$ which contains the non zeroes segments of $\Sigma$.
Also Can It be written with a slimmer version using $u_i\in \mathbb R^{m\times1},v_i\in \mathbb R^{n\times1}$, vectors from $U,V$ and $\sigma_i$ the diagonal values of $\Sigma$?
Is the following valid\good enough?
$$x=A^T(AA^T)^{-1}b=(UΣV^T)^T(UΣV(UΣV^T)^T)^{-1}b=U^TΣ^TV(UΣVU^TΣ^TV)^{-1}b$$
$$=U^T ΣV(UΣVU^T ΣV)^{-1}b$$

A: I assume that $m \le n$ holds? Then note:
$$AA^t = U \Sigma V^t V \Sigma^t U^t = U \Sigma \Sigma^t U^t$$
Since $A$ has full rank, $\Sigma \Sigma^t$ also has full rank. From $U \Sigma \Sigma^t U^t U (\Sigma\Sigma^t)^{-1}U = I$, we can infer $(AA^t)^{-1}$ = $U(\Sigma\Sigma^t)^{-1}U^t$. This yields:
$$A^t(AA^t)^{-1} = V \Sigma^t U^t U (\Sigma\Sigma^t)^{-1} U^t = V \Sigma^t (\Sigma \Sigma^t)^{-1} U^t.$$
We have $\Sigma = (\Sigma_{m \times m})$ and therefore $\Sigma \Sigma^t = \Sigma_{m \times m} \Sigma_{m \times m}^t = \Sigma_{m \times m}^2$. This implies $$\Sigma^t(\Sigma \Sigma^t)^{-1} = \begin{pmatrix}\Sigma_{m \times m}^{-1} \\ 0\end{pmatrix}.$$
Edit: If $u_i$ resp. $v_i$ are the rows of $U$ resp. $V$, you can simplify this further.
$$\begin{pmatrix}v_1 \\ v_2 \\ \vdots \\v_n\end{pmatrix} \begin{pmatrix}\Sigma_{m \times m}^{-1} \\ 0 \end{pmatrix} \begin{pmatrix}u_1^t & u_2^t & \cdots & u_m^t\end{pmatrix} =\begin{pmatrix}v_1 \\ v_2 \\ \vdots \\v_n\end{pmatrix} \begin{pmatrix}\Sigma_{m \times m}^{-1} u_1^t & \Sigma_{m \times m}^{-1} u_2^t & \cdots & \Sigma_{m \times m}^{-1}u_m^t \\ 0 & 0 & \cdots & 0\end{pmatrix}$$
Now if $\sigma_i$ are the diagonal elements of $\Sigma_{m \times m}$, then the $(i, j)$-th coordinate of this matrix is given by $\sum \limits_{k = 1}^m v_{i, k} \sigma_{k, k}^{-1} u_{j, k}$.

A: The target matrix has full row rank
$$
\mathbf{A} \in \mathbb{C}^{m\times n}_{m},
$$
and $m < n$. The null space $\mathcal{N}\left( \mathbf{A}^{*} \right)$ is trivial and the singular value decomposition takes the form
$$
\begin{align}
  \mathbf{A} &=
  \mathbf{U} \, \Sigma \, \mathbf{V}^{*} \\
%
 &=
% U
  \left[ \begin{array}{c}
     \color{blue}{\mathbf{U}_{\mathcal{R}}}
  \end{array} \right]
% Sigma
  \left[ \begin{array}{cccccc}
     \sigma_{1} & 0 & \dots &  &   & \dots &  0 \\
     0 & \sigma_{2}  &&&&&  \\
     \vdots && \ddots &&&& \vdots\\
      0 & & & \sigma_{m} & 0 & \dots & 0 \\
  \end{array} \right]
% V
  \left[ \begin{array}{c}
     \color{blue}{\mathbf{V}^{*}_{\mathcal{R}}} \\
     \color{red}{\mathbf{V}^{*}_{\mathcal{N}}}
  \end{array} \right]  \\[3pt]
%
  & =
% U
  \left[ \begin{array}{cc}
     \color{blue}{\mathbf{U}_{\mathcal{R}}}
  \end{array} \right]
% Sigma
  \left[ \begin{array}{cc}
     \mathbf{S}_{m\times m} & \mathbf{0} \\
  \end{array} \right]
% V
  \left[ \begin{array}{c}
     \color{blue}{\mathbf{V}^{*}_{\mathcal{R}}} \\
     \color{red}{\mathbf{V}^{*}_{\mathcal{N}}}
  \end{array} \right]  \\[3pt]
%
\end{align}
$$
The product matrix is
$$
  \mathbf{A} \, \mathbf{A}^{*} =
  \left( \mathbf{U} \, \Sigma \, \mathbf{V}^{*} \right)
  \left( \mathbf{V} \, \Sigma \, \mathbf{U}^{*} \right) =
  \color{blue}{\mathbf{U}_{\mathcal{R}}} \, \mathbf{S}^{2} \, \color{blue}{\mathbf{U}^{*}_{\mathcal{R}}}
$$
with the inverse being
$$
  \left( \mathbf{A} \, \mathbf{A}^{*} \right)^{-1} =
  \color{blue}{\mathbf{U}_{\mathcal{R}}} \, \mathbf{S}^{-2} \, \color{blue}{\mathbf{U}^{*}_{\mathcal{R}}}
$$
Finally
$$
\begin{align}
\mathbf{A}^{*} \left( \mathbf{A} \, \mathbf{A}^{*} \right)^{-1} &=
\left(
% V
  \left[ \begin{array}{cc}
     \color{blue}{\mathbf{V}_{\mathcal{R}}} &
     \color{red}{\mathbf{V}_{\mathcal{N}}}
  \end{array} \right]
% Sigma
  \left[ \begin{array}{c}
     \mathbf{S} \\ \mathbf{0} \\
  \end{array} \right]
% U
     \color{blue}{\mathbf{U}^{*}_{\mathcal{R}}}
\right)
\color{blue}{\mathbf{U}_{\mathcal{R}}} \, \mathbf{S}^{-2} \, \color{blue}{\mathbf{U}^{*}_{\mathcal{R}}} \\
&=
% V
  \left[ \begin{array}{cc}
     \color{blue}{\mathbf{V}_{\mathcal{R}}} &
     \color{red}{\mathbf{V}_{\mathcal{N}}}
  \end{array} \right]
% Sigma
  \left[ \begin{array}{c}
     \mathbf{S}^{-1} \\ \mathbf{0} \\[2pt]
  \end{array} \right]
% U
     \color{blue}{\mathbf{U}_{\mathcal{R}}}  \\
&=
\mathbf{A}^{\dagger}
\end{align}
$$


text:
Q: Define multiple auth routes with omniauth I'm versioning my rails app and I want to be able to authenticate an user with 2 different routes :
get 'v1/auth/:provider' => 'The omniauth method containing the appropriate callback'
get 'v1/auth/:provider/callback => 'v1/sessions#create'

get 'v2/auth/:provider' => 'The omniauth method containing the appropriate callback'
get 'v2/auth/:provider/callback => 'v2/sessions#create'

Is it possible to "hack" the prefix_path attributes so I can generate both routes ?


text:
Q: HttpClient fail to login to CAS Service I'm using Apache Http Components library and I'm trying to login into a CAS System. I found a CAS Client for Android on GitHub, I tried to use it but it doesn't work for me. The problem is that the header of the response doesn't contain the "Location" attribute where I can find the returned ticket.
I tried to use Google chrome to simulate the authentification and I don't know what Google chrome do to get the ticket :3 is it a redirection ? How can I detect it using httpClient ?

Thank you

A: You can enable the CAS RESTful API: https://wiki.jasig.org/display/CASUM/RESTful+API
Or
http://jasig.github.io/cas/4.0.x/protocol/REST-Protocol.html (after 4.0.x)
The REST protocol allows one to model applications as users, programmatically acquiring service tickets to authenticate to other applications. This means that other applications would be able to use a CAS client to accept Service Tickets rather than to rely upon another technology such as client SSL certificates for application-to-application authentication of requests. This is achieved by exposing a way to RESTfully obtain a Ticket Granting Ticket and then use that to obtain a Service Ticket.
Hope this helps.


text:
Q: NMinimize - function involves a very small number, solution is wrong NMinimize apparently doesn't worry much about the accuracy of small numbers in the result - They don't contribute much to the overall accuracy. Example:
f[x_, y_] := (x - 1)^2 - 10^-20 (y - 2)^2
NMinimize[f[x, y], {x, y}]

yields {-1.75769*10^-20, {x -> 1., y -> 0.674219}} rather than {x->1,y->2}.
Is there a way to fix this, without knowing the nature of f[x,y]?

A: As @xzczd pointed out, for a minimum to exist the coefficient of the second term should be positive. After doing that, you can improve accuracy by playing with WorkingPrecision, AccuracyGoal, or PrecisionGoal. Here's one example:
f[x_, y_] := (x - 1)^2 + 10^-20 (y - 2)^2
NMinimize[f[x, y], {x, y}]
(* Output: {1.75769*10^-20, {x -> 1., y -> 0.674219}}*)
NMinimize[f[x, y], {x, y}, AccuracyGoal -> 40]
(* Output: {6.70318*10^-29, {x -> 1., y -> 1.99992}} *)


text:
Q: Provisioning a vagrantfile using json Hey so i want to provision my vagrantfile using json, i have done this with yaml before and tried to follow the syntax alongside a little research on json. I have included print commands to confirm that the values from my json are readable but im struggling in understanding how to put them into my code as values? so my question is how do i call these values within a vagrant file?
require 'json'
filej = File.read('info.json')
jinfo = JSON.parse(filej)
vagrant.configure("2") do |config|

  jinfo.each do |key, value|
    p key
    p value

    config.vm.define jinfo['name'] do |js|
      js.vm.box = jinfo['box']
      js.vm.network 'private_network', ip: js['ip_addr']
      js.vm.provider "virtualbox" do |vb|
        vb.cpus = jinfo['vcpu']
        vb.memory = jinfo['ram']
      end
    end
  end
end

and my json is as follows
[
  {
    "name": "jenkins",
    "box": "centos/7",
    "ram": 4096,
    "vcpu": 2,
    "ip_addr": "192.168.33.11"
  },
  {
    "name": "server",
    "box": "centos/7",
    "ram": 4096,
    "vcpu": 2,
    "ip_addr": "192.168.33.10"
  }
]

A: If your Vagrantfile is same as pasted above, it looks like this:
require 'json'
filej = File.read('info.json')
jinfo = JSON.parse(filej)
vagrant.configure("2") do |config|

  jinfo.each do |key, value|
    p key
    p value

    config.vm.define jinfo['name'] do |js|
      js.vm.box = jinfo['box']
      js.vm.network 'private_network', ip: js['ip_addr']
      js.vm.provider "virtualbox" do |vb|
        vb.cpus = jinfo['vcpu']
        vb.memory = jinfo['ram']
      end
    end
  end
end

jinfo is actually an array and not a hash. You are trying to loop through each key value pair of the json instead of looping through each value. Try this:
require 'json'
filej = File.read('info.json')
jinfos = JSON.parse(filej)
vagrant.configure("2") do |config|

  jinfos.each do |jinfo|
    p jinfo

    config.vm.define jinfo['name'] do |js|
      js.vm.box = jinfo['box']
      js.vm.network 'private_network', ip: js['ip_addr']
      js.vm.provider "virtualbox" do |vb|
        vb.cpus = jinfo['vcpu']
        vb.memory = jinfo['ram']
      end
    end
  end
end

I changed the variable names slightly. You can remove the print part altogether and try.
Hope this helped.


text:
Q: The kernel appears to have died. It will restart automatically. (When importing numpy or pandas) I get this error when I import numpy or pandas.

I have tried every solution found in similar posts but was not successfull. I have downgraded or upgraded many libraries, but the problem is still there.
Any help is much appreciated.


text:
Q: How to check if a file exists in folder I have a class that creates acf + guttenberg blocks. It automatically includes style files and block scripts. But not for all blocks I need scripts. And when I delete the script file, there is an error in the console. How can I check for a file so that it does not include an empty file, but only when it is in the folder?

                    acf_register_block(
                        [
                            'name'            => $slug,
                            'title'           => $file_headers['title'] ?: __('Unnamed Block:', 'bluegfx_dev') . ' ' . $slug,
                            'description'     => $file_headers['description'],
                            'category'        => $file_headers['category'] ?: 'formatting',
                            'icon'            => $file_headers['icon'],
                            'keywords'        => explode(' ', $file_headers['keywords']),
                            'supports'        => json_decode($file_headers['supports'], true),
                            'render_callback' => [$this, 'block_render_callback'],
                            'enqueue_style'   => get_template_directory_uri() . '/' . $this->get_block_dir_path($slug) . 'style.css',
                            'enqueue_script'  => get_template_directory_uri() . '/' . $this->get_block_dir_path($slug) . 'script.js',
                        ]
                    );

A: Use file_exists():
$script_file_path = get_template_directory() . '/' . $this->get_block_dir_path($slug) . 'script.js';

if (file_exists($script_file_path)) {
    $enqueue_script = get_template_directory_uri() . '/' . $this->get_block_dir_path($slug) . 'script.js';
} else {
    $enqueue_script = '';
}

acf_register_block(
    [
        'name'            => $slug,
        'title'           => $file_headers['title'] ?: __('Unnamed Block:', 'bluegfx_dev') . ' ' . $slug,
        'description'     => $file_headers['description'],
        'category'        => $file_headers['category'] ?: 'formatting',
        'icon'            => $file_headers['icon'],
        'keywords'        => explode(' ', $file_headers['keywords']),
        'supports'        => json_decode($file_headers['supports'], true),
        'render_callback' => [$this, 'block_render_callback'],
        'enqueue_style'   => get_template_directory_uri() . '/' . $this->get_block_dir_path($slug) . 'style.css',
        'enqueue_script'  => $enqueue_script,
    ]
);


text:
Q: How to add gravity to UIViews in a UITableViewCell? I am trying to animate a few UIViews by having gravity act on them. Ideally, each view would stay inside the UITableViewCell bounds and they would bounce off of each other and the walls like boundaries. However, when I run this code, the UIView's just kind of float in place, only moving if another view happens to populate in the same spot.
class AnimateTableViewCell: UITableViewCell {

    private var animator: UIDynamicAnimator!
    private var gravity: UIGravityBehavior!
    private var collision: UICollisionBehavior!

    private var views = [UIView]()

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        animator = UIDynamicAnimator(referenceView: self.contentView)
        let items = [UIImage(systemName: "star.fill"),UIImage(systemName: "star.fill"),UIImage(systemName: "star.fill"),UIImage(systemName: "star.fill"),UIImage(systemName: "star.fill")]

        for item in items {
            let size = Int.random(in: 75 ... 180)
            self.setUpView(view: UIView(frame: CGRect(x: 100, y: 100, width: size, height: size)), image: item!, size: size/2)
        }

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func applyGravity(to item: UIView) {
        gravity = UIGravityBehavior(items: [item])
        animator.addBehavior(gravity)

        collision = UICollisionBehavior(items: views)
        collision.translatesReferenceBoundsIntoBoundary = true
        animator.addBehavior(collision)

        let bounce = UIDynamicItemBehavior(items: views)
        bounce.elasticity = 0.3
    }

    private func setUpView(view: UIView, image: UIImage, size: Int) {
        contentView.addSubview(view)
        view.backgroundColor = image.averageColor
        view.layer.cornerRadius = view.frame.height/2

        let imageView = UIImageView(image: image)
        imageView.contentMode = .scaleAspectFit

        view.addSubview(imageView)
        imageView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            imageView.heightAnchor.constraint(equalToConstant: CGFloat(size)),
            imageView.widthAnchor.constraint(equalToConstant: CGFloat(size)),
            imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        ])
        views.append(view)
        applyGravity(to: view)
    }
}

A: There are two main problems.
First, the collision behavior is getting in your way. Comment out this line:
 animator.addBehavior(collision)

Now at least you will see the gravity operate.
Second, you are saying
    gravity = UIGravityBehavior(items: [item])
    animator.addBehavior(gravity)

multiple times, once per item. That's wrong. You must have just one gravity behavior that embraces all the items.
I got a fair-to-middling result just by rearranging some of your code and changing a few of the magic numbers; this should get you started, at least (I used a table view with just one cell, quite tall in height):
class AnimateTableViewCell: UITableViewCell {

    private var animator: UIDynamicAnimator!
    private var gravity = UIGravityBehavior()
    private var collision = UICollisionBehavior()

    private var views = [UIView]()

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        animator = UIDynamicAnimator(referenceView: self.contentView)
        let items = [UIImage(systemName: "star.fill"),UIImage(systemName: "star.fill"),UIImage(systemName: "star.fill"),UIImage(systemName: "star.fill"),UIImage(systemName: "star.fill")]
        for item in items {
            let size = Int.random(in: 20...40)
            self.setUpView(view: UIView(frame: CGRect(x: 100, y: 100, width: size, height: size)), image: item!, size: size)
        }
        animator.addBehavior(gravity)
        collision.translatesReferenceBoundsIntoBoundary = true
        animator.addBehavior(collision)
        let bounce = UIDynamicItemBehavior(items: views)
        bounce.elasticity = 0.3
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func applyGravity(to item: UIView) {
        gravity.addItem(item)
        collision.addItem(item)
    }

    private func setUpView(view: UIView, image: UIImage, size: Int) {
        contentView.addSubview(view)
        view.backgroundColor = .red
        view.layer.cornerRadius = view.frame.height/2

        let imageView = UIImageView(image: image)
        imageView.contentMode = .scaleAspectFit

        view.addSubview(imageView)
        imageView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            imageView.heightAnchor.constraint(equalToConstant: CGFloat(size)),
            imageView.widthAnchor.constraint(equalToConstant: CGFloat(size)),
            imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        ])
        views.append(view)
        applyGravity(to: view)
    }
}


text:
Q: Limit access to the Admin REST API of SyncGateway According to the documentation the Admin REST API of the SyncGateway shouldn't be exposed.
Quote:

By default, the Admin REST API runs on port 4985 (unless you change
  the adminInterface configuration parameter). Do not expose this
  port—It belongs behind your firewall. Anyone who can reach this port
  has free access to and control over your databases and user accounts.

This makes sense but I'm wondering how I can grant my Application Server which runs on Google AppEngine and which handles the sign-up / creation of sessions access to the API without exposing it? Is there an option to expose the Admin REST API but limit the access to a specific server sending the request or requiring a username / password combination like the GUI on the :8091 port?
Edit
Just for clarification I'm adding my comment to the question:
The app server (running on GAE) and the Couchbase server (running on DigitalOcean) are two different physical devices and thus have different IP addresses. Means: I can't change the adminInterface configuration parameter in my syncgateway_config.json to a loop-back address since a connection from my GAE Server to the Couchbase Server won't have any effect afterwards. The server would be unreachable from the outside if I'm not mistaken?!

A: The usual expectation is that your database server and other servers that need admin-level access will be either on the same host, or on an internal network that's behind a firewall. In the latter case you can safely bind the admin port to the internal net. Then of course your firewall rules will allow external connections only to the Sync Gateway (SG) public port.
If you have an auth server that's on an entirely different network, things get a bit more complex.
One possibility is to use fancier options on the firewall so it can allow external access to the admin port, but only from the external auth server. A few ways I can imagine doing this are (a) hardcode only the auth server's IP address, (b) use an SSL connection with a client cert, or (c) open an SSH tunnel from the auth server to the SG server.
Another possibility is to use a distributed auth system like OAuth, which is designed to do exactly this kind of thing. So your mobile app would talk to the auth server to obtain a token, then present the token to SG, which then shows the token to the auth server to validate it. IIRC we don't have general purpose OAuth support in SG yet so you would need to write a small OAuth handler to run on the SG server that would do this work.
[Disclaimer: I'm an architect at Couchbase and have worked on Sync Gateway but I only work on Couchbase Lite these days so I'm not an expert on SG's current capabilities!]

A: Well the new piece of info in your comments needs to be addressed.  I'm not an expert in this area, but I think the assumption is that the auth service and sync gateway run on the same server.  If not things get slightly more complicated, but I think it might be doable by changing the adminInterface section of your Sync Gateway configuration to be the internal IP address and port (e.g. 192.168.3.2:4985).

A: You could install an http proxy on the same local network as Sync Gateway e.g. nginx.
You would configure nginx to accept public facing SSL connections authenticated using client side certificates.
Configure Sync Gateway to only accept admin connection from the local network shared with nginx.
Configure your App Server to use the client side certificate when connecting to Sync Gateway via nginx.
There is a good blog covering nginx client certificate setup here: http://nategood.com/client-side-certificate-authentication-in-ngi

A: The recommendation is to wrap what you need in an authentication service. This blog post explains very well how to do this: http://ti.eng.br/configuring-your-very-first-couchbase-mobile-sync-backend/

A: This point is mentioned in the documentation (If I correctly understood the question). In Managing API Access section of page Administering the REST APIs.
Quoting that section which contain answer your question:

The APIs are accessed on different TCP ports, which makes it easy to
  expose the Sync REST API on port 4984 to endpoints while keeping the
  Admin REST API on port 4985 secure behind your firewall.
If you want to change the ports, you can do that in the configuration
  file.
To change the Sync REST API port, set the interface property in the
  configuration file.
To change the Admin REST API port, set the adminInterface property in
  the configuration file.
The value of the property is a string consisting of a colon followed
  by a port number (for example, :4985). You can also prepend a host
  name or numeric IP address before the colon to bind only to the
  network interface with that address.
As a useful special case, the IP address 127.0.0.1 binds to the
  loopback interface, making the port unreachable from any other host.
  This is the default setting for the admin interface.

The bold letters says you can specify the IP and Port to bind it to specific network.
I think this is what you need.


text:
Q: Pandas json normalize Can someone help on how to put this json structure into pandas dataframe ? I would like the final structure to have date, high, low, open, low, close as the column.
The issues I have with this structure is that the key is a running numbers (eg 1607956200, 1607956500, 1607956800 ...) and I can't possibly lay out all the running numbers.
I have tried with the code below but I get all the data in the column with only 1 row.
response=requests.get(url).text
data = json.loads(response)
df = pd.json_normalize(data['history'] )

Below is an example of data
data = {"meta": {"regularMarketPrice": 9.78, "chartPreviousClose": 9.02, "previousClose": 9.78, "scale": 3, "dataGranularity": "5m", "range": "" },
        "history": {"1607956200": { "date": "14-12-2020", "open": 9.13, "high": 9.18, "low": 9.12, "close": 9.14 },
                    "1607956500": { "date": "14-12-2020", "open": 9.14, "high": 9.14, "low": 9.08, "close": 9.1 },
                    "1607956800": { "date": "14-12-2020", "open": 9.1, "high": 9.11, "low": 9.09, "close": 9.1 },}}

A: Create the dataframe and then transpose
df = pd.DataFrame(data['history']).T

                  date  open  high   low close
1607956200  14-12-2020  9.13  9.18  9.12  9.14
1607956500  14-12-2020  9.14  9.14  9.08  9.10
1607956800  14-12-2020  9.10  9.11  9.09  9.10


text:
Q: packaging external jars into a jar from command line I want to package my external jars (that are in lib/) and the jar that I am building of the class files all into one jar. Ive tried to do it as:
jar cvf proj.jar -C classes/ . lib/

The jar gets built up but when I use this jar in the program, the external jars supposed to be included as lib/ end up missing. So I think this is perhaps not the right way to do this.
I have tried exporting a jar through eclipse too (though I would like to fix the command line stuff) by giving it the location of external jars and I still had the problem of the program unable to locate the external jars.

A: You cannot (by default) nest jars in this fashion.
You may, however, use something like JarClassLoader to do this, or something like onejar (or jarjar, or fatjar, etc.) that repackages jar contents into a single, un-nested jar.


text:
Q: How to validate cron job with spring boot I want to have a cron job that executes every 00:10 am
according to online validators this is the correct expression "0 0/10 0/00 ? * * *"
but it has '?' and spring rejects this.
how can i validate my cron job properly ? my assumption is this should work  '0 0/10 0/00 * * *' but it doesnt, please can someone point me in the right direction ?  what am i doing wrong ? i will like to have a task 10 minutes after midnight
@Transactional
    @Scheduled(cron = "0 0/10 1/00 * * *")
    public void invalidateOutdatedPolicies() {
        InsurancePolicyStatus policyStatus =
        System.out.println("Scheduled task done");
    }``

A: you can validate pattern like this
public class ValidateCrontab {
    public static void main(String[] args) {
        // {second} {minute} {hour} {day} {month} {week} {year (optional)}
        // Second time, day, month and week, these 6 items are mandatory.

        CronSequenceGenerator cron1 = new CronSequenceGenerator("0 05 10 23 * ?");

        CronSequenceGenerator cron2 = new CronSequenceGenerator("0 05 08 ? * MON-FRI");
        Calendar cal = Calendar.getInstance();

        //cal.add(Calendar.DATE, 2); // add two days to current date
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");

        System.out.println("current date " + sdf.format(cal.getTime()) +"\n ----");

        System.out.println("Next cron trigger date cron1 " + cron1.next(cal.getTime()));
        System.out.println("Next cron trigger date cron2 " + cron2.next(cal.getTime()));
    }
}


text:
Q: Working of fork() in C++ I have this program in C++.
#include <iostream>
#include <unistd.h>
#include  <sys/types.h>

using namespace std;

int main()
{
    cout<<"*\n";
    fork();
    cout<<"A\n";
    fork();
    cout<<"B\n";
    fork();
    cout<<"C\n";
    return 0;
}

The output is:
*
A
B
C
*
A
B
C

I think it should be:
*
A
B
C
A
B
C
B
C
C

Explanation: '*' should be printed on by one process. Now, after fork() 2 'A' should be printed and son for 'B' & 'C'.
Link to code

A: Based on comments on the question, the answer is that fork in the ideone.com online compiler is simply limiting you to one instance of your process, and buffering your output.
Update: Actually, it's also lying: http://ideone.com/oXqqwM shows that fork() claims to succeed, but only the first produces a new copy of your process.
I suspect if you checked the return values of fork() you'd get some clues as to the surprising behaviour you're seeing -- all but the first will have returned -1 -- and if you used std::endl instead you might avoid the first *.
The expected result is that each fork() duplicates the running process at that moment, and so you'd expect to see twice each character compared to the one before, except that buffering means you might still have previous characters in the buffer at the time of fork().
So expect 1 or more "*", 2 or more "A", 4 or more "B" or 8 or more "C", except that if fork() fails, the numbers will be capped.
Your expectation of 1 "*", 2 "A", 3 "B" and 4 "C" indicates that you overlooked that both processes coming out of a fork() will hit the next fork(), so you double, rather than incrementing by one.

A: so... if you are getting more than one * then there is something strange going on, and I suspect that it is implementation specific...
fork will give each of the child processes a copy of the file descriptors, including stdout... so in your implementation it is also getting a valid copy of the std::cout stream... which already has a buffer loaded with *...
I think if you change your program to include a flush, you will see the same thing that I did:
#include <iostream>
#include <unistd.h>
#include  <sys/types.h>

using namespace std;

int main()
{
    cout<< "*\n";
    flush(cout);
    fork();
    cout<<"A\n";
    flush(cout);
    fork();
    cout<<"B\n";
    flush(cout);
    fork();
    cout<<"C\n";
    flush(cout);
    return 0;
}


text:
Q: Java Date Format Issue I have the number of seconds from 31 Dec 1969 19:00:00 i.e. (EST) and I want to convert the same to a date format.
I have the following code which returns any invalid date. Can anyone point out what seems to be the issue here.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class sample
{

    public static void main(String args[])
    {
        DateFormat df = new SimpleDateFormat("dd/MMM/yyyy HH:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone("EST"));
        Date d1 = new Date(1000*1373604190); //Converting to millisecond
         String formattedDate = df.format(d1);
         System.out.println(formattedDate); //I'm getting 22/Dec/1969 16:50:55
    }
}

How can I solve this.

A: You are using int literals instead of long in your numbers. By default a integral literal is int unless you specify that is long with L at the end. Try this:
Date d1 = new Date(1000*1373604190L);

(note the L at the end of your literal 1373604190)

A: tl;dr
Instant.ofEpochSeconds( 1_373_604_190L )
       .atZone( ZoneId.of( "America/New_York" ) )
       .format( DateTimeFormatter.ofPattern( "dd MMM uuuu HH:mm:ss" , Locale.CANADA ) )

Details

the number of seconds from 31 Dec 1969 19:00:00 i.e. (EST)

Do not think parochially when doing date-time work. Rather than translate values such as the epoch reference moment in and out of your own zone, just think in UTC. Consider UTC to be The One True Time, all others being variations on that theme.
So, always refer to the epoch reference moment as 1970-01-01T00:00:00Z, the first moment of 1970 in UTC, rather than in any other time zone.

(EST)

Also, never use those 3-4 letter abbreviations as time zones. Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Those 3-4 letter abbreviation such as EST or IST are not true time zones, not standardized, and not even unique(!).
Using java.time
The modern way to do this work is with the java.time classes.
long secondsSinceEpoch = 1_373_604_190L ;

We convert that to a Instant object. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.ofEpochSeconds( secondsSinceEpoch ) ;

To see this value through the lens of some wall-clock time, apply a time zone as a ZoneId to get a ZonedDateTime object.
I am guessing that by EST you meant the time zone used by much of the eastern portions of the United States and Canada. I will arbitrarily choose the time zone America/New_York.
ZoneId z = ZoneId.of( "America/New_York" );
ZonedDateTime zdt = instant.atZone( "America/New_York" );

secondsSinceEpoch: 1373604190
instant.toString(): 2013-07-12T04:43:10Z
zdt.toString(): 2013-07-12T00:43:10-04:00[America/New_York]

See live code at IdeOne.com.
Strings
To generate a string, you can either let java.time automatically localize or you can specify an explicit formatting pattern.
Locale locale = Locale.CANADA ;
DateTimeFormatter formatterLocalized = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM ).withLocale( locale );
String outputLocalized = zdt.format( formatterLocalized );

12-Jul-2013 12:43:10 AM

DateTimeFormatter formatterCustom = DateTimeFormatter.ofPattern( "dd MMM uuuu HH:mm:ss" , locale );
String output = zdt.format( formatterCustom );

12 Jul 2013 00:43:10

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?

*

*Java SE 8 and SE 9 and later

*

*Built-in.

*Part of the standard Java API with a bundled implementation.

*Java 9 adds some minor features and fixes.

*Java SE 6 and SE 7

*

*Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

*See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


text:
Q: How to disable code conditionally I'm a C/C++ Programmer new to PHP.
In C/C++, I often add code to my project (e.g. debugging output) that will be active only if a specific macro is defined. So, I'm able to "switch on / switch off" some code by defining / removing the macro definition inside a central header file.
E.g. in the header file:
#define ENABLE_DEBUG_OUTPUT

and anywhere in the code where it is useful:
#ifdef ENABLE_DEBUG_OUTPUT
    print_debug_output ( ... );
#endif

So to disable the print-debug_output calls (or anything else), I only need to comment out the #define inside the header file.
Is there some equivalent in PHP?
At first, I want to use FirePHP for debugging output on my test system, but disable it as soon as I put the code on the server. What's the best way to do this?

A: You can use native PHP function http://www.php.net/define
//Place the below line to your first loading file or any preferred place;
define("ENABLE_DEBUG_OUTPUT", true); //Or false;

//Then use it anywhere:
if( ENABLE_DEBUG_OUTPUT )
    print_r($my_debug_var);

A: Typically you'd use the most basic way:
$debug = SOME_CONDITIONAL;

if ($debug) {
    // display errors/warnings/notices in output
    ini_set('display_errors',1);
    ini_set('display_startup_errors',1);
    error_reporting(-1);
}

then as expected in your main code:
if ($debug) {
    /* debugging code */
}

I'm aware this is pretty gross, but it's nice and clear.

A: One possible approach would be to place such variable in the globals:
$GLOBALS['ENABLE_DEBUG_OUTPUT'] = true;

and then
if (isset($GLOBALS['ENABLE_DEBUG_OUTPUT'])){
  echo ...
}

A: Use a global debug function like:
// $level = 0 nothing - 9 alert with email
function debug($str, $level = 1) {
    // Uncomment the following line in NO_DEBUG mode:
    //return;

    switch ($level) {
        case 9:
            //mail();
        case 8:
        case 7:
        case 5:
            // file_put_contents(); // or whatever
        case 3:
            echo $str, PHP_EOL;
        case 2:
        case 1:
        case 0: break;
    }
}

You can put in different levels and say, if its lvl 9 it sends a mail, writes a log and echos to screen. on lvl 5 you only want write a log and print to screen (that's why I don't break upon every case).
With a function like taht you don't have to wrap
if (defined('ENABLE_DEBUG')) {
    //...
}

arround every debug message but instead simply use debug('test string');

A: you can also use constants in php :
<?php
  define('DEBUG', true);

And you can create a function to display things only if DEBUG is true
<?php

  function debug($obj)
  {
    if (DEBUG)
    {
      echo '<pre>';
      var_dump($obj);
      echo '</pre>';
    }
  }

I personally use a function debug($obj, $label) which send this to Firephp to have the debug info in the firebug console


text:
Q: Which is better: cURL or fopen (with a stream context) What differences are between curl() and fopen()(with a stream context) while trying to get remote content.
Flexibility? Feature-rich? or What.. Is there something, that one can do, and another cant?

A: If I'm not wrong, both the PHP curl extension and streams are dinosaurs from the PHP/4 days with the kind of API you could expect from the early days of the language: incoherent and with magic features that happen to be a security hole, such as @ prefixes in strings that trigger file uploads (curl) and remote downloads taking place in the least expected places (such as include statements).
However, unlike other agey extensions like mysql or mcrypt, both of these appear to have been properly maintained along the years so I'd dare say that in 2017 they are both equality safe and reasonably feature-packed. Of course, none of them are object-oriented or nice to use and that led to creation of wrappers like Guzzle and standardisation attempts like PSR-7.
If we stick to plain HTTP, I believe the feature set is roughly the same, except that Curl has native support for multipart/form-data file uploads (with streams you need to implement it yourself, although it isn't difficult) and cookie handling.
Also, Curl has been heavily used along the years and you'll possibly find better documentation and less outdated information about it.
The key point of PHP streams is that they go way beyond HTTP (you can even register your own protocols) and they integrate nicely with several other PHP extensions (most builtin functions that accept file pointers will also accept streams). Curl, however, is mostly a self-contained wrapper on top of the C extension of the same name.
As about availability, I've seen both features missing from hosting plans, but that tends to happen on lame plans purchased by unaware customers.
To sum up: both are ugly, both get the job done. Benchmarks aside (I've done none) it's mostly a matter of preference... until you need a feature that one can do and the other cannot :-)

A: This question has been answered multiple times before, but here is my take on it.
Curl is a lot more powerful when it comes to streaming, sending, receiving and everything else you can possibly want to do.
fopen is not designed for web-requests in general and can only do GET requests easily. POST requests are counter-intuitive and are probably more of a hack than an acceptable practice.
Curl supports SSL, custom headers, cookies, file upload and is by default available on all hosting provides, while url requests with fopen are frequently disabled and have to be re-enabled by administrator.
Additionally, unless you are using a framework which has its own implementation for web requests, you should always stick with CURL because everyone is familiar with it.


text: Q: How to know when a client has disconnected in Socket.IO because of connection issues? I've noticed that with socket.io server, if the client's network times out, then the server never gets the disconnect event. How do I handle disconnect in case the client silently times out? Or do I get the disconnect even after very long time? Can anyone explain what happens  in socket.io server, when client silently disconnects (power plugged, router crashed, network issues, etc.)


text:
Q: Function score inside the Post filter query.(elasticsearch) I ran these following queries.
This query gives me proper score as expected.
{
  "query": {
    "filtered": {
      "query": {
        "function_score": {
          "query": {
            "bool": {
              "should": [
                {
                  "match": {
                    "categorytags_snow": "gyms"
                  }
                },
                {
                  "match": {
                    "locationtags_snow": "gyms"
                  }
                },
                {
                  "match": {
                    "offerings_snow": ""
                  }
                },
                {
                  "match": {
                    "title_snow": "gyms"
                  }
                },
                {
                  "match": {
                    "locationcluster_snow": "gyms"
                  }
                },
                {
                  "match": {
                    "facilities_snow": "gyms in bandra"
                  }
                },
                {
                  "match": {
                    "info_service_snow": "gyms"
                  }
                }
              ]
            }
          },
          "functions": [
            {
              "filter": {
                "query": {
                  "bool": {
                    "should": [
                      {
                        "match": {
                          "categorytags_snow": "gyms"
                        }
                      }
                    ]
                  }
                }
              },
              "boost_factor": 8
            },
            {
              "filter": {
                "query": {
                  "bool": {
                    "should": [
                      {
                        "match": {
                          "locationtags_snow": "gyms"
                        }
                      }
                    ]
                  }
                }
              },
              "boost_factor": 10
            },
            {
              "filter": {
                "query": {
                  "bool": {
                    "should": [
                      {
                        "match": {
                          "offerings_snow": "gyms"
                        }
                      }
                    ]
                  }
                }
              },
              "boost_factor": 4
            },
            {
              "filter": {
                "query": {
                  "bool": {
                    "should": [
                      {
                        "match": {
                          "title_snow": "gyms"
                        }
                      }
                    ]
                  }
                }
              },
              "boost_factor": 12
            },
            {
              "filter": {
                "query": {
                  "bool": {
                    "should": [
                      {
                        "match": {
                          "locationcluster_snow": "gyms"
                        }
                      }
                    ]
                  }
                }
              },
              "boost_factor": 2
            },
            {
              "filter": {
                "query": {
                  "bool": {
                    "should": [
                      {
                        "match": {
                          "facilities_snow": "gyms"
                        }
                      }
                    ]
                  }
                }
              },
              "boost_factor": 2
            },
            {
              "filter": {
                "query": {
                  "bool": {
                    "should": [
                      {
                        "match": {
                          "info_service_snow": "gyms"
                        }
                      }
                    ]
                  }
                }
              },
              "boost_factor": 6
            }
          ],
          "boost_mode": "max",
          "score_mode": "sum"
        }
      },
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "city": "bankok"
              }
            }
          ]
        }
      }
    }
  }
}

While this query where i am using post_filter to wrap my query is not computing desired score(score is always 1)
{
  "post_filter": {
    "query": {
      "filtered": {
        "query": {
          "function_score": {
            "query": {
              "bool": {
                "should": [
                  {
                    "match": {
                      "categorytags_snow": "gyms"
                    }
                  },
                  {
                    "match": {
                      "locationtags_snow": "gyms"
                    }
                  },
                  {
                    "match": {
                      "offerings_snow": "gyms"
                    }
                  },
                  {
                    "match": {
                      "title_snow": "gyms "
                    }
                  },
                  {
                    "match": {
                      "locationcluster_snow": "gyms"
                    }
                  },
                  {
                    "match": {
                      "facilities_snow": "gyms"
                    }
                  },
                  {
                    "match": {
                      "info_service_snow": "gyms"
                    }
                  }
                ]
              }
            },
            "functions": [
              {
                "filter": {
                  "query": {
                    "bool": {
                      "should": [
                        {
                          "match": {
                            "categorytags_snow": "gyms"
                          }
                        }
                      ]
                    }
                  }
                },
                "boost_factor": 8
              },
              {
                "filter": {
                  "query": {
                    "bool": {
                      "should": [
                        {
                          "match": {
                            "locationtags_snow": "gyms"
                          }
                        }
                      ]
                    }
                  }
                },
                "boost_factor": 10
              },
              {
                "filter": {
                  "query": {
                    "bool": {
                      "should": [
                        {
                          "match": {
                            "offerings_snow": "gyms"
                          }
                        }
                      ]
                    }
                  }
                },
                "boost_factor": 4
              },
              {
                "filter": {
                  "query": {
                    "bool": {
                      "should": [
                        {
                          "match": {
                            "title_snow": "gyms"
                          }
                        }
                      ]
                    }
                  }
                },
                "boost_factor": 12
              },
              {
                "filter": {
                  "query": {
                    "bool": {
                      "should": [
                        {
                          "match": {
                            "locationcluster_snow": "gyms"
                          }
                        }
                      ]
                    }
                  }
                },
                "boost_factor": 2
              },
              {
                "filter": {
                  "query": {
                    "bool": {
                      "should": [
                        {
                          "match": {
                            "facilities_snow": "gyms"
                          }
                        }
                      ]
                    }
                  }
                },
                "boost_factor": 2
              },
              {
                "filter": {
                  "query": {
                    "bool": {
                      "should": [
                        {
                          "match": {
                            "info_service_snow": "gyms"
                          }
                        }
                      ]
                    }
                  }
                },
                "boost_factor": 6
              }
            ],
            "score_mode": "sum"
          }
        },
        "filter": {"bool": {
          "must": [
            {
              "term": {
                "city": "bankok"
              }
            }
          ]
        }}
      }
    }
  }
}

Is it like query inside post_filter don't support function_score.
Thanks in advance

A: This is expected, as stated in the official doc and the definitive guide, anything in post_filter will run after the query has executed and will not affect the query scope, hence will not affect the score either.
Besides post_filter is a basically a filter and filters do not affect scoring, score 1 is always returned.


text: Q: Jenkins - Creating parallel ipa build creation for multiple targets for iOS Application We have one iOS Application projects with a huge number of targets lets say 30, we can build targets individually or one by one through Jenkins, but this take huge time like 5-6 hrs since it has to generate 30 IPA. So is there any alternate way to parallelly generate multiple ipa's using Jenkin's? Help me out with any possible tutorials or examples. Or with MultiJob plugin how we should do it with an example.


text:
Q: Executing Python code with a custom local dictionary As a follow-up to this question I asked earlier, I'm experimenting with executing Python code as if it were in the context of an outer function.  I do this by simply wrapping a block of code with def outer():, and doing some simple string processing to properly indent the inner code.  Then I compile it and execute the compiled inner code by executing the first code object in the co_consts list.
Example:
mycode = """
print("Hey!")
"""

wrapped_code = 'def outer():\n    ' + '\n    '.join(mycode.strip().split('\n'))
compiled_code = compile(wrapped_code, '<str>', 'exec')
exec(compiled_code.co_consts[0], {}, {})

This executes the code print("Hey") from within the context of an outer function.  (If anyone is wondering why I'm doing this, it's part of a C extension module I've been working on.)

Question: A problem I run into is that if I wrap code in an outer function, and then execute the inner block of code, I don't seem to be able to pass any local variables to the execution context.
mycode = """
print(locals())
"""

wrapped_code = 'def outer():\n    ' + '\n    '.join(mycode.strip().split('\n'))
compiled_code = compile(wrapped_code, '<str>', 'exec')
exec(compiled_code.co_consts[0], {}, {"foo" : "bar"})

This outputs:
{}

Notice that I explicitly passed a local dict containing {"foo" : "bar"} to exec, yet when it actually executes the code and prints locals(), it shows an empty dictionary.  Why didn't Python use the dictionary of local variables I passed it?

A: You are passing in a function as the first parameter to exec. A function will define it's own locals, so that's the locals you are printing. Remove the wrapping (which I can't see any use of whatsoever) and it works.


text:
Q: Upload word file with cfinder integrated into ckeditor Is there a posibility to upload a file with ckfinder when integrated into ckeditor? I'm trying to upload a word document and insert the link into the text that is currently edited in ckeditor, but i can only upload images and flash files. Is there a way to browse the server and upload any files without placing another ckfinder control for the upload of non-embeddable files?
I am using it on a 2.0 asp.net page

A: Use the link dialog, it should have a browse server button if you have integrated CKFinder correctly.