Cognito authentication keeps retrying forever, without throwing exception

Question: I have a simple test code for Cognito authentication code in Java with Spring Boot. It works fine on my local, but when I on my remote server (CentOS) it acts very weirdly. If a user does not exist in the pool. keeps creating and recreating new threads and sending the request.
The code:
protected boolean isValidCognito(String username, String password) {

        // Retrieving the AWS credentials from the default instance profile credentials instead of ".withCredentials()".
        // More info on https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html
        AWSCognitoIdentityProvider awsCognitoIDPClient = AWSCognitoIdentityProviderClientBuilder.standard().build();

        Map<String,String> authParams =new HashMap<>();
        authParams.put("USERNAME", username);
        authParams.put("PASSWORD", password);

        AdminInitiateAuthRequest initialRequest = new AdminInitiateAuthRequest()
                .withAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH)
                .withAuthParameters(authParams)
                .withClientId(COGNITO_CLIENT_ID)
                .withUserPoolId(COGNITO_POOL_ID);

        try {
            // NOTE: I know the request is being sent for sure, so we probably get at least this far
            AdminInitiateAuthResult initialResponse = awsCognitoIDPClient.adminInitiateAuth(initialRequest);
            Map<String, String> challengeParams = initialResponse.getChallengeParameters();
            String cognitoUserIdForSrp = challengeParams.get("USER_ID_FOR_SRP");
            String cognitoUserAttributes = challengeParams.get("userAttributes");
            logger.debug("Cognito authenticated user ID: " + cognitoUserIdForSrp
                    + " with user attributes: " + cognitoUserAttributes);
            return true;
        } catch (NotAuthorizedException nae) {
            logger.error("Invalid Cognito username/password provided for " + authParams.get("USERNAME"));
            return false;
        } catch (AWSCognitoIdentityProviderException acipe) {
            logger.error("Amazon Cognito Identity Provider Error!");
            logger.debug("Make sure the user exists in the pool, and ALLOW_ADMIN_USER_PASSWORD_AUTH is enabled.");
            return false;
        } catch (Exception e) {
            logger.error("Unexpected Error: ", e);
            return false;
        }
    }

Logs if it helps:
2020-02-25 17:14:54.919 TRACE 25144 --- [http-nio-8080-exec-98] o.s.t.i.TransactionInterceptor           : Getting transaction for [METHOD_NAME]
2020-02-25 17:14:54.926 TRACE 25144 --- [http-nio-8080-exec-98] o.s.t.i.TransactionInterceptor           : Completing transaction for [METHOD_NAME]
2020-02-25 17:14:54.935 TRACE 25144 --- [http-nio-8080-exec-98] o.s.t.i.TransactionInterceptor           : Getting transaction for [METHOD_NAME]
2020-02-25 17:14:54.942 TRACE 25144 --- [http-nio-8080-exec-98] o.s.t.i.TransactionInterceptor           : Completing transaction for [METHOD_NAME]
2020-02-25 17:14:54.950 DEBUG 25144 --- [http-nio-8080-exec-98] c.c.c.r.persistence.CognDaoImpl  : There is a user migrated to Cognito with user_id: SOME_UUID
2020-02-25 17:14:54.950  INFO 25144 --- [http-nio-8080-exec-98] c.c.c.r.c.AuthenticationController       : firstname.lastname@example.com has been migrated. Using Cognito for authentication.

2020-02-25 17:14:56.655 TRACE 25144 --- [http-nio-8080-exec-160] o.s.t.i.TransactionInterceptor           : Getting transaction for [METHOD_NAME]
2020-02-25 17:14:56.673 TRACE 25144 --- [http-nio-8080-exec-160] o.s.t.i.TransactionInterceptor           : Completing transaction for [METHOD_NAME]
2020-02-25 17:14:56.683 TRACE 25144 --- [http-nio-8080-exec-160] o.s.t.i.TransactionInterceptor           : Getting transaction for [METHOD_NAME]
2020-02-25 17:14:56.692 TRACE 25144 --- [http-nio-8080-exec-160] o.s.t.i.TransactionInterceptor           : Completing transaction for [METHOD_NAME]
2020-02-25 17:14:56.705 DEBUG 25144 --- [http-nio-8080-exec-160] c.c.c.r.persistence.CogDaoImpl  : There is a user migrated to Cognito with user_id: SOME_UUID
2020-02-25 17:14:56.705  INFO 25144 --- [http-nio-8080-exec-160] c.c.c.r.c.AuthenticationController       : firstname.lastname@example.com has been migrated. Using Cognito for authentication.

...

Answer: There is nothing inherently wrong with "creating and recreating threads". If you have too many threads, your jvm will run out of memory or your process will die because you have hit some system limits. If you think your code is going into a loop, you need to find out who is calling your code and analyze that part of your code. Perhaps a thread-dump may help.


Memory Exceeded Error in MS Access

Question: I have the following procedure that I run (in an MS Access module) on a regular basis to switch the linked table connection strings from Test to Production and vice-versa:
Public Function TableRelink()
    Dim db As Database
    Dim strConnect As String
    Dim rs As Recordset
    Dim tdf As TableDef
    strConnect = "ODBC;DRIVER=SQL Server;SERVER=MYTESTSERVER;Trusted_Connection=Yes;APP=Microsoft Office 2013;DATABASE=MyDB;"
    'strConnect = "ODBC;DRIVER=SQL Server;SERVER=MYLIVESERVER;Trusted_Connection=Yes;APP=Microsoft Office 2013;DATABASE=MyDB;"
    CurrentDb.TableDefs.Refresh
    For Each tdf In CurrentDb.TableDefs
        If tdf.Connect <> "" Then
            tdf.Connect = strConnect
            tdf.RefreshLink
        End If
    Next
    MsgBox ("Done!")
End Function

The above has been working for months and months.  About a week ago, the following error randomly popped up.  Then, after a few minutes, without any intervention on my part, it would allow me to run the procedure again.  Today, the error has come back.

Run-time error '3035': System resource exceeded.

It is thrown on this line: tdf.RefreshLink
I did a Google search and found an article out there talking about a hotfix (that wouldn't install on my machine), and another about editing a registry value (which didn't seem fix it).  As I type this, the error has stopped popping up and I can again re-link my tables, so at this point, I can't really do any more troubleshooting.  I was reading another SO post talking about the lock file, but couldn't really make heads or tails of the accepted answer, and I'm not really convinced it has anything to do with my particular scenario.  Does anyone know what might be causing this and/or what can be done to prevent it?
For reference, I'm running Office 365 ProPlus on a Win10 64-bit machine.
Comment: What is the SO post that you can't make heads or tails of?
Answer: First, do use your db object:
Public Function TableRelink()
    Dim db As Database
    Dim strConnect As String
    Dim rs As Recordset
    Dim tdf As TableDef

    strConnect = "ODBC;DRIVER=SQL Server;SERVER=MYTESTSERVER;Trusted_Connection=Yes;APP=Microsoft Office 2013;DATABASE=MyDB;"
    'strConnect = "ODBC;DRIVER=SQL Server;SERVER=MYLIVESERVER;Trusted_Connection=Yes;APP=Microsoft Office 2013;DATABASE=MyDB;"

    Set db = CurrentDb
    db.TableDefs.Refresh
    For Each tdf In db.TableDefs
        If tdf.Connect <> "" Then
            tdf.Connect = strConnect
            tdf.RefreshLink
        End If
    Next
    MsgBox ("Done!")

    Set td = Nothing
    Set db = Nothing

End Function

However, another and a much faster method is to have both sets of tables linked permanently and then rename them for switching the database.
For example, to switch from Production to Test:
Table1 -> Table1_p
Table2 -> Table2_p
...
Table1_t -> Table1
Table2_t -> Table2

Of course, if you modify a table schema, you must relink as usual.
Comment: What is the advantage of using the `db` object versus just calling `CurrentDb.TableDefs.Refresh`?
Comment: And most importantly, how does that fix my issue?
Comment: Well, most others open the object only once that way and don't see your issue, And you asked: "Does anyone know what might be causing this and/or what can be done to prevent it?"
Comment: Not sure I follow... But, I'll change it next time I see the error and see if that fixes it.  Thx.
Comment: Update: This suggestion didn't fix the problem.
Comment: Then I would suggest using the renaming method.
Comment: That sucks... so, I have to abandon a completely fine method that has been tried and true for several months and refactor it, all because of some vague Access crap that nobody understands.  I hate when that happens.
Comment: Typically, in REAL development frameworks, you get specific errors that include a proper diagnosis so that you can evaluate and determine whether the issue can be circumvented, or if a new solution is necessary.  But, in Access (much like SharePoint), you just get "Nope!  This doesn't work anymore" without any rhyme or reason.

Memory Exceeded Error in MS Access


Legato slide, Pulloff, hammer on combo

Question: I have been trying to figure out how to play these notes for months.. I don't know if I'm supposed to do it as 1 pick starting at the 16 then pull off and slide hammer and slide again?? Please help.
Which notes do I fret first and in what order?
Comment: Where is this from? Listening to the original performance could help.
Comment: Really need to see at least the surrounding bars to provide better answers.
Answer: Pluck 16, pull off to 14. Slide down to 12. Hammer back on to 14. Slide back to 16. There is only one place to pluck - the very first time anything is played. Use whichever fingers you feel work best for you, bear in mind the slides will utilise the same finger each time.
Comment: Wow that is probably going to be a fast note sequence. Thanks Tim
Answer: Starting on 16, pull off to 14, slide to 12, hammer on to 14 and slide to 16. I'd suggest following fingering where (1) is the index finger and (3) is the ring finger (or right hand equivalent).
(3)16 P (1)14 S (1)12 S (1)16
The long slur connecting the 16's at either end is notation for legato. This means in the entire line there is only meant to be one pluck on the first 16.
Comment: I disagree, there is only one pluck at the beginning, the legato covers the last note which is articulated with the slide from 14 to 16.
Comment: Thank you so much! That definitely makes so much sense!! You're the best
Comment: Slide to pluck is a standard technique in electric guitar. There's objectively no way of knowing John until a bigger screenshot is posted by OP. In the score legato continues from the final 16 to other notes. This infers a second plucking.
Comment: I disagree that slide to pluck is a standard technique. Yes, it gets used, but more often, in a fast passage, there's no need to pluck after the slide, as here.
Comment: It very much is a standard technique it's name is a "shift slide" and is notated exactly as above. Curious as to how you can justify the ongoing slur if the last note is not meant to be plucked?
Comment: It's impossible to tell if it's a slur or tie from the picture
Comment: @ojs - no, it's not. A slur will join several notes that are of different pitch, as here. A tie has to join notes of the same pitch.
Comment: @Tim there are two arcs in the picture. The fully shown one is a slur. The one to the right that is cut in half could be a tie depending what's on the other end. If you know what is there, please tell how you know.
Comment: @ojs - I only looked at the tab. But, it's an educated guess that the 2nd one will be a tie, looking at the vib. sign above.
Comment: @Tim I would expect it to be a tie too. I was answering to the person above who seemed to think that it's the beginning of next slur and should be picked. The tab suggests it's a tie but this wouldn't be the first time tab and standard notation disagree.
Comment: Looking at the context it's clear that the part in original question was single slur and only first note is picked.

Legato slide, Pulloff, hammer on combo


problemas com sinais de uma consulta mysql com php

Question:

        Atividade Primária

        <select name="id_cnae" class="browser-default custom-select">
                <option value=0>Atividade Primária</option>
                <?php
                        $sql = mysqli_query($conn, "SELECT id_cnae, descricao FROM CNAE") or die(mysqli_error($conn));
                        while($aux = mysqli_fetch_assoc($sql)) {
                ?>
                <option value='<?php echo $aux["id_cnae"]?>'><?php echo $aux["descricao"] ?>
                </option>
                <?php
                        }
                ?>
        </select>

Estou com problemas no front, o resultado sai com simbolos ao invés de Ç e acentuação, meu html já tem UTF-8
Comment: Caro Jonas, tem que ajustar a conexão também, a estrutura do banco (talvez já esteja ok) e salvar os seus .php em UTF-8 sem "B O M". Tá detalhado na pergunta que linkei na sua
Answer: Adicione <meta charset='utf-8'> ao header do seu arquivo HTML.
OU
Tente alterar sua query para SELECT id_cnae, descricao FROM CNAE collate utf8_unicode_ci.
Mas sugiro que você troque a collação (se é assim que chama) das suas tabelas no banco.
Fonte: Outra pergunta do Sopt
Comment: já adicionei, mas não funcionou


List files in .7z, .rar and .tar archives using PHP

Question: I want to list the files inside an archive, without their extraction.
The types of archives I am interested in:

.7z (7-Zip)
.rar (WinRAR)
.tar (POSIX, e.g. GNU tar).
.zip (ISO standard, e.g. WinZip)

For .zip files, I have been able to achieve this:
<?php
    $za = new ZipArchive();
    $za->open('theZip.zip');
    for ($i = 0; $i < $za->numFiles; $i++) {
        $stat = $za->statIndex($i);
        print_r(basename($stat['name']) . PHP_EOL);
    }
?>

However, I have not managed to do the same for .7z files. Haven't tested .rar and .tar, but will need them as well.
Comment: Would it be an option to capture the 'list' output of an external program such as [7z](http://linux.die.net/man/1/7z)? (assuming Linux)
Comment: @Arnauld: hardly as it is to be done after a user uploads a file.
Comment: @M.M is there something missing from my answer to accept it, or are you waiting for an answer that includes a pure PHP LZMA implementation?
Comment: @Leith, I awarded you the bounty because your answer deserved it, however I want to give others the oportunity to specify and implementation more precisely (examples, Zipbombs, ...)
Comment: @M.M I have updated with notes on zip bombs and some code examples for the official PECL extensions.
Answer: This is something that has come up before (for various reasons like this and this and the one with broken links in the answer).
Generally the prevailing opinion at the moment is to create a wrapper (either DIY or use a library) which relies on having a 7-zip binary (executable) to be accessible on the server and wrap calls to the binary using exec(), rather than a pure PHP solution.
Since the 7zip format supports a variety of compression algorithms, I'm assuming that you probably want a pure PHP implementation of reading/decompressing the LZMA format. While there are LZMA SDKs available for C, C++, C# and Java and someone has made a PHP Extension for LZMA2 (and a fork for LZMA) as yet even though there has even been interest on the 7-zip forums for quite a while, no one seems to have ported this over as a comprehensive PECL extension or pure PHP yet.
Depending on your needs & motivation, this leaves you with:

add the 7-zip binary to your server, and use a wrapper library, be it your own or someone else's
install and use an unofficial PECL extension
bravely port the LZMA SDK to PHP yourself (and hopefully contribute it back to open source!)

For other formats you can look to the PHP documentation for examples and details on usage:

.rar has its own official PECL extension
.tar can be extracted by the Phar PECL extention (also see SO for examples)
.zip has an official PECL extension
.gz has an official PECL exension
and a couple of other formats

Since all of these involve PECL extensions, if you're limited by your webhost in some way and need pure PHP solutions for this, it might be easier to just shift to a more amenable webhost.
To attempt to protect against zip bombs, you can look at the compression ratios as suggested by this answer (packed size divided by unpacked size and treat anything over a certain threshold as invalid), although the zip bomb talked about the answer to one of the linked questions would indicate that this can be ineffective against multi-layered zip bombs. For those you would need to look at whether or not the files you're listing are archives as well, ensuring you're not doing any kind of recursive extraction and then treat archives that contain archives as invalid.
For completeness, some usage examples for official PECL extensions:
RAR:
<?php
// open the archive file
$archive = RarArchive::open('archive.rar');
// make sure it's valid
if ($archive === false) return;
// retrieve a list of entries in the archive
$entries = $archive->getEntries();
// make sure the entry list is valid
if ($entries === false) return;
// example output of entry count
echo "Found ".count($entries)." entries.\n";
// loop over entries
foreach ($entries as $e) {
    echo $e->getName()."\n";
}
// close the archive file
$archive->close();
?>

TAR:
<?php
// open the archive file
try {
    $archive = new PharData('archive.tar');
}
// make sure it's valid
catch (UnexpectedValueException $e) {
    return;
}
// make sure the entry list is valid
if ($archive->count() === 0) return;
// example output of entry count
echo "Found ".$archive->count()." entries.\n";
// loop over entries (PharData is already a list of entries in the archive)
foreach ($archive as $entry) {
    echo $entry."\n";
}
// no need to close a PharData
?>

ZIP (adapted from OP's question which is from here):
<?php
// open the archive file
$archive = new ZipArchive;
$valid = $archive->open('archive.zip');
// make sure it's valid (if not ZipArchive::open() returns various error codes)
if ($valid !== true) return;
// make sure the entry list is valid
if ($archive->numFiles === 0) return;
// example output of entry count
echo "Found ".$archive->numFiles." entries.\n";
// loop over entries
for ($i = 0; $i < $archive->numFiles; $i++) {
    $e = $archive->statIndex($i);
    echo $e['name']."\n";
}
// close the archive file (redundant as called automatically at the end of the script)
$archive->close();
?>

GZ:
Since gz (gnu Zlib) is a compression mechanism rather than an archive format, this is different in PHP. If you open a .gz file by itself (rather than treating it like a .tar) with gzopen(), any reads from it are transparently decompressed. Since this is most commonly .tar.gz, you can treat it like a .tar as above (also see this answer on another question). Or you can extract the tar with PharData::decompress() as in this answer on another question.
Answer: Arnuld's comment is a clue as to the most practical way to solve the problem. Even if you can find implementations of all the possible archive types you want to support acessible to PHP, only ZIP and gzip are natively supported by a PHP extension. The remainder will either be native PHP code or shell out to invoke a standalone binary. The former will be a bit of a performance/resource bottleneck while the latter will be dependant on your underlying platform.
(BTW, unless you trust the users completely with access to your server, or are a relatively good programmer, you're going to have to do more inspection of the content than just listing what is inside an uploaded archive).
Once you've collected a ragtag assortment of utilities, and audited the code to a reasonable level, you should then be decorating the implementation with a uniform API to ensure that your glue code doesn't turn into spaghetti.
If it were me, I'd start from scratch implementing an interface like that for PHP's zip around the standalone binaries; PHP is, after all, a scripting language. That you will be applying this to user uploaded files is no reason not to use an existing, native code implementation, indeed, the security consideration is a strong argument for such an approach.
Remember to watch outfor zip bombs.
Comment: +1 great advice, do you have any idea how to avoid zip bombs? i found [this](http://stackoverflow.com/questions/13279418/how-to-detect-a-zip-bomb-using-php) but it seems fallible
Comment: While most archive formats/code implementations provide a means for listing the content of an archive, including the uncompressed size, these usually work by reading a manifest. The only safe solution I know of is to extract the file onto a constrained file system (e.g. a ram disk or loopback filesystem) in practice you'd probably implement multiple such devices in a managed pool.
Answer: I think this class might help you
Code sample from the link
// Open an archive.
$archive = new SevenZipArchive('docs.7z');

// Show number of contained files:
print $archive->count() . " file(s) in archive\n";

// Show info about the first contained file:
$entry = $archive->get(0);
print 'First file name: ' . $entry['Name'] . "\n";

// Iterate over all the contained files in archive, and dump all their info:
foreach ($archive as $entry) {
    print_r($entry);
}

Update
As promised in my comments and OP asked for one way to check uploaded files against bomb, here is a link that describe it. It is a ClamAV® is an open source antivirus engine for detecting trojans, viruses, malware & other malicious threats source antivirus.
From ClamavNet site I found this information

Whenever a file exceeds ArchiveMaxCompressionRatio (see clamd.conf man
  page), it's considered a logic bomb and marked as Oversized.zip . Try
  increasing your ArchiveMaxCompressionRatio setting.

That said my experience with uploading files comes from typically trusted users. Zip bombs or any other threats, if I was you, I will research it first and find out how a zip bombs/any other threats works, this will help you preventing it through extra coding or solution.
Further more depending on your business size, budget and how critical your web-app is, it is a good idea to make a kind of strategy, policy and roles on your site, which describes the usage of your web-app. A part of that is files uploading policy, like which type of files allowed to be uploaded, what is the maximum size, who can upload and accepting your disclaimer where you mentioning these stuffs etc. that policy should be reflected as guideline to audience using your web-app services.
Here is few links about zip bombs:

How does one make a Zip bomb?
How can I protect myself from a zip bomb?
https://en.wikipedia.org/wiki/Zip_bomb
Comment: +1, i am yet to test it but it seems like a piece of the puzzle. do you have any idea on how to avoid zip bombs as well?
Comment: +1 liked the question. Regarding you other question in comment, zip bomb, my experience with upload comes from trusted users, but if I was you I will research first and find out how a zipbomb works http://stackoverflow.com/questions/1459673/how-does-one-make-a-zip-bomb and http://stackoverflow.com/questions/1459080/how-can-i-protect-myself-from-a-zip-bomb and see how I can prevent it through the code.
Comment: If I get more details regarding zip bombs I will added to my answer.
Answer: Try this
<?php

$x = exec("7z l ./test.zip | awk '/^[0-9]{4}-/{print}'", $l);
foreach($l as $r)
{
    $e = explode(" ", $r);
    $c = count($e)-1;
    echo $e[$c]."\n";
}
?>


passing custom parameters to facebook fan page tab

Question: I'm unable to get custom parameters send to my facebook fan page tab.
I'm using php and is passing like this:
http://www.facebook.com/pages/{page-name}/?sk=APP_ID&pass=1
but I'm unable to read the parameter pass
Sreejith
Comment: I suppose your application is inside an IFrame inside your fan page! this is why you can access those parameters.
Comment: @ifaour, yes it's inside an IFrame
Answer: Facebook passes in your data as part of the signed_Request data.
Here is how you would retrieve it using PHP:
<code><?php
require 'facebook.php';
$app_id = "YOUR APP ID HERE";
$app_secret = "YOUR SECRET KEY HERE";

$facebook = new Facebook(array(
        'appId' => $app_id,
        'secret' => $app_secret,
        'cookie' => true
));

// THE MAGIC SAUCE
$signed_request = $facebook->getSignedRequest();

$page_id = $signed_request["page"]["id"];
$like_status = $signed_request["page"]["liked"];
// HERE IS A STRING OF YOUR APP DATA.
$app_data = $signed_request["app_data"];

echo '$app_data = '.$app_data;
?>
</code>
This example requires the Facebook PHP api and will write your app_data into the browser window where you can marvel in all its glory.
Comment: You can add http://facebook.com/blabla?app_data=value1|value2|value3 and then do explode('|', $signed_request['app_data'])
Answer: Oh wow, I didn't know about the app_data parameter.Here's another method for whatever it's worth:
http://iamskwerl.com/tech/2011/11/passing-query-variables-to-facebook-fan-page-tabs/
Comment: The link seems dead. It might we worth adding the answer here direct instead of redirecting.
Comment: Your approach is a great solution, when you have no server side component in your application. Thumbs up : ]
Answer: There is a solution available although I have not tried it but hope it works
http://ikorolchuk.blogspot.com/2011/03/facebook-fan-page-pass-parameter-to.html


Why are least-squares parameters normally distributed?

Question: I am trying to figure out why the parameter $$\begin{equation*}
\hat\beta = (X^TX)^{-1}X^TY \end{equation*}$$
is normally distributed in least-squares prediction. (Where Y is a linear function plus normal noise.)
All the examples I've found have said that since
$$\begin{align*}
\hat\beta &= (X^TX)^{-1}X^TY \\
&= (X^TX)^{-1}X^T(X\beta + \varepsilon) \\
&= \beta + (X^TX)^{-1}X^T\varepsilon
\end{align*}$$
we know that
$$\hat\beta-\beta \sim \mathcal{N}(0,\sigma^2 (X^TX)^{-1})$$
I can see how the mean and variance are calculated, but why is this a normal distribution?
Comment: property: a linear transform of a normal is a normal
Comment: Possible duplicate of [Help clarify the implication of normality in an Ordinary Least Square (OLS) Regression](http://stats.stackexchange.com/questions/100332/help-clarify-the-implication-of-normality-in-an-ordinary-least-square-ols-regr)
Comment: Also be aware that under certain regularity conditions, the distribution of $\hat{\beta}$ will be asymptotically normal as the number of observations $n \rightarrow \infty$. For the asymptotic argument, you don't need $\epsilon$ to be normal (but you do need conditions such that a central limit theorem and other asymptotic arguments apply).
Answer: In classical statistics the parameter value $\beta$ in a linear regression model is an unknown constant.  The value $\hat{\beta}$ is not a parameter - it is an estimator of the parameter, which is a function of the data.  The reason this estimator is normally distributed is that it is a linear function of the underlying error vector (as written in the equation you have shown), which is normally distributed under the model assumptions.  (Note that even if you relax of the normality assumption, the parameter estimator will still be a summation quantity for which you can invoke the CLT under fairly general conditions; so the distribution of the parameter estimator will converge to the normal distribution under broad conditions even if the model is misspecified.)
Comment: What do you mean by the estimator being a summation quantity? Do you mean that it's a summation over the random unobserved errors?
Comment: Yes.  You can see from the above that it is of the form $\hat{\beta} = \beta + A \varepsilon$ where $A$ is an appropriate transformation matrix.  This means that the estimator is an affine transformation of $\varepsilon$
Comment: Ah yes, so this seems to imply that CLT also applies to weighted sums? Also, I think one issue with CLT here could potentiall be if the errors aren't independently distributed. In that case, CLT would not work?
Comment: Yes, but it depends on specifics.  There are broad CLTs that apply for weighted sums and for correlated errors.  Broadly speaking, these work only if the correlation is weak enough, and the weighting is diffuse enough that no finite set of error terms "dominate" the sum in the limit.


ZIndex within a DockPanel

Question: I have a DockPanel as the root element for my window.
I have another DockPanel that is essentially a menu bar which is set to be docked to the Top of the root-element-DockPanel.
I would like to have an image docked to the top of the root-element-DockPanel that floats over the menu-bar-DockPanel.
For example:
<DockPanel x:Name="RootDockPanel">
  <Image Souce="/MyProject;component/Images/imageName.jpg" DockPanel.Dock="Top" Panel.ZIndex="3" />
  <DockPanel x:Name="MenuDockPanel" DockPanel.Dock="Top" Panel.ZIndex="0">

  </DockPanel>
</DockPanel>

I have tried setting the Panel.ZIndex of the Image to something higher than the Panel.ZIndex of the menu-bar-DockPanel but this doesn't work.
Since the ZIndex is proving to be useless, I'm not sure how to accomplish this and I'm looking for your input.
Thanks for your help!
-Frinny
Answer: I recommend simply ditching the DockPanel control and using Grid instead. In my experience, DockPanel is a poorly-designed control and is the most useless of all the panel controls in WPF.
Comment: As much as I hated this answer when I asked the question originally; I found that ditching the DockPanel and using a Grid instead fixed the issue and has been my approach ever since. So yeah, it didn't answer my question on how to fix the DockPanel; but it did help me overall.
Answer: DockPanel.ZIndex works for me.
Here's an example to help (it may not compile, I just wrote it from memory to illustrate the concept):
<DockPanel>

</DockPanel>

ZIndex within a DockPanel


Dealing with violation of linear regression assumptions

Question: I have a data set where some extreme, but not nonetheless important observations are present which prompts violation of the linear regression assumptions of normality and constant variance. The assumption of normality I read here: Regression when the OLS residuals are not normally distributed, is of less concern as long as we're not concerned with p-values or intervals.
The violation of constant variance however is discussed here: What does having "constant variance" in a linear regression model mean?, as well as here: Regression when the OLS residuals are not normally distributed, where Michael R.Chernick in the comments of his response writes

log transformation or Box-Cox with small lambda shrink the tails. That can work for some heavytailed and skewed distribution. I don't know what if any transformations will work for very heavy-tailed distributions.

As such I tried Box-Cox transformation, with optimal lambda = 0.1414141 and also using first difference rewriting of the response variable ($y_t - y_{t-1}$). I plotted the results of the optimal Box-Cox transformation:

This does not provide a solution to my situation, and the assumption of constant variance remains violated.
I would like some pointers towards what I can, if any, to fix this alternatively how I can model my data using other regression techniques.

Edit
My modelling is about quantifying uncertainty of an agnostic prediction model, in a highly stochastic environment (travel times in traffic). For the two data points in the graph that normally would be considered outliers, the agnostic prediction model made a reasonable prediction. I have checked this by comparing the predictions versus the actual outcome. That motivates me to not treat them as outliers, as I assume the data fed forward to the prediction model was viable.
The agnostic prediction model have access to GPS position and speed when making its predictions about arrival times. I don't have access to the same data, but rather what I'm using here is the previous travel time as a modeling feature. The reason behind those data points being so extreme is unknown to me.
Comment: With two extreme outliers among what seem to be over 1000 observations, I'm not sure that a single simple linear regression will adequately represent your data. You say "some extreme, but not nonetheless important observations are present." It might help to describe why those observations should be included in your analysis. Why are those values so extreme? Please provide that information by editing the question, as comments are easy to overlook and can be deleted.
Comment: Those two outliers are so far away from everything else after your transformation. Why do you think they should be modeled by the same data generating process?
Comment: I tried to provide an explanation about why I think they shouldn't be treated as outliers @EdM, please let me know if helps to clarify the situation.
Comment: @wzbillings I have made an edit to the post where I provide an explanation.
Answer: From the plots the problems seem to boil down to two outliers (OK I get that these plots are from after Box-Cox transformation and before things may have looked worse), potentially leverage points. This may have a rather detrimental effect on the regression estimation, but can be handled well using robust regression. A state of the art method for this is the MM-estimator, as performed by R-function lmrob in package robustbase. Note that this will estimate a hopefully good regression for the non-outliers; the outliers, if important and correct, should be separately interpreted.
Proviso: Obviously I don't see diagnostic plots from before transformation, but the outliers may affect the Box-Cox as well. Using robust regression with the same Box-Cox lambda is probably fine, but also another or no transformation may (or may not) work well with robust regression.
Comment: If MM-estimator estimates a "hopefully good regression for the non-outliers", does this mean the outliers are essentially disregarded by the model? If so, is there a reason to not just exclude them?
Comment: @OLGJ The MM-estimator will weight outliers down in a continuous manner, i.e., some observations will be given nonzero but low weight, some almost full weight, some zero weight. Particularly, it will determine these weights in a data-based manner. The outliers still have effect insofar that they are taken into account for the workings. The thing is that outlier identification based on OLS-residuals is unreliable as there may be masking effects and leverage points may not show large residuals but may have large effect. So you shouldn't think you know exactly what the outliers are based on OLS.
Comment: A major reason for running robust regression is that its diagnostic plots are more informative/reliable than those for OLS.
Comment: @OLGJ Furthermore, the distributional theory behind the tests run in MM-regression is robust against outliers, too, whereas OLS theory is invalidated by removing outliers in a data-based manner.


Include Search Parameters Custom Paging SQL Query

Question: answered
Having some trouble modifying an SQL query that is commonly used for ObjectDataSource custom paging.
Below is a custom ObjectDataSource paging SQL call, that will return only the results for a single page of information on the website gridview. This is often used for faster loading times.
SELECT *
FROM
(SELECT *,
   ROW_NUMBER() OVER(ORDER BY ApplicationDescription DESC) AS PriceRank
FROM InstallationCodes
) AS ProductsWithRowNumber
WHERE
PriceRank > 0 AND
PriceRank <= (12);

The goal is to add a search parameter to filter the call before the result ordered and filtered down to the page size.
Here is an example search parameter so that the query will only return results with gold or null in the column FeatureString:
WHERE (FeatureString LIKE 'gold' OR FeatureString IS NULL)

How do we filter by parameter before reducing to page size?
Please let me know if you need me to clarify anything in more detail.
Answer: answer
SELECT *
FROM
(SELECT *,
ROW_NUMBER() OVER(ORDER BY ApplicationDescription DESC) AS PriceRank
FROM InstallationCodes ***WHERE FeatureString LIKE 'gold' OR FeatureString IS NULL***)
AS ProductsWithRowNumber
WHERE
PriceRank > 0 AND
PriceRank <= (12);

remove the multiplication stars (***)


Just a sanity check in basic functional analysis

Question: Consider the algebra $C(S^1)$ of continuous functions $S^1 \to \mathbb C$ together with the $\|\cdot\|_\infty$ ($\sup$-norm). I am thinking that:
(?) The (sub-)algebra generated by $\rm{id}$ and $\overline{\cdot}$ (the complex conjugation) is the set of all polynomials.
(??) The closure of this subalgebra generated by $z$ and $\overline{z}$ is the entire algebra $C(S^1)$ (because of Stone-Weierstrass)?.
Is that accurate? If my thinking is wrong I'd greatly appreciate any corrections.
Comment: Note that $z\mapsto\frac{1}{z}$ ($=\overline{z}$ over $S^1$) cannot be approximated by polynomials. If it could, then $\int_{S^1}\frac{dz}{z}=0$, but it doens't.
Comment: @JonathanY. Polynomials here means polynomials in $z$ and $\overline{z}$, for the circle, also trigonometric polynomials.
Comment: More accurate: $\dots$ subalgebra generated by $1,z,\overline z$ $\dots$
Answer: Regarding the first question, yes, it is the algebra of polynomials, if you consider polynomials in $z$ and $\overline{z}$. This is also the algebra of trigonometric polynomials, generated by $\cos nt,\, n \geqslant 0$ and $\sin nt,\, n\geqslant 1$.
By Weierstraß' theorem, this algebra is dense in $C(S^1)$.
Comment: But the algebra generated by $z$ and $\overline{z}$ does not contain $1$. To apply Stone-Weierstrass the algebra has to contain $1$, no?
Comment: On the unit circle, $1 = z\cdot \overline{z}$, so the algebra generated by $z$ and $\overline{z}$ contains all polynomials in $z$ and $\overline{z}$, including the constants. For other spaces than $S^1$, the generated algebra need not include $1$.
Answer: By Stone-Weierstrass, the sub-$C^*$-algebra generated by $z\mapsto z$ and $z\mapsto\bar{z}$ (which is to say, that generated by $z\mapsto z$, as complex conjugation is simply the involution of this algebra), which naturally separates points, is indeed dense in $C(S^1,\mathbb{C})$.
However, the fact mentioned above ($\int_{S^1}\frac{dz}{z}=2\pi i$ and $\int_{S^1}p(z)dz=0$ for all $p\in\mathbb{C}[z]$, implying that uniform approximation is impossible) shows that it must be a proper super-set of the polynomials.
In fact, it's not difficult to verify that the $C^*$-algebra of rational functions (which naturally contains the $C^*$-algebra generated by $z\mapsto z$) is also contained in it.
Comment: Right, great thanks! I just had a new thought: isn't it true then that the polynomials are the algebra generated by the identity function together with the $1$ function?
Comment: Do you have any ideas about (??)?


Json array issue on binding to bootstrap datatable

Question: I am having a json object like the one below which I am reading from an xml file. I can see on the alert that the json obj is being displayed.
Now that I have the json object I am trying to bind against a Bootstrap datatable like in this example
How to load JSON data into Bootstrap table?
Whatever I tried the bootstrap table won't get populated. I think is because my json object contains the "book", which is the object name while the example from the link above has just a Json array. However I tried to do book.author and it still not working.
This is my plnk attempt, if anyone can have a look and tell what I am doing wrong would be great. https://plnkr.co/edit/h9islDjHyz6Sxkhl
<code>        {
      "book": [
        {
          "author": "Gambardella, Matthew",
          "title": "XML Developer's Guide",
          "genre": "Computer",
          "price": "44.95",
          "publish_date": "2000-10-01",
          "description": "An in-depth look at creating applications \n      with XML.",
          "id": "bk101"
        },
        {
          "author": "Ralls, Kim",
          "title": "Midnight Rain",
          "genre": "Fantasy",
          "price": "5.95",
          "publish_date": "2000-12-16",
          "description": "A former architect battles corporate zombies, \n      an evil sorceress, and her own childhood to become queen \n      of the world.",
          "id": "bk102"
        }
      ]
    }

    var $table = $('#table');
        var mydata = "";

    //read data from XML
    $.get('hello.xml', function(xml) {
          var json = $.xml2json(xml);
          console.log(json);
          // This part is for displaying the json result  in this example
          var jsonAsString = JSON.stringify(json, null, 2);
          setJsonVal(jsonAsString);
        });

    //set mydata variablle with the json obj from XML
    function setJsonVal(value){
      mydata = value;
      alert(value)
    }

$(function () {
    $('#table').bootstrapTable({
        data: mydata
    });
});
</code>
Answer: You need to use JSON.parse() to convert the value to json and then you can access the book by using .book.
<code>function setJsonVal(value){

    mydata = JSON.parse(value).book;
    alert(value)

    $('#table').bootstrapTable({
        data: mydata
    });
}
</code>


How to use Instagram Graph API using PHP to retrieve public post info

Question: I need help getting started using the Graph API to retrieve basic public info from an Instagram account (account name, likes, post date, image url, description). I was able to do all of this with the Instagram API but i haven't seen any examples on how to do this using the Instagram Graph API.
Comment: Thanks Martin, my understanding but hopefully i'm wrong is that the standard api will stop working in july 2018
Comment: thanks but thats the first thing I did
Comment: The Instagram Graphc API seems to be more about interacting with business accounts. If you're just wanting to get details of any Instagram user, then the "traditional" API (https://www.instagram.com/developer/endpoints/users/) seems to be the most appropriate way.
Comment: Try reading the documentation: https://developers.facebook.com/docs/instagram-api/reference/
Answer: Yes, Instagram API is going to deprecate some APIs till 2018. complete API deprecation by 2020: https://developers.facebook.com/blog/post/2018/01/30/instagram-graph-api-updates/ - and everything would be moved on FB graph API.

We will be deprecating the older Instagram API Platform in three
  phases with complete deprecation occurring in early 2020.
The following will be available until July 31, 2018:
Follower List - to read the list of followers and followed-by users
  Relationships - to follow and unfollow accounts on a user's behalf
  Commenting on Public Content - to post and delete comments on a user's
  behalf on public media The following will be available until December
  11, 2018:
Commenting - to post and delete comments on a user's behalf on owned
  media Public Content - to read any public profile info and media on a
  user's behalf Likes - to like and unlike media on a user's behalf
  Subscriptions - to receive notifications when media is posted The
  following will be available until early 2020:
Basic - to read a user's profile info and media

But yes, your concern is correct - there is no way for public content in graph api.
And your use case to search on public content won't be supported.
FB wants to move to business account approach rather being a photo repository for search (like twitter or pinterest or flickr). they would want to have brand accounts with ads and other account type specific features. (like fb or wechat)


How would I locate the correct IP address of another computer on my LAN which is not publicly accessible?

Question: I am writing a distributed Java app, but the networking side of things is stumping me. For some reason it's not working correctly. I think it's because the IP address I get through ipconfig /all is not accessible from outside the LAN. I appreciate any tips or advice.
Answer: Hmmm??? "How would I locate the correct IP address of another computer on my LAN which is not publicly accessible?" and "I think it's because the IP address I get through ipconfig /all is not accessible from outside the LAN." appear to run opposite of each other. Which one is it?
Are you trying to identify IPs internally from within the same network or are you having accessibility issues from one network to another?
If it's the former, then an internal ICMP scan across the network is fairly easy or an ARP table read if it a system which has already made direct contact with the application system (or another local network device where its ARP table can be referenced/extracted from).
If it's the later, then you might consider providing some additional details that as to what is being attempted.
Comment: Hi, yes I'm trying to identify IPs internally from within the same network. I have to run a networked demo between 2 machines inside a university lab. So I should do an ICMP scan ? I'll look that up and do that! Thank You ,
Comment: That's typical for on a local network. You might also check with the network support folks to ensure there are no policies against scanning within the network. Some security folks and/or products may view that as a possible impending attack, but if it is legitimate, then coordinating that up front should take care of subject.
Comment: Glad that it is working out for you.


How should the first chords in "Rubber Human (Key Ingredient Ver.)" be labeled?

Question: I was looking at this song (which I think is in Gb Major) and tried to figure out what the chords in the first 4 measures are in context from this sheet music that I have:
You can also listen to it here if it helps (the first 8 seconds or so):

Here's my attempt:
Measure #1 Ab minor sus 4 which resolves to Ab minor.
Measure #2 Bb Major flat 5 (?) which resolves to Bb Major.
Measure #3 I think this is maybe an Eb minor flat 13 which resolves to Eb minor?
Measure #4 I don't really know, maybe an Ab 9?
I'm not very knowledgeable about chord notation, so I'm probably doing something wrong.
I don't know how to write these as scale degrees of Gb major either (Tonic, Supertonic, Mediant, etc.), and I was wondering if someone could notate and help me understand this small passage properly in the context of Gb Major, or however it would make sense to normally interpret a passage like this.
Thanks!
Answer: I listened to the beginning of the piece (at least long enough to hit its vi - IV - V - I loop), and we're safer off treating all the first right-hand chords of these first 4 measures as non-chord tones. They sound that way, after all. Heck, this continues to at least Bar 6 (not notated in the question). Note that Bar 7 (also not notated in the question) has a particularly aggravating C♭m7 chord smack dab in the middle of this G flat major piece, implying this introduction is greatly chromatic and tends to follow good voice-leading instead of functional harmony.
Assuming the transcription is accurate (I have only been able to fully confirm the melody and bottommost notes):
Bar 1 ends with an A♭m7 chord.
Bar 2 ends with a B♭7no3 chord. The starting chord of Bar 2 sounds especially chromatic and out-of-place, to the point that its D natural sounds like an alien non-chord tone.
Bar 3 ends with a E♭no3 chord. It could be construed as an E♭m or E♭m7 chord based on notes in the starting chord.
At Beat 3, Bar 4 has a C7♭5no3 chord. It strongly gives off the impression that it is a secondary dominant, thus letting it be interpreted as Cm7♭5 (rooted on the leading tone of the dominant key). Note that the D flat in Beat 4 may be an anticipation, the start of a dominant pedal point that continues into Bar 6, or the closest to a proper resolution that C7♭5no3 chord gets.
Note that the non-notated Bar 5 also ends with an A♭m7 chord, which means that secondary dominant does not resolve properly and the piece opts to start at the beginning of the previous phrase chord-wise instead (a common tactic in more modern music).
Ignoring chromatic starting chords, we can interpret Bars 1-4 as ii7 - iii7 - vi7 - viiø7/V in G flat major.
Comment: Thank you so much for the great explanation! It has helped me to understand this section way better now. I find it very interesting that we can interpret so much of it as non-chord tones, and yet to me it sounds really good.
Answer: Based on the written chords, and without reference to the recording:

Ab7sus4 moving to Ab-7
Bb7#11 moving to Bb7
Eb-7(add13) moving to Eb-7
C-7(add b13) moving to C-7b5

The primary error in your analysis is missing that these are seventh chords, not triads.
The problem in attempting to label them according to function within the key of Gb is that they don't all function with that key. For example, which the first and third chords are the Tonic and (minor) Dominant chords, the chord is measure 2 is called a "secondary" chord, because it operates in relation to the key of Eb minor. Search this site for many posts relating to secondary chords, specifically secondary dominant chords.
To label the chord in measure 4, we would have to know where it's leading.
A (simplified) Roman Numeral Analysis of the first three measures (using I, ii, iii in place of Tonic, Supertonic, Mediant, etc.) would look approximately like this:
ii7  V7/V  v  ??
Answer: The first rule of transcriptions: they are always wrong.
Here's another wrong transcription I made from the audio:

Musical notation is written communication from a person, to a person, for some purpose, in a context. Which aspects do you want to communicate, is it melody, bass, voice-leading, suggestions on how to divide the notes between the left and right hand... what is the point? Is it OK if similar harmonic ideas are executed with different voicings, or even quite different chords? Does it have to be a piano, or would accordion be OK? Do people need to sing this? Who might be the reader of the notation? Where do they have to perform this? Who is the audience?
If I had to give this to a beginner guitarist and flute combo, I'd make the following reduction:

I think many listeners would be happy with this. Don't you think? Why does it have to be in Eb minor anyway, six flats, completely unnecessary for a tune like this.
If the players or the audience or someone are familiar with the original Youtube video, and they're expecting to experience something closer to that, I could add some more detail:

But you must ask yourself: what do you want to achieve by writing something about this tune? Do you want it to sound exactly like the Youtube video? Then you'll have to play the Youtube video. Or do you want someone to create a sound that fools 99.9% of the general public that what they heard was identical to the Youtube video? Does it have to be a piano sound? Why do you care about chord symbols? What is the goal?


OLS Regression versus Neural Network with regression output

Question: I'm looking for a 'not too technical' explanation on how Neural Networks with a regression output differ from running a traditional regressions (eg. OLS) on the data.
Say we want to estimate how a set of independent variables $(x_1, ..., x_n)$ are related to a dependent variable $y$. OLS estimates slope values $b_1,...,b_n$ that minimizes the sum of square errors, thus finding the 'best fit' for a given function, eg:
$$y = b_1x_1 + ... + b_nx_n + \varepsilon$$
If we were to run this data through a neural net with $n$ input nodes and an activation function that outputs a floating point value; how/why do we get a different/'better' estimate than the OLS which simply minimizes the sum squared error of the above function.
Am I correct in thinking that the answer has something to do with the neural net exploring different non-linear combinations of the x-values?
Answer:
Am I correct in thinking that the answer has something to do with the neural net exploring different non-linear combinations of the x-values?

Yes, you are exactly correct. OLS can only learn a linear combination of the input features, whereas a neural network with one or more hidden layers can learn any function of the input features, including non-linear functions. In this sense the neural network is a universal function approximator.
In practice, the neural network's ability to accurately approximate the underlying function of the data will increase with more neurons and more hidden layers. However, increasing the size of the neural network comes with the danger of overfitting the data, in which case it may be ideal to reduce its size again or to add regularization.


mongodb javascript: return document with only matched sub-document

Question: anyone know how to return the document with only matched sub-document in javascript?
e.g. here is the database records:
[
  {"name":"bestbuy",notes:["article IT", "article 2"]},
  {"name":"microsoft",notes:["article IT", "another IT", "article 5"]},
  {"name":"IBM",notes:["article 8", "article 9"]}
]

here is my query:
collection.find({"company.notes":/IT/}, function(err,result){})

result is:
[
  {"name":"bestbuy",notes:["article IT", "article 2"]},
  {"name":"microsoft",notes:["article IT", "another IT", "article 5"]},
]

but my expected result is:
[
  {"name":"bestbuy",notes:["article IT"]},
  {"name":"microsoft",notes:["article IT", "another IT"]}
]

any idea?
thanks
Comment: possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection)
Comment: thanks, it is more javascript specific i think
Answer: You can use aggregation
db.collection.aggregate([
    {$match: {"notes": /IT/}},
    {$unwind: "$notes"},
    {$match: {notes: /IT/}},
    {$group: {_id: '$_id', name: {$first: '$name'}, notes: {$push: '$notes'}}},
    {$project: {'name': 1, 'notes': 1, _id: 0}}
])

yields:
{ "name" : "microsoft", "notes" : [ "article IT", "another IT" ] }
{ "name" : "bestbuy", "notes" : [ "article IT" ] }

Comment: thanks, I did not try because I found the db schema is different, so I updated my question. would you please shed a light on that?
Comment: and another question: why need to use 2 "$match"s?
Comment: @aaron This is the answer to you first question. If your db schema is different accept the answer and **ask** a new question. You should not create a [chameleon](http://meta.stackexchange.com/questions/43478/exit-strategies-for-chameleon-questions) question.
Comment: Then I tried, and the code throws, a headache..
Output is:

    collection opened

    D:\Test\node_modules\mongodb\lib\mongodb\connection\base.js:246
            throw message;
                  ^
    TypeError: object is not a function
        at D:\Test\node_modules\mongodb\lib\mongodb\collection\aggregation.js:317:7
Comment: var results = collection.aggregate([
        {$match: {"notes": /IT/}},
        {$unwind: "$notes"},
        {$match: {notes: /IT/}},
        {$group: {_id: '$_id', name: {$first: '$name'}, notes: {$push: '$notes'}}},
        {$project: {'name': 1, 'notes': 1, _id: 0}}]);
Comment: Hi, @aaron I'm having one question if notes are `zero` then that entire object is not returned! I want it to be returned like `{ "name" : "Microsoft", "notes" : [  ] }` in the result. How to achieve this?


Valores da função retornando undefined em Javascript

Question: var const1 = function (a,b,c,d){
return  (a*b+c-a)/d; {

const1(10, 2, 2, 10, 2);
console.log('a = ' + const1.a);
console.log('b = ' + const1.b);
console.log('c = ' + const1.c);
console.log('d = ' + const1.d);

Por que os valores mostrados através do console.log são retornados como undefined e não como os valores que estão armazenados na variáveis.
Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver pontuação suficiente, acontecerá assim que fizer a aceitação).
Answer: Eles estão undefined porque eles não existem. Você está tentando acessar um objeto que em tese deveria ter esses membros, mas o que você tem é um objeto com um valor numérico único sem membros. Por alguma razão você acha que uma função é um objeto e ela não é, e neste caso tão pouco retorna um objeto.
Este código não faz o menor sentido. Sua função retorna um valor calculado e pode usá-lo, assim:

function calculo(a, b, c, d) {
    return (a * b + c - a) / d;
}

console.log('a = ' + calculo(10, 2, 2, 10, 2));

Coloquei no GitHub para referência futura.
Se o que deseja é retornar 4 operações diferentes, teria que retornar um objeto ou array com os resultados que deseja, porém neste caso teria que definir o que são essas 4 operações para colocar cada resultado em um membro, aí poderia escrever o código acessando do jeito que deseja, o que me parece um pouco esquisito, mas seria algo assim:

function calculo(a, b) {
return { adicao : a + b, subtracao : a - b, multiplicacao : a * b, divisao : a / b, };
}

var resultados = calculo(10, 2, 2, 10, 2);
console.log('adicao = ' + resultados.adicao);
console.log('subtracao = ' + resultados.subtracao);
console.log('multiplicacao = ' + resultados.multiplicacao);
console.log('divisao = ' + resultados.divisao);

Coloquei no GitHub para referência futura.
Por último pode ser que queria criar variáveis e não usar literais (não temos como saber sem a pergunta dar detalhes):

function calculo(a, b, c, d) {
    return (a * b + c - a) / d;
}

var a = 10;
var b = 2;
var c = 2;
var d = 10;
var e = 2;
console.log('a = ' + a);
console.log('b = ' + b);
console.log('c = ' + c);
console.log('d = ' + d);
console.log('resultado = ' + calculo(a, b, c, d, e));
//note que a variável e não é usado em lugar algum, mesmo no original isso é um erro conceitual ainda que não dê erro

Coloquei no GitHub para referência futura.
Na verdade pode ser várias outras coisas que queria fazer.
O fato de não dar nomes significativos no código ajuda você a não entender o que está fazendo e mais ainda para outras pessoas entenderem o que é sua necessidade. Ajuda menos o fato da pergunta não descrever o que quer, apenas diz o que está  errado. Desenvolver software é em primeiro lugar conceituar corretamente o que está fazendo, o código é consequência disso.
Answer: const1 não tem a definição de a, b, c ou d. const1 é uma function que tem como retorno (number) o resultado de uma equação ((a*b+c-a)/d), no caso const1(10, 2, 2, 10, 2); retorna como valor 1.2.
Um exemplo de como atribuir a const1 as a definições de a, b, c ou d:
var const1 = function (a,b,c,d){
    return  {a,b,c,d, resultado: (a*b+c-a)/d};
}
var result = const1(10, 2, 2, 10, 2);

Assim result tem como valor: {a: 10, b: 2, c: 2, d: 10, resultado: 1.2}
console.log('a = ' + result.a); // a = 10
console.log('b = ' + result.b); // b = 2
console.log('c = ' + result.c); // c = 2
console.log('d = ' + result.d); // d = 10
console.log('resultado = ' + result.resultado); // resultado = 1.2


Is it possible to make a custom facet that behaves like a Views grouped filter?

Question: I am moving my user search from vanilla Views to the Search API/Solr backend/Facet API with Views.
On my site, I have a Countries field on the user profile, and I would like to give users the option to choose between two options: from Japan or not from Japan.
In Views, I did this using a grouped filter:

Now I am trying to make a facet that does the same thing.  However, I don't think this is possible from the Facet UI, even with Facet API Bonus installed.  There appears to be no way to provide users with the choice of A or NOT A for a facet that has 100+ values.
How can I implement this A or NOT A search using the Facet API for a specific facet?
Comment: I recently had this on boolean value fields where the default was either "1" or "0" unless you set a label. This was for unique fields though with a facet for each, not ideal in your case as you would need a unique boolean checkbox on/off field for each country.
Answer: Based on this article, I was able to do this with the following code:
<code>/**
 * Implements hook_entity_property_info_alter().
 */
function MYMODULE_entity_property_info_alter(&$info) {
  $info['user']['properties']['agg_nat'] = array(
    'type' => 'text',
    'label' => t('Search API Agg Nationality'),
    'sanitized' => TRUE,
    'getter callback' => 'MYMODULE_search_agg_nat_getter_callback',
  );
}

/*
 * Getter callback for agg nationality property.
 */
function MYMODULE_search_agg_nat_getter_callback($item) {
  // Need to load the user object to get fields
  $account = user_load($item->uid);
  $nationality = $account->field_gen_nationality['und'][0]['iso2'];
  switch ($nationality) {
    case 'JP':
      return 'ja';
    break;
    default:
      return 'en';
    break;
  }
}
</code>


Why does Tom Waits' voice sound the way it does?

Question: Do singers like Waits achieve a "gruff" vocal sound by some sort of technique, or is it just from smoking a lot?
Answer: Tom had this to say in an interview:
"I bark my voice out through a closed throat, pretty much"
http://www.wbur.org/npr/141657227/tom-waits-the-fresh-air-interview
Answer: The smoking didn't hurt, but it's a vocal technique. Check out Captain Beefheart and Howling Wolf. They were both influences to his vocal style.

 Captain Beefheart

 Howlin' Wolf
Answer: It could be HPV (human papilloma virus) which can in a small percentage of men attack the vocal chords. Instead of vocal cords that resemble violin strings, HPV turns them into jello, making clear crisp sounds difficult.


.yaml file for Google Kubernetes engine static website?

Question: I'm trying to set up a static website .yaml file for a Google Kubernetes Engine but it keeps giving me errors. I can't find a single example of doing this on Google or on StackOverflow.
Here's what i have so far...
apiVersion: v1
kind: Service
Namespace: default
name: "rcts_test"
app: rcts
protocol: TCP

I'm getting an error...
error when retrieving current configuration of: [yaml_file_contents] from server for: "app.yaml" resource name may not be empty

On a side note, it's really annoying that I can't cut-and-paste to or from the Google Cloud Shell Terminal.
Comment: what's failing in static site ? deployment or not able to create the service ?
Comment: Check whether you provided a **name** under the **metadata** section. Can you add a **deployment** manifest to your question? Which part is failing, is it deploying the application or creating a service?
Comment: Using Kubernetes was overkill guys. I'm just going to use Google App Engine instead.
Answer: This error might come when the manifest file syntax is not correct. Like missing the metadata, name etc. You can try using the following manifest for your service
apiVersion: v1
kind: Service
metadata:
  name: rcts-test
spec:
  selector:
    app: rcts #Modify as your deployment label
  ports:
    - name: http
      protocol: TCP
      port: 80
      targetPort: 8080

Refer to this document for detailed information about deploying an application in GKE.
Comment: HI @Myuser03 did you get a chance to look into this answer? is it helpful?
Comment: Yes. Very helpful thanks @Dharani Dhar Golladasari. Turns out though, there's a much simpler way of doing this. I should have been using Google App Engine instead for a simple ChatGPT implementation. D'oh.


Why is $F(x)$ continuous at $x=0$?

Question: Let
$$f(x) =
\left\{
 \begin{array}{ll}
  x  & \mbox{if } x < 0 \\
  \sin x & \mbox{if } x \ge 0
 \end{array}
\right.$$
$F(x)$ the anti-derivative should be $\frac{x^2}{2} + C_1$ for $x>0$ and $-\cos x + C_2$ for $x<0$. Now, I've understood that $F(x)$ must be continuous at $x=0$.
Why?
Comment: If it is not continuous at $x=0$ then it is not differentiable at $x=0$ so cannot serve as antiderivative there. Btw, if $f(x)=x$ for $x<0$ then $F(x)=\frac{x^2}{2}+C_1$ for $x<0$. Not for $x>0$ as you say in your question.
Comment: in Other words if function is continuous that is not guarantee for us derivation exist but if derivative is exist in every point of domain function is continuous.
Answer: If you want $F'(x) = f(x)$ for every $x$, then necessarily $F$ has to be continuous because diffentiable functions are continuous.
If you do not work out the constants so that $F$ is continuous at $0$ you would be able to say $F'(x) = x$ for $x < 0$ and $F'(x) = \sin(x)$ for $x > 0$, but it would not be true at $0$.
Another more explicit way to look at this is to compute the limit definition of the derivative and observe that if $F$ is discontinuous at $0$ the right and left limits for the derivative at $0$ will not agree.
Answer: It is a very general result, that
$$
x\to \int_a^x f(u) du
$$
is a continuous function. Here, you are in the case where $f$ is itself continuous. Hence, if
$y<x$:
$$
\left|
\int_a^x f(u) du - \int_a^y f(u) du \right|
= \left|\int_y^x f(u) du \right|
\le \int_y^x |f(u)| du \le M|x-y|
$$
with $M = \sup_{u\in [x,y]} |f(u)|$ (this is defined because $f$ is continuous).
Hence
$$
x\to \int_a^x f(u) du
$$
is Lipschitz continuous.

Why is $F(x)$ continuous at $x=0$?


Automatic type resolving for generics

Question: I want to define an interface for a table column with the following properties:

title: the title of the column
key: the key of a property in a specific model (so I can get the value)
valueFormatter: any function to format the value which returns a string

The valueFormatter-Function should get a parameter, which has the same type as the property (key). So something like this.
export interface Column<T, P extends keyof T> {
  label: string;
  key: P;
  valueFormatter?: (value: T[P]) => string
};

Is there any way to use this in another interface without explicit define the "P" type like this:
export interface Table<T> {
  data: T[];
  columns: Column<T>[];
}

Or: how can I define the Column Interface without the P-Generic and be safe with "key" and "valueFormatter"?
Answer: Personally I'd be inclined to make columns an object with one property per key of T, since you presumably don't want to risk missing one of the columns:
interface Column<T, P extends keyof T> {
  label: string;
  key: P;
  valueFormatter?: (value: T[P]) => string;
}

interface TableWithColumnObject<T> {
  data: T[];
  columnObject: { [K in keyof T]: Column<T, K> };
}

There columnObject is a mapped type, and you'd use it like this:
interface Person {
  name: string;
  age: number;
}

const table1: TableWithColumnObject<Person> = {
  data: [{ name: "Alice", age: 35 }, { name: "Bob", age: 38 }],
  columnObject: {
    name: {
      label: "Name",
      key: "name",
      valueFormatter: name => name
    },
    age: {
      label: "Age",
      key: "age",
      valueFormatter: age => "" + age
    }
  }
};

If you don't care about missing one of the columns (or maybe you want to be able to miss some of the columns or include duplicates) then you can get your desired type by using the columnObject mapped type in a slightly more complicated way:
interface TableWithColumnArray<T> {
  data: T[];
  columnArray: { [K in keyof T]: Column<T, K> }[keyof T][];
}

Here we've taking the mapped type, and looked up its properties, and said we want an array of those.  So for Person, that type looks like Array<Column<Person, "name"> | Column<Person, "age">>.  And we use it like this:
const table2: TableWithColumnArray<Person> = {
  data: [{ name: "Alice", age: 35 }, { name: "Bob", age: 38 }],
  columnArray: [
    {
      label: "Name",
      key: "name",
      valueFormatter: name => name
    },
    {
      label: "Age",
      key: "age",
      valueFormatter: age => "" + age
    }
  ]
};

Hope that helps.  Good luck!
Link to code
Comment: The type `{ [K in keyof T]: Column }` is a [mapped type](https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types) with the same keys as `T` but the property types are mapped.  If we use a [lookup type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types) on the `keyof T` property (so `{...}[keyof T]`), that is the union of all those properties.  And then if we suffx that type with `[]`, we are saying we want an array of those.
Comment: Assuming `T` is `Person`, `{ [K in keyof T]: Column }` becomes `{name: Column; age: Column }[keyof T]` becomes `Column | Column`.  And then `{ [K in keyof T]: Column }[keyof T][]` becomes `Array | Column>`, which is what you want.  If you leave off `[keyof T][]` you are left with the mapped type, which requires named keys.
Comment: Thanks for this very good and detailed answer. I'd go with the second approach in case I don't always want to be forced to define every column for the given data array. Do you have any further informations about the syntax? Especially why I have to define all properties on columnObject if I omit '[keyof T][]'?

Automatic type resolving for generics


how to fix collider offset when using rigging animation with navmesh agent

Question: When i use rigging and navhmesh agent, i have this problem with animation. My collider going a little bit slower from enemy speed as a result, collider stays back. How can i fix it? If i use normal animation without rig builder it works good, but with rigging i can do much better animation.
I already tried to make children-parents etc. I looked everywhere on web and didnt find something to fix it. The only thing that i found, i thing was saying that it was a bug.
Photo of the problem
Answer: I fix it. The solution is simple. It is a bug. If anyone has the same problem you should make all the animation at once. If you make the animation and then try to make any changes, it is going to destroy your animation and bug it.


jQuery post() and reading cookies

Question: I am using jQuery.post() to send data to the server, when the server sends data back to the client, the post() callback is invoked. I know that the data which the server sends has a cookie, and I would like to read it. In order to do so, I used document.cookie within the callback. Printing (alerting) the document.cookie does not hold the cookie, though using Firebug (or Chrome developer tools), the cookie appears.
Is there any way to access the cookie, which was returned by sending data to the server using jQuery.post()?
Answer: If the cookie is set with the HttpOnly flag you cannot read it from client scripts. Make sure that the server doesn't use this flag when setting the cookie if you ever hope to be able to read it from javascript.

jQuery post() and reading cookies


Using predict_proba with sklearn's multiclass SVC

Question: I'm using python's sklearn for multi-class classification (SVC)
When using the predict method, i get very high scores with my dataset,
However, I want to plot ROC curves for each of my classes. That is, I would like to reduce the problem to a in_class/out_of_class problem for each of the classes.
For that i resorted to the predict_proba method of the SVC.
However, I find no correlation between the probabilities given and the predictions.
For instance, for a 5 class classification problem, I may get a prediction of the 1st class, but get a probability vector - [ 0.1, 0.2, 0.5, 0.3, 0.0 ]. The 1st class did not get the highest probability.
Does anyone know how the SVM uses its decision function to make a prediction, or how the predict_proba works on a multi-class problem?
Thanks
Answer: SVC's predict just uses its decision function, which is distance from the hyperplane.
According sklearn documentation, SVC's predict_proba does the following

The probability model is created using cross validation, so the results can be slightly different than those obtained by predict. Also, it will produce meaningless results on very small datasets.

according to their documentation here.
Much more details here. You will have to read Wu et al (2004) paper, mentioned in that section to figure out how exactly they did it. I am not familiar with it.


Exposed Views Combine filter not working

Question: Exposed Views Combine filter is working fine for administrator role, But its showing "Page not found" when I am trying to access with authenticated user role. I rebuild the cache so many times and rechecked the permissions.
For authenticated user its showing result on :
    http://localhost/example/testfilter?combine=&title=abc
But showing "Page not found" on
    http://localhost/example/testfilter?combine=textdata&title=abc
Again for administrator , Both URLs are displaying correct result.
Answer: Check which fields you are combining.
If e.g. you have a user field as combined field, Drupal needs the "Administer users" permission to use this filter.
An issue about this can be found at
https://www.drupal.org/project/drupal/issues/3030696


IPv6 default gateway route disappear after reboot

Question: I'm using Debian Wheezy on a dedicated server which uses IPv4 and IPv6 at the same time.
ifconfig eth0
eth0      Link encap:Ethernet  HWaddr 11:11:11:11:11:11
          inet adr:184.108.40.206  Bcast:184.108.40.206  Masque:255.255.255.0
          adr inet6: fe80::21c:c0ff:feb9:829c/64 Scope:Lien
          adr inet6: 2001:a100:1:bbbb::1/64 Scope:Global
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1544 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2199 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 lg file transmission:1000
          RX bytes:304146 (297.0 KiB)  TX bytes:1376282 (1.3 MiB)

(Several minutes later, the RX dropped counter increases.)
cat /etc/network/interfaces
I first used the "gateway" keyword, but it didn't work, so I then tried to add the route in the file, but it didn't work either.
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
    address 126.96.36.199
    netmask 255.255.255.0
    network 188.8.131.52
    broadcast 18.104.22.168
    gateway 18.104.22.168

iface eth0 inet6 static
    address 2001:a100:1:bbbb::1
    netmask 64
#   gateway 2001:a100:1:bbff:ff:ff:ff:ff
    up ip -6 route add ::/0 via 2001:a100:1:bbff:ff:ff:ff:ff dev eth0
    down ip -6 route del ::/0 via 2001:a100:1:bbff:ff:ff:ff:ff dev eth0

ip -6 route show
These are the routes shown several minutes after rebooting the server.
2001:a100:1:bbbb::/64 dev eth0  proto kernel  metric 256
2001:a100:1:bb00::/56 dev eth0  proto kernel  metric 256  expires 2591959sec
fe80::/64 dev eth0  proto kernel  metric 256
default via fe80::224:c3ff:fe84:400 dev eth0  proto ra  metric 1024  expires 1759sec
default via fe80::224:c3ff:fe84:800 dev eth0  proto ra  metric 1024  expires 1759sec

Questions

Why isn't my default route taken into account (no matter using keyword gateway or ip -6 route add in the /etc/network/interfaces, during boot time?
Note that if I add the route manually, it works perfectly and I can TX and RX to and from the Internet using IPv6. (The problem is to make it automatic.)
What are those strange kernel routes, that will expire? Do I need them? My server is connected directly to the same network as a rooter (2001:a100:1:bbff:ff:ff:ff:ff), which is itself connected directly to the internet.

EDIT
ifdown --force eth0; ifup --verbose eth0;
Configuring interface eth0=eth0 (inet)
run-parts --verbose /etc/network/if-pre-up.d
ip addr add 18.104.22.168/255.255.255.0 broadcast 18.104.22.168       dev eth0 label eth0
ip link set dev eth0   up
 ip route add default via 22.214.171.124  dev eth0
run-parts --verbose /etc/network/if-up.d
run-parts: executing /etc/network/if-up.d/avahi-daemon
run-parts: executing /etc/network/if-up.d/bind9
run-parts: executing /etc/network/if-up.d/mountnfs
run-parts: executing /etc/network/if-up.d/ntpdate
run-parts: executing /etc/network/if-up.d/openssh-server
run-parts: executing /etc/network/if-up.d/openvpn
run-parts: executing /etc/network/if-up.d/postfix
run-parts: executing /etc/network/if-up.d/upstart
Configuring interface eth0=eth0 (inet6)
run-parts --verbose /etc/network/if-pre-up.d
modprobe -q net-pf-10 > /dev/null 2>&1 || true # ignore failure.

sysctl -q -e -w net.ipv6.conf.eth0.autoconf=0
ip link set dev eth0   up
ip -6 addr add 2001:a100:1:bbbb::1/64  dev eth0
 ip -6 route add default via 2001:a100:1:bbff:ff:ff:ff:ff dev eth0
RTNETLINK answers: File exists
Failed to bring up eth0.

Comment: Don't configure a /56 on an interface, always use a /64
Comment: I've checked my config, and I am pretty sure you are getting 2001:a100:1:bb00::/56 gateway address from your router as part of the IPv6 auto-configuration handshake.  I notice you disabled net.ipv6.conf.eth1.autoconf, but you also need to disable net.ipv6.conf.eth1.accept_ra, if you want to completely turn-off IPv6 auto-configuration. (ref: http://superuser.com/questions/33196/how-to-disable-autoconfiguration-on-ipv6-in-linux)
Comment: IPv4 address `220.127.116.11/24` and gateway `184.108.40.206` are on different networks, as are `2001:41D0:2:4F51::1/64` and `2001:a100:1:bbff:ff:ff:ff:ff`. The default routes you see (the `fe80:` addresses) are learned from Router Advertisements (`proto ra`). Your configuration makes no sense, so it is no surprise that it doesn't work...
Comment: I am confused `2001:a100:1:bbff:ff:ff:ff:ff` is not on the same network as `2001:41D0:2:4F51::1`.  Those are different networks.  Can you ping `2001:a100:1:bbff:ff:ff:ff:ff` without the gateway set?
Comment: Sorry, I made a mistake. I just updated. Yes, I can ping it when the route is not set.
Comment: I also just corrected the IPv4 mistakes. There were just obfuscation mistakes!
Comment: If you do an `ifdown --force eth0`, followed by an `ifup --verbose eth0`, do you see any output or errors?
Comment: I just added the output of this command.
Comment: The thing is, I didn't configure it, and don't know where it does come from. This route appears automatically after reboot, as well as other strange routes (which will all expire).
Answer: Possibly these sysctl settings might help you?
net.ipv6.conf.all.autoconf=0
net.ipv6.conf.all.accept_ra=0

Answer: The following configuration in /etc/network/interfaces works for me:
iface eth0 inet6 static
     address 2001:a100:1:bbbb::1
     netmask 64
     up ip -6 route add default via 2001:a100:1:bbff:ff:ff:ff:ff
     down ip -6 route del default via 2001:a100:1:bbff:ff:ff:ff:ff


Kvm poor cpu performance

Question: I have running some Minecraft Servers in a Qemu VM over Libvirt, and the performance is only half good than on real hardware.
Libvirt started the vm over:
<code>/usr/bin/kvm
-S
-M pc-1.1
-cpu SandyBridge,+osxsave,+pdcm,+xtpr,+tm2,+est,+smx,+vmx,+ds_cpl,+monitor,+dtes64,+pbe,+tm,+ht,+ss,+acpi,+ds,+vme
-enable-kvm
-m 28672
-smp 6,sockets=6,cores=1,threads=1
-name Minecraft
-uuid ed7e6bda-2e9f-3895-2ff8-c52c54db588f
-no-user-config
-nodefaults
-chardev socket,id=charmonitor,path=/var/lib/libvirt/qemu/Minecraft.monitor,server,nowait
-mon chardev=charmonitor,id=monitor,mode=control
-rtc base=utc
-no-shutdown
-device piix3-usb-uhci,id=usb,bus=pci.0,addr=0x1.0x2
-drive file=/ssd/vm/Minecraft/boot.img,if=none,id=drive-virtio-disk0,format=raw,cache=writeback
-device virtio-blk-pci,scsi=off,bus=pci.0,addr=0x5,drive=drive-virtio-disk0,id=virtio-disk0,bootindex=1
-drive file=/srv/vm/Minecraft/data.img,if=none,id=drive-virtio-disk1,format=raw
-device virtio-blk-pci,scsi=off,bus=pci.0,addr=0x7,drive=drive-virtio-disk1,id=virtio-disk1
-drive if=none,id=drive-ide0-1-0,readonly=on,format=raw
-device ide-cd,bus=ide.1,unit=0,drive=drive-ide0-1-0,id=ide0-1-0
-netdev tap,fd=20,id=hostnet0
-device virtio-net-pci,netdev=hostnet0,id=net0,mac=52:54:00:49:93:3c,bus=pci.0,addr=0x3
-chardev pty,id=charserial0
-device isa-serial,chardev=charserial0,id=serial0
-device usb-tablet,id=input0
-vnc 127.0.0.1:1
-k de
-vga cirrus
-device intel-hda,id=sound0,bus=pci.0,addr=0x4
-device hda-duplex,id=sound0-codec0,bus=sound0.0,cad=0
-device virtio-balloon-pci,id=balloon0,bus=pci.0,addr=0x6
</code>
Host-CPU: Intel Xeon 1270 V2
Any Ideas to improve the Performance ?
Answer: Well...you're segregating the server hardware across multiple servers. Of course you'd take a performance hit. VMs "force" a cap on resources whereas running multiple instances of the server on the physical hardware gets "balanced" by the system itself.
There's also the overhead of KVM in general.
Comment: I'm run only one VM to be more flexible, so there is no segregation
Comment: If you're running only one VM, why one core? `-smp 6,sockets=6,cores=1,threads=1`

Kvm poor cpu performance


Preserving autograph on a guitar done in sharpie?

Question: I have two guitars that were signed by artists over 20 years ago. I rarely remove them from the case.
One is a white flying V knock off with signatures all over the body.
One is an ESP LTD MV-300, with a dark blue-ish finish.
Both were signed with black sharpie.
How can I protect both?
Answer: I would comment but don't have 50 reps!
Do you know what kind of finish is on the guitars, depending on the type of finish you can just add another coat of that finish or a lacquer that doesn't react with the guitar finish. Some finishes have a colour tint to them but you should use a clear coat to avoid creating a darker tint to the applied area.
Always test out on a scrap piece of wood before applying to your guitars. If in any doubt take it to a Luthier who can advise the best type of lacquer to apply and may do it for you.
Here is some info on various finishes found on guitars https://acousticmusic.org/research/guitar-information/guitar-finishes/
I would expect the flying v would be a poly type finish, but not sure about the ESP.


Prove that the absolute value of the difference of two invariant distributions on a Markov chain is invariant

Question: If we have $a(x)$, $b(x)$ which are invariant distributions on a Markov chain $X_n$ with state space $S$, how can I prove that $|a(x)-b(x)|$ is also invariant?
I know that I must show that:
$\sum_{x \in S} |a(x)-b(x)|p(x,y) = c(y)$
where $p(x,y)$ is the transition function for $X_n$.
So what I did was I partitioned $S$ such that $A \subset S$ where if $a(x) \geq b(x)$ then $x \in A$. So that gets me:
$\sum_{x \in A}a(x)p(x,y) - \sum_{x\in A}b(x)p(x,y) - \sum_{x\in A^c}a(x)p(x,y)+\sum_{x\in A^c}b(x)p(x,y)$
But I do not know where to go from here... My first thought was to combine summations from complementary sets but I am not sure how to do that to make the whole thing either constant or constant as a function of $y$.
Thank you.
Comment: Each irreducible class of your Markov chain has at most one associated "extremal invariant distribution" associated with its time average limiting behavior given you start in a state of that class.  Further, distinct extremal invariant distributions have disjoint support sets.  Then you can prove that any invariant distribution is a convex combination of extremal distributions.
Comment: Also, you do not want to show $\sum_{x \in S} |a(x)-b(x)|p(x,y)=c(y)$, a function of $y$, that is in fact always true since $x$ is a dummy variable that is summed out.  You want to show that, if $d^T$ is the transpose of the vector, then $d^T = d^T P$ (where $P$ is the transition probability matrix).
Comment: In particular, you want to show that $\sum_{x \in S} |a(x)-b(x)|p(x,y) = |a(y)-b(y)|$ for all $y \in S$.
Comment: Well, I have received no feedback so far.  Do you agree that the goal is in fact as described in my last comment?  And that $\sum_{x \in S} |a(x)-b(x)|p(x,y)$ is in fact _always_ a function of $y$ alone (regardless of the properties of $a(x), b(x),p(x,y)$), and so proving it is a function of $y$ alone cannot be the goal?
Answer: For a vector $h = (h_1,…,h_n)$, define $|h|$ as the entrywise absolute value:
$$ |h| = (|h_1|, …, |h_n|) $$
Now,  for example, if $z=(1/2,1/2,0,0,0)$ and $w=(0,0,1,0,0)$ then for any scalars $\alpha, \beta$ we have:
$$ |\alpha z + \beta w| = |\alpha| z + |\beta| w $$
and if $z^T = z^T P$ and $w^T = w^T P$ then:
$$ |\alpha z + \beta w|^T P = |\alpha|z^T P + |\beta| w^T P = |\alpha | z^T + |\beta| w^T = |\alpha z + \beta w|^T $$
This example can be generalized to see that the absolute value of linear combinations of invariant distributions with disjoint support indices are also invariant  under multiplication by $P$.


Formatação de JSON criado em PHP

Question: Estou criando um JSON que precisa de uma formatação especifica em PHP, o problema é que não consigo fazer ele ficar igual meu modelo JSON, segue modelo e meu PHP:
Modelo:
<code>{
  "success":true,
  "message":"",
  "data":
  {
        "id": "lojas_monitoradas",
        "name": "lojas monitoradas",
        "data": {
          "total":1
        },
        "children":[
        {
          "id": "gondolas_monitoradas",
          "name": "gôndolas monitoradas",
          "data": {
            "total":7
          },
          "children":[
          {
            "id": "produtos_total",
            "name": "produtos",
            "data": {
              "total":750
            },
            "children":[
              {
                "id": "produtos_encontrados",
                "name": "produtos encontrados",
                "data": {
                  "total":500,
                  "percentual":0.66
                }
              },
              {
                "id": "produtos_em_ruptura",
                "name": "produtos em ruptura",
                "data": {
                  "total":200,
                  "percentual":0.33
                },
                "children":[

                ]
              }

            ]
          }
          ]
      }
    ]
  }
}
</code>
PHP:
<code>    $json = array("id" => "lojas_monitoradas",
            "name" => "lojas monitoradas",
            "data" => array("total" => $lojas),
            "children" => array(
                "id" => "gondolas_monitoradas",
                "name" => "gôndolas monitoradas",
                "data" => array("total" => $gondolas),
                    "children" => array([
                        "id" => "produtos",
                        "name" => "produtos",
                        "data" => array("total" => $produtos_total),
                        "children" => array([
                            array(
                                "id" => "produtos_encontrados",
                                "name" => "produtos encontrados",
                                "data" => array("total" => $produtos_encontrados, "percentual" => $produtos_encontrados_percentual)
                            ),
                            array(
                                "id" => "produtos_em_ruptura",
                                "name" => "produtos em ruptura",
                                "data" => array("total" => $produtos_em_ruptura, "percentual" => $produtos_em_ruptura_percentual)
                            ),
                            "children" => array([
                                array(
                                    "id" => "produtos_em_ruptura_sistemica",
                                    "name" => "produtos em ruptura sistemica",
                                    "data" => array("total" => $produtos_em_ruptura_sistemica, "percentual" => $produtos_em_ruptura_sistemica_percentual)
                                ),
                                array(
                                    "id" => "produtos_em_ruptura_gondola",
                                    "name" => "produtos em ruptura na gondola",
                                    "data" => array("total" => $produtos_em_ruptura_gondola, "percentual" => $produtos_em_ruptura_gondola_percentual)
                                ),
                                "children" => array([
                                    array(
                                        "id" => "produtos_resolvidos",
                                        "name" => "produtos resolvidos",
                                        "data" => array("total" => $produtos_resolvidos, "percentual" => $produtos_resolvidos_percentual)
                                    ),
                                    array(
                                        "id" => "produtos_aindanaotratados",
                                        "name" => "produtos ainda não tratados",
                                        "data" => array("total" => $produtos_nao_tratados, "percentual" => $produtos_nao_tratados_percentual)
                                    ),
                                    array(
                                        "id" => "produtos_em_transicao",
                                        "name" => "produtos em transição",
                                        "data" => array("total" => $produtos_em_transicao, "percentual" => $produtos_em_transicao_percentual)
                                    ),
                                    "children" => array([
                                        array(
                                            "id" => "produtos_estoquevirtual",
                                            "name" => "produtos com estoque virtual ajustado",
                                            "data" => array("total" => $produtos_estoquevirtual, "percentual" => $produtos_estoquevirtual_percentual)
                                        ),
                                        array(
                                            "id" => "produtos_abastecido",
                                            "name" => "produtos abastecidos",
                                            "data" => array("total" => $produtos_abastecido, "percentual" => $produtos_abastecido_percentual)
                                        ),
                                        array(
                                            "id" => "produtos_alarmefalso",
                                            "name" => "produtos com alarme falso",
                                            "data" => array("total" => $produtos_alarmefalso, "percentual" => $produtos_alarmefalso_percentual)
                                        ),
                                    ]),
                                ]),
                            ]),
                        ]),
                    ]),
                ));
</code>
Retorno do meu PHP:
<code>{
   "success":true,
   "message":"",
   "data":
        "id": "lojas_monitoradas",
        "name": "lojas monitoradas",
        "data": {
            "total": 1
        },
        "children": {
            "id": "gondolas_monitoradas",
            "name": "gôndolas monitoradas",
            "data": {
                "total": 7
            },
            "children": [
                {
                    "id": "produtos",
                    "name": "produtos",
                    "data": {
                        "total": 779
                    },
                    "children": [
                        {
                            "0": {
                                "id": "produtos_encontrados",
                                "name": "produtos encontrados",
                                "data": {
                                    "total": 254,
                                    "percentual": 0.32605905006418
                                }
                            },
                            "1": {
                                "id": "produtos_em_ruptura",
                                "name": "produtos em ruptura",
                                "data": {
                                    "total": 525,
                                    "percentual": 0.67394094993582
                                }
                            },
                            "children": [
                                {
                                    "0": {
                                        "id": "produtos_em_ruptura_sistemica",
                                        "name": "produtos em ruptura sistemica",
                                        "data": {
                                            "total": 99,
                                            "percentual": 0.12708600770218
                                        }
                                    },
                                    "1": {
                                        "id": "produtos_em_ruptura_gondola",
                                        "name": "produtos em ruptura na gondola",
                                        "data": {
                                            "total": 426,
                                            "percentual": 0.54685494223363
                                        }
                                    },
                                    "children": [
                                        {
                                            "0": {
                                                "id": "produtos_resolvidos",
                                                "name": "produtos resolvidos",
                                                "data": {
                                                    "total": 0,
                                                    "percentual": 0
                                                }
                                            },
                                            "1": {
                                                "id": "produtos_aindanaotratados",
                                                "name": "produtos ainda não tratados",
                                                "data": {
                                                    "total": 0,
                                                    "percentual": 0
                                                }
                                            },
                                            "2": {
                                                "id": "produtos_em_transicao",
                                                "name": "produtos em transição",
                                                "data": {
                                                    "total": 0,
                                                    "percentual": 0
                                                }
                                            },
                                            "children": [
                                                [
                                                    {
                                                        "id": "produtos_estoquevirtual",
                                                        "name": "produtos com estoque virtual ajustado",
                                                        "data": {
                                                            "total": 6,
                                                            "percentual": 0.0077021822849807
                                                        }
                                                    },
                                                    {
                                                        "id": "produtos_abastecido",
                                                        "name": "produtos abastecidos",
                                                        "data": {
                                                            "total": 11,
                                                            "percentual": 0.014120667522465
                                                        }
                                                    },
                                                    {
                                                        "id": "produtos_alarmefalso",
                                                        "name": "produtos com alarme falso",
                                                        "data": {
                                                            "total": 4,
                                                            "percentual": 0.0051347881899872
                                                        }
                                                    }
                                                ]
                                            ]
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    }
}
</code>
Note que no meu retorno do PHP ele antes do children está como array associativo e preciso que o retorno seja igual no modelo, podem me ajudar ?
Comment: No caso converter o json para um array PHP te ajudaria? Porque o PHP tem já a função para converter de json para array e de array PHP para json.
Answer: Seu array será:
<code>array (
  'success' => true,
  'message' => '',
  'data' =>
  array (
    'id' => 'lojas_monitoradas',
    'name' => 'lojas monitoradas',
    'data' =>
    array (
      'total' => 1,
    ),
    'children' =>
    array (
      0 =>
      array (
        'id' => 'gondolas_monitoradas',
        'name' => 'gôndolas monitoradas',
        'data' =>
        array (
          'total' => 7,
        ),
        'children' =>
        array (
          0 =>
          array (
            'id' => 'produtos_total',
            'name' => 'produtos',
            'data' =>
            array (
              'total' => 750,
            ),
            'children' =>
            array (
              0 =>
              array (
                'id' => 'produtos_encontrados',
                'name' => 'produtos encontrados',
                'data' =>
                array (
                  'total' => 500,
                  'percentual' => 0.66,
                ),
              ),
              1 =>
              array (
                'id' => 'produtos_em_ruptura',
                'name' => 'produtos em ruptura',
                'data' =>
                array (
                  'total' => 200,
                  'percentual' => 0.33,
                ),
                'children' =>
                array (
                ),
              ),
            ),
          ),
        ),
      ),
    ),
  ),
)
</code>
Utilize este site para fazer a conversão caso queira otimizar estas conversões:
https://wtools.io/convert-json-to-php-array
No php se você tem um array e deseja convertê-lo em json você utiliza  função json_encode passando o array como parâmetro. Se você deseja o contrário, converter de json para array, você utiliza a função json_decode passando como parâmetro a string json e também o parâmetro TRUE.

Formatação de JSON criado em PHP