what are the consequences of using ${-0}$ in exponentiation?

Question: mainly in regards to $10^{-0}$, $-10^{-0}$, $0^{-0}$, $-0^0$ and $-0^{-0}$
i have have tried wolframalpha but i can't get it to interpret ${-0}$ as ${-0}$, it just interprets it as ${0}$
Comment: $-0$ **is** $0$. What else would it be?
Comment: If $-0$ is not $0$ then $0-0$ is not $0$ either.
Comment: I concur with Gerry Myerson. In any algebraic structure, the symbol $-x$ denotes the additive inverse of $x$, and $0$ is the additive identity. The additive inverse of $0$ is $0$, since $0+0=0$, since $0$ is the additive identity. Thus $-0=0$. This is just how it is. It is incoherent to treat $0$ as the additive identity and then say $-0\neq0$.
Comment: This being said, some people write $f(0^-)$ when they really mean $\lim_{\varepsilon \rightarrow 0, \varepsilon > 0} f(\varepsilon)$
Comment: but doesn't the signage affect the outcome?, making say $10^{-0}={-1}$?, that is what im asking.
Comment: Where do you see these notations? Meanings of notations may depend on contexts.
Comment: Are you talking about the [signed zero](https://en.wikipedia.org/wiki/Signed_zero)?
Comment: What on Earth makes you think $10^{-0}=-1$?
Answer: As noted in the comments, the reason Wolfram Alpha interprets $-0$ as $0$ is because $-0$ is $0$. They are one and the same.
$0$ is the identity element of addition: the number such that for any other number $a$, $a + 0 = 0$. There can be only one identity element. Because if $e$ also has this property, then $e + 0 = 0$ by $0$ being an identity, and $e + 0 = e$ by $e$ being an identity. So $e = e + 0 = 0$. They are the same number.
For any number $a$, the number $-a$ is by definition the number such that $a + (-a) = 0$. Again, for a given $a$, there is can be only one such number. For if $a + b = 0$ and $a + c = 0$, then $$c = 0 + c =(b + a) + c = b + (a + c) = b + 0 = b$$So every number has a unique opposite.
But $0 + 0 = 0$, which means that $0$ is the unique number which when added to $0$ results in $0$. By the definition of "$-a$" given above, that means, $-0 = 0$. They are the exact same number.
So

$10^{-0} = 10^0 = 1$.
$-10^{-0} = -(10^{-0}) = -(1) = - 1$, because exponentiation has precedence over negation as operators.
$(-10)^{-0} = (-10)^0 = 1$ because any real number raised to the power of $0$ is $1$ (Okay, some people have a snit about defining $0^0 = 1$, since $0^x = 0$ for all $x > 0$. But I won't get into why they are so, so wrong about that here.)
$0^{-0} = 0^0 = 1$
$(-0)^0 = 0^0 = 1$
$(-0)^{-0} = 0^0 = 1$


XML, XSL not rendering in Chrome, just showing XSL in Firefox

Question: I've got an XML and XSL file that will not render when opened in Chrome, and will simply display the XSL file in Firefox when loaded. Can anyone figure out where I'm missing something? I think I've already tracked down every bracket and backslash that would trip it up.
XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<?xml-stylesheet type="text/xsl" href="Assignment06-PresidentsXSL"?>

<LIST>
<President id="01">
    <Name>George Washington</Name>
    <Term count="2">
        <TermStart>1789</TermStart>
        <TermEnd>1797</TermEnd>
        <TermLength unit="years"> 8 </TermLength>
    </Term>
    <Party>N/A</Party>
    <HomeState>Virginia</HomeState>
</President>

<President id="02">
    <Name>John Adams</Name>
    <Term count="2">
        <TermStart>1797</TermStart>
        <TermEnd>1801</TermEnd>
        <TermLength unit="years"> 8 </TermLength>
    </Term>
    <Party>Federalist</Party>
    <HomeState>Massachusetts</HomeState>
</President>

<President id="03">
    <Name>Thomas Jefferson</Name>
    <Term count="2">
        <TermStart>1801</TermStart>
        <TermEnd>1809</TermEnd>
        <TermLength unit="years"> 8 </TermLength>
    </Term>
    <Party>Republican-Democrat</Party>
    <HomeState>Virginia</HomeState>
</President>

<President id="07">
    <Name>Andrew Jackson</Name>
    <Term count="2">
        <TermStart>1829</TermStart>
        <TermEnd>1837</TermEnd>
        <TermLength unit="years"> 8 </TermLength>
    </Term>
    <Party>Democrat</Party>
    <HomeState>Tennesee</HomeState>
</President>

<President id="09">
    <Name>William Henry Harrison</Name>
    <Term count="1">
        <TermStart>1841</TermStart>
        <TermEnd>1841</TermEnd>
        <TermLength unit="years"> 1 </TermLength>
    </Term>
    <Party>Whig</Party>
    <HomeState>Ohio</HomeState>
</President>

<President id="15">
    <Name>Abraham Lincoln</Name>
    <Term count="2">
        <TermStart>1861</TermStart>
        <TermEnd>1865</TermEnd>
        <TermLength unit="years"> 4 </TermLength>
    </Term>
    <Party>Republican</Party>
    <HomeState>Illinois</HomeState>
</President>
</LIST>

XSL:
<?xml version="1.0"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://ww.w3.org/1999/xsl/Transform">

<xsl:template match="/">

            <TITLE>
            Presidents
            </TITLE>

                President
                Term in office
                Party

        <xsl:for-each select="LIST/President">

                <xsl:value-of select="TermStart"/> - <xsl:value-of select="TermEnd"/>
                <xsl:value-of select="Party"/>

        </xsl:for-each>

</xsl:template>
</xsl:stylesheet>

Answer:
<?xml-stylesheet type="text/xsl" href="Assignment06-PresidentsXSL"?>

Your stylesheet does not end with .xsl. Typcially, a web server will not send the correct response headers in that case, resulting in Chrome not recognizing it as text/xml. You may try to fix this by changing the filename and/or by making sure the proper headers are sent.
Even if you change the filename, and the problem persists, check the web server configuration whether it sets the mime type for this file correctly.
Note: if you are running it from your local disk, it will not work in Chrome, and usually not in Internet Explorer (recent versions), because of security issues. Serve it from a web server instead.
Comment: @fluffywarthog, wait, are you saying you are only trying to do this to _test_ your XML/XSLT? Because really, browsers are the worst when it comes down to XSLT parsing. You can use any other XSLT parser, see the [xslt/info page](http://stackoverflow.com/tags/xslt/info) for a list of available parsers and development environments.
Comment: @fluffywarthog Also, consider XSLT a *server side technology*. Browser-integrated XSLT is nothing you should ever rely on in a production environment, outside of a corporate Intranet maybe, where browser choice is fixed and predictable. For any other situation, process XSLT on the server and send the result to the client.
Comment: That's a pretty solid guess.
Comment: I've tried the filename with and without the extension, I've tried "text/xsl" as well as "application/xml," and it still doesn't change anything. I've also tried applying  `--allow-file-access-from-files` flags to Chrome, without any luck. Can you recommend a good XML testing program or lightweight (Windows) hosting platform?
Comment: @fluffywarthog If you don't need interactive debugging or XSLT 2.0 capabilities, [msxsl.exe](http://www.microsoft.com/en-us/download/details.aspx?id=21714) is a solid command-line XSLT processor.


Modelo de Requisição SOAP E-SOcial

Question: Fala, pessoal, estou com sérios problemas pra executar a requisição SOAP nos servidores do e-social.
Esse é o meu código:
    $pfx = file_get_contents($pfx);
    $certificate = Certificate::readPfx($pfx, $pass);

    $wsdl = 'https://webservices.producaorestrita.esocial.gov.br/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc?WSDL';
    $arquivo_xml = file_get_contents(ROOT_APP_CONTROLLER."rh/esocial/teste.xml");

    $action = 'EnviarLoteEventos';
    $operation = '';
    $parameters = [];
    $namespaces = [];
    $request = htmlentities($arquivo_xml, ENT_COMPAT, 'UTF-8');
    $soapheader = null;

    try {
        $soap = new \NFePHP\Common\Soap\SoapCurl($certificate);
        $response = $soap->send($wsdl, $operation, $action, SOAP_1_1, $parameters, $namespaces, $request, $soapheader);
        print_r($response);

    } catch (Exception $e) {
        print_r($e->getMessage());
    }

Ele me apresenta o seguinte erro no retorno do try catch:
An error occurred while trying to communication via soap,  [https://webservices.producaorestrita.esocial.gov.br/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc?WSDL]HTTP/1.1 100 Continue

HTTP/1.1 415 Cannot process the message because the content type 'application/soap+xml;charset=utf-8;action=EnviarLoteEventos' was not the expected type 'text/xml; charset=utf-8'.
Cache-Control: private
Server: Microsoft-IIS/8.5
Set-Cookie: ASP.NET_SessionId=kfr2yuodygwpey5lnoronfzi; path=/; HttpOnly
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 27 Apr 2018 12:15:18 GMT
Content-Length: 0

Ai eu imaginei que seria somente eu alterar o cabeçalho da requição para text/xml; charset=utf-8', porém, quando eu mudo, ele me apresenta o seguinte erro:
An error occurred while trying to communication via soap,  [https://webservices.producaorestrita.esocial.gov.br/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc?WSDL]HTTP/1.1 100 Continue

HTTP/1.1 400 Bad Request
Cache-Control: private
Server: Microsoft-IIS/8.5
Set-Cookie: ASP.NET_SessionId=k0ii5ocr23zuujcgcuw0xfl2; path=/; HttpOnly
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 27 Apr 2018 12:18:40 GMT
Content-Length: 0

Já estou a 3 dias batendo cabeça nisso, se alguém souber como resolver, me ajude por favor!!!
Answer: A mensagem é bem clara, você está enviando um Content-type inválido, diferente do que o serviço está esperando.
Tente adicionar o Content-type  correto no header da requisição, algo assim:
$soapheader = array("Content-type: text/xml;charset=utf-8",
                    "Accept: text/xml");

Modelo de Requisição SOAP E-SOcial


Python GDAL does not install on Mac OSX El Capitan

Question: I am having several issues when installing pygdal in my Mac OSX El capitan. The procedure is the folowing:

Install GDAL Libraries from http://www.kyngchaos.com/software/frameworks#gdal_complete
pip install gdal

The output is the following:
.
.
.
    extensions/gdal_wrap.cpp:3085:10: fatal error: 'cpl_port.h' file not found

    #include "cpl_port.h"
         ^
2 warnings and 1 error generated.
error: command 'cc' failed with exit status 1

Looks like the installer cannot find the GDAL libraries, or headers (libgdal or gdal-devel in ubuntu).
Where are they placed in OSX?
FYI, the following /Library/Frameworks/GDAL.framework/Programs is into the $PATH variable.
Comment: El Capitan as part of increased security puts system files in different places. A number of mainstream programs have been broken by this. I can not find any file cpl_port.h on my Mac should that help.
Comment: I did a `sudo find / -name cpl_port.h` and got this: `/Library/Frameworks/GDAL.framework/Versions/1.11/Headers/cpl_port.h
/opt/local/include/cpl_port.h`. I added those directories to my PATH but I am still getting the same error.
Comment: Hey !!! Sorry..now it worked !!... I put wrong the path int $PATH.
Comment: Easily done.   Well, if it also works as a solution to your original question, I suggest write it up as an answer to your own question.
Answer: I finally (with a little help from Cam_Aust) solved the problem !!!
Here is what I did:

Find the cp_port.h file in your system: sudo find / -name cpl_port.h, My output was:

/Library/Frameworks/GDAL.framework/Versions/1.11/Headers/cpl_port.h      /opt/local/include/cpl_port.h

Add the resulting folders to your $PATH in your bash init script (~/.bash_login or ~/.zshrc). This worked for me: export PATH=/Library/Frameworks/GDAL.framework/Headers:$PATH
Open a new terminal session or source ~/.zshrc

After this, you can now pip install gdal:
Collecting gdal
Using cached GDAL-2.1.0.tar.gz
Installing collected packages: gdal
Running setup.py install for gdal ... done
Successfully installed gdal-2.1.0

Comment: Excellent, here now for others.
Comment: Despite adding the path variables to my .bash_profile, I still get the 'cpl_port.h' error. Any other suggestions?
Comment: @ToneDaBass - this answer didn't work for me either (macos sierra, python 2.7 in virtualenv), see below for the fix that did work
Answer: After installing the GDAL Libraries from kyngchaos (as mentioned in the question) you should be able to find the python package ready to go.
I cheated and used that:
export PYTHONPATH=$PYTHONPATH:/Library/Frameworks/GDAL.framework/Versions/2.1/Python/2.7/site-packages


What is the lifecycle of Watch App?

Question: There are two subclasses of WKInterfaceController in my Apple Watch app.
The first one is the entrance of another one, their relationships is nextPage with the Interface Builder.
For the awakeWithContext, willActivate and didDeactivate method in each InterfaceController, I printed them all out while watch app launching.
And I got this output:
awakeWithcontext -> First
awakeWithContext -> Second
willActivate -> First
willActivate -> Second
didDeactivate -> Second

and I swipe to the next InterfaceController:
willActivate -> Second
didDeactivate -> First

So now the question is:
Will all the awakeWithContext method of all InterfaceControllers in Watch App be fired as long as launched?
What about the willActivate method?
Answer: The life cycle of watchOS apps is as described below.
awakeWithContext
When initializing the page, awakeWithContext will be called. This is the first method to be called, and no UI is displayed yet.
You should do something like updating model arrays for table views, setting properties, etc in awakeWithContext. This method has a very similar job to initializers in simple classes (init()), but this time in WKInterfaceControllers.
The answer of your first question:

awakeWithContext will be called on ALL PAGES as soon as the watchOS
  app launches.

willActivate
When the interface controller is about to be displayed, willActivate will be called.
You should update label values, actions and anything else related to view elements there.
The answer of your second question:

willActivate will be called on ALL PAGES as soon as the watchOS app
  launches, but in contrast with awakeWithContext, this will be called
  again as soon as you view the controller (in other words, when you
  navigate to that desired interface).

For the first time you launch the app, all controllers' didDeactivate will be called, except the current, and when going to another, its willActivate will be called prior to didDeactivate being called on first one.
So the life cycle is:
1- awakeWithContext of all views
2- willActivate of all views
3- didDeactivate of all views, except the first one (the current one)
And when swiping to the second:
1- willActivate of the second view
2- didDeactivate of the first view
Answer: awakeWithContext is called on initialization. This method will be called on all your pages in your watch app on launch.
willActivate is called when the interface controller is about to be displayed. The reason your second interface controller's willActivate followed by didDeactivate is called, is because it's the next page that can be onscreen. This happens in order to help load the next interface controller with relevant data since it may come on screen soon.
Therefore, if you had a 3rd page interface controller its willActivate followed by didDeactivate would be called when the 2nd interface controller is onscreen.
Apple Doc on willActivate. Page-based navigation on the watch may not explicitly say this, but they always help to read.

What is the lifecycle of Watch App?


How Does $ {L}_{1} $ Regularization Present Itself in Gradient Descent?

Question: If we incorporated $ {L}_{1} $ Loss in gradient descent, how would the update rule change? It's easy to write down the optimization objective. But I'm not sure what to put for the update rule.
Answer: The problem is that the gradient of the norm does not exist at $0$, so you need to be careful
$$
E_{L_1} = E + \lambda\sum_{k=1}^N|\beta_k|
$$
where $E$ is the cost function (E stands for error), which I will assume you already know how to calculate the gradient for.
As for the regularization term, note that if $\beta_k > 0$ then $|\beta_k| = \beta_k$ and the gradient is $+1$, similarly when $\beta_k < 0$ the gradient is $-1$, so in summary
$$
\frac{\partial |\beta_k|}{\partial \beta_l} = {\rm sgn}(\beta_k)\delta_{kl}
$$
so that
$$
\frac{\partial E_{L_1}}{\partial \beta_l} = \frac{\partial E}{\partial \beta_l} + \lambda\sum_{k=1}^N {\rm sgn}(\beta_k)\delta_{kl} = \frac{\partial E}{\partial \beta_l} + \lambda {\rm sgn}(\beta_l)
$$
Answer: It changes the direction you descent towards.
You may have a look at this PDF - Steepest Descent Direction for Various Norms.
It shows the direction for few different norms.
Comment: Thanks for the PDF, did you write that? It's pretty good.
Comment: Yes. Yet I'm not sure when I read you question again that this is what you meant.


UIGraphicsBeginImageContextWithOptions and Multithreading

Question: I'm a bit confused about UIGraphicsBeginImageContextWithOptions and threading because according to UIKit Function Reference UIGraphicsBeginImageContextWithOptions should be called only on the main thread. When called it creates a bitmap-based context, which is ready to be manipulated either with CoreGraphics' functions or with methods like -drawInRect: for UIImage, -drawInRect:withFont: for NSString and so on. For CoreGraphics' drawing everything is clear - you pass a CGContextRef argument that is being manipulated to every function, but the UIKit drawing methods use the current context in the stack. In the release notes of What's New in iOS 4.0 it's written that

Drawing to a graphics context in UIKit is now thread-safe. Specifically:
  - The routines used to access and manipulate the graphics
  context can now correctly handle contexts residing on different
  threads. - String and image drawing is now thread-safe. - Using color and
  font objects in multiple threads is now safe to do.

So far so good. The interesting part is that I have a project, where I do some intensive drawings and create multiple images by creating context with UIGraphicsBeginImageContextWithOptions, but when these operations happened to be more time-consuming and I just moved the drawing in a background thread and when ready display them on the screen with some animations and everything works just fine - no crashes, no leaks. Images draw as they are expected and it seems that UIGraphicsBeginImageContextWithOptions creates a context for the background thread and everything seems to be fine.
So my questions are:
 - Why it's necessary to call UIGraphicsBeginImageContextWithOptions only on the main thread as it seems to be working fine in background?
 - How to use UIImage's -drawInRect: method for example, in a background thread, where I don't have a current context and I can't seem be able create one because I can't call UIGraphicsBeginImageContextWithOptions there?
 - What's is the correct approach to background image manipulation using UIKit's methods (I know I can also use CGBitmapContextCreate, but it neither pushes the created context into the context stack nor I seem to be able to do it myself in order to use -drawInRect: method of UIImage)?
Answer: So, after a couple of days of investigating, how come manipulating the UIKit context is thread-safe and yet you don't seem to be able to create one in a thread other than the main because UIGraphicsBeginImageContextWithOptions "should be called only on the main thread", but still doing so works perfectly fine and after reading some small posts on the subject and discussing it with other guys on Apple's developer forums I can clearly state that, what's said in the documentation about UIGraphicsBeginImageContextWithOptions, UIGraphicsPushContext and UIGraphicsPopContext is WRONG and those methods could be called and the context used in another thread without problems. So UIGraphicsBeginImageContextWithOptions, UIGraphicsPushContext and UIGraphicsPopContext are thread-safe.
Comment: The documentation has been fixed: `In iOS 4 and later, you may call this function from any thread of your app.`
Comment: I can confirm this. This was a documentation error in iOS5 SDK and earlier (if you have access to WWDC 2012 videos, check session 211 and iOS6 SDK docs).
Comment: It's also super important to call UIGraphicsEndImageContext() or things start to get wacky with the CPU.
Answer: Partial answer: Use UIGraphicsPushContext to push your own CG context to the top of the "UIKit context" stack and everything (from that thread, as I interpret Apple's documentation) will paint to that. Don't forget to use UIGraphicsPopContext to pop it from the UIKit context stack.
This applies to all UIKit drawing operations; for example drawing UIImages, like you asked. Push a context, draw, then pop the context.
Comment: I can't recall which and I can't find it, but I saw these things covered in great detail in a WWDC video from 2011 or 2010. My intuition from what I remember is that some of the documentation is subtly misleading and that it will all work out in some sane way if you just follow a few rules from the video. (I wouldn't expect you to bet the farm on this advice, but I think that if you found the video it would answer your questions.)
Comment: That's was one of my ideas, but unfortunately the docs says: `You should call this function from the main thread of your application only.` both for `UIGraphicsPushContext` and `UIGraphicsPopContext`
Comment: I'll take a look now and will write down an answer.


Como se livrar de uma linha vertical no editor do Pycharm

Question: to inciando agr em Python e to usando o pycharm, e logo depois de abrir o editor e tem uma linha na vertical, COMO eu me livro dessa bagaça?
Answer: Aquela linha é pra te auxiliar, afinal, o pycharm tem uma integração com a pep8 e se não me engano, aquilo representa o tamanho máximo que uma linha deve ter de acordo com a pep8, e quando aquela linha é ultrapassada ele mostra formas de quebrar a linha e deixar o código mais clean. De qualquer forma espero ter exclarecido...
"PEP 8, às vezes escrito PEP8 ou PEP-8, é um documento que fornece diretrizes e práticas recomendadas sobre como escrever código Python. ... O foco principal do PEP 8 é melhorar a legibilidade e a consistência do código Python. PEP significa Python Enhancement Proposal, e há vários deles."
Comment: Aaaaaa então é isso, muito obrigado:)
Comment: se ajudou, da um upvote na minha resposta pra ajudar :)


Zyxel P-660H-D1

Question: Can't seem to load the web interface of Zyxel P-660H-D1 ADSL Router, I have to refresh quite a few times and then the web interface appears and sometimes it doesn't.
Also, I can't seem to change the user and Admin password, even when I enter the default password (1234) it won't log-on, but if you don't enter anything and just click login - it will.
anyone with some thoughts on this or faced a similar / same situation with a zyxel.
Have contacted there support but its been 24 hours and no reply as of yet :-)
Will be grateful for your help on this
Kind Regards
Answer: Often a firmware upgrade/downgrade helps with these kind of issues.
Also, do you connect over LAN or over ADSL? Maybe poor line quality could be the cause...
Comment: @rihaturn Just be sure that the firmware is for the *exact* model and for the country you'll use it in.
Comment: @rihaturn it's always a good idea to reset configuration after a firmware upgrade.
Comment: Thanks for the comment, I am accessing it over the lan it is connected on, can't change password, have to refresh alot to get the interface.

any precautions while upgrading the firmware, as some of these types of routers have two types of firmware file or is it just a case of downloading the firmware and uploading it ?

Thanks
Comment: MrShunz, Thank you for the reply, during the firmware install process, will it delete all the existing settings ?

I have downloaded the appropriate firmware, is it just a case of pointing the file from the web interface and that's it ?
Have you flashed / updated a zyxel and any suggestions you may have ?

Thanks so much for your prompt responses.

Zyxel P-660H-D1


Postfix, canonical_classes, and cron mail

Question: I've come across a situation in Postfix where it seems that my configuration is being ignored. I have a home network where the machines are named hostname.fakedomain, and a colo mail host with a real domain example.com. On my home machine, Postfix is configured to rewrite envelope addresses to use the real domain example.com, but to preserve the headers as-is. I keep this setup because I want mail to be delivered to my colo mail server, but I like preserving the headers so that I can see at a glance which machine on my home network sent which mail.
Relevant details:

Arch Linux
Postfix 2.7.2
/etc/postfix/canonical:
@hostname.fakedomain email@example.com
"postconf -n" (partial output):
alias_database = $alias_maps
alias_maps = hash:/etc/postfix/aliases
canonical_classes = envelope_sender, envelope_recipient
canonical_maps = hash:/etc/postfix/canonical
mydestination =
myhostname = hostname.fakedomain
relay_domains =
relayhost = example.com

Normally, this works just fine: local mail on my desktop is delivered to the postmaster account on my mail server, but the headers are not rewritten. However, if the mail as provided to the sendmail binary is missing the From: header, then the header is rewritten to From: root <email@example.com>. Since canonical_classes doesn't include "header_sender", this doesn't seem like it should happen. What I thought would happen is that Postfix would add From: email@example.com. Also, I know that this is due to the canonical map, because if I change the address there to "email@example.com", the headers change as well.
One possible workaround would be to pipe each cron entry's output through /bin/mail, but I would prefer a Postfix configuration fix, so that this works for any mail that is missing a From: header, rather than just cron mail.
Is this actually a bug in Postfix, or am I misunderstanding how canonical_classes should work in this situation?
Answer: Might check these two: remote_header_rewrite_domain and local_header_rewrite_clients
The latter defaults to "permit_inet_interfaces" which, in the description of this other parameter, might give you the answer?
always_add_missing_headers (default: no):
   Always add (Resent-) From:, To:, Date: or Message-ID: headers when not
   present.  Postfix 2.6 and later add these headers only when clients
   match the local_header_rewrite_clients parameter setting.  Earlier
   Postfix versions always add these headers; this may break DKIM
   signatures that cover non-existent headers.**

Even though the default is no, perhaps the local_header_rewrite_clients parameter not being empty is causing this.
However, I might also add the following (from the man page):
The canonical(5) mapping is not to be confused with virtual alias
support or with local aliasing. To change the destination but not the
headers, use the virtual(5) or aliases(5) map instead.**

While what you're doing should work, perhaps using virtual/aliases would work better?
Oh, also just found that there are sender_canonical_classes and recipient_canonical_classes parameters as well. May want to check on those.
Comment: Hmm, apparently you can't format comments here, so I'll put in a separate comment for each point:
Comment: sender_canonical_classes / recipient_canonical_classes: I tried them out and they unfortunately don't fix the problem. It turns out they only apply for the sender_canonical_maps and recipient_canonical_maps.
Comment: remote_header_rewrite_domain / local_header_rewrite_clients: I actually do want it to add the missing headers, I just don't want canonical_maps to rewrite them.
Comment: canonical vs. virtual vs. aliases maps: I had thought canonical maps was the recommended way to accomplish this, but after going over the documentation again, it seems you're correct. However, I'd still like to figure out whether or not this is the intended behavior for Postfix.
Comment: One last comment: a friend also suggested that I use a lightweight SMTP agent such as ssmtp on my home machines. I think that's the best overall solution.


Como mudar o text do select depois que um option for escolhido?

Question: Estou fazendo uma aplicação em que o usuário deve selecionar o seu ddi. Os ddi estão num select dessa forma:
<select name="paises" id="ddi">
     <option value="55" id="bra">Brasil</option>
     <option value="1" id="eua">Eua</option>
</select>

Coloquei duas linhas apenas de exemplo, são várias. Gostaria que quando o usuário selecionasse o país, por exemplo, Brasil o que aparecesse após selecionado fosse o 55 e não o text Brasil. Espero ter conseguindo explicar.
Comment: Qual o problema com algo como `55 - Brasil` ?
Comment: Olá `@lufizi`! Como está o teu JavaScript? Queres que o select mostre o nome do Pais enquanto escolhes e depois de escolhido mude para o numero? ou onde queres mostrar esse  `55`?
Answer: Você pode fazer assim:

ddi.onchange = function() {
  var option = this.querySelector('option:checked');
  option.setAttribute('data-name', option.innerHTML); //essa parte é opcional caso você não queira voltar com os nomes
  option.innerHTML = option.value;

  // Voltar com o valor original dos outros campos (essa parte é opcional caso você não queira voltar com os nomes)
  this.querySelectorAll('option:not(:checked)').forEach(function(option) {
      var name = option.getAttribute('data-name');
      if(name) option.innerHTML = name;
  });
  //
}
<select name="paises" id="ddi">
  <option value="" disabled selected>Selecione</option>
  <option value="55">Brasil</option>
  <option value="1">Eua</option>
</select>

2º Forma (sugerida pelo @TiagoGomes)

ddi.onchange = function() {
  var selectedOption = this.querySelector('option:checked');

  displayValue.innerHTML = selectedOption.value;
  displayValue.value = selectedOption.value;
  this.value = selectedOption.value;
}
<select name="paises" id="ddi">
  <option id="displayValue" value="" selected disabled>Selecione</option>
  <option value="55">Brasil</option>
  <option value="1">Eua</option>
</select>

OBS1: Não acho que essa seja a melhor solução para o seu problema, mas para o jeito que você descreveu, isso vai ajudar.
OBS2: Acho que a forma que o @LucasCosta mencionou no comentário fica melhor!
Comment: Olá, Para o que foi exposto acho que a resposta está bem, mas trocaria uma coisa na logica. Quando selecionar a opção, alterar a option Selecione para o numero e assim a lista dos paises ficava sempre intacta.
Comment: @TiagoGomes faz sentido, vou colocar como uma segunda forma!
Comment: Funcionou, muito obrigada!
Answer: Não sei se entendi exatamente a sua demanda, mas segue abaixo um exemplo funcional e jQuery.

// id do select
var objeto = $("#ddi");

// salva o texto atual para poder ser recuperado
$.each($(objeto).children('option'), function(){
  console.log($(this).text());
  $(this).attr('des', $(this).text());
});
$("#ddi option:selected").text('+' + $('#ddi').val()); // marca o selecionado

// ao mudar a seleção (pode ser ao perder o foco ou da forma que preferir)
$('#ddi').change(function(){
  $("#ddi option").text($("#ddi option").attr('des'));
  $("#ddi option:selected").text('+' + $('#ddi').val());
});

<select name="paises" id="ddi">
         <option value="55"  id="bra">Brasil</option>
         <option value="1"  id="eua">Eua</option>
</select>


Is there geometric interpretation to Skew symmetric coefficient matrix,

Question: We know that the Frenet-Serret equation implies that the coefficient matrix of $\dot t,\dot n,\dot b$  is anti symmetric wrt $t,n,b$. But is there any geometric intuition that immediately gives this result? Thanks!
Answer: Antisymmetric matrices describe linear maps involving oriented planes.  In this case, the plane is the one that describes the instantaneous rotation (and dilation*) of the frame.  The system rotation is described in two parts--a part the $tn$-plane, describing how the curve bends, and a part in the $nb$-plane, describing how the frame twists around the path of the curve.  Non-unit coefficients describe how the frame also dilates or shrinks in these planes.
(*) I say "dilation" here.  That is to say, the "natural" description of a frame of basis vectors is not necessarily a frame of unit vectors, and the coefficients reflect that.
Comment: Sure.  An antisymmetric matrix used as a linear map takes a vector input and returns a vector in the plane that is orthogonal to the original vector's projection onto the plane.  Whether the output vector is clockwise or counterclockwise from the input is dependent on the plane's innate "orientation" (in 3d, this is equivalent to a choice between two opposing normal vectors).  This description is entirely equivalent to taking a normal vector and doing a cross product.
Comment: "Antisymmetric matrices describe linear maps involving oriented planes", that's a new viewpoint I haven't learnt before. Can you describe it more clearly? Thanks for your attention and effort!
Answer: If $v$ is a vector $= [v_x  v_y  v_z]^T$ in the frame described by versors $i, j, k$ then skew-symetric matrix $S(v)$ assigned to the vector $v$ is constructed as follows
$$S(v) = \begin{pmatrix} v \times i \ \ v \times j \ \ v \times k \end{pmatrix}$$ (cross products of vector $v$ with versors)
From this construction geometric properties of skew-symmetric matrix follow, e.g. that columns of $S(v)$ are coplanar, vectors (columns) lie in the plane perpendicular to the vector $v$.
Comment: Welcome. This site uses LaTeX syntax for math: see [math notation guide](http://math.stackexchange.com/help/notation). I edited your answer.


webhdfs open file NullPointerException

Question: I am trying open a file from HDFS throught the webhdfs API. I can create files and upload them, but once I try to open I get this error
{"RemoteException":{"exception":"NullPointerException","javaClassName":"java.lang.NullPointerException","message":null}}

using the following command
curl -i -X GET "http://ec2-xx-xx-xx-xx.eu-west-1.compute.amazonaws.com:50070/webhdfs/v1/tmp/tmp.txt?op=OPEN"

I tried this from multiple machines (from the master node, or remotely) I get the same error. It's running on CHD4.6.
thanks,
Answer: apparently this is a bug in CDH running on Ubuntu 12.04, due to /run mounted with noexec
can be resolved as follows:
sudo mount -o remount,exec /run

webhdfs open file NullPointerException


Question about powers of a number, modulo a prime

Question: I have a feeling this one was already asked, or is so well-known that it hasn't needed asking yet, but I can't find an answer.
I was looking into divisibility of $10^{2n} + 1$, after finding that $10^{2n + 1} + 1$ is always divisible by $11$. After looking into divisibility of powers of numbers by primes generally, I came across a result I thought was interesting, but I can't prove it or find anything else out about it.
It appears to me that:

If $2p + 1$ is an odd prime, and $q$ is coprime to $2p + 1$, then $q^p$ is congruent to either $1$ or $-1$ mod $2p + 1$.

Is this in fact the case?
If so, when is the power congruent to $-1$ and when is it congruent to $1$?
Answer:
Yes. It follows from Fermat's little theorem.
It is $1$ exactly when $q$ is a square mod $p$. This is Euler's criterion.
Comment: Thanks! So, it's definitely really basic, but kind of interesting :-)
Comment: I'm missing something though. I can see that a^2p is congruent to 1, and therefore that a^p is its own inverse. But how do I get from there to see that a^p is 1 or -1? What am I missing?
Comment: @MattGutting, $2p+1$ is a prime that divides $a^{2p}-1=(a^p+1)(a^p-1)$.
Comment: duh. Thanks :-\


Map large Arrays without browser crashing in javascript

Question: so the array i'm trying to map contains about 10000 to 25000 of objects, and all the objects are something like below:
{
 name:"NewYork",
 code:"NY",
 fullName:"NewYork city",
 id:"2",
}

so the way i'm using to map this array is as i map all the other lists, but the problem here is it causes the browser to crash, but i have seen in some other sites, that they easily manage to do the same, without any problem or their browser slowing down, so i was wandering if there is a way to handle this without effecting the performance and the browser crashing, by the way, i map the array like below:
this.state.CitiesList.map(item =>

        {item.name}

)

Comment: Why do you have 25000 objects client side? You need to implement paging where you only show like 100 records at a time and fetch more pages if requested by the user.
Comment: Read about windowing https://blog.logrocket.com/windowing-wars-react-virtualized-vs-react-window/#:~:text=Windowing%20(aka%20virtualizing)%20is%20a,one%20list%20item%20is%20visible.
Answer: Problem with long lists is that react needs to render all the items, which leads to a browser lag.
If you are rendering the entire list, there is a technique called windowing, take a look at react-window. It just render what you see in the viewport. As you scroll it renders other items as well.
Here is a sample of how react-window works:
React Window Example
import { FixedSizeList as List } from 'react-window';

const longList = [/* very long list of items */];

const Row = ({ item, index }) => (

Row {index}

);

const Example = () => (
  <List
    height={150}
    itemCount={1000}
    itemSize={35}
    width={300}
  >
    {longList.map((item, index) => <Row item={item} index={index} /> )}
  </List>
);

You can also have a pagination functionality which prevents from rendering the whole array.


Inequality (extension of triangular inequality?)

Question: I am asking help to prove the following statement.
Let $a_i, b_i, c_i\in\mathbb R$.
Statement: $\big[\sum_{i=0}^n(a_i-b_i)^2\big]^\frac{1}{2}+\big[\sum_{i=0}^n(a_i-c_i)^2\big]^\frac{1}{2}>\big[\sum_{i=0}^n(b_i-c_i)^2\big]^\frac{1}{2}$.
In case it helps, I think that, for $n=1$, this is just the statement that the sum of two sides of a triangle is greater than the other side.
Many thanks.
Comment: This is false for $a_i=1,b_i=c_i=0$
Comment: You have your inequality pointing the wrong way. As it stands, it says that the sum of the lengths of two sides of a triangle is _less_ than the length of the other side.
Comment: Yes. I need to reverse the inequality. It is a typo. It will be ok in 1 second. Thanks for catching it.
Answer: This is the triangle inequality
$$\|b-a\| + \|a-c\| \geqslant \|b-c\|$$
for the Euclidean norm in $\mathbb R^{n+1}$ (because your summation range is $0$ to $n$).
The "$\geqslant$" is needed to include degenerate triangles as well.
Comment: Thanks. Let's see whether I get your idea. Do you mean the following?
 $\big[\sum(b_i-c_i)\big]^\frac{1}{2}=\big[\sum(b_i-a_i+a_i-c_i)\big]^\frac{1}{2}\le\big[\sum(b_i-a_i)+\sum a_i-c_i)\big]^\frac{1}{2}\le$ $\big[\sum(b_i-a_i)\big]^\frac{1}{2}+\big[\sum(a_i-c_i)\big]^\frac{1}{2}$.
Comment: Yes, that is meant, using the Euclidean norm
$\,\|a\| = \sqrt{\langle a|a\rangle} = \sqrt{\sum_i a_i^2}$
Comment: Many thanks. By they way there was a typo in my comment above. I meant to raise every content in round brackets  to the power of 2, as you probably understood.
Comment: All good, glad it helped ;-)  Frankly spoken, I didn't spot the lacking exponents, guess they have inserted themselves on the track from eye to brain.


Trying to scrape table data from a

Question: I'm trying to scrape the table from the following website: https://www.corelogic.com.au/our-data/recent-sales?postcode=5600
Using BeautifulSoup and attempting to 'find' the 'table' returns a NoneType because the table itself actually appears to be a script function that is pulling 90 random records from a secured dataset...
I've tried the following:
url = "https://www.corelogic.com.au/our-data/recent-sales?postcode=5600"

oururl= urllib.request.urlopen(url).read()
soup = BeautifulSoup(oururl)

data = json.loads(soup.find('script', type='function decodeEntities(encodedString)').text)
print(data)

However, I just receive a 403 error.
Can anyone help me to inspect and pull the freely available 90 records from this site's table?
Answer: You are close to your goal and could extract the data and store it in a dataframe like:
import json, requests, re
import pandas as pd

url = 'https://www.corelogic.com.au/our-data/recent-sales?postcode=5600'

jsonData = json.loads(re.search(r'postcodeData = (.*?});', requests.get(url).text).group(1))
pd.DataFrame(jsonData['data'][0]['properties'])

Trying to scrape table data from a


String manipulation using MD5 in rails 3

Question: I have a big string
approx 4000 characters

i want encrypt and decypt it using MD5 because of i want to do convert in a small string please help me a lot of finding i found Base64 but it is not our solution please any one help me
my_string="abcdefghhhhhhhhhhhhhhhhhhhhhh"
      Base64.encode64(my_string)

it gives us very lengthy string.
Comment: I think we can only encrypt the string using MD5 not decrypt.
Comment: any another way to large string into small string using any conversion
Comment: Please decrypt your question first by adding punctuations in appropriate positions and doing appropriate capitalization.
Comment: It is good you have a correct answer now. However the question (and title) make no sense. Currently your question looks most like a request for help using MD5, but the accepted answer is something different. If you have time to correct that and explain what you really needed, that would be good. It is fine to mention that you tried MD5 and Base64, even though they are the wrong tools to do what you wanted, but please at least remove the words "encrypt" and "decrypt", and put your *real need* into the title.
Answer: Encrypting a string will not make it smaller, it will at best be the same length. I think what you are looking for is a way to compress your string. That aside, MD5 is a one-way hashing algorithm, that means that it is designed, so there is now way of recovering the source string (it turns out that it was designed rather poorly).
Answer: MD5 is a one-way hash, you can't decrypt it.
To encode a string use Digest::MD5.hexdigest('foobar') but for most purposes I'd say use a better hashing algorithm; MD5 has been broken for a long time.
Comment: thanks for this answer but my main problem is that i have a big string and iwant to convert in a small string by the conversion any another way instead of md5


Heavy metal: how to play and "arc down" shown in tablature

Question: I'm currently mastering a Troy Stetina "Heavy Metal rhythm" course, but having troubles with one of the exercises. It has an "half arc pointed down" sybmol after a note on 12th fret, what does it mean? If it was pointed up, I would think that it is a bend, but on the mp3 file, that came along with a book, it sounds more like a long slide down. I just can't reproduce the sound, no matter what I do.

This is how it sounds:

How is this technique called and how do you play this? I would appreciate a link to youtube video with an example, if one exists.
Answer: Until I listened to your example, I wasn't sure if it would be a divebomb (whammy bar pushed all the way down until the strings don't sound any more) or a slide, but in this case it's actually just a slide down from the 12th fret to somewhere near the 1st fret (can't quite tell which fret it stops at but it doesn't sound like it goes all the way)
What happens when you try the slide? If it tapers off too soon, try higher gain, or a compressor before your distortion pedal.


Hyper-V 2012 R2 cluster functional level missing

Question: I have a 4 node Windows Server 2012 R2 Datacenter Hyper-V cluster that was built from scratch. Everything is working well but when I tried adding a Windows Server 2016 node to the cluster it gave "Different OS level" error. When I type Get-Cluster | select ClusterFunctionalLevel there is no level returned. I tried the command Update-ClusterFunctionalLevel and it said the command is not recognized.
Any idea what I am missing?
Answer: On the server 2016 box open fail over cluster manager and do a "connect to cluster". That should work, you can not add the 2016 server from a 2012r2 server, not sure why, but thats what microsoft's documentation says.
https://docs.microsoft.com/en-us/windows-server/failover-clustering/cluster-operating-system-rolling-upgrade
Comment: Using the 2016 server cluster manager, I was able to join the 2016 node to the 2012 r2 cluster. It won't let me migrate any of the vm's to the 2016 node. Tried using both the 2012 & 2016 cluster manager.
Comment: Update: Typo in network settings on 2016 node. Corrected and all is working correctly. Thanks for the assistance!


Can LESS generate images like Compass (Sass)?

Question: I'm comparing capabilities of LESS with Compass(Sass)
To make cross browser transparent background in Compass we can use this method http://aaronrussell.co.uk/legacy/cross-browser-rgba-support/ which can generate transparent image too along with rgba code.

compass-rgbapng plugin for providing cross-browser compatible RGBA
  support by creating transparent PNGs on the fly for browsers that
  don't support RGBA. Uses the pure Ruby ChunkyPNG library for hassle
  free install and deployment.

sudo gem install compass-rgbapng

require "rgbapng"

@import "rgbapng";

background: url('/images/rgbapng/000000bf.png?1282127952');
background: rgba(0, 0, 0, 0.75);

Is it possible to do same with LESS? I think not because LESS is based on JavaScript and JavaScript is not as capable as ruby. Am i right?
Comment: _JavaScript is not as capable as ruby_ is not something I would agree with at all.  More the the point is if a tool already exists for this  in LESS/JS similar to the one you mention for SASS/Ruby.
Comment: @AlexWayne - It uses the pure Ruby ChunkyPNG library
Comment: Nitpicking here but JavaScript is a turing complete language so it's disingenuous to say it's not as capable. The browser implementation of JavaScript cannot generate images to my knowledge but you are more than able to generate images using a server side implementation such as NodeJs.
Comment: Actually, you can generate an image with pure JS. **You just need one tiny browser feature, Data URLs**. Files are just an array of bytes with a defined structure, and with Javascript you can work with binary strings to build any kind of structure you want. The only problem is that from Javascript you cannot generate file references, except with the use of Data URLs. The problem would be to ensure support for Data URLs on all IE versions targeted, and the fact that **this solution is kind of horrible, as it introduces A LOT of overhead** to make just a fancy solid-color transparent background.
Answer: Short answer: no.
Long answer: not with just the LESS library.
You can combine the server side plugin with a LESS script. You can make a LESS class that generates the CSS style:
background: url('/images/rgbapng/000000bf.png?1282127952');
background: rgba(0, 0, 0, 0.75);

I'm not sure how that library works, but the only important part i can see is the name of the PNG being the RGBA value hex-encoded. Being just that, I've made a LESS script that allows using that URL schema to take advantage of the server-side image builder:
@compass-url: '/images/rgbapng/';

.rgba-background(@r, @g, @b, @a) {
    @date-nocache: `new Date().getTime().toString()`;
    @colorInt: floor(@a * 255) + 256 * (@b + (256 * (@g + 256 * @r)));
    @colorHex: `(parseInt("@{colorInt}") + Math.pow(256,4)).toString(16).slice(1,9)`;

    background: "@{compass-url}@{colorHex}.png?@{date-nocache}";
    background: rgba(@r, @g, @b, @a);
}

This scripts creates the class/function rgba-background in LESS, allowing you to anotate your LESS class like:
.yourClass {
    .rgba-background(0,0,0,0.75);
}

If you plan to use this accross multiple less scripts, it would be adviceable to extract it to another file, and use the @import directive wherever you want to use it.
If the URL generated is more complex that i thought, please provide some additional info on how to build that URL, so we can see if this can be resolved using LESS.


What does dehydration mean in the context of data loading?

Question: There are a few threads which discuss the meaning of data hydration.
But I can't find any definitions of data dehydration.
I can see three possible meanings

1) Extracting the current state of an object
2) Clearing the state of an object
3) Both 1) and 2)

EDIT
This is not a duplicate of other threads where the meaning of hydration is discussed. This question is about dehydration.
Comment: @Enigmativity This is NOT a duplicate. The linked thread only references hydration. Not dehydration.
Comment: What about the question in the subject line is unclear to you? I cannot imagine a more clearly stated question.
Comment: Possible duplicate of [What does it mean to hydrate an object?](https://stackoverflow.com/questions/6991135/what-does-it-mean-to-hydrate-an-object)
Comment: I cannot see any detail in your question that helps distinguish this question. Please read [ask]. If I were to edit this question to remove unnecessary text I would delete everything in the content. Please provide a suitable description of what you are asking.
Comment: The title is all that I had to go on, which is why I marked it as a duplicate.
Answer: Dehydration is simply the opposite of hydration. In context of data loading, given you have an API that reads data from an ORM. The process to transform the ORM object tree into a JSON with primitive types in it, is dehydration. The extraction of data from the hydrated objects.
As you already mentioned:

Extracting the current state of an object
Answer: Data dehydration usually refers to the process of storing db data off in a compressed file. The data is then removed from the db (and as such is inaccessible)
The process of rehydration is loading the stored data into the original or ancillary table so that it can be worked with.


click on link paste to text area jQuery

Question: Hey guys I'm trying to make it so when you click on the existing a href= it will paste the inner text to the textarea. Though of course if click that the a href it'll lead to link so i made it so it'll take out the href. So far I have this code
<code>$(function(){
$(".username a").removeAttr("href").css("cursor","pointer");
var $paste = $('div.post h4 .username a span');
  $paste.click('')
});
</code>
Ok I guess thats a good start lol. Problem to me is, I don't know how to add onClick="" or whatever to make the function work on click ya know? or would .click  work in general. of course i would need a function in the .click area. I don't know what to place in there to create what text is inside the a tag... Can someone help me, if you use .append or or anything can you also give an explanation, I'm trying to learn as I go.
Comment: Instead of removing the href, just `e.preventDefault();` in the click function. This tells jQuery to stop the event propogation and it will never reach the page switching code. http://api.jquery.com/event.preventDefault/
Comment: ok...? haha Ya lost me TheZ.So .click('e.preventDefault()')? how would I make so it would paste the text inside to the textarea? like {username} I would want that text to go into the textarea
Answer: <code>$(function(){
    $('.username a').click(function(){ return false; });
    $('.username a').one('click', function(e){
             //e is short for event
        e.preventDefault(); //will no longer follow through
        //You want to append the text of the anchor link into the textarea.

        var innerTxt = $(this).text();
        //need to trim whitespace from the string
        innerTxt = $.trim(innerTxt);

        var $obj= $('textarea'); //replace this with textarea selector
        $obj.val(
           $obj.val()+'\n@'+innerTxt
        );
    });
});
</code>
Comment: I like the above coding. Seems nice, jsFiddle nicely done, and you explained to me what each does (some I'm still curious lol.) but when in the jsFiddle, click once works, click twice adds TWO more not just one...
Comment: @user1760670 that's fine, that's an easy fix. you just want it to happen once?
Comment: Also if I get this to work on my site, is it possible to do this

'@'+innerText+':'  ??? so when clicked it will be as so @Inner Text:
Comment: more like that http://jsfiddle.net/LWGhJ/1/  how do I get it to have no spaces? when click it shows @ Inner Text : I want to get rid of the spaces here @Inner Text:   and will this work if there are multiple links of the section I want .username a? And it doesnt need to be once, it just when you clicked once it pasted once, then when you click again it had three altogether Inner Text Inner Text Inner Text...
Comment: Hahaha I see why it had the space, it was because the generated html had the space in it. Nevermind. I got it working fine. Just need to know if it'll work with multiple .username a and such?
Comment: Each generated element will only be allowed one click. The downside is that when you're done with it the click function will follow through again. Also, you should combat the whitespace issue by calling `innerTxt = $.trim(innerTxt);` This will ensure any leading/trailing whitespace is trimmed. Let me know if you want a solution to the `.one()` follow-through issue.
Comment: I would :) i see how you did the .one() in your jsfiddle I rewrote to be back to .click because I saw that once .one() ran it went back to a href tag. Though once go through it created the same issue of creating a duplicate. Please see http://jsfiddle.net/LWGhJ/2/  and click every tag once
Comment: @user1760670 Just use the new jsFiddle. I've already handled the `.one()` issue.
Comment: Only have 13 points so cant go into chat. Same issue persist, when clicking more than one it duplicates a main one. How to ensure that this does not happen?
Comment: @user1760670 - [Just like this](http://jsfiddle.net/P2Nuv/). We'll just remove the substring and selection methods and keep it simple.
Comment: Love that one much better :) Though when going to my website it is not working for some reason...

Mr.EasyBB
Comment: Love that one much better :) Though when going to my website it is not working for some reason...

Mr.EasyBB

Is html where a is located

textarea id and class name are #text_editor_textarea .quick_reply_textarea
Comment: my bad on the double post. it wouldn't let me edit haha. It keeps being able to click to the actual href :/
Comment: @user1760670 Are you sure that the jQuery library is loading properly? What browser are you using, we should check the console for errors.
Comment: We should :) though Im not sure if this is helpful but the a href is generated through php {postrow.display.POSTERNAME} though i dont think it should matter since we are editing the generated html. Two syntaxErrors. P.S this code is to help another code for tagging. Uncaught SyntaxError: Unexpected token ILLEGAL
Comment: @user1760670 The error you're experiencing is not in my code.
Comment: Ok I got rid of one error, your code is still experiencing some sort of syntax error. Im trying to figure it out now, maybe I messed something up
Comment: Hey Ohgodwhy could you come to my website, there is a chatroom, and it would be easier for you to see what is going on. the consoleError was from me adding this $('h4.username a') for some reason it doesnt like that haha.
Comment: www.easybbtutorials.forumotion.com   you'll have to sign up if thats not a problem to see the chatroom
Comment: I see you created an account. :) Chat is at bottom of page ill be waiting
Answer: Try this
<code>$(".username a").click(function(e){
    //DO Wathever you want here
    e.preventDefault();
})
</code>

click on link paste to text area jQuery


Windows Server 2008: "not genuine" - performance impact?

Question: Is it possible that not activating a copy of Windows Server 2008 might have a performance impact, specifically over TCP?
Background:

I've been provided with a Windows Server 2008 Oracle VM. It displays "This copy of Windows is not genuine". I've submitted a request for it to be activated to the system administrator, but the request is currently being processed.
Local performance is not an issue, but simple SQL statements executed against a remote Oracle DB instance (on the same network, in the same IP range) via SQL*Plus take an exceptionally long time to complete. N.B. it's not the DB server - that's been tested extensively.
The system administrator has run exactly the same queries on two other Windows Server 2008 Oracle VMs (clones) in the same IP range. One of the other machines demonstrated the same terrible performance, but the other did not. The only reported difference is that Windows on the machine without any issues is already activated.

I'm highly skeptical: this looks like a big red herring. I think there must be other differences in configuration which have not yet been identified.
Is it remotely possible that this is due to Windows activation?!
EDIT I:
Apologies for not being more specific. It's on Oracle VM, not VMware. Do you think the VMware articles might still be relevant?
I can't add comments yet (!) but thanks a lot for the suggestions, I'll get the system admin. to give them a try.
EDIT II:
Power Plan was set to balanced, but changing it to High Performance has made no difference.
Activating windows has made no difference - fundamentally this was not the issue.
Answer: Yes, it is REMOTELY possible - but that is really so remotely I dont think there are practical  chances of that. Would be a driver for example that readcts different when not activated (on purpose) and I am not aware of that.
So, by all means - no. SOmething is really bad here configuratoin wise and it is not the activation.
Answer: I'd agree with TomTom, that Windows not being activated would only be remotely possible, but just to rule it out, are you able rearm it so that it turns back to an evaluation version using:
slmgr.vbs –rearm

just to rule it out?
Moving away from looking at the activation being a cause, I have had, what sounds like, an almost identical performance problems on a Windows 2008 server running under ESXi connecting to an Oracle database via JBoss and SQL*Plus the only real difference being that my Oracle instance was accessed over our WAN.
I ended up eventually resolving these problems following the instructions in VMware KB 2008925. Specifically modifying the Power Plan from Balanced to High Performance. I'd also previously tried disabling TCO (VMWare KB 1009517) using
netsh int tcp set global chimney=disabled

which didn't seem to make a difference, I'm not ruling out a combination of the two helping as I didn't undo it before changing the Power Plan.
Comment: with regards to your edit to the original question, disabling TCO may not be as relevant due to it specifically mentioning the vmware network drivers, but I'd still consider the Power Plan settings as it should be VM agnostic. I've not used OracleVM, so that's purely hypothetical, but won't do any harm.


Why should I avoid using Java Label Statements?

Question: Everywhere across the internet people say that you should avoid using label statements in java. However, I find them very useful in some cases, namely nested loops.
I cannot find satisfactory answers as to why not to use them. I think that alternatives to labels often reduce either readability, or performance, or both.
So what makes labeled break and continue statements so bad?
Comment: Seems to be a duplicate. Check this
Comment: http://stackoverflow.com/questions/46496/
Comment: I think this would be a much more interesting discussion if you provided some code showing a, in your oppinion, just case for using a label.
Comment: No reason at all. When you need them, you need them. Probably some trace of *goto*-aversion, but not really related.
Answer: Labels are perfectly okay to break out of nested for-loops.

PS: personally, I'd suggest (and I am in accordance with Kent Beck on this, see his implementation patterns book) to put the nested loops in a separate method and then break out with return but that will cast the anger of the "single return point" folks upon me. Internet, oh, internet.
Comment: +1 for good advice and especially for scorn on religious nonsense.
Answer: I find both labelled breaks and continue statements to be completely unnecessary.  It's just a style thing.  There are other ways to achieve the same results and many people prefer those.
Answer: Most common argument is that they're hard to interpret for starters. Another argument is that (too many) nested loops are considered bad practice; in other words, when you see a label, then there's almost certain a nested loop and that makes the label thus implicitly bad. Common practice is that nested loops are refactored into a method. This should improve maintainability and other things like that. However, if the nested loop isn't doing other things than the obvious thing in only a few lines of code, then it's in my opinion perfectly affordable.
Answer: No need to avoid labels as long as the method does just one thing, one thing only and does it well.
However, if there is a need for labelled breaks and continue statements just do a quick mental check if the method is still cohesive enough.


test on a proportion with the hypotheses

Question: Suppose you are doing a test on a proportion with the hypotheses
$H_0$: p = 0.4,
$H_a$: p $\neq$ 0.4.
In addition, you plan to use a sample of 50 values, and a significance level of $\alpha$ = 0.05.
Find $\beta(0.44)$, the probability of making a type II error given that the true population proportion is p = 0.44.
I found 0.26421< p< 0.53579 and -2.56< z<1.42 but it seems to be wrong. Could someone helps me please?
Answer: $\beta$=Type-II error=$P(accept~H_0|H_0~is~false)$
$0.26421< p< 0.53579$ is 95% CI
Now, find the probability of when you accept p, if true p=0.44.


Using Bokeh, Jupyter Notebook and Pelican for interactive plots

Question: I created a jupyter notebook with interactive plots using Bokeh.
An example notebook looks like this:
import pandas as pd
import numpy as np
from bokeh.plotting import figure, show
from bokeh.charts import ColumnDataSource
from bokeh.io import output_file
from bokeh.models import HoverTool

df = pd.DataFrame(np.random.normal(0,5,(100,2)),columns=['x','y'])

output_notebook()

source = ColumnDataSource(df)
hover = HoverTool(
        tooltips=[
            ("x", "@x"),
            ("y", "@y"),
        ]
    )
p = figure(plot_width=800, plot_height=500, tools=[hover])

p.circle('x', 'y', size=7, fill_alpha=0.5,source=source)

show(p)

Things work on the notebook itself and the figure is interactive.
I'm using pelican static website generator with the pelican-ipynb plugin (https://github.com/danielfrg/pelican-ipynb) in order to convert the notebook to html. When the html is created the Bokeh plots don't show up. I can't seem to figure out how to get an html with the interactive Bokeh plots. I inspected the html and there is nothing after the show(p) line.
How do I get the Bokeh plot work with pelican?
Answer: Bokeh uses JavaScript for the client-side of the interactive part (BokehJS) and that JS code is not embedded when you export the notebook to HTML ouside Bokeh.
You need to export the Bokeh code to HTML using Bokeh's own functions to generate standalone HTML.
To generate the HTML, simply add to your code:
from bokeh.resources import CDN
from bokeh.embed import file_html
p_html = file_html(p, CDN)

For an example, see this Jupyter Notebook with your original code and the generated HTML (too long to embed it here in SO, about 45 K characters for your simple example).
Comment: Thanks! I actually just figured out that if I add:     '

' to the html it works well with the pelican plugin


Quantiles in ols/cph

Question: I need to conduct regression analyses with continuous and categorised data (as the latter is common in my field). So far, I used to do this as follows:
q <- lm(ep ~ cut2(exposure, g=5), data=data)

When I use the functions in the rms package, this doesn't seem to work:
q <- ols(ep ~ cut2(exposure, g=5), data=data)

and results in an error message (subscript out of bounds). It does work fine if I pre-define the quantiles, but this causes problems in the scripts I use.
Is there an alternative?
Answer: The rms package wants you to handle complex transformations by creating a new variable in your data frame.  Although simple transformations are handled in-line (e.g., log(x)), you'll need to create a variable for the result of cut2.
Comment: Yes.  But note that analyzing quintiles of a continuous variable is not really valid - it leads to misleading estimates and inefficiency.  Use this approach only for educational purposes.  This should **never** be the primary analysis.
Comment: I've never had a paper rejected to used only continuous analyses.  The quantile approach is wrong on so many levels.  Just to mention two: the outer quintiles will be very heterogeneous, and the definition of your variable will come from sample demographics and have nothing to do with the intrinsic meaning of the variable.  It's a lose-lose situation.  See my BBR and RMS notes and checklist for authors [here](http://fharrell.com/links) for more information.
Comment: Splines are actually much easier to interpret and don't assume piecewise flat relationships.  You can explain this as "I did a test of goodness of fit of the model to the data and the quintile approach failed the test".  Also tell the editor that how many friends and neighbors who are like you is not what predicts your outcomes; it's YOUR weight.
Comment: Thank you! Would I do the same when using `fit.mult.impute`, i.e. create the quintiles before imputation (and analysis)?
Comment: Unfortunately using quintiles is so common that reviewers will probably not accept not having them. But I will try.
Comment: I agree completely - but you're well known and respected, with considerable experience and expertise.

I haven't found any paper in a mainstream journal of my field (nutrition), where quantiles were not the main results (and perhaps a spline-figure to accompany it). Most readers are used to quantiles and many would struggle to interpret splines (which would not give the same "accurate" numbers to interpret).

Quantiles in ols/cph


IIS Redirection - command line

Question: I have a website say www.mywebsite.com/demo . When ever if anyone requests this site, i want to navigate to another website www.myanotherwebsite.com . I know that this can be done in IIS by using the HTTP Redirect feature. But since i want to do this for different websites, I would like to write a bat file which would run the command to set the redirect url for a website. Can anyone please help me how to set the redirection URL through command line?
Edit: I'm using IIS 7
Answer: Look at this PowerShell script
http://forums.iis.net/t/1162778.aspx
<code>Set-WebConfiguration system.webServer/httpRedirect "IIS:\sites\Default Web Site" -Value @{enabled="true";destination="domain.com";exactDestination="true";httpResponseStatus="Permanent"}
</code>

IIS Redirection - command line


Prove Newtons trident is an algebraic curve

Question: I was working on a problem where I have two curves $C_1 \longleftrightarrow x^2-y=0$ and $C_2 \longleftrightarrow xy-1=0$ in $\mathbb{A}^2$ (so a parabola and a hyperbola). Now consider the connection lines from a point of $C_1$ to a point of $C_2$ parallel to the y-axis. Then I have to show that the points lying on the middle of these lines form an algebraic curve. The problem also says that this curve is called Newtons trident.
I made a sketch so I could see how the curve lies inbetween $C_1$ and $C_2$. The left side of the y-axis is trivial, since it follows both asymptotes. For the right side I am a little confused. Because how i look at is my new curve (let's call it $C$) has to go through the intersection of $C_1$ and $C_2$. But if I look up Newtons trident, it does not go through this intersection. Why is that the case?
My second question is how can I find the formule for this algebraic curve. I suppose I can take x fixed and then look at the middle of both y-values. But I would need absolute value for that, right? So I have no idea how to do this. Or should I first go to $ \mathbb{C}P^2$, then I get
$$ f_1(x_0,x_1,x_2)=x_1^2-x_0x_2$$
$$ f_2(x_0,x_1,x_2)=x_1x_2-x_0^2$$
Could someone please help me? Thanks in advance!
Comment: For the first question, I looked up a trident here: https://mathshistory.st-andrews.ac.uk/Curves/Trident/
From my sketch, this is just a reflected version (w.r.t. $y$-axis) of the curve you should get for this question.
Answer: I think the easiest way to find an equation of the curve in this case is by parametrizing it.
We parametrize the parabola by $(t, t^2)$ and hyperbola by $(t,1/t)$. So the midpoints are parametrized by
$$(t, \frac{t^2 + 1/t}{2}) = (t, \frac{t^3 + 1}{2t})$$
and it can be readily seen that the equation for these points is
$$2xy = x^3 + 1$$
In general, you could compute the resultant to work out the equation of parametrized curve, see this question for example.
The algebraic curve $2xy = x^3 + 1$ is a particular case of trident curve (which in general have the form $xy+ax^{3}+bx^{2}+cx=d$, according to wikipedia)
Comment: @Oopsilon, the equation $2xy = x^3 +1$ certainly contains the point $(1,1)$ which, as you correctly mentioned, is the intersection of $C_1$ and $C_2$. As I said, the graph I cited doesn't contain this point, because it is "reflected" about the $y$ axis. And if you look at the general equation, the reflection about the $y$ axis, i.e. $x \mapsto -x$ preserves this general form.
Comment: Thank you! I still have a question. You can see that $(1,1)$ is a point on $C_1$ and on $C_2$. So then the middle of the connection lines between those two points, is just the point $(1,1)$ itself, right? But I see in your formula (and in the graph you cited in your other remark) that $C$ does not contain $(1,1)$, how can this be the case? I would think $C$ would intersect both curves in the point $(1,1)$.
Comment: Also is it possible to solve this question without using a parametrization? I can see the parametrization does make it easier.


Sample size calculation for expected percentage change in continuous score

Question: I know how to conduct a sample size calculation comparing two independent means in a randomized controlled trial. However, I am confused by the following situation.
There are 2 groups: intervention (IG) and control (CG).
The outcome of interest is a severity score (0-100, the higher the worse).
The baseline score in both groups is 20. Within a year the score increases by 5 in the general population. The intervention is supposed to cut the score by 50%.
So, given a baseline of 20, the IG is expected to have a score of 22.5 after a year, while the CG is expected to have a score of 25.
Let's assume the standard deviation of the score in both groups is 10. Aiming for an alpha of 5% (two-sided test) and a power of 80% what sample size is needed to identify the difference?
Using the standard formula 2*(Ζα∕2 + Ζ1-β)² devided by (mean1-mean2)/SD
gives about 250 per group.
However, I was told the approach is not correct and I should instead calculate the sample size needed to identify that the score is 50% lower in the IG than in the CG. How can that be done? Isn't that the same?
Best,
Joey
Comment: Since the score scale [0,100] is limited on both sides and have only 101 vales, the starting mean 20 and standard deviation of 10 don't adequately describe the population. I don't believe there can be any closed form solution that might give us the sample size, especially if you are going to use a non-parametric test, which is strongly preferred here. If you have a real-world distribution of the score in different age groups it might serve a basis for a Monte Carlo simulation to attempt to estimate the sample size for the target power of 80%.
Comment: Thanks, Alex. The numbers were just an example. Disregarding that a mean of 20 and SD of 10 may not be plausible, what would be the correct formula to calculate the sample size for a percentage change (as in the example, i.e. "the IG experiences a 50% lower increase in the score than the CG")?
Comment: By there is no closed form solution I meant no formula :-)
Comment: It seems you need to clarify with whomever is running the study what "50% reduction" means.  Do they mean the score in control will be 50% of the treatment?  Do they mean the change in scores will be 50% of what would have been otherwise?  You need clarity on what the estimand should be.
Comment: Percent change is an asymmetric measure so is not appropriate for use as a dependent variable.  See [this](https://hbiostat.org/bbr/change).
Answer: It seems like the problem is how you understand "The intervention is supposed to cut the score by 50%." It looks like your calculation reflects the situation when the intervention cuts the increase by 50% instead of the score. However, that sentence is unclear, leading to the intervention value to possibly be either 10 or 12.5 after one year. Did I get it right?


how we can access cookies in angular 6 without ngx- cookie service

Question:

  login() : any {
    for(let data of this.loginsdata)
    if(this.username == data.usr && this.password == data.pw){
      // this.toastr.success('logged in');
      console.log(this.username);
      console.log(this.password);

      this.router.navigate(['table']);

    }
    document.cookie =?

I want to access a cookies in angular 6 without external module like ng-x cookie service. I wanted to use get set delete. is there any method? I have done with javascript approach like  document.cookie but its throwing error
Answer: You can inject the document into your component/service using:
import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(@Inject(DOCUMENT) private document: Document) {}
}

And you can later access it using
this.document.cookie

You asked in the comments for get set delete, but I'd still recommend using ngx-cookie-service. You may add these functions to your component if you don't want to:
import { Inject, PLATFORM_ID, InjectionToken, Component } from '@angular/core';
import { DOCUMENT, isPlatformBrowser } from '@angular/common';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private readonly documentIsAccessible: boolean;

  constructor(
    @Inject( DOCUMENT ) private document: any,
    @Inject( PLATFORM_ID ) private platformId: InjectionToken<Object>,
  ) {
    this.documentIsAccessible = isPlatformBrowser( this.platformId );
  }

  check( name: string ): boolean {
    if ( !this.documentIsAccessible ) {
      return false;
    }

    name = encodeURIComponent( name );

    const regExp: RegExp = this.getCookieRegExp( name );
    const exists: boolean = regExp.test( this.document.cookie );

    return exists;
  }

  get( name: string ): string {
    if ( this.documentIsAccessible && this.check( name ) ) {
      name = encodeURIComponent( name );

      const regExp: RegExp = this.getCookieRegExp( name );
      const result: RegExpExecArray = regExp.exec( this.document.cookie );

      return decodeURIComponent( result[ 1 ] );
    } else {
      return '';
    }
  }

  getAll(): {} {
    if ( !this.documentIsAccessible ) {
      return {};
    }

    const cookies: {} = {};
    const document: any = this.document;

    if ( document.cookie && document.cookie !== '' ) {
      const split: Array<string> = document.cookie.split(';');

      for ( let i = 0; i < split.length; i += 1 ) {
        const currentCookie: Array<string> = split[ i ].split('=');

        currentCookie[ 0 ] = currentCookie[ 0 ].replace( /^ /, '' );
        cookies[ decodeURIComponent( currentCookie[ 0 ] ) ] = decodeURIComponent( currentCookie[ 1 ] );
      }
    }

    return cookies;
  }

  set(
    name: string,
    value: string,
    expires?: number | Date,
    path?: string,
    domain?: string,
    secure?: boolean,
    sameSite?: 'Lax' | 'Strict'
  ): void {
    if ( !this.documentIsAccessible ) {
      return;
    }

    let cookieString: string = encodeURIComponent( name ) + '=' + encodeURIComponent( value ) + ';';

    if ( expires ) {
      if ( typeof expires === 'number' ) {
        const dateExpires: Date = new Date( new Date().getTime() + expires * 1000 * 60 * 60 * 24 );

        cookieString += 'expires=' + dateExpires.toUTCString() + ';';
      } else {
        cookieString += 'expires=' + expires.toUTCString() + ';';
      }
    }

    if ( path ) {
      cookieString += 'path=' + path + ';';
    }

    if ( domain ) {
      cookieString += 'domain=' + domain + ';';
    }

    if ( secure ) {
      cookieString += 'secure;';
    }

    if ( sameSite ) {
      cookieString += 'sameSite=' + sameSite + ';';
    }

    this.document.cookie = cookieString;
  }

  delete( name: string, path?: string, domain?: string ): void {
    if ( !this.documentIsAccessible ) {
      return;
    }

    this.set( name, '', new Date('Thu, 01 Jan 1970 00:00:01 GMT'), path, domain );
  }

  deleteAll( path?: string, domain?: string ): void {
    if ( !this.documentIsAccessible ) {
      return;
    }

    const cookies: any = this.getAll();

    for ( const cookieName in cookies ) {
      if ( cookies.hasOwnProperty( cookieName ) ) {
        this.delete( cookieName, path, domain );
      }
    }
  }

  private getCookieRegExp( name: string ): RegExp {
    const escapedName: string = name.replace( /([\[\]\{\}\(\)\|\=\;\+\?\,\.\*\^\$])/ig, '\\$1' );

    return new RegExp( '(?:^' + escapedName + '|;\\s*' + escapedName + ')=(.*?)(?:;|$)', 'g' );
  }
}

Comment: how can set , get and delete cookies its like javascript or different method suggest me
Comment: For that, you have to use a library. If you don't want to use anything else you have to implement it yourself. You just have to parse the cookie string and create your own get set and delete methods. There are not built in functions like this.
Comment: @AkhilRaghav I've edited my answer with some example commands
Comment: I want in terms of examples so that i can understand clearly I have seen some methods But unable to understand it
Comment: Cookies are stored in a string in the browser with `;` between them. And they are a key value pair with `=` between them. You just have to split the string if you want to get the value by the semicolon first and then by the `=`. If you'd like to add a value to it just append a semicolon to the end, and then print your cookie in a `key=value` format.
Comment: And to delete a cookie you just simply make the expiration date to a date in the past
Comment: In this case, if you'd like to add a cookie with a name `test` and a value `value` you use this code somewhere with `this.set('test', 'value)`. The arguments with a `?` after them are all optional. You don't have to specify them.
Comment: Sir,I am beginner I want to learn without external modules so I asked this question I have posted my code Can you please check it out refer me good solution
Comment: Actually you're using AngularJS 1.6 which is NOT the same as Angular 6. I recommend you to go to the [Angular Quick Start Guide](https://angular.io/guide/quickstart) to start using the latest Angular.
Comment: Also, don't be afraid to use external libraries in development. They are available for a reason and you don't have to reinvent the wheel every time you write something.
Comment: Given the code you wrote I assume you currently don't really understand how the web works. That is not a problem, everyone has to start somewhere. I would recommend you to take some online courses for example complete the [freeCodeCamp](https://freecodecamp.org) tutorials before building your own websites.
Comment: I am using angular 6 and typescript yes i understood how to use cookies in angular but I wanted to know detailed information about it so I choose it
Answer: Implemented using browser's document object.
// Set Cookiee
// "Secure;HttpOnly;" will work if your site is having SSL certificate.
// You can ignore these 2 attributes in development.
document.cookie = `myKey=${myValue};Path=/;Secure;HttpOnly;`;

// Read Cookiee
const _name = 'myKey',
let value = `; ${document.cookie}`.match(`;\\s*${_name}=([^;]+)`);

// Delete Cookiee (using expiration time)
const expires = 'expires=' + new Date().toUTCString();
document.cookie = `myKey=;Path=/;expires=${expires}`;

However, for Server Side Rendering (Angular Universal) implementation, you should not use default browser document object. In that case, ngx-cookiee will help.


Adding tooltip for icon in GWT

Question: Can anyone help how to add tooltip for an UiHandler using GWT in java
Thanks in advance,
Raj
Answer: <code>button.setTitle(tooltip);
</code>
Read the documentation at http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/UIObject.html#setTitle-java.lang.String-
Comment: Hi @Soufiane Hassou,@krishnakumarp thanks for the suggestion.can you please tell how to set message in two languages.As my application is in two languages, i want to set tooltip message in two languages.
Comment: You can use GWT I18N framework to internationalize the message. Read more at https://developers.google.com/web-toolkit/doc/latest/DevGuideI18n and https://developers.google.com/web-toolkit/doc/latest/tutorial/i18n

Adding tooltip for icon in GWT


create 1 daily calendar event with multiple times a day

Question: i want to create custom calendar events for iOS, and have succeeded in obtaining one eventIdentifier for weekly, monthly and yearly events using:
initRecurrenceWithFrequency:
interval:
daysOfTheWeek:
daysOfTheMonth:
monthsOfTheYear:
weeksOfTheYear:
daysOfTheYear:
setPositions:
end:

now i want to do the same for daily events.
for example i want one daily event (eventIdentifier)  from:
6AM -> 8AM and 2PM -> 5PM and 9PM -> 11PM
how can i do that?
Answer: it doesn't work on iOS, I created multiple events on the same day


Usando select o mesmo select mais de uma vez

Question: Preciso usar o mesmo select outras vezes, mas não estou conseguindo.
Ele mostra o resultado no primeiro while, mas nos demais não.
Na mesma tela irei repetir por 4x, isso porque estou me referindo aos pneus: Dianteiro Direito, Dianteiro Esquerdo, Traseiro Direito, Traseiro Esquerdo.
MYSQL:
$rsMarca = $mysqli->query("SELECT * FROM pneu_marca");
$row_rsMarca = $rsMarca->fetch_assoc();

Primeiro While
<select name="marca_de">
  <?php do { ?>
  <option value="<?php echo $row_rsMarca['ID_Marca']; ?>">
    <?php echo $row_rsMarca['marca']; ?>
  </option>
  <?php } while ($row_rsMarca = $rsMarca->fetch_assoc()); ?>
</select>

Segundo e outro while
<select name="marca_dd">
  <?php do { ?>
  <option value="<?php echo $row_rsMarca['ID_Marca']; ?>">
    <?php echo $row_rsMarca['marca']; ?>
  </option>
  <?php } while ($row_rsMarca = $rsMarca->fetch_assoc()); ?>
</select>

Answer: Bem, basicamente você está tentando executar o loop "enquanto" a execução da consulta acontece, no caso ela acontece apenas uma vez, e como você utilizou a estrutura do do while, ele executa uma vez, verifica a condição do while e para. Recomendaria você usar  o foreach, onde o mesmo executa o loop para cada linha do resultado.
No primeiro
<select name="marca_de">
  <?php foreach($row_rsMarca as $resultado) { ?>
  <option value="<?php echo $resultado['ID_Marca']; ?>">
    <?php echo $resultado['marca']; ?>
  </option>
  <?php } ?>
</select>

No segundo
<select name="marca_dd">
  <?php foreach($row_rsMarca as $resultado){ ?>
  <option value="<?php echo $resultado['ID_Marca']; ?>">
    <?php echo $resultado['marca']; ?>
  </option>
  <?php } ?>
</select>

Isso fará com que "para cada" linha da sua consulta, ele crie um option contendo as informações referentes da linha.
Comment: Esta tendo um problema, veja como esta sendo exibido (https://prnt.sc/npgvjn), no mysql esta assim (https://prnt.sc/npgvod)
Comment: Descobrir o erro...rsrs. No lugar de `` era ``.
Comment: Se na sua consulta você colocar um `return` antes de `$row_rsMarca`, creio que funcionaria sem trocar no foreach.


Closing Open positions on Binance

Question: I am using the Binance Python API (Python 3.x)
When one uses the "create_order" functionality, it creates an order on the SPOT exchange with a STATUS of NEW. When it gets filled, the STATUS goes to FILLED.
Also, when it is FILLED, my understanding is that a POSITION is being created (Long or Short)
My question is as follows:
What endpoint can I use to get a list of the Open Positions.
Why do I want this?
If a Position is on the SELL side, I would like to execute a BUY to close it.
If a Position is on the BUY side, I would like to execute a SELL to close it.
Can this be done?
Any help, hints or advice would be ~greatly~ appreciated.
TIA
@michaeldel
ETA:
I am using this here: https://python-binance.readthedocs.io/en/latest/
For the Orders, I have been following:
https://python-binance.readthedocs.io/en/latest/account.html?highlight=orders#orders
Can you note what the equivalent would be the equivalent under this (Python) API?
I have been using: "get_all_orders" with a focus of the "STATUS" being "FILLED".
https://python-binance.readthedocs.io/en/latest/binance.html#binance.client.Client.get_all_orders
I was looking for Open Positions (not Orders)
If a BTCUSDT SELL Position that has status=FILLED with a origQty =.20, I want to be able to reverse it with a BUY and a Quantity of .20
If a BTCUSDT BUY Position has status=FILLED and a origQty=.30, I want to be able to reverse it with a SELL and a Quantity of .30
Does this make sense?
Is there a better way to do it? Am I missing something?
Thanks for the input!
Comment: https://binance-docs.github.io/apidocs/spot/en/#current-open-orders-user_data
Comment: Thanks for the response! pls see update in Post. TIA
Answer: For binance futures this feature was added at 2020-05-18!
With the STOP_MARKET or TAKE_PROFIT_MARKET you can use closePosition param!
closePosition=true

As per the change long from the api doc here:

2020-05-18
New parameter closePosition for endpoint POST /fapi/v1/order:
If a STOP_MARKET or TAKE_PROFIT_MARKET order with closePosition=true is
triggered,all of the current long position( if SELL order) or current
short position( if BUY order) will be closed.
New field closePosition in response to endpoints:

POST /fapi/v1/order
POST /fapi/v1/batchOrders
GET /fapi/v1/order
DELETE /fapi/v1/order
DELETE /fapi/v1/batchOrders
GET /fapi/v1/openOrder
GET /fapi/v1/openOrders
GET /fapi/v1/allOrders

Check the new order doc description
Comment: I think TAKE_PROFIT_MARKET  and STOP_MARKET  are both Market order. can we close position with maker order type using closePosition  ?
Answer:
Also, when it is FILLED, my understanding is that a POSITION is being created (Long or Short)

As far as I know, Binance does not provide semantics for position (in terms of trading). Such abstractions are usually implemented for derivatives (e.g. futures) when it comes to currency markets, since currencies buying-and-selling-to-make-profit is not their only use.
On Binance, and most other cryptocurrency exchanges, you are making spot transactions, i.e. giving some amount of a currency to receive some amount of another currency. Plain and simple.
You may abstract positions yourself though, but that may involve much more work especially considering heterogeneous chains of transaction (e.g. BTC -> ETH -> USDT -> BTC), partial fills, etc.
Comment: Thanks, I had started to see that
Answer: Spot trading doesn't have positions like other instruments do because you are settling the trade immediately. When you place an order to buy btc using usdt and it becomes FILLED, that btc is immediately credited to your account.
if you sell usdt  to buy btc then  You should sell your btc to "close" the position.
The closet way to list a of "open spot positions" in the way you are thinking about it would be to get your balances via GET api/v3/account.
Quoted from the link below :
https://dev.binance.vision/t/closing-positions/221

Closing Open positions on Binance


Regex para split de operadores de comparação

Question: Estou com dificuldades para montar uma expressão regular que atenda a seguinte condição:
String formula = " 100 != (50 + 20 + 30) ";

String arr = formula.split(" somente os caracteres: '=', '!=', '<', '<=','>=' e '>' ");

Como ficaria essa expressão? Também gostaria de não perder o operador no split.
Answer: Uma alternativa é:
String formula = " 100 != (50 + 20 + 30) ";
String[] partes = formula.split("!?=|[<>]=?");
for (String s : partes) {
    System.out.println(s);
}

A regex usa alternância (o caractere |, que significa ou), e tem duas opções:

o caractere !, mas como tem um ? logo depois, isso o torna opcional. Em seguida, temos sinal de igual (=). Assim, o trecho !?= pega tanto != quanto =
[<>]=?: uma classe de caracteres ([<>], que corresponde a qualquer um dos 2 caracteres < ou >), seguida de sinal de igual opcional (=?). Assim, podemos ter >, >=, < ou <=

A saída é:
 100
 (50 + 20 + 30)

Um detalhe é que esta regex também pode considerar casos como 10 ==== 1 + 9, e o array resultante do split poderá ter vários elementos que são apenas uma string em branco.
Para evitar isso, podemos assumir que antes e depois do separador sempre tem um espaço:
String[] partes = formula.split(" (!?=|[<>]=?) ");

Repare que agora tem um espaço antes e outro depois da regex. E também agrupei tudo dentro de parênteses, pois os espaços devem estar antes e depois de ambas as possibilidades (sem os parênteses, a regex é interpretada como "tem espaço antes de !?= (mas depois tanto faz), ou tem espaço depois de [<>]=? (mas antes tanto faz)".
Mas este caso só funciona se tiver um espaço antes e depois do separador. Se este for o seu caso, pode usar esta mesmo.

Mas se quiser aceitar fórmulas sem espaços (como 10!=20), pode verificar se antes e depois do separador só tem caracteres que não são os próprios separadores:
String[] partes = formula.split("(?<=[^!=<>])(!?=|[<>]=?)(?=[^!=<>])");

Agora eu uso lookarounds: o lookbehind (o trecho com (?<=) e o lookahead (o trecho com (?=), que servem para verificar se algo existe antes e depois. No caso, estou verificando [^!=<>] (qualquer coisa que não seja os caracteres !, =, < ou >) - o ^ logo depois do colchete de abertura faz com que a classe de caracteres seja negada.
O truque do lookbehind e lookahead é que eles só verificam se algo existe antes ou depois, mas este trecho não faz parte do match, e portanto não é removido no split.
Assim, a expressão ignora casos como 2===1+1, além de fazer o split corretamente mesmo se não tiver espaços antes e depois do separador.

Após o split, o operador é perdido. Para recuperá-lo, você tem duas opções:

obtê-lo separadamente, usando a mesma regex:

String formula = " 100>=(50 + 20 + 30) ";
Matcher matcher = Pattern.compile("(?<=[^!=<>])(!?=|[<>]=?)(?=[^!=<>])").matcher(formula);
while (matcher.find()) {
    System.out.println(matcher.group()); // >=
}

Eu uso while para o caso de ter mais de uma ocorrência do operador na string. Mas se quiser somente a primeira ocorrência, pode trocar para if.

obtê-lo no mesmo array retornado pelo split. Isso exige uma complicação a mais, pois é necessário outro lookahead e outro lookbehind em volta de toda a expressão:

String regexTemplate = "((?<=%1$s)|(?=%1$s))";
String formula = " 100>=(50 + 20 + 30) ";
String[] partes = formula.split(String.format(regexTemplate, "(?<=[^!=<>])(!?=|[<>]=?)(?=[^!=<>])"));
for (String s : partes) {
    System.out.println(s);
}

A ideia desta regex foi tirada desta resposta do SOen.
Basicamente, você usa ((?<= expressão )|(?= expressão)). Ou seja, verifica as posições da string que contém a regex antes ou depois, e faz o split nessas posições. Como o lookahead e lookbehind não fazem parte do match, o operador também é retornado no split.
A saída é:
 100
>=
(50 + 20 + 30)

Se quiser incluir o operador ==, mude a regex para:
String formula = " 100 == (50 + 20 + 30) ";
String[] partes = formula.split("[!=]?=|[<>]=?");
for (String s : partes) {
    System.out.println(str);
}

Agora, em vez de apenas !, eu uso [!=], que aceita tanto ! quanto = antes do outro = (ou seja, aceita tanto != quanto ==).
Se quiser mudar as opções 1 e 2 acima, ficaria:
String formula = " 100==(50 + 20 + 30) ";
Matcher matcher = Pattern.compile("(?<=[^!=<>])([!=]?=|[<>]=?)(?=[^!=<>])").matcher(formula);
while (matcher.find()) {
    System.out.println(matcher.group()); // ==
}

String regexTemplate = "((?<=%1$s)|(?=%1$s))";
String formula = " 100==(50 + 20 + 30) ";
String[] partes = formula.split(String.format(regexTemplate, "(?<=[^!=<>])([!=]?=|[<>]=?)(?=[^!=<>])"));
for (String s : partes) {
    System.out.println(s);
}

Comment: @BrennoSegolim Atualizei a resposta
Comment: Após realizar o split o operador " != " é perdido, consigo resgata-lo ?
Comment: @BrennoSegolim Sim, consegue. Atualizei a resposta
Comment: Muito Obrigado pela ajuda !
Comment: deparei-me com um erro na minha instrução, seguindo a lógica do regex acima não é possível obter-se o retorno caso a expressão contenha "==", correto?
Comment: @hkotsubo é possivel seguir essa mesma lógica para uma expressão utilizando javascript?
Comment: @VictorHenrique Sim: https://jsfiddle.net/3ugj9txk/  (mas se sua dúvida for outra, sugiro que faça outra pergunta, pois aí ela fica visível pra todos na página principal e vc tem mais chances de alguém responder - se comentar aqui, provavelmente só eu vou ver, e ultimamente estou sem muito tempo para dedicar ao site...)


Mixed models (lme4) + lsmeans to estimate trend in population means

Question: I aim to estimate one populations mean blood pressure during different years. Here is the setting:
(1) 7400 onservations; repeated measurements. Unbalanced.
(2) measurements are undertaken anually from 2001 to 2012. Eachindividual maybe measured several times.
(3) one can expect a time-bias, i.e as time progress, there will be made advances in therapy, which will lead to more efficient blood pressure lowering. These factors will not be taken into account. Deliberately.
Aim: estimate population mean blood pressure each year. Including confidence interval.
Methods: use lme4 package (linear outcome, blood pressure) to account for repeated measurements and lsmeans package to estimate the population mean each year.
Code:
fit <- lmer(bloodpressure ~ year + age + sex + (1 | patient_id), data=data)

'year' is the factor variable for which I'd like to obtsin the means.

lsmeans(fit, ~ year) # not tried

Questions
- is this method OK?
- will the covariance be respected by using lsmeans, or should I use lmerTest package which has a built in function for estimating lsmeans?
- each individual has a random slope in the call above, should I adjust it to include random effects for year also?
Thanks for any advice on this
Comment: The lsmeans package DOES use the ccorrect ovariate matrix from the object. If you look in the vignettes, you'll find some examples with models fitted with `lmer`.
Comment: Thanks @rvl. And the results appear plausible after comparing with crude figures. I'm only using a random term for individual. Id you could provide your comment as answer instead I can approve the question as answered.
Answer: The lsmeans package does produce the correct results with model objects from a number of packages, including lme4. If you have a fairly recent update of lsmeans installed, you can do ? models and see information on what model objects are supported, and details of any special provisions.
Comment: What's the difference between lmertest, mertools and lsmeans?


DRYing up JQuery

Question: I have a couple links and divs I would like to have the same functionality on. Basically, you click on a link/button/anything-chosen-as-the-trigger and the corresponding space slides open.
The markup looks like...

First

Second

Third

So far, I have tried to refactor
// script.js.coffee
$(document).ready ->
  $('#first').click ->
    $('#f_i_r_s_t').slideToggle()

// script.js.coffee
$(document).ready ->
  $('#second').click ->
    $('#s_e_c_o_n_d').slideToggle()

// script.js.coffee
$(document).ready ->
  $('#third').click ->
    $('#t_h_i_r_d').slideToggle()

which works, to
// refactored_script.js.coffee
hideables = {
  '#first': '#f_i_r_s_t',
  '#second': '#s_e_c_o_n_d',
  '#third': '#t_h_i_r_d'
}

for content_space, link_trigger in hideables
  $(content_space).hide()
  $(link_trigger).click ->
    $(content_space).slideFadeToggle()

but the refactored script does not work. Any ideas?
Comment: can you do a console of: test = for content_space, link_trigger in hideables; I think this syntax is wrong. and yes, your naming is just plain wrong. f_i_r_s_t -> seriously ?
Comment: This is perhaps a better question for http://s.tk/review.
Comment: thanks, I used that just for question-purposes. the concept is the link "explodes" the space. My app uses more descriptive terms which I cannot use here
Comment: @Raynos ИΞVΞЯ ...okay, maybe eventually
Comment: You need the parentheses in `for`.
Comment: @LeaVerou in Coffeescript, the parentheses are optional
Answer: I would actually do

First

Second

Third

$('li.links a').click(function(e) {
    e.preventDefault();
    target = $(this).attr('href');
    $(target).slideToggle();
});

that way you can use the css :target attribute as a failover
Answer: Do something like this

First

Second

Third

$('a.links').click(function() {
    $('#' + $(this).attr('id') + '-content').slideToggle()
});

Adding underscores to your ID's is just making your problem harder and less dynamic; sure it can be done.  You'd just have to take the ID attr and insert a underscore between each character but ... is all I have to really say about that.
Answer: I would achieve this that way:

First

Second

Third

and JS:
$(document).ready(function(){
  $('.toggler').click(function(){
    $('#'+$(this).attr('toggle')).slideToggle();
  });
});

It's kind of universal solution, can be used in may ways.

DRYing up JQuery