text:
Q: No graphical interface after hard shutdown I just installed ubuntu on my laptop and I must have spelled my username and or password wrong because I cannot login now.  I tried shuting down my computer manually by holding down the power button and now all I see is a blinking dash.  What can I do?

A: You can reinstall. Or the geeky method would be this:

*

*Boot from the live CD into Ubuntu.

*Mount your hard drive by opening it in Nautilus/Dolphin

*Open a terminal window

*type cd /media to go where the harddrives are

*type ls to see the names of all of them. One is your root drive.

*become root by doing sudo su, the password is empty, just press enter

*chroot HARD_DRIVE_NAME

*passwd YOUR_SHORT_USER_NAME and enter a new password

*reboot and use your new password


text:
Q: First order differential equation (with a logistic function) I came across this first order differential equation
$$ f'(x) = \left( \frac{1}{x} + \frac{g'(x)}{g(x)} \right) f(x) - c \frac{g'(x)}{g(x)} \textrm{,}$$
where $g(x)$ is this logistic type function
$$ g(x) = \frac{h}{1+e^{-(x-a)}} + b $$
and $a$, $b$, $c$ and $h$ are constants.
1st try:
First I tried integrating both sides and got
$$ f(x) = \int \frac{f(x)}{x} \mathrm{d}x + \left[ cx - f(x) \right] \ln g(x) + C $$
or
$$ \int \frac{f(x)}{x} \mathrm{d}x = \left[ 1 + \ln g(x) \right] f(x) - c x \ln g(x) + C $$
and in both cases the leftover integral term seems to be quite problematic.
2nd try:
After that I remembered that I should probably be using the integrating factor method and looked up that the solution should be
$$ f(x) = \frac{1}{\mu(x)} \left( \int \mu(x) \left( - c \frac{g'(x)}{g(x)}\right) \mathrm{d} x + C\right) $$
with
$$ \mu(x) = \exp \left[ -\int \left( \frac{g'(x)}{g(x)} + \frac{1}{x} \right) \mathrm{d}x \right] = \frac{1}{x g(x)}$$
so finally
$$ f(x) = x g(x) \left( \int \frac{1}{x g(x)} \left( - c \frac{g'(x)}{g(x)}\right) \mathrm{d} x + C \right) = - c x g(x) \left( \int \frac{g'(x)}{g^2(x)} \frac{\mathrm{d} x}{x} + C\right) \textrm{.}$$
The evaluation of the integral
$$ \int \frac{g'(x)}{g^2(x)} \frac{\mathrm{d} x}{x} = \int \frac{\mathrm{d}}{\mathrm{d}x} \left( \frac{h}{1+e^{-(x-a)}} + b \right) \left( \frac{h}{1+e^{-(x-a)}} + b \right)^{-2} \frac{\mathrm{d} x}{x} $$
$$ = h \int \left( \frac{ e^{-(x-a)}}{(1+e^{-(x-a)})^2} \right) \left( \frac{h}{1+e^{-(x-a)}} + b \right)^{-2} \frac{\mathrm{d} x}{x} $$
seems quite though and I haven't made much progress.
Is there a way to evaluate this integral or is there possibly an easier way to solve the original differential equation?
EDIT: I just realized that
$$ g'(x) = [g(x) - b] - [g(x) - b]^2 = g(x) - b - g^2(x) + 2g(x)b - b^2 $$
so that
$$ \frac{g'(x)}{g^2(x)} = \frac{1 + 2b}{g(x)} - \frac{b + b^2}{g^2(x)} - 1 $$
and I would only need to know how to evaluate
$$ \int \frac{1}{g(x)} \frac{\mathrm{d} x}{x} \quad \textrm{and} \quad \int \frac{1}{g^2(x)} \frac{\mathrm{d} x}{x} \textrm{.} $$
Could there be a closed form solution or maybe just a series representation or something?

A: Whenever I see $\displaystyle\frac{g'(x)}{g(x)}$, my immediate instinct is to write that as $[\ln g(x)]'$. Here it helps, as follows:
$f'(x) = [\,\displaystyle\frac{1}{x} + (\ln g)'\,]\,f(x) - c\,(\ln g)'$
$f' = \displaystyle\frac{f}{x} + (f-c)\,(\ln g)'$
Now define a new function $u(x) = f(x) - c$. Then,
$u' = \displaystyle\frac{u + c}{x} + (\ln g)'\,u$
$x\,u' = u + c + x\,(\ln g)'\,u = c + \underbrace{[1 + x\,(\ln g)']}_{a(x)}\,u$
$x\,u'(x) - a(x)\,u(x) = c$
The homogeneous equation is:
$\displaystyle\frac{u'(x)}{u(x)} = \displaystyle\frac{a(x)}{x}$
So...
$[\,\ln u(x)\,]' = \displaystyle\frac{a(x)}{x} = \displaystyle\frac{1}{x} + [\,\ln g(x)\,]'$
and
$\ln u = \ln x + \ln g + \ln A$
($A$ is an integration constant)
$u(x) = A\,x\,g(x)$
I'll let you continue from here. You could use the method of variation of parameters to find a particular solution $u_{p}(x)$ of
$x\,u'(x) - a(x)\,u(x) = c$
then use $f(x) = A\,x\,g(x) + u_{p}(x) + c$ as your final general solution.
Edit: I decided to complete the solution so...
Method of variation of parameters. We have a general solution of the homogeneous equation, $u(x) = A\,x\,g(x)$. Now, try a particular solution of the form $u_p(x) = A(x)\,x\,g(x)$. Then,
$x\,u'(x) - a(x)\,u(x) = c$
gives us
$A'(x)\,x^2\,g(x) = c$
so
$A(x) = \displaystyle\int^x \frac{c\,dt}{t^2\,g(t)}$
and
$u_p(x) = A(x)\,x\,g(x) = c\,x\,g(x) \displaystyle\int^x \frac{dt}{t^2\,g(t)}$
and the final general solution is
$f(x) = A\,x\,g(x) + c\,x\,g(x) \displaystyle\int^x \frac{dt}{t^2\,g(t)} + c$
where $A$ is a constant.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get original image from thumbnail URL I am using a method to find the first image included in a post's content to display as it's thumbnail (a little hacky, but it works). However, some authors add small sized images, and since this function only finds the URL for that size, it doesn't look to good when it's inflated.
if ($img = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches))
    return $img = $matches[1][0];

So, I need a way to get the URL of the original image, or the large size. It can probably be done with RegEx, but what is the fastest solution?

A: This is sort of an alternative solution to doing a bunch of RegEx. Query all images attached to the post, get the thumbnail of the first and display it as thumbnail ( you could even assign it as the post thumbnail if you wanted to, to make it easier next time the loop is run ). So inside your loop you would have:
if( have_posts() ) {
    $image_mimes = array( 'image/jpeg', 'image/gif', 'image/png' );

    while( have_posts() ) {
        the_post();
        $attachment_query = new WP_Query( array(
            'post_type'         => 'attachment',
            'post_parent'       => $post->ID,
            'post_status'       => 'inherit',
            'post_mime_type'    => $image_mimes,
            'posts_per_page'    => 1,
            'fields'            => 'ids',               // Small and Quick query, only pull attachment IDs
        ) );

        if( has_post_thumbnail() ) {
            $thumbnail_html = get_the_post_thumbnail();
        } elseif( $attachment_query->have_posts() ) {
            $thumbnail_html = wp_get_attachment_image( $attachment_query->posts[0], 'thumbnail' );
            wp_reset_query();
        } else {
            $thumbnail_html = 'Default Image HTML here - No Images Attached to Post';
        }

        echo $thumbnail_html;
    }
}

Now there are some drawbacks to this:

*

*This won't remove the image from the content, just allows you to append it to the top

*This includes all images attached to the post, not images just in the content - so images could be assigned to the post but not directly in the post content.


text:
Q: curl does not terminate after successful POST I have created some curl command to send a POST to my server where I am listening on that port for input to trigger additional action. The command is the following (Just masked the URL):
curl -v -H "Content-Type: application/json" -X POST -d "{\"Location\":\"Some Name\",\"Value\":\"40%\"}" http://example.com:8885/

I get the following output from curl:

About to connect() to example.com port 8885 (#0)
Trying 5.147.XXX.XXX...
Connected to example.com (5.147.XXX.XXX) port 8885 (#0)
POST / HTTP/1.1
User-Agent: curl/7.29.0
Host: example.com:8885
Accept: /
Content-Type: application/json
Content-Length: 40
upload completely sent off: 40 out of 40 bytes

However after that curl does not close the connection. Am I doing something wrong? Also on the server I only receive the POST as soon as I hit ctrl+c.

A: It sits there waiting for the proper HTTP response, and after that has been received it will exit cleanly.
A minimal HTTP/1.1 response could look something like:
HTTP/1.1 200 OK
Content-Length: 0

... and it needs an extra CRLF after the last header to signal the end of headers.

A: I'm a bit rusty on this, but according to section 6.1 of RFC7230, you might need to add a Connection: close header as well. Quoting part of the paragraph:

The "close" connection option is defined for a sender to signal
that    this connection will be closed after completion of the
response.  For    example,
 Connection: close

in either the request or the response header fields indicates that
the sender is going to close the connection after the current
request/response is complete (Section 6.6).

Let me know if it solves your issue :-)

A: Is there a question mark in link ?
I found that my link had question mark like http... .com/something/something?properties=1 and i tried header connection: close but it was still active so i tried then removing ?properties etc. and it worked...


text:
Q: Neo4j Cypher: interdependent relationship values in a path I have a graph dataset loaded in Neo4j with nodes being various persons and relationships being some "real" relationships between them. What makes it complicated is that each relationship has a time period during which it was valid. For example:
(p1:PERSON {name: "Andy"})
-[r1:HAS_RELATIONSHIP {from: "20190201", to: "20190215"}]->
(p2:PERSON {name: "Betty"})
-[r2:HAS_RELATIONSHIP {from: "20190301", to: "20190331"}]->
(p3:PERSON {name: "Cecil"})

I'd like to take one concrete person P and get a list of all persons with whom P was in an indirect relationship through other persons. It must hold that the intersection of dates in any relationship chain is nonempty.
So from the previous example, if we take Andy as P, the result should be Andy, Betty, because the relationship with Cecil was valid in a completely different period of time. But in the following case:
(p1:PERSON {name: "Andy"})
-[r1:HAS_RELATIONSHIP {from: "20190201", to: "20190215"}]->
(p2:PERSON {name: "Betty"})
-[r2:HAS_RELATIONSHIP {from: "20190210", to: "20190301"}]->
(p3:PERSON {name: "Cecil"})

the result should be Andy, Betty, Cecil.
Is there a way how to specify this condition in Cypher? I'm looking for an efficient solution which prunes the already found paths.

A: You basically have a list of intervals from all relationships on a path. For this list of intervals you need to check if they all overlap. This can be done by checking max(from) <= min(to), in cypher:
MATCH path=(p:PERSON {name:'Andy'})-[*..10]-(other) // Doesn't matter how you get the paths
UNWIND relationships(path) as r
WITH path,max(r.from) AS maxFrom,min(r.to) AS minTo
WHERE maxFrom <= minTo
RETURN extract(x in nodes(path) | x.name)


text:
Q: Checkbox not working on mac I wrote an excel VBA macro that works with checkboxes. To check whether the checkbox is selected or not I use the following code:
Sheet4.Shapes("dietary").OLEFormat.Object.Value

This works well on a windows PC; however, a colleague uses a mac and there it produces an error.
How can I use the checkboxes in a way that is compatible with windows and mac?

A: The problem is not with the Checkbox. It is with the way you are referencing the sheet :)
Codenames sometimes give a problem in Excel 2011
Try this
ThisWorkbook.Sheets("Sheet4").Shapes("dietary").OLEFormat.Object.Value

Example (Depicting Both Scenarios)

Now removing the CodeName


text:
Q: Determine corner weights of a trapezoid Working with determining the corner weights on one axis isn't too bad.

If A is to the left of the Center of Gravity and B is to the right of the Center of Gravity. You have two equations to work with.
$$\text{Total}_\text{Moment} = \text{A}_\text{Moment} + \text{B}_\text{Moment}$$
$$\text{Total}_\text{Weight} = \text{A}_\text{Weight} + \text{B}_\text{Weight}$$
If I have a rectangle I can determine the weight on one axis for the left section and then determine the weights for the other axis. Since everything is parallel this seems to work out.

However, once I have a trapezoid, things stop coming out. How would I determine this?
Also, is there a way to determine the corner weight of a quadrilateral that doesn't have any corners that are parallel to one another.

In all the example, the Total Weight is known, the CG on the X axis and Y axis relative to a given Datum point are known. And all corner locations relative to that same Datum point are also known.

A: *

*Problem Setup
A flat table with $n$ legs resists the total weight $W$ and the forces and moments are balanced. Each leg is located at $(x_i,\,y_i)$ relative to the center of gravity of the table. The legs run along the z-direction.
Find the force $F_i$ on each leg.

*Mathematical Model
First the degrees of freedom are recognized and the problem is described with respect to those degrees of freedom. Since the table defines a plane, there are three possible DOF here. The total vertical translation of the table $\delta_z$, and two orientation angles $\theta_x$ and $\theta_y$ such as the cartesian coordinates of each support are $$ \vec{p}_i = \pmatrix{x_i \\ y_i \\ \delta_z + y_i \theta_x - x_i \theta_y} $$
To make the problem solvable, we assume the legs are equally elastic (springs) with a coefficient $k$, which in the end will cancel out. This makes the leg force proportional to the deflection (taken from the z-coordinate of $\vec{p}_i$) $$ F_i = k (\delta_z + y_i \theta_x - x_i \theta_y) $$
This means, that if we solve for the three degrees of freedeom $(\delta_z,\, \theta_x,\, \theta_y)$ we can calculate each leg force and sovle the problem.

*Force Balance
The sum of the forces must equal the weight, which yields one of the three equations needed.
$$ W = k \sum_{i=1}^n (\delta_z + y_i \theta_x - x_i \theta_y) $$
The above is solved for the vertical translation $\delta_z = \frac{1}{n} \left( \tfrac{W}{k} + \theta_y \sum_{i=1}^n x_i - \theta_x \sum_{i=1}^n y_i \right) $ which can be used in the leg force expression as
$$ F_i = \frac{1}{n} \left( W + k \left( \theta_x \left( n y_i - \sum_{i=1}^n y_i \right) - \theta_y \left( n x_i - \sum_{i=1}^n x_i \right) \right)  \right) $$

*Moment Balance
Each force results in a torque about the origin that is simply a function of the position of the leg $  (M_x)_i = y_i F_i$ and $(M_y)_i = -x_i F_i $. The sum of all the torques must be zero
$$ \matrix{ 0 = \sum \limits_{i=1}^n y_i F_i & 0 = \sum \limits_{i=1}^n (-x_i) F_i } $$
These are the two other equations needed to solve for $\theta_x$ and $\theta_y$. Use the force expression to get
$$\begin{aligned}
0&=\tfrac{W\left(\sum_{i=1}^{n}y_{i}\right)+k\left(\left(n\sum_{i=1}^{n}y_{i}^{2}-\left(\sum_{i=1}^{n}y_{i}\right)^{2}\right)\theta_{x}-\left(n\left(\sum_{i=1}^{n}x_{i}y_{i}\right)-\left(\sum_{i=1}^{n}x_{i}\right)\left(\sum_{i=1}^{n}y_{i}\right)\right)\theta_{y}\right)}{n}\\
0&=\tfrac{-W\left(\sum_{i=1}^{n}x_{i}\right)+k\left(-\left(n\sum_{i=1}^{n}x_{i}y_{i}-\left(\sum_{i=1}^{n}x_{i}\right)\left(\sum_{i=1}^{n}y_{i}\right)\right)\theta_{x}+\left(n\sum_{i=1}^{n}x_{i}^{2}-\left(\sum_{i=1}^{n}x_{i}\right)^{2}\right)\theta_{y}\right)}{n}
\end{aligned}$$

*Deflection Solution
The above 2×2 system is solved as $ \theta_x = \frac{W\,n}{k} C_x$ and $ \theta_y = \frac{W\,n}{k} C_y$ where
$$ \begin{aligned}
C_{x} & = \tfrac{\left(\sum_{i=1}^{n}x_{i}\right)\left(\sum_{i=1}^{n}x_{i}y_{i}\right)-\left(\sum_{i=1}^{n}x_{i}^{2}\right)\left(\sum_{i=1}^{n}y_{i}\right)}{\left(n\left(\sum_{i=1}^{n}y_{i}^{2}\right)-\left(\sum_{i=1}^{n}y_{i}\right)^{2}\right)\left(n\left(\sum_{i=1}^{n}x_{i}^{2}\right)-\left(\sum_{i=1}^{n}x_{i}\right)^{2}\right)-\left(n\left(\sum_{i=1}^{n}x_{i}y_{i}\right)-\left(\sum_{i=1}^{n}x_{i}\right)\left(\sum_{i=1}^{n}y_{i}\right)\right)}
\\ C_{y} & = \tfrac{\left(\sum_{i=1}^{n}x_{i}\right)\left(\sum_{i=1}^{n}y_{i}^{2}\right)-\left(\sum_{i=1}^{n}y_{i}\right)\left(\sum_{i=1}^{n}x_{i}y_{i}\right)}{\left(n\left(\sum_{i=1}^{n}y_{i}^{2}\right)-\left(\sum_{i=1}^{n}y_{i}\right)^{2}\right)\left(n\left(\sum_{i=1}^{n}x_{i}^{2}\right)-\left(\sum_{i=1}^{n}x_{i}\right)^{2}\right)-\left(n\left(\sum_{i=1}^{n}x_{i}y_{i}\right)-\left(\sum_{i=1}^{n}x_{i}\right)\left(\sum_{i=1}^{n}y_{i}\right)\right)}
\end{aligned} $$

*Force Solution
Using the above angles $\theta_x$ and $\theta_y$ in the force equation from step 3) yields the following solution (where $k$ cancels out).
$$ \boxed{ F_i = W \left( \frac{1}{n} + \left( n y_i - \sum_{i=1}^n y_i \right) C_x - \left( n x_i - \sum_{i=1}^n x_i \right) C_y \right) } $$

*Example
I wrote a quick (Fortran) computer program to test the above. I used 4 legs at $A=(-1,-1)$, $B=(1,-1)$, $C=(-2,2)$ and $D=(2,5)$.

The source code is avaiable on GitHub as a gist.


text:
Q: Lock a column based on id using jQuery Is it possible to lock a column based on it's id using jquery? I've seen different solutions, like header locking, and some can also lock the columns indexing from left. What I am trying to do is when I click the lock button, it will lock the column and won't be moved when scrolled horizontally.
For example I click the lock on header 1, scrolled horizontally, then clicked lock on header 3. Header 1 and Header 3 should be adjacent to each other and shouldn't move when scrolled horizontally.
Click here to view image
Below is my code:

                January 24, 2013
                <button id="lid_1">Lock</button>

                January 25, 2013
                <button id="lid_2">Lock</button>

                January 26, 2013
                <button id="lid_3">Lock</button>

                January 27, 2013
                <button id="lid_4">Lock</button>

                January 27, 2013
                <button id="lid_5">Lock</button>

                January 28, 2013
                <button id="lid_6">Lock</button>

        Header 1
        Header 2
        Header 3
        Header 1
        Header 2
        Header 3
        Header 1
        Header 2
        Header 3
        Header 1
        Header 2
        Header 3
        Header 1
        Header 2
        Header 3
        Header 1
        Header 2
        Header 3

                    1
                    2
                    3

                    1
                    2
                    3

                    1
                    2
                    3

                    1
                    2
                    3

                    1
                    2
                    3

                    1
                    2
                    3

A: OK I got it.
Continuing fricke
approach which is fixing the column...
It seems that you need a map of fixed columns and prevent pileing on ot top of another. It's not replaced as you thought it's just that probably the newly fixed goes on top of the old one.
So you do that:
var fixedColumns = jQuery();
$('#id_of_column').click(function () {
    var that = $(this);
    if (that.hasClass('locked')) {
        //Unlock
        that.removeClass('locked')
            .css({'left': ''});
        fixedColumns = fixedColumns.not(that);
    } else {
        //Lock
        fixedColumns = fixedColumns.add(that);
        that.addClass('locked');
        orderLockedColumns(fixedColumns);
    }
});

function orderLockedColumns(columns) {
    var that, leftPos, prevCol, prevColWidth, prevColPos;
    columns.each(function (i) {
        that = $(this),
        leftPos = 0;
        if (i !== 0) {
            prevCol = jQuery(columns[i - 1])
            prevColWidth = prevCol.width();
            prevColPos = prevCol.position().left;
            leftPos = prevColPos + prevColWidth
        }
        that.css('left', leftPos+'px');
    })
}

CSS:
.locked{
  position:fixed;
}

However I do not recommend adding multi-listeners based on id !
It's better using class="lockButton" and then if you need the id you can take it.
So it's better:
jQuery(document).on('click','.lockButton'){
   var that = $(this),
   id = that[0].id;
   //... same code
}

Additionally since you didn't provide code and this is bad most people won't help you here if you don't provide any... so this code above might not work since I don't know your markup at all just guessing.

A: OK, here's a solution to your update.
However ids are meant to be unique so you shouldn't have 2 or more same ids. Classes are the tool in general use-cases.
You may add unique ids if unique columns are required but not using them as reference in the context of locking, but extract the id when you want to do something with it.
Here are the examples:
http://jsbin.com/odaxil/5
http://jsbin.com/odaxil/5/edit
js:
(function (window, undefined) {
    jQuery(function () {
        bindings();
    });

    function bindings() {
        var locker = jQuery('#locker');
        jQuery(document).on('click', 'button.lockButton', function () {
            var that = $(this),
                lidClass = '',
                parent = that.parents('td[class^="lid"]');
            if (parent.length) {
                lidClass = getColumnLidClass(parent);
                lockings = jQuery('td.' + lidClass);
                lockings.addClass('locked');
                that.text('Unlock');
                var fixedColumn = $(getLockedWrapper(lockings, lidClass));
                var index = parent.index();
                fixedColumn.data('index', index);

                if (index === 0) {
                    locker.prepend(fixedColumn);
                } else {
                    var lockedWraps = $('div.lockedWrap', locker),
                        lwrap = null,
                        indx, appended = false;
                    if (!lockedWraps.length) locker.append(fixedColumn);
                    lockedWraps.each(function () {
                        lwrap = $(this);
                        indx = lwrap.data('index') * 1;
                        if (!appended && (index < indx)) {
                            lwrap.before(fixedColumn);
                            appended = true;
                            return;
                        }
                    });
                    if (!appended) locker.append(fixedColumn);
                }
                that.text('Lock');
            } else {
                parent = that.parents('div.lockedWrap');
                lidClass = getColumnLidClass(parent);
                lockings = jQuery('td.' + lidClass);
                lockings.removeClass('locked');
                parent.remove();
            }
        });
    }

    function getLockedWrapper(lockings, lidClass) {
        var fixedColumn = [],
            cont;
        lockings.each(function () {
            cont = $(this).html();
            fixedColumn.push('
' + cont + '
');
        });
        fixedColumn = '
' + fixedColumn.join('') + '
';
        return fixedColumn;
    }

    function getColumnLidClass(td) {
        for (var i = 0; i < 100; i++) {
            if (td.hasClass('lid_' + i)) break;
        }
        return 'lid_' + i;
    }
})();

HTML:

January 24, 2013
                    <button class="lockButton" id="lid_1">Lock</button>

January 25, 2013
                    <button class="lockButton" id="lid_2">Lock</button>

January 26, 2013
                    <button class="lockButton" id="lid_3">Lock</button>

January 27, 2013
                    <button class="lockButton" id="lid_4">Lock</button>

January 27, 2013
                    <button class="lockButton" id="lid_5">Lock</button>

January 28, 2013
                    <button class="lockButton" id="lid_6">Lock</button>

            Header 1
            Header 2
            Header 3
            Header 1
            Header 2
            Header 3
            Header 1
            Header 2
            Header 3
            Header 1
            Header 2
            Header 3
            Header 1
            Header 2
            Header 3
            Header 1
            Header 2
            Header 3

                        1
                        2
                        3

                        1
                        2
                        3

                        1
                        2
                        3

                        1
                        2
                        3

                        1
                        2
                        3

                        1
                        2
                        3

CSS:
.locked{
  display:none;
}
#locker{
  float: left;
  min-width: 100px;
  min-height: 110px;
  background-color: #333;
}
div.lockedWrap{
  float:left;
  margin-right:1px;
  background-color: orange;
}


text:
Q: Pass A File Through Shell Script I have a script called head.sh, it looks like this:
#!/bin/bash
{
    read line1
    read line2
    read line3
}
echo $line1
echo $line2
echo $line3

And I need to call it like this:
sh head.sh < rhymes.txt

when I hardcode the filename in it works, but I can't work out how to pass in the file.

A: I've tried your script like this and it works:
cat some_file | sh ./head.sh > rhymes.txt

Or you're not allowed to use pipe in your excercise?
EDIT: OK, however still, your script works for me:
$ cat test
11111111
22222222
33333333
4444
555
66
7
$ sh ./head.sh < test
11111111
22222222
33333333
$ cat ./head.sh
#!/bin/bash
{
    read line1
    read line2
    read line3
}
echo $line1
echo $line2
echo $line3


text:
Q: How to make an inset border with padding I have this JsFiddle: Click here

                    hone

asdsad

Replace this LOL

Replace this LOL

Replace this LOL

What I want to have my border more look like this the border in the image:

As you can see it has an inset border with padding on top and bottom i guess.
How can I achieve those using css? I tried adding padding to li but it didnt work.

A: If I understand the question here is   DEMO
a.styleanchor:hover:before
    {
        content: "";
       position: absolute;
    display: inline-block;
    width: 0;
    height: 0;
    line-height: 0;
    border: 8px solid transparent;
    border-bottom: 8px solid #ffffff;
    left: 43%;
    right:43%;
    bottom: 0;
    }
#menu {
        text-align: center;
        position: relative;
        border-bottom: 1px solid gray;
        border-top: 1px solid gray;
        background: #ffffff; /* Old browsers */
        background: -moz-linear-gradient(top,  #ffffff 0%, #e5e5e5 100%); /* FF3.6+ */
        background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#e5e5e5)); /* Chrome,Safari4+ */
        background: -webkit-linear-gradient(top,  #ffffff 0%,#e5e5e5 100%); /* Chrome10+,Safari5.1+ */
        background: -o-linear-gradient(top,  #ffffff 0%,#e5e5e5 100%); /* Opera 11.10+ */
        background: -ms-linear-gradient(top,  #ffffff 0%,#e5e5e5 100%); /* IE10+ */
        background: linear-gradient(to bottom,  #ffffff 0%,#e5e5e5 100%); /* W3C */
        filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#e5e5e5',GradientType=0 ); /* IE6-9 */
        border-radius: 10px 10px 0px 0px;

    }

A: box-shadow: inset 0 0 5px 5px rgba(0, 0, 0, 0.1), inset 0 3px 2px 5px rgba(0, 0, 0, 0.1);


text:
Q: VB.net String contains reference to DataTable.Column I am using VB.NET and ADO 4.0. Given that I have a string containing a reference to a table.column, can I use the content of the string in a command?
Here is an example of the code I am trying to use:
intStatus = 1
strName = "tablename.columnname" & intStatus

'here I would need to have:
tablename.columnname1
'so I can perform following line
tablename.columnname1 = strValue

//////////////////////////////////////////////////
I got to the point where I can use the string contents as "reference", it seemed to obvious but [strName] does the trick, partially.... When I debug bookableday.room1 remains 0 whilst it should show 6. There might be a conversion issue because the debugger shows me "6" i.s.o. 6 . this is the actual code:
Do While intStatus < 14
                    If arrRoomStatus(intStatus) = True Then
                        strName = "bookableday.room" & intStatus
                        [strName] = 6
                        Bookableday.av_avail_id = intAv_avail_id
                        Bookableday.Av_Date = dteAddDate
                        dteAddDate = dteAddDate.AddDays(1)
                        intStatus = intStatus + 1
                        intAv_avail_id = intAv_avail_id + 1
                    Else
                        strName = "bookableday.room" & intStatus
                        [strName] = 5
                        Bookableday.av_avail_id = intAv_avail_id
                        Bookableday.Av_Date = dteAddDate
                        dteAddDate = dteAddDate.AddDays(1)
                        intStatus = intStatus + 1
                        intAv_avail_id = intAv_avail_id + 1
                    End If

A: I think all you are trying to do is this:
tablename.Rows(index)(ColumnName) = value

You can reference a column by it's column name, not just the index position.
Try referencing the DataTable by the current row and your column name, like this:
'// strName = "bookableday.room" & intStatus
strName = "room" & intStatus
If arrRoomStatus(intStatus) = True Then
  Bookableday(rowIndex)(strName) = 6
Else
  Bookableday(rowIndex)(strName) = 5
End If


text:
Q: To trigger every time with .click()? I tried to have a .click() on a  to find out it wont trigger every time I click, what it suppose to do is open a dialog.
That is not the only problem I would need to pass a value to my jquery to. I just cant figure this one out.
I need it to be a  because it's gone be in a dropdown menu. Do you got any suggestions?
EDIT
this is the code I use and it workes
$(document).ready(function() {
        $('#dialog').dialog({ autoOpen: false, bgiframe: true, modal: true, height: 600, width: 1000, Close: function() { $(this).dialog('destroy'); } });

        $('a').live('click', function(evt) {
            evt.preventDefault();
            var ids = $(this).attr('id');
            var first = "<iframe style='width: 100%; height: 100%;' src='" + "" + "''";
            $('.iframe').html(ids);

            $('#dialog').dialog('open');
        });
    });

This code intilise the dialog, open on every click and it work every time, trick for me here was the 'destroy' at the end and the inilise

A: This will trigger on every click. Whilst I doubt this will be the case, check you haven't got any other event handlers listening on the 'a', that are applying event.stopImmediatePropagation(). Try adding a return false to the end of the click handler, or even better:
$('a').click(function(evt) {
        var first = "<iframe style='width: 100%; height: 100%;' src='" + need to put value here + "''";
        $('.iframe').html(first);
        $('#dialog').dialog({ bgiframe: true, modal: true, height: 600, width: 1000 });

        evt.preventDefault();
    });

You might find that the page is reloading if you're not preventing the default action of the anchor tag, which would give the impression nothing is happening.
What sort of "value" are you thinking of? You can use jQuery's data() to store information, and of course you have access to all global variables in that scope.
EDIT:
To answer your comment, you can retrieve the ID of the a inside the click event as follows:
var theIdOfTheA = $(this).attr('id');

Note that this must be placed inside the handler.
EDIT2:
$('a').live('click', function(evt) {
        var first = "<iframe style='width: 100%; height: 100%;' src='" + $(this).attr('id') + "''";
        $('.iframe').html(first);
        $('#dialog').dialog({ bgiframe: true, modal: true, height: 600, width: 1000 });

        evt.preventDefault();
    });

A: DEMO: http://jsbin.com/olalu/edit
make sure you close the dialog before open it again!
click

EDITED
$('a').click(function(evt) {
    evt.preventDefault();

    var theIdOfTheA = this.id;

    var first = "<iframe style='width: 100%; height: 100%;' src='" +
                "http://www.sf.se" + "''";
      $('.iframe').html(theIdOfTheA);
       $('#dialog').dialog({
       bgiframe: true,
       modal: true,
       height: 600,
       width: 1000,
       //this
       Close: function() { $(this).dialog('close'); },
       //OR this OR both
       Cancel: function() { $(this).dialog('close'); }
    });
 });

A: You can pass data into an event handler by doing the following (from jQuery docs):
$('#foo').bind('custom', function(event, param1, param2) {
  alert(param1 + "\n" + param2);
});
$('#foo').trigger('custom', ['Custom', 'Event']);

So you could do this:
$(document).ready(function() {
    $('a').bind("click", function(event, myValue) {
        var first = "<iframe style='width: 100%; height: 100%;' src='" + myValue + "''";
        $('.iframe').html(first);
        $('#dialog').dialog({ bgiframe: true, modal: true, height: 600, width: 1000 });
    });
});

Note that you are now using bind() to bind the event handler, and the function is receiving a value (name it whatever you want). To show google in the iframe:
$('a').trigger('click', ['http://www.google.com']);


text:
Q: Google Maps Marker As a Link I've been trying to get this to work for hours :-(
It's actually a posted solution to an older question here Google Maps Marker as a link
This is what I've put together but it won't work http://jsfiddle.net/9GrcW/

A: Looks like it works if you change this[i].url to this.url:
for ( i = 0; i < markers.length; i++ ) {
  google.maps.event.addListener(markers[i], 'click', function() {
    window.location.href = this.url;
  });
}


text:
Q: Failed to process impala request after drop and create partition OS: centos 7.4.1708
   Python: 3.6
   impyla==0.14.0
   thriftpy==0.3.9
I have one use case:

*

*Create Table

*Add partition

*Insert values

*Drop partition (to remove old date)

*Create partition

*Insert values

on the step 6 I got error thriftpy.transport.TTransportException: TTransportException(type=4, message='TSocket read 0 bytes')
Test:
class TestExecution:
SQL_LIST = [
    "create schema if not exists test",

    "drop table if exists test.test_table",
    """
    create table test.test_table(
        id                 string not null,
        tran_time          bigint not null,
        primary key (tran_time, id)
    )
    partition by range(tran_time) (partition 0 <= values <= 1262304000) -- till 2010-01-01
    stored as kudu
    """
]
INSERT = "insert into test.test_table (id, tran_time) values('1', 1577836800)"

DROP = "alter table test.test_table drop if exists range partition 1577836800 <= values < 1577923200"
ADD = "alter table test.test_table add if not exists range partition 1577836800 <= values < 1577923200"

@classmethod
def setup_class(cls):
    sql_runner.execute_sql_list(cls.SQL_LIST)

def test_remove_old_data(self):

    sql_runner.execute_sql(self.ADD)
    sql_runner.execute_sql(self.INSERT)

    sql_runner.execute_sql(self.DROP)
    sql_runner.execute_sql(self.ADD)

    sql_runner.execute_sql(self.INSERT)

Traceback:
    hiveserver2.py             946 ERROR    Failed to open transport (tries_left=3)
Traceback (most recent call last):
  File "/usr/lib/python3.6/site-packages/impala/hiveserver2.py", line 940, in _execute
    return func(request)
  File "/usr/lib64/python3.6/site-packages/thriftpy/thrift.py", line 198, in _req
    return self._recv(_api)
  File "/usr/lib64/python3.6/site-packages/thriftpy/thrift.py", line 210, in _recv
    fname, mtype, rseqid = self._iprot.read_message_begin()
  File "/usr/lib64/python3.6/site-packages/thriftpy/protocol/binary.py", line 372, in read_message_begin
    self.trans, strict=self.strict_read)
  File "/usr/lib64/python3.6/site-packages/thriftpy/protocol/binary.py", line 164, in read_message_begin
    sz = unpack_i32(inbuf.read(4))
  File "/usr/lib64/python3.6/site-packages/thriftpy/transport/__init__.py", line 32, in read
    return readall(self._read, sz)
  File "/usr/lib64/python3.6/site-packages/thriftpy/transport/__init__.py", line 14, in readall
    chunk = read_fn(sz - have)
  File "/usr/lib64/python3.6/site-packages/thriftpy/transport/buffered/__init__.py", line 39, in _read
    self._rbuf = BytesIO(self._trans.read(max(sz, self._buf_size)))
  File "/usr/lib64/python3.6/site-packages/thriftpy/transport/socket.py", line 125, in read
    message='TSocket read 0 bytes')
thriftpy.transport.TTransportException: TTransportException(type=4, message='TSocket read 0 bytes')

Do you have any idea why it fails?


text:
Q: Background Image Cycle - z index with smooth fade or transition I realise there are some similar questions but please hear me out. I'm asking because the other answers haven't quite got me to a solution.
Here is my fiddle: https://jsfiddle.net/k6z22kns/
I can get the images to cycle but I'm really struggling trying to make them fadeIn or just smoothly transition. Right now it just jumps from one image to the next as you can see in the fiddle. I've tried animate with a callback to fadeIn, amoungst other things but I just can't get it right. This has been killing me all morning.
var imageIndex = 0;
var imagesArray = ["https://www.gstatic.com/webp/gallery/1.sm.jpg","https://www.gstatic.com/webp/gallery/2.sm.jpg","https://www.gstatic.com/webp/gallery/3.sm.jpg","https://www.gstatic.com/webp/gallery/5.sm.jpg"];

function changeBackground(){
  var index = imageIndex++ % imagesArray.length;
  $(".bsh-images").eq(index).css({"z-index":"-997"});
  $(".bsh-images").eq(index-1).css({"z-index":"-998"});

}

$(document).ready(function() {
  setInterval(changeBackground, 5000);
});

A: You can simply create an animation effect by using transitions/animations.In this example i have initially Set the opcaity of image to zero and then change the opacity of displaying image  to 1.and added transition for the image in css.
Or you can find so many plugins for the creating these types of image sliders

var imageIndex = 0;
var imagesArray = ["https://www.gstatic.com/webp/gallery/1.sm.jpg", "https://www.gstatic.com/webp/gallery/2.sm.jpg", "https://www.gstatic.com/webp/gallery/3.sm.jpg", "https://www.gstatic.com/webp/gallery/5.sm.jpg"];

function changeBackground() {
  var index = imageIndex++ % imagesArray.length;

  $(".bsh-images").eq(index).css({
    "z-index": "-997"
  }).addClass('show');
  $(".bsh-images").eq(index - 1).css({
    "z-index": "-998"
  }).removeClass('show');

}

$(document).ready(function() {
  setInterval(changeBackground, 3000);
});
.bsh-images {
  height: 100%;
  width: 100%;
  position: absolute;
  top: 0px;
  z-index: -998;
  display: block;
  opacity: 0;
  -webkit-transition: opacity 2s ease-in;
  -moz-transition: opacity 2s ease-in;
  -ms-transition: opacity 2s ease-in;
  -o-transition: opacity 2s ease-in;
  transition: opacity 2s ease-in;
}

.bsh-images.show {
  opacity: 1;
}


text:
Q: How to implement multi threading in Angular? https://www.npmjs.com/package/threads
It seems to me we can use this package in Angular for running threads.
But I feel difficulties on implementing this.
Is there anyway to use threading in Angular?
How can I use thread in Angular?

A: Angular does not have "threads", which by the way can mean many different things, in different contexts, environments, platforms, CPUs, and operating systems. Threads can be a way to accomplish parallelism; or they can be a way to organize your code as a set of concurrent processes; or they can be a way to manage access to shared resources; or any or all of the above.
Angular works in a browser. Browsers run JavaScript. The closest thing we have to threads in our browser world is web workers. To greatly oversimplify, web workers are not light-weight threads; in other words, you wouldn't want to create 100,000 of them. But if you are looking for a simple way to offload some computation away from the main browser task, so that it does not lock up the browser while you are computing, then you are probably interested in web workers.
Web workers do not really need any special library, or wrapping, or scaffolding. They're easy enough to just write directly. However, if you're interested in some ways to facilitate the process of using web workers within an Angular context, then google for "angular web workers".
I have no special knowledge of the library you mention. At first glance, it appears to be a way to abstract concurrent algorithms over different threading implementations appropriate for the node.js platform vs. the browser. If you're planning on working in Angular, then most likely the node.js platform part is irrelevant, so this entire library is not anything you should be interested in.


text:
Q: Difference between page_load and onLoad What is difference between page_load and onLoad functions in ASP.NET codebehind?

A: Load is the event and OnLoad is a method that raises that event when called
it's just base class implementation that does it of course, and therefore
needs to be called from deriving classes so that events work)

A: You should probably read the Page Lifecycle Overview for more info.
This little bit should help clear up the difference:

Note that when an event handler is
  created using the Page_event syntax,
  the base implementation is implicitly
  called and therefore you do not need
  to call it in your method. For
  example, the base page class's OnLoad
  method is always called, whether you
  create a Page_Load method or not.
  However, if you override the page
  OnLoad method with the override
  keyword (Overrides in Visual Basic),
  you must explicitly call the base
  method. For example, if you override
  the OnLoad method on the page, you
  must call base.Load (MyBase.Load in
  Visual Basic) in order for the base
  implementation to be run.

and

Pages also support automatic event
  wire-up, meaning that ASP.NET looks
  for methods with particular names and
  automatically runs those methods when
  certain events are raised. If the
  AutoEventWireup attribute of the @
  Page directive is set to true, page
  events are automatically bound to
  methods that use the naming convention
  of Page_event, such as Page_Load and
  Page_Init.

The OnLoad is part of the page and is always called.  You don't need to have a Page_Load method which is just optional extension of the event.

A: They handle the same event but Page_Load() works only when AutoEventWireup="true".

A: OnLoad fires the Load event, which Page_Load is a default event handler.


text:
Q: What is the best practice for having several AWS Lambdas consuming an external(EC2) Postgres I've +100 endpoints at AWS API each one calling a specific Lambda script, that connects to a external Postgres DB, that fetch the data and return it.
My question is, if I do that, 100 Lambdas scripts, will need to have in each one the connections details as environment variables?
That is probably not the way to do it... what is the best way to manage this in a single place, like Global Environment Variables that can be accessed to all the lambdas?
another thing is, every Lambda open a connection is very bad too, is there a way to manage a connection pool, that can be shared between other lambdas?
Is there anyway to group them?
Thanks!

A: The recommended way of storing secret configuration for access by AWS services like Lambda functions is Secrets Manager.  You store the connection details as a secret, and in each Lambda function code you load the value from the Secrets Manager service as and when you require it.
Lambda functions are deliberately isolated, and so there is no way to share connections or other resources between different functions.  You can sometimes share resources between successive invocations of the same function, but you can't rely on this and for something like a database connection it's not even a good usecase.  Instead, you should be trying to open and close the connection as compactly as possible, so that other function invocations can have access to the databases's connection pool.


text:
Q: cURL not sending content-length I'm trying to get an O-Auth token from the Spotify API but when using cURL on Debian 8 I always get the error message POST requests require a Content-length header. while it works on my MacBook.
$authString = $spotifyId . ":" . $spotifySecret;
$encodedAuthString = base64_encode($authString);

$spotifyHeaders = array(
    "Authorization: Basic " . $encodedAuthString,
    "Content-Type: application/x-www-form-urlencoded",
);

$spotifyOauthCurl = curl_init();
curl_setopt($spotifyOauthCurl, CURLOPT_URL, "https://accounts.spotify.com/api/token");
curl_setopt($spotifyOauthCurl, CURLOPT_POST, true);
curl_setopt($spotifyOauthCurl, CURLOPT_HTTPHEADER, $spotifyHeaders);
curl_setopt($spotifyOauthCurl, POSTFIELDS, "grant_type=client_credentials");
curl_setopt($spotifyOauthCurl, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($spotifyOauthCurl, CURLINFO_HEADER_OUT, true);
$result = curl_exec($spotifyOauthCurl);
echo curl_getinfo($spotifyOauthCurl, CURLINFO_HEADER_OUT);

Adding CURLOPT_VERBOSE as suggested by @hanshenrik returned the following output
Trying 35.186.224.25...
* TCP_NODELAY set
* Connected to accounts.spotify.com (35.186.224.25) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use http/1.1
* Server certificate:
*  subject: C=SE; L=Stockholm; O=Spotify AB; CN=*.spotify.com
*  start date: May  3 00:00:00 2021 GMT
*  expire date: May  3 23:59:59 2022 GMT
*  subjectAltName: host "accounts.spotify.com" matched certs "*.spotify.com"
*  issuer: C=US; O=DigiCert Inc; CN=DigiCert TLS RSA SHA256 2020 CA1
*  SSL certificate verify ok.
> POST /api/token HTTP/1.1

/api/token?grant_type=client_credentials HTTP/1.1
Host: accounts.spotify.com
Accept: */ *
Authorization: Basic ...
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

* HTTP 1.0, assume close after body
< HTTP/1.0 411 Length Required
< Content-Type: text/html; charset=UTF-8
< Referrer-Policy: no-referrer
< Content-Length: 1564
< Date: Wed, 26 Jan 2022 17:36:23 GMT
<
* Curl_http_done: called premature == 0
* Closing connection 0

A: 1: you're ignoring the error log, every time you run
curl_setopt($spotifyOauthCurl, POSTFIELDS, "grant_type: client_credentials");

your errorlog gets a message like
Warning: Use of undefined constant POSTFIELDS - assumed 'POSTFIELDS' (this will throw an Error in a future version of PHP) in /in/S9fsj on line 3
string(10) "POSTFIELDS"

Also you're running php 5/7, because in PHP8 this will throw an exception: https://3v4l.org/S9fsj
2: you're ignoring curl_setopt return errors, curl_setopt returns false on errors, which your code is ignoring. an easy way around that would be
function ecurl_setopt ( /*resource*/$ch , int $option , /*mixed*/ $value ){
    $ret=curl_setopt($ch,$option,$value);
    if($ret!==true){
        //option should be obvious by stack trace
        throw new RuntimeException ( 'curl_setopt() failed. curl_errno: ' .  curl_errno ($ch) .'. curl_error: '.curl_error($ch) );
    }
}

3: it's all caused by a typo! it's supposed to be CURLOPT_POSTFIELDS not just POSTFIELDS


text:
Q: python reference to a float, int, etc As I understand it, there are no references in python to ints or floats or similar data.  Nevertheless, I am working on a problem where it would be very convenient for me if I could do something like
a=1
b=2
c=3
ref_dict={'field1':ref_to_var_a,'field2':ref_to_var_b,'field3':ref_to_var_c}

and then
def update(field,value):
   ref_dict[field]=value

And so if the user called
update('field2',5)

the value of b would become 5.
Is there any way this can be done?  Thanks.
In response to arbanert's helpful comment and answer, what I really want to do is -- surprise, surprise -- more complicated.  I am building a GUI with wxPython.  I have many TextCtrl controls, each of which will set the value of one variable.  Of course, I could write one method for each control, or I could write a single method, which would look something like
def handleTextEvent(self,event):
    if (event.GetEventObject() == widget1):
       a=int(event.GetString)
    elif (event.GetEventObject() == widget2):
       b= ....

I think you can see why I don't like this either.  It would be nice if I could just do one short function like:
def handleTextEvent(self,event):
    ref_dict[event.GetEventObject()]=int(event.GetString())

And, yes, I am very new with wxPython.
Thanks!

A: This is possible, but it's almost always a bad idea.
Assuming a, b, and c are globals:
ref_dict = {'field1': 'a', 'field2': 'b', 'field3': 'c'}
def update(field, value):
    globals()[ref_dict[field]] = value

If you really want to, you can even create "reference wrappers":
class GlobalReference(object):
    def __init__(self, name):
        self.name = name
    def get(self):
        return globals()[self.name]
    def set(self, value):
        globals()[self.name] = value

ref_dict = {'field1': GlobalReference('a'), 'field2': GlobalReference('b')}
def update(field, value):
    ref_dict[field].set(value)

And if you want to wrap things that aren't in globals, like globals from another module, class attributes, instance attributes, etc.? Create more reference wrapper types:
class NamespaceReference(object):
    def __init__(self, namespace, name):
        self.namespace, self.name = namespace, name
    def get(self):
        return getattr(self.namespace, self.name)
    def set(self, value):
        setattr(self.namespace, self.name, value)

ref_dict = {'field1': GlobalReference('a'), 'field2': NamespaceReference('myobj', 'b')}

Or you can forgo the classes and just store setter functions…

So, if this is a bad idea, what's the right answer?
Without knowing what you're trying to do, it's hard to say, but here are some possibilities:

*

*Use a single dict variable full of values instead of a bunch of separate variables.

*Make the variables instance attributes of a class, and pass an instance of that class around.

*Use a mutable float-holder object instead of a plain float instance.

For your specific case, I think what you want is the second one. This is standard model-view-controller design. Or, if you don't like MVC, model-template-view or some other variant (you don't really need a controller here).
Your model is a bunch of scattered globals, which is why it's hard to hook it up to the view. The simplest answer is to represent the model as an object. Then give the view (or its controller) a reference to this model, which is trivial, and you're done.


text:
Q: How to use Google Apps Script's LockService, with Sheets API i'm actually using google sheet api in automation to write cells etc.. It is working fine but issue is when we use concurrent run. When we write exactly at the same time, which can happen, both run try to write in the same cell and then there is a blank line and we lose one run.
I found out this LockService but it is in Google Apps Script, can we call that with Google Sheets API in Java code ?
Thank you


text:
Q: discord oauth2 access token api php returns "invalid user" my project wants to authorize a user through Discord Api, user logs in to my project then redirected to discord authorization page that authorization renders a code and after that I need to get access token from code through token uri mention in Discord Developer Source, my code to access token is this:
$authorization = base64_encode("OAUTH2_CLIENT_ID:OAUTH2_CLIENT_SECRET");
$header = array("Authorization: Basic {$authorization}", "Content-Type: application/x-www-form-urlencoded");
$content = "grant_type=authorization_code&code=$authorization_code&redirect_uri=$redirectURI";

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => $tokenURL,
    CURLOPT_HTTPHEADER => $header,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $content
));
$response = curl_exec($curl);
curl_close($curl);

it returns
{"error": "invalid_client"}

i checked same error was posted in here, which suggests to put application/x-www-form-urlencoded in header, my function is already doing it, I am using Discord for first time.
Any help would be appreciated.


text:
Q: Plotting a 3D graph in Latex I am trying to change the 2D scatter graph into 3D which can also take the value of the P column as z-axis. But the output I got is not smooth and I really don't understand how I can change it into 3D graph which shows the regions where cost DR, BR or SC is optimal for (P:Q:R) coordinates. Can any expert please help me draw a nice 3D graph of the given data? In the code, I am using a minimum dataset for illustration purpose although the actual file is so big with many data points. Here is the code:
\documentclass[border=5mm]{standalone}
\usepackage{pgfplotstable}
\pgfplotsset{compat=1.16}

\pgfplotstableread[col sep=comma]{
P, Q, R, cost
6, 3, 1, SC
6, 2, 2, SC
6, 1, 3, SC
5, 4, 1, DR
5, 3, 2, BR
5, 2, 3, DR
5, 1, 4, DR
4, 5, 1, DR
4, 4, 2, BR
4, 3, 3, BR
}\MyData

\begin{document}
    \begin{tikzpicture}
    % define a few macros for convenience
    \newcommand\AxisW{10cm} % width/height of axis
    \newcommand\AxisXMin{0.5} % xmin/ymin
    \newcommand\AxisRange{10} % range of axis, x y and z
    \begin{axis}[
    % define how the different cases are drawn
    % all should have same mark and draw opacity,
    % but change the color as you prefer
    scatter/classes={
        SC={mark=square*, draw opacity=0, fill=blue},
        DR={mark=square*, draw opacity=0, fill=red},
        BR={mark=square*, draw opacity=0, fill=green}
    },
% add labels for the axes
xlabel=R,
ylabel=Q,
zlabel=P,
% set up the size of the axis
scale only axis, % width/height applies to axis box alone, without labels
width=\AxisW, height=\AxisW,
% set up the range of the axes
xmin=\AxisXMin, xmax=\AxisXMin+\AxisRange,
ymin=\AxisXMin, ymax=\AxisXMin+\AxisRange,
zmin=\AxisXMin, zmax=\AxisXMin+\AxisRange,
% calculate the mark size - divide by 2 because the size is half the width
mark size={\AxisW/\AxisRange/2},
% set legend entries in one row
legend columns=-1,
% move legend outside top of axis
legend style={at={(0.5,1.02)}, anchor=south},
% have ticks every 1 unit distance
xtick distance=1,ytick distance=1,ztick distance=1,
]

\addplot3 [
scatter, % make a scatter plot
only marks,
scatter src=explicit symbolic
]
table[x=R, % use R-column for x-values
y=Q, use Q-column for y-values
z=P, % use P-column for z-values
meta=cost % use cost-column to define which scatter class should be used
] \MyData;

\legend{SC, DR, BR}
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Not Found status:404 const express = require("express"),
    http = require("http"),
    bodyParser = require("body-parser"),
    cookieParser = require('cookie-parser'),
    session = require('express-session'),
    morgan = require('morgan'),
    methodOverride = require('method-override'),
    compression = require('compression');

const app = express();
// compress responses
app.use(compression());

process.on('uncaughtException', function(exception) {
    console.log(exception);
});

const config = require("./app/config.js")();
const logger = require("./app/server/modules/logger");

//app Config.
app.use(methodOverride());
app.set('env', 'dev');
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
    extended: true
}));

//cross domain
app.use(function(req, res, next) {
    if (req.method === 'OPTIONS') {
        var headers = {};
        headers["Access-Control-Allow-Origin"] = "*";
        headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
        headers["Access-Control-Allow-Credentials"] = false;
        headers["Access-Control-Max-Age"] = '86400'; // 24 hours
        headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
        res.writeHead(200, headers);
        res.end();
    }
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
    res.header["Access-Control-Allow-Credentials"] = false;
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,X-HTTP-Method-Override, Content-Type, Accept");
    next();
});

app.use(cookieParser());
app.use(session({ secret: 'xxxxxxxxxxx' }));
// app.use(cookieParser('optional secret string'));
// app.use(session({secret: 'xxxxxxxxxxx'}));
app.locals.pretty = true;

//Folder config.
/*app.use(express.static(__dirname + '/app/user/'));*/
app.use('/', express.static(__dirname + '/app/user/'));
app.use('/admin', express.static(__dirname + '/app/admin/'));

require('./app/server/router')(app); //route file

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    const err = new Error('Not Found');
    err.status = 404;
    next(err);
});

if (app.get('env') === 'dev') {

    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.json({
            message: err.message,
            error: err
        });
    });

}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error.html', {
        message: err.message,
        error: {}
    });
});

http.createServer(app).listen(config.port, function(err) {
    if (err) console.log(err);
    logger.info("server listening on port " + config.port + " in " +
        config.mode + " mode");
});

this is my http link http://localhost:9989/ later it will redirected to http://localhost:9989/login for the first time it works fine , when i refresh http://localhost:9989/login its says {"message":"Not Found","error":{"status":404}}, why its happening ? is there any solution for this ? or did i any mistake ? please guide me here!!


text:
Q: How to get my file from a form and insert it into a folder in my project? i am creating a paltform, and there is a page "insertPage.php" containing a form, where the 'teacher' can upload his course and students can see it ..
my form worked perfectly when i used only $_POST to get my data but when i used $_FILES it didnt work ..
here is my html code :
<form method="post" action="insertion.php">

   <input name="file" type="file"><br>

</form>

And here is my insertion.php Page :
$file = "photo-".$_FILES["file"]["name"];

if(isset($_POST["titre"]) && isset($_FILES["file"]["name"]) && isset($_POST["niveau"]) && isset($_POST["filliere"]) && isset($_POST["format"]) && isset($_POST["matiere"]) && isset($_POST["type"])){

copy($_FILES["tmp_name"]["file"],"C:/Users/user/Desktop/Platforme/Files/".$file);

$req = "insert into courses(nomCourse,type,format,file,matiere,module) VALUES (?,?,?,?,?,?)";

$data = array($titre,$type_text,$format_text,$file,$matiere,$module);

$gdb->insertIntoBD($req,$data);

}

i get nothing in my database, That's why i need some help, Thank you guys ..


text:
Q: jQuery DOM manipulation of table lost after submit Based on a TextBox "autocomplete" functionality the user can select amongst a list of results, the user would then select one of theese results and add it to a "basket", the user performs multiple rapid searches and adds or removes items from this basket.
At the moment i've used a table as the "Basket". once the user is satisfied with the basket, the user submits the basket to the server and the server loops trough the basket and updates the database.
I'm trying to manipulate a table with jQuery, the problem is that once the postback happens, the DOM manipulations are removed.
The table looks like the following.
 <asp:Table ID="Basket"
 runat="server"
 EnableViewState="False">
     <asp:TableHeaderRow TableSection="TableHeader">
         <asp:TableHeaderCell>ID</asp:TableHeaderCell>
         <asp:TableHeaderCell>Name</asp:TableHeaderCell>
         <asp:TableHeaderCell>Quantity</asp:TableHeaderCell>
     </asp:TableHeaderRow> </asp:Table>

with jQuery i can modify the table, add rows, delete them and all is fine and dandy. I then have a submit button
<asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" />
in the Click event of the button i loop through the rows of my table
foreach (TableRow row in this.Basket.Rows)
{
            if (row.TableSection != TableRowSection.TableBody) { continue; }
}

This is where the problem is, the Table is reset to the initial state only containing 1 row. Considering i've disabled the ViewState, I would think the control would mimic what is posted back. But clearly something makes it reset.

A: You are thinking about this all wrong, Javascript is front end and without you telling the server that rows have been added, it will never know and thus it only adds one row as you tell it to do.
You will need to save the values somehow


text:
Q: .Net MVC / Web API Attribute Routing triggers Download Having added WebApi to an MVC 5 project (.aspx AND Razor engines) I am trying to add Attribute Routing however whenever I add this line:
// Web API routes
config.MapHttpAttributeRoutes();

to the WebApiConfig file it produces the bizarre behaviour that the initial page load (MVC route of account/login) results in the browser treating the request as a download and the browser opens the download dialog box!
To me this would typically be the result of a bad file extension but in this environment there is clearly something wrong with the routing but for the life of me I can't figure out what I'm missing.
Without the MapHttpAttributeRoutes line an Ajax call to the WebApi controller's "Post" action  does work.
I'll mention that the Ajax call is via Angular however there is no angular functionality embedded in the pages related to the /Account/Login routing
I am posting the related controllers and App_Start/Config files and Web.Config files below.
Any idea would be greatly appreciated, I'm hoping to avoid having to recreate the project from scratch :-(
Thanks!
My Api Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web;
using System.Data;
using System.Data.Entity;
using System.Web.Http.Filters;
using mvc4.SecretService.com.Models;

namespace mvc4.SecretService.com.Controllers
{
     [RoutePrefix("api/santas")]
     public class SantasController : ApiController
     {

           private SeniorsSecretServiceEntities db = new SeniorsSecretServiceEntities();

    [HttpGet]
    [Route("list")]
    public IEnumerable<sssSantaProfile> List()
    {
        var profiles = db.sssSantaProfiles.AsEnumerable();
        return profiles;

    }
    ......
 }

WebApiConfig file :
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        // THIS CAUSES THE ISSUE
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        //config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        //config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
    }
}

The RouteConfig file looks like this :
 public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

And the MVC Account Controller looks like this :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using mvc4.SecretService.com.Filters;
using mvc4.SecretService.com.Models;

namespace mvc4.SecretService.com.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class AccountController : Controller
    {

        public AccountController()
            : base()
        {
            ViewBag.Message = "Seniors Secret Service";

         }

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.Action= "Log In";
            ViewBag.ReturnUrl = returnUrl;
            return View();
         }

         [HttpPost]
         [AllowAnonymous]
         [ValidateAntiForgeryToken]
         public ActionResult Login(LoginModel model, string returnUrl)
         {
               if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
              {
                  return RedirectToLocal(returnUrl);
              }

              // If we got this far, something failed, redisplay form
              ModelState.AddModelError("", "The user name or password provided is incorrect.");
              return View(model);
        }
        .....
    }

ROOT Web.Config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>

        <sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core">

     </sectionGroup>
</configSections>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="true" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.1">
  <assemblies>
    <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <add assembly="WebMatrix.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    <add assembly="WebMatrix.WebData, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  </assemblies>
</compilation>
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<pages>
  <namespaces>
    <add namespace="System.Web.Helpers" />
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization" />
    <add namespace="System.Web.Routing" />
    <add namespace="System.Web.WebPages" />
  </namespaces>
</pages>
<roleManager enabled="true" defaultProvider="simple">
  <providers>
    <clear />
    <add name="simple" type="WebMatrix.WebData.SimpleRoleProvider,WebMatrix.WebData" />
  </providers>
</roleManager>
<membership defaultProvider="simple">
  <providers>
    <clear />
    <add name="simple" type="WebMatrix.WebData.SimpleMembershipProvider,WebMatrix.WebData" requiresQuestionAndAnswer="false" />
  </providers>
</membership>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" />
    <bindingRedirect oldVersion="0.0.0.0-4.3.0.0" newVersion="4.3.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" />
    <bindingRedirect oldVersion="0.0.0.0-4.3.0.0" newVersion="4.3.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="itextsharp" publicKeyToken="8354ae6d2174ddca" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.5.6.0" newVersion="5.5.6.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Data.OData" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.6.4.0" newVersion="5.6.4.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Data.Edm" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.6.4.0" newVersion="5.6.4.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Spatial" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.6.4.0" newVersion="5.6.4.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="WebMatrix.Data" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="WebMatrix.WebData" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
  </dependentAssembly>
</assemblyBinding>
<legacyHMACWarning enabled="0" />
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<dotNetOpenAuth>
<openid>
  <relyingParty>
    <security requireSsl="false">
    </security>
    <behaviors>
      <add type="DotNetOpenAuth.OpenId.RelyingParty.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth.OpenId.RelyingParty" />
    </behaviors>
  </relyingParty>
</openid>
<messaging>
  <untrustedWebRequest>
    <whitelistHosts>
    </whitelistHosts>
  </untrustedWebRequest>
</messaging>
<reporting enabled="true" />
</dotNetOpenAuth>
<uri>
<idn enabled="All" />
<iriParsing enabled="true" />
</uri>
<system.net>
<defaultProxy enabled="true" />
<settings>
</settings>
</system.net>
</configuration>

/Views Web.Config
<?xml version="1.0"?>
<configuration>
<configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

    </sectionGroup>
</configSections>

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
        <namespaces>
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Optimization"/>
            <add namespace="System.Web.Routing" />
        </namespaces>
    </pages>
</system.web.webPages.razor>

<appSettings>
    <add key="webpages:Enabled" value="false" />
</appSettings>

<system.web>
    <httpHandlers>
        <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
    </httpHandlers>

    <pages
        validateRequest="false"
        pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
        <controls>
            <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
        </controls>
    </pages>
</system.web>

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
        <remove name="Session" />
        <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
    </modules>
    <handlers>
        <remove name="BlockViewHandler"/>
        <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
</system.webServer>
</configuration>

A: I encountered the exact same behavior when I added the same line of code config.MapHttpAttributeRoutes(); to the WebApiConfig file in my MVC 5 project. The problem was resolved by making a change in the Global.asax file. As noted under the heading Enabling Attribute Routing in this article on adding attribute routing in ASP.NET you can check for the line:
WebApiConfig.Register(GlobalConfiguration.Configuration);

in Global.asax and replace it with:
GlobalConfiguration.Configure(WebApiConfig.Register);

Once I made this change in Global.asax my MVC 5 project ran properly without the bizarre display of the downloads dialog. As noted in the article I had migrated my MVC 5 project from a Web API 1 template. I started using Web API 2 in my project by adding the Web API 2 NuGet package.
Here is the text from the article:
Note: Migrating From Web API 1
Prior to Web API 2, the Web API project templates generated code like this:
protected void Application_Start()
{
    // WARNING - Not compatible with attribute routing.
    WebApiConfig.Register(GlobalConfiguration.Configuration);
}

If attribute routing is enabled, this code will throw an exception. If you upgrade an existing Web API project to use attribute routing, make sure to update this configuration code to the following:
protected void Application_Start()
{
    // Pass a delegate to the Configure method.
    GlobalConfiguration.Configure(WebApiConfig.Register);
}


text:
Q: In jinja2 on Google App Engine, how can I (easily) build a URL based on a route name with arguments? If I construct a jinja environment as follows:
jinja_environment = jinja2.Environment (
    loader=jinja2.FileSystemLoader ((os.path.dirname (__file__), 'templates')), extensions=[])
jinja_environment.globals['url_for'] = webapp2.uri_for

In my templates, I can build simple URLs from a route name when the route does not define any arguments:
{{ url_for('user_home') }}

However, when the route contains an argument as defined by a string such as /invoice/<:\d+>, I am unable to pass any arguments. Calling it in all the following ways fails, with a KeyError "Missing argument "0" to build URI.":
{{ url_for('invoice') }}
{{ url_for('invoice', args=['123']) }}
{{ url_for('invoice', kwargs={'__0__':'123'}) }}
{{ url_for('invoice',_request=None, args=['123'],kwargs={'__0__':'123'}) }}

Existing examples for this seem to be out of date--at least I haven't been able to make them work. What am I missing?

A: Route('/invoice/<invoice_id>/', handler=invoice_handler, invoice_id='something')
{{ url_for('invoice', invoice_id=123) }}
You can try the above, Jinja is expecting the named parameter you defined your handler.

A: I think just {{ url_for('invoice', 123) }} should work.


text:
Q: Variant of Workbook.Add(object) for EPPlus We're trying to step away from using Microsoft's Interop Excel dependency and switch over to EPPlus, however I'm running into an issue where I can't seem to find a replacement for Interop's Workbook.Add(object), instead in EPPlus it seems like you can only use a file as template and not an object:
https://msdn.microsoft.com/library/microsoft.office.interop.excel.workbooks.add.aspx

A: If it's OK to use an in-memory representation of an actual Excel file, you can load a stream. For example, I have stored an Excel template as an embedded resource in a DLL, then instantiate an ExcelPackage this way:
ExcelPackage LoadCalculationsPackage()
{
    Assembly assembly = typeof(ExcelService).GetTypeInfo().Assembly;
    using (Stream s = assembly.GetManifestResourceStream(EXCEL_TEMPLATE_RESOURCE))
    {
        return new ExcelPackage(new MemoryStream(), s);
    }
}

You could do this with a completely empty Excel file.


text:
Q: Algorithm for routing through space filled with polygons I have a (geographic) map built up of polygons depicting land and a boat trying to get from A to B without hitting any of the land. Preferably, it should follow the shortest available path.
I have an algorithm that works most of the time, but it is rather clumsy and inefficient. Any hints or references to algorithms that I could use are greatly appreciated.

A: Create a graph:

*

*Create one node for each vertex of each polygon, the start point and the end point.

*Create an edge between two nodes if there is a straight line going from one to the other, not passing through any obstacle.

Use an A* algorithm (http://en.wikipedia.org/wiki/A_star) to find the shortest path in the resulting graph. Estimate the distance as the straight line distance.
You can use any sort of obstacles, as long as you are able to determine the set of 'interesting' points: they are the contact points of all tangents for each pair of obstacles (nearly all vertices of a convex polygon are 'interesting'. ) and of all lines that touch the same (non-convex) obstacle twice.


text:
Q: How to find the bin number of the frequency of interest from an fft signal in python? I am doing a task which involves taking two signals from a phase doppler anemometry system and calculating the phase shift and the frequency which will further help in finding the velocity and diameter of the droplet. Before getting into the actual task, I am now taking two sine signals from a function generator and producing a phase shift and then calculating the phase and frequency via a program in python with FFT to verify if both are the same. In that process, I am now getting the frequency value same as what I have set in the function generator. So frequency problem is solved. I am currently stuck up in a state where I need to find the bin number where my frequency belongs and using that I can calculate the exact phase shift.
Also, I would like to know how to find the number of bins used in the FFT.
My signal is 40MHz, my sampling frequency is 125MHz.
Thank you!

A: It might be slightly overkilling but you can use numpy.where to find the index of a specific value in an array
>>> import numpy as np
>>> np.where(np.linspace(1,10,10)==4)
(array([3]),)


text:
Q: Why are a form's system buttons highlighted when calling WindowFromPoint in MouseMove event? Calling WindowFromPoint within the MouseMove event of a TWinControl causes a MouseOver event at the point passed to WindowFromPoint. Is this a VCL bug? Anybody know if there is a workaround?

Here's the demo code:
unit Unit7;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm7 = class(TForm)
    Button1: TButton;
    procedure Button1MouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form7: TForm7;

implementation

{$R *.dfm}

procedure TForm7.Button1MouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer);
begin
  WindowFromPoint(Point(Mouse.CursorPos.X, Mouse.CursorPos.Y - 40));
end;

end.

DFM:
object Form7: TForm7
  Left = 0
  Top = 0
  Caption = 'Form7'
  ClientHeight = 40
  ClientWidth = 116
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object Button1: TButton
    Left = 24
    Top = 7
    Width = 75
    Height = 25
    Caption = 'Button1'
    TabOrder = 0
    OnMouseMove = Button1MouseMove
  end
end

I'm using Delphi XE2 on Windows 7 Pro 64bit. I can also reproduce using Delphi 7.

A: I tested this with a simplest C++ application and observed the same behavior, this is not a VCL bug (as David mentioned in the comments). It's not related with mouse movements BTW, anytime you call WindowFromPoint passing a caption button's coordinates, the peculiarity occurs. And it occurs only on the windows that belong to the thread that makes the call to the function.
So, for a workaround, you can call WindowFromPoint from a thread. Simple example below, not really a background thread as the code waits for it to finish:
type
  TGetWndThread = class(TThread)
  private
    FPoint: TPoint;
  protected
    procedure Execute; override;
    constructor Create(AOwner: TComponent; Point: TPoint);
  end;

constructor TGetWndThread.Create(AOwner: TComponent; Point: TPoint);
begin
  FPoint := Point;
  inherited Create;
end;

procedure TGetWndThread.Execute;
begin
  ReturnValue := WindowFromPoint(FPoint);
end;

..

var
  Wnd: HWND;
  Thr: TGetWndThread;
begin
  Thr := TGetWndThread.Create(nil, Point(Mouse.CursorPos.X, Mouse.CursorPos.Y - 40));
  Wnd := Thr.WaitFor;
  Thr.Free;
  .. // use Wnd

It would make sense to test for the conditions which the bug is displayed (OS, themes..) and make the code conditional to avoid the overhead where unnecessary.


text:
Q: How to set up memory for Spark in a web application? I'm running spark in single node.
My application (java-web) is using less memory than available.. I found this thread as useful.
http://apache-spark-user-list.1001560.n3.nabble.com/Setting-spark-executor-memory-problem-td11429.html.
From the link

For local mode you only have one executor, and this executor is your
  driver, so you need to set the driver's memory instead. *That said, in
  local mode, by the time you run spark-submit, a JVM has already been
  launched with the default memory settings, so setting
  "spark.driver.memory" in your conf won't actually do anything for you.
  Instead, you need to run spark-submit as follows
bin/spark-submit --driver-memory 2g --class your.class.here app.jar

It suggests to use the memory-flag along with bin/spark-submit --for a jar file
But I'm running a maven-web applicaiton. Can I run this with spark-submit??
I set these in spark-env.sh  and run source spark-env.sh but still no change
SPARK_EXECUTOR_MEMORY=10g
SPARK_WORKER_MEMORY=10g

A: You can just config these parameters in Spark's configuration files(spark/conf/spark-defaults.sh). And by the way, this is a better way than configuration in spark-shell unless you want to change it every time.

A: Using spark-env.sh won't work in your setup since you're using a web application that uses its own runtime environment that in turn doesn't see the env vars. You can't use spark-submit either.
Given the comment about using local mode it means you need to tune in your JVM where the web app runs within and stop worrying about Spark. It will pick up the memory setting off the JVM since all services are running on the single JVM.


text:
Q: Zend plugin's preDispatch can't see roles I try to use ACL in plugin's preDispatch method and it can't see roles and resources.
in bootstrap:
protected function _initAutoLoad() {
...

$acl=new Application_Model_LibraryAcl();
$auth=Zend_Auth::getInstance();
$fc= Zend_Controller_Front::getInstance();
$fc->registerPlugin(new Application_Plugin_AccessCheck($acl, $auth));
...
}

in plugin's preDispatch:
$this->_acl = $acl;
$this->_auth=Zend_Auth::getInstance();
$identity = $this->_auth->getStorage()->read();
$role=$identity->role;
$resource = $request->getControllerName();
$action= $request->getActionName();
if($this->_acl->isAllowed($role, $resource, $action)){
...
}

And I get error 'role 'admin' not found' (this error is for all roles). No matter what I tried to do it doesn't work. I solve this problem by moving ACL code from Model to this plugin but I think it is not very good idea to keep ACL here. Other models and controllers can see ACL from Application_Model_LibraryAcl and it's roles and resources but plugin's preDispatch doesn't want to.
I use ZF 1.12.
EDIT. My Application_Model_LibraryAcl() is:
<?php
class Application_Model_LibraryAcl extends Zend_Acl {

    public function __construct(){

        //----------------------ADD ROLES HERE---------------------------------

        $acl = new Zend_Acl();
        $acl->addRole(new Zend_Acl_Role('guest'));
        $acl->addRole(new Zend_Acl_Role('user'), 'guest');
        $acl->addRole(new Zend_Acl_Role('admin'), 'user');

        //----------------------ADD RESOURCES HERE---------------------------------

        $acl->add(new Zend_Acl_Resource('authentication'));
        $acl->add(new Zend_Acl_Resource('index'));

        //----------------------ADD PERMITIONS HERE---------------------------------

        $acl->deny();

        $acl->allow('admin', NULL);
        $acl->allow('guest', 'authentication', array('login', 'registration', 'confirm', 'index' ));
        $acl->allow('guest', 'index', array('index' ));
        $acl->allow('user', 'index', array('index', 'confirm'));
        $acl->allow('user', 'authentication', array('logout' ));
        $acl->deny('user', 'authentication', array('login' ));

    }

}

I keep role of current user in Zend storage. This code works fine when I move all code from model to plugin without any changing. I have error on this string if I use model:
if($this->_acl->isAllowed($role, $resource, $action))

and no any errors when I use ACL as part of plugin.


text:
Q: Using tail to follow daily log file in Bash I have a task to use a bash script to monitor a couple of log files named with the current day, eg. YYYY-MM-DD.log.
(1) I used tail -f to follow the file but unable to deal file rotation.
Even if using tail -F $FILENAME, I can only follow the log for 24 hours max and need to restart again.
What I wish to accomplish is to have something like tail -F $CURRENTDATE, so I can leave it running forever and every midnight It will switch to follow the new log file named with current date.
But it seems the variable $CURRENTDATE is not dynamic. Is there another way to do this without crontab'ing the script every 24 hours? Maybe set a symbolic file or something?
(2) Meanwhile, if tail -f is used, what signal will it return if the file it follows is missing or changes its name? How can I trap the exceptions during execution.

A: The variable $CURRENTDATE isn't dynamic the way that you think. That variable gets expanded when the tail -F $CURRENTDATE command is evaluated to execute. You can see this if you run the ps command, AFTER it's executed. Notice in the output that it shows the value of current date rather than $CURRENTDATE.
$ CURRENTDATE=$(date +%Y%M%d.log)
$ tail -F $CURRENTDATE

$ ps -eaf|grep tail
saml      1171 13564  0 22:13 pts/4    00:00:00 tail -F 20130517.log

This issue you're encountering is typically why most server daemons such as Apache, Nginx, or Jetty log all the current date into a file named, error.log, and then this file is rotated to another name, such as error_20130517.log afterwards.
This allows you to monitor the error.log continuously using a command such as tail -F error.log.

A: This is exactly what you are looking for:
watch -n 60 'tail -n 30 /path/to/logfile-$(date +%Y-%m-%d.log)'

This refreshes the logfile for the current date every 60 seconds.
Customize the n parameters to your liking.
Note the single quotes: These make the watch command evaluate the command every time instead of evaluating it once and providing output. I ran into the same problem myself and this worked perfectly for me. I don't think the current answer of "Well the big players don't like to hack around so they use logrotate" is an adequate solution if you're trying to debug a program that logs this way instead of the other way.
This is the quick and dirty way, but If you're developing something, make like the big players and use logrotate.


text:
Q: Resursive string replacement with escaping in Python I made a simple script in Python to do some project generation based on sources directory structure. In it I used Formatter as it proved quite handy with the ability to use a dictionary (also nested!) for replacement strings.
Yet now, while extending the script, I need a more sophisticated replacement. Firstly I would like to have the replacement be recursive. A string substituted for a field might need formatting on its own (using same arguments). And secondly I need to be able to escape final string according to provided function (the only use case so far is re.escape to escape for regular expressions).
I looked for something build-in in Python but didn't found anything useful. Formatter (as provided) obviously doesn't meet those criteria.

My first try was to use a simple function like:

def expand_vars(string, vars):
    while True:
        expanded = string.format(**vars)
        if expanded == string:
            break
        string = expanded
    return string

It simply keeps calling format until nothing more changes in the string (which means all fields were substituted).
Yet it is not easy to embed here escaping. I need to escape only substituted values (not entire string) and only the final value (escaping on each call would result in multi-escaping some parts of the string).
Also another issue of this function is that it could unintentionally create fields that are not fields. When one of the fields ends as a string {a while another one ends as b} in next iteration we have unexpected field {ab}. (Well, it could be considered a feature but I did not perceive it that way in my case.)

Another approach was to subclass Formatter. I ended up with something like that:
class RecursiveEscapingFormatter(Formatter):
    def __init__(self, escape=None):
        Formatter.__init__(self)
        self.escape = escape

    def get_field(self, field_name, args, kwargs):
        obj, arg_used = super(RecursiveEscapingFormatter, self).get_field(field_name, args, kwargs)
        if self.escape is None:
            nonEscapingFormatter = self
        else:
            nonEscapingFormatter = copy.copy(self);
            nonEscapingFormatter.escape = None
        obj = nonEscapingFormatter.vformat(obj, args, kwargs)
        return obj, arg_used

    def convert_field(self, value, conversion):
        result = super(RecursiveEscapingFormatter, self).convert_field(value, conversion)
        if self.escape is not None:
            result = self.escape(result)
        return result

Now the issue is that I cannot assure proper call to check_unused_args. I don't see way to reasonably (=not requiring entire class overwrite) keep track of arguments used by the recursive call in get_field. I don't need that myself but making a proper class (a one that could be later on inherited from…) requires proper handling of check_unused_args. How to do that?

Or maybe is there a better approach to the issue (of recursive replacement with escaping)?

A: I had a similar problem and here's how i've solved it.
from string import Formatter

class RecursivelySubstitutedDictionary:
    def __init__(self, dictionary):
        self.formatter = Formatter()
        self.dictionary = dictionary
        self.substituting = set([])

    def __getitem__(self, key):
        if(key in self.substituting):
            raise ValueError("Cyclic reference. Key: %s." % key)
        self.substituting.add(key)
        unsubstitutedval = self.dictionary[key]
        substitutedval = self.formatter.vformat(unsubstitutedval,[],self)
        self.substituting.remove(key)
        return substitutedval

Example usage
regulardict = {
    'hi': 'hello {arg}',
    'arg': '{arg_1}{arg_2}',
    'arg_1': 'wo',
    'arg_2': 'rld',
}

print RecursivelySubstitutedDictionary(regulardict)['hi']
# prints hello world

cyclicdict = {
    'hi': 'hello {arg}',
    'arg': '{hi}',
}

print RecursivelySubstitutedDictionary(cyclicdict)['hi']
# raises ValueError: Cyclic reference. Key: hi.

You may also consider caching substituted vals and clearing the cache if __setitem__ is called. At least that's what i'm doing in my original code.


text:
Q: Css flex with equal I want a flex parent with equal width items plus margin, I used flex: 1 0 15% but the problem is I don't want two last items get full width of row. First row has six items, right? second row has two row (7 & 8) width full width, see snippet below:

ul {
  display: flex;
  flex-wrap: wrap;
  margin: 0;
  padding: 0;
}

ul li {
  flex: 1 0 15%;
  background: darkseagreen;
  margin: 5px;
  list-style: none;
}

body {
  margin: 0;
}

1

2

3

4

5

6

7

8

My goal is to get this result but with equal width, prefer flex:

ul {
  display: flex;
  flex-wrap: wrap;
  margin: 0;
  padding: 0;
}

ul li {
  background: darkseagreen;
  margin: 5px;
  list-style: none;
  width: 15%;
}

body {
  margin: 0;
}

1

2

3

4

5

6

7

8

A: The flex: 1 0 15%; here is the shorthand of flex-grow, flex-shrink and flex-basis.
If you want the last two item not being grow. Set flex-grow to 0. Or you can do this:
ul li {
  flex: 0 0 15%;
}

EDIT:
If you want to use up the whole container width, here is a suggestion.
ul li {
  flex: 0 0 calc((100% - 12 * 5px) / 6);
}


text:
Q: How to run Django units test with default and unmanaged database? I have a Django project with a default database used for storing things like user, orders etc.
We also have an unmanaged database. Now when you run Django test they try to make test databases, but since we have an unmanaged db we cannot do this. I cannot create migrations of this db since that will land 300 errors about clashing reverse accessor.
We use Docker and automatically spin up this unmanaged database and fill it with some mock data. This one is used for development and such. I would like the unit test to use this one for testing.
I tried things like creating migrations but since the reverse accessor issue this is not possible.
Is there a way to use the unmanaged database for unit testing? The test_default database which Django creates is fine, but I cannot create a test_unmanaged database.

A: We use a setup with managed and unmanaged tables in the same database, which might also work for your use case:
We have a script to generate the test database from two dumps: test_structure.sql an test_fixtures.sql. The former contains the structure of the database at a certain point in time, including all unmanaged tables. The latter contains any data you might need in the unmanaged tables during testing, and the contents of the django_migrations table. We dump test_fixtures.sql using a generated list of COPY (SELECT * FROM {table}) TO STDOUT; statements, for example: COPY (SELECT * FROM obs_00.django_migrations) TO STDOUT WITH NULL '--null--';.
The output from psql -c {copy_statement} is transformed to INSERT statements using a function like this:
def csv2sqlinsert(table_name, data):
    """
    Convert TSV output of  COPY (SELECT * FROM {table}) TO STDOUT
    to                     INSERT INTO {table} VALUES (), ()...();
    """

    def is_int(val):
        try:
            return "{}".format(int(val)) == val
        except ValueError:
            return False

    def column(data):
        if data == "--null--":
            return "null"
        elif is_int(data):
            return data
        else:
            return "'{}'".format(data.replace("'", "''"))  # escape quotes

    rows = [row.split("\t") for row in data.decode().split("\n") if len(row) > 1]

    if len(rows) == 0:
        return f"-- no data for {table_name}\n"

    data = ",\n".join("({})".format(",".join(column(col) for col in row)) for row in rows)

    ret = ""
    ret += f"-- {table_name} ({len(rows)} rows)\n"
    ret += f"INSERT INTO {table_name} VALUES\n{data};\n"

    return ret

In reality this function is more complicated, also simplifying our postgis geometries and truncating large text fields to save space.
creating the test db
Define the test db name in settings_test.py:
DATABASES["default"].update({
    "NAME": "django_test_db",
    "TEST": {"NAME": "django_test_db",},
})

With the two files above, (re)creating the test database looks like this:
dropdb django_test_db
createdb django_test_db
psql -d django_test_db -f test_structure.sql
psql -d django_test_db < test_fixtures.sql

We now have the state of the database at the moment of the dump. Because there might be new migrations, we let django migrate:
./manage.py migrate --settings=settings_test

Running the tests
Now we can run the tests using ./manage.py test --settings=settings_test. Because recreating the database every test run might take a considerable amount of time, adding --keepdb will save you a lot of time waiting for the test database restore procedure.
We've amended manage.py like this so we cannot forget:
#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "test":
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings_test")
        cmd = sys.argv + ["--keepdb"]
    else:
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
        cmd = sys.argv

    from django.core.management import execute_from_command_line
    execute_from_command_line(cmd)