Squaring a logarithm when the base is a square root

Question: How is this equality obtained?
$$
-\log_\frac 1 {\sqrt 2}(x - 7) = \log_2 (x - 7)^2
$$
I understand the process until this point
$$
\log _\sqrt 2 (x-7) .
$$
How do I get from there to
$$
\log_2 (x - 7)^2
 ?$$
Answer: Use the formula:
1) $$\frac 1{\sqrt2}=2^{-\frac12}$$
2) $$\log_{a^p}b=\frac1p\log_ab$$
3) $$k\log_{a}b=\log_ab^k$$
Comment: Exactly what I was looking for. Thanks a lot!
Answer:
Your claim is false, for example try $x = 6$.

$\log_2( (6 - 7)^2 ) = \log_2 (1) = 0$.
But $-\log_\frac 1 {\sqrt 2}(6 - 7) = -\log_\frac 1 {\sqrt 2}(-1)$ is not a real number (even no matter which branch cut).

The claim is only true for certain values of $x$, such as real $x > 7$.

Do take a look and see whether the properties of logarithms you were taught were correctly stated or not (the conditions are very very important!).

$\log_a(bc) = \log_a(b) \log_a(c)$ for any positive reals $a,b,c$ such that $a \ne 1$.
a. This is false for $b,c < 0$.
b. This is meaningless for $a = 1$ or $b = 0$ or $c = 0$.
$\log_a(b^c) = c \log_a(b)$ for any positive reals $a,b$ and real $c$ such that $a \ne 1$.
a. This is false for $b < 0$.
b. This is meaningless for $a = 1$ or $b = 0$.
$\log_a(c) = \dfrac{\log_b(c)}{\log_b(a)}$ for any positive reals $a,b,c$ such that $a,b \ne 1$.
a. This can be extended for $c < 0$ (if we allow complex numbers).
b. But this is still meaningless for $a = 1$ or $b = 1$ or $c = 0$.

Let's see the correct claim and the proof:

$-\log_\frac 1 {\sqrt 2}(x - 7) = \log_2( (x - 7)^2 )$ for any real $x > 7$.

Proof:
Take any real $x > 7$.
$\log_\frac 1 {\sqrt 2}(x-7) = \dfrac{\log_2(x-7)}{\log_2(\frac1{\sqrt{2}})}$   [by property (3)]
$\ = \dfrac{\log_2(x-7)}{\log_2(1)-\log_2(\sqrt{2})}$   [by property (1)]
$\ = -\dfrac{\log_2(x-7)}{\log_2(2^{\frac12})}$
$\ = -\dfrac{\log_2(x-7)}{\frac12\log_2(2)}$   [by property (2)]
$\ = -2\log_2(x-7)$
$\ = -\log_2((x-7)^2)$.   [by property (2)]
Note that in all steps the conditions for the properties of logarithms hold! The crucial step that fails if $x < 7$ is the last step, even if complex-valued logarithms are allowed. If (like in high-school) complex-valued logarithms are not allowed, then the very first step is already illegal because "$\log_\frac 1 {\sqrt 2}(x-7)$" is meaningless.
Comment: Conditions were never the part of the question. Your post is irrelevant. I know how to work out conditions, I had a difficulty understanding how would one transfer equation in a way I have explained.
Comment: @Fiste: If you say that my post is irrelevant, you're basically saying that **all mathematics** is irrelevant. If that is your **opinion**, fine, but it is **wrong** in mathematics. Mathematics is not about making **false** statements. "$\log_{\sqrt{2}}(x-7) = \log_2((x-7)^2)$" is a **false or meaningless** statement.
Comment: @Fiste: In case you don't understand my above comment, in real mathematics you are **not allowed** to perform arbitrary symbolic manipulation **unless** they are justified. Don't think that you can "manipulate first and work out conditions later". That may give you the right answer for very basic arithmetic but not for real mathematics. So if your goal is to get away from mathematics as fast as possible, then yes my post is not for you. But I hope that you'll realize that mathematics is not about mindless symbol manipulation but about one way to grasp **truth**.
Comment: You are blowing it way out of proportion. I asked a simple question, check out the preferred answer I have selected, that is EXACTLY what I was looking for.
I understand very well what you were saying in your answer, it's simply not what I asked for.
Comment: My point is precisely that I am sure that what you're asking for is not enough if you want to learn real mathematics. Logical correctness is absolutely crucial beyond high-school mathematics, which is not really mathematics at all. You clearly don't appreciate it now, but you should later. If you've seen enough questions on Math SE about difficulty in understanding concepts, you would've seen that most of them are due to a weak or non-existent grasp of logic. The problem is that people who do not grasp logic are **rarely aware** of that issue until they finally learn logic properly.
Answer: $$-\log_{1/\sqrt2}(x-7)=-\dfrac{\log(x-7)}{\log(1/\sqrt2)}=-\dfrac{\log(x-7)}{\log(2^{-1/2})}=2\dfrac{\log(x-7)}{\log2}=?$$
See Properties of Logarithm


Can three diagonals in a $2k+1$-gon intersect?

Question: Is it possibly to find three diagonals in a regular $2k+1$-gon that intersect? More particularly can  they intersect inside the polygon? I am looking for an elementary solution. Can one be found without using trigonometry? Any solution is welcome.
Answer: Great question. No, it's not possible.
At this page http://arxiv.org/pdf/math/9508209.pdf you can find  a complete answer (for any regular $n$-gon).  It used to be a famous unsolved question of Steinhaus, for $2k+1$ prime ...
Comment: The bibliography of the article above is also worth looking at.


Move field from one profile type to another?

Question: I have a field in one profile type that really belongs in another profile type. The field already contains values.
I can imagine exporting the contents of the field, attaching a new instance of the field to the "other" profile, and importing the exported values to the new instance using feeds. But is there a more straightforward way to move a field (and existing values) from one profile type to another?
Answer: There's no easy way. That means if you don't have a lot of records your better off doing it manually.
If you must:
   1. Add the field to profile type B.
   2. Change the nid in the field data and revision DB table for every user from the nid of profile A to the nid of profile B.
   3. Remove the field from profile type A.
Comment: I doubt that it would work well if the node revisions are enabled.It is not enough to change the nid in the field_revision table alone. That way the field revisions will be related to a non-existing vid (version ID) of the new node.


Need center align of ul whose  are float left

Question:

Home

The Resort

Facilities

Tariff

Media

Links

Contact Us

Here I want li's in middle of div whose class is wrap. Do any one know how can i do that? I have tried center align but it does not work...............
Comment: do you want that li should move to center of the div , are you trying to make a vertical menu
Comment: no its horizontal menu... all the li must be central align of div with class wrap
Comment: If its a horizontal menu , then you want that all li elements should be next to each other from the left is it, iddnt understand properly what do you mean by center aligned
Comment: just copy paste my above codes in html file then you will know clearly what i really want to ask
Answer: body{
       margin:0;
       padding:0;
      }
    #module_footerLink li{
    display: inline-block;
        list-style:none;
        margin:0 5px;
        /* For IE 7 */
        zoom: 1;
        *display: inline;
    }
    .clear{
        clear:both;
    }
    .wrap{
        border:1px solid #ccc;
        width:900px;
            text-align:center;
    }

Answer: see the updated css :-

i think you looking like this:-
http://jsfiddle.net/eHyuZ/2/
UPDATED
Now you can add li's as per your requirement...it will not go anywhere actually your bit of your method was not correct that's why you were facing problems now i have made some changes and made it the navigation in proper way
see the updated link:
http://jsfiddle.net/eHyuZ/7/
Comment: if i add more li's? It will go down... these li will be dynamically placed later
Comment: you don't need to use the floats in your li because it will come randomly through display:inline; in li....and now you can add more li's in your UL list with div class wrap...
Comment: i have just figure out the problem and saw ur answer thanks anyway
Answer: you must use margin:0 auto;
.wrap{
    border:1px solid #ccc;
    width:900px;
    margin:0 auto;
    text-align:center;
}

http://www.w3schools.com/css/css_align.asp
Comment: you must set width for ul and set margin:0 auto for ul, this work when the number of li's and th total width is fixed otherwise you must use script to calculate the li's width then set to ul.
Answer: EDITED by comment
Try add
#module_footerLink {
display:inline-block;
/*IE7*/
zoom:1;
*display:inline;
}

http://jsfiddle.net/DEmTh/1/
But in IE7 its not working
Comment: If you need to support IE7 I would use a
Comment: Try http://stackoverflow.com/a/6545033/1102223
#module_footerLink {
display:inline-block;
*display:inline;
zoom:1;
}


Stage plans - input lists, output lists, monitor lists

Question: I am going to make a stage plot for my school project.
I have researched how and I have found lots of examples. The thing that is unclear are the following
Input list
Output list
Monitor list
FoH inserts
It feels like a Monitor List maybe a subset of Output list but it may be an overloaded term?
I also have seen examples (example1 and example2) of monitor information (or FoH inserts) in the input list which has confused me even more.
My question is, what are the differences between input list, output list, monitor list and FoH inserts?
Answer: Input is as it says - mostly mics, for drums, for picking up guitar amp sounds, vox, etc.
Output is also as it says, what comes out of the mixer, in whatever mixed state.
Monitor list is whatever gets fed back through the monitor (foldback) system. There may be several different mixes here. Vocalists may want their own voice, plus guitar or keys, drums will want themselves (!) plus maybe bass, and a little bit of vox. Guitar may want nothing, as their amp would be behind them, making it its own monitor.
FoH inserts are the front of house (main p.a.) effects. Vox would prefer a little reverb, drums dry, and so on, it's personal choice here.
On a big rig, there will be the facility to provide all this, with several mixes for monitor, going through several different foldback speakers, or better still, I.E. monitors, which totally eliminate feedback. Effects may be on a separate rack, and again, get fed both to FoH and monitors if wanted.
Lots of knobs, lots of control - if one knows what one is doing. A good sound guy will listen not only to the sound (!) but to the requirements of individuals, then attempt to get FoH and monitor mixes appropriate for the band, but also for the room. Not an easy task. I've found that the best sound guys are musos, who can understand what musos want, and are talking about.
Comment: Thanks - is it common for the mixes of the monitor to be defined in the stage plot itself, or would you think it's common to simply have a chat with the sound engineer?
Comment: From past experience (as the sound guy) the more discerning performers want to have the same sound in the monitors as they produce FoH. But that may not always be the case. And some sound guys seem to have their own end product in mind, which I've found from being at the other end of the train. Not always good!


File Upload Without Using Any Asp Controls

Question: I'm trying to upload an image without using any of the asp controls. So far I've been trying:
        <form id="form1" data-ajax="false" method="post" runat="server" enctype="multipart/form-data">
            <input type="file" id="uploadFile" name="uploadFile" runat="server"/>
            <input type="submit" class="btn-login" data-corners="true" value="Yükle" onclick="UploadPhoto()" />
        </form>

in my .aspx page and in UploadPhoto() method in JQuery:
function UploadPhoto() {
            $.ajax({
                type: "POST",
                url: "IncidentChange.aspx/UploadPhoto",
                contentType: "application/json; charset=utf-8",
                success: function (msg) {
                },
                error: function () {
                }
            });
        }

I am posting to C# code behind. However, I could not reach the uploaded item from codebehind.
        [WebMethod]
        public static string UploadPhoto()
        {
            try
            {
                byte[] fileData = null;
                using (var binaryReader = new BinaryReader(HttpContext.Current.Request.Files[0].InputStream))
                {
                    fileData = binaryReader.ReadBytes(HttpContext.Current.Request.Files[0].ContentLength);
                }

            }
            catch (Exception ex)
            {
            }
            return null;
        }

However Request.Files appears to be a null array. Since the method is static ([WebMethod]) I cannot reach the input control within the method to get the posted file. How can I overcome this issue? Thank you.
Comment: your are not sending the file in the ajax data
Answer: Html:
<input type="file" id="uploadFile" name="uploadFile"/>
<input type="button" id="submit" value="Submit" onClick="UploadFile();"/>

JQuery:


Pandas dataframe grouped operation inside numpy function

Question: I have a data frame consisting of thousands of stock quotes, ordered by symbol(tic) and Date.
    Date    tic    prccd
0   1-1-20  AAPL    4.00
1   2-1-20  AAPL    4.10
2   3-1-20  AAPL    4.12
3   1-1-20  MSFT    6.00
4   2-1-20  MSFT    6.15
5   3-1-20  MSFT    6.10

With
stocks_data['log_return'] = np.log(1 + stocks_data.groupby('tic')['prccd'].pct_change())

I aim to get the logarithmic daily return of these stocks. Does the numpy function acknowledge the groupby tic operation?
Comment: numpy dose not know the groupby.,
Answer: To calculate daily log returns per tic group use:
stocks_data['log_return'] = df.groupby('tic').prccd.transform(lambda x: np.log(x) - np.log(x.shift(1)))

or equivalent formula:
stocks_data['log_return'] = df.groupby('tic').prccd.transform(lambda x: np.log(x / x.shift(1)))

result:
     Date   tic  prccd  log_return
0  1-1-20  AAPL   4.00         NaN
1  2-1-20  AAPL   4.10    0.024693
2  3-1-20  AAPL   4.12    0.004866
3  1-1-20  MSFT   6.00         NaN
4  2-1-20  MSFT   6.15    0.024693
5  3-1-20  MSFT   6.10   -0.008163

Comment: Thank you. I just did it with your formula and the results are actually the same


Detecting a color when it appears on screen

Question: I wanted to make a color detection program to display a message box when a certain color is found
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace evade
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            SearchPixel("#00042");

        }

        private bool SearchPixel(string hexcode)
        {
            Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Graphics graphics = Graphics.FromImage(bitmap as Image);
            graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);

            Color desiredPixelColor = ColorTranslator.FromHtml(hexcode);

            while (true)
            {

                for (int x = 0; x < SystemInformation.VirtualScreen.Width; x++)
                {
                    for (int y = 0; x < SystemInformation.VirtualScreen.Height; y++)
                    {
                        Color currentPixelColor = bitmap.GetPixel(x, y);

                        if (desiredPixelColor == currentPixelColor)
                        {

                            MessageBox.Show("Found!");
                            return true;

                        }

                        else
                        {
                            return false;
                        }
                    }

                }

            }

        }

    }
}

So that's my code. And the color is #00042 this one (html) I'm running the detection on a while loop so when the desired color appears on screen it displays a little message box but It does not work.
Comment: `Bitmap.GetPixel` is very slow method. Use [this way](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.bitmap.lockbits?view=dotnet-plat-ext-3.1) instead.
Comment: I think your color code is wrong. https://www.htmlcsscolor.com/hex/000042 You need 4 zeros ie: 6 digits for the RGB code
Comment: Oh yeah my bad. It does not work still though
Comment: I think you should put `CopyFromScreen` inside the `while` loop.
Answer: In your code you have:
if (desiredPixelColor == currentPixelColor)
{

    MessageBox.Show("Found!");
    return true;

}
else
{
    return false;
}

Which returns true if the color is found, but at the same time returns false as soon as a color does not match.
What happens if the very first pixel is not a match?  Then you return false without ever checking the rest of the pixels!
Instead, you need to return false after the for loops have exited:
for (int x = 0; x < SystemInformation.VirtualScreen.Width; x++)
{
    for (int y = 0; x < SystemInformation.VirtualScreen.Height; y++)
    {
        Color currentPixelColor = bitmap.GetPixel(x, y);
        if (desiredPixelColor == currentPixelColor)
        {

            MessageBox.Show("Found!");
            return true;

        }
    }
}
return false;

Also, get rid of that while(true) loop as it's not necessary.
Comment: Thank you very much for the Information! Also, I still think I should keep the while since I want to keep constantly checking after I click the button.
Comment: If you keep the while loop called from your button click handler, your app will become un-responsive as you'll tie up the main UI thread and it won't be able to respond to user interaction or re-paint itself.  Besides, with the `return` statements in there, the while loop gets exited; thus it is doing nothing for you.  If you want to periodically check, turn on a Timer control from your Button handler and then check for the color from within the Tick() event.  Or create another thread and check from there...


Can no longer import app module into unit tests after changing deployment target

Question: For unit testing public classes of my main app target in my swift unit tests, I have to import my main app module in my tests like so:
#import MyAppModuleName
This worked just fine until I changed my deployment target from 7.0 to 8.4.
Now building and running my app still works perfectly, but running unit tests stopped working. The compiler complains about the above import statement: Swift Compiler Error: Module file's minimum deployment target is iOS8.4 v8.4
I have no clue why. Did I forget to change the deployment target somewhere else?
My workspace (Xcode 6.4.) contains my own project and a Pods project (automatically created by cocoapods). I'm using both Swift and Objective-C in my app and in my tests.
Here's what I did in more detail:
1) Changed deployment target from 7.0 to 8.4 for my project, my main target, and also for the Pods project in my workspace, and all the pods targets.

2) Cleaned the build folder (Shift+Alt+Cmd+K) and restarted Xcode.
3) Cmd+U -> Error
When changing the main app's deployment target back to 7.0, everything works fine again.
Any ideas where this problem is coming from?
Answer: You were almost there, you just need to update the iOS Deployment Target for your Project and both of your targets.
For your project:

For your app target:

For your test target:

You should probably do a clean and rebuild, no need to restart Xcode. I guess this will also work if you want to target 8.1 etc.
Comment: Yeah, that was it. I simply missed the fact that there are indeed three or more different places to setup the deployment target. I'm not really sure I understand what this is good for. E.g. project: 9.0, app target: 8.0, tests 8.4


Am I missing a step in the elimination of parameter $t$?

Question: I am working on eliminating parameter $t$ in these parametric equations:

$x(t) = e^{2t}$
$y(t) = e^t + 3$

I know when eliminating parameter $t$, you have to solve for $t$ in one equation and then plug the new equation into y. That's what I did for x and ended up with
$$t=\frac{ln(x)}{2}$$
Next, I just plugged this into $y$ and got
$$y=e^{\frac{ln(x)}{2}}+3$$
Unfortunately, none of the answers provided by the quiz match my answer, the only options are:

$y=e^{2x}+3$
$y=\sqrt{x-3}$
$y=x^2 +3$
$y=\sqrt{x}+3$

Did I accidentally miss a step?
Comment: Just use that $\,e^{2t}=\left(e^t\right)^2\,$.
Answer: You have
$$e^\frac{\ln(x)}{2}=(e^{\ln(x)})^\frac{1}{2}=x^\frac{1}{2}=\sqrt{x}$$
Thus, you have
$$e^\frac{\ln(x)}{2}+3=\sqrt{x}+3$$, i.e. number 4 is right.
Comment: Of course, don't worry about it :)
Answer: Notice that $x(t) = e^{2t} = (e^t)^2 = (y(t)-3)^2$.


General Solution to a Differential EQ with complex eigenvalues.

Question: I need a little explanation here the general solution is $$x(t)=c_1u(t)+c_2v(t)$$ where $u(t)=e^{\lambda t}(\textbf{a} \cos \mu t-\textbf{b} \sin \mu t$ and $v(t)=e^{\lambda t}(\textbf{a} \sin \mu t +\textbf{b} \cos \mu t)$ I am confused on what happened to the $i$ that is suppose to be in front of $v(t)$ and why it just "goes away". When they were deriving this formula they just go from writing it as $x^{1}(t)=u(t)+iv(t)$ to the general solution which is throwing me off as to what happened to the $i$. Nothing can just disappear in math without reason.
Answer: It doesn't really disappear.
Note that $\{u,v\}$ is linearly independent over $\mathbb R$, so if they are solutions of a second degree  ordinary differential equation with constant coefficients, they form a basis of solutions.
The $i$ disappears because usually one is interested in real functions.Of course $u+iv$ will also be a solution to the differential equation, just not a real solution. There's probably a hidden assumption that you're only looking for real solutions.
Comment: @adam And maybe even more! Think about roots of $x^3-1\color{grey}{=(x-1)(x^2+x+1)}$. There is only solution in $\mathbb R$, there are three in $\mathbb C$ and maybe there's even a possibility of extending $\mathbb C$ further to have more solutions to this equation. Just as long as there are not contradictions, you're free to do anything.
Comment: Ok so there are actually two solutions two the differential equation? One in the complex plane and the other in the real plane?
Comment: how can that equation have more than 3 solutions????
Comment: @adam What about if you look at it also as a matrix equation? To give meaning to an equation it is necessary to specify in which realm you're working on.
Comment: Are you referring to Demovires theorem in which use consider the equation in polar coordinates?
Comment: @adam No, not all. Just regular matrices.
Comment: I am not familiar with the technique of solving polynomial equations of a degree higher than 1 as a matrix
Comment: @adam You misunderstood me. Surely you can recognize that the identity matrix $I$ is a root of the equation $X^3-I
=0$. This is what I mean. Of course in this case $1$ is the identity matrix and not the number $1$.


A Lagrange optimisation that I don't understand. $f(x, y, z) = x^2 + y^2$ is constrained by $5x^2 + 6xy + 5y^2 = 1$

Question:
The function $f(x, y, z) = x^2 + y^2$ is constrained by $5x^2 + 6xy + 5y^2 = 1$. Using Lagrange, maximise and minimise this function.

My original Lagrange equation was
$$L = x^2 + y^2 + \lambda(1 - 5x^2 - 6xy - 5y^2).$$
After partially differentiating I got:
$$\begin{aligned}
L_x &= 2x - 10\lambda x - 6\lambda y ,\\
L_y &= 2y - 6\lambda x - 10\lambda y , \\
L_\lambda &= 1 - 5x^2 - 6xy - 5y^2 .
\end{aligned}$$
As I'm attempting to find a minimum and maximum, I set all the equations equal to $0$. Rearranging the partial derivative w.r.t. $x$ gave me
$$\lambda = \frac{2x}{10x + 6y}$$
and rearranging the partial derivative w.r.t. $y$ gave me $\lambda = 2y/(10y + 6x)$. Putting these two equations equal to one another gives $$\frac{2y}{10y + 6x} = \frac{2x}{10x +6y}.$$ Multiplying both sides out led to $20xy + 12y^2 = 20xy + 12x^2$. As such I could equate $x$ to $y$.
Subbing in $x$ for $y$ into the constraint gave me $16x^2 = 1$ and as such $x$ (and $y$) $= \pm \frac14$. However, I don't think either $\left(\frac14, \frac14\right)$ or $\left(-\frac14, -\frac14\right)$ are the minimum and maximum points. If I have done something wrong please correct me but as of right now I am unsure what to do. Also, $z$ being listed in the function but actually having no part in any of the question confused me too. Was just hoping someone could help me understand.
Comment: Please show what you have tried or why you think it may be impossible if you want good feedback.
Comment: Why wouldn't it be possible? the constraint tells you that our points lie on an ellipse and a continuous function on a compact set takes a max and a min.
Comment: Hi, welcome to Math SE. Hint: the stationary points of the Lagrangian solve a quadratic function in $z:=y/x$.
Comment: Considering $f$ as a function only in $x, y$, it's a continuous function on a compact set (completing the square on the constraint shows that the set of solutions is bounded, and it's obviously closed) so it must achieve both its minimum and maximum.  Please **edit the question** to tell us what you've tried and where you're stuck.
Comment: Maybe you are doing a paper for credit and are fishing for a solution? How can we know if you don't contribute anything?
Comment: the constraint set is an ellipse, draw a careful picture.
Comment: @whpowell96 I'm sorry this is my first time using this site. I have added in all my workings out to the summary to show what I've done. Hope this helps.
Comment: @lulu I don't understand how to get the actual minimum and maximum points
Comment: @J.G. I'm sorry I don't quite understand what this means? Should i have put my partial derivative for x over my partial derivative for y to get that of z?
Comment: @RobertShore was the z in the f(x, y, z) just put there to throw me off? I have added in what I did for the question.
Comment: @Paul I'm sorry about that, I have now added in what I did for the question.
Comment: @WillJagy I see. Would I have had to draw out the function in order to answer the question?
Comment: Did you mean to write $f(x,y)$ instead of $f(x,y,z)$?
Comment: @AnotherUser I was confused about that as well but the question specifically said f(x, y, z)
Comment: I suppose that that's a typo.
Comment: @AnotherUser Potentially but if so it really threw me off for the entire question
Comment: Another possibility is $ y = - x $, and that leads to $ ( \dfrac{1}{2}, - \dfrac{1}{2} ) $ and $(-\dfrac{1}{2}, \dfrac{1}{2} ) $
Comment: @ghasheem I completely missed that thank you. So that would make (0.5, -0.5) and (-0.5, 0.5) the maximum and (0.25, 0.25) (-0.25, -0.25) the minimum?
Comment: Yes.  That is correct.
Comment: Thanks for editing in your work. To answer your question about my previous comment, I was only suggesting a way to rewrite a quadratic equation in $x,\,y$ as a quadratic in $y/x$ only, but the Lagrangian still should be construed instead as a function of $x,\,y,\,\lambda$. By the way, your calculation only shows extrema satisfy $x^2=y^2$, which is compatible with not only $x=y$ (which minimizes $f$) but also $x=-y$ (which maximizes $f$).
Answer: I think that I can safely assume that $f$ is a function of $2$ variables, rather than $3$.
Let $g(x,y)=5x^2+6xy+5y^2$. Note that
$$
E=\{(x,y)\in\mathbb{R}^2\,:\,g(x,y)=1\}
$$
is a compact set (it is an ellipse), and therefore the restriction of $f$ to that set must have a maximum and a minimum. The points at which they are attained are such that $\nabla g=(0,0)$ or that, for some $\lambda\in\mathbb{R}$, $(x,y,\lambda)$ is a solution of the system
$$
\left\{\begin{array}{l}
         2\bigl((1-5\lambda)x-3\lambda y\bigr)=0\\
         2\bigl(-3\lambda x+(1-5\lambda)y\bigr)=0\\
         5x^2+6xy+5y^2=1.
       \end{array}\right.\label{sys}\tag{1}
$$
But $\nabla g(x,y)=(10x+6y,6x+10y)$, which is $(0,0)$ only at the origin, which does not belong to $E$. On the other hand, the first two equations of the system \eqref{sys} form a system of two linear equations in two variables depending upon a parameter $\lambda$. The matrix of the coefficients of this system is
$$
\begin{pmatrix}
1-5\lambda&-3\\
-3&1-5\lambda
\end{pmatrix},
$$
whose determinant is $0$ if and only if $\lambda=\frac12$ or $\lambda=\frac18$. If the determinant is not $0$, then the only solution of the system which consists of the first two equation is $x=y=0$, which is not a solution of the third equation.
Now, suppose that $\lambda=\frac12$. Then the system becomes
$$
\left\{\begin{array}{l}
         -\frac32x-\frac32y=0(\iff x+y=0)\\
         5x^2+6xy+5y^2=1,
       \end{array}\right.
$$
whose only solutions are $\pm\left(\frac12,-\frac12\right)$. And if $\lambda=\frac18$, then the system becomes
$$
\left\{\begin{array}{l}
         \frac38x-\frac38y=0(\iff x-y=0)\\
         5x^2+6xy+5y^2=1,
       \end{array}\right.
$$
whose only solutions are $\pm\left(\frac14,\frac14\right)$. But $f\left(\pm\left(\frac12,-\frac12\right)\right)=\frac12$ and $f\left(\pm\left(\frac14,\frac14\right)\right)=\frac18$. So, the maximum is $\frac12$ and the minimum is $\frac18$.
Comment: Thank you so much. In the second Lagrangian multiplier how did you get the final +y?
Comment: It was a typo. Sorry about that.
Comment: @AnotherUser You need some extra work to actually show that the critical points that you have identified are minimum or maximum points...
Comment: @PierreCarre I have expanded my answer. What do you think now?
Comment: @PierreCarre I did provide that information, when I wrote that the equality $\nabla g(x,y)=(0,0)$ never occurs on the points of the ellipse (since actually it never occurs at any point of $\mathbb{R}^2\setminus\{(0,0)\}$).
Comment: @AnotherUser You'rr right! didn't notice!

A Lagrange optimisation that I don’t understand. $f(x, y, z) = x^2 + y^2$ is constrained by $5x^2 + 6xy + 5y^2 = 1$


Change dates in list with multiple dictionaries in Python

Question: I have a list with multiple dictionaries, like the following:
[{'Date': '6-1-2017', 'Rate':'0.3', 'Type':'A'},
 {'Date': '6-1-2017', 'Rate':'0.4', 'Type':'B'},
 {'Date': '6-1-2017', 'Rate':'0.6', 'Type':'F'},
 {'Date': '6-1-2017', 'Rate':'0.1', 'Type':'B'}
]

I would now like to change the dates, because they need to be in the format 'yyymmdd', which starts at 1900-01-01. In other words, I would like to change the '6-1-2017' to '1170106'.
As this has to be done every week (with the then current date), I do not want to change this by hand. So next week, '13-1-2017' has to be transformed into '1170113'.
Anyone ideas how to do this? I have tried several things, but I can't even get my code to select the date-values of all dictionaries.
Many thanks!
Comment: `1170106` is not the same as `yyyy-mm-dd`.
Comment: Show what you have tried, and how it came up short.
Comment: what even us `1170106`?
Comment: @MattDMo, you are completely right. I need the `yyymmdd` format. I'll change the post.
Comment: @WhatsThePoint, it is the 117th year after 1900, and then month 01 and day 06. So 1170106.
Answer: You can use the datetime module, which provides a lot of functionality to manipulate datetime objects including converting datetime to string and the way back, accessing different components of the datetime object, etc:
from datetime import datetime

for l in lst:
    l['Date'] = datetime.strptime(l['Date'], "%d-%m-%Y")
    l['Date'] = str(l['Date'].year - 1900) + l['Date'].strftime("%m%d")

lst
#[{'Date': '1170106', 'Rate': '0.3', 'Type': 'A'},
# {'Date': '1170106', 'Rate': '0.4', 'Type': 'B'},
# {'Date': '1170106', 'Rate': '0.6', 'Type': 'F'},
# {'Date': '1170106', 'Rate': '0.1', 'Type': 'B'}]


How to implement authentication in a Proxy Server

Question: I borrowed code for an http proxy server, everything works fine. Now I want to limit use of the proxy server by requiring authentication.
So, I tried the following:
On the client side:

web client created to request page from google.
web client uses WbProxy with username and password.

on the server, the request comes through, and I can see the headers:

GET http://www.google.com/ HTTP/1.1
Host: www.google.com
Proxy-Connection: Keep-Alive

So I have the server respond to the client with:

HTTP/1.0 407 Proxy Authentication Required
Proxy-Authenticate: Basic realm="proxy"

At this point, I was hoping the client would then respond with the username and password used for the WebProxy credentials. But that doesn't happen.
What am I missing? How do I get my Proxy server to require authentication and ultimately to test the credentials sent?
Answer: I figured it out, had to add "\r\n\r\n" to the response back to the client. LAME!


Instructing Python to click a button using urllib2

Question: I'm writing a web scraper using urllib2 and BeautifulSoup in python and am looking for a way to instruct python to click a button on a page that it reads the HTML source code for.
The following snippet of my script reads in URLs from a csv file and is meant to scrape data from the webpages specified, but an intermediary step is to click a "submit" button that exists on the webpage that is read from the csv's provided URLs.
<code>for line in triplines:
    FromTo = line.split(",")
    From = FromTo[0].strip()
    print(From)
    To = FromTo[1].strip()
    print(To)
    url = KCString1 + From + KCString2 + To + KCString3
    print(url)
    page = urllib2.urlopen(url)
    page_source = page.read()
    soup = BeautifulSoup(page_source)
    print(soup.prettify())
</code>
Is there a way to utilize urllib2 functionality in such a way as to say "follow the URL that is obtained from clicking this button"? I imagine I may need to find the JavaScript source to identify the button's identifiers first.
Comment: Why not using Scrapy (http://scrapy.org/)?
Comment: Not sure if you want to use urllib2 for this. Have you looked at [Selenium](https://pypi.python.org/pypi/selenium)?
Answer: Buttons do not typically have urls attached to them. They normally need javascript interaction, which needs emulation. If you want to click a button, you should use a browser emulator like Ghost instead of a parser like Beautifulsoup


An error occured while attempting to process /ajax/ajax_facets/refresh:$.blockUI is not a function

Question: Ajax facets work but I get an error "An error occured while attempting to process /ajax/ajax_facets/refresh:$.blockUI is not a function" when I click on ajax links with checkboxes for the facets for the first time.
I am using search api views as per mentioned in the project description
You can check the error in the screenshot attached
Answer: The above issue was occuring due to conflict with other module Ajax Screen Lock
Disabling it solves the problem.


Perl for loop going haywire

Question: I have a simple for loop in Perl
for ($i=0; $i <= 360; $i += 0.01)
{
print "$i ";
}

Why is it that when I run this code I get the following output, where as soon as it gets to 0.81 it suddenly starts to add in a load more decimal places?  I know I could simply round up to avoid this issue but I was wondering why it happens. An increment of 0.01 does not seem at all crazy to do.
 0.77
 0.78
 0.79
 0.8
 0.81
 0.820000000000001
 0.830000000000001
 0.840000000000001
 0.850000000000001
 0.860000000000001
 0.870000000000001

Comment: http://learn.perl.org/faq/perlfaq4.html#Why-am-I-getting-long-decimals-eg-19.9499999999999-instead-of-the-numbers-I-should-be-getting-eg-19.95-
Comment: [What Every Programmer Should Know About Floating-Point Arithmetic](http://floating-point-gui.de/)
Comment: http://stackoverflow.com/questions/10908825/, http://stackoverflow.com/questions/9790048, http://stackoverflow.com/questions/3916314, http://stackoverflow.com/questions/7066636, http://stackoverflow.com/questions/2080629, http://stackoverflow.com/questions/2056681, http://stackoverflow.com/questions/14204125
Comment: 8.1 seems to be a remarkably hard number to convert. Years ago, I had a mini-project trying to find *some* way to manipulate a particular value: '8.10' accurately. Both Java and Perl, were having problems with this number.
Answer: Computers use binary representations. Not all decimal floating point numbers have exact representations in binary notation, so some error can occur (its actually a rounding difference). This is the same reason why you shouldn't use floating point numbers for monetary values:

(Picture taken from dailywtf)
Most elegant way to get around this issue is using integers for calculations, dividing them to the correct number of decimal places and using sprintf to limit the number of decimal places printed. This will both make sure:

There's always to correct result printed
The rounding error doesn't accumulate

Try this code:
#!/usr/bin/perl
for ($i=0; $i <= 360*100; $i += 1) {
  printf "%.2f \n", $i/100;
}

Comment: +1 for the documentary evidence of incorrect programming practices in the wild!
Answer: Basically, because the decimal number 0.01 does not have an exact representation in binary floating point, so over time, adding the best approximation to 0.01 deviates from the answer you'd like.
This is basic property of (binary) floating point arithmetic and not peculiar to Perl. What Every Computer Scientist Should Know About Floating-Point Arithmetic is the standard reference, and you can find it very easily with a Google search.
See also: C compiler bug (floating point arithmetic) and no doubt a myriad other questions.

Kernighan & Plauger say, in their old but classic book "The Elements of Programming Style", that:

A wise old programmer once said "floating point numbers are like little piles of sand; every time you move one, you lose a little sand and gain a little dirt".

They also say:

10 * 0.1 is hardly ever 1.0

Both sayings point out that floating point arithmetic is not precise.
Note that some modern CPUs (IBM PowerPC) have IEEE 754:2008 decimal floating point arithmetic built-in.  If Perl used the correct types (it probably doesn't), then your calculation would be exact.
Answer: To demonstrate Jonathan's answer, if you code up the same loop structure in C, you will get the same results. Although C and Perl may compile differently and be ran on different machines the underlying floating point arithmetic rules should cause consistent outputs. Note: Perl uses double-precision floating point for its floating point representation whereas in C the coder explicitly chooses float or double.
Loop in C:
    #include <stdio.h>

    int main() {
        double i;
        for(i=0;i<=1;i+=.01)  {
          printf("%.15f\n",i);
        }
      }

Output:
    0.790000000000000
    0.800000000000000
    0.810000000000000
    0.820000000000001
    0.830000000000001
    0.840000000000001
    0.850000000000001

To demonstrate the point even further, code the loop in C but now use single-precision floating point arithmetic and see that the output is less precise and even more erratic.
Output:
    0.000000000000000
    0.009999999776483
    0.019999999552965
    0.029999999329448
    0.039999999105930
    0.050000000745058
    0.060000002384186
    0.070000000298023
    0.079999998211861
    0.089999996125698
    0.099999994039536

Answer: 1/10 is periodic in binary just like 1/3 is periodic in decimal. As such, it cannot be accurately stored in a floating point number.
>perl -E"say sprintf '%.17f', 0.1"
0.10000000000000001

Either work with integers
for (0*100..360*100) {
   my $i = $_/100;
   print "$i ";
}

Or do lots of rounding
for (my $i=0; $i <= 360; $i = sprintf('%.2f', $i + 0.01)) {
   print "$i ";
}

Perl for loop going haywire


proper uses of minor seventh chords

Question: Having used dominant seventh chords extensively,I am now trying to incorporate minor seventh chords into my compositions...
Based on my [rudimentary] knowledge, minor seventh chords are usually used in ii-V-I progressions (replacing the ii with ii7) , and also to add "colour" to the chords... How else could i use these chords in my songwriting?
Besides, i have noticed that minor seventh chords tend to sound a bit "less gloomy" than minor triads, which i presume is due to the "major" component in them. (eg. Dm7 = D F A C which has an F major triad as its "element", ie.  F A C). (Not sure whether my statement is true though). Could I use minor seventh chords this way, ie. to make my song a bit happier but not overly happy?
Explanations would be greatly appreciated.
Answer: Casey's answer is fundamental and should be thoroughly understood.  When you're ready to go farther afield, you can use other closely-related minor 7th chords.
Consider this chord progression: I-I7-IV-V7-I.  The I7 is a "secondary dominant", the "V7 of the IV" chord.  It gives a stronger feeling of "fourness" to the IV chord.  Now, if you wanted to more strongly emphasize the subdominant (IV), you could do this: I-v7-IV-I7-IV-V7-I.  The v7 (minor 7th chord built on the dominant) is the "ii7 of IV" (technically a "secondary supertonic").  This allows you to flirt longer with the "fourness" without getting repetitive.
I'm only using the IV chord as an example.  You can apply the same idea to the V chord, for example, and this is very often done in practice.
Comment: You can use ii7, but that's one of the chords that Casey talks about.  II7 is the V7 of V, and vi7 is the ii7 of V.  Try this progression: I-vi7-II7-V7-I.  That will give an extended feeling of "fiveness" to the progression.
Comment: So, keep in mind this concept of "secondary dominants" and "secondary supertonics".  Secondary dominants are dominant 7ths ("five ofs") of another note in the scale, typically IV or V, and secondary supertonics are supertonic 7ths ("two ofs") of another note in the scale.  Also, do keep in mind that for every element of joy, there must be an element of sorrow, so that we may better understand both.  :P
Comment: Thanks @BobRodes, i tried it on my keyboard and it sounds wonderful! :) so if i were to apply it to the V chord, do i go this way: ii(7)-vi7-V7 -I?
Comment: Yes @BobRodes, i actually prefer II7. Sounds happier than ii7☺. In fact i am overdoing it (also i use too much of V7 and III7... lol)
Comment: that's right. Great insight!☺ indeed, balance is very important.
Answer: Minor seventh chords can typically be substituted whenever adding a diatonic 7th (the 7th that is within the current key) to a minor triad leads to a minor seventh.  In a major key, this occurs for ii7, iii7 and vi7.  In a minor key, this occurs for i7, vi7 and v7.
So for instance, if you have a chord progression, like I-iii-vi-ii-V, you could add 7th to any of the minor chords without dramatically changing the character of the harmony.
As you pointed out, adding a 7th to a minor triad gives the chord results in a major triad on top, which, when played by itself, appears to give the sound of the chord a little "levity", so to speak.  However, in context, I think the effect is more often to add some dissonant nuance to the harmony, rather than to make these chords sound "happier".  I personally tend to use minor 7th quite frequently for an almost opposite purpose to what you describe: to increase the tension in the harmony.
Comment: Thanks @Casey-rule... The use of m7 to increase the tension sounds interesting☺. What chord would you choose to go after the m7- is it something from the 2-5-1 progression?
Answer: Following the two excellent answers, Im7 can be used in place of I7, leading, as it usually does to IV. As in C - Cm7 - F. The Cm7 can come over as Eb6, but by keeping the root at the bottom, it works as  a dominant of F. Example found in 'The Lady Is a Tramp'. That change from C to seemingly a non-diatonic chord a minor third above can appear subtle and 'in your face' at the same time, I think.
Comment: @mey - it works - the theory says that Cm/Eb are very close relatives, thus introducing the Eb whilst in C maj will often lead to Cmin.
Comment: Thanks @Tim. That progression sounds awesome.☺ By the way, i recall a composition (in my own country) involving i minor (it was in a major key), but not sure if I could add a minor seventh on top of it. The progression was V-v-I -i - II7 sus4 -V.
Comment: i found another interesting feature of Cm7: if i play it over an Eb note in the key of C, it leads smoothly to the key of C min/Eb maj without needing help from another pivot chord... Have you encountered this situation, and do you think this is right?
Comment: @mey - right and wrong don't feature as such in music, as far as 'rules' are concerned.The right and wrong are more  - does it work? does it sound good?
Comment: Ah yes. ☺ So do you think Cm7 actually works that way?

proper uses of minor seventh chords


What the difference in vim, compiled with python (ruby) support and without it?

Question: I want to use vim on many servers, where in repository it compiled without ruby and python support. But syntax plugins work fine on it. And other things looks normal, when i trying to edit python file.
I will use it with plenty of filetypes (configs, logs, sourcecode and other), and i want to know the difference and decide to use repository's version or compiled by myself
Answer: The optional Python, Ruby, Perl or Scheme supports allow script developers to write vim plugins in their chosen languages. Vim will, when compiled in, provide a small interface for interacting. It doesn't affect the syntax files or indentations etc. They are written in VimScript.
There are quite a few nontrivial Vim plugins that use Python so at least compiling Vim with Python support will expand your options with plugins in noticeable manner.
Answer: When not compiled with <code>+python</code>, Vim is not able to perform omnicompletion for python code. I believe it's the same for Ruby.


CSS selector within style of another selector

Question: I have seen the following before, but cannot find it on Google. I am wondering if it is a framework. Also, is this good practice?
body {
    position:absolute;
    p {
        float:left;
    }
}

Basically, there are some selectors nested within others. I don't know if I'mk Googling the wrong words, or if this is hard to find because it's a bad idea. So the question is: what is this nesting thing, and should/can I use it?
EDIT:
Is there a way that it could come out as:
body {
    position:absolute;
    p {
        float:left
    }
}

that would then compile to:
body {
    position:absolute;
}
body p {
    position:absolute;
    float:left;
}

Answer: This is SCSS type of programming for CSS.
You need compiler later to compile to CSS code.
body {
    position:absolute;
    p {
        float:left;
    }
}

will be compiled to:
body {
    position:absolute;
}
body p {
    float:left;
}

http://sass-lang.com/ for more informations.
Comment: Does the body p selector inherit position:absolute? (learning on my own here)
Comment: In css this isninvalid syntax.
Answer: You're looking at SASS or .scss files, not CSS. It is a language that is preprocessed to become CSS. It it good practise for readability, however it is not CSS. As it stands it will not work in a browser.
body {
    position:absolute;
    p {
        float:left;
    }
}

Is processed to become:
body { position:absolute; }
body p { float:left; }

Edit
To make what you describe you would just do this:
body {
    position:absolute;
    p {
        position:absolute;
        float:left;
    }
}

Is processed to become:
body { position:absolute; }
body p { position:absolute; float:left; }

If you are interested on what happens to it when processed, you can have a look on Codepen by setting the CSS to be SCSS. I have setup what you are working with here:
http://codepen.io/EightArmsHQ/pen/zNjpLP
You can click "View compiled CSS" in the dropdown to see how it works.
Comment: You should be able to edit your question to add further code if you need to.


Swift Beginner - Auto layout constraints (Xcode Interface Builder) question - is 'leading = label.leading' the same as 'label.leading = leading'

Question: Interface builder occasionally sets constraints for me, and it sets the main view's leading constraint to a label's leading constraint + an arbitrary number, let's say 30 for example with a view that has a top header label in the upper left corner.
Sometimes, when this happens, my constraints (at build time) seem to be off a little and interface builder just glitches like hell, preventing me from perfecting a view evenly, etc.
My question is, are these constraints (below) the same? What is the difference if there is one?
leading = label.leading

vs
label.leading = leading

Answer: If you are asserting that two values should wind up coinciding, and there is no ambiguity in your layout, then when all the constraints are resolved, those two values should coincide.
It doesn't matter if you say the superview's leading edge should match the labels's leading edge, or that the label's leading edge should match the superview's leading edge.  They mean the same thing.
If there is ambiguity in the layout, and the system tries to break that ambiguity, however, it might choose to resolve the ambiguity differently in either case.


User is Anonymous in DefaultSessionCloseStrategy

Question: I have extended the DefaultSessionCloseStrategy and created a custom class DefaultStorefrontSessionCloseStrategy storefront session timeout functionality. So as per this when user storefront session is expiring, before that user can execute some custom code in this new class. But as soon session timeout is happening, current user is getting Anonymous even before the logout. I need the current user details before the session expires.
Any idea what I am missing here ?
And this is working fine in Developer (local) machine. But user is getting anonymous in in cloud (ccv2) environment.
Answer: Try to create a listener extending BeforeSessionCloseEvent.
Then, fetch the user using the Jalosession in the overridden onEvent method,
JaloSession session = (JaloSession) beforeSessionCloseEvent.getSource();
UserModel user = this.modelService.get(session.getUser());


Como faço pra conseguir sortear uma quantidade X de números sem se repetirem em JS?

Question: let user = require(`readline-sync`)

let loteria = {
    totalNumeros: "",
    intervalo: "",
    numeros1: "",
    numeros: [],
    numeroexcluido: "",
    sortear: function () {
        this.totalNumeros = user.questionInt("Informe quantos numeros deseja sortear: ")
        this.intervalo = user.questionInt("Informe qual o numero maximo: ")

        for (let i = 0; i < this.totalNumeros; i++) {
            this.numeros[i] = Math.floor(Math.random() * this.totalNumeros + 1)

        }

        console.log(this.numeros);

    }

}

loteria.sortear()
Este é o código até o momento, queria apenas aperfeiçoar ele mas to quebrando a cabeça e não consigo.
Answer: Fala Miguel!

Você vai fazer um loop, com o total de números que você irá querer.
Você irá criar um array para adicionar os números não repetidos aleatoriamente.
Primeiro você gerará um número aleatório dentro do loop.
Segundo você vai verificar se esse número existe no array, se não existir, você pode fazer um .push nesse array com o número aleatório.
Se isso acontecer (não existir um número no array e você colocar lá dentro), você teria que ir diminuindo o total de números para ele sair do loop!

Segue o código abaixo:
let total = 20;
const numbers = [];
const maxValue = 100;

while (total > 0) {
  const number = Math.floor(Math.random() * maxValue);
  if (!numbers.includes(number)) {
    numbers.push(number)
    total -= 1
  }
}

console.log(numbers)

Answer: Eu sugeria a criação de um array com todos os possíveis números de serem sorteados. Depois, removia desse array a adicionaria num novo com os números sorteados. Ao utilizar o length to array para obter o index aleatório e sabendo que se remove o número sorteado, não há hipótese de alguma vez saírem números repetidos.
Seria algo como:

const totalNumeros = +window.prompt('Informe quantos numeros deseja sortear:');
const intervalo = +window.prompt('Informe qual o numero maximo:');
const intervaloArray = [...Array(intervalo).keys()];
const numeros = [];

for (let i = 0; i < totalNumeros; i++) {
  const index = Math.floor(Math.random() * intervaloArray.length);
  numeros.push(+intervaloArray.splice(index, 1) + 1);
}

console.log(numeros);


Reverse bundle install --without env through bundler

Question: I've inherited a project that used to have a build script that bundle installed with the --without env flag. Now I need that env.
I removed the --without flag from the build script, but those preferences are cached by bundler in .bundle/config. The build server has some confusing auto-caching of dependencies itself, and I have no idea where the .bundle/config is located.
Is there an bundler invocation capable of unsetting these --without preferences? A --with would be nice.
Answer: While undocumented in the bundle install help, bundle config notes you can reset or unset the without flag via bundle config without newenv and bundle config --delete without respectively.
Answer: You could always remove the .bundle directory and reinstall. The only reason I'd hesitate to do this is if you have versions of gems that are no longer available. You could always move it first to test:
mv .bundle _bundle
bundle install

If that works, you can remove the temporary _bundle directory, or whatever you've called it.
If it screws up, you can always restore it:
rm -rf .bundle
mv _bundle .bundle

Comment: That would involve messing with the `.bundle` folder manually--something I can't do. I need an bundler-CLI solution.
Comment: The `Gemfile` and `Gemfile.lock` should have all the information required to re-generate the contents of the `.bundle` directory, but if you're prevented from messing with it because of policy, you might have to go about this the hard way.


CSS: Prevent summing color in opacited elements

Question: I have 3 overlapping html divs, one next to another, colored: red, green and blue. All elements have opacity 0.5. First two divs (red and green) I want to summate color (creates something between red and green) - standard behaviour, without changes here.
My problem is how to prevent summating colors only between green and blue divs?
It would be great if we could do this without additional elements.
html:

css:
div {
  position: absolute;
  opacity: 0.5;
}

#d0 {
  top: 60px;
  height: 100px;
  left: 50px;
  width: 100px;
  background-color: red;
}

#d1 {
  height: 150px;
  left: 130px;
  top: 50px;
  width: 200px;
  background-color: green;
}

#d2 {
  height: 100px;
  left: 300px;
  top: 80px;
  width: 120px;
  background-color: blue;
}

EDIT:
I forgot about: http://plnkr.co/edit/5MIduRMFo0dZ54xqzpAa?p=preview
It should look likt this (fourth element is to show that blue also has opacity):
Comment: Have you tried CSS Blend Modes (see example in https://css-tricks.com/basics-css-blend-modes/ after "Arbitrary HTML Elements Blend Modes")?
Answer: If you want to keep opacity of all divs to be still 0.5. Then here is your pure CSS solution. No additional elements added.
Here is a fiddle for that.
http://jsfiddle.net/tdh7ks2x/2/
**HTML**

**CSS**

#d2 {
   opacity: 1;
   height: 100px;
   width: 120px;
   left: 300px;
   top: 80px;
}
#d2:before,
#d2:after{
   content: "";
   position :absolute;
   left: 0;
   top: 0;
   height: 100px;
   background-color: blue;
}
#d2:before{
   width: 30px;
   z-index: 2;
   opacity: 0.99999999;
   background-color: #7F7FFF;
}
#d2:after{
   width: 120px;
   z-index: 1;
   opacity: 0.5;
}

#d4 {
   width: 200px;
   height: 80px;
   left: 400px;
   top: 90px;
   background-color: red;
}

Just added this CSS instead of #d2, rest all your CSS is fine. Let me know if this resolves your issue.
Pick the color of the div with opacity and use it in the ":before" div.
Comment: @michalv: Check this out:  http://jsfiddle.net/tdh7ks2x/2/                       This should solve your issue. I have also updated the fiddle link above in the answer above.
Comment: It looks better, but it unfortunately doesn't resolve my issue - I would like #d2:before not to cover with opacity 1 but, like before, 0.5. I edited issue with picture to show what I want to achieve.
Answer: You can use z-index property to bring a div to front or back. Higher the value of z-index to move it to the top and decrease it to move it back.
Moreover you have used opacity:0.5 due to which you will see the back colors at the intersection. You must increase the opacity to see the exact colors there

div {
  position: absolute;
  opacity: 0.5;
}

#d0 {
  top: 60px;
  height: 100px;
  left: 50px;
  width: 100px;
  background-color: red;
  z-index:2
}

#d1 {
  height: 150px;
  left: 130px;
  top: 50px;
  width: 200px;
  background-color: green;

}

#d2 {
  height: 100px;
  left: 300px;
  top: 80px;
  width: 120px;
  background-color: blue;
}

css:
Comment: z-index is not the solution for me - I have to have opacity in some cases
Answer: Basically, this problems occurs due to overlapping transparent colors. Example is rgba(255,255,255,0.3) overlapping with rgba(255,255,255,0.3) to form a brighter color.
If your design can do without transparent colors, you can easily solve this by converting your transparent colors (rgba) to fully opaque ones (hex) for related elements.
You will need the background color to help compute a fully opaque hex from rgba or just use a color picker browser extension after rendering.


Same question asked on stackoverflow and magento.stackexchange

Question: Following a bout of deja vous I noticed these two questions are posted by the same asker.

How Do I exclude a Magento category from the main menu
https://stackoverflow.com/questions/26438115/how-do-i-exclude-a-magento-category-from-the-main-menu

Should they be merged into one?  Which site gets the combined question?  The two questions elicit different answers, perhaps because different people visit the two sites, so are both questions actually valid?
Answer: This is not so easy. As long as this website is in beta (and might never get out of it) it is not possible to move the question for SO to here. So no simple einfach solution here.
Comment: One of my questions got moved here, so it's obv. possible.
Comment: but only from stackexchange/stackoverflow moderators, not from us
Comment: Right. The migration has to be initiated by moderator of  sender website.


Add javascript to multiple specific urls

Question: I'm trying to add some javascript to my template.php file on a Drupal 7 site. I'd like the javascript to load on a specific set of pages, based on the url. For example, I'd like the script to load on:
mysite.com/blog/page1
mysite.com/blog/page2
but not on:
mysite.com
or
mysite.com/blog
or
mysite.com/about
I'm using
function mytheme_preprocess_html(&$variables) {
  $theme_path = path_to_theme();
  $path = drupal_get_path_alias();
  if($path == 'blog/page1') {
      drupal_add_js($theme_path . '/js/example.js');
    }
}

to load the script on that specific page, but is there any way to use a url argument or wildcard or something so that all internal blog pages (i.e. blog/page1, blog/page2, blog/page3) will load the script?
Thanks!
Answer: The drupal_match_path() function should do the trick:
$path = drupal_get_path_alias();
$pattern = 'blog/*';

if (drupal_match_path($path, $pattern)) {
  drupal_add_js($theme_path . '/js/example.js');
}


Permutation question: Pick out 2 items from 4 items which 2 duplicated, is there any formula?

Question: If given ABBC, find the permutations if 2 letters are picked.
If I calculate manually, they are:
AB, AC, BA, BB, BC, CA, CB, 7 permutations.
Is there any formula to solve this type of question?
(Meaning, picking r number of letters from n number of letters with duplicated letters)
Comment: Depends a bit on what you mean by "this type of question". Are you always given 4 letters, or can that vary? Do they always include 3 distinct letters, or can that vary? Do you always pick 2 letters, or can that vary?
Comment: For this type of question, I am meaning, picking r number letters from n number letters with k duplicated.
Answer: Suppose you had $n$ unique letters ${X_k}$, and letter $X_k$ were present in $r_k$ copies.
Then the number of unique pairs of letters, can be computed as $n (n-1) + \sum_{k} \mathrm{sgn} (r_k-1)$.
The term $n(n-1)$ count the number of pairs where letters are distinct, and remaining sum counts same letter pairs.
Comment: If $r_k\gt2$ then you want to count just one pair where both letters are $X_k$, not $r_k-1$ pairs. From AAA you just get AA, for example.
Comment: @Gerry I realized this as well, I will edit as soon as I can. Thanks
Comment: If picking 3 letters out of ABBC, is there any formula?
Comment: @Allen Suppose all $n$ letters are distinct. Then there are $n(n-1)(n-2)$ ways to pick triplets. Now if you have some distinct letters, you should subtract from that number the number of identical triples.
Comment: @Sasha Thank you for your explanation.
Answer: Permutation of n things taken r at a time out of which k are repeated is
$\frac{n!}{(n-r)!k!}$
In your question , n=4 r=2, k=2
so total permutations is  $\frac{4!}{2!2!}$=6
Comment: Allen has shown you 7 permutations, so if your formula gives 6, then something is wrong with your formula, or something is wrong with mathematics.


Oracle: Can Weblogic 11G run PL/SQL code like App Server 10G?

Question: This is probably a silly question, but I'm not an oracle admin so I'm not sure.  Our client currently runs a website written in PL/SQL and HTML on a Oracle 10G system.  As everything is moving in the direction of 11G the question has come up, will our current PL/SQL system keep working.
I guess the real question here is where does PL/SQL code execute?  I know the 11G database supports PL/SQL.  I'm just unsure about how Oracle is integrating what used to be Application Server into WebLogic Application Server.
Answer: The PL/SQL runs in the database, and so any changes on the application server won't affect the actual execution of PL/SQL code. However, it may still impact on the final result, eg. how the application presents itself to the user, depending on how the application is built.
As for PL/SQL compatibility between Oracle Datababase 11G and 10G you will likely have to do minor modifications in the code. I believe Oracle is claiming backwards compatibility, but in my experience with previous releases there are always a few things that needs tweaking.
Comment: We're aware of the little issues that can come up from migrating the database so that shouldn't be a major problem.

As long as the new Weblogic app server will serve up our PL/SQL pages, we can make whatever other changes need be made.


Taylor coefficients.

Question: I have a function $$f(x) = e^{-x(2a-x)}$$ It is easy to write out the Taylor expansion for this function in $x=0$ point. But.. I want to get a formula for the Taylor coefficients. I tried a lot. I tried to take derivatives, perform some simple transformations and used the computer, trying to calculate them. Nothing much happened. Maybe there is some clever trick here? I would be very grateful for that.
I got the following expression:
$$f(x) = e^{-x(2a-x)} = \sum_{k=0}^{\infty}\frac{(-1)^kx^k(2a-x)^k}{k!}=\sum_{k=0}^{\infty}\frac{(-1)^kx^k}{k!}\sum_{m=0}^{k}\frac{k!(2a)^{k-m}(-1)^mx^m}{m!(k-m)!}=$$ $$=\sum_{k=0}^{\infty}\sum_{m=0}^{k}\frac{(-1)^{m+k}(2a)^{k-m}x^{k+m}}{m!(k-m)!}$$
I thought to designate $m + k = s$ and rewrite the sums in a more convenient form for determining the coefficients, but nothing happened.
Thank you in advance!
Comment: Thank you for your comment. I did it.
Comment: I think it's better if you share with us what you've done so far. So, do write them out. It will save the time of the people who are willing to help you. Also, add a calculus tag to your question to increase its visibility.
Comment: Try to write the function as $e^{-a^2}e^{(x-a)^2}$.
Comment: @user, I have tried it, but I do not know how it can help me, since I have an $x^m$ in the sum that is decomposition of $(x−a)^{2k}$.
Comment: For the fun of it, I did the same for $e^{ax+bx^2+c x^3}$ and $e^{ax+bx^2+c x^3+dx^4}$
Answer: As you said, this is not the most simple problem.
Using brute force, developed at $x=0$
$$e^{-x(2a-x)}=1-2 a x+\left(2 a^2+1\right) x^2-\left(\frac{4 a^3}{3}+2 a\right) x^3+\left(\frac{2
   a^4}{3}+2 a^2+\frac{1}{2}\right) x^4-\left(\frac{4 a^5}{15}+\frac{4
   a^3}{3}+a\right) x^5+\left(\frac{4 a^6}{45}+\frac{2 a^4}{3}+a^2+\frac{1}{6}\right)
   x^6+O\left(x^7\right)$$
Now, searching for a pattern in
$$e^{-x(2a-x)}=\sum_{k=0}^\infty c_k\,x^k$$  the $c_k$'s correspond to the recurrence equation
$$c_k=-\frac 2 k(a\,c_{k-1}-c_{k-2})\qquad \text{with}\qquad c_0=1\qquad \text{and}\qquad c_1=-2a$$ I do not think that we could have anything more explicit.
Comment: Upon solving this recurrence relation, I get $c_k = 2^{-k}\left(\gamma_1 ((-2a/n) - \sqrt{4a^2/n^2 + 8/n})^k + \gamma_2 ((-2a/n) + \sqrt{4a^2/n^2 + 8/n})^k\right)$, where $\gamma_1, \gamma_2$ are then solved with the initial conditions.
Comment: Ah, I agree with @ClaudeLeibovici now; it appears hunting for a more explicit expression is fruitless. I tried using generating functions to solve this recurrence, only to end up with the original expression $\exp(-x(2a-x))$. Should have expected such a tautology!
Comment: @TomChen. Sorry for that ! I had a typo in $c_k$. Can you find the solution ?
Comment: I tried brute force, but I did not see a recurrent formula like that of Tom Chen. Now I see and do not quite understand how it turned out.
Moreover, I need to think about how it can help me, but that's another problem. Anyway, thanks a lot!
Comment: @mathmaniac. I think that the problem was my typo. Making the mistake again, I get what Tom CHen gave. I do not think that, as it is, it could be more explicit. To tell the truth, I generated a dozen of coefficients and I found the pattern. By the way, you are very welcome ! Cheers.
Comment: Okay, then I will wait some more time and, if nothing happens, I will mark your post as an answer. Thanks again.
Comment: Thanks all of you!

Taylor coefficients.


Problema com .map() , erro quando não possui um dos arrays

Question: Tenho um json que chega da minha api como esse exemplo:  obs: "imagens" é um array de objetos
[
    {
        "_id": "625112d17123e250ecfe9d09",
        "modelo": "corola",
        "marca": "toyota",
        "ano": 2020,
        "preco": 100000,
        "imagens": [
            {
                "key": "ccbc1c54f037.jpeg",
                "url": "https://vcars.s3.amazonaws.com/ccbc1c54f037.jpeg"
            },
            {
                "key": "1e3b9259f338.jpeg",
                "url": "https://vcars.s3.sa-east-1.amazonaws.com/1e3b9259f338.jpeg"
            },
            {
                "key": "58732b07f66f.jpeg",
                "url": "https://vcars.s3.sa-east-1.amazonaws.com/58732b07f66f.jpeg"
            }
        ],
    },

meu frontend React recebe esse array e preciso retornar um card para cada objeto do array 'um veiculo' ... estou fazendo da seguinte forma: {(veiculos).map((veiculo) => ( e passando as propriedades, já em imagens como é um array de objetos dentro do objeto veiculos,
imagem={veiculo.imagens.map((url) => url.url)} até aqui funciona perfeitamente, o problema está quando não tem nenhuma imagem dentro de "imagens" no console da erro: Uncaught TypeError: Cannot read properties of undefined (reading 'map') alguma solução? ou então alguma outra forma melhor de fazer isso?
import { useState, useEffect } from "react";
import { Container, Row } from "react-bootstrap";
import VeiculoCard from "../components/VeiculoCard";

export default function Veiculos() {

  const [veiculos, setVeiculos] = useState([]);

  useEffect(() => {
    fetch("http://localhost:4000/veiculos", {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    })
      .then((resp) => resp.json())
      .then((data) => setVeiculos(data))
      .catch((err) => console.log(err));
  }, []);

  return (

      <Container>
        <Row xs={1} md={2} lg={3} xl={4}>
          {(veiculos).map((veiculo) => (
            <VeiculoCard
              key={veiculo._id}
              modelo={veiculo.modelo}
              marca={veiculo.marca}
              ano={veiculo.ano}
              preco={veiculo.preco}
              imagem={veiculo.imagens.map((url) => url.url)}
            />
          ))}
        </Row>
      </Container>

  );
}

Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Comment: você pensou em fazer um if !== null ?
Answer: Essa execução irá depender do retorno da sua API quando não existe imagem em um determinado veículo. Se ela retorna um array vazio [], nulo ou simplesmente não retorna o atributo.
Para esses casos você poderia apenas validar com um ternário se o campo acessado é realmente um array:
{(veiculos).map((veiculo) => (
  <VeiculoCard
    imagem={Array.isArray(veiculo.imagens) ? veiculo.imagens.map((img) => img.url) : []}
  />
))}

Ou, caso a propriedade simplesmente não venha quando não existe nenhuma imagem ou retorne null, validar a existência da mesma antes de executar o map.
{(veiculos).map((veiculo) => (
  <VeiculoCard
    imagem={veiculo.imagens?.map((img) => img.url)}
  />
))}

Espero ter ajudado!
Comment: funcionou obrigado!
Comment: Por nada, que bom que funcionou!


HTML meta tag for Cache-Control header does not work with chrome

Question: When opening my page I can see the cache-control header is set the right way. I look into the Network tab and check the Response. It says
<meta http-equiv="Cache-Control" content="no-cache"/>
Now looking into the Header tab I can not find this header in the Response Header section.
Also other headers set by the meta tag like <meta http-equiv="X-UA-Compatible" content="IE=edge"/>are not listed here:

I read this Is Chrome ignoring Cache-Control: max-age? which mentions that you should open the url in a new tab but I tried that and many other things. Still no look for this headers to be visible.
Any idea what is wrong here?
Answer: The header tab show the HTTP headers, not the meta http-equivs in HTML head.
You have to set this HTTP header in your webserver configuration or from within your programming in order to see it in the Response Header section
If you want to check, if your Cache-Control setting is working, don't just reload the page in your browser, but click in the address box and hit enter with the network tab in developer tools open and check the response code.
Comment: @xetra11 If you see a status code of `200` it means that your page is not cached but loaded again. If you get a `304` it means it should be taking from the cache.
Comment: To see it or to get it to work? If it already works that way it's fine. I don't have to actually see it in the tab
Comment: Hey again. What do you mean by "check the response code". I opened the network panel and have the reponse body html here and can see `` in the html. Is that already showing me it will work?
Comment: @xetra11 [HTTP status code](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes)
Comment: I don't understand what the status code has to do with the `Cache-Control` header being set right or not?


Aspose.Word convert DOCX to HTML looses MERGEFIELD, IF conditions, headers and footer, table cell widths

Question: I'm trying to write a online document editor with TinyMCE 5 as editor and Aspose.Word v20.8 as converter.
But when I convert the DOCX to HTML5 with Aspose.Word, it is not rendering as expected in TinyMCE.
The HTML looses for example headers, footers, MergeFields, IF, TableStart:TableEnd sofar I can tell now.
I need this HTML has all the data because I need to convert it back to DOCX again.
Code to generate the HTML5 is:
var doc = new Document({Stream_Of_DOCX});
var options = new HtmlSaveOptions();
options.SaveFormat = SaveFormat.Html;
options.Encoding = System.Text.Encoding.UTF8;
options.UpdateFields = true;
options.ExportRoundtripInformation = true;
options.ExportImagesAsBase64 = true;
options.ExportFontsAsBase64 = true;
options.ExportPageSetup = true;
options.ExportDocumentProperties = true;
options.ExportHeadersFootersMode = ExportHeadersFootersMode.PerSection;
options.HtmlVersion = HtmlVersion.Html5;

doc.Save($"{fileName}.html", options);

The code to convert the HTML5 back to DOCX is, were the model.Html is the TinyMCE textarea:
var doc = new Document();
var builder = new DocumentBuilder(doc);
builder.InsertHtml(model.Html);
doc.Save($"{fileName}.docx");

Can anybody help me to get this working with some code examples?
Or maybe has a better idear to accomplish the task.
The main idear is to be able to edit DOCX files online, without to have to download it and upload again with some windows service as client for example.
Answer: Aspose.Words do preserve headers and footers upon saving to HTML if ExportRoundtripInformation option is enabled. In this case Aspose.Words writes header and footer content with special css attributes, which are understood by Aspose.Words:

        header

Also, Aspose.Words preserves some fields (PAGE, NUMPAGES, NOTEREF, REF, AUTOR and TITLE). For example, PAGE field is exported like the following:
1

Such content is recognized by Aspose.Words upon reading HTML and loaded into the model as field. I logged a request WORDSNET-21037 to preserve other types of fields too.
I am not familiar with TinyMCE, but I suspect that custom attributes used by Aspose.Words for roundtrip MS Word features are removed and that is why Header and Footer are not preserved in your case.
Disclosure: I work at Aspose.Words team.
Comment: Thanks for your feedback.
When I convert DOCX to HTML with Aspose.Word I see in TinyMCE that the HTML contains this "-aw-headerfooter-type" text. So it isn't removed by TinyMCE.
Whenever I save the TinyMCE-HTML back to the server, the whole HTML content is converted by Aspose.Word to DOCX again and it should be the same as the original DOCX I supose.
Comment: @Christiaan It depends on the complexity of the document you convert to HTML and back. Html format cannot preserve all Word document features, that is why such custom attributes are used. I tested a simple document with header/footer and few fields and after DOCX->HTML->DOCX roundtrip header, footer and supported fields are preserved.
Comment: Ok, then which settings are wrong in the above code?
I have MERGEFIELD and IF code in my Word document and a image in the header and a pagenumber in the footer. And tables are not aligned as in the orginal.
Can you wrtie the code you are using to do the roundtrip?
Is it wrong to think that the input and output should be the same?
When I look at for example to DevExpress that has an nice RichEditor which works as expected. I thought maybe Aspose.Word can that too.
Comment: I used your code to convert to HTML and then open the resulting HTML using Aspose.Words again and saved it to DOCX. Header, footer, table and PAGE field are properly preserved in output DOCX document. As I mentioned MERGEFIELD and IF fields are not preserved upon DOCX->HTML-DOCX roundtrip and this is logged as a defect. Input and output documents really must look the same if input and output formats support the same set of features. HTML and DOCX do not. DevExpress demo really looks cool, but I am not sure they are using HTML or only HTML format as intermediate format for editing.


RD Session Host 2012R2 Session settings set via GP are not reflected in QuickSessionCollection Properties

Question: I have a Quick Start RDS deployment on one host under Windows 2012R2, domain member. I applied group policies on this host that limited sessions timeouts:
Windows Components/Remote Desktop Services/Remote Desktop Session Host/Session Time Limits:
End session when time limits are reached Enabled
Set time limit for active but idle Remote Desktop Services sessions Enabled
Idle session limit: 1 hour
Set time limit for disconnected sessions Enabled
End a disconnected session 1 hour
Gpresult shows these settings are applied successfully, and the server drops the sessions according to the settings.
When I go to
 Server Manager\Remote Desktop Services\Collections\QuickSessionCollection proprties I can see
Time outs are set to never.
 Why I don't see the actual settings here? Is there something similar to RDP-TCP properties in 2008 R2 server?

Where I can see the settings set by GPO.
Answer: You must configure the Session settings with the Session Collection settings dialog (your first screenshot) and the session hosts will reconfigure to match your selection.
You shouldn't tweak the settings with a GPO.
I highly recommend you to disable/remove the GPO that you created, and reconfigure the settings that you want within the Session Collection properties in Server Manager. When you'll hit the "Apply" button, Server Manager will configure remotely your session hosts (hence the delay when you click "Apply")


Computing $ \sum_{n=0}^{\infty} (-1)^{n+1}\int_{0}^{1}\frac{t^{3n+3}}{1+t^3}\mathrm{d} t$

Question: I would like to find the exact value of the following series:
$$ \sum_{n=0}^{\infty} (-1)^{n+1}\int_{0}^{1}\frac{t^{3n+3}}{1+t^3}\mathrm{d} t$$
We can easily show that the series converges using the alternating series test:
$$ 0 \leq\int_{0}^{1}\frac{t^{3n+3}}{1+t^3}\mathrm{d} t \leq\frac{1}{3n+4}$$
So $$ \int_{0}^{1}\frac{t^{3n+3}}{1+t^3}\mathrm{d} t \rightarrow_{n\rightarrow\infty} 0$$
And $$ \int_{0}^{1}\frac{t^{3n+6}}{1+t^3}\mathrm{d} t-\int_{0}^{1}\frac{t^{3n+3}}{1+t^3}\mathrm{d} t=\int_{0}^{1}\frac{t^{3n+3}(t^3-1)}{1+t^3}\mathrm{d} t\leq0 $$
So the series converges.
Do you have any idea to compute the sum?
Comment: One idea (no time to check the details): If you integrate only to $1-\epsilon$, the series converges uniformly, and you can compute the sum explicitly, and integrate it too. Now all that remains is to let $\epsilon\to0$ and to justify the limit (which is likely to be the hardest part).
Comment: @Plane Chon-Ju how do you get $0 \leq\int_{0}^{1}\frac{t^{3n+3}}{1+t^3}\mathrm{d} t \leq\frac{1}{3n+4}$
Comment: @Gingerjin: $ 0 \leq \int_{0}^{1}\frac{t^{3n+3}}{1+t^3}\mathrm{d} t \leq \int_{0}^{1} t^{3n+3}\mathrm{d} t =\frac{1}{3n+4}$
Answer: $$\sum_{n=0}^{m-1} (-1)^{n}\int_{0}^{1}\frac{t^{3n+3}}{1+t^3}\mathrm{d} t = \int^1_0 \frac{t^3}{1+t^3} \sum_{n=0}^{m-1} (-t^3)^{n}\mathrm{d} t$$
$$ =  \int^1_0 \frac{t^3}{1+t^3} \frac{1 - (-t^3)^m }{1+t^3} \mathrm{d} t.$$
Thus by the Dominated Convergence Theorem, $$ \sum_{n=0}^{\infty} (-1)^n \int_{0}^{1}\frac{t^{3n+3}}{1+t^3}\mathrm{d} t = \lim_{m\to\infty} \int^1_0 \frac{t^3}{1+t^3} \frac{1 - (-t^3)^m }{1+t^3} \mathrm{d} t$$
$$ = \int^1_0 \frac{t^3}{(1+t^3)^2} \mathrm{d} t = \frac{2\sqrt{3}\pi +\log 64 -9}{54}.$$
Comment: Great! Thank you very much!
Answer: We have
$$ \begin{align*}
\sum_{n=0}^{\infty} (-1)^{n+1} \int_{0}^{1} \frac{t^{3(n+1)}}{t^3 + 1} \; dt
& = - \int_{0}^{1} \frac{t^3}{(t^3 + 1)^2} \; dt \\
&= \left[ \frac{t}{3} \frac{1}{t^3 + 1}\right]_{0}^{1} - \frac{1}{3} \int_{0}^{1} \frac{dt}{t^3 + 1} \\
&= \frac{1}{6} - \frac{1}{3} \int_{0}^{1} \left( \frac{1}{3(t+1)} -\frac{2 t-1}{6(t^2-t+1)}+\frac{1}{2(t^2-t+1)} \right) \; dt \\
&= \frac{1}{6} - \frac{1}{3} \left( \frac{1}{3} \log 2 + 0 + \frac{\pi}{3\sqrt{3}} \right) \\
&= \frac{1}{6} - \frac{1}{9} \left( \log 2 + \frac{\pi}{\sqrt{3}} \right).
\end{align*}$$


How do I create a bar chart showing percentages bound to a list of objects?

Question: Using the DataVisualization.Charting.Chart control, I need to create a bar chart (maybe stacked bar chart) that shows per person the number of hours booked for that person and a those hours' percentage of total hours. So far I am a bit overwhelmed by the number of collections and properties to set on this beast, so I'd appreciate some help on first getting my chart up, then I'll explore more on my own.
I need to bind the chart to a list of the following object:
Public Class DOHoursChartItem

    Public Property Name As String
    Public Property Hours As Double
    Public Property Percent As Double

End Class

I'm not sure I need the percentage property here, in favour of somehow letting the chart control handle this and just give it the Hours value per point and a total hours value, but that's why I'm asking: how do I set up the chart I describe above?
Comment: Do you want to show two charts (one for the hours and one for the percentage) one upon the other or the two columns of each person have to be side-by-side ?
Comment: @digEmAll I'd prefer both measures in one column for each person.
Answer: I'm not very good in VB, so I will start posting an example in C# (then I can try to translate it if you really need).
Here are three examples of methods that you can use to bind your items to a mschart and get columns charts:
Example 1: single area and side-by-side columns
private void FillChartSingleArea()
{
    // this set the datasource
    this.chart1.DataSource = GetItems();

    // clear all the (possible) existing series
    this.chart1.Series.Clear();

    // add the hours series
    var hoursSeries = this.chart1.Series.Add("Hours");
    hoursSeries.XValueMember = "Name";
    hoursSeries.YValueMembers = "Hours";
    hoursSeries.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;

    // add the percentages series
    var percSeries = this.chart1.Series.Add("Percentages");
    percSeries.XValueMember = "Name";
    percSeries.YValueMembers = "Percent";
    percSeries.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
}

Example 2: two charts one upon the other
private void FillChartDoubleArea()
{
    // this set the datasource
    this.chart1.DataSource = GetItems();

    // clear all the (possible) existing series
    this.chart1.Series.Clear();

    // clear all the existing areas and add 2 new areas
    this.chart1.ChartAreas.Clear();
    this.chart1.ChartAreas.Add("Area1");
    this.chart1.ChartAreas.Add("Area2");

    // add the hours series
    var hoursSeries = this.chart1.Series.Add("Hours");
    hoursSeries.ChartArea = "Area1";
    hoursSeries.XValueMember = "Name";
    hoursSeries.YValueMembers = "Hours";
    hoursSeries.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;

    // add the percentages series
    var percSeries = this.chart1.Series.Add("Percentages");
    hoursSeries.ChartArea = "Area2";
    percSeries.XValueMember = "Name";
    percSeries.YValueMembers = "Percent";
    percSeries.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
}

Example 3: single area and stacked columns
private void FillStackedChartSingleArea()
{
    // this set the datasource
    this.chart1.DataSource = GetItems();

    // clear all the (possible) existing series
    this.chart1.Series.Clear();

    // add the hours series
    var hoursSeries = this.chart1.Series.Add("Hours");
    hoursSeries.XValueMember = "Name";
    hoursSeries.YValueMembers = "Hours";
    hoursSeries.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.StackedColumn;

    // add the percentages series
    var percSeries = this.chart1.Series.Add("Percentages");
    percSeries.XValueMember = "Name";
    percSeries.YValueMembers = "Percent";
    percSeries.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.StackedColumn;
}

Where GetItems method is defined as follows (for all the examples):
private List<DOHoursChartItem> GetItems()
{
    var items = new List<DOHoursChartItem>()
    {
        new DOHoursChartItem("John", 120),
        new DOHoursChartItem("Amanda", 40),
        new DOHoursChartItem("David", 70),
        new DOHoursChartItem("Rachel", 10),
    };
    // compute the percentages
    var totalHours = items.Sum(x => x.Hours);
    foreach (var item in items)
        item.Percent = (item.Hours * 100.0) / totalHours;
    return items;
}

and DOHoursChartItem as :
    class DOHoursChartItem
    {
        public String Name { get; set; }
        public double Hours { get; set; }
        public double Percent { get; set; }
        public DOHoursChartItem(string name, double hours)
        {
            this.Name = name;
            this.Hours = hours;
        }
    }

N.B.
these are actually Column charts; by setting the ChartType to Bar (or StackedBar), you will get the same result but the bars will have an horizontal orientation.
Comment: @digEmAll, thank you very much for such a comprehensive answer.
Comment: Thanks. C# is no problem, I'm a lot better at it than VB.NET myself, but I'm just doing VB for this one project.
Comment: @ProfK - did this not answer your question?
Comment: @ProfK: adedd a stacked chart example.


Ler conteúdo de vários arquivos .txt's de uma determinada pasta

Question: Tenho este código que lê um arquivo criado por Netscape HTTP Cookie File, porém eu só consegui utilizar o script e ler o arquivo do usuário que está com a sessão username aberta, eu preciso listar todos os TXTS e ler todos eles sem exceção.
OBS: os arquivos estão com nomes diferentes:
<?php

require_once getcwd() . '/modules/config.php';

$username = null;

if (isset($_SESSION['username'])) {
    $username = $_SESSION['username'];
}

$pointer = fopen(getcwd() . '/cookies/' . $username . '.txt', 'r');

while (!feof($pointer)) {
    $row = fgets($pointer);
}

fclose($pointer);

Como ler todos os arquivos com nomes diferentes sem ser o arquivo com o nome criado na sessão ?
EDITADO
Nos comentários o Anderson citou o uso da função glob(), eu consegui ler todos os arquivos com este código.
foreach (glob(getcwd() . '/cookies/*.txt') as $file) {
    $pointer = fopen($file, 'r');
    while (!feof($pointer)) {
        $row[] = fgets($pointer);
    }
}

var_dump($row);

Porém contem linhas desnecessárias no arquivo, eu preciso pegar apenas os cookies, olha o que me retorna:

Eu preciso apenas dos cookies, entendem?
Comment: Leia sobre a função [`glob`](http://php.net/manual/pt_BR/function.glob.php).
Comment: Pode sim, sem problemas.
Comment: Quais dessas linhas seriam os cookies?
Comment: Ta blz. vou ver.
Comment: @AndersonCarlosWoss posso responder minha propria pergunta?
Comment: @AndersonCarlosWoss Editei, vê se vc consegue me ajudar.
Comment: `_twitter_sess`, `ct0`, `auth_token`, `twid`, preciso dessses, prefixo e valores. entende?
Answer: Pelo comentário, você deseja pegar apenas as linhas que contenham os valores de _twitter_sess, ct0 e auth_token. Você pode armazenar esses valores em uma lista:
$tokens = ['_twitter_sess', 'ct0', 'auth_token'];

E verificar quais linhas possuem pelo menos um desses valores:
foreach (glob(getcwd() . '/cookies/*.txt') as $file) {
    $pointer = fopen($file, 'r');
    while (!feof($pointer)) {
        $line = fgets($pointer);

        foreach ($tokens as $token) {
            if (strpos($line, $token) !== false) {
                $row[] = $line;
                break;
            }
        }
    }
}

Assim, a linha em $pointer só será adicionada à lista se algum token definido em $tokens for encontrado na linha. Depois disso, você pode utilizar tanto expressão regular quanto separar a linha nos espaços em branco para extrair o valor desejado.
Comment: Pronto, era preciso ler a linha do arquivo antes da verificação, com a variável `$line`. Antes eu estava verificando o ponteiro, que não faz muito sentido.
Comment: Testando... só um minuto, está com erro, vou tentar resolver
Comment: Eu adicionei mais linhas, `$tokens = ['_twitter_sess', 'ct0', 'auth_token', 'twid'];` porem só está me retornando assim: http://prntscr.com/ggz52e, e percebi que não está listando todos os arquivos.
Comment: Você verificou se o retorno de `glob` é a lista com todos os arquivos?
Comment: Sim todos eles contém no arquivo, no caso ali você está verificando todos que são diferentes de `false` no caso, me retornará todos as linhas que são `TRUE / TRUE` porém não está retornando todos, apenas `_twitter_sess`, os dois primeiro, do arquivo 1 e do arquivo 2. E o resto não.
Comment: Tem como colocar o conteúdo dos arquivos em algum lugar para podermos replicar? Pode retirar dados potencialmente sensíveis, desde que não altere o formato do arquivo.
Comment: @PedroSilva outro erro meu, perdão. O `fgets` deve estar fora do laço que percorre os *tokens*, senão o conteúdo da linha é alterado de um *token* para o outro, por isso gerou um resultado inesperado. Já alterei na resposta e acredito que assim deva funcionar.
Comment: Boa, eu poderia ter percebido isso também, mas passou batido rsrs, obrigado, agora uma dúvida, posso usar esses cookies normalmente sem usar a global `$_COOKIES` ? não faz sentido eu salvar um arquivo contendo cookies e não utiliza-los.


Evaluate $\lim\limits_{x \to 1}\dfrac{x-x^x}{1-x+\ln x}$.

Question: Problem
Evaluate $$\lim\limits_{x \to 1}\frac{x-x^x}{1-x+\ln x}$$.
Solution
Consider using Taylor's formula. Expand $x^x $ and $\ln x$ at $x=1$. We obtain
$$x^x=1+(x-1)+(x-1)^2+o((x-1)^2);$$
$$\ln x=(x-1)-\frac{1}{2}(x-1)^2+o((x-1)^2).$$
Therefore
\begin{align*}
\lim_{x \to 1}
\frac{x-x^x}{1-x+\ln x}&=\lim_{x \to 1}\frac{x-[1+(x-1)+(x-1)^2+o((x-1)^2)]}{1-x+[(x-1)-\frac{1}{2}(x-1)^2+o((x-1)^2)]}\\
&=\lim_{x \to 1}\frac{-(x-1)^2-o((x-1)^2)}{-\frac{1}{2}(x-1)^2+o((x-1)^2)}\\
&=2.
\end{align*}
Please correct me if I'm wrong! Can we solve it by L'Hospital's rule?
Comment: How do you get the expansion of $x^x$ ?
Comment: l'Hospital's rule can be used because it is the case $0/0$ and the denominator derivative $(x-1+\ln x)'\neq 0$ if $x\neq 1.$
Answer: $1-x=h\implies$
$$\lim_{h\to0}(1-h)\cdot\dfrac{1-(1-h)^{-h}}{h+\ln(1-h)}=\lim_{h\to0}\dfrac{1-\left(1+(-h)(-h)+\dfrac{(-h)(-h-1)}2\cdot h^2+O(h^3)\right)}{h-\left(h+\dfrac{h^2}2+O(h^3)\right)}=\dfrac1{\dfrac12}$$
So, you are correct
Answer: Why no?
$$\lim_{x\rightarrow1}\frac{x-x^x}{1-x+\ln{x}}=\lim_{x\rightarrow1}\frac{1-x^x(1+\ln{x})}{-1+\frac{1}{x}}=\lim_{x\rightarrow1}\frac{-x^x(1+\ln{x})^2-x^x\cdot\frac{1}{x}}{-\frac{1}{x^2}}=2$$
Answer: Another solution by L'Hospital's rule
Let $x=:1+h$. Then
\begin{align*}
\lim_{x \to 1}
\frac{x-x^x}{1-x+\ln x}&=\lim_{h \to 0}\frac{(1+h)[1-(1+h)^{h}]}{\ln(1+h)-h}\\
&=\lim_{h \to 0}\frac{e^{h\ln(1+h)}-1}{h-\ln(1+h)}\\
&=\lim_{h \to 0}\frac{h\ln(1+h)}{h-\ln(1+h)}\\
&=\lim_{h \to 0}\frac{h^2}{h-\ln(1+h)}\\
&=\lim_{h \to 0}\frac{2h}{1-\frac{1}{1+h}}\\
&=2\lim_{h \to 0}(1+h)\\
&=2.
\end{align*}


XSLT Namespace troubles

Question: In the next step of a project I am working on I am having a problem with namespace statements in an xslt file. I admit that the problem is likely identical to that found in this question: Filemaker XSL Importing blank fields. However, I'm not able to understand the solution there and feel that perhaps the answer may be a bit more simplistic, i.e. I've mucked up the syntax somehow.
The xml I'm working with is:
    <?xml version="1.0" encoding="utf-8" ?>
    <ledesxml xmlns="http://www.ledes.org/ledes20.xsd">
      <firm>
        <lf_vendor_id>test</lf_vendor_id>
      </firm>
    </ledesxml>

The xslt I'm currently using is:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
    xmlns="http://www.ledes.org/ledes2000.xsd"
    xmlns:t="http://www.ledes.org/ledes2000.xsd"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="/">

<FMPXMLRESULT xmlns="http://www.filemaker.com/fmpxmlresult">

    <METADATA>
        <FIELD NAME="lf_vendor_id" TYPE="TEXT"/>
    </METADATA>

    <RESULTSET>
        <ROW>
            <COL><DATA><xsl:value-of select="/t:ledesxml/t:firm/t:lf_vendor_id"/></DATA></COL>
        </ROW>
    </RESULTSET>

</FMPXMLRESULT>

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

The import to Filemaker results in a new record without any data. The xml input here is an industry standard and doesn't change (at least for present purposes).
The use of name spaces here is a bit confusing and is based almost entirely on the namespaces used in the question linked above. Using a wild card in the "value-of select" statement does work, but as you might expect, grabs all the text in the xml sample and not just the data in which I am interested.
Since the import seems to work and the name space convention seems to have worked for another poster, I'm at a bit of a loss. Does anyone have some pointers as to where I've gone wrong?
Answer: The XML document has xmlns="http://www.ledes.org/ledes20.xsd" while the XSLT declares xmlns:t="http://www.ledes.org/ledes2000.xsd" with ledes2000 instead of ledes20. You will need to use the same namespace URL in both documents.
Comment: Again, you have saved the day. Thank you once more.

XSLT Namespace troubles


I can not figure out why my drop down menue is not hiding

Question: So, I can not figure out why my drop down menu is not hiding  my #nav ul is set to left:-999px and so it should be way off screen, but for some reason it is not  hiding and instead just sitting in plain view.  BTW my nav bar is a PHP include, I have gotten this to work before, I probably just missed something along the way and it is probably just a stupid mistake on my part, feel free to call me an idiot, but I can not for the life of me figure out what I did wrong this time.
Here is a link to it hosted: http://addisonbwilson.com/Index.php
The CSS
@charset "UTF-8";
/* CSS Document */

/*The body is responsiable for the background image, the rest of the site is divided between the sub wrapper and the includes */
/*bground tile is from http://subtlepatterns.com/white-brushed/ created by Andre Schouten, crediting him here as per the usage agreement */
body {margin-top: 0px; background-image:url(../firstname.lastname@example.com)}
/* navbar is a php include*/

#navbarwrapper{positon: absolute; width:980px; height: 120px; z-index:30; background-color:#FFF;}
#navbar{width:980px; height:120px; background-image:url(../Portfolio/IMAGES/Bannerbgimg.png); background-repeat:repeat-x; z-index:31;}
#navbarlogo{width:210px; height:120px; float:left; z-index:32;}
#navbarcontent{width:770px; height:120px; float:left; font-family:Verdana, Geneva, sans-serif; z-index:32;}
#wrapper{width:980px; height:auto;}
#subwrapper{width: 980px; height: auto;}
#imagecontainer{width: 320px; height: 320px; background-color:#FFF; margin:3px 3px 3px 3px;}

/*Unordered lists which are used to handle drop down nav bar*/
#nav{
        list-style:none;
        font-family:Helvetica, Arial, sans-serif;
        margin-bottom:10px;
        float: right;
        width:100%;
        position:relative;
    }
#nav li{float:left; margin-right:10px; position:relative;}
#nav a{display:block; padding:5px; color:#000; text-decoration:none;}
#nav a:hover{color:#fff; background:#000; text-decoration:none;}

#nav ul{
    background:#fff;
    background:rbga(255,255,255,0);
    list-style:none;
    position:absolute;
    left:-9999px !important;}
#nav ul li{ padding-top:1px; float:none; list-style:none;}
#nav ul a{white-space:nowrap;}
#nav li:hover ul{ left:0;}
#nav li:hover a{background:#ccc; text-decoration:underline;}
#nav li:hover ul a{text-decoration:none;}
#nav li:hover ul li a:hover{background:#000;}

h1{font-size:large}
h2{font-size:larger}
h3{font-size:medium}
img {border:none}

/*link modification*/
a:link{ text-decoration: none; color:#FFF; font-family: Helvetica, Arial, sans-serif}
a:visited{text-decoration: none;color:#FFF; font-family: Helvetica, Arial, sans-serif}
a:active{text-decoration: none;color:#FFF; font-family: Helvetica, Arial, sans-serif}
a:hover{text-decoration: none; color:#FFF; font-family: Helvetica, Arial, sans-serif}

The navbar.php
<link rel="stylesheet" type="text/css" href="Portfolio/CODE/pcss.css">

Portfolio

Photography

Graphic Art

Web Design

Game Design

About Me

Resume

Contact

Social Media

Contact Information

The site itself is just an include tag for the nav and a wrapper for the content, which is empty atm.
<!doctype html>

<meta charset="UTF-8">
<title>Addison Wilson</title>
<link rel="stylesheet" type="text/css" href="Portfolio/CODE/pcss.css">

    <?php include ("Portfolio/INCLUDES/navbar.php"); ?>

Answer: I browsed to the site in your link, but I couldn't find the dropdown css in the uploaded css file.
So by using the live edit tool in Firefox, I added the css that you have in your question,
#nav ul{
    background:#fff;
    background:rbga(255,255,255,0);
    list-style:none;
    position:absolute;
    left:-9999px !important;}

and the submenu disappeared off screen. Could you double check that the css file on the server is up to date?
Comment: It is there, I just downloaded the version that is up on my webserver and it is there.  I even then deleted the version on my webserver and uploaded the most recent version.  If you go to the style editor tab under FireFox's inspect, it shows it as well, but under the inspector it does not show it inheriting the rules from #nav ul.
Comment: I took a look in Chrome instead, and there I saw the css. I repaced the `` with `/* drop down */` instead, and then the submenu was moved off screen.