text:
Q: Which integer polynomials represent fewer primes, in terms of order of magnitude, when shifted by a constant integer? Let $f(x_1,\dots,x_n) \in \mathbb{Z}[x_1,\dots,x_n]$ be a polynomial for which the set of integers not represented by it is infinite. I'm curious about cases in which there exists an integer $c$ such that the density of primes represented by $f$ and those represented by $f+c$ differ in their orders of magnitude.
[EDIT: It seems that the previous condition on the set of integers not represented by $f$ needs to be improved to: not $o(N/\log N)$. The example of $f(x,y,z)=2x^2+xy+3y^2+z^3-z$ in this interesting question, Integers not represented by $2x^2+xy+3y^2+z^3-z$, makes one aware of this. Thank you for the hint!]
[EDIT: A slightly more specific and maybe better way to phrase the question is: For which $f\in \mathbb{Z}[x_1,\dots,x_n]$ do we have $f$, $f+1$ both representing an infinite amount of primes and
$$
\sum_{\substack{p \leq N\\p-1 = f(x_1,\dots,x_n)}} 1 = o\left(\sum_{\substack{p \leq N\\p = f(x_1,\dots,x_n)}} 1\right)?
$$
Thanks to js who points out that if one believes the Bateman-Horn conjecture, then this phenomenon is specific to multivariate polynomials.]
Motivation: These two questions, Integers represented by the polynomial $a^2+b^3+c^6$ and Primes $1+x^2+y^2$, made me wonder. In the second linked question, the integers less than $N$ represented by $x^2+y^2+a^2$ for any $a\in\mathbb{Z}$ are asymptotically the same, namely
$$
\frac{0.7642\dots N}{\sqrt{\log N}}.
$$
Yet the primes less than $N$ representable by $x^2+y^2$ are asymptotically
$$
\frac{N}{2\log N}
$$
while those less than $N$ representable by $x^2+y^2+1$ have order of magnitude
$$
\asymp \frac{N}{(\log N)^{3/2}}.
$$
Question: Is there a really good way to characterize which polynomials $f$ behave somewhat like this?
Intuitively, it seems that the above difference is due to the phenomenon that the more factors $x^2+y^2=m$ has, then the more "collisions" as well - many $(x,y)$ map to the same $m$. As in here. And $p-1$ is always composite, except $p=2,3$. But I don't know if this is the right way to think of the question, or whether other $f$ which are like this, behave like this for the same reason.
Note: Let's exclude the cases where the polynomial becomes reducible over $\mathbb{Z}[x_1,\dots,x_n]$ after being shifted. I.e., let's stick to cases where both $f$ and $f+c$ still represent an infinite amount of primes.
Thank you.
EDIT: I'm not really sure about this, but perhaps one possible way is to consider norm forms for algebraic number fields, generalizing the case of $f(x,y)=x^2+y^2$ corresponding to $\mathbb{Q}[i]$. If $f$ is the norm of elements in the ring of integers of some number field, then the primes less than $N$ represented by it will have order of magnitude
$$
\asymp\frac{N}{\log N}.
$$
The exact constant depends on the degree and class number of the field. Then the task is to understand how often it takes values in $\mathbb{P}-1$. In the case of $f(x,y)=x^2+y^2$, it seems we had
$$
\sum_{\substack{p\leq N\\p-1=x^2+y^2}}1 = o(N/\log N)
$$
because the integers of the form $x^2+y^2$ were characterised by being divisible by even powers of primes $q\equiv 3 \bmod 4$ with no condition on the primes $q \equiv 1 \bmod 4$. This is in turn was due to the properties of $f$ coming from a number field, in this case, $\mathbb{Q}[i]$. We then had to estimate the number of primes $p\leq N$ for which the factorization of $p-1$ has only even powers of $q \equiv 3 \bmod 4$ occuring. Found something helpful on binary quadratic forms in the whole of section 4 of these notes by Pete Clark and Proposition 4.1 of these course notes of Andrew Granville. They give the analogue of this phenomena for binary quadratic forms. This motivates:
Question 2: For any form $f$ that is the norm of elements in the ring of integers of a number field, is there a general statement that will characterise the set of integers represented by it in such a way that will allow us to conclude that
$$
\sum_{\substack{p\leq N\\p-1=f(x_1,\dots,x_n)}}1 = o(N/\log N)?
$$
Thank you.
EDIT: It seems that Question 2 is nicely thought of in the following light: Motivated by the comment by Greg Martin in this interesting question, Average orders of multiplicative functions, one is led to consider Theorem 1 of this paper, Counting numbers in multiplicative sets: Landau versus Ramanujan of Moree on multiplicatively-closed sets, and also this MO question, Density of a set of integers. These indicate that the primes in such multiplicatively-closed sets occur more frequently than what would be expected from applying the heuristics on the likelihood of an integer being prime derived from the Prime Number Theorem to a "random" set which is the same size as the multiplicatively-closed set in question. The integers represented by the function $f$ in Question 2 are a multiplicatively-closed set, but shifting them by a constant integer removes this property. Guess that accounts for Question 2. Now, this interesting question, What is the geometry of an undecidable diophantine equation?, shows that the general case is really not straightforward!


text:
Q: Basic question about wave funtions: using the Born rule I have a textbook giving an example of what the probability is of observing system $Ψ = a|A⟩ + b|B⟩$ in states $a|A⟩$ and $b|B⟩$.
I'm not sure I understand it fully. How do I use the Born rule to know the probability of observing system $Ψ = a|A⟩ + b|B⟩ + c|C⟩$ in the state $c|C⟩$?
Could someone please give a rundown of the steps?

A: If I understand your question correctly, you would want to calculate the probability of observing $\vert \Psi\rangle$ in the normalized state $\vert C\rangle$ (without the prefactor $c$).

*

*Form the bra $\langle C\vert$.

*Compute the overlap $\langle C\vert \Psi\rangle$:
\begin{align}
\langle C\vert \Psi\rangle=&a \langle C\vert A\rangle +b \langle C\vert B+ c\langle C\vert C\rangle\, ,\\
&= c + a \langle C\vert A\rangle +b \langle C\vert B\rangle\, ,
\end{align}
where $\langle C\vert C \rangle =1 $ has been used.

*Compute the modulus square of this (generally complex) number:
$$
P(\vert C\rangle) =
\vert c + a \langle C\vert A\rangle +b \langle C\vert B\rangle \vert^2
= (c + a \langle C\vert A\rangle +b \langle C\vert B\rangle)^*
(c + a \langle C\vert A\rangle +b \langle C\vert B\rangle)
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Application on key as home button I'm collecting measurements in an Excel workbook.
All the measurements are displayed in separate sheets.
The average and max of every sheets'  measurement is displayed in the home sheet (with the name "1")
I added a line of code to jump from the home sheet to a certain sheet by entering the sheet name in cell J23 and clicking on a button.
Now i'd like to add a physical key/button in order to go back to the home sheet.
for example with ctrl+b
unfortunately my code does not work yet.
I've pasted my code below, hope someone has a solution.
Thanks in advance
Sub Macro1()

i = Sheets("1").Range("J23").Value

    Worksheets(i).Select

End Sub

Sub Home()

Application.OnKey "^b", Worksheets("1").Select

End Sub

A: You need to pass Application.OnKey the name of a procedure, not a VBA command as you are trying to do.
Something along these lines:
Sub Home()
    Sheets(1).Select
End Sub

Sub SetUp()
    Application.OnKey "^b", "Home"
End Sub

The above subs are in a standard code module. When I run SetUp, I am afterwards able to get back to Sheet1 from any other sheet by entering Ctrl+b.


text:
Q: Does acquiring and releasing java monitor locks (synchronized blocks, reentrant locks etc) requires context switch to kernel space? AFAIK, Every object in Java has a mark word. The first word (the mark word) is used for storing locking information, either through a flag if only one thread is acquiring the lock or pointing to a lock monitor object if there is contention between different threads, and in both the cases, compare and swap construct is used for acquiring the lock.
But according to this link -
https://www.baeldung.com/lmax-disruptor-concurrency

To deal with the write contention, a queue often uses locks, which can cause a context switch  to the kernel. When this happens the processor involved is likely to lose the data in its caches.

What am I missing ?

A: Neither, synchronized nor the standard Lock implementations, require a context switch into the kernel when locking uncontended or unlocking. These operations indeed boil down to an atomic cas or write.
The performance critical aspect is the contention, i.e. when trying to acquire the monitor or lock and it's not available. Waiting for the availability of the monitor or lock implies putting the thread into a waiting state and reactivating it when the resource became available. The performance impact is so large, that you don't need to worry about CPU caches at all.
For this reason, typical implementations perform some amount of spinning, rechecking the availability of the monitor or lock in a loop for some time, when there is a chance of becoming available in that time. This is usually tied to the number of CPU cores. When the resource becomes available in that time, these costs can be avoided. This, however, usually requires the acquisition to be allowed to be unfair, as a spinning acquisition may overtake an already waiting thread.
Note that the linked article says before your cited sentence:

Queues are typically always close to full or close to empty due to the differences in pace between consumers and producers.

In such a scenario, the faster threads will sooner or later enter a condition wait, waiting for new space or new items in a queue, even when they acquired the lock without contention. So in this specific scenario, the associated costs are indeed there and unavoidable when using a simple queue implementation.


text:
Q: How do I create an Alarm to detect DynamoDb limits have reached a certain percent and then increase it I'm writing a web application that has steadily increasing traffic through the day.  I'd like to create an Alarm that can detect if my read / write limits have reached a certain percentage (like 80%), and then increase that limit.  I will then decrease it again at midnight.
I've tried creating an Alarm - "Average" seems a bit useless and is always 1.0. "Sum" is more useful so I assume i should use this.  I also assume i should use Consumed Write/Read Capacity at the metric name.
Problems:

*

*Sum seems to use an absolute value of "Count" for its limits.  If my DynamoDB is set to 100 writes, and i setup an alarm for 80%, it checks if my writes exceed 0.8, not 80.

*I've setup an email topic, but this is not correct - I assume I need to create a function/controller which a topic can call.  How would i set this up and if you have 2 Amazon VM's, would both get called or just one? Or is this the wrong route and there is a standard action one can take on events to increase DynamoDB limits without coding anything. (my lack of SNS knowledge is probably showing here)

A: When running Amazon's wizard to create a table, it suggests to create an alarm at 80% threshold and to link it to an SNS topic.
Under the hood, for R/W capacity of 1, this creates an alarm on

*

*ConsumedReadCapacityUnits >= 240 for 60 minutes

*ConsumedWriteCapacityUnits >= 240 for 60 minutes

240 = 0.8*1*60*5 that is to say, capacity(1) * seconds_in_5_minutes(300) * threshold(0.8). 60 minutes is the alarm period. You can shorten down to 5 min but this might increase the number of false positive.
In other words, the alarm is triggered every time the sum of the consumed capacity units on ranges of 5 min exceeds the 24 treshold for at least 1 hour.
note: 5 min corresponds to the sampling period.
In the SNS console, you can add 'subscribers' to a topic. They can be e-mails, HTTP(S) callbacks, ... This allow you to contact multiple human/machines.
Every time your scaling logic is triggered, you will need to use the API to automatically update the alarms using this formula.


text:
Q: Debug .ps1 file started from a dos command file I want to run a Powershell script (.ps1) to deploy Biztalk2009 artifacts in a virtual machine.
The .ps1 file is running from a dos command file called 'install.cmd'.
As part of the install.cmd file the Powershell is runned:
powershell -command "& {get-content %1 | .\Install.ps1}"

The 24 parameters needed for the script are stored in a .txt file and the filename is given as a parameter of the dos command file. The parameter file is just a regular .txt file. So I run the dos command file as:
install.cmd dev.txt

Now I encounter several exceptions and I want to debug the Powershell script(s). The initial Powershell script uses a 2nd function Powershell script called 'functions.ps1'.
The exceptions are arising from the 2nd script.
How can I easily debug the Powershell scripts that are started from a dos command ?

A: If you can modify Install.ps1, insert a Set-PSDebug -Step command near the beginning of the script or where you are interested in stepping through the script.  Once you start stepping you can press "S" to enter a nested prompt and from there you can examine the value of variables variables (and modify their values) as well as execute commands.
If you are on PowerShell 2.0, you can also use Set-PSBreakpoint on a line in your script or the use of a command or the read/write of a variable.


text:
Q: 'No data to display' message when gridstore is loaded Ext JS Extjs 4.3.1I have a grid that is being loaded with a javascript array. The array is populated but when the page is loaded nothing appears. When you click the refresh button in the Ext.toolbar dock the items appear.
How do I make the data load when the page is rendered and not when the refresh button is selected?

Code
var grid = [],
        title = 'Topics List',
        gridHeight = 600,
        uniqueId = 'topics',
        dSort = 'modified',
        dSortOrder = 'DESC';
    var items = [];

    Ext.define('Model', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'title', type: 'string'},
        {name: 'description', type: 'string'},
        {name: 'updated', type: 'date'},
        {name: 'state', type: 'string'}
    ]
    });
    var gridStore = Ext.create('Ext.data.Store', {
        model: 'Model',
        autoload: true,
        proxy: {
            type: 'ajax',
            url: url,
            reader: {
                type: 'json',
                root: 'entry',
                idProperty: 'title'
            }
        },
            fields: [{
                name: 'title',
                type: 'string'
            }, {
                name: 'description',
                type: 'string'
            }, {
                name: 'updated',
                type: 'date',
                format: 'm/d/Y'
            }, {
                name: 'state',
                type: 'string'
            }],
            sorters: [{
                property: 'updated',
                direction: 'DESC'
            },{
                property: 'title',
                direction: 'DESC'
                }
            ],
            listeners: {
                render: function () {
                    gridStore.load();
                }
            }

        });

        var searchField = new SearchField({store: gridStore, width: 300});
        var filters = {
            ftype: 'filters',
            // encode and local configuration options defined previously for easier reuse
            encode: false, // json encode the filter query
            local: true   // defaults to false (remote filtering)

        };
        var searchBar = Ext.create('Ext.toolbar.Toolbar', {
            cls: 'x-toolbar-top',
            items: ['Search: ', ' ', searchField, {xtype: 'tbfill'}]
        });
        var clearButton = Ext.create('Ext.Button', {
            text: 'Clear Filter Data',
            handler: function () {
                grid[uniqueId].filters.clearFilters();
            }
        });
        var openButton = Ext.create('Ext.Button', {
            text: 'Open Topics',
            handler: function () {
                var filter = grid[uniqueId].filters.getFilter('state');
                if (!filter) {
                    filter = grid[uniqueId].filters.addFilter({
                        type: 'string',
                        dataIndex: 'state'
                    });
                }
                filter.setActive(true);
                filter.setValue('Open/Current');
            }
        });
        var holdButton = Ext.create('Ext.Button', {
            text: 'On Hold Topics',
            handler: function () {
                var filter = grid[uniqueId].filters.getFilter('state');
                if (!filter) {
                    filter = grid[uniqueId].filters.addFilter({
                        type: 'string',
                        dataIndex: 'state'
                    });
                }
                filter.setActive(true);
                filter.setValue('Hold');
            }
        });
        var closedButton = Ext.create('Ext.Button', {
            text: 'Closed Topics',
            handler: function () {
                var filter = grid[uniqueId].filters.getFilter('state');
                if (!filter) {
                    filter = grid[uniqueId].filters.addFilter({
                        type: 'string',
                        dataIndex: 'state'
                    });
                }
                filter.setActive(true);
                filter.setValue('Archived/Closed');
            }
        });

        var createColumns = function () {

            var columns = [{
                text: 'Title',
                width: 260,
                dataIndex: 'title',
                filterable: true
            }, {
                text: 'Description',
                flex: 1,
                dataIndex: 'description',
                filter: {
                    type: 'string'
                    // specify disabled to disable the filter menu
                    //, disabled: true
                }
            }, {
                text: 'Status',
                width: 100,
                dataIndex: 'state',
                filter: {
                    active: true,
                    type: 'list',
                    //value: 'Open/Current',
                    options: ['Open/Current', 'Archived/Closed', 'Hold']

                }
            }, {
                text: 'Modified',
                width: 90,
                dataIndex: 'updated',
                xtype: 'datecolumn',
                format: 'm/d/Y',
                filter: true
            }];

            return columns;
        };
        grid[uniqueId] = Ext.create('Ext.grid.GridPanel', {
            renderTo: uniqueId,
            store: gridStore,
            tbar: [
                searchBar,
                openButton,
                holdButton,
                closedButton,
                clearButton
            ],
            columns: createColumns(),
            enableColumnHide: true,
            enableColumnMove: true,
            height: gridHeight,
            title: title,
            loadMask: true,
            features: [filters],
            dockedItems: [Ext.create('Ext.toolbar.Paging', {
                dock: 'bottom',
                store: gridStore,
                displayInfo: true
            })],
        listeners: {
            render: function () {
                gridStore.load();
            }
        }
        });

JSON ex
"entry": [{
        "title": "Alternative Methods",
        "shortTitle": "LCRs",
        "description": "This project is a carryover from the 2017 effort.",
        "govStatus": "Progress",
        "state": "Open/Current",
        "dateCreated": "",
        "targetComplete": "",
        "updated": "2017-08-14T10:58:19"
    },...

A: If the grid is not loading, then what do you get when you add a listener to the gridPanel for 'onRender'? Is the data from your store available on the grid render?
http://docs.sencha.com/extjs/4.2.4/#!/api/Ext.grid.Panel-event-render

A: Populate the store before creating the grid using ajax or store.load(). What is happening in your case is that, the store has not finished loading by the time grid is rendered. That is why on refreshing the data is there and not on render.


text:
Q: Small question about the output form of the derivative I have an expression:
D[D[Subscript[T, 1][x[t], y[t], x'[t]] + Subscript[T, 2][x[t], y[t], y'[t]], x'[t]], t]

The result is:
$y'(t) T_1{}^{(0,1,1)}\left(x(t),y(t),x'(t)\right)+x'(t)
   T_1{}^{(1,0,1)}\left(x(t),y(t),x'(t)\right)+x''(t)
   T_1{}^{(0,0,2)}\left(x(t),y(t),x'(t)\right)$
I need to make it so that when differentiating with respect to time, variables $x'(t)$ and $y'(t)$ are not taken out of brackets.

A: Clear["Global`*"]

Use HoldForm
(expr = HoldForm[
   D[D[Subscript[T, 1][x[t], y[t], x'[t]] +
      Subscript[T, 2][x[t], y[t], y'[t]], x'[t]], t]])

expr // TraditionalForm

expr // ReleaseHold

EDIT: To reverse the order of the products
expr2 = HoldForm[D[D[f[x[t], y''[t], z''[t], x'[t]], x'[t]], t]]

expr2 // TraditionalForm

expr2r = (expr2 // ReleaseHold) /. Times[a_, b_] :> HoldForm[Times[b, a]]

expr2r // TraditionalForm

EDIT 2: For the revised question
expr3 = Derivative[2][x][t]*
    Derivative[0, 0, 2, 0, 0][f][x[t], y[t], Derivative[1][x][t],
     Derivative[2][y][t], Derivative[3][z][t]] +
   Derivative[3][y][t]*
    Derivative[0, 0, 1, 1, 0][f][x[t], y[t], Derivative[1][x][t],
     Derivative[2][y][t], Derivative[3][z][t]] +
   Derivative[1][y][t]*
    Derivative[0, 1, 1, 0, 0][f][x[t], y[t], Derivative[1][x][t],
     Derivative[2][y][t], Derivative[3][z][t]] +
   Derivative[1, 0, 0, 0, 0][f][x[t], y[t], Derivative[1][x][t],
    Derivative[2][y][t], Derivative[3][z][t]] +
   Derivative[4][z][t]*
    Derivative[0, 0, 1, 0, 1][f][x[t], y[t], Derivative[1][x][t],
     Derivative[2][y][t], Derivative[3][z][t]] +
   Derivative[1][x][t]*
    Derivative[1, 0, 1, 0, 0][f][x[t], y[t], Derivative[1][x][t],
     Derivative[2][y][t], Derivative[3][z][t]];

(expr3r = expr3 /. Plus :> Inactive[Plus] /.
    Inactive[Plus][a__, b_, c_] :> Inactive[Plus][a, c, b]) //
      TraditionalForm

For subsequent operations Activate expr3r


text:
Q: Entitydatasource to Datatable I have a Gridview that reads the DataSource from an EntityDataSrouce.
Now I want to convert the EntityDatasource of the gridview to DataTable so I can export it the Gridview as an Excel file.

A: You do not need to convert it to DataTable just to export. You can do it by gridview self.
Look at this link:
http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html
In this article, the author uses a utility class that export it to .xls file, so, you can download it, add on your project and use like the sample.


text:
Q: Getting a Notice: Undefined variable: _SESSION after uploading local site to a web hosting I am soon to be done on my website project and I am having a little trouble.
Today I bought a web hosting server and a domain.
Everything works perfectly on xampp on my localhost, but on the server the sessions seem to not work properly.
I have no idea why.
It presents to me with the error: Notice: Undefined variable: _SESSION
Although, the session does store something within it because it redirects me back to my main page when I try to go to the login page. It is right to do because there is an if in the start of the login page that does just that.
It also destroys the contents of the session when I go to logout.php and lets me enter login.php when previously I couldn't without destroying it first.
I updated my site's php version to 7.3 and no luck so far.
I am completely lost. I thought this question would have a lot of answers but none of the answers I've found online helped me.
This is the code of the login page:
<?php
// Initialize the session
session_start();

if(!empty($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: index.php");
exit;
}

// Include config file
require_once "config.php";

// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){

// Check if username is empty
if(empty(trim($_POST["username"]))){
    $username_err = "Please enter username.";
} else{
    $username = trim($_POST["username"]);
}

// Check if password is empty
if(empty(trim($_POST["password"]))){
    $password_err = "Please enter your password.";
} else{
    $password = trim($_POST["password"]);
}

// Validate credentials
if(empty($username_err) && empty($password_err)){
    // Prepare a select statement
    $sql = "SELECT id, username, password FROM accounts WHERE username = ?";

    if($stmt = mysqli_prepare($link, $sql)){
        // Bind variables to the prepared statement as parameters
        mysqli_stmt_bind_param($stmt, "s", $param_username);

        // Set parameters
        $param_username = $username;

        // Attempt to execute the prepared statement
        if(mysqli_stmt_execute($stmt)){
            // Store result
            mysqli_stmt_store_result($stmt);

            // Check if username exists, if yes then verify password
            if(mysqli_stmt_num_rows($stmt) == 1){
                // Bind result variables
                mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
                if(mysqli_stmt_fetch($stmt)){
                    if(password_verify($password, $hashed_password)){
                        // Password is correct, so start a new session
                        session_start();

                        // Store data in session variables
                        $_SESSION["loggedin"] = true;
                        $_SESSION["id"] = $id;
                        $_SESSION["username"] = $username;

                        // Redirect user to welcome page
                        header("location: index.php");
                    } else{
                        // Display an error message if password is not valid
                        $password_err = "The password you entered was not valid.";
                    }
                }
            } else{
                // Display an error message if username doesn't exist
                $username_err = "No account found with that username.";
            }
        } else{
            echo "Oops! Something went wrong. Please try again later.";
        }
    }

    // Close statement
    mysqli_stmt_close($stmt);
}

// Close connection
mysqli_close($link);
}
?>

<!DOCTYPE html>

<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">

Login

Please fill in your credentials to login.

    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
        <div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
            Username
            <input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
            <?php echo $username_err; ?>

        <div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
            Password
            <input type="password" name="password" class="form-control">
            <?php echo $password_err; ?>

            <input type="submit" class="btn btn-primary" value="Login">

Don't have an account? Sign up now.

    </form>

Needless to say but the session is initialized in the page.
I have only 1 page and it is the index.php.
The session is initialized every time I use it - register.php, login.php, index.php.
I also have a condition in the nav bar to present a special navigation option if the user is logged in.
 if(array_key_exists('loggedin', $_SESSION) && $_SESSION['loggedin'] == 1){
 echo "";
 echo "
Logout
";
 echo "

Catalog (Wish Premium)

";
 }
 else{
 echo "
Login
";
 echo "";
 echo "";
 }

This does not work although the session stores something.
The register page functions great and the connection between the site and the sql server works flawlessly.
I can insert users and it will tell me if the login is incorrect in the login page.
What could be the problem?

A: I could have deleted this but I'd rather answer to myself and serve as a solution to future beginners in php instead of just deleting this resulting in complete waste of time.
The solution is that I put

session_start();

after I started my HTML code.
When I placed session_start(); at the head of the document everything worked just fine.
Thank you readers for reading, thank myself for...nothing.


text:
Q: Insert new rows if values from TWO columns doens't already exists (peewee with PostgreSQL db) I'm trying to insert new rows if values from user_id AND answered_at doesn't already exists in my table.
Here's my model:
class NPS(BaseModel):
    class Meta:
        schema = os.getenv('SCHEMANAME')
        table_name = os.getenv('TABLENAME')

    user_id = pw.IntegerField()
    answered_at = pw.DateField()
    score = pw.IntegerField()
    motivation = pw.TextField()
    comment = pw.TextField(null=True)
    attempts = pw.DateField()
    scores = pw.TextField()

And here's the insert part, where dados_nps is a list of dicts in right format:
cursor = (NPS
          .insert_many(dados_nps)
          .on_conflict(conflict_target=[NPS.user_id, NPS.answered_at], action='ignore')
          .returning())

inserted_rows = cursor.execute()
print(inserted_rows)

As you can see, I'm passing a list of (two) fields in conflict_target: [NPS.user_id, NPS.answered_at]. But this is not working, because the rows are always inserted.
The action argument is right? There's something else I'm missing in my class model definition or inside the on_conflict() method?
Maybe should I set something in constrainst using Check() like this example?
class Meta:
   constraints = [Check('user_id AND answered_at NOT EXISTS')]

http://docs.peewee-orm.com/en/latest/peewee/models.html?highlight=constraint#indexes-and-constraints
Obs: I'm using returning() to after this count the number of rows inserted.

A: As @AdamKG pointed out, I needed to pass unique indexes to my class model.
This solves the problem, thanks!
If someone else is still getting this problem, maybe this can be the error:
I was trying to do this, but not working yet
class NPS(BaseModel):

    user_id = pw.IntegerField()
    answered_at = pw.DateField()
    score = pw.IntegerField()
    motivation = pw.TextField()
    comment = pw.TextField(null=True)
    attempts = pw.DateField()
    scores = pw.TextField()

    class Meta:
        schema = os.getenv('SCHEMANAME')
        table_name = os.getenv('TABLENAME')

        indexes = (
            (('user_id', 'answered_at'), True)
        )

But the documentation says that we need to keep the trailing comma in the 2-tuple, so this works:
class NPS(BaseModel):

    user_id = pw.IntegerField()
    answered_at = pw.DateField()
    score = pw.IntegerField()
    motivation = pw.TextField()
    comment = pw.TextField(null=True)
    attempts = pw.DateField()
    scores = pw.TextField()

    class Meta:
        schema = os.getenv('SCHEMANAME')
        table_name = os.getenv('TABLENAME')

        # need to keep the trailing comma
        indexes = (
            (('user_id', 'answered_at'), True),
        )

Note the trailing coma in indexes.


text:
Q: WorksheetFunction.Match Cannot Paste/Run I recently upgraded my work Microsoft account from Excel 2010 to Excel 2016.
While I still had Excel 2010, I coded a series of Macros to automate a substantially tedious task. Upon moving to Excel 2016, one of my VBA scripts appears to have "broken".
Below is the script:
Sub RunMacro()

Sheets("Control1").Select

'Step 1: #Script searches for header matches in Control1 dataset, then will copy in next
'step to Data list

    With Sheets("Control1")

        Route_Name = WorksheetFunction.Match("ROUTE_NAME", Rows("1:1"), 0)
        Feature_Type = WorksheetFunction.Match("FEATURE_TYPE", Rows("1:1"), 0)
        Shape_Length = WorksheetFunction.Match("SHAPE_LENGTH", Rows("1:1"), 0)

'Step 2: #Data transfer process

        Sheets("Control1").Columns(Route_Name).Copy Destination:=Sheets("Data").Range("A7")
        Sheets("Control1").Columns(Feature_Type).Copy Destination:=Sheets("Data").Range("B7")
        Sheets("Control1").Columns(Shape_Length).Copy Destination:=Sheets("Data").Range("T7")

    End With

End Sub

When I run the script, I receive a Run-time error '1004', stating: "You can't paste this here because the Copy area and paste area aren't the same size. Select just one cell in the paste area or an area that's the same size and try pasting again."
The difficulty is, this script has no problem running in Excel/VBA 2010. What problems might exist with this script, or alternatively, are there potential macro security settings limiting this from functioning properly?
I appreciate any help.

A: Always declare your variables:
Dim Route_Name As Long
Dim Feature_Type As Long
Dim Shape_Length As Long

You are not using the With Block you set up.  You need to precede any ranges that use that parent with .
.Rows("1:1")

Use Intersect to only copy the area that is used:
Intersect(.UsedRange, .Columns(Route_Name)).Copy Destination:=Sheets("Data").Range("A7")

So:
Sub RunMacro()

Dim Route_Name As Long
Dim Feature_Type As Long
Dim Shape_Length As Long

'Step 1: #Script searches for header matches in Control1 dataset, then will copy in next
'step to Data list

    With Sheets("Control1")

        Route_Name = WorksheetFunction.Match("ROUTE_NAME", .Rows("1:1"), 0)
        Feature_Type = WorksheetFunction.Match("FEATURE_TYPE", .Rows("1:1"), 0)
        Shape_Length = WorksheetFunction.Match("SHAPE_LENGTH", .Rows("1:1"), 0)

'Step 2: #Data transfer process

        Intersect(.UsedRange, .Columns(Route_Name)).Copy Destination:=Sheets("Data").Range("A7")
        Intersect(.UsedRange, .Columns(Feature_Type)).Copy Destination:=Sheets("Data").Range("B7")
        Intersect(.UsedRange, .Columns(Shape_Length)).Copy Destination:=Sheets("Data").Range("T7")

    End With

End Sub

One more note:
This will fail if any of the lookups do not exist in the the first row.  There are many methods of capturing and dealing with this problem.
I like to use On Error Resume Next with an immediate On Error Goto 0 This will then skip the error on those three lines only.  The Ifs will then only copy if the column was found:
Sub RunMacro()

Dim Route_Name As Long
Dim Feature_Type As Long
Dim Shape_Length As Long

'Step 1: #Script searches for header matches in Control1 dataset, then will copy in next
'step to Data list

    With Sheets("Control1")
        On Error Resume Next
            Route_Name = WorksheetFunction.Match("ROUTE_NAME", .Rows("1:1"), 0)
            Feature_Type = WorksheetFunction.Match("FEATURE_TYPE", .Rows("1:1"), 0)
            Shape_Length = WorksheetFunction.Match("SHAPE_LENGTH", .Rows("1:1"), 0)
        On Error GoTo 0

'Step 2: #Data transfer process

        If Route_Name Then _
            Intersect(.UsedRange, .Columns(Route_Name)).Copy Destination:=Sheets("Data").Range("A7")
        If Feature_Type Then _
            Intersect(.UsedRange, .Columns(Feature_Type)).Copy Destination:=Sheets("Data").Range("B7")
        If Shape_Length Then _
            Intersect(.UsedRange, .Columns(Shape_Length)).Copy Destination:=Sheets("Data").Range("T7")

    End With

End Sub


text:
Q: How to modify context menu of internet explorer using IDocHostUIHandler::ShowContextMenu? I am trying to implement a custom menu for Internet Explorer 7.0. For this i have to use IDocHostUIHandler::ShowContextMenu only. Till now i am able to implement a basic context menu with two options. The problem is that they are disabled by default. The sample code for the same is:
HRESULT CWebEventHandler::ShowContextMenu(DWORD dwID,POINT *ppt, IUnknown *pcmdTarget, IDispatch *pdispObject)
{
    if (false) // I will put some guard code here. as of now do not consider it
        return S_FALSE;      // Show standard context menus.
    else
    {
        IOleWindow* pWnd = NULL;
        HRESULT hr = pcmdTarget->QueryInterface(IID_IOleWindow,
            (void**) &pWnd);

        if (SUCCEEDED(hr))
        {
            HWND hwnd;

            if (SUCCEEDED(pWnd->GetWindow(&hwnd)))
            {
                HMENU menu = ::CreatePopupMenu();
                ::AppendMenu(menu, MF_STRING, ID_HELLO, L"&Hello" ); // ID_HELLO & ID_WORLD are two menu resource items
                ::AppendMenu(menu, MF_STRING, ID_WORLD, L"&World" );

                long myRetVal = ::TrackPopupMenu(menu,
                    TPM_RIGHTBUTTON | TPM_LEFTALIGN | TPM_RETURNCMD,
                    ppt->x, ppt->y, NULL, hwnd, NULL);

                // Send the command to the browser.
                //
                LRESULT myResult = ::SendMessage(hwnd, WM_COMMAND,
                    myRetVal, NULL);
            }

            pWnd->Release();
        }
    }
    return S_OK;
}

Kindly suggest what is wrong with this code & why my menu entries are disabled??
Thanks
EDIT
The same post is available on this link also ( http://social.msdn.microsoft.com/Forums/en/ieextensiondevelopment/thread/13584f76-21bd-4764-b5b7-e81932561574 )

A: I think i have solved the problem. After getting the hwnd object in if (SUCCEEDED(pWnd->GetWindow(&hwnd))) install your own CALLBACK for context menu. In the callback
if ((uMsg == WM_INITMENUPOPUP) && (wParam == (WPARAM) menu)) {
        return 0;
    }

otherwise let the original handler process it.
once done with
long myRetVal = ::TrackPopupMenu(g_hPubMenu,TPM_RIGHTBUTTON | TPM_LEFTALIGN | TPM_RETURNCMD,
                    ppt->x, ppt->y, NULL, hwnd, NULL);

revert back to the original proc handler....
Sample
WNDPROC g_lpPrevWndProc = NULL;

HRESULT CWebEventHandler::ShowContextMenu(DWORD dwID, POINT *ppt, IUnknown *pcmdTarget, IDispatch *pdispObject)
    {

if (false)
        return S_FALSE;      // Show standard context menus.
    else
    {
        IOleWindow* pWnd = NULL;
        HRESULT hr = pcmdTarget->QueryInterface(IID_IOleWindow,
            (void**) &pWnd);

        if (SUCCEEDED(hr))
        {
            HWND hwnd;

            if (SUCCEEDED(pWnd->GetWindow(&hwnd)))
            {
                g_lpPrevWndProc = (WNDPROC)SetWindowLong(hwnd, GWL_WNDPROC, (LONG)CtxMenuWndProc);

                if (g_hPubMenu)
                {
                    DestroyMenu(g_hPubMenu);
                    g_hPubMenu = NULL;
                }
                g_hPubMenu = ::CreatePopupMenu();

                ::AppendMenu(g_hPubMenu, MF_STRING|MF_ENABLED   , ID_HELLO, L"&Hello" );
                ::AppendMenu(g_hPubMenu, MF_STRING|MF_ENABLED   , ID_WORLD, L"&World" );

                long myRetVal = ::TrackPopupMenu(g_hPubMenu,
                    TPM_RIGHTBUTTON | TPM_LEFTALIGN | TPM_RETURNCMD,
                    ppt->x, ppt->y, NULL, hwnd, NULL);

                SetWindowLong(hwnd, GWL_WNDPROC, (LONG)g_lpPrevWndProc);

                // Send the command to the browser.
                //

                if (myRetVal == ID_HELLO)
                {
                    box(_T("Hello"));
                }else if(myRetVal == ID_WORLD)
                {
                    box(_T("World"));
                }else{
                        LRESULT myResult = ::SendMessage(hwnd, WM_COMMAND,myRetVal, NULL);
                }

            }

            pWnd->Release();
        }
    }
    return S_OK;
}

LRESULT CALLBACK CtxMenuWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    if ((uMsg == WM_INITMENUPOPUP) && (wParam == (WPARAM) g_hPubMenu)) {
        return 0;
    }
    return CallWindowProc(g_lpPrevWndProc, hwnd, uMsg, wParam, lParam);
}

A: I'm sure you already figured this out, but in the second sample, you are doing:
::SendMessage(hwnd, WM_COMMAND,myRetVal, NULL);
after reverting:
 SetWindowLong(hwnd, GWL_WNDPROC, (LONG)g_lpPrevWndProc);
Your callback will never get executed on the return 0; path, though, nor was there such a case in this particular sample.


text:
Q: web host returned ERROR_WINHTTP_INVALID_SERVER_RESPONSE I am hosting a website on a webhost for a game. I wanted to test if my webhost could handle the ammount of requests my game would make. So I created a script that would send 500 requests per minute to my website.
It seemed to handle everything perfectly, but after a while de respondse would return ERROR_WINHTTP_INVALID_SERVER_RESPONSE. I googled it, and it ment that the server respondse could not be parsed.
PHP Code:
<?php
$json = file_get_contents("php://input");

$array = json_decode($json, true);

include "../MySQL/connect_to_mysql.php"; //Just an basic mysqli_connect()

$query = mysqli_query($link, "UPDATE playerData SET wins = wins + 1 WHERE PlayerID='".$array['playerID']."'");

echo mysqli_error($link);

mysqli_close($link);

echo $_SERVER['REMOTE_ADDR'];
exit();
?>

The in-game script just sends a HTPP PostAsync to this file, with an array which contains the playerID.
Is this an error in my php code or in my website configuration or in my code in my game? Also, how do I fix that error?


text:
Q: Minimal nonnegative combinations of vectors Fact: Start with $m$ points $u_1,...,u_m\in \mathbb R^n$. Now pick any $u$ in the cone of $u_1,...,u_m$; that is,
$$
u = \sum_{i=1}^m \alpha_i u_i  \text{ for some }  \alpha_i \geq 0, \; i = 1,...,m.
$$
Then it is known that there exists nonnegative coefficients $\beta_1,...,\beta_m$ such that
$$
u = \sum_{i=1}^m \beta_i u_i.
$$
where at most $n$ coefficients $\beta_1,...,\beta_m$ are nonzero.
This fact is used to prove many things, such as Caratheodory's theorem and the Shapley-Folkman lemma. It is sometimes called the "conic Caratheodory's theorem."
I've seen this result in two places, one which says the "proof is in many texts on linear programming" and another which uses Caratheodory's theorem to prove it, which I find circular.
Can someone give me a proof of this fact that doesn't use Caratheodory?
To start, we know that if we drop the nonnegativity constraints on the coefficients, then this is a simple property in linear algebra. Specifically, if $u \in \mathbf{span}(u_1,...,u_m)$ and $m > n$, then $u$ can be written as a linear combination of at most $n$ points in $\{u_1,...,u_m\}$. But it's not obvious to me how to extend this to the ``conic version".


text:
Q: Software to watch changes on web and machine with ability to automaticaly act on them? I am in need of software which can do all of the following:

*

*Monitor:

*

*Web pages

*RSS Feeds

*Files

*Folders

*Ports

*Social Networks (e.g.: FaceBook)

*Processes

*Email (e.g.: POP3, IMAP and GMail)

*Run custom commands when items being watched change

*Alert the user through the built-in notifications system of any changes to watched items

Is there an application which can do all of this? I am running Ubuntu GNOME 16.04 with GNOME 3.20.

A: Specto is just what you are looking for!
Install it with:
sudo apt-get install specto

Description:
Unobtrusive update notification program
 Specto is a desktop application that will watch any user-specified events
 (web, folder, ...). This will allow users, for instance, to specify a website
 to watch, and Specto will automatically check for updates on the web page. It
 will then notify the user when there is activity. This will allow the user to
 be informed of new updates/events instead of having to look out for them.

Screenshots:


text:
Q: In a chair at a club, what does it mean if somebody "wheels up their chair"? From a short story by Algernon Blackwood, titled If the Cap Fits (public domain PDF),

Field-Martin, the naturalist, sat in his corner armchair at the Club [...]
[...]. Field-Martin wheeled up his chair
with vigorous strokes of his heels and joined the
group [...]

The description is from the early decades of the 20th century. Does it mean to raise/erect the chair, as opposed to reclining? I assume there were chairs operated by heels?

A: Items of furniture, including heavy padded armchairs and sofas, often have what are called 'castors'. One person could wheel or roll such a chair to move it, e.g. when cleaning, making the room tidy, or to re-position it. They help avoid damage to carpets or floors. It would be possible to move a chair while sitting, as described. The text is from the short story "If the Cap Fits" by Algernon Blackwood.

A: It means he moved his chair along the ground towards the group; he must be in a wheelchair or another kind of chair that has wheels. Hence he was able to "wheel" it up to join the group. He was moving the chair using the heels of his feet as a source of propulsion.


text:
Q: How to enable an Event Handler to intercept upload from email in document library I have a Document Library with an email associated with the OOTB feature. When I send to the library an email with some attachments, every attachment is stored with one of the OOTB methods (divided in folder by sender).
I need to do some operation whenever a new file is added so I tryed to add an event handler. I tried every method but:

*

*When I upload a file from the SharePoint UI the event handler is triggered

*When I upload a file by e-mail it is not

Is there any way to do that?
Thank you very much!

A: There are custom events for incoming emails, have you looked for "Email events"? If you add such Event Receiver you might have to handle the item correctly as well, or else it will not be inserted properly.
Like this:
public class OnEmail : SPEmailEventReceiver
{

   public override void EmailReceived(SPList list, SPEmailMessage emailMessage, String receiverData)
   {
       base.EmailReceived(list, emailMessage, receiverData);

       var item = list.AddItem();
       item["Title"] = emailMessage.Headers["Subject"];
       item["EmailSubject"] = emailMessage.Headers["Subject"];
       item["EmailFrom"] = emailMessage.Headers["From"];
       item["EmailHeaders"] = emailMessage.Headers;
       item["EmailSender"] = emailMessage.Headers["x-sender"];
       item["EmailTo"] = emailMessage.Headers["To"];
       item["Body"] = emailMessage.HtmlBody;
       emailMessage.Attachments.Cast<SPEmailAttachment>().ToList().ForEach(attachment =>
       {
           var array = new byte[attachment.ContentStream.Length];
           attachment.ContentStream.Read(array, 0, (int)attachment.ContentStream.Length);
           item.Attachments.Add(attachment.FileName, array);
       });
       item.Update();
   }
}


text:
Q: Sharing VBA Modules across Workbooks I have a number of workbooks. Each workbook contains a number of spreadsheets, and all workbooks are exactly the same, except for the data they carry. Each workbook has a number of VBA modules, and when I make changes to one module, I then need to push the same changes to all other modules to all other workbooks.
Is there a way to share the VBA modules across all of my Workbooks, so I can make changes only in one place?

A: Move the code into a separate Excel workbook and save it as .xlam (Excel macro-enabled add-in).
Reference the add-in from all the other files' Tools - References (click Browse, change the file type to "Microsoft Excel files" and navigate to the xlam file).
Go through the code and make sure it is written correctly and properly references workbooks and worksheets. E.g. ThisWorkbook will now refer to the add-in workbook, not to the document calling it.

A: I got an amateur fix for this kind of stuff. At my office, there are like 15 persons who share some utilities and UDFS on EXCEL. We had to change 15 Excel Workbooks when the code had to be revised or improved. Waste of time

First of all, I must say that for this solution to work, all users
needs to share a folder where you can put a shared workbook for
everyone to access. If users cannot share anything, then this solution
won't work.

We found an easy solution for us. I'm pretty sure there is, indeed, a better way to do this, and more elegant, but this works for us for the last 10 years and we've had enough.
We created a MASTER WORKBOOK with all subs and functions we needed. I'll make a quick example. This master workbook is named MASTER_WB (title of VBAProject is also MASTER_WB)

This MASTER_WB would hold all your utilities and common codes. As you can see in the image, I typed 1 sub and 1 UDF really simple (as Public, to be called from anywhere).
Also, I strongly recommend to use MW initials in every sub/Function you type in MASTER_WB. That way you make 100% sure there is no conflict of names between USER_WB and MASTER_WB calling same procedure. This is just a personal fixation.
In this MASTER_WB, the relevant code is in the workbook object:
Option Explicit

Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.Saved = True
End Sub

Private Sub Workbook_Open()
If Application.Workbooks.Count > 2 Then '2 BECAUSE I got also PERSONAL MACRO WORKBOOK
    ThisWorkbook.IsAddin = True
Else
    ThisWorkbook.IsAddin = False
End If
End Sub

Now we save and close MASTER_WB and then in every USER_WB in a module we add the newly created MASTER_WB as a reference:

Notice that in every USER_WB we also type codes to call those public subs and UDF we created in MASTER_WB:
Option Explicit

Sub ESTE_LIBRO()
Call MASTER_UTILITIES.MW_ESTE_LIBRO(ThisWorkbook)
End Sub

Function PORTRES(vRNG As Range) As Double
PORTRES = MASTER_UTILITIES.MW_PORTRES(vRNG)
End Function

And that would be all! Now every USER_WB can access the UDF and subs stored in MASTER_WB. And when we need to make an update/change, we just update MASTER_WB.
If we create a new UDF/SUB, then yes, it needs to be created in both workbooks. MASTER_WB would hold the code itself and every USER_WB needs to add in their modules something like:
Sub MY_NEW_SUB()
Call MASTER_UTILITIES.MY_NEW_SUB
End Sub

Also, if parameters/arguments of a sub/udf change, yes, you also need to update every USER_WB.
But believe me when I say is worth it, at least in our office, because those cases are uncommon. The most usual one is just improving/adding new line of codes, so updating MASTER_WB will make the new code available for all USER_WB connected, without doing it 15 times.
As I said in first line. this solution is not the most elegant one, and for sure there is a better one, but I can tell it works for us. I would like to learn some day about developing add-ins, but for now, we use this amateur fix.
Hope you can adapt this to your needs.


text:
Q: Redirect .html request from Apache server to Tomcat server Our web server is a combination of Apache http server and Tomcat server. When ever any request comes, first it will handled by Apache server.If it is type of .html or .htm or .log etc., then the Apache server will process it. If the request is type of .jsp, Apache will pass the request to Tomcat server and Tomcat server will process the request.
I deployed a java web application in Tomcat which having some servelt mapping for .html and .log. Since the Apache http server having the configuration to handle .html, the given request is not passed to Tomcat server.
I checked with our Admin, they confirmed me that, i can create a .htaccess file in the root directory, which having the configuration to ignore or redirect the .html request from being handled by Apache http server.
Is any one know what is the command/configuration i need to add in the .htaccess file ?

A: I'm guessing you use mod_jk: take a look here http://tomcat.apache.org/tomcat-3.3-doc/mod_jk-howto.html#s73 to forward requests to your tomcat instance.

A: mod_jk is the one to use for this purpose.
You can also use Apache mod_proxy. Read the Warning at the beginning of the page carefully.
http://httpd.apache.org/docs/2.2/mod/mod_proxy.html


text:
Q: How do I view the built-in definition of TemplateBox styles in terms of low level boxes? The following:
TemplateBox[{"a", "b"}, "Binomial"] // RawBoxes

yields the correctly formatted (2d box structure) of Binomial[a,b]:
$$\begin{pmatrix}a\\b\end{pmatrix}$$
But I would like to see its (and other built-in functions') explicit definition in terms of low level boxes.  Presumably, the definition of the style "Binomial" lives somewhere.  Where is it?

A: They live in stylesheets:
CurrentValue[{StyleDefinitions, "Binomial"}]

{TemplateBoxOptions -> {DisplayFunction -> (RowBox[{"(",
    GridBox[{{#1}, {#2}}], ")"}] &), Tooltip -> Automatic}}


text:
Q: infimum of the Calabi energy in a given Kahler class Given a compact Kahler manifold $M^n$ and a Kahler class $\Omega$. We have the Calabi energy (or Calabi functional)
$$\textrm{Ca}(\omega)=\int_Ms^2(\omega)\omega^n,\qquad \forall \omega\in\Omega.$$
Here $s(\omega)$ is the scalar curvature with respect to the metric $\omega$. My question is whether or not there is an explict expression of
$$\textrm{inf}_{\omega\in\Omega}\textrm{Ca}(\omega).$$
Here by "explicit" I mean that if it can be expressed in terms of some well-known or familar quantities in Kahler geometry.
According to my best knowledge, A.D. Hwang and Xiuxiong Chen have a result that $\textrm{Ca}(\omega)$ has a lower bound in terms of the Calabi-Futaki functional evaluted at the extremal vector field and the equality holds iff there exists an extremal metric in $\Omega$. So according to their result, $\textrm{inf}_{\omega\in\Omega}\textrm{Ca}(\omega)$ also has this as its lower bound.

A: If $\Omega$ is a rational Kähler class, so $M$ is projective algebraic, then Donaldson was the first to prove the Chen-Hwang lower bound that you stated. In fact, in this case he proved more, namely that
$$\inf_{\omega\in\Omega}\mathrm{Ca}(\omega)\geq \sup_{\mathfrak{X}}\Psi(\mathfrak{X}),$$ where $\mathfrak{X}$ is any test configuration for $(M,\Omega)$, and $\Psi(\mathfrak{X})$ is a suitable normalization of the Futaki invariant of $\mathfrak{X}$ (see the paper of Donaldson for definitions). The point is that if $(M,\Omega)$ is K-unstable, then the supremum is strictly positive (by definition), and so you conclude that there is no constant scalar curvature Kähler metric in the class $\Omega$.
In the same paper (p.455) Donaldson conjectures that equality above should always hold. This would be the sharp lower bound that you are looking for, and it is still open in general. Very recently, as a consequence of work of Chen, Donaldson, Sun, Tian and Li, it was shown that equality holds when $M$ is Fano, $\Omega$ is the anticanonical class, and $(M,\Omega)$ is K-stable or K-semistable (i.e. the case when the supremum on the RHS is zero).
Therefore there is no general "simple" formula for the lower bound of the Calabi energy, and this is related to the difficult open problem of relating existence of constant scalar curvature Kähler to algebro-geometric stability. See for example these surveys for more on this problem.
By the way, Donaldson's inequality was inspired by a similar identity proved by Atiyah-Bott for holomorphic vector bundles on algebraic curves, with the infimum of the Calabi energy replaced by the infimum of the $L^2$ norm of the curvature of all compatible unitary connections. This identity was recently extended by A.Jacob to all holomorphic vector bundles on compact Kähler manifolds.


text:
Q: How do I count which function requests what number of bytes? I have a complex code base in C++. I have run a memory profiler that counts the number of bytes allocated by malloc, this gives me X bytes. Theoretically, my code should return X-Y bytes (Y varies with the input, and ranges from a few KB to a couple of GB, so this is not negligible.)
I need to find out which part of my code is asking for the extra bytes. I've tried a few tools, but to no avail: massif, perf, I've even tried gdb breaking on malloc(). I could probably write a wrapper for malloc asking to provide the calling function, but I don't know how to do that.
Does anyone know a way to find how much memory different parts of the program are asking for?

A: If you use a custom allocate function - a wrapper around malloc - you can use the gcc backtrace functions (http://man7.org/linux/man-pages/man3/backtrace.3.html) to find out which functions call malloc with what arguments.
That'll tell you the functions which are allocating. From there you can probably sort the biggies into domains by hand.
This question has good info on the wrapping itself. Create a wrapper function for malloc and free in C
Update:
This won't catch new/delete allocations but overriding them is even easier than malloc! See here: How to properly replace global new & delete operators + the very important comment on the best answer "Don't forget the other 3 versions: new[], delete[], nothrow"

A: You can make a macro that calls the libc malloc and prints the details of the allocation.
#define malloc( sz ) (\
{\
    printf( "Allocating %d Bytes, File %s:%d\n", sz, __FILE__, __LINE__ );\
    void *(*libc_malloc)(size_t) = dlsym(RTLD_NEXT, "malloc");\
    printf("malloc\n");\
    void* mem = libc_malloc(sz);\
    mem; // GCC-specific statement-expression \
}

This should ( touch wood ) get called in lieu of the real malloc and spit out the number of bytes allocated and where the allocation occurred. Returning mem like this is GCC-specific though.


text:
Q: Pull tweet upon provided tweet URL I am trying to develop a CCK module, this module basically provides a field that handles a tweet URL.
On node save, Drupal will pull this tweet's text depending on the tweet URL i submitted and display it formatted.
Does Twitter API provide any function that handles this type of requests ?
Thanks

A: Yes, you can get the contents of a tweet.
http://dev.twitter.com/doc/get/statuses/show/:id

A: Ok, i figured a way out to integrate this with CCK in Drupal
http://batayneh.me/post/how-pull-tweet-pasting-its-url-drupal-cck


text:
Q: Web-ifing a python command line script? This is my first questions here, so I hope it will be done correctly ;)
I've been assigned the task to give a web interface to some "home made" python script.
This script is used to check some web sites/applications availability, via curl commands. A very important aspect of this script is that it gives its results in real-time, writing line by line to the standard output.
By giving a web interface to this script, the main goal is that the script can be easily used from anywhere, for example via a smartphone. So the web interface must be quite basic, and work "plugin-free".
My problem is that most solutions I thought or found on the web (ajax, django, even a simple post) seem to be needing a full generation of the page before sending it to the browser, losing this important "real-time" aspect.
Any idea on how to do this properly ?
Thanks in advance.

A: A sketch for a solution:
Create an HTML file which contains the layout for your web page, with a dedicated DIV for the output of the script:


text:
Q: Trying to login into webpage with cookies and requests I am trying to log in into a website called www.zalando.fr with requests in python (i don't want to use selenium) I tried to send a post request with my login credentials, but I didn't find out which request do i have to send (i am not very experienced with requests and any of the post requests seems like having my credentials) and i heard that you can login by using the same cookies as the ones in your already started session, so i tried the following:
#-*-coding: utf-8-*-
from requests import Session
from requests.utils import cookiejar_from_dict
from codecs import open

def main():
    cookies = '''plain text cookies i got by doing document.cookie after logging in'''
    s = Session()
    cookie_dict = {}
    for cookie in cookies.split(";"):
       cookie =  cookie.split("=")
       cookie_dict[cookie[0]] = cookie[1]
    cj = cookiejar_from_dict(cookie_dict)
    print("Cookie jar to dict done...")
    s.cookies = cj
    headers = {
        "User-Agent": "Mozilla/5.0"
    }
    print("Requesting")
    html = s.get("https://www.zalando.fr/myaccount/", headers=headers)
    print("request done")

    html = s.get("https://www.zalando.fr/myaccount/", headers=headers)
    print("request done")
    if "My name" in html.text:
        print('Good')
    else:
        print("Bad")
    with open("response.html", "w", encoding="utf-8") as f:
        f.write(html.text)
    s.close()

if __name__ == '__main__':
    main()

The if at the end checks if my name is in the page, because there is a message that says "Bonjour User" when you log in, but it always seems like it is not logged in.
and when i open response.html it shows the login page, what am i doing wrong?

A: Cookies are not directly visible to client-side programs such as JavaScript if they have been sent with the HttpOnly flag. So with document.cookie you are not getting any authentication cookies.
Go developer tools under Application -> Storage -> Cookies you will find all the cookies.


text:
Q: Master List of abbreviations using a .bib or .aux file I know there are many questions about the list of symbols and abbreviations already posted but I can not find one that solves my problem directly. I found one answer (https://tex.stackexchange.com/a/366282/211159)(method 4) which relates to my question but it requires loading external files. I am using Overleaf as my tex editor so I am not entirely sure how to do that.
I am thinking of either using the glossaries acro or nomencl packages. I think nomencl is the most straightforward.
What I want:

*

*To define all my symbols and/or abbreviations in a .aux or .bib master file (can be a separate file for symbols and one for abbreviations if necessary)

*When I type in my document and use for example \ac{NY} the abbreviation 'NY' appears in my text and the entry is taken from the .bib or .aux file and added to the List of Abbreviations.

*Use the code \input{ListofSymb} where I want the list to appear.

I do something similar with my preamble and my bibliography, whereby I have a master list that I have for all my projects and I just recall the files using \input.
MWE:
Preamble:
\usepackage{glossaries}

Main file
\documentclass [a4paper,12pt]{report}

\input{1.mypreamble}

\begin{document}

\input{ListofSymb}

This is a test paragraph where I will use some of the entries in the "ListofSymb" file. The entries I use are the only one I want to appear in the printed List of Symbols i.e. Not all symbols in the master list must appear the List of Symbols. I want symbols; $\gls{a}$, $\gls{t}$ and
$\gls{F}$ to appear. Additionally, they should appear in alphabetical order.

\end{document}

ListofSymb
@entry{x,
 name={\ensuremath{x}},
 description={position}
}
@entry{v,
 name={\ensuremath{v}},
 description={velocity}
}
@entry{a,
 name={\ensuremath{a}},
 description={acceleration}
}
@entry{t,
 name={\ensuremath{t}},
 description={time}
}
@entry{F,
 name={\ensuremath{F}},
 description={force}
}

Output:

I'm not sure if the packages and code used in this example is correct but its the closest I could get. I have taken examples from many different answers so it may be slightly jumbled.

A: After some searching I found a suitable answer. It is not exactly what I was hoping for in terms of a master list but I am happy with the results I have for now, so I am posting this answer for anyone that has the same problems.
I made use of the standalone package along with the nomenclpackage.
I added the following to my preamble:
\usepackage{standalone}
\usepackage{nomencl}
\makenomenclature

\renewcommand{\nomname}{List of Abbreviations and Symbols}

\renewcommand{\nomgroup}[1]{\bigskip
\ifthenelse{\equal{#1}{S}}{\item[\textbf{\large{Symbols}}]}{%
\ifthenelse{\equal{#1}{A}}{\item[\textbf{\large{Abbreviations}}]}{}}}

Then I created a .tex file called abb.tex with following code:
\documentclass[preview]{standalone}
\usepackage{nomencl}
\makenomenclature
\renewcommand{\nomname}{List of Abbreviations and Symbols}

\renewcommand{\nomgroup}[1]{\bigskip
\ifthenelse{\equal{#1}{S}}{\item[\textbf{\large{Symbols}}]}{%
\ifthenelse{\equal{#1}{A}}{\item[\textbf{\large{Abbreviations}}]}{}}}

\begin{document}
\printnomenclature[3cm]
\nomenclature[A]{ABAQUS/CAE}{Complete Abaqus Environment}
\nomenclature[A]{ASTM}{American Society for Testing and Materials}
\nomenclature[A]{CDM}{Continuum Damage Mechanics}
\nomenclature[A]{CLT}{Cross-Laminated Timber}
\nomenclature[A]{FRP}{Fibre Reinforced Polymer}
\nomenclature[A]{FEM}{Finite Element Modelling}
\nomenclature[A]{FEA}{Finite Element Analysis}
\nomenclature[A]{Glulam}{Glue-Laminated Timber}
\nomenclature[A]{MoR}{Modulus of Rupture}
\nomenclature[A]{MoE}{Modulus of Elasticity}
\nomenclature[A]{NDT}{Non-destructive Tests}
\nomenclature[A]{SA}{South Africa(n)}
\nomenclature[A]{UMAT}{User-defined material model}
\nomenclature[A]{USDFLD}{User-defined field}
\nomenclature[S]{$G$}{Modulus of Rigidity}
\nomenclature[S]{$I_k$}{Moment of inertia of all knots within 15cm of the critical cross section}
\nomenclature[S]{$I_g$}{Gross moment of inertia}

\end{document}

The {standalone} and [preview] allow the abb.tex file to be compiled on its own and then when using an \input{abb} command in the main text file the preamble of the abb.tex file is ignored and does not clash with the existing preamble in the main document.
Therefore my main document MWE is as follows:
\documentclass [a4paper,12pt]{report}
\input{1.mypreamble}
\begin{document}

Some text

\newpage
\input{abb}
\newpage

Some text

\end{document}


text:
Q: Always get printed value of "None" Alright so here is my code, I get the result I want but I keep getting the "None" value under it. How do I eliminate the "None" value?
n = input("What day of the week are you leaving?")
r = input("How many days will you be resting?")

def days(n):
    if n == 0:
        print "Sunday"
    elif n == 1:
        print "Monday"
    elif n == 2:
        print "Tuesday"
    elif n == 3:
        print "Wednesday"
    elif n == 4:
        print "Thrusday"
    elif n == 5:
        print "Friday"
    elif n == 6:
        print "Saturday"
    elif n >= 7:
        print days(n%7)

print days(n+r)

A: This should do the trick:
days = ["Sunday", "Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday", "Saturday"]
print days[(n+r) % 7]

A: days never returns anything, so it implicitly returns None. Change all of the print statements in days to return statements:
def days(n):
    if n == 0:
        return "Sunday"
    elif n == 1:
        return "Monday"
    elif n == 2:
        return "Tuesday"
    elif n == 3:
        return "Wednesday"
    elif n == 4:
        return "Thrusday"
    elif n == 5:
        return "Friday"
    elif n == 6:
        return "Saturday"
    elif n >= 7:
        return days(n % 7)

A: Change all the print statements in your days(n) function to return instead.

A: You print in function days and print result from function days.
Because of function days returns nothing it prints None.


text:
Q: Not able to move to next line when enter is hit in textarea I'm stuck here with the problem of not able to move to next line when I hit enter in a text area
This is the code I've used for text area:
<apex:inputTextarea id="Ascp"  rows="5" value="{!mNC.newCase.desc}"
styleClass="form-control right-section pull-none" html-placeholder="
{!$Label.test_label}"/>

Please help!


text:
Q: Как посчитать количество checked checkbox в form у которых value=5 Как посчитать количество checked checkbox у input в form по value=5 а также отдельно у которых value=-2?

A: console.log(document.querySelectorAll("input[type='checkbox'][value='5']:checked").length);


text:
Q: Set Column Attribute to be Date and Time I am working on MySql and I have to set the time-stamp of the one of the field of my column to be 4 days ahead from current time-stamp. I created the triggers for the same.
My timestamp fields are Insert_Time and Bid_Time with Default value set as Current_Timestamp.
My Trigger Query:
CREATE TRIGGER setDefaultDate BEFORE INSERT ON product FOR EACH ROW SET New.Bid_Time = ADDDATE(curdate(), INTERVAL 4 DAY);

I tried inserting the rows into table but trigger seems not working. In both the fields I can see the current timestamp only.
My Insert Query:
insert into test.product (ITEM_NAME,ITEM_DESC,Item_Price, ITEM_QTY,SELLER_FIRSTNAME, SELLER_LASTNAME,EMAIL,SELLER_USERNAME,CATEGORY,GROUP_NAME,Bid,COND ) values ('J.K Rowling','HARRYPOTTER AND MYSTERY ','60','10','sahil','kaw', 'sahil1.kaw@gmail.com', 'sahraw','BOOKS','FICTION','1','NEW');

Is it because I am not providing the timestamp value while inserting.
Please find the screen-print attached for the schema of the tables.

A: This is mostly speculation, but I'm pretty sure the problem is the fact that bid_time has a default value of timestamp.  Such columns are automatically initialized.
Unfortunately, the copious documentation on the subject does not seem to address triggers.  However, I could easily imagine that the automatic value over-rides the trigger.


text:
Q: EMC VNX iSCSI setup - unsure about SP/port assignment We have a new VNX5300 waiting to get configured, and I need to plan out the network infrastructure before the EMC tech arrives. It has 4x1gbit iSCSI per SP (8 ports in total), and I'd like to get the most out of the performance until we jump over to 10gig iSCSI.
From what I can read from the docs - the recommendation is to use only two ports per SP, with 1 active and 1 passive. Why is this? It seems kind of pointless to have quad-port i/o-modules and then recommend to not use more than two of them?
Also - I'm a bit unsure about the zoning. The best practices guide state that you should separate each port on each SP from each other on different logical networks. Does this mean that I have to create 4 logical networks to be able to use all 8 ports?
It also gives the following example:

Does this mean that A0 and B0 should sit on the same physical switch aswell? Won't this make all traffic go on one switch (if both A1 and B1 are passive)?
Edit: Another brainpuzzle

I don't  get it - each host (as in server) should not have more iSCSI bandwidth available than the storage processor. What on earth does this matter? If serverA have 1gbit and serverB have 100mbit, then the resulting bandwith between them is 100mbit. How can this result in some kind of oversubscription?
Edit4: Wait, what. Active and passive ports? The VNX runs in a ALUA configuration with asymmetrical active/active.. there shouldn't be any passive ports, only preferred ones..

A: What EMC's documents seem to be discussing is to have two separate IP broadcast domains - two separate fabrics on separate hardware, so that a misconfig in a given switch or a switching loop or somesuch doesn't bring down all storage connectivity.
Along these lines:

I personally think it's a little nuts to keep creating additional fabrics for each port per SP, though - I'd say just split them up evenly among the storage fabrics; SP A's other two ports would be 10.168.10.9 for the one plugged to fabric 1, and 10.168.11.9 for the one plugged to fabric 2.
The client's multipathing should be the one handling all load balancing and failover.  And how the heck are you supposed to put a client with two HBAs into 4 vlans, anyway?  They can handle two targets visible from a given initiator just fine.
(no idea on the "oversubscription" thing.)

A: No, no.  We want all 8 ports on the same subnet.  You never want iSCSI traffic to cross subnets.  It'll just slow down while going through the routers.  You want both SPs connected to each switch.  E0,E2 should be connected to Switch0 and E1,E3 should be connected to Switch1.
Not sure what you are seeing in the Edit2 screenshot that makes you want to rape your sales person with a watermelon (can I watch while you do this)?  Slots and ports are different.
You'll want to install PowerPath (software package to purchase) so that you get the best possible MPIO setup.

A: It seems that the best answer would be two separate networks, a la fibre, and they don't route to each other. Put them all on, possibly 2 active, two passive if that is a config requirement, otherwise all on ALUA if possible.


text:
Q: How to stop download of a single image I'm creating an application where the user selects one item from a recycler view and this starts the download of a group of images.
I'm using universal image loader's loadImage method to fetch images for me which is working very well.
The problem is,if the user wants to cancel downloading this group of images (can be very network consuming) I cannot find a way to make ui stop only some of the images.
I'm aware of the method ImageLoader.cancelDisplayTask(), but as I'm using loadImage I have no ImageView or ImageAware available to send as a parameter to this task.
Also ImageLoader.stop() or ImageLoader.pause() stops all current downloads and I want to stop only the ones selected by the user.
How can I achieve this?
PS: A suggestion to some future development would be returning a pointer of the download task when using loadImage method. Maybe I'll look it myself when I have some time to contribute to this awesome library.
Here's my code for downloading an image.
private void downloadFile(final URL downloadURL,
                          final URL destinationURL,
                          final boolean isThumbnail,
                          final MyDownloadListener listener) {
    final NewsData thisClass = this;
    final ImageLoader il = ImageLoader.getInstance();

    File imageFile = il.getDiskCache().get(destinationURL.toString());
    if (imageFile.exists()) {
        fallDownloadCompleted(this, isThumbnail);
        return;
    }
    il.stop();
    il.loadImage(
            downloadURL.toString(),
            null,
            Application.getAppDisplayOptions(),
            new SimpleImageLoadingListener() {
                @Override
                public void onLoadingStarted(String imageUri, View view) {
                    if (listener != null) {
                        listener.onLoadingStarted(thisClass);
                    }
                }

                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                    fallDownloadFail(thisClass, failReason, isThumbnail);
                }

                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    try {
                        il.getDiskCache().save(destinationURL.toString(), loadedImage);
                        if (isToday()) deleteImageFile(imageUri);
                    } catch (IOException e) {
                        deleteImageFile(imageUri);
                        fallDownloadFail(
                                thisClass,
                                new FailReason(FailReason.FailType.IO_ERROR, new Throwable()),
                                isThumbnail);
                        return;
                    }

                    fallDownloadCompleted(thisClass, isThumbnail);
                }
            },
            new ImageLoadingProgressListener() {
                @Override
                public void onProgressUpdate(String imageUri, View view, int current, int total) {
                    float progress = 0;
                    if (total > 0 && numberOfTotalPages > 0) {
                        if (!isThumbnail) {

                            progress = numberOfAvailablePages / (float) numberOfTotalPages;
                            progress += (current / (float) total) / numberOfTotalPages;

                        } else {
                            progress = current / (float) total;
                        }
                    }
                    if (listener != null) {
                        listener.onProgressUpdate(thisClass, progress);

                    }
                }
            });
}

A: private ArrayList<ImageLoader> images = new ArrayList<ImageLoader>();

images.remove():

? Not familiar with ImageLoader class but I hope this helps
These might help
android: Universal Image Loader get drawable from string array
How to change array list to string array for using Universal Image Loader?
https://github.com/nostra13/Android-Universal-Image-Loader/issues/109

A: I managed to solve this issue with a small workaround.
I couldn't find a way to cancel a particular ImageLoader.loadImage() so what I had to do was use the normal ImageLoader.displayImage() by passing a NonViewAware class in place of the image view required as a parameter.
I then added this NonViewAware into an ArrayList<NonViewAware> to keep track of which images were being downloaded.
Finally when I wanted to cancel a display task I just called ImageLoader.cancelDisplayTask(NonViewAware) with one of the stored items from the list.


text:
Q: ImportError : No module named _sqlite3 on GAE While trying to start local Google App Engine (v1.3.8) Server on my Fedora 14 with Python 2.5 (installed from source) I get the importerror
ImportError: No module named _sqlite3

I have the following package installed - sqlite, sqlite-devel, python2.5, python2.7. I did some Google and it looks like this error comes when there is no C binding for sqlite. However, since I have both the sqlite and sqlite-devel installed C bindings should be present. I get this same error when I do
import sqlite3

on Python console. What possibly can I do to resolve this error?

A: Install sqlite-devel and rebuild Python.

A: This works equally on Ubuntu 10.10 using

$ sudo aptitude install sqlite3 libsqlite3-dev

and rebuilding Python.


text:
Q: How can I call host from docker container? I am running Keycloak in docker container and would like to call to sed valid url redirect to my localhost (application is not running in container). This is my docker-compose:
version: '3.3'
services:
  todoDB:
    image: mysql:5.7
    restart: always
    environment:
      MYSQL_DATABASE: 'todo'
      MYSQL_USER: 'application'
      # You can use whatever password you like
      MYSQL_PASSWORD: 'password'
      # Password for root access
      MYSQL_ROOT_PASSWORD: 'password'
    ports:
      # <Port exposed> : < MySQL Port running inside container>
      - '3306:3306'
    expose:
      # Opens port 3306 on the container
      - '3306'
      # Where our data will be persisted

  keycloak:
    depends_on:
      - todoDB
    container_name: local_keycloak
    restart: unless-stopped
    environment:
      DB_VENDOR: mysql
      DB_ADDR: todoDB
      DB_PORT: 3306
      DB_DATABASE: 'todo'
      DB_USER: 'application'
      DB_PASSWORD: 'password'
      KEYCLOAK_USER: 'admin'
      KEYCLOAK_PASSWORD: 'admin'
    image: jboss/keycloak:13.0.0

    ports:
      # <Port exposed> : < MySQL Port running inside container>
      - '28080:8080'
    expose:
      # Opens port 3306 on the container
      - '8080'
      # Where our data will be persisted
    volumes:
      - my-db:/var/lib/mysql
      - ./lab-keycloak:/data
    links:
      - todoDB
    extra_hosts:
      - "host.docker.internal:host-gateway"

volumes:
  my-db:

After validation Keycloak should call http://host.docker.internal:9090/dasboard/* but I get an error Invalid parameter: redirect_uri.
What did I do wrong?

A: I solved it with wildcard * as redirect URL.


text:
Q: android one signal duplicate notification I use One signal for a few days I was actually doing data push since I do not necessarily create notifications at all. But for a few hours when I send a notification I get two.
I have implemented only the service that extends NotificationExtenderService and redefined the onNotificationProcessing method, although I do not put any code to create a notification once I send one from my back office the notification still creates.
Thank you in advance for your answers and sorry for my English


text:
Q: Netty 4.0 channel.id() returns negative integer? When trying to log the channel ID for debugging purposes:
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    // TODO: Investigate negative id
    LOGGER.info("Established Connection with = {}, Channel Id = {}", ctx
            .channel().remoteAddress(), ctx.channel().id());
}

I got the following:
2013-06-08 22:12:49,468 [nioEventLoopGroup-2-1] INFO  com.zeedoo.mars.server.HandshakeHandler - Established Connection with = /127.0.0.1:59236, Channel Id = -1228118933

And pretty much all other channel ids I got are negative also, I'm just wondering if this is an intended behavior? And if so, what's the rationale behind it?
Thanks a lot!

A: It is intentional. AbstractChannel either allocates a unique negative id, or accepts a user-specifed positive unique id. The ID ranges are separated to avoid duplicate conflicts.


text:
Q: What do alternating plus and minus operators do? For some reason, this program compiles in C:
int x;
x = 3+-+-5+-5;
printf("%d\n",x);

And in general, alternating "+" and "-" compiles. It seems like if there are odd "-" then it'll subtract, otherwise, add.
What in the world is this?

A: In cases such as these, the first + or - to the right of the left-hand operand indicates the binary operation to perform; the other + and - after that are the unary + and - operators applied to the right-hand operand. The unary + operand does nothing and - changes the sign. This gives rise to the behavior you see: an odd number of - is either addition of a negative quantity (+ followed by +s and an odd number of -s) or subtraction of a positive quantity (- followed by +s and an even number of -s).


text:
Q: How to get the returned value of a function called from settimeout I have live agent set up and I am trying to set an alert on the agent side when a customer does not reply to his messages after a certain interval of time
Here is how I am trying to achieve (All these are in the js helper,being delegated from the js controller)

*

*Declared A global variable globalvariable1 which keeps track of its changed value

*Used an onAgentMessageSend component which fires when an Agent chats
onAgentMessageSend : function(cmp,recordId,content,name,type,timestamp){
    if(type=='Agent')
       {
           var self = this;
           setTimeout(function() {
           var returnedType=self.checkMessageSenderAndResetCounter(cmp);
          }, 5000);

           if(returnedType=='Default Value')
           {alert('Unresponsive Customer');}
           else{
           console.log('customer responded hence reset');
           globalvariable1= 'Default Value'}}
           else{
            console.log('Do nothing');}},

*A function to change the global value as and when coming from Agent or Customer

 checkMessageSenderAndResetCounter: function(cmp) {

     console.log('the current value of globalvarable'+this.globalvariable1);
     return this.globalvariable1;},

*A method which is fired when a customer messages
onNewMessageFromEndUser : function(cmp,recordId,content,name,type,timestamp){
  this.globalvariable1='Customer';},

Summing up, what I am trying to achieve here is once the agent chats, a timer is set for lets say 5 seconds. Within that time frame if a customer replies, the global variable changes and it continues. In case there is no reply from the customer's end, the global variable is still a default value, then it raises an alert indicating that there is an unanswered question.
But the result from the Settimeout is not achievable, could you please help out here for any other way to achieve this, or rectify this itself?

A: You need to perform your logic either inside setTimeout or create a function and call it inside timeout.
if(type=='Agent')
   {
       var self = this;
       setTimeout(() => {
       var returnedType=self.checkMessageSenderAndResetCounter(cmp);

       // perform rest of your logic inside
       if(returnedType=='Default Value') {
           alert('Unresponsive Customer');
       else{
           console.log('customer responded hence reset');
           globalvariable1= 'Default Value';
        }

      }, 5000);
},


text:
Q: New Graphics Card Preventing Boot Up I have a pretty strange problem here and I would appreciate your help. I recently bought a new graphics card (MSi R9 390 8GB) and a new case as part of an ongoing upgrade to my existing, fairly ancient PC. I transferred all existing components to the new case and it works just fine - that is with all the components as they were in the old case.
When the new graphics card is inserted in place of the old one, I get an error message before I can even load the BIOS; "A bootable device has not been detected" and then a URL for Intel motherboard support. I don't think the GPU is faulty, because I am still getting an image on the screen. So what could it be? Could it be that the motherboard is simply too ancient for this GPU? Am I connecting power to the GPU incorrectly?
Things I have tried, among others:

*

*Resetting CMOS.

*Using Guru3D to make sure old drivers are deleted.

*Checked every connector - the computer works exactly as it should with the old GPU in place.

*Reseated the RAM.

*Updated motherboard BIOS to latest version.

*Checked every setting of new BIOS, PCI-E slot is selected, boot drives are in right order.

*Attempted to boot in safe mode.

*Disconnected and reconnected every drive between attempting to boot.

PC current specifications:

*

*Intel DP35DP Motherboard

*Intel Core 2 Duo 2.66GHz CPU

*Samsung SSD + 2x HDD Drives

*4GB RAM

*Msi R9 390 8GB GPU (new)

*Msi GeForce 630 GPU (old - working)

*750W PSU (within range for GPU and only a couple of weeks old)

*Windows 10 Pro 64bit (no install disc available)

A: I managed to solve the issue, so I am posting for anyone who might have the same problem.
Despite PCI-E being backwards compatible, there was an issue with my particular model of motherboard (Intel DP35DP) making it incompatible with the graphics card, even after updating the BIOS.
My solution was to buy a new motherboard, and this solved the issue completely.


text:
Q: Interpreting integer color values As I'm writing a small "paint" program of my own (just for fun), I wanted to convert an imported image into a pixel array. So far, so good - I found a working solution on stackoverflow that creates an int[][] array. Now, the colors are (obviously, since it's an integer array) integer values. I'll probably use something like Color color = new Color(integerValue) for conversion, but what I'm interested in is how exactly the color is converted between RGB and integer values.
Specifically, which parts of the value specify the red/green/blue/alpha value of the color? Or if it doesn't work that way (i.e. there is no clear distinction between these 4 values), how DOES it work?
For example, the color black (rgb: #FFFFFF) has a value of -16777216. Is it possible to find out the rgb counterpart just by looking at the integer value?
As said, I'm just asking this so I can comprehend it - I don't intend to actually unravel the integer value manually and create a color that way. I also know that I could use int red = (new Color(integerValue)).getRed() to retrieve individual values, but that's pointless considering that I already know that the color is black.
It's just that I expected the integer to show some kind of pattern, considering that red, green and blue have the same values. Furthermore, I've been slightly puzzled that white has a value of -1.
Thanks in advance!


text:
Q: Rudin's discussion on cantor set After defining the Cantor set $P$, Rudin claims no segment of the form $$\Big(\frac{3k+1}{3^m},\frac{3k+2}{3^m}\Big)\tag{24}$$ where $k$ and $m$ are positive integers, has a point in common with $P.$ (it took me a while to verify this; I found this argument and accepted despite wanting more!)
Then he claims : since every segment $(\alpha,\beta)$ contains a segment of the form $(24)\dots$
I wanted to verify this i.e $\Big(\frac{3k_o+1}{3^{m_o}},\frac{3k_o+2}{3^{m_o}}\Big) \subseteq (\alpha,\beta) \subseteq (0,1) $ for some positive integers $k_o$ and $m_o$.
Attempt: For the possibility of inclusion we would want the length of $\Big(\frac{3k+1}{3^m},\frac{3k+2}{3^m}\Big)$ which is $\frac{1}{3^m}$ to be less than the length of $(\alpha,\beta)$ which is $\beta -\alpha$. By the Archimedean property it is possible to find an $m_o(\in \mathbb{N}) > \log_3\frac{1}{\beta - \alpha}$ so that $\frac{1}{3^{m_o}}<\beta -\alpha.$
But I have trouble finding the right $k_o.$ It is possible again to choose $k_o$ by Archimedean property to have $\frac{3k_o+1}{3^{m_o}}> \alpha.$ But how do you ensure that $\frac{3k_o+2}{3^{m_o}}< \beta?$

A: As you observed the length of the interval $\big(\frac{3k+1}{3^m},\frac{3k+2}{3^m}\big)$ is $\frac{1}{3^m}$. Now given $\alpha<\beta\in\mathbb{R}$, let $m$ be sufficiently large so that $\frac{1}{3^m}<\frac{\beta-\alpha}{4}$. This choice of $m$ implies that $$\text{($\star$) }\beta-\frac{4}{3^m}>\alpha$$
From now on $m$ is fixed and we have to choose $k$ (which is going to be dependent on $m$). Since $\frac{3k+1}{3^m}\rightarrow\infty $ as $k\rightarrow\infty$ there exists $k$ for which $\frac{3k+1}{3^m}>\alpha$, let $k_0$ be the minimal $k$ satisfying this condition.
It is left to show that the interval $\big(\frac{3k_0+1}{3^m},\frac{3k_0+2}{3^m}\big)$ lies in $(\alpha,\beta)$. We already know that $\alpha<\frac{3k_0+1}{3^m}$ hence it left to show that $\frac{3k_0+2}{3^m}<\beta$.
Suppose not, then $\frac{3k_0+2}{3^m}\geq\beta$, hence $\frac{3k_0-2}{3^m}+\frac{4}{3^m}\geq \beta$ we conclude that $\frac{3k_0}{3^m}\geq\beta-\frac{4}{3^m}$ From ($\star$) we have that $\frac{3(k_0-1)+1}{3^m}>\alpha$ which is a contradiction to the minimality of $k_0$. This completes the proof.


text:
Q: Extract data from nested tables in PDF
*

*I have a few pdf files that were created from word or excel files.

*I need to get the information thats in the tables.

*The text in the document is not an image so I'm able to extract the text using tools such  as pdfbox.

*When I have the text I have no way of knowing what cells in the table it belongs to because I don't know where the table borders are.

*Iv'e tried a few desktop tools such as abby or solid pdf converter and they are able to convert the files into nice word documents but this doesn't suit my needs as I want to be able to do this programatticly in C#.

*Some of the tables have nested tables wich I think makes this a little bit more diffucult.
I appreciate your help

A: The difficulty here is caused by the fact that the text in the PDF is not contained within any table. It might look like it is, but underneath the surface, it is not.
So there are a couple of options that I can think of. But none of them are going to be quite as satisfying as you'd probably like.

*

*There are some companies that offer SDKs for PDF to Excel/Word conversion. Investintech and Iceni are a couple of examples. But these solutions are not free.

*If you know the exact layout of the PDF files that you need to extract the table data from, then you can use any SDK that lets you extract text from a PDF and also tells you the exact co-ordinates of the extracted text. Using this method you need to know in advance where the text is going to be, so that you can extract text from a specific area on the page. It obviously won't work if you need to process any random document.

It's a difficult task, but hopefully this will give you a starting point.


text:
Q: Why isn't it working T extends Record type Test<T extends Record<symbol, unknown>> = T;

type Result = Test<{
  a: string;
}>;

I made this T extends Record<symbol, unknown> , Test only accept index type with symbol key,why Test<{a:string}> no false alarms ?

A: Typescript interfaces are "open", meaning that additional properties can be present on an object outside of its known interface, and this is not a compile time error.
For this reason, a value of type {a: string} is a valid value for Record<symbol, unknown>.
You can verify this with the following code that compiles perfectly fine:
const obj: {a: string} = {a: "foo"};
const record: Record<symbol, unknown> = obj;

A: If you want it to be invalid you can intersect it with another Record whose values are never:
type Test<T extends Record<symbol, unknown> & Record<string | number, never>> = T;;

type Result = Test<{ // ! error, string/number keys should be type never
  a: string;
}>;

Works well enough
Playground


text:
Q: How to Find the Remaining Length of a Cone With Only a Part of It I took three measurements for a certain plastic cup in my kitchen. One was of the circle on the bottom of the cup, and the other was the top(the larger opening) and the height in between the two. Assuming that the cup is a cone it should collapse to a single point. How can I go about figuring out the length of the remaining section? My maths level: just finished calculus II.
NOTE: This mini-project is just for the fun of maths, so there isn't the need to rush, also I'm perfectly fine being given a long answer that uses higher mathematics and I'll research it at long as it isn't too high above my maths level.
Measurements: Bottom Circle:(.75in diameter), Top Circle(3.5in diameter), and Height(5.5in).

A: Draw a 2D picture of a cross-section of the cup. Let $x$ be the length of the remaining section of the tip of the cone. Then, by similar triangles in your picture, you will see that
$$
\frac{x}{0.75} = \frac{x+5.5}{3.5}
$$
Solve to get $x$.


text:
Q: sapper or svelte for new project? I have looked and played with svelte and sapper and I wondered why would one create a new project with the svelte template rather than the sapper template?
I believe that sapper is to be replaced with sveltekit in due time but it is still the recommended approach.

A: Svelte and Sapper are related very much in the same way that, say, React and Next.js are.  Sapper provides features like server-side rendering (SSR), routing (which can easily be dynamic, if needed), and single-page application (SPA) support.  Creating a route is as simple as dropping a .svelte (for a page) or .js (for a server route) file in the routes folder.  For nested routes, you just drop a folder with a .js file.
I think the answer to your question lies mostly in your use-case.  If you need to create routes, want SSR, or SPA, go with Sapper.  If, however, you don't need those things (or don't know), start with Svelte, since migration to Sapper from Svelte on a smaller project can be as simple as copying a few files.  It should be noted, as @Madacol points out below, that there are some differences (such as {#await}) that can't simply be ported over and will require heavier lifting.  There are a few static sight generators out there (Routify, Elder.js, etc), as well, if that is more your flavor.
Regarding SvelteKit, as @johannchopin stated:

the transition to sveltekit won't be to hard according to the creator Rich Harris.

Rich talks a bit about SvelteKit on this podcast.
UPDATE (3/19/21): It looks like there are docs that include a migration guide, at this point.  It should be noted, though, that SvelteKit 1.0 hasn't dropped yet, so it is possible some of this will change.


text:
Q: Rendering two different sized images with same srcset picks the biggest Rendering the same images twice, once with a bigger size, will make the browser pick the larger even for the image rendered smaller.
Confusing, yes, but let me show.

*

*Just a single image, will show the 200x150 placeholder image:

Small picture?

*Render same image twice, one small and one big, both images show the 800x600 placeholder.

Small picture?

Big picture?

In most cases, this is okay, since we're just loading images of the same aspect ratio, but sometimes, just sometimes, there is a case where mobile viewports show a different aspect ratio from desktop, in that case this could cause stretched or cropped images.
I'm just curious if this is the expected behaviour? Can we prevent this somehow? Or should we suffix the urls with something unique? (Okay, in most cases we could probably leave out the bigger images from the srcset of the smaller rendered image, but I'm 100% sure there is a possible case where suddenly that smaller image does need to be shown big somehow. It's solvable with separate images, sure, but I'd just like to know if it could be just the one.)