Continuity of a rational function on $\mathbb{R}$

Question: If $f(x)=\dfrac{2x+1}{x^2+ax+1}$. Find the value(s) of $a$ so that $f(x)$ is continuous on all real numbers $\mathbb{R}$.
Here, I'll write my attempt. The denominator $x^2+ax+1 \neq 0$. Then by using the quadratic formula, we obtain the following equation $\dfrac{-a \pm \sqrt{a^2-4}}{2} \neq 0$. That means $-a \pm \sqrt{a^2-4} \neq 0$. Then $-a = \pm \sqrt{a^2-4}$. By squaring both sides, we obtain $a^2 \neq a^2-4$ which is always true. So the conclusion is that $a$ is any real number. Your comment is highly appreciated.
Comment: The quadratic formula doesn't give that $\dfrac{-a \pm \sqrt{a^2-4}}{2} \neq 0$, but instead that $\dfrac{-a \pm \sqrt{a^2-4}}{2} \neq x$.
Answer: The case you want is that $x^2+ax+1\neq0$ on the real line, which is equivalent to saying that $x^2+ax+1$ has complex roots
Comment: I just study the roots on the real line. So what $a$ can be?
Comment: @user113715: for what values of $a$ does the quadratic formula indicate there are no real roots?
Comment: Offtopic: @user113715 I visited your profile, is there any reason why you learned knot theory prior to quadratic polynomials?
Comment: I see, the quadratic formula gives no real number if $a^2-4 <0$. That means if $a \in (-2,2)$. This gives that $a \in (-\infty,-2] \cup (2,+\infty)$
Answer: you need to be very careful with your inequalities, since for example setting setting $a=-2$ yields that $x=2$ is a solution of your denominator. In particular you need not look for $\neq 0$ but you need to look for $\neq x$, since the existence of a soltion to your quadratic equation would yield to a zero of the denominator. Hence if you pick $a$ such that $a^2<4$ you are done, since then your squareroot does not exist in $\mathbb{R}$ (pictorially your parabola does not touch the x axis), and so the fraction is defined everywhere.
Comment: ah yes, sorry, I am quite bad with the directions of my inequalities myself.
Answer: A very simple counterexample would be choosing $a = 2$.
$$x^2+2x+1 \neq 0 \implies (x+1)^2 \neq 0 \implies x\neq -1$$
Thus, $a \in \mathbb{R}$ isn't correct.
Your error is that you used the quadratic formula incorrectly.
$$ax^2+bx+c = 0 \implies \color{blue}{x} = \frac{-b\pm\sqrt{b^2-4ac}}{2a}$$
You used $\color{red}{0}$ instead of $\color{blue}{x}$ in your inequality.
$$x^2+ax+1 \neq 0$$
$$x \neq \frac{-a\pm\sqrt{a^2-4}}{2}$$
If you think about the function $f(x) = x^2+ax+1$, what value of $a$ would produce no solutions (a.k.a $x$-intercepts)? The discriminant must become negative.
$$\Delta < 0 \implies a^2-4 < 0 \implies a^2 < 4 \implies a < 2 \text{ and } a > -2 \implies a \in (-2, 2)$$
Comment: I got it. Thank you so much.
Comment: In reply to Nick Liu commnet, There is no link actually between my question about quadratic polynomial and my research area (knot theory). Someone asked me this question and I got confused, so I posted my question here. Thank you all.
Answer: You're interpreting the quadratic formula in a wrong way: asking for
$$
\frac{-a\pm\sqrt{a^2-4}}{2}\ne0
$$
is imposing that the polynomial doesn't have $0$ among its roots, which is surely true for every $a$, because the product of the roots is $1$ (Viète's formulas). So no wonder you found that your inequation is satisfied for every value of $a$.
You rather want to impose that the polynomial $x^2+ax+1$ has no real root. Whenever $a^2\ge4$ there are real roots given by the quadratic formula. So you want $a^-4<0$, that is $-2<a<2$.
Comment: Thank you so much egreg, got it.


An inequality with infinite sum

Question: If $p>1$, and $k$ is a positive integer more than $1$,
show that $$\sum_{n=2}^{\infty}\frac{(\ln n)^k}{n^p} \le \frac{k!}{(p-1)^{k-1}}$$
At first, I thought many ideas such as Cauchy-Schwarz inequality, Taylor expansion, Induction on k, etc..
But they does not work efficiently.....
Comment: Have you tried integral ?
Comment: @MatikKen you mean the left-hand side's series is relavant with integral?
Comment: Yes. or estimate the lnn.
Answer: Notice that $\dfrac{\ln^k x}{x^p}$ is a decreasing function with limit $0$, and so we may use integrals to understand its convergence and size. Then
$$ \sum_{n \geq 1} \frac{\ln ^kn}{n^p} < \int_1^\infty \frac{\ln ^k x}{x^p} \mathrm{d}x,$$
so we need to approximate the integral. Perform the substitution $x \mapsto e^x$ (or $u = \ln x$) to see that our integral is
$$ \int_0^\infty u^{k+1}e^{-(p-1)u}\frac{\mathrm{d}u}{u},$$
which is almost a Gamma function. Perform the substitution $u \mapsto \frac{u}{p-1}$ to see that our integral is now
$$\frac{1}{(p-1)^{k+1}} \int_0^\infty u^{k+1}e^{-u}\frac{\mathrm{d}u}{u} = \frac{\Gamma(k+1)}{(p-1)^{k+1}} = \frac{k!}{(p-1)^{k+1}},$$
which is very similar but just a little smaller than your bound.
Comment: um.. I had a mistake which is the summation starting from n=2.
However,  I think there must be some constant in the RHS of the first inequality by drawing a graph of decreasing function...
Comment: @Jeong: Ah yes, there will be a constant. This just comes from the integral test.
Comment: I understand it. Thanks a lot!
Answer: Too long for a comment:
Euler's famous expression for the Gamma function can be rewritten $($using the fact that $a\ln b=$ $=\ln b^a$ for $a=-1$, and then substituting $x\to\frac1x\Big)$ as follows:
$$k!=\int_0^1(-\ln x)^kdx=\int_0^1\ln^k\left(\dfrac1x\right)dx=\int_1^\infty\dfrac{\ln^kx}{x^2}dx$$
Then, by changing the power of x in the denominator to p, we get
$$\int_1^\infty\dfrac{\ln^kx}{x^p}dx=\frac{k!}{(p-1)^{k+1}}$$
At the same time, since $\displaystyle\zeta(p)=\sum_{n=1}^\infty\frac1{n^p}$ , by differentiating k times with respect to p and ignoring the resulting $(-1)^k$ factor, we get
$$\left|\zeta^{(k)}(p)\right|=\sum_{n=1}^\infty\frac{\ln^kn}{n^p}=\sum_{n=2}^\infty\frac{\ln^kn}{n^p}$$
since $\ln1=0$, and $(a^x)'=a^x\cdot\ln a$. For $p=2$ we have $\left|\zeta^{(k)}(2)\right|\simeq k!$ These links between the two functions, $\Gamma$ and $\zeta$, should not come as too much of a surprise, especially given the fact that $\Gamma\left(\frac1p\right)$ is linked, via Newton's binomial theorem, with geometric shapes of the form $x^p+y^p=r^p$, or, in other words, with bounded sums of powers, while on the other hand, the $\zeta$ function is also related to convergent $($and therefore bound$)$ sums of powers: hence the numerous mathematical identities between the two.
So your sum is nothing more than $|\zeta^{(k)}(p)|$, and the term on the right is nothing else than what one would obtain if one were to replace the summation sign on the left with an integral sign with the limits of integration $1$ and $\infty$, and their link to the factorial function is due to the reasons laid out above. Why replace the summation sign with an integral one ? Because integrals are nothing else than continuous sums, and the sign itself comes from medieval Latin s, just like the one for discrete sums comes from the Greek letter sigma, representing the same sound.

An inequality with infinite sum


How does Google's UserService do its magic?

Question: I have an app that is hosted on appspot and authentication is set to Federated Login.  My app uses Google's UserService to check if the user is logged in, and if necessary redirect them to a login page where the user can choose their OpenId provider, and then login.  It all works fine.
In the case where the user chooses Google as their OpenId provider, if they then open a new tab and go to gmail (for example), gmail knows who they are - no login/authentication needed.
In the case where the user chooses Yahoo as their OpenId provider, if they then open a new tab in the browser and go to MyYahoo - Yahoo knows who they are - no login/authentication needed.
I am fine with this behavior - I just can't figure out how logging in on my app let's Yahoo know the user has authenticated.  I don't think it is the ACSID cookie, since I removed that and everything still worked.
It's probably pretty simple, so many thanks in advance for taking the time to enlighten me...
Answer: This isn't anything App Engine is doing - it's part of OpenID. When you select an OpenID provider, you're sent to that provider, who logs you in to authenticate you, before sending you back to the app. In the process, the OpenID provider logs you in with them (eg, Yahoo or GMail) too.
Comment: Thanks so much for the clarification - that makes perfect sense.


How to get angles from bytes c#

Question: I have a binary file with vertex normals. The value is coded as byte. How do I encode angle from byte and convert the angle to float?
Example:
binary: 128, 128, 255

obviously in angles it's: 90*, 90*, 180*

How do I get a value in float?
Values are obviously 0.5 0.5 1.0 but what's the c# code so I can convert byte from 128 to 0.5f?
Comment: Do you have angles in `[0..180]` range only?
Comment: No, 1000 0000 is not 0.5f and 1111 1111 is not 1f. But assuming there are only 180° angles: 180/255*(yourBinValue) = YourAngle => Parse to Int
Comment: Simple math? 255 => 180 leads to 180/255*value gives you the angle
Comment: I guess it;s -180...180
Answer: byte has a range of [0..255], so if you're mapping it to a [0.0..1.0] range, it's simple math:
double angle = byteValue / 255.0;

At that point, you can then multiply by whatever angle system you desire.
// Degrees
double angleDeg = angle * 360.0;

// Radians
double angleRad = angle * 2.0 * Math.PI;

Comment: @MrJox Wrong how? What result are you expecting, and what are you getting?
Comment: another example:
binary: 29, 208, 112
float: -0.6084800, 0.7681854, 0.1991063
Comment: Then you implemented it wrong. If you manually calculate it, the values are correct.
Comment: @JanesAbouChleih the result in above example is a correct one and my problem is I can't understand the algorithm of getting these values. It can be anything..
Comment: I don't get it? First you say that the result is wrong. Now the result is correct. Do you want an explanation of this basic mathematical construct? Rule of three, there you go. 255 = 360°, so you map your byte value to a range of 0.0 to 1.0 (byte/255), after that you multiply your range to a degree (°) value by multiplying with 360 (full circle). If you need further explanation: math.stackexchange.com or a math book or secondary school.
Comment: @JanesAbouChleih that's probably the result of the way how I explained the issue, sorry.
What I say is this **binary: 29, 208, 112 float: -0.6084800, 0.7681854, 0.1991063** is the correct conversion and I can't understand the algorithm how to do this.
Im doing a conversion of vertex normals from byte value to float. I use 3d max to export both binary file and xml file and I compare values. All my attempts so far to convert from binary byte to float didn't result me same values as I have in xml.
Comment: You should probably update your question with what you really want to accomplish.

How to get angles from bytes c#


Safe breakout for an RV outlet

Question: I have an existing 120V 30A outlet used for an RV. I would like to make myself a breakout box to use this outlet as a bunch of regular outlets when I have the need for outdoor use. The outlet is wired with 10AWG copper.
I have seen existing products that are simply an adapter from an RV 30A plug to a NEMA 5-15R or 5-20R, but I'm concerned that these don't protect the thinner gauge wire used on the far end of the circuit. Also, the RV plug does not have a GFCI (I could not find a BR-type single-pole 30 amp GFCI or a standalone GFCI rated for 30 amps; also, according to my research, GFCI is not currently required for RV outlets) but I would want (need?) a GFCI when using regular outlets outdoors.
What is a safe way to break out this RV connector into two regular plugs with proper overcurrent and GFCI protection?
Additionally, would it be safe for me to put a 20 amp and a 15 amp split ( instead of two 15 amp) which would allow me to put a 20 amp receptacle, given that if the sum of the two goes over 30 amps, it will still be protected by the breaker in the panel?
Comment: Best answer is a RV box that has 50A 240/30A 120/20A 120 on a small subpanel - it comes all as one ready-made thing. But that would most likely require bigger wire: What wire (and how many wires - 2 + ground or 3 + ground) do you have now, and is there a practical way to run new wire?
Comment: @manassehkatz-Moving2Codidact It would be easy to run new wire, but the point of this exercise is to see if I can use what I have instead of spending more inside. The existing wire is 2+ground (black, white, and green) 10AWG copper.
Answer: You can get "a solution in a can".  It is called an "RV subpanel" and it replaces the 30A socket.   It contains a 30A breaker for a TT30 socket, as well as a 15A or 20A breaker to feed a 20A receptacle. All this is mounted in a single enclosure.
Or you can wing this together using a 2-space subpanel, 2 breakers, and two receptacles with in-use covers.
Answer: You need a portable subpanel, or "power distribution box" though this one will be unusual (most of those "off-the shelf" are designed for NEMA14-class 4-wire input. There might be a unicorn you can buy though.)
DIY, you're looking for a TT-30 input cord, a proper strain relief/cable gland to get it into a sub-panel (probably a 2-space unit, or a 4-space you don't use half of) a board (or something) to mount the sub-panel and a couple of (drawn, so as to be less likely to cut things) steel boxes to, 15 & 20A breakers, and 15 & 20A GFCIs unless you choose to use GFCI breakers instead. Use drawn exposed work covers for the boxes and connect to the subpanel using conduit nipples.
If you want "A bunch of outlets" use a bigger board and a few more boxes, feeding from the LOAD terminals of the respective GFCIs.
Comment: See this for the 50A case...it's otherwise a similar problem/solution  https://diy.stackexchange.com/a/210081/18078

Safe breakout for an RV outlet


Modify STARTUPINFO after CreateProcess

Question: I would like to be able to change the STARTUPINFO values, right after CreateProcess has been called (suspended).
So the new remote/child process can get custom GetStartupInfo values as soon as it starts.
How could I achieve this?
More Info:
I would like to pass arbitary data to the child process.
Regarding to this article: http://www.catch22.net/tuts/undocumented-createprocess it is possible to do so with the reserved2 members from the STARTUPINFO structure. This method works but has a limit of 65536 bytes. A theoretical solution in order to pass more than 65536 bytes would be if you:

Create the process (suspended)
Alloc space with VirtualAllocEx in the child process
Write data > 65536 bytes to the child process with WriteProcessMemory
Change the reserved2 members with the address from Step 2
Resume the process
The child process calls GetStartupInfo and gets the data
Comment: You don't need a window handle. Memory mapped file would be perfect for this. The docs are clear on `lpReserved2`. Don't use it. Pass the name the file mapping as a command line argument and it's all good.
Comment: The obvious thing to do is to change the values before you call `CreateProcess`. Presumably that's not an option because you aren't calling `CreateProcess`. Which makes me think that there's some external process, injection, hooking trickery going on. Would it help if we knew what that was?
Comment: I don't really understand that comment. All the same, I think that you should edit the question to add some more details. Perhaps somebody will have a different way to solve your root problem.
Comment: Why don't you use standard IPC to let the other process know where to find this memory?
Comment: @DavidHeffernan You are correct. I would like to extend/break the `lpReserved2` limit which is 65536 bytes. If I was able to fill this value with the result of a previous `VirtualAllocEx` call, I could theoretically store as much bytes as RAM has to offer.
Comment: @DavidHeffernan I have edited my question.
Comment: @DavidHeffernan Because you need to allocate a window handle, etc. I would prefer if my "idea" would work by simply changing the value of this member.
Answer: I'm not aware of any supported way for you to do what you ask. However, I suggest an alternative solution to the root problem.

You should not be using lpReserved2 anyway since the documentation tells you to set it to NULL.
Have the parent process create a named memory mapped file.
Pass the name of this file mapping to the child process as a command line argument.

Indeed, there are many variants on this approach, but command line arguments are the way to pass information to a new process.

Modify STARTUPINFO after CreateProcess


npm ERR! ERROR: connect ETIMEDOUT 2606:4700::6810:1d22:80 when create-react-app

Question: Im trying to create a react app using
npx create-react-app my-app
but im getting this error in prompt
npm ERR! code ETIMEDOUT
npm ERR! syscall connect
npm ERR! errno ETIMEDOUT
npm ERR! network request to https://registry.npmjs.org/create-react-app failed, reason: connect ETIMEDOUT 2606:4700::6810:1a22:443
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! A complete log of this run can be found in: C:\Users\andre\AppData\Local\npm-cache\_logs\2023-08-07T18_45_41_230Z-debug-0.log

I already deactivate proxy config and firewall in my pc, remove the npm proxy settings and set the registry in .npmrc with
npm config set proxy null
npm config set https-proxy null
npm config set registry http://registry.npmjs.org/

Im using a home network, im not using proxys.
It use to work few weeks ago. I'm not understanding what is happening.
Any Help?
Answer: I have changed the registry url from http to https like below , also cleaned the cache, removed the proxy but nothing work.
npm config get registry http://registry.npmjs.org
The only things that work for me is disabling ipv6 connectivity by going to the control panel
Video Reference =>  https://youtu.be/vzORm7AUUSQ


MailKit MailKit.Net.Smtp.SmtpClient.OnSenderNotAccepted error

Question: I have an issue connected with MailKit. On the dev environment it works correctly and sends the e-mails correctly. I have a beta environment of the system hosted on my domain (where the email server is located - kumminui.specodit.pl) I have created the production environment at kumminui.pl (so the .specodit part has been removed). Right now the emails are not working.
Error no1 (with port 587 and hostname equal to server name and STARTTLS):
    fail: API.Program[0]
Jul 27 10:08:08 specodit.pl dotnet-example[3445]:       An error occurred during migration
Jul 27 10:08:08 specodit.pl dotnet-example[3445]:       MailKit.Net.Smtp.SmtpCommandException: 188.8.131.52 is _my_ address
Jul 27 10:08:08 specodit.pl dotnet-example[3445]:          at MailKit.Net.Smtp.SmtpClient.OnSenderNotAccepted(MimeMessage message, MailboxAddress mailbox, SmtpResponse response)
Jul 27 10:08:08 specodit.pl dotnet-example[3445]:          at MailKit.Net.Smtp.SmtpClient.ProcessMailFromResponse(MimeMessage message, MailboxAddress mailbox, SmtpResponse response)
Jul 27 10:08:08 specodit.pl dotnet-example[3445]:          at MailKit.Net.Smtp.SmtpClient.FlushCommandQueueAsync(MimeMessage message, MailboxAddress sender, IList`1 recipients, Boolean doAsync, Cancell
Jul 27 10:08:08 specodit.pl dotnet-example[3445]:          at MailKit.Net.Smtp.SmtpClient.SendAsync(FormatOptions options, MimeMessage message, MailboxAddress sender, IList`1 recipients, Boolean doAsyn
Jul 27 10:08:08 specodit.pl dotnet-example[3445]:          at StableManagement.Services.MailService.SendMessage(Notification notification) in /home/admin/web/kumminui.pl/App/StableManagement/Services/M
Jul 27 10:08:08 specodit.pl dotnet-example[3445]:          at StableManagement.Data.ScheduleTask.ScheduledItemChangeState(DateTime scheduleFor) in /home/admin/web/kumminui.pl/App/StableManagement/Data/
Jul 27 10:08:08 specodit.pl dotnet-example[3445]:          at StableManagement.Data.ScheduleTask.RecoverScheduledTasks() in /home/admin/web/kumminui.pl/App/StableManagement/Data/ScheduleTask.cs:line 48
Jul 27 10:08:08 specodit.pl dotnet-example[3445]:          at API.Program.Main(String[] args) in /home/admin/web/kumminui.pl/App/StableManagement/Program.cs:line 33

I send the email with .NET Core and MailKit:
    private async Task<MimeMessage> PrepareMessage(AppUser user, string subject, BodyBuilder body)
    {
        var emailSMTPUserName = (await _settingsRepository.Get("emailSMTPUserName"))?.Value ?? "email@example.com";
        MimeMessage message = new MimeMessage();

        MailboxAddress from = new MailboxAddress("Kumminui - Administracja", emailSMTPUserName);
        message.From.Add(from);

        MailboxAddress to = new MailboxAddress(user.FirstName + " " + user.LastName, user.Email);
        message.To.Add(to);

        message.Subject = subject;
        var path = "./Data/htmls/emails/assets/logo.png";
        var image = body.LinkedResources.Add(path);
        image.ContentId = MimeUtils.GenerateMessageId();
        image.ContentDisposition = new ContentDisposition() { Disposition = ContentDisposition.Inline };
        body.HtmlBody = body.HtmlBody.Replace("./assets/logo.png", string.Format("cid:{0}", image.ContentId));

        message.Body = body.ToMessageBody();

        return message;
    }

And Send:
    public async Task SendMessage(Notification notification)
    {
        MimeMessage message;
        using (var memory = new MemoryStream(notification.Message, false))
        {
            message = MimeMessage.Load(memory);
        }

        var emailSMTPHost = (await _settingsRepository.Get("emailSMTPHost"))?.Value;
        var emailSMTPPort = (await _settingsRepository.Get("emailSMTPPort"))?.Value;
        var emailSMTPUserName = (await _settingsRepository.Get("emailSMTPUserName"))?.Value;
        var emailSMTPPassword = (await _settingsRepository.Get("emailSMTPPassword"))?.Value;
        if (emailSMTPHost is not null
            && emailSMTPPort is not null
            && emailSMTPUserName is not null
            && emailSMTPPassword is not null)
        {
            SmtpClient client = new SmtpClient();
            client.ServerCertificateValidationCallback = (s, c, h, e) => true;
            await client.ConnectAsync(emailSMTPHost, Int32.Parse(emailSMTPPort), SecureSocketOptions.Auto);
            await client.AuthenticateAsync(emailSMTPUserName, emailSMTPPassword);
            Console.WriteLine(client.IsAuthenticated);
            await client.SendAsync(message);
            await client.DisconnectAsync(true);
            client.Dispose();
        }
    }

The message is loaded from DB and sent to the user at a specific moment. What could be an issue with the production environment? Those applications works on the same machine only the domain changes.
SMTP log:
Connected to smtps://specodit.pl:465/
Jul 27 10:40:18 specodit.pl dotnet-example[9875]: S: 220 specodit.pl ESMTP Exim 4.90_1 Ubuntu Tue, 27 Jul 2021 10:40:18 +0000
Jul 27 10:40:18 specodit.pl dotnet-example[9875]: C: EHLO [22.214.171.124]
Jul 27 10:40:18 specodit.pl dotnet-example[9875]: S: 250-specodit.pl Hello [18.104.22.168] [188.8.131.52]
Jul 27 10:40:18 specodit.pl dotnet-example[9875]: S: 250-SIZE 52428800
Jul 27 10:40:18 specodit.pl dotnet-example[9875]: S: 250-8BITMIME
Jul 27 10:40:18 specodit.pl dotnet-example[9875]: S: 250-PIPELINING
Jul 27 10:40:18 specodit.pl dotnet-example[9875]: S: 250-AUTH PLAIN LOGIN
Jul 27 10:40:18 specodit.pl dotnet-example[9875]: S: 250-CHUNKING
Jul 27 10:40:18 specodit.pl dotnet-example[9875]: S: 250 HELP
Jul 27 10:40:18 specodit.pl dotnet-example[9875]: C: AUTH PLAIN AGFkbWluQGt1bW1pbnVpLnBsAGMxOU91bkNsN08=
Jul 27 10:40:18 specodit.pl dotnet-example[9875]: S: 235 Authentication succeeded
Jul 27 10:40:18 specodit.pl dotnet-example[9875]: C: MAIL FROM:<firstname.lastname@example.com> SIZE=51244 BODY=8BITMIME
Jul 27 10:40:18 specodit.pl dotnet-example[9875]: C: RCPT TO:<email@example.com>
Jul 27 10:40:18 specodit.pl dotnet-example[9875]: S: 550 220.127.116.11 is _my_ address
Jul 27 10:40:18 specodit.pl dotnet-example[9875]: C: RSET

Answer: The error being returned as part of the RCPT TO command is weird seeing as how the error message seems to refer back to the EHLO command:
C: EHLO [184.108.40.206]

The SMTP server is rejecting you because the IP address that the client is claiming to be is the same IP address as the server.
You can override this by setting the client.LocalDomain property which will be used in the EHLO command instead of the auto-detected IP address. You could try setting that to something (maybe "localhost"?) and see if that solves it.


How to show rendered html text in ui?

Question: I have HTML content from sql query.When I am showing this in UI it is displaying tags too.I want to show the text with the html properties(bold).
My text : Total Amount
This is show as Test in ui.When i checked with fire fug it is showing as ">Test

from sql :  'Total Amount' AS Amount
How can I solve this?
Comment: share your  code
Answer: It may be caused by using jquery text() method when you are showing your result in the UI. You have to use $('#yourHtmlTag').html('Total Amount') instead of $('#yourHtmlTag').text('Total Amount').

How to show rendered html text in ui?


How to rename files with count?

Question: I have a directory like this:
randomized_quad015.png
randomized_quad030.png
randomized_quad045.png
randomized_quad060.png
randomized_quad075.png
randomized_quad090.png
randomized_quad1005.png
randomized_quad1020.png
randomized_quad1035.png
randomized_quad1050.png
randomized_quad105.png
randomized_quad1065.png
randomized_quad1080.png
randomized_quad1095.png
randomized_quad1110.png
randomized_quad1125.png
randomized_quad1140.png

and I want to rename the first files adding 0 in front of number, like:
randomized_quad0015.png

But I don't know how. Some help?
Answer: rename is a command-line tool that lets you rename files, using a Perl command to transform the name. A Perl command that's commonly used in this circumstance is s/REGEXP/REPLACEMENT/.
If I interpret your question correctly, you want to add a leading 0 in the names that have fewer than 4 digits, so that all the names end up having 4 digits. This slightly complicated expression handles the general case where you have file names with 1, 2 or 3 digits: it aligns all of them to 4 digits. The e modifier at the end causes the replacement to be interpreted not as a string but as a Perl expression. This expression repeats the digit 0 as many times as necessary to pad the number to 4 digits.
rename 's/(?=([0-9]+)\.)/"0" x (4 - length($1))/e' *.png

If the files you want to rename all have three digits, there are simpler ways, such as
rename 's/[0-9]+\./0$&/' *[!0-9][0-9][0-9][0-9].png

or
rename 's/(?<=[^0-9])[0-9]{3}\./0$&/' *.png

Answer: As an alternative to the various Perl-based methods in other answers, you can do this particular example, and lots of other similar ones with plain bash:
for i in randomized_quad???.png; do
  mv $i randomized_quad0${i#randomized_quad}
done

This loops over the filenames with only three characters in the number region, and the variable expression in braces takes each filename, snips "randomized_quad" off the front (with the # operator), and adds "randomized_quad0" on the front.
Other excitingly useful operators like this include:

% - cut something off the end
/ - search and replace (/ for the first match, // for all matches)
: - for extracting substrings

A more complete list with examples is here. Also, note that these use POSIX-style regular expressions, so . will match any character, not just a "." If you want to match a ".", you should 'escape' it, with a backslash:
TestVariable1="filename.png"
TestVariable2="filename0png"

echo "${TestVariable1%.png}"
> filename

echo "${TestVariable2%.png}"
> filename

echo "${TestVariable1%\.png}"
> filename

echo "${TestVariable2%\.png}"
> filename0png

Answer: rename 's/quad([0-9]{3})\.png/quad0$1/' randomized_quad*

Comment: you might mean `{3}`
Answer: With a recent version of bash you could write:
for f in randomized_quad*.png; do
    if [[ $f =~ [1-9][0-9]* ]]; then
        new=$(printf "randomized_quad%04d.png" ${BASH_REMATCH[0]})
        [[ $f != $new ]] && mv -v $f $new
    fi
done

How to rename files with count?


Terraform: provisioning via app/client id and secret

Question: In azure portal, i have a registered app named 'terraform'.
I also created a Client Secret for this app.
Lastly, the App has the role 'Cloud  Application Administrator'
I would like to use this to run my terraform code which will create/provision resources.  i have the following:
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = ">=3.53.0"
    }
    azapi = {
      source = "azure/azapi"
    }
  }
}

provider "azurerm" {
  features {}
  subscription_id = "<subscription_id>"
  client_id = "<client_id>"
  client_secret = "<client_secret>"
  tenant_id = "<tenant_id>"
}
provider "azapi" {
  subscription_id = "<subscription_id>"
  client_id = "<client_id>"
  client_secret = "<client_secret>"
  tenant_id = "<tenant_id>"
  use_cli = true
}

data "azurerm_container_registry" "acr" {
  name                = "container-registry"
  resource_group_name = "coreinfra-eastus-rg"
}

In the above, "container-registry" is an existing azure container registry.  when i run a terraform plan, i am seeing the following:
│ Error: retrieving Registry (Subscription: "<subscription_id>"
│ Resource Group Name: "coreinfra-eastus-rg"
│ Registry Name: "container-registry"): unexpected status 403 with error: AuthorizationFailed: The client '<object_id>' with object id '<object_id>' does not have authorization to perform action 'Microsoft.ContainerRegistry/registries/read' over scope '/subscriptions/<subscription_id>/resourceGroups/coreinfra-eastus-rg/providers/Microsoft.ContainerRegistry/registries/container-registry' or the scope is invalid. If access was recently granted, please refresh your credentials.
│
│   with data.azurerm_container_registry.acr,
│   on data.tf line 1, in data "azurerm_container_registry" "acr":
│    1: data "azurerm_container_registry" "acr" {

In the above "<object_id>" is the id for my 'terraform' app.
How do i add the roles necessary to allow this app to broadly create/provision any cloud resources?
Is this the correct approach im taking - using an app to enable access to creation of cloud resources or is there a better approach?
Comment: Make sure to assign the **Reader** role at the Resource Group or Container Registry level to allow the Service Principal to retrieve the container registry.
Answer: 'Microsoft.ContainerRegistry/registries/read'

I also created a Client Secret for this app. Lastly, the App has the role 'Cloud Application Administrator'
How do i add the roles necessary to allow this app to broadly create/provision any cloud resources?

The Cloud Application Administrator   is Microsoft Entra ID role for enabling, disable, and delete devices in Microsoft Entra ID in the Azure portal.
To create or provision resources within a subscription, you may need an RBAC role at the subscription level. In your case, as you are attempting to read the container registry, it may necessitate having the Reader Role on the subscription for the  service principals.
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = ">=3.53.0"
    }
    azapi = {
      source = "azure/azapi"
    }
  }
}

provider "azurerm" {
  features {}
  subscription_id = "<subscription_id>"
  client_id = "<client_id>"
  client_secret = "<client_secret>"
  tenant_id = "<tenant_id>"
}
provider "azapi" {
  subscription_id = "<subscription_id>"
  client_id = "<client_id>"
  client_secret = "<client_secret>"
  tenant_id = "<tenant_id>"
  use_cli = true
}
data  "azurerm_container_registry"  "acr"  {
name = "venkatacrtest"
resource_group_name = "v-venkal-Mindtree"
}

After running the above Terraform code, I'm able to read the container registry.

Reference: Cloud Device Administrator
Assign Azure roles using the Azure portal
Comment: Hi @mike01010, For the list credentials action, you can assign the Contributor role.
Comment: thank you - can you explain how to add the RBAC role at the subscription level? i have to say that seems quite broad and dangerous.  But i will try it to confirm.
Btw, as any of this changed in the last 6 months - because all this was working fine about 6 months ago when i ran these scripts.
Comment: You may follow this link : https://learn.microsoft.com/en-us/azure/role-based-access-control/role-assignments-portal?tabs=delegate-condition for assigning RBAC role on subscription level.
Comment: This helped thanks.  i added the reader role, but i thinki need some 'List" roles:
```does not have authorization to perform action 'Microsoft.ContainerRegistry/registries/listCredentials/action'```.   i dont see any such roles except for Kubernetes


Markers in Openlayer LineString

Question: Is there anyway to divide the openlayer line into equal segments? I want to generate markers at defined interval in the line.
Comment: I believe openlayers has no built-in functionality for this, but it can be easily done with a bit of your own code. If this answer is not enough, I can prepare a fiddle when I get to my computer.
Comment: yes please. If you can, please let me know, how can it be done? Thanks.
Comment: Also, the line is not straight. It could have multiple vertices.
Answer: Here's a script that splits a linestring into n equally long segments and generates a point geometry at each split point: https://gist.github.com/Kenny806/37c767f46bcb2687e0ae
I understand you wanted to split a line into segments by defining the length of a segment, rather than number of segments, but you can get the number of segments easily like this:
<code>var n = geometry.getLength() / desiredSegmentLength;
</code>
Of course, you should make sure that n is a positive integer.
Hope this helps
Comment: There's an example of a modified version of that script being used for styling here https://gis.stackexchange.com/questions/306976/add-image-along-the-linestring/306979

Markers in Openlayer LineString


How to get more info on AnimationException?

Question: I have a WPF application where I create a Storyboard to animate some controls. After triggering the animation the project breaks but all I get from Visual Studio is the bellow output message:
Exception thrown: 'System.Windows.Media.Animation.AnimationException' in WindowsBase.dll

How is it possible to get more info so I would know exactly where the problem is? The documentation only states that

The exception that is thrown when an error occurs while animating a
  property.

I have no idea in which line the code broke in order to insert a try-catch block.
Comment: You create an animation in a storyboard. That is an object which you then start. Unless you wrote a custom animation, there won't be a line in your code to return an error. What animation are you using on what?
Comment: Ineed I wrote a custom animation @Andy. The storyboard includes `DoubleAnimationUsingPath` and `DoubleAnimation`. I apply it to normal controls.
Answer: First of all I would catch these unhandled exceptions like this:
public MyCustomControl()
{
  Dispatcher.UnhandledException += Dispatcher_UnhandledException;
}

void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
  switch (e.Exception)
  {
    case AnimationException aniEx:
      Log(aniEx.GetDetails());
      break;
    // ...
    // default: ...
  }
}

and second I would add a GetDetails extension for exceptions to get all details out of it:
public static class Extensions
{
    ///
    /// Returns all Details of an exception
    ///
    /// <param name="exception"></param>
    /// <returns></returns>
    public static string GetDetails(this Exception exception)
    {
        string GetInnerExceptionDetails(Exception e)
        {
            var s = new StringBuilder(e.GetType().FullName);
            if (e.GetType().GetProperties()
                 .Select(prop => new { prop.Name, Value = prop.GetValue(e, null) })
                 .Select(x => $"{x.Name}: {x.Value ?? string.Empty}").ToList() is List<string> props && props.Any())
            {
                s.AppendLine(string.Join(Environment.NewLine, props));
                s.AppendLine();
            }

            if (e.InnerException != null)
                s.AppendLine(GetInnerExceptionDetails(e.InnerException));
            return s.ToString();
        }
        return GetInnerExceptionDetails(exception);
    }
}


Index was outside the bounds of the array. Rijndael Encryption

Question: Before spending any time reading this, see the self-answer below. The problem was invalid input.

When I try to decrypt some strings it throws this exception:
    "   at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast)
       at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
       at System.Security.Cryptography.CryptoStream.FlushFinalBlock()
       at System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing)
       at System.IO.Stream.Close()
       at System.IO.Stream.Dispose()
       at EBookReader.cryptography.DecryptString(String message, String KeyString, String IVString) in C:\\Users\\XWare\\Documents\\Visual Studio 2008\\Projects\\EBookReader\\EBookReader\\cryptography.cs:line 94"

Under debugging it throws the exception on this line :
    byte[] messageBytes = Convert.FromBase64String(message);

I think this problem just appears when string to decrypt is too big because when I try to encrypt and decrypt short strings like "Hi there I am X-Ware" it works fine
    public static string DecryptString(string message, string KeyString, string IVString)
    {
        byte[] Key = ASCIIEncoding.UTF8.GetBytes(KeyString);
        byte[] IV = ASCIIEncoding.UTF8.GetBytes(IVString);

        string decrypted = null;
        RijndaelManaged rj = new RijndaelManaged();
        rj.BlockSize = 256;
        rj.Key = Key;
        rj.IV = IV;
        rj.Mode = CipherMode.CBC;
        rj.Padding = PaddingMode.PKCS7;
        try
        {
            MemoryStream ms = new MemoryStream();
            Encoding enc = new ASCIIEncoding();
            using (CryptoStream cs = new CryptoStream(ms, rj.CreateDecryptor(Key, IV), CryptoStreamMode.Write))
            {
                byte[] messageBytes = Convert.FromBase64String(message);
                cs.Write(messageBytes, 0, messageBytes.Length);
                cs.FlushFinalBlock();
            }// This is line 94
            byte[] encoded = ms.ToArray();
            decrypted = enc.GetString(encoded);

            ms.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("An error occurred: {0}", e.Message);
        }
        finally
        {
            rj.Clear();
        }

        return decrypted;
    }

any suggestions ?!
P.S. I wrote a comment to show you line 94 // This is line 94
Comment: Your Key and IV are extremely weak. Look up PasswordDeriveBytes
Comment: `ASCIIEncoding.UTF8` is horrible style. Use `Encoding.UTF8`.
Comment: You should also follow @Henk's advice. The way you get your key from the password is bad. Use the `Rfc2898DeriveBytes` class(It's the successor of the class Henk mentioned).
Answer: The FlushFinalBlock method is only intended to flush the last complete or partial block of bytes. Thus if you write more than a single block size it is not the right method call to make. Try instead simply closing the crypto stream before you attempt to read from the memory stream.
To do this in the context of your code, simple remove the line cs.FlushFinalBlock()...
Comment: would you please explain this by an example?!
Comment: I tried what you told me it is not working ... the exception is thrown on line 91 Convert.FromBase64String(message); when I put this line before opening cryptostream it throws Invalid character in a Base-64 string. Note that this string is generated in PHP but someother strings are decrypted successfully while some other did not.
Comment: But that's not the exception you posted. If the string is generated in PHP, is it being URL encoded or something similar before reaching the .NET code?
Answer: The problem is that the string I pass as Base64 string is invalid the problem is just in the input file which makes decryption impossible
Thanx all


Can't send jwtToken from react client to node/express backend with axios

Question: I am about to learn full stack development with react, node and postgresql and facing a jwttoken authorization issue. I need your support.
Whenever I try to send my token from react to my backend API with axios I get following error message.
Failed to load resource: the server responded with a status of 403 (Forbidden)
createError.js:16 Uncaught (in promise) Error: Request failed with status code 403
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:62)

If I use postman or remove the authorization it works perfectly fine.
After some research I applied cors as middleware but still it doesn't work.
Further code:
server side
authorization.js
import jwt from "jsonwebtoken";
require("dotenv").config();

module.exports = async (req, res, next) => {
  try {

    console.log("TEST");
    console.log(req.header("token"));

    // Get token from header
    const token = req.header("token");

    // Check if not token
    if (!token) {
      return res.status(403).json("Authorization denied");
    }

    const payload = jwt.verify(token, process.env.jwtSecret);

    req.user = payload.user;

    next();
  } catch (err) {
    return res.status(403).json("Token is not valid");
  }
};

server.js
import express from "express";
const morgan = require("morgan");
import dotenv from "dotenv";
import cors from "cors";
dotenv.config();

const app = express();

// bring in routes
import hotelRoutes from "./routes/hotel";

// route middleware
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());

app.use("/api/hotel", hotelRoutes);

const port = process.env.PORT || 8080;
app.listen(port, () =>
  console.log(`A node Js API is listening to port: ${port}`)
);

hotel.js // routes
const express = require("express");
const { createhotel } = require("../controllers/hotel");
const { createhotelValidator } = require("../validator");
const authorization = require("../middleware/authorization");

const router = express.Router();
router.post("/", createhotelValidator, authorization, createhotel);

module.exports = router;

client side
hotel.js
import axios from "axios";

export const createhotel = async (token, data) => {
  await axios.post(`${process.env.REACT_APP_API}/hotel`, data, {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });
};

Comment: try header name "Authorization", not "token"... `const token = req.header("token"); `
Comment: Can you refer to https://stackoverflow.com/a/67556664/2822041
Answer: Change token to Authorization in your authorization.js file
console.log(req.header("Authorization"));

// Get token from header
const token = req.header("Authorization");

Comment: Thanks. This worked for me. But I did have to remove "Bearer" prefix from my client side hotel.js posted in my initial post. What is "Bearer" and why do I need it. Thanks in advance.
Comment: you can split string with `Bearer `


I can't boot of Ubuntu OS when my Windows 7 hibernates

Question: I have Ubuntu 12.10 and Windows 7 Home Basic in one machine. After I put my Windows 7 to hibernate and then when I press the power button, instead of loading the BOOT OPTIONS or GRUB screen it directly boots Windows 7. I've read in some forum that pressing ESC after you press the power button, but even it couldn't help me as the laptop started making a loud noise.
Please help me on how should I boot OS while hibernate W7 and again RESUME W7 after shutting down Ubuntu.
Thanks in anticipation.
Comment: Are you sure you're hibernating, not sleep?
Comment: Yup.. i hibernate my W7...den i press the power button, in the intention of booting Ubuntu; but to no avail. The only way i have to boot Ubuntu is SHUT DOWN W7, and then start the machine, and eventually choose the booting option from the Grub screen.(Hope you're getting my point??)
Comment: Can **ANYBODY** answer me?
Comment: @Alaa .. pls help mahn!!!!
Comment: How is your Ubuntu installed? Using Wubi (installed *inside* Windows) or on a separate partition?
Comment: @Alaa I have installed Ubuntu in the same hard disk as Windows 7 Home Basic's but different partition. My Windows reside in C parition and Ubuntu is H paritition.
Comment: H partition? You problem is that you installed Ubuntu inside Windows using Wubi. I'll post an answer explaining in a bit.
Comment: Wait. I just read your comment on amc's answer. How is it that you installed Ubuntu using a bootable USB, but you say "it's installed in the H: partition"? In your Windows **right now**, do you see an H: partition with an "Ubuntu" folder inside it?
Comment: @Alaa ..i know I am confusing things right now!! **Sorry** ...i'l give u the picture-
_I installed the Ubuntu by, first copying the .iso file in by USB and making the USB bootable with the help of instructions given by Ubuntu community(I mean when I was installing it, I kept on getting the instructions). OK!
And then, I installed an .exe file which let me install Ubuntu from Windows itself, without the need of, you know, booting the entire the system._
Comment: @Alaa ..got the picture!!????
Comment: Answer all these questions: what was the name of that `.exe` file? `wubi.exe`? In your Windows right now, do you see an H: partition with an "Ubuntu" folder inside it?
Comment: @Alaa
1. Yup, it was wubi.exe.. _thanks for reminding me_ .
2. Yup, I have a partition named H, with an Ubuntu folder in it...comprising of Ubuntu OS files.
Answer: First, it's important to understand the technical reasons why what you are are hoping to achieve is likely infeasible. When you hibernate Windows the computer writes everything in memory to the harddrive and powers off the computer. When hibernating, any changes to the disk could corrupt the install and render your computer unusable. Therefore, hibernation is specifically designed NOT to allow you switch between OSes while one is hibernating.
That being said, see  https://superuser.com/questions/46299/is-it-possible-to-enable-hibernation-when-dual-booting-windows
Depending on your setup you should be able to use your BIOS boot menu to switch between OSes when hibernating.
This relies on you having installed each OS on different physical drives.
Comment: Why is it infeasible? It's perfectly normal to do it. Windows "writes everything in the memory to the harddisk" to a file called hiberfil.sys. Starting up a computer after a hibernate should start normally, and load the bootloader, giving you the OS options (even if both are installed on the same physical hard disk on different partitions). I am dual booting, and as far as I remember, I can hibernate Windows and boot Ubuntu, without having to change anything.
Comment: thanks for the reply...actually my friend has tried and succeeded in doing it. I installed Ubuntu 12.10 in the following way:
1. Downloaded Ubuntu 12.10 in .iso format.
2. Made a bootable USB with the .iso file in it(with unetbootin software)
3. Installed Ubuntu with USB, also, I downloaded an application which helped installed Ubuntu from Windows without restarting Windows 7.
4. Installed properly...with virtually no glitches...
Can you specify an alternate way to get Grub Screen?? I know the risks..but just wanna know it, and wanna try it.
Comment: @Alaa...can u suggest an alternate way ??
Comment: Depends on how you use your system -- it's potentially dangerous to access anything on the windows drive while using Ubuntu. I know that when I dual boot I still want to access and modify the windows file system.
Comment: @amc yes, I completely agree, it is dangerous, that's why one can't mount a hibernated Windows partition (we get an error). However, the problem with the person that asked the question is that he **can't even boot into Ubuntu when he hibernates Windows**; he doesn't even get a choice of OS.
Answer: Answer:
Because you have Ubuntu installed using Wubi, unfortunately, you won't be able to choose which OS you want to boot if Windows is hibernated.
Explanation:
From the comments, it seems that you have Ubuntu installed using Wubi, which means that you installed Ubuntu inside Windows. This is because in the comments, you said "Ubuntu is installed on partition H:", which probably means that you can access this H: partition from your Windows OS and see a folder called "Ubuntu" inside it, correct? If yes, read on:
When you restart your computer, it boots BOOTMGR by default, which is the Windows bootloader, and gives you the OS choice (Windows or Ubuntu). If you select Ubuntu, you go into GRUB. All good so far. However, the first thing BOOTMGR does (before giving you the OS choice) is it first checks if there is a hibernated OS. When it finds that Windows is hibernated, it directly boots into it, without giving you the options. This is what is happening on your machine. GRUB, on the other hand, does not do this.
How would you overcome this? By making GRUB the default bootloader (with Ubuntu and Windows as OS choices), not BOOTMGR. This, however, is in the case if Ubuntu is installed on a separate partition (a partition formatted in another format, ext4, that is not accessible through Windows). But because your Ubuntu is installed through Wubi, meaning that it's on the H: partition, meaning that it's on a Windows partition, this partition is part of the hibernated Windows! Get it =)? So we can't install GRUB as the default bootloader and ask it to boot Ubuntu from the hibernated partition, because then it will (I think) attempt to destroy the "hibernated data" and basically shutdown your Windows (and you lose all your unsaved data when you hibernated), then attempt to boot into Ubuntu. Get it now?
So in the end, unfortunately, I don't think it's feasible. Your solution would be to uninstall Ubuntu/Wubi, and install Ubuntu from scratch on a separate partition. This solution will uninstall Ubuntu/Wubi and will delete everything in your Ubuntu, so make sure you backup the files you need.
Another possible solution is to convert (migrate) your Wubi Ubuntu into a full, normal Ubuntu installation (put in on a separate partition). This way, it will copy over all your content, and you should find all your files the way they were (**although it is always advisable to backup your files whenever playing around with OSs). The steps to do this solution are detailed here: How to convert Wubi install into regular install? Here is a brief description of what you'll be doing:

Boot into your Wubi Ubuntu.
Using gparted, create an empty partition big enough to house your Wubi Ubuntu (just make a partition as big as your H: partition, or as big as the "Ubuntu" folder). Choose ext4 as the filesystem type for the new partition.
Download the script from that question, and run sudo bash wubi-move.sh /dev/sdaX, where sdaX is your new partition you created in step 1 ("X" is a number, e.g. sda6. You can see the number of that new partition in gparted next to the partition).

Again, this is a brief description. Visit the question I linked and read the whole thing.
Having said all of this, my advised solution would be to:

Backup everything you want from your Ubuntu.
Completely remove Ubuntu Wubi (How do I uninstall Wubi)
Install Ubuntu from scratch.

If your H partition was only meant for Ubuntu, then you can use that whole partition to install the new Ubuntu.
Comment: ...thanks a lot for such an elaborate explanation!! your last sentence said that _I can uninstall Wubi_..right??? so, if i do that will I lose all my data in ubuntu.. i.e all my softwares and applications like NetBeans, OpenJdk, etc..??? or else, should I **RE-INSTALL** Ubuntu ...???
Comment: There is a way to convert your Wubi to a full installation. In my opinion though, you should backup your files, completely remove and uninstall Wubi (deleting everything), and reinstall Ubuntu. This way, it's "cleaner", you know, because you never know what may go wrong, or if it's going to be stable. I've edited my answer to include more info on both solutions.
Comment: thanks a lot bro!!!!!!!!!!!!!!!!!! Will boot Ubuntu n den remove the WUBI crap from it. :)
Answer: I am answering the part of the question that deals with the issue "I can't even resume Windows". I was also having this problem... in a system with dual-boot installation of Windows 7 and Ubuntu (actually Linux Mint 17 64-bit!), I have a modern system (Gigabyte motherboard with UEFI bios) and can selectively boot the Windows boot manager, the GRUB loader, etc.
When I hibernate my W7 session, no matter what I do, I cannot resume it. I always get
"Your computer cannot come out of hibernation"

and the error shown is code 0xC000009a. It doesn't matter if I choose the Windows boot loader from the BIOS boot menu, or use GRUB and select the Windows boot option; the end result is the same: I am forced to destroy the information from the suspended (hibernated) W7 session and boot "fresh" into Windows.
Researching this a bit, especially by searching for that error message and the specific code, I found this solution, credit where it is due: http://www.sevenforums.com/general-discussion/307622-serious-error-0xc000009a.html and http://answers.microsoft.com/en-us/windows/forum/windows_7-system/windows-boot-manager-your-computer-cant-come-out/a3170a6f-2962-45ac-8005-bde7abb35831
Apparently, the error code indicates an error relating to registry information in Windows. But, it appears there also may be some problem with the hiberfil.sys file that Windows uses to store the hibernated information.
SO, the fixes suggested by both of these websites is as follows:

Find your Start -> All Programs -> Accessories -> Command Prompt item on the menu, right click it, and select Run As Administrator. Then, type the following command:
powercfg -h off
Reboot your system (do NOT hibernate)...
when you are back in Windows again, repeat the running of Command Prompt with Administrator privilege as above (kinda like "sudo"), then type:
powercfg -h on
test your fix by hibernating W7, then waking the machine up and (if you enter the GRUB loader due to your setup) choose to boot Windows 7. It should say "Resuming Windows"

This sequence of steps apparently clears up any corrupted hiberfil.sys AND any Registry "misapprehensions" about how your hibernation is set up. I don't have more technical detail as to why it works, but it does! I can now hibernate freely, and boot back into Windows 7 after hibernating, even using GRUB as the boot manager (but of course, selecting Windows boot).
I changed my GRUB default to boot Windows after the timeout, so that restoring my hibernated sessions of W7 would be the most convenient for me. I use W7 more than Linux, but with the dual boot setup, I have the best of both worlds!
Thanks to every person out there who has brought us this wonderful free software called GNU/Linux!


Append table row with user input

Question: I have a table of data as follows-

        ID
        First Name
        Last Name

And I have an input form section as follows-
<form>
      <input type="text" id ="userID">
      <input type="text" id ="firstname">
      <input type="text" id ="lastname">
      <input type="submit">
</form>

Can someone help me out with the javascript required to append a new row to my table containing data gained from the user input form?
Comment: Have you tried anything?
Comment: Would you mind using jquery
Comment: Yup. jQuery all the things
Comment: Either your markup has a typo or it is invalid.
Comment: Try http://jsfiddle.net/97ZpN/1/
Answer: You don't need jQuery to do that. Just use javascript.
You can use a function like this:
HTML with function on click of submit button..

        ID
        First Name
        Last Name

<form action="">
    <input type="text" id ="userID" />
    <input type="text" id ="firstname" />
    <input type="text" id ="lastname" />
    <input type="submit" onclick="return fillTable();" />
</form>

JavaScript
function fillTable() {
  var table = document.getElementById("myTable");
  var row = table.insertRow(0);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);
  cell1.innerHTML = document.getElementById("userID").value;
  cell2.innerHTML = document.getElementById("firstname").value;
  cell3.innerHTML = document.getElementById("lastname").value;
  return false;
}

I've build a JSFiddle for you to illustrate the behavior.

Append table row with user input


Reference type is changed in proxy class that generated from WCF

Question: I know the title is little confusing, so here is the explaination:
I am trying to streaming a large file with WCF and I kind of know how to do it.
When I wrote a method say:
    [OperationContract]
    void sendStream(System.IO.Stream _StreamSource);

There, the generated proxy class insides my Client App will have the System.IO.Stream type as input parameter correctly.
But if I create another class:
[MessageContract]
[KnownType(typeof(Stream))]
public class MyData
{
    [MessageHeader(MustUnderstand = true)]
    public string Key { get; set; }
    [MessageBodyMember(Order = 1)]
    public Stream Data { get; set; }
}

And have the service interface:
    [OperationContract]
    void sendStream(MyData _StreamSource);

The stream type from MyData in my client class will be under Service Reference namespace.
i.e: MyServiceRef.Stream
Which made me cannot pass the stream to WCF.
But this doesn't happen for string and int stuff.
I wonder why, I throught Stream type is known type like string and int?
Or is there any workaround?
Thanks in advance!
Answer: The KnownType attribute instructs WCF to add type definitions to the service reference.  It appears that this also has the side effect of making any properties of a KnownType inside the DataContract to use the service-generated type.  (This makes sense for the normal usage of KnownType, where WCF does not otherwise know about the type.)
Did you try using the contract without declaring Stream as a KnownType?
Comment: I did try, but it doesn't work, that's why I added the KnownType to try my luck
Answer: Stream is not serializable like int or string. So you can't use them as a property of a messagecontract.
You can, however, use streaming in wcf : http://msdn.microsoft.com/en-us/library/ms731913.aspx, but this require to have the stream as the unique parameter.
Comment: But what I did above is working if I do not use auto-generated proxy class by sharing the service interface with client and using ChannelFactory. So does that means is impossbile to do it with auto-generated proxy class? (and yes, I am using streaming in wcf)
Comment: I admit I'm surprised this works with ChannelFactory... as described in the [link](http://msdn.microsoft.com/en-us/library/ms731913.aspx) above : `Restrictions on Streamed Transfers : Operations that occur across a streamed transport can have a contract with at most one input or output parameter. That parameter corresponds to the entire body of the message and must be a Message, a derived type of Stream, or an IXmlSerializable implementation. Having a return value for an operation is equivalent to having an output parameter.`
Comment: I am guessing that's what is mean by at most one input or output parameter is means the [MessageBody] in the above of code, since the [MessageHeader] is not the part of streaming during transfer. The streaming part should be the [MessageBody]. (And I tried to made another [MessageBody] in the code, it gives me error saying "In order to use Streams with the MessageContract programming model, the type MyData must have a single member with MessageBodyMember attribute and the member type must be Stream.")


shell_exec with PHP

Question: I am attempting to run apktool (just a tool to unpackage android applications) over the web using PHP shell_exec but it isn't working.  Does anyone know why this might be?
This is what the line of code actually looks like:
   $output = `apktool d -f $file_name`;

Any suggestions would help I'm totally at a loss why I run the php and nothing happens.
Thanks!
Comment: Probably important to call http://php.net/escapeshellarg
Comment: Are any errors output?  Try using the `exec` function instead, this will give you access to the output of the `apktool` command if you use the second or third arguments.  Post the output back here if you want more help.
Comment: apktool is usually run using a simple shell command `apktool d -f $file_name` which is why I basically just copied that command and put it in the backticks.  I also tried it with `shell_exec` and `exec` and nothing so far.
Comment: And I know php.ini has `safe_mode` off and it is not in `disable_functions`  I feel like I'm doing it right which is why I'm so confused.
Answer: I found the solution.
Create build.sh file with exec permissions and write there this code:
#!/bin/bash
export PATH=/opt/local/bin:/opt/local/sbin:/usr/bin/:/usr/sbin/:/bin:/sbin/:/bin/sbin:/usr/local/bin:/usr/X11/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin

/usr/local/bin/apktool b -d $1 $2

--
usage ./build.sh
<? php shell_exec("/path/to/build.sh $dir $file"); ?>

Answer: check if you web server (probably apache) has sufficient permissions to execute apktool. Include the whole path to the apktool binary. Use single quotes if there are spaces in your file name.
Check your web server's logs if there is any detail why the command is not executed.
Answer: Make sure that your actual line is:
 $output = shell_exec(`apktool d -f $file_name`);

And that your php.ini file does not have safe_mode turned on or have shell_exec listed in
the disable_functions directive.

shell_exec with PHP


String formatting in output

Question: I have a python script that looks like this:
    print "Header 1"
    print "\t Sub-header 1"
    print "\t\t (*) Sentence 1 begins here and goes on... and ends here."

The sentences are being printed in a loop with the similar format, and it gives an output like this in the terminal:
Header 1
    Sub-header 1
        (*) Sentence 1 begins here and goes on...
and ends here.
        (*) Sentence 2 begins here and goes on ...
and ends here.
         .
         .
         .

Is there any way I can make the formatting as follows? :
Header 1
    Sub-header 1
        (*) Sentence 1 begins here and goes on...
            and ends here.
        (*) Sentence 2 begins here and goes on ...
            and ends here.
         .
         .
         .

Comment: There is certainly a way to make the formatting as you wish, but the correct way to do this may depend of your existing code. Can you explain how this formatting is done for the moment?
Comment: I use something print `print ('Text_1= %-20s   | Text_2 = %0s    | Text_3 = %6s\n') %('Here', 'Here_2', 'Here_3')` to print on screen. Does this help you? (run it)
Comment: @SnuKies: Thank you, but it doesn't help in my case. Due to the sentences being too long, the formatting still breaks in the terminal.
Comment: @Tryph: I've edited the question to explain how I've done the formatting. Any help is appreciated, thank you.
Answer: with the help of the textwrap module, it could be done quite easily:
import textwrap

LINE_LENGTH = 80
TAB_LENGTH = 8

def indent(text, indent="\t", level=0):
    return "{}{}".format(indent * level, text)

def indent_sentence(text, indent="\t", level=0, sentence_mark=" (*) "):
    indent_length = len(indent) if indent != "\t" else TAB_LENGTH
    wrapped = textwrap.wrap(text,
                            LINE_LENGTH
                            - indent_length * level
                            - len(sentence_mark))
    sentence_new_line = "\n{}{}".format(indent * level, " " * len(sentence_mark))
    return "{}{}{}".format(indent * level,
                           sentence_mark,
                           sentence_new_line.join(wrapped))

print indent("Header 1")
print indent("Sub-header 1", level=1)
print indent_sentence("Sentence 1 begins here and goes on... This is a very "
                      "long line that we will wrap because it is nicer to not "
                      "have to scroll horizontally. and ends here.",
                      level=2)

It prints this in a Windows console where tab are 8 chars long:
Header 1
        Sub-header 1
                 (*) Sentence 1 begins here and goes on... This is a very long
                     line that we will wrap because it is nicer to not have to
                     scroll horizontally. and ends here.

Comment: Thank you! This was exactly what I was looking for!

String formatting in output


Custom login vs existing service auth?

Question: When needing to setup a login system for your app, both backend and front-end, what is the quickest to implement:

create your own custom login (username, email, password...)
use one of the existing credential services (FB, Twitter, Linkedin, G+ etc)

Thanks for your opinions!
Answer: Of course using an existing service is faster, especially with Facebook:
https://developers.facebook.com/docs/reference/plugins/login/
"Get code" > done. No database needed, no PHP needed, no need to think about security and stuff because that´s all done by Facebook.

Custom login vs existing service auth?


replacing a 3 way switch with 4 wires

Question: I'm trying to replace a 3 way switch with a smart switch but the wiring is confusing.
There's no green or bare ground and I was trying to figure out what the wire setup is with 2 black wires, 1 red, and 1 white.  In the photo, you can see what looks to be neutral wires above the switch. But I'm not confident enough to make any definitive calls on this at all. Throwing it out to the community for help.
Appreciate any help I can get!
Edit sorry I added a photo originally. Apologies to everyone who kindly answered without having that to reference. Added now because of course you'd need to see this ♂
Comment: Most of the time, you don't get a choice where the 3-way "smart switch" goes. You can't just slap it anywhere you want. We'll need to have a look at your wiring. Please draw or show photos of the wiring in both switches.
Comment: Pictures of all the wiring (with none of the devices disconnected!) involved will be most helpful in getting you an accurate and _safe_ answer.
Comment: In case it's not clear, you have to [Edit] your question to add the requested pics.
Comment: 3 way switch would have 3 wires, no ground. You could repurpose the wiring coming from the other 3 way switch
Comment: Thank you to all of you who tried to help me without a photo. I swear I'd attached one...but apparently not. I've added it now and I'm grateful for any help.
Comment: My guess  would be
White -> neutral
One red and one black : traveler wires
other black: hot feed to source or to light.

But you have to check it with a multimeter or a test light.
Answer: No ground? I've never seen switches like this, as the body appears all plastic, so perhaps ground is not needed, and perhaps this is permissible in your jurisdiction.
As to the 4 wires, well you really don't have 4, as as far as the switch is concerned, the 2 black wires are the same. These could have been implemented by twisting the 2 blacks together with a 3rd pigtail wire, and then that single pigtail wire brought to the switch and you would have only seen 3 wires at the switch, However, the electrician choose to join these wires by bringing one to the side screw and one to the backstab. Same effect, but not as clean in my opinion.
What to do? If your new switch has a ground, then you will have to find a ground in the box and bring it to the switch. As for the 2 blacks, you could do what was done here, use side screw and backstab (do not put both wires under the same screw!) or you could do as I suggest in the previous paragraph and use a pigtail.

replacing a 3 way switch with 4 wires


Device Admin Settings Intent

Question: I am trying to have a shortcut to the device admin settings page on my Widget.
I have looked at the AndroidManifest.xml (for the standard Android Settings App) for the Intent string, but it doesn't seem to be there, any ideas where it would be?
Thanks!
Answer: As per the answer here you can launch an Intent with any string from the android.provider.Settings class, with different ones for different things. The list of available strings is here.
Comment: Did you find the appropriate Intent for Device Admin Ash? If so please share.
Comment: Thanks Martin, I have been using that list, but it doesn't seem to be exhaustive.  I have been able to find quite a few more in the Android Settings App's AndroidManifest.xml, but for DeviceAdminSettings it just lists the generic: - .  I thought there might have been a bigger list somewhere.  Thanks for your help!

Device Admin Settings Intent


apache2 is not starting

Question: Starting web server apache2
(99)Cannot assign requested address: AH00072: make_sock: could not bind to address 10.0.1.43:8069
no listening sockets available, shutting down
AH00015: Unable to open logs
Action 'start' failed.
The Apache error log may have more information.

The apache2 instance did not start within 20 seconds. Please read the log files to discover problems

Answer: Like the error message says, "(99)Cannot assign requested address: AH00072: make_sock: could not bind to address 10.0.1.43:8069
no listening sockets available, shutting down". Some other process has allocated the socket you are trying to make Apache use (probably an earlier attempt to start Apache).
Find out which process has TCP port 8069 open with:
sudo lsof -i :8069

apache2 is not starting


Do the elements of a set have to be unique?

Question: Does the mathematical definition of a set specify/imply that its elements be unique?

For context, this question has arisen in my mind from my experience using the Python programming language where one of the properties of the 'Set' data structure is that its elements are necessarily unique. Prior to this I had done a maths degree, but don't recall this being highlighted when learning about [mathematical] sets; certainly not with the emphasis it is given in Python.
Moreover, I feel like I came across questions or problems where sets would sometimes have repeated elements (perhaps problems in probability or combinatorics), but I may be mis-remembering this or it may have simply been an abuse of the notation. But an example might be:

What is the probability that the sum of two numbers, one each drawn randomly from the sets $A = \{1, 2, 2, 3, 3, 3\}$ and $B = \{1, 2, 3, 4\}$ is at least 6?

(where the desired answer is 8/24, rather than 3/12)
The Set Theory Wikipedia page does not use the term "unique" or "distinct" in reference to set elements. I came across this Stack Overflow question, but it's obviously geared heavily towards programming, so it's hard to know if that answers are really about the mathematical concept rather than programming data structures. It does mention that a set where repeated elements are allowed is called a Multiset, and in making this distinction, the Wikipedia page for Multiset does assert that a set is only allowed a single instance of an element. But it goes on to say that the term Multiset was only coined in the 1970s, so I'm left wondering what Mathematicians did before then if they wanted collections of objects with duplicates?
Comment: Yes, because there is no way for you to know how many of a given element are in a set, just whether an element is in a set or not. Hence, regardless or not of whether the element is unique, to you, it will seem unique.
Comment: To allow for objects with duplicates, we make functions from some indexing set into a set of elements from which we want to build our set. For example, If I want to represent your $A$, I would represent it as a function $A:\{1,2,3,4,5,6\}\to\{1,2,3\}$ defined by $$1\mapsto1;\;2,3\mapsto2;\;4,5,6\mapsto3$$
Comment: We don't really use collections with duplicates much, anyways. Functions are far more versatile.
Comment: Possible duplicate of https://math.stackexchange.com/questions/934378/why-cant-a-set-have-two-elements-of-the-same-value
Comment: I think the real issue here is that of notation. As I understand it, in very fundamental set theory, you wouldn't write out things in lists in braces like $A=\{1,2,2,3,3,3\}$. Instead, you might say that $A$ is the set for which $1\in A, 2\in A, 3\in A$ and $x\in A\implies x=1$, $x=2$, or $x=3$. We've said that $A$ has as its elements just $1$, $2$, and $3$. But there's no basic logical/ set-theoretic language we could use to specify 'how many times' $1$ or $2$ or $3$ appears in $A$. In fact, at such a basic level the idea of 'how many times' hasn't itself been defined yet.
Answer:
Does the mathematical definition of a set specify/imply that its elements be unique?

Yes.

The Set Theory Wikipedia page does not use the term "unique" or "distinct" in reference to set elements.

No, but it does say this:

"Set theory begins with a fundamental binary relation between an object o and a set A. If o is a member (or element) of A, the notation o ∈ A is used."

I interpret this as: To be an object in the universe is to be unique.  For every thing, it is the only thing that is itself and either an object $o$ is a member of a set $A$.... or it isn't.
Now a set has nothing about how order the things or how you pick them out or list them. And if $o$ is in the set $A$, it doesn't matter if when asked to describe the elements of $A$ I mention $o$ first, or last, or $53$rd and if I say "$A$ has $o$ and it has $t$ and $s$ and it has $o$, did I mention $o$ already, and it has $q$ and $z$ and $o$ and $m$ and $o$ and $o$ and, gee I'm mentioning $o$ a lot, and ..."  The fact remains either $o$ is in the set or not.  Those are the only options.
So if a set is $\{1,2,3,4\}$ that doesn't mean we can't list it as $\{4,3,4,1,2,4\}$.  In fact consider $\mathbb Q = \{\frac ab| a,b\in \mathbb Z; b\ne 0\}$.  That's perfectly valid but inefficient. Notice we have include then element $\frac 34$ when we consider $\frac 34\in \mathbb Q$ as $3,4\in \mathbb Z$.  But we considered it a second time when we considered $-3, -4 \in \mathbb Z$ and $\frac 34 = \frac {-3}{-4}$.  And we considered it a third time when we considered $51, 68\in \mathbb Z$.
....
As to consider sets as lists with multiple listings of elements or as listings where order does matter.... well, that is why we have such concepts as multisets or sequences.  Even functions is an extension of the concept.
As for a probability problem as you suggest.  I imagine must would state it as something like "What is the probability that the sum of two numbers, one each drawn randomly from the collections A={1,2,2,3,3,3} and B={1,2,3,4} is at least 6?"  Technically we'd say $A$ is a multiset, not a set.


How can I use tab completion in the 'Run a command' box?

Question:
Possible Duplicate:
Getting completion feature with Alt+F2 in Unity?

I finally upgraded to Ubuntu 11.04 and so far, I am liking the experience.
The only thing I have a problem with, is:

While in the execute dialog, I can't complete the path with Tab like I could do in 10.10

Is anybody having any fix for this?
Comment: Does it help if you log out and choose the Ubuntu Classic session before logging back in? It will give you a GNOME2 interface like in 10.10 (no Unity), but it could be a temporary fix.
Comment: Yes, it works. It does give me the classic Gnome2 interface. but this is surely not a solution :-/
Comment: This is what I was thinking about, to split them, but somehow I wrote them into one. Sorry. I just try `appmenu-gtk`
Comment: One more unusual thing found. When I drag a document to the launcher, it only highlights the programs that can open it, but what about the case when I have to drop it somewhere else? like in my thinderbird or GMail, to attach in in the mail? this is bad.
Comment: @Jorge I just did that. I hope it looks fine now.
Comment: @Sheikh Thanks, and don't worry about keeping around the crossed-out material. The most important thing is to maintain a well-presented question, and it's okay to do so at the expense of losing some of the history of this page. *[Edit, edit, edit](http://meta.askubuntu.com/questions/257/how-does-ask-ubuntu-work/542#542)*, they say.
Answer: Couldn't find any solution to this.. as a result, got used to with the default Unity behavior :-/
Answer: Well, Natty is different and making something different may result in bugs.
Crashes might happen. For the top bar a restart (re-log-in) usually helps.
I didn't have many problems with Unity.
Comment: I've restarted the system several times, as a part of my regular routine, but that didn't help.
Answer: It seems that unity may not be quite ready for prime time yet.  I have experienced similar issues and I think the simplest fix for now may be to disable unity and revisit in a month or two.


What will be custom scheduler name in kubernetes

Question: I have ran service account and pod for custom scheduler.so what will be my custom scheduler name ?it will be pod name or service name or anything else.
Answer: Generally, you define your scheduler name while writing the scheduler itself. Then you create a docker container for scheduler and ran that scheduler as deployment in kubernetes.
Now that scheduler will schedule your pods (based on how you write your scheduling).
You should watch the following talk of Kelsey Hightower on how to write custom scheduler and use it

https://www.youtube.com/watch?v=IYcL0Un1io0

Here is the toy scheduler source code, you can refer

https://github.com/kelseyhightower/scheduler

Hope this gives you brief idea.
EDIT:
The kelsey hightower's scheduler (link mentioned above) has to be deployed in following way:
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    app: scheduler
  name: scheduler
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: scheduler
      name: scheduler
    spec:
      containers:
        - name: scheduler
          image: kelseyhightower/scheduler:0.4.0
        - name: kubectl
          image: kelseyhightower/kubectl:1.3.4
          args:
            - "proxy"

Then whenever you deploy new pods with that scheduler you need to provide `schedulerName' in yaml file:
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    app: nginx
  name: nginx
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: nginx
      name: nginx
    spec:
      schedulerName: hightower
      containers:
        - name: nginx
          image: "nginx:1.11.1-alpine"
          resources:
            requests:
              cpu: "500m"
              memory: "128M"

That schedulerName should be the name of the scheduler define in your code.
Comment: I got it but other deployment which will use that scheduler,there in yaml file what will be schedulername field.is it depoyment name of custom scheduler pod or anything else?
Comment: You need to write the function in your scheduler to do so. However now you can have multiple scheduler so that you can schedule using your specific requirements and also have default scheduler to have standard tuning like nodeSelector etc https://kubernetes.io/docs/tasks/administer-cluster/configure-multiple-schedulers/
Comment: Yeah,I checked that thing.if I use node_selector for default scheduler, node is assigned when nodeselector matched,but this case custom scheduler nodename is not assigned with nodeselctor matching.will happen once nodename we change by scheduler only.


Evaluate $\lim_{x\to0^+} \frac{(1-x)^{x}-\cos x e^{-\frac{x^2}{2}}}{\arctan(x^2)\sin x +x^3 \ln x}$

Question: I'm trying to evaluate
$$\lim_{x\to0^+} \frac{(1-x)^{x}-\cos x e^{-\frac{x^2}{2}}}{\arctan(x^2)\sin x +x^3 \ln x}$$
I've found that it is
$$\lim_{x\to0^+}\frac{-\frac{x^3}{2}+\text{o}(x^3)}{x^3+x^3\ln x +\text{o}(x^3)}$$
My doubt is: which is the dominant term at the denominator? If I write it like this
$$\lim_{x\to0^+}\frac{-\frac{x^3}{2}+\text{o}(x^3)}{x^3\left(1+\ln x +\frac{\text{o}(x^3)}{x^3}\right)}$$
Or like this
$$\lim_{x\to0^+}\frac{-\frac{x^3}{2}+\text{o}(x^3)}{x^3\ln x\left(1+\frac{1}{\ln x} +\frac{\text{o}(x^3)}{x^3\ln x}\right)}$$
I get $0$, which is right; but I'm not sure if they are both correct, because I don't fully understand if the $\ln x$ is irrelevant or not.
Thanks to you all.
Answer: What you do is right! Follow your method:
$$\lim_{x\to0^+}\frac{-\frac{x^3}{2}+\text{o}(x^3)}{x^3\left(1+\ln x +\frac{\text{o}(x^3)}{x^3}\right)}=\lim_{x\to0^+}\frac{-\frac{1}{2}+\text{o}(1)}{1+\ln x +\text{o}(1)}=0.$$
Actually,
$$(1-x)^{x}-\cos x e^{-\frac{x^2}{2}}\sim\frac{-1}{2}x^3.$$
So you also can evaluate this limit as follows:
$$\lim_{x\to0^+} \frac{(1-x)^{x}-\cos x e^{-\frac{x^2}{2}}}{\arctan(x^2)\sin x +x^3 \ln x}=\lim_{x\to0^+} \frac{\frac{-1}{2}x^3}{\arctan(x^2)\sin x +x^3 \ln x}$$
$$=\lim_{x\to0^+} \frac{\frac{-1}{2}}{\frac{\arctan(x^2)\sin x}{x^3}+\ln x}=0.$$
Because $$\lim_{x\to0^+}\frac{\arctan(x^2)\sin x}{x^3}=1$$
and $$\lim_{x\to0^+}\ln x=-\infty.$$
Comment: Typo at end : replace $\infty $ by $-\infty $.
Comment: thanks! @Paramanand Singh
Comment: Pending +1 delivered.


usb issues on ubuntu

Question: i have 2 64gb usb sticks that had all my backed up music on them. when i attached them to the laptop ubuntu said it was only 24mb and had nothing on. now when i plug into a windows laptop my stick is only 24mb and nothing else is detected. i also have 2 TB hard drives but there is no way im hooking them up until i can resolve this issues?? can anyone help as i have tried various things and various usbs and the same thing happens to them all, i essentially now have 4 unusable usb sticks and one is only a day old.
Answer: I'm going to take a wild guess here (because I've had it too with my first 64GB USB stick) that these sticks may need exFAT.  Try installing exFAT support first, and see what it does: apt-get install exfat-fuse.  Try inserting them again.
Alternatively, run the "Disks" program, and give me a screenshot of the USB disk in question.
The 2TB disk drives should not have this issue, because they will not use exFAT.  They will most likely be formatted NTFS these days.
Granted.  Wild guess based on experience, given the limited amount of information you give.
Comment: Thank you will give it a try, sorry my question was so lacking in detail was typed whilst on the move. Basically what happens is i put in my usb and it detects it however it says only 24mb available. When I click on properties it doesn't seem to register that it is a 64gb stick. When I saw there was only 24mb I thought it might be as it was full with music. However when I now insert into a Windows laptop it only registers as 24mb even if re formatted . So now I'm stuck with no music and a useless usb. This has happened to several usb that I have and it's getting really frustrating.
Comment: Ok got a slight update, I have realised that my Ian shows up if I open drives, it says it's fat32 however I am unable to access anything on it., when in command prompt and I type df -Th it didn't show up. Not going to lie this whole usb issue is really annoying me , never had this with Windows. I'm new to Ubuntu so don't understand fully m, I just want my usbs to work as I use it a lot at work but hey are a Windows system.
Comment: please see above
Comment: Do you have smaller USB keys?  Like 4GB ones, for test?
The behaviour is peculiar.
It looks like, for some reason, the partition tables of these USB sticks got broken.  Can you either show the partions on the disks (make a screenshot) under Windows using "Computer Management", or using the "Disks" or "GParted" applications on Ubuntu.
Comment: stupid question but how do add a screen shot to my comment
Comment: You can't...  Either add it to your question, or use imgur.com or similar services.
Comment: Ok I have come to the conclusion that basically I have to format everything to fat32 and get rid of all the partitions and have a brand new clean usb stick, I upgraded to 16 from 14 and it now recognises the sticks but are non accessible so need to be wiped
Comment: You can format them exFAT.  See my answer.

usb issues on ubuntu


Loop through array, set property of each element?

Question: Okay, very simple: there is an array containing 3 objects.  Each object has a unique property called "ID" with values of either 1, 2, or 3.
One of the objects gets deleted.
The objective now is to update the ID property of each object corresponding to the new array.length value.
So for example, the object with ID of 2 got deleted.  The remaining objects in the array would each have ID values of 1 and 3 respectively.
So the objective is to loop through the array and update the ID properties to 1, and 2 (instead of 1 and 3).
So I guess the question is how to write a loop to update a common property of each element in an array.  Thanks.
Answer: You can use a for-loop to go through the array, as in walkietokyo's answer, or you can use a method closure:
myArray.forEach ( function ( item:*, i:int, arr:Array) : void { item.ID = i; } );

or a while-loop:
var i:int = -1;
while (++i < myArray.length) myArray[i].ID = i;

Answer: for (var i:uint = 1; i <= myArray.length; i++) {
    myArray[i].ID = i;
}

General info on loops:
http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7fcf.html
Answer: var i:uint; // for speed keep out of the loop
var arrayLength = myArray.length // for speed keep out of the loop

for (i = 0; i < arrayLength; i++) {
    myArray[i].ID = i;
}


PuPHPet doesn't run custom script

Question: I played with this for far too long, (a week now) and I need some help.
I created a Vagrant config with PuPHPet and it gives me a lot of errors.
The simple thing what I'm trying is to run a 12.04 Ubuntu with Nginx, PHP and MySQL.
My problem comes when I add a custom script to the puphpet/files/exec-always, called provision.sh as the original documentation writes:

You can run your own custom code after the VM finishes provisioning by adding files to the puphpet/files/exec-always and puphpet/files/exec-once folders.

The following small script:
#!/usr/bin/env bash

cd /project/app

# Run migrations
echo ">> Running migrations"
php ./yiic migrate --interactive=0

My config.yaml can be found here.
The whole output can be found here.
So I have a clean, PuPHPet generated file structure. What are these errors and why is my script not executed?
And one more thing: My MySQL user, doesn't get the ALL PRIVILEGES right, phpmyadmin only writes: USAGE. If someone could help with this also, would be more then nice ;)
Comment: Hi. Did you find a solution to this in the end? I have the same issue at the moment. My scripts in exec-always never run
Comment: Hi @Gortron, sorry but I couldn't figure it out back then and we decided to drop Vagrant because of the lot of problems. Instead we created our own VM image that we copied.
Comment: Hi @Edifice. OK cool, thank you for getting back to me.
Comment: I am also unable to run any scripts. Well its running the scripts but there is something funky going on. It says it can't find some files in /etc that are there.
Answer: In the directories exec-once/exec-always/.. there are files called empty.
That file should be removed for the directory that contains your script, in this case the puphpet/files/exec-always directory.
Comment: I don't think that has anything to do with scripts not running. The files named "empty" are just there so that the folders (if truly empty) can be pushed to a version control system

PuPHPet doesn't run custom script


Ceiling light goes off itself

Question: My ceiling light goes off itself after 10 mins or sometimes even after an hour, no loose connection from the ceiling fixture and the switch, nothing seems loose even breaker too. How can i find the problem and what is causing to shut off itself? 5 LED bulbs was working fine about 2 years and suddenly went wrong? need help, thanks

Actually I am helping with my friend's living room ceiling fixture; they did not put any extra load on same circuit and bulbs could be issue but I really want to know it could be switch problem too. The light goes off slowly with a couple of flickers before it goes off, and you can not turn back on right away, even if you try to turn it on. I can only turn it on 5-10 mins after going off. It could be a switch issue, maybe the switch is not passing the power to the fixture. The funny thing is that when I opened the fixture, I did not see any transformer on the fixture. I don't know where it gets overheated if there is no transformer.
Comment: If you have a multi-meter, take off the switch cover plate and check voltage. Check voltage on all receptacles as well. Wait for the light to go off and check all voltages again. This way you can trace the circuit and locate the voltage drop. If you have a voltage drop everywhere, it's probably a bad breaker.
Answer: Heat is an enemy for LED bulbs, and many bulbs say specifically that they cannot be used in an enclosed fixture since there is no airflow and a build up of heat.  I tested this with some LED bulbs from IKEA, and sure enough, in an enclosed fixture they would turn on and off as they heated up.
It could be that your bulbs used to be fine, but the heat has slowly degraded them.  Check the bulbs and see if they mentioned use in an enclosed fixture.  Either way, replacing the bulbs with the appropriate type is probably your best bet.
Comment: Sometimes even the enclosures have heat-sensitive switches not likely the culprit with LED's installed.
Answer: Have you recently added an appliance or other large load in the same circuit?
I had an interesting dilemma similar to this once. I kept changing a customer's bulbs as they were continuously blowing. It turns out that she had plugged a mini fridge into the bedroom outlet with an extension cord. The light was in the circuit after the fridge and was only getting about 40 volts when the fridge turned on, blowing the light. I moved the fridge and the problem was solved.

Ceiling light goes off itself


Does a vent register boot always has to be installed parallel to wall for a better air flow all around?

Question: In my basement, I have a gas pipe (1" diameter) running between the joists. There is a reason why I have choose this cavity to run a supply line from where. But I am end up using a end boot register which would be perpendicular to the exterior wall. I have seen in my house in the upper living area,  builder used 90 degree vent register most of places and, few places the end boot register. In all case, the register vent boots is install parallel to any wall.
Would there be any problem in the air flow, if I run a supply through end vent boot which will be perpendicular to outer wall. The below is the picture I am trying to say. this vent will be just above the exterior door
End boot register :
Answer: The air flow will be the same but the distribution of that air will be compromised. Supply vents up through the floor are usually aimed at the wall and air flows up the wall and into the room, the reason for them being installed parallel to the wall. It's also stands a better chance of not being obstructed by furniture in the room. A perpendicularly installed vent looses the "Wall effect" and also stands a good chance of being obstructed by furniture because it will stick out far.
Comment: Thanks Jack. If furniture is not a concern as the end boot is just above an exterior door. How the air will be compromised here ?
Comment: Does this vent supply air to the basement or first floor? the exterior door in the basement threw me.
Comment: its in basement.
Comment: @PAN  if it's blowing cold air down into the basement area, the air flow won't be compromised. If the vent register has directional guides, direct them away from the wall.
Comment: Thanks Jack! I am considering the hot air won't also compromised. since your specifically mentioned cold air.
Comment: @PAN Hot air won't b compromised either but you'd want to adjust the directional guides more downward since the hot air will rise.
Comment: @PAN  Just an after thought: is there  reason your extending that duct work all the way to the exterior wall?  Splitting the distance between the main trunk and the outside wall would reduce the duct work (resistance) and allow for better air flow into that room....  just a thought.
Comment: Good Point Jack Are you asking why not to put supply vent in the middle of space in the ceiling than running it all the way to exterior wall ? Actually I heard and seen that supply vent should be installed to exterior wall to stop cold draft coming from window in winter and,  another reason you mentioned due to furniture placement,. btw the total length of flex duct will be 13 feet.
Comment: @PAN I would  fix the windows with weather stripping. The furniture issue really only applies if the vent was coming through the floor  to cool/heat the first floor. Putting the supply vent in the middle just seems to make more sense IMHO.


Emailjs just working sometimes with Microsoft Edge

Question: Hi I'm new to web development and I'm trying to send a simple  contact form using emailJS, it was working a week ago from my localhost and a hosting site from firebase but I don't know what happened that stopped working properly  and now only works sometimes from localhost in Microsoft edge browser. If I try to submit with one of the text-areas empty the window alert pops out but when I have all the fields it only reloads the page but doesn't show the window alert that says 'Email sent!'
I followed this tutorial to use EmailJS https://blog.mailtrap.io/react-send-email/#Sending_emails_with_EmailJS
I am developing the website with ReactJS so here are the functions of my contact form component, any help is appreciated! Thanks :D
This is where I handle the changes from the text-areas
constructor(props) {
super(props);
this.state ={
  name: '',
  email: '',
  message: '',
}

this.handleChangeName = this.handleChangeName.bind(this);
this.handleChangeEmail = this.handleChangeEmail.bind(this);
this.handleChangeMessage = this.handleChangeMessage.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);;

This is my summit part
handleChangeName(event) {
this.setState({name: event.target.value});
}
handleChangeEmail(event) {
this.setState({email: event.target.value});
}
handleChangeMessage(event) {;
this.setState({message: event.target.value});
}
handleSubmit(event) {
 event.preventDefault();
 const templateId = 'template_7HeYQshf';
 if(this.state.email === '' || this.state.name === '' || this.state.message === '')
 {
   window.alert('All fields are required.')
   window.location.reload();
 }
 else {
  this.sendFeedback(templateId, {message_html: this.state.message, from_name: this.state.name,
  reply_to: this.state.email})
 }
}
sendFeedback (templateId, variables) {
window.emailjs.send(
  'gmail', templateId,
  variables
  ).then(res => {
    window.alert('Email sent!');
    window.location.reload();
  })
  // Handle errors here however you like, or use a React error boundary
  .catch(err => window.alert('something went wrong, please try again '))
  window.location.reload();
}

Answer: I solved the Issue with the following changes:
constructor(props) {
super(props);
this.state ={
  name: '',
  email: '',
  message: '',
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

This is my new summit part
handleChange = (event) => {
this.setState({[event.target.name]: event.target.value});
};

handleSubmit = (event) => {
event.preventDefault();
if(this.state.email === '' || this.state.name === '' || this.state.message === '')
{
  window.alert('All fields are required.')
  window.location.reload();
}
else {
  emailjs.send(
    "gmail",
    "template_7HeYQshf",
    {message_html: this.state.message, from_name: this.state.name, reply_to: this.state.email},
    "*****"
  )
  window.alert('Email sent!')
  window.location.reload();
 }
}