Hibernate Infinispan Entity/Query caching

Question:
I've been banging my head against the wall for a few days with this issue.
We are trying to implement Hibernate's second-level cache, using Infinispan. The application is running on JBoss AS 6, and using JTA transactions.
On our persistence.xml we have:
<code>...
<!-- JTA configurations -->
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup" />
<property name="current_session_context_class" value="jta" />

<!-- Infinispan configurations -->
<property name="hibernate.cache.use_second_level_cache" value="true" />
<property name="hibernate.cache.use_query_cache" value="true" />

<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.infinispan.InfinispanRegionFactory"/>
<property name="hibernate.cache.infinispan.cachemanager" value="java:CacheManager/entity"/>
...
</code>
as defined here:
On our understanding this is the kind of cache that we need in order to do the following:
Use case one:
We have records on a Database which will hold reference data. This data won't be changed for long periods of time (we hope :) ).
We want to cache these records as they are likely to be queried a lot. And as users query this data there won't be a need to go to the DB, since it should be cached.
For this case, is the cache type query cache, or entity cache? Being the query always the same, my understanding it's query cache as que query is supposed to return always the same results.
My query:
<code>List<MyEntity> list = session.createCriteria(MyEntity.class)
        .add(Restrictions.eq("id", 1))
        .setCacheable(true)
        .list();
</code>
Use case two:
A user gets a specific record from the DB, and he might update it. We would like this entity (or list of entities) to be saved on the user's session (login session) cache so if he updated this entity on the client, we wouldn't need need to make a select before the update.
In this case, since we are saving specific entities, it's considered entity caching, right? If we want to store the
For that we're using:
<code>@Cacheable (true)
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
public class MyEntity implements Serializable
{
...
}
</code>
Am I making these assumptions correctly? If not, what is the approach here? I gues I'm making a big mess out of this.
Answer: The 2nd level (entity) cache is (making it simpler) a map base on the id as key.  So each time reference data is "referenced" in other entity, the entity manager first check if it is present in the cache before going to the DB.
The query cache is a cache of result (ids) entities of a query.  Then base on the ids it will retrieve the corresponding entity (preferably from the entity cache...), so you need the entity to be cached in the 2nd level cache to be useful.
For you first use case, reference data:  you should annotated the entity as cacheable and use read-only strategy.  The entity manager will put the reference data in the referencer entity when loaded, or use find(clazz,id) to get the reference data out of the 2nd level cache.
Case 2 is a bit more tricky.  There is no "session" scoped cache (you need to manage it your self via SFSB or any upper level session mechanism if you need to keep intermediary result bind to user session).  If you make the entity cachable it will be cached for every user on the server, the entity manager context has no direct link with a user.
If you want to prevent to make a select before updating, you should prevent the entity to reach unmanaged state (to prevent merge) via the extended persistence context.  If the entity can often been updated by several user, the cache may decrease performance as it will take more time to manage consistency than going to the DB will take.
If you get performance bottle neck there you should first look on the related entity fetch and propagation annotation, if they are too large you make request or/and updating too much data from and to the DB.
Comment: I'm still trying to assimilate all your answer. And I have another question. For my first use case, what will happen if I add another reference data object (record) to the DB (using the same application)? Will the cache know the result of the query was changed, and next time a select is made, will it go to the DB?
Comment: I don't know if it will put it in the cache when it persist it.  Probably it will make a select as there may be some data change due to triggers.  Any way it will make at maximum one select, and then put it in the cache.
Comment: You can find more details on this post: http://www.javalobby.org/java/forums/t48846.html
Answer: Cross posted to https://community.jboss.org/message/751275#751275 - see my answers there.


Holomorphicity of $(z^2-1)^{1/2}$

Question: In one workshop question I am asked to find a branch of $f(z) = (z^2-1)^{\frac{1}{2}}$ such that it's holomorphic on the exterior of the unit disk $|z|>1$. Hint for the question is to separate $z^2-1$ into $z^2(1-z^{-2})$ and take the logarithm only for the second term when computing the power, as $(z^2)^{\frac{1}{2}} = z$. Thus we can find a branch.
I am really reluctant to the solution. In theory $f(z) = \exp(\frac{1}{2}\log_\theta(z^2-1))$, for some $\theta$ which defines the branch cut. Thus, I need to find a $\theta$ such that the image of $z^2-1$ doesn't cross the cut, which is impossible.
Any help please :)?
Answer: First note that $f(z) = \sqrt{z^2-1}$ has branch points at $z=\pm 1$.
We cut the plane with branch cuts from $(-1,0)$ to $(\infty, 0)$ and from $(1,0)$ to $(\infty,0)$ such that
$$0\le \arg(z-1)<2\pi$$
and
$$0\le \arg(z+1)<2\pi$$

Next, we note that on the real axis for $\text{Re}(z)>1$, coming from the upper-half plane,
$$\begin{align}
\arg(\sqrt{z^2-1})&=\frac12 \arg(z-1)+\frac12 \arg(z+1)\\\\
&=\frac12 (0)+\frac12 (0)\\\\
&=0
\end{align}$$
while on the real axis for $\text{Re}(z)>1$, coming from the lower-half plane,
$$\begin{align}
\arg(\sqrt{z^2-1})&=\frac12 \arg(z-1)+\frac12 \arg(z+1)\\\\
&=\frac12 (2\pi)+\frac12 (2\pi)\\\\
&=2\pi
\end{align}$$
And since $e^{i2\pi }=1$, we find that $f(z)$ is continuous across that part of the real axis for which $\text{Re}(z)>1$.

Similarly, we find that $f(z)$ is continuous across that part of the real axis for which $\text{Re}(z)<-1$.

Finally, let's examine the behavior of $f$ along the real axis between $z=-1$ and $z=1$.  Coming from the upper-half plane, we find that
$$\begin{align}
\arg(\sqrt{z^2-1})&=\frac12 \arg(z-1)+\frac12 \arg(z+1)\\\\
&=\frac12 (\pi)+\frac12 (0)\\\\
&=\pi/2
\end{align}$$
while coming from the lower-half plane, we find that
$$\begin{align}
\arg(\sqrt{z^2-1})&=\frac12 \arg(z-1)+\frac12 \arg(z+1)\\\\
&=\frac12 (\pi)+\frac12 (2\pi)\\\\
&=3\pi/2
\end{align}$$
Note that $e^{i\pi/2}=-e^{i3\pi/2}$ and the function $f(z)$ is, therefore, discontinuous across the line segment from $z=-1$ to $z=1$.

Putting all of this together, we conclude that the two individual chosen branch cuts have a "cancellation" effect for $\text{Re}(z)>1$.  The net result is a branch cut from $z=-1$ to $z=1$ and $f(z)$ is analytic outside the disk $|z|=1$.

NOTE:
A word of caution is in order here.  This "cancellation" effect does not happen in general.  The line segment between the two branch points of the function $g(z)=(z^2-1)^{1/3}$, for example, is not a suitable branch cut for $g(z)$.
Comment: For $Re(z)>1$ you proved $f$ continuous. Not analytic. So analyticity for $Re(z)>1$ is the fact that one should prove or it is consequence of continuity on $Re(z)>1$?
Comment: @MeetPatel It is not a consequence of continuity.  It is a consequence of the fact that $\log(z)$ is analytic on $\mathbb{C}\setminus [0,\infty)$.
Comment: Please give me more hint on how it implies the conclusion.
Comment: @MeetPatel I wish I had more time, but that might take a while
Comment: No problem. Thank you for your reply.
Answer: Actually, you just need to know that any closed loop crosses the cut an even number of times; since each crossing represents a sign change, you get consistency along paths.
In this case, the log of $z^2$ will have branch cuts on, say, the positive and negative real axes, and the only homotopically nontrivial loops are those that go around the disk some integral number of times, hence hit these branch cuts an even number of times.
Comment: Just a work of caution here ... While a branch cut from $-1$ to $1$ is suitable for the function of interest $(z^2-1)^{1/2}$, such a construction does not work in general. For example, it is not suitable for the function $(z^2-1)^{1/3}$.
Comment: Indeed. Since we're supposed to deal with the exterior of the unit disk, I was suggesting a *pair* of cuts from $-\infty$ to $-1$ and from $1$ to $\infty$.
Comment: John, yes absolutely.  And that cut is suitable here.  I thought it would be useful to emphasize that this "cancellation effect" does not generally work.  That is, for a function with two branch points, a cut that adjoins those points does not render, in general, the function analytic in the domain exterior to any bounded domain that contains the branch points.  - Mark
Comment: Indeed: that idea's suitable only for a two-sheeted cover; in the case of three sheets, as in your example, or even more, there's a permutaiton of sheets at each branch, and the composed permutations have to work out nicely. I liked this point enough that I upvoted your answer. :)
Comment: John.  Thank you for the up vote!  Much appreciative.  And +1 back... - Mark

Holomorphicity of $(z^2-1)^{1/2}$


Como conseguir Colocar o texto de uma textBox numa Label? C# WPF

Question: Estou a desenvolver uma aplicação em C# WPF, e tenho dois forms.
Um Form tem várias labels (com o nome de vários campos, como idade genero, nome, etc...) e debaixo de cada uma das labels tem uma TextBox para inserir um valor para a mesma.
No form seguinte eu tenho novamente um conjunto de labels com o nome dos campos, e por baixo de cada label quero ter outra label com o valor que foi introduzido na textBox respectiva no Form anterior, ou seja isto tem de ser conseguido de forma dinâmica.
Alguém tem ideia como posso fazer isto?
Tenho como auxiliares classes para os campos:
class:atributos
public class atributos
{

    public string Name { get; set; }
    public int atributoID { get; set; }

}

class: valores
public class AtributosValores
{

    public string Name { get; set; }
    public string Value { get; set; }
}

Basicamente eu quero apresentar no segundo conjunto de labels do 2º Form este Value, ou seja o Value introduzido na Text Box
Crio as textBox e Labels de forma dinamica tambem:
        public static Label createNewLabelSize (string name, int content, HorizontalAlignment horizontal, VerticalAlignment vertical, int width, int height)
        {

            //Create a new label
            Label newLabel = new Label();
            //Defines the new label characteristics
            newLabel.Name = name;
            newLabel.Content = content;
            newLabel.HorizontalAlignment = horizontal;
            newLabel.VerticalAlignment = vertical;
            newLabel.Width = width;
            newLabel.Height = height;

            return newLabel;
        }

Por isso coisas como label1.text = textbox2.text... não resultam!
Answer: Crie uma lista de objetos da classe AtributosValores, percorra o Form localizando os TextBox, e adicione os objetos na lista. Passe a Lista para o Form2, e percorra criando os campos. Utilize a propriedade Name do TextBox como o nome do atributo (que é exibido no Label).
Exemplo:
public List<AtributosValores> ValoresForm1 = new List<AtributosValores>();
private void button1_Click(object sender, EventArgs e)
{
    LerValores(this);
    Form2 form = new Form2();
    form.ValoresForm2 = this.ValoresForm1;
    form.Show();
}
private void LerValores(Control ctrl)
{
    foreach (Control c in ctrl.Controls)
    {
        if (c.HasChildren)
        {
            LerValores(c);
        }
        else if (c is TextBox)
        {
            AtributosValores obj = new AtributosValores();
            obj.Name = c.Name;
            obj.Value = ((TextBox)c).Text;
            ValoresForm1.Add(obj);
        }
    }
}

Segue código alterado para WPF:
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null && child is T)
                    {
                        yield return (T)child;
                    }

                    foreach (T childOfChild in FindVisualChildren<T>(child))
                    {
                        yield return childOfChild;
                    }
                }
            }
        }
        public List<AtributosValores> ValoresForm1 = new List<AtributosValores>();
        private void LerValores(ContentControl ctrl)
        {
            foreach (TextBox tb in FindVisualChildren<TextBox>(ctrl))
            {
                AtributosValores obj = new AtributosValores();
                obj.Name = tb.Name;
                obj.Value = tb.Text;
                ValoresForm1.Add(obj);
            }

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            LerValores(this);
            Form2 form = new Form2();
            form.ValoresForm2 = this.ValoresForm1;
            form.Show();
        }

Comment: acho que editou enquanto ainda estava a responder
Comment: Editei a resposta para adequar à sua edição.
Comment: é uma public List ValoresForm2 = new List(); porém dentro do Form2
Comment: no evento Load do Form 2, você percorre essa lista pra criar os campos
Comment: ctrl.Controls  com S no final
Comment: ok ok, estou falando de Forms e vc de Window (WPF), um momento
Comment: coloquei o código para WPF
Comment: mais algum codigo ?
Comment: não sei se aqui tem batepapo direto, mas chama no Facebook qlqr coisa


How to handle update request from different users on same product collection for same productId on same time mongodb

Question: I am having product Collection. And i want to handle the case where 8 users checkout for same product at same time. And suppose all 8 users request went inside update part then at that time which user will get product and what about the update query of rest 7 users?
8 user inside same update function
one user get update and available product count 0
if product is not available sent error or rollback database
Answer: You could implement a "lock" mechanism allow only one transaction on a given product at a time.
Maybe something like this. (I haven't tested this code; just sketching out the idea.)
<code>// utility function that just waits the specified duration and resolves
const sleep = duration => new Promise(resolve => setTimeout(resolve, duration));

// a map of the currently active locks
const locks = {};

// productId: the key to lock on
// transaction: an async function that performs the transaction
// timeout: how long to keep retrying before throwing
async function withLock (productId, transaction, timeout) {

  // if there's already a lock on this id...
  if (locks[productId]) {

    // …and we've exhausted the timeout…
    if (timeout <= 0) {
      // …throw an error
      throw new Error('Unable to acquire lock');
    }

    // otherwise wait 100ms…
    await sleep(100);

    // …and try again, reducing the timeout
    return withLock(productId, transaction, timeout - 100);
  }

  // no existing lock on this productId; proceed.
  try {
    // establish the lock so other calls on this id have to wait
    locks[productId] = true;

    // perform the transaction
    return await transaction();
  }
  finally {
    // and release the lock
    delete locks[productId];
  }
}
</code>
With this in place you can then do:
<code>try {
  const result = await withLock(productId, async () => {
    // perform checkout, update mongo, deduct inventory, whatever
  }, 2000);
}
catch (e) {
  // something went wrong, possibly a lock timeout
}
</code>
And
Comment: Is there any mongoDb lock collection or any other way to slove. Rather then setTimeout because i dont want to hold the api for that much time
Comment: setTimeout isn't going to hold up the api. setTimeout is going to try again in 100ms if there's already a lock, and it will keep trying for 2 seconds before giving up. But there's nothing here that's holding up the API. There are probably off-the-shelf implementations of this kind of thing. I don't know, haven't looked, but it seems likely.
Comment: Thanks. Is there any other standard format to solve the same
Comment: Standard format to do the same thing as this example?


Construction of continuous-time markov chain and finding stationary distribution

Question: There are 15 lily pads and 6 frogs. Each frog, with rate 1, jumps to one of the other 9 unoccupied pads chosen uniformly at random.
What is the stationary distribution for the set of occupied lily pads?
This is from Durrett's Essentials of Stochastic Processes.
I thought we would consider all possible combinations of occupied pads as states of a continuous-time Markov chain, so $15\choose6$ states. From there I suspect the stationary distribution is $\frac{1}{15\choose6}$ for every state. Is this a correct formulation? I am new to the subject of CTMC's so am not very sure in my answer.
Comment: Do the frogs all jump at once, or one at a time? The wording makes it sound like it is one at a time, but we should be careful about that.
Comment: I think it would be one at a time since each frog has its own rate. I don't have any other information besides that problem statement unfortunately
Answer: Yes, the states all have the same probabilities in the stationary distribution.  This is easy to see once you notice that the process is reversible: given two states $s_1$ and $s_2$ such that a transition from $s_1$ to $s_2$ is possible (by moving one frog), the rate of jumps from $s_1$ to $s_2$ when in state $s_1$ is the same as the rate of jumps from $s_2$ to $s_1$ when in state $s_2$.
Comment: Thanks for the confirmation! That reasoning makes sense.


Projective Closure of Morphism of Affine Varieties

Question: Every affine variety $V$ has a unique projective closure $\overline{V}$, and there is an injective morphism $\iota : V \rightarrow \overline{V}$ given by something like $\iota(X_1,\ldots, X_n) = (X_1, \ldots, X_n, 1)$. The projective variety $\overline{V}$ can be determined explicitly by homogenizing the polynomials which define $V$.
Now suppose $f: V_1 \rightarrow V_2$ is a morphism of affine varieties. My intuition says that there is a way to "complete" $f$ to give a morphism of projective varieties $\overline{f} : \overline{V_1} \rightarrow \overline{V_2}$ in a way that agrees with $f$ on the affine subvariety $V_1$. In other words, I think there should be some projective morphism $\overline{f}$ that yields a commutative diagram $\iota_2 \circ f = \overline{f} \circ \iota_1$. Since the value of $\overline{f}$ is determined by $f$ on $V_1$, it remains only to define $\overline{f}$ on the points at infinity on $V_1$.
My questions is does such an $\overline{f}$ always exist, is it unique, and how can it be determined?
Comment: A nitpick: the statement "every affine variety has a unique projective closure" can be very false depending on what definitions you take. At the very least you need to specify some embedding in $\Bbb A^n$, otherwise you can have [bad things happen](https://math.stackexchange.com/questions/3646684/isomorphic-affine-variety-induces-isomorphism-between-its-projective-closure/3647025#3647025). Can you be more specific about what the scenario you're dealing with is?
Comment: Mostly I'm interested in curves, and specifically elliptic curves. Does that make the scenario more straight forward?
Comment: No. The link in the previous comment gives an example of a curve with two different non-isomorphic projective closures.
Comment: In that case, I'm confused. Silverman's Arithmetic of Elliptic Curves textbook defines the projective closure of an affine algebraic set as the projective algebraic set whose homogenous ideal is generated by the homogenizations of the polynomials defining the affine variety. He goes on to remark that each affine variety may be identified with a unique projective variety in this way.
Comment: See, this is specific, and now your statement makes sense! You've picked a particular embedding $X\to\Bbb A^n$, and the projective closure of your variety is the closure of the image of the composite morphism $X\to \Bbb A^n\to \Bbb P^n$. Without specifying an embedding, this doesn't make sense.
Comment: I'm not understanding how my previous comment was more specific. You mentioned in your original reply about which definitions are being used, so I suspect this is the issue. Doesn't "affine variety" imply the set lives in some particular affine space and has a specific set of polynomials which define it?
Comment: [There's more than one definition of an affine variety](https://math.stackexchange.com/questions/3492560/what-is-an-algebraic-variety/).
Answer: It exists, but no uniqueness. Given $f$, take $i:V_1\to W_1$, $j:V_2\to W_2$, some projective closures (highly non-unique). Then, take the closure $Z$ of the graph, $V_1\to W_1\times W_2$, $v\mapsto (i(v), j\circ f(v))$. We have natural maps $V_1\to Z\to W_2$ and I will leave you to check the rest.


Network Locking/Unlocking via IMEI

Question: Hie There Everyone !!!
So this question is about cellphone companies and 3rd party companies being able to lock/unlock a cellphone to/from a particular network. My question is how do they do it especially/given that the mobile handset is located in a particular country ?? Also given that a phone is Network locked, what exactly is locked ?? Is it the firmware or it's software that basically prevents you from using another SIM Card ?? Is there any hardware available to unlock your mobile device on your own and at what cost ??
Thanks Very Much, I hope I made myself clear in this question.
Answer: Locking a phone on a particular network is up to recently a matter of sim locking the phone. This means the firmware does a test on startup is the inserted sim belongs to a specific operator. Most of the time there is an official procedure to unlock the phone you can ask to your operator if yous had been a subscriber "long enough". The ere are also unofficial procedures which can be applied if you have the right software you have to buy. In Africa it's a real business people do in the street.
Some spartphone vendors can also lock their phones is they have specific commercial agreements with the operator. They do it on their centralized servers. Unlocking in this case is tricky, or even impossible.

Network Locking/Unlocking via IMEI


How to sync two different content types?

Question: I'm going to build a website for a magazine.I have two different content types. In the first one, I will post the first page of magazine. But in the second one is for articles.
Now, my problem is:
I want to show just articles which are related to the issue which displayed on the top. I know how to show latest content [for first content type which includes first page], but i don't know how to show its articles under it. I guess,I would use views, but I don't know how.
to be more clear: I want something like this site.
Comment: First you need to define the relationship between these two content types. Drupal can't magically know how articles belong to which piece of front page content.
Answer: Assuming you have an Issue content type, and an Article content type
Install References and enable Node References.  On the Article content type, Add a Node Reference field (could name it "issue") and restrict its options to nodes of type Issue.
Then create a View of Articles and add (under Advanced) a Contextual Filter of Content: Issue (and if you are using url aliases for the Issues, then provide the Contextual filter with a default value of Content ID from URL).  Make it a Block display.
Then display the block on Nodes of type Issue, and it should work great for you.
Comment: thx, I'll give it a try.
Answer: A combination of Panels, Taxonomy and Views could be used for this site. You  could use taxonomy terms to differentiate the issues. For e.g for Issue 1, you could enter the term "issue1", for Issue 2 you could use "issue2", etc.
Then you could use views  to filter content based on Taxonomy terms.
This  tutorial comes close to what you are trying to build.


make background of sprite transparent in SDL

Question: How to change background color of sprites to transparent by changing alpha after loading it to a SDL_Surface. Are there any functions in SDL which use a floodfill kind of algorithm and change all pixel with a given color to transparent on the outside. I don't want it to happen inside the border of the sprite if the same color is used.
Sample Image:

I would like to make the background blue here transparent before I blit it on the window surface using SDL_BlitSurface.
Comment: You can't just edit the base image to have an alpha-channel and transparent background?
Comment: I think you do this with `SDL_SetColorKey()` - https://wiki.libsdl.org/SDL_SetColorKey but I don't know exactly how to do it, and the doco is inconclusive.
Comment: SDL_SetColorKey() works if the background color was not included in my palette for any sprite. I think most of my sprites don't have it and for the ones that do have, I will change the color by a small value and use it.
Comment: Can't you change or copy-and-replace the image "offline" (ie: during development, rather than in the game)?
Answer: Only a color key (SDL_SetColorKey()) or a full alpha channel are going to help you here.
Note, that you can provide an alpha channel in your source graphics if you use a format such as PNG. If you only sometimes need/want an alpha, then provide the alpha channel in your source graphics and use SDL_SetSurfaceBlendMode() with SDL_BLENDMODE_NONE to blend without the alpha and SDL_BLENDMODE_BLEND to blend with it.
Both SDL_Surface and SDL_Texture support SDL_BlendMode.
Even if SDL provided another method, such as the fill you mentioned. You wouldn't want to use that. It is more difficult, expensive, and unnecessary overhead. You should stick with best practices here.
You may want to look into SDL_Texture and SDL_Renderer and switch to using a "texture atlas" instead of individual surfaces/textures for each image to maximize performance.


feeds_ex module tests returns me fatal error

Question: When I am running feeds_ex test i got an error that says:
<code>PHP Fatal error: Class 'TUnit' not found in /sites/all/modules/contrib/feeds_ex/src/Tests/FeedsExUnitTests.test on line 11
</code>
I am looking around in google and forums but nothing similar found.
Any solution appreciated!
Answer: Per the instructions for the Feeds extensible parsers module:

To run tests locally, the TUnit module is required.

So you need to install the TUnit module, which contains the missing class.


WooCommerce Add to Cart - Redirect to URL

Question: I want to just show a simple add to cart button at the bottom of a page. I can do so by using shortcodes:
[add_to_cart id="99"] or [add_to_cart_url id="99"]
The problem is that I want to then go to another URL that is not related to WooCommerce. It has to be customized depending on the page we are on.
An example would be:

Intro Landing page (add to cart at bottom)
 a. Action: adds product 99 to cart then redirects to #2.
Upsell page with 3 products on it
 a. Action: adds one of the three products to the cart and redirects to #3.
Second Upsell page with 1 product on it
 a. Action: adds the product to the cart and redirects to #4.
Checkout Page.

I was hoping there was a shortcode that I could use for Add to Cart and Redirect but can't find anything online. I have found a custom redirect option that woocommerce offers but it would set the redirect for all Add to Cart buttons.
I was thinking that there may be a way to create a function that expands the add to cart button shortcode so I can add a custom redirect URL to it.
For example: [add_to_cart id="99" redirect="../step2/"]
This can even be a URL that I can use in a link. I found that on this page under the section titled "URL: Add One Simple Product to Cart & Redirect to Any Page Afterwards" that says I should be able to just use:
href="http://yourdomain.com/your_custom_page/?add-to-cart=25"

It adds the product to the cart but then just redirects to the cart (I have AJAX add to cart buttons enabled).
Any ideas may help!
Thanks,
Matt
Answer: Using this works: http://yourdomain.com/your_custom_page/?add-to-cart=25
I just had to uncheck the box in WooCommerce Settings that says to go to cart when someone clicks add to cart and make sure AJAX links was checked


zip 2 lists of dictionaries into 1

Question: I have a first list like so
[{"name":"jon", "age":10}, {"name":"mary", "age":12}]

And a second list like so
[{"city":"nyc"}, {"city":"la"}]

And would like to combine them into a single list of dicts. They are assumed to be of same length too.
[{"name":"jon", "age":10, "city":"nyc"}, {"name":"mary", "age":12, "city":"la"}]

thanks!
Answer: Using list comprehension:
>>> lis1 = [{"name":"jon", "age":10}, {"name":"mary", "age":12}]
>>> lis2 = [{"city":"nyc"}, {"city":"la"}]
>>> [dict(x, **y) for x, y in zip(lis1, lis2)]
[{'city': 'nyc', 'age': 10, 'name': 'jon'}, {'city': 'la', 'age': 12, 'name': 'mary'}]

As Guido dislikes dict(x, **y), another option is:
>>> [dict(x.items() + y.items()) for x, y in zip(lis1, lis2)]
[{'city': 'nyc', 'age': 10, 'name': 'jon'}, {'city': 'la', 'age': 12, 'name': 'mary'}]

Answer: Also simply:
for i in xrange(len(x)):
    x[i].update(y[i])

Answer: Three new ways, all direct variants:
from collections import ChainMap

first  = [{"name":"jon", "age":10}, {"name":"mary", "age":12}]
second = [{"city":"nyc"}, {"city":"la"}]

Firstly:
map(ChainMap, first, second)
#>>> <map object at 0x7fee1c53ddd0>

Note that this doesn't copy the objects. If you need it in an actual list:
[ChainMap(f, s) for f, s, in zip(first, second)]
#>>> [ChainMap({'name': 'jon', 'age': 10}, {'city': 'nyc'}), ChainMap({'name': 'mary', 'age': 12}, {'city': 'la'})]

If you need it copied:
[dict(ChainMap(f, s)) for f, s, in zip(first, second)]
#>>> [{'name': 'jon', 'age': 10, 'city': 'nyc'}, {'name': 'mary', 'age': 12, 'city': 'la'}]

Honestly this seems nicer to me than dict(first.items() + second.items()) and it's also quite stable.

zip 2 lists of dictionaries into 1


how to bound a Persistent volume claim with a gcePersistentDisk?

Question: I would like to bound PersistentVolumeClaim with a gcePersistentDisk PersistentVolume. Below the steps I did for getting that:
1. Creation of the gcePersistentDisk:
gcloud compute disks create --size=2GB --zone=us-east1-b gce-nfs-disk
2. Definition the PersistentVolume and the PersistentVolumeClaim
# pv-pvc.yml
apiVersion: v1
kind: PersistentVolume
metadata:
  name: nfs-pv
spec:
  capacity:
    storage: 2Gi
  accessModes:
    - ReadWriteOnce
  gcePersistentDisk:
    pdName: gce-nfs-disk
    fsType: ext4
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: nfs-pvc
  labels:
    app: test
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 2Gi

After running kubectl apply -f pv-pvc.yml, the nfs-pvc is not bound with nfs-pv. In fact, below is the list of the PersistentVolume and PersistentVolumeClaim I have:
$ kubectl get pv
NAME                                       CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS      CLAIM             STORAGECLASS   REASON    AGE
nfs-pv                                     2Gi        RWO            Retain           Available                                              30s
pvc-16e4cdf2-cd3d-11e7-83ae-42010a8e0243   2Gi        RWO            Delete           Bound       default/nfs-pvc   standard                 26s
$ kubectl get pvc
NAME      STATUS    VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   AGE
nfs-pvc   Bound     pvc-16e4cdf2-cd3d-11e7-83ae-42010a8e0243   2Gi        RWO            standard       59s

The obtained PersistentVolume is a volume on the disk of the node I created on Google Container Engine.
So, have I missed something?
PS: the version of kubernetes
$ kubectl version
Client Version: version.Info{Major:"1", Minor:"8", GitVersion:"v1.8.3", GitCommit:"f0efb3cb883751c5ffdbe6d515f3cb4fbe7b7acd", GitTreeState:"clean", BuildDate:"2017-11-08T18:39:33Z", GoVersion:"go1.8.3", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"7+", GitVersion:"v1.7.8-gke.0", GitCommit:"a7061d4b09b53ab4099e3b5ca3e80fb172e1b018", GitTreeState:"clean", BuildDate:"2017-10-10T18:48:45Z", GoVersion:"go1.8.3", Compiler:"gc", Platform:"linux/amd64"}

Comment: Name of your PV is my-pvc as well as PVC is my-pvc.However, In the result of commands 'Kubectl get pv,pvc' name is different which are nfd-pv, nfs-pvc.  Why is this behaviour?
Comment: I got your point. Original names are put back. But, any way, the problem is still here...
Answer: I found the solution.
Below the new definitions of the PV and PVC:
apiVersion: v1
kind: PersistentVolume
metadata:
  name: nfs-pv
  labels:
    app: test  # the label has been added to make sure the bounding is working as expected
spec:
  capacity:
    storage: 2Gi
  accessModes:
    - ReadWriteOnce
  gcePersistentDisk:
    pdName: gce-nfs-disk
    fsType: ext4
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: nfs-pvc
  labels:
    app: test
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: "" # the storageClassName has to be specified
  resources:
    requests:
      storage: 2Gi
  selector:
    matchLabels:
      app: test

After these modifications, this is the bounding worked:
$ kubectl get pvc
NAME      STATUS    VOLUME    CAPACITY   ACCESS MODES   STORAGECLASS   AGE
nfs-pvc   Bound     nfs-pv    2Gi        RWO                           8s
$ kubectl get pv
NAME      CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS    CLAIM             STORAGECLASS   REASON    AGE
nfs-pv    2Gi        RWO            Retain           Bound     default/nfs-pvc                            22m

I hope it will help.
Comment: Getting this error on using volume as above. Failed to get GCE GCECloudProvider with error
Answer: With PersistentVolumeClaim, you don't need to create PersistentVolume objects or gcePersistentDisk. Instead, create only a PVC and Kubernetes automatically creates a PV object that references the backing storage.
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: nfs-pvc
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: ssd-sc  # specify the storage class created below
  resources:
    requests:
      storage: 10Gi

Create a StorageClass so it knows which backing storage to use. You can specify that it retains the storage (reclaimPolicy: Retain) if you delete the PVC and the storage type (type: pd-ssd).
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: ssd-sc
provisioner: kubernetes.io/gce-pd
reclaimPolicy: Retain # Retain storage even if we delete PVC
parameters:
  type: pd-ssd # ssd


Sample specific area of hypersphere

Question: Question
I want to find a set of D dimensional vectors with a minimum distance (similarity) to each other. A lab-mate of mine has shown how to do this using the Graham-Schmidt process, but it doesn't seem to be working for high-dimensional surfaces. On a 3D surface, the matrix M, seems to show the boundary of the valid sampling area. How do I sample this surface specifically? Is it possible to generalize this sampling methodology to higher dimensions?
In other words, I'm trying to find a set of vectors $V$ distributed over a hypersphere such that all pairs possible pairs of $V$ have a dot product larger than a similarity $s$. I think this is analogous to sampling a certain area of the hypersphere that $V$ is being sampled from.
Visualisation and Code
Here is the visualisation that shows M (in green) surrounding the valid vectors (in blue).

Here is the code I used to create this visualization. I'm using some weird libraries, but this is just so you understand what I'm doing.
<code>import nengo
from nengolib.stats import sphere

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def proj(u, v):
    return u.dot(v.T) / u.dot(u.T) * u

uniform_sphere = nengo.dists.UniformHypersphere(surface=True)

d = 3
similarity = 0.3

M = np.zeros((d, d))       # output matrix
Q = np.zeros((d, d))       # Gram-Schmidt orthogonalization of S
S = uniform_sphere.sample(d, d=d)  # some random samples used to form Q

for i in range(d):
    Q[i, :] = S[i, :]
    a = similarity/((i-1)*similarity + 1)
    for j in range(i):
        Q[i, :] -= proj(Q[j, :], S[i, :])
        M[i, :] += a*M[j, :]
    M[i, :] += np.sqrt((1 - i*a*similarity)/Q[i, :].T.dot(Q[i, :]))*Q[i, :]

good = []
bad = []
for p in sphere.sample(200, d=d):
    if np.all(M.dot(p.T) >= similarity):
        good.append(p)
    else:
        bad.append(p)

assert len(good) > 0
good = np.asarray(good)
bad = np.asarray(bad)
assert np.all(good.dot(good.T) >= similarity)

plt.figure(figsize=(7, 7))
ax = plt.subplot(111, projection='3d')
ax.scatter(*bad.T, s=5, c='red')
ax.scatter(*good.T, s=20, c='blue')
ax.scatter(*M.T, s=50, c='green')
ax.set_xlim3d(-1, 1)
ax.set_ylim3d(-1, 1)
ax.set_zlim3d(-1, 1)
ax.view_init(45, 45)
plt.show()
</code>
Comment: "vectors with a minimum to each other"  A minimum WHAT to each other?
Comment: The code looks like python, and as a non python user who also never used the maths lib in python, this is painful to read. A bit more of explaining about what you're trying to achieve in English or maths assertions would be very welcomed. I am currently trying to go through the link you provided to get those information, but your question would benefit from a more detailed explanation.
Comment: @N.Bach I'm sorry for making things needlessly hard for you. I'll try to make my questions more clear in the future.
Comment: @WillJagy similarity/distance /*facepalm/*
Comment: @N.Bach I added further English assertions. Should I remove the figure and code entirely? I don't totally understand it, so it's hard for me explain it.
Comment: I think the edit is better, but it's a little bit late. Especially now that I went through the other link you provided. The figure actually helped a lot. The code somewhat helped, but just the code alone makes for a very poor question. I spent more time than I'd want to admit trying to figure out what you wanted. For future questions, try to help your reader, because people are often lazy and don't want to go around to find the information they need.
Answer: Quickly went through the link you provided, and if I understood properly (honestly, I probably didn't), your current problem would be: "how to sample the blue area" and "why does your code fail to find any good sample in high dimension".

About your sampling problem, here are my assumptions.

I will assume that every vectors lie on some hypersphere, cause that's what it looks like in your figure.
I will also assume that you are able to somehow compute the $D$ green vectors, where $D$ is your dimension. I think those green vectors are stored in your matrix $M$.
If my understanding is correct, you fix a threshold $b$ of "similarity". The blue surface has the following property:

Let $S$ be any sampling of the blue surface. For any two vectors $v_1,v_2\in S$, then $\langle v_1,v_2\rangle \ge b$.

Assuming all of that, that blue surface corresponds to the conical hull of the green vectors, intersected with the hypersphere. If you prefer, you can take the convex hull of those green vectors, and just project that convex hull along the radii of the hypersphere, onto the hypersphere:

Denote by $M_1,\ldots,M_D$ the $D$ green vectors.
  Then, for any vector $v$ in the blue surface, there exists $D$ coefficients
  $0\le \lambda_1,\ldots,\lambda_D \le 1$ and $\alpha\ge 0$ such that

$\sum_{i=1}^D\lambda_i = 1$
$\hat v=\sum_{i=1}^D\lambda_iM_i$
$v=\alpha\hat v$

Basically $\alpha$ is just there to say you should scale $\hat v$ so that it lies on the hypersphere. If my previous assumption about everyone living on some hypersphere is false, then this whole thing is obviously useless.
If I somehow interpreted your question properly and I'm right, then this allows you to systematically pick a point inside your blue surface. If you're fine with $n$ random samples, you can just sample coefficients
$\lambda_1,\ldots,\lambda_D$ whichever way you like.

Regarding your other problem, about why your sampling fails in higher dimensions, it's a bit difficult to say unless you provide us with
a rough idea of the dimension, and how many samples you used.
But if you went into very high dimensions, then the short answer would be "yes, you're underestimating how small the [blue surface] is in higher dimensions".
Consider the $D$ vectors in $M$, they constitute a basis of $\mathbb R^D$. That basis is in general not orthogonal, so not that "nice" to use. But using that basis, the blue surface can be expressed as the portion of the hypersphere that lies within the positive hyperoctant. And that is a very, very small portion of the surface of the complete hypersphere, because there are a total of $2^D$ hyperoctants. So a ballpark estimate indicates that your blue surface represents $\frac 1{2^D}$-th of the surface of the complete hypersphere.
Of course, all hyperoctants are not of the same "angular" size, but in the figure you provided, it is already among the smallest hyperoctants. Additionally, the higher your similarity threshold $b$, the smaller the hyperoctant will be, so any practical use case for you would yield a small surface.

Sample specific area of hypersphere


ProgressDialog on top of Dialogue Fragment

Question: I have an activity which displays a Dialogue Fragment when user Performs an action.
when user clicks one button in Dialogue Fragment i want to show a Progress Dialog  but it is shown below Dialogue Fragment,How to bring it to front ?
Answer: I think you are showing Prgress Bar before Dialog Fragment try to show Progress Bar just after the Dialog Fragment. Hope this will help you
Comment: Can you post your code for showing `Dialog Fragment` and also for showing `Progress Bar`
Comment: DialogFragment newFragment = new Myfragment();
    newFragment.setStyle(DialogFragment.STYLE_NO_FRAME,
      R.style.MyDialogTheme);
    //
    newFragment.show(getSupportFragmentManager(), "dialog");

in Myfragment  i wrote this code,
 progressDialog = ProgressDialog.show(getActivity(), null, "Loading...");
Comment: You should update it in your question and also update code for `Dialog Fragment`
Answer: it is solved
i am showing progress dialog in transaparent dialogfragment


Show $(1+\frac{z}{n})^{n} \underset{n \to +\infty}{\longrightarrow }e^{z}$

Question:
To show that $$z_n=\left(1+\dfrac{z}{n} \right)^{n} \underset{n \longmapsto +\infty}{\longrightarrow \exp(z)}$$
  the author of textbook use the following method but there is some steps that i'm not sure if i got it right so would someone elaborate it

Let $x = \Re(z)$ and $y=\Im(z)$

${\displaystyle r_n=\sqrt{\left(1+\dfrac{x}{n} \right)^{2}+\dfrac{y^{2}}{n^2}}=\sqrt{1+\dfrac{2x}{n}+o\left(\dfrac{1}{n}\right)}=1+\dfrac{x}{n}+o\left(\dfrac{x}{n}\right)}$
why if $r_n=1+\dfrac{x}{n}+o\left(\dfrac{x}{n} \right)$ then $\ln(r_n)\sim \dfrac{x}{n}$
how we can get the expression of $\tan(\alpha_n)$
why if $\tan\left( \alpha_n \right)\sim \dfrac{y}{n}$ then $\alpha_{n}\sim \dfrac{y}{n}$

My thoughts:
first i think there is typo in $z_n=r_n^{n}e^{n\alpha_n}$ should we write $z_n=r_n^{n}e^{i n\alpha_n}$ instead.

${\displaystyle r_n=\sqrt{\left(1+\dfrac{x}{n}
   \right)^{2}+\dfrac{y^{2}}{n^2}}=\sqrt{1+\dfrac{2x}{n}+o\left(\dfrac{1}{n}\right)}=1+\dfrac{x}{n}+o\left(\dfrac{x}{n}\right)}$

note that

$$\left(1+x \right)^{\alpha}\underset{x\to 0}{=}1+\alpha x +o\left( x\right) $$

$$\begin{cases} \left(1+\dfrac{x}{n} \right)^{2}=1+2\dfrac{x}{n}+o\left( \dfrac{1}{n}\right) \\ \dfrac{y^{2}}{n^{2}}=o\left(\dfrac{1}{n}\right)\end{cases}\implies 1+\dfrac{2x}{n}+o\left(\dfrac{1}{n}\right)$$
on the other hand
\begin{aligned}\sqrt{1+\dfrac{2x}{n}+o\left(\dfrac{1}{n}\right)}=\left(1+\dfrac{2x}{n}+o\left(\dfrac{1}{n}\right) \right)^{\frac{1}{2}}&=1+\dfrac{1}{2}\left( \dfrac{2x}{n}+o\left( \dfrac{1}{n}\right)\right)+o\left(o\left(\dfrac{1}{n}\right)\right) \\
&=1+\dfrac{x}{n}+o\left( \dfrac{1}{n}\right)+o\left(\dfrac{1}{n}\right)\\
&=1+\dfrac{x}{n}+o\left( \dfrac{1}{n}\right)
\end{aligned}
then $$\fbox{$r_{n}=1+\dfrac{x}{n}+o\left( \dfrac{1}{n}\right)$}$$

why if $r_n=1+\dfrac{x}{n}+o\left(\dfrac{x}{n} \right)$ then $\ln(r_n)\sim \dfrac{x}{n}$

note that :

if $u_n\sim v_n $ and $v_n \sim w_n $ then $u_n \sim w_n$
  $u_n\sim v_n \iff u_n=v_n+o(v_n)$

i can't show this

how we can get the expression of $\tan(\alpha_n)$

If $a+ib=\rho e^{i\theta}$ with  $a>0$  then $\tan(\theta)=\frac b a$

since $\left( 1+\dfrac{z}{n}\right)=\left( 1+\dfrac{x}{n}\right)+i\dfrac{y}{n}=r_{n}e^{i\alpha_n} $ then
$$\tan(\alpha_n)=\dfrac{\dfrac{y}{n}}{1+\dfrac{x}{n}}=\dfrac{y}{x+n}$$
$$\fbox{$\tan(\alpha_n)=\dfrac{y}{x+n} $} $$

why if $\tan\left( \alpha_n \right)\sim \dfrac{y}{n}$ then $\alpha_{n}\sim \dfrac{y}{n}$

if $u_n\sim v_n $ and $v_n \sim w_n $ then $u_n \sim w_n$

So should show that $\alpha_n \underset{n \to +\infty}{\overset{}{\longrightarrow}}0$ to be able to say that $\tan(\alpha_n)\sim r_n$
we've $\tan(\alpha_n)=\dfrac{y}{x+n}$ then $\alpha_n=\arctan\left(\dfrac{y}{x+n}\right) $
$$\lim_{n\to +\infty}\alpha_n=\lim_{n\to +\infty} \arctan\left(\dfrac{y}{x+n}\right)=\arctan\left(\dfrac{y}{x+\lim_{n\to +\infty} n}\right)=\arctan(0)=0   $$
then $$\begin{cases}\tan(\alpha_n) \sim \alpha_n  \\  \tan(\alpha_n)\sim \dfrac{y}{n} \end{cases} \implies \alpha_n\sim \dfrac{y}{n}$$

If my proof wrong would you elaborate the steps
Comment: what is your definition for $\mathrm{e}^z$? Is it $\exp(z)$ or $\exp(1)^z$ or $\Big[\lim_{n\in\mathbb{N}}\big(1+\frac{1}{n}\big)^n\Big]^z$?
And it would be nice if you had mention that $x = \Re(z)$ and $y=\Im(z)$
Comment: okay i have added them
Answer: This is a very strange proof, apart from the handwaving colloquial style in printed matter. The usual  setup is the following:
$$\eqalign{e^z-\left(1+{z\over n}\right)^n&=\bigl((e^{z/n}\bigr)^n-\left(1+{z\over n}\right)^n\cr
&=\left(e^{z/n}-\bigl(1+{z\over n}\bigr)\right)\cdot\sum_{k=0}^{n-1}\bigl(e^{z/n}\bigr)^{n-1-k}\left(1+{z\over n}\right)^k\cr
&=R_n\cdot \Sigma_n\ .\cr}$$
Here
$$R_n={z^2\over n^2}g\left({z\over n}\right)$$
with $\lim_{\zeta\to0}g(\zeta)={1\over2}$ by Taylor's theorem, and
$$\eqalign{|\Sigma_n|&\leq \sum_{k=0}^{n-1}\bigl(e^{|z|/n}\bigr)^{n-1-k}\left(1+{|z|\over n}\right)^k\leq \sum_{k=0}^{n-1}\bigl(e^{|z|/n}\bigr)^{n-1-k}\left(1+{|z|\over n}\right)^k\cr &\leq \sum_{k=0}^{n-1}\bigl(e^{|z|/n}\bigr)^{n-1-k}\bigl(e^{|z|/n}\bigr)^k\leq n\>e^{|z|}\ .\cr}$$


Matrix multiplication error when I tried to build the neural network from scratch

Question: When I learned about mathematical working of neural network I tried to build it from scratch using Numpy. The neural network structure I tried to build was input_layer with 3 nodes -> hidden_layer_1 with 2 nodes -> hidden_layer_2 with 2 nodes -> output_layer with 1 node. Both of the hidden layers use ReLu activation function, and the output layer uses Sigmoid activation function. Here is the data set : https://drive.google.com/file/d/1xP6BvneSdG5SoXL1ADp0veZMSrOcFlQc/view?usp=drive_linkThe code is below:
import numpy as np
import pandas as pd

W1 = np.random.rand(2, 3) # Weight matrices
W2 = np.random.rand(2, 2)
W3 = np.random.rand(1, 2)

B1 = np.random.rand(2, 1) # Bias vectors
B2 = np.random.rand(2, 1)
B3 = np.random.rand(1, 1)

ReLu = lambda x : np.maximum(x, 0)
Sigmoid = lambda x : 1/ (1+np.exp(-x))

def forward_prop(inputs):

    Z1 = W1@inputs + B1
    A1 = ReLu(Z1)

    Z2 = W2@A1 + B2
    A2 = ReLu(Z2)

    Z3 = W3@A2 + B3
    A3 = Sigmoid(Z3)

    return Z1, A1, Z2, A2, Z3, A3

d_relu = lambda x : x>0
d_sigmoid = lambda x : np.exp(-x) / (1+np.exp(-x))**2

def back_prop(Z1, A1, Z2, A2, Z3, A3, X, Y):

    #derivatives
    dC_dA3 = 2*A3 - 2*Y

    dA3_dZ3 = d_sigmoid(Z3)
    dZ3_dW3 = A2
    dZ3_dB3 = 1
    dZ3_dA2 = W3

    dA2_dZ2 = d_relu(Z2)
    dZ2_dW2 = A1
    dZ2_dB2 = 1
    dZ2_dA1 = W2

    dA1_dZ1 = d_relu(Z1)
    dZ1_dW1 = X
    dZ1_dB1 = 1

    dC_dW3 = dC_dA3 @ dA3_dZ3 @ dZ3_dW3.T
    dC_dB3 = dC_dA3 @ dA3_dZ3 * dZ3_dB3
    dC_dA2 = dC_dA3 @ dA3_dZ3 @ dZ3_dA2
    dC_dW2 = dC_dA2 @ dA2_dZ2 @ dZ2_dW2.T
    dC_dB2 = dC_dA2 @ dA2_dZ2 * dZ2_dB2
    dC_dA1 = dC_dA2 @ dA2_dZ2 @ dZ2_dA1 # Problem is here
    dC_dW1 = dC_dA1 @ dA1_dZ1 @ dZ1_dW1.T
    dC_dB1 = dC_dA1 @ dA1_dZ1 * dZ1_dB1

    return dC_dW1, dC_dB1, dC_dW2, dC_dB2, dC_dW3, dC_dB3

data = pd.read_csv('light_dark_font_training_set.csv')
x = data.iloc[:, :-1].values
y = data.iloc[:, -1].values

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=1/3)

n = x_train.shape[0]
L = 0.05
epochs = 100_000

for i in range(epochs):

    idx = np.random.choice(n, 1, replace=False)
    x_sample = x_train[idx].transpose()
    y_sample = y_train[idx]

    z1, a1, z2, a2, z3, a3 = forward_prop(x_sample)
    w1, b1, w2, b2, w3, b3 = back_prop(z1, a1, z2, a2, z3, a3, x_sample, y_sample)

    W1 -= L*w1
    W2 -= L*w2
    W3 -= L*w3

    B1 -= L*b1
    B2 -= L*b2
    B3 -= L*b3

    if i%10000 == 0:
        print(i)

When I tried running the above program it shows the following value error, which says that the matrix dimensions are not matched for matrix multiplication. At first I thought I had some problems with the partial derivatives in back propagation but as for my as knowledge it looks fine to me.
Why does this happen and how to resolve it?

ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_11036/3060626554.py in <module>
      6
      7     z1, a1, z2, a2, z3, a3 = forward_prop(x_sample)
----> 8     w1, b1, w2, b2, w3, b3 = back_prop(z1, a1, z2, a2, z3, a3, x_sample, y_sample)
      9
     10     W1 -= L*w1

~\AppData\Local\Temp/ipykernel_11036/566612658.py in back_prop(Z1, A1, Z2, A2, Z3, A3, X, Y)
     22     dC_dW2 = dC_dA2 @ dA2_dZ2 @ dZ2_dW2.T
     23     dC_dB2 = dC_dA2 @ dA2_dZ2 * dZ2_dB2
---> 24     dC_dA1 = dC_dA2 @ dA2_dZ2 @ dZ2_dA1# Problem is here
     25     dC_dW1 = dC_dA1 @ dA1_dZ1 @ dZ1_dW1.T
     26     dC_dB1 = dC_dA1 @ dA1_dZ1 * dZ1_dB1

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc     signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 1)

Comment: issue with the matrix multiplication in the backward propagation function - (dC_dA1)
Answer: try like this :
def back_prop(Z1, A1, Z2, A2, Z3, A3, X, Y):

# derivatives
dC_dA3 = 2 * (A3 - Y)

dA3_dZ3 = d_sigmoid(Z3)
dZ3_dW3 = A2
dZ3_dB3 = 1
dZ3_dA2 = W3

dA2_dZ2 = d_relu(Z2)
dZ2_dW2 = A1
dZ2_dB2 = 1
dZ2_dA1 = W2

dA1_dZ1 = d_relu(Z1)
dZ1_dW1 = X
dZ1_dB1 = 1

# Use element-wise multiplication for dC_dA1
dC_dA1 = dC_dA2 * (dA2_dZ2 @ dZ2_dA1.T)

dC_dW3 = dC_dA3 @ (dA3_dZ3 * dZ3_dW3).T
dC_dB3 = dC_dA3 * dA3_dZ3 * dZ3_dB3
dC_dW2 = dC_dA2 @ (dA2_dZ2 * dZ2_dW2).T
dC_dB2 = dC_dA2 * dA2_dZ2 * dZ2_dB2
dC_dW1 = dC_dA1 @ (dA1_dZ1 * dZ1_dW1).T
dC_dB1 = dC_dA1 * dA1_dZ1 * dZ1_dB1

return dC_dW1, dC_dB1, dC_dW2, dC_dB2, dC_dW3, dC_dB3

Comment: you missed out the dC_dA2


Is this an SQL injection attack? If so, what's it trying to do?

Question: I'm seeing a number of entries in my access log where 'A=0 is added to a query parameter, eg:
http://www.server.org/foo/?bar=1'A=0&type=xml
The parameter that 'A=0 is attached to varies, but it's always 'A=0, so it seems unlikely that this is some accidentally malformed URL being clicked on.  Also, the referer is always the same as the target URL, which makes me think it's a wholly manufactured request.
What I don't get is what this is intended to do.  Assuming it's an SQL injection attempt, it seems like it would generate invalid SQL and simply fail.  Is there something I'm missing?
Comment: It might be a test probe just to see how you handle it.  If your server throws some crazy error and dumps a crashlog, the bot may try crafting more malicious urls.
Answer: It's a bit of a blunt instrument, intended to "probe" poorly-written sites, i.e. those vulnerable to SQL Injection attacks and with poor error-handling.
$user = $_GET[ 'bar' ] ; // "1'A=0"
$sql = "select * from users where username = '$user'" ; // literally '1'A=0'

Such sites will throw an error at this and, more than likely, display the whole error message for all the World, and the attacker, to see.  The wording of that error will, most likely, be DBMS specific.
So, one dodgy request like this and Bingo!  Your attacker now knows what DBMS you're running and can reach for their favourite "Attack Vector Playbook" to start breaking into that.
Answer: I've seen these for months, I just assumed they were caused by a bot looking for SQL injection holes.
Almost all of my URL variables are strictly numeric, so I filter all non-numeric URL variables and redirect to a friendly error page.
The error page emails me the CGI dump, so if the attack is more than a few sorties, I block the IP.


IBM Worklight - "Could not connect to database" error message

Question: I have been trying to connect MySQL via my SQL adapter but I keep getting the following error:

Could not connect to database. Cannot create PoolableConnectionFactory
  (Connection refused. Check that the hostname and port are correct and
  that the postmaster is accepting TCP/IP connections.). [project
  SampleWorklightApp]

My adapter XML:
<code><?xml version="1.0" encoding="UTF-8"?>
<wl:adapter name="sampleSQLAdapter" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:wl="http://www.worklight.com/integration" xmlns:sql="http://www.worklight.com/integration/sql">

  <displayName>sampleSQLAdapter</displayName>
  <description>sampleSQLAdapter</description>
  <connectivity>
    <connectionPolicy xsi:type="sql:SQLConnectionPolicy">
      <!-- Example for using a JNDI data source, replace with actual data
        source name -->
      <!-- <dataSourceJNDIName>java:/data-source-jndi-name</dataSourceJNDIName> -->

      <!-- Example for using MySQL connector, do not forget to put the MySQL
        connector library in the project's lib folder -->
      <dataSourceDefinition>
        <driverClass>com.mysql.jdbc.Driver</driverClass>
        <url>jdbc:mysql://127.0.0.1:3306/test</url>
        <user>root</user>
        <password>sanchit</password>
      </dataSourceDefinition>
    </connectionPolicy>
    <loadConstraints maxConcurrentConnectionsPerNode="5" />
  </connectivity>

  <!-- Replace this with appropriate procedures -->
  <procedure name="getCustomerName" />
  <procedure name="insertCustomerDetails" />
</wl:adapter>
</code>
Using:

OS Platform : Mac OSX 10.8
Eclipse:Kepler Service Release 1
Worklight: Version 6 Developer Edition
MySQL: mysql-connector-java-5.1.28-bin.jar 1.6.0_65
Comment: There are two ways to connect to mysql, on using networking (address and port) and one using socket files. Depending on how and which version of mysql you installed, networking is disabled (it is something like a security feature having mysql not reachable from outside by default), so the first steps are, check if mysql is running, then check if networking is active for mysql or change the connection type to use file socket instead.
Comment: Double check the host (Try "localhost"...) port, database name, firewall settings (try disabling it).
Comment: Also sometimes restarting the machine helps... try that too.
Comment: @t.niese: MYSQL is running and also network is active for the MYSQL. I don't have idea regarding the socket file. Could you let me know how can I resolve it using socket files.
Comment: @idan Adar: I did tried restarting my machine but still not able to connect it.Could you guide me.
Comment: Double check the host (Try "localhost"...) port, database name, firewall settings (try disabling it).
Comment: @RahulSingh how did you check that mysql is running and that it is listening on on port `3306`? Please check it e.g. using `sudo lsof -i -P | grep -i "mysqld"` in terminal. If mysql is listening on a port, you should then see something like this: `mysqld             _mysql   36u  IPv4       0t0  TCP *:3306 (LISTEN)`  and on which `*:3306`
Comment: Yes, I get the following message.When Trying to run mysql(mysql=/usr/local/mysql/bin/mysql) command,I get the following error:`ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)`.How can I fix it.
Comment: @RahulSingh: Did you manage to solve this problem with the help of answers and comments in here? If so, could you close this question or provide a follow up, please?
Answer: See if the below helps:

Try "localhost" instead of "127.0.0.1".
When you connect to "localhost" the socket connector is used, but when you connect to "127.0.0.1" the TCP/IP connector is used (source).
From your error message in the question there seems to be some problem with the TCP/IP connection... so try "localhost" as well.
Based on the information pasted in the comments discussion in the question, you can try these solutions:

https://stackoverflow.com/questions/4788381/getting-cant-connect-through-socket-tmp-mysql-when-installing-mysql-on-m
Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
Mountain Lion: Can't connect to local MySQL server through socket '/tmp/mysql.sock'
Can't connect to local MySQL server through socket tmp/mysql.sock


Proving $\int_{0}^{\pi/2} \sin^{2}x\, dx = \int_{0}^{\pi/2} \cos^{2}x\, dx$ with substitution

Question:
Show that $\int_{0}^{\pi/2} \sin^{2}x\, dx = \int_{o}^{\pi/2} \cos^{2}x\, dx$ using the substitution $t=\frac{\pi}{2}-x$

My solution
$$\int_{0}^{\pi/2} \sin^{2}x\, dx$$
$$\int_{\pi/2-0}^{\pi/2-\pi/2} -\sin^{2}(\frac{\pi}{2}-t)\, dt$$
$$-\int_{0}^{\pi/2} -\sin^{2}(\frac{\pi}{2}-t)\, dt$$
$$\int_{0}^{\pi/2} \cos^{2}t\, dt$$
However, I don't know how to switch the integral back to be in terms of $x$ instead of $t$. The answer sheet shows the same steps I've taken, but the last one simply switches the $x$'s to $t$'s like this: $$\int_{0}^{\pi/2} \cos^{2}t\, dt=\int_{0}^{\pi/2} \cos^{2}x\, dx$$ But I don't understand how this switch can be done like that, shouldn't they switch back using $t=\frac{\pi}{2}-x$ instead of $t=x$.
I could understand changing the variables to some other, say $z$, but not $x$. I tried making the $t=\frac{\pi}{2}-x$ substitution but got nowhere: I either went back to $\sin^{2}x$ or nowhere.
How should I do the last step, that is how to switch back to $x$?
Comment: $t$ and $x$ are dummy variables: http://mathworld.wolfram.com/DummyVariable.html
Comment: It does not matter whether you use $t$, $x$, $z$ etc. as the variable of integration. Similar is the case with summations.
Comment: from where Comes the minus sign? $\sin(\frac{\pi}{2}-t)=\cos(t)$
Comment: Note that both the integrals are constants, and if  you approximated it, it doesn't matter what variable you use.
Comment: @Dr.SonnhardGraubner From the $dx/dt$
Answer: It does not matter what is the name of the integration variable, you can use any name you like, so
$$
\int_{x=a}^{x=b} f(x) \,dx = \int_{z=a}^{z=b} f(z) \,dz
$$
or any other letter of your choice...
Answer: Surprisingly, this sort of integral can be related to The Beta Function.
We start with, for any complex number $a$, where $\operatorname{Re}(a)>-1$,
$$S(a)=\int_0^{\pi/2}\sin^a(t)dt$$
The substitution $u=\sin^2t$ gives
$$S(a)=\frac12\int_0^1u^{\frac{a-1}2}(1-u)^{-1/2}du$$
Which we ignore for right now. What we do now is focus on
$$C(a)=\int_0^{\pi/2}\cos^a(t)dt$$
The same substitution of $u=\sin^2t$ gives
$$C(a)=\frac12\int_0^1 u^{-1/2}(1-u)^{\frac{a-1}2}du$$
At this point we recall that the Beta function is defined as
$$B(z_1,z_2)=\int_0^1t^{z_1-1}(1-t)^{z_2-1}dt$$
Of course, noting that $\frac{-1}2=\frac12-1$, and $\frac{a-1}2=\frac{a+1}2-1$, we have our integrals:
$$S(a)=\frac12 B\bigg(\frac{a+1}2,\frac12\bigg)$$
$$C(a)=\frac12 B\bigg(\frac12,\frac{a+1}2\bigg)$$
We then recall that
$$B(z_1,z_2)=\frac{\Gamma(z_1)\Gamma(z_2)}{\Gamma(z_1+z_2)}$$
With $\Gamma(s)$ being The Gamma Function
Next we note that
$$B(z_1,z_2)=\frac{\Gamma(z_1)\Gamma(z_2)}{\Gamma(z_1+z_2)}=\frac{\Gamma(z_2)\Gamma(z_1)}{\Gamma(z_2+z_1)}=B(z_2,z_1)$$
Plugging in $z_1=\frac{a+1}2$, and $z_2=\frac12$ gives our conclusion:
$$S(a)=C(a)$$
Answer: $t$ is dummy variable ,
put $x$ instead of $t$
$$\int_{0}^{\pi/2} \cos^{2}x\, dx$$


No Response on Google App Engine Java Blobstore Upload from Android

Question: I'm attempting to upload an image to the blobstore from Android but when my server servlet is called upon completion, the Blobstore fails to hand off any BlobKeys. And when I check the actual blobstore, no image has been uploaded. There is no error code, no warnings, no errors, nothing. Now I know the server stuff works because the upload works in iOS. And the Android code works just fine on the local development server but it's not working in production. I'm hoping that maybe someone can spot an error in my code.
Thanks in advance.
HttpURLConnection connection = null;

    try {

        Log.d(LOG_TAG, "Starting multipart POST request to: " +fullUrlValue);

        URL fullUrl = new URL(fullUrlValue);

        //make server call
        connection = getClient().getConnection(fullUrl, RequestMethod.POST);
        connection.setConnectTimeout(60000); //60 seconds to complete an upload
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //see if we are streaming the upload
        if(requestOptions == null || requestOptions.isChunckedStreamingMode())
        {
            connection.setChunkedStreamingMode(2048);
        }

        String boundry = "z6fQbdm2TTgLwPQj9u1HjAM25z9AJuGSx7WG9dnD";

        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundry);

        //attach post objects
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

        //add form fields
        if(additionalParameters != null && additionalParameters.keySet().size() > 0)
        {
            Iterator<String> it = additionalParameters.keySet().iterator();
            while(it.hasNext())
            {
                String fieldName = it.next();
                if(fieldName != null)
                {
                    String value = additionalParameters.get(fieldName);
                    if(value != null)
                    {
                        //add form field to upload form
                        outputStream.writeBytes("--" + boundry + "\r\n" + "Content-Disposition: form-data; name=\"" + fieldName + "\"\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n"+value+"\r\n");
                    }
                }
            }
        }

        //attach file
        if(postObjectBytes != null)
        {
            //build the request body
            outputStream.writeBytes("--" + boundry + "\r\n" + "Content-Disposition: form-data; name=\"" + formElementName + "\";filename=\"" + fileName + "\"\r\n\r\n");

            //object upload content size
            long totalUploadSize = postObjectBytes.length;

            //we have to manually process the stream in order to correctly update the progress listener
            byte[] buffer = new byte[2048];
            long totalBytes = 0;
            int bytesRead = 0;

            InputStream inputStream = new ByteArrayInputStream(postObjectBytes);

            while ((bytesRead = inputStream.read(buffer)) > -1) {
                totalBytes += bytesRead;
                outputStream.write(buffer, 0, bytesRead);

                if(progressListener != null){
                    progressListener.transferred(totalBytes, totalUploadSize);
                }
            }

            outputStream.writeBytes("\r\n--" + boundry + "--\r\n");

        }

        outputStream.flush();
        outputStream.close();

Answer: Well, I found the answer thanks to AppEngine BlobStore upload failing with a request that works in the Development Environment .
Apparently I was missing a space between the semi-colon and the start of "filename". That's just insane.
formElementName + "\";filename


Least common multiple for integer matrices

Question: Given two full-rank $3\times3$ integer matrices $M_1$ and $M_2$, I am trying to find integer matrices $N_1$ and $N_2$ such that $M_1N_1$=$M_2N_2$, such that $\left|\det(M_1N_1)\right|$ is minimal.
edit: The $N_i$ are only required to within a similarity transformation (i.e., $\tilde{N}_i\sim U_iN_iV_i$, where $U_i$ and $V_i$ are unimodular integer matrices).
This seems analogous to finding the "least common multiple" of two integer matrices, but I'm having trouble identifying an algorithm or matrix decomposition that helps me.
I'm aware of the relationship of this problem to ring theory, in that the columns of the "LCM" matrix that I'm looking for generate the ideals formed by the intersection of the ideals generated by $M_1$ and $M_2$. I'm not very familiar with ring theory, but I tried rewriting the problem in terms of the Smith normal forms of $M_1$ and $M_2$, which didn't get me much closer to a solution.
Just for context, my ultimate goal is to find the (crystallographic) lattice formed by the coincident points of two other lattices (described by the lattice vectors $L_1=LM_1$ and $L_2=LM_2$).
Comment: if unimodular means "with determinant 1" then det$(M_1N_1)=$det$M_1$ always and...
Comment: if you drop the unimodular requirement, then the problem becames possible and the cofactor matrix help
Comment: Sorry if that was unclear-- $N_i$ is similar (for my purposes) to any $\tilde{N}_i=N_i U$, where $U$ is unimodular. $\det(M_1N_1)\ge lcm(\det(M_1)\det(M_2))$, and det(M_1) may be different from $\det(M_2)$
Comment: ok. As I said, the matrix of cofactors does not solve a priori, but gives you a $N_1=\det M_2 Id$, which is optimal if det$M_1$ and det$M_2$ are coprime. For the general answer I don'tn know
Comment: do you require $N_i$ invertible?
Answer: This is only a partial answer. (I assume you want $N_1$ and $N_2$ invertible, otherwise $N_1=0$ solves)
Given $M$ its matrix of cofactors $\mathrm{Cof}(M)$ (see for instance here) is such that
$\mathrm{Cof}(M)=M^{-1}\det M$. As $\mathrm{Cof}(M)$ is made by minors of $M$ if $M$ is integer then $\mathrm{Cof}(M)$ is.
If $M_2N_2=M_1N_1$ we have
$$N_2=\frac{\mathrm{Cof}(M_2)M_1}{\det M_2}N_1$$
This is computable. Reduce  so that
$\frac{\mathrm{Cof}(M_2)M_1}{\det M_2}=A/n$ where $A$ is integer. Then we have $$\det N_2=\frac{\det A}{n^3}\det(N_1)$$
If $\frac{\det A}{n^3}$ is reduced, then you must have $\det N_1\geq n^3$ and $nId$ solves.
In general this reduces the problem to solve
$$\frac{A}{n}N_1$$
integer with $|\det N_1|$ minimal.
Comment: $N_i$ don't have to be invertible on $\mathbb{Z}$ (which would require unimodularity), but they can't be indeterminate. Now that I think about it, the $M_i$ can also be right-multiplied by unimodular matrices $V_i$, so I can reduce your expression via $N_2=\frac{V^{-1}_2AV_1}{n} N_1$, which means I can choose $V_2$ and $V_1$ to form the Smith normal form of $A$ ($A=V_2 S V^{-1}_1$, with $S$ diagonal), From there I should be able to find an optimal solution in all cases.  Sorry, I don't have enough reputation yet to vote your answer up.
Comment: Alright, I think I found the optimal solution:
Taking the Smith normal form of $A=BST$, where $B$ and $T$ are unimodular and $S$ is diagonal (and $S(i,i)\mid S(i+1,i+1))$, an optimal solution can be constructed as $N_1=T^{-1}R$, where $R$ is diagonal with entries $R(i,i)=n/\mathrm{gcd}(S(i,i),n)$.  Then $N_2=BSR$, and $\det(N_2)$ is minimized.  I'm not sure what the protocol is for editing answers, so I'll leave this as a comment.
Comment: just click on "Post your answer" and use LaTeX for formulas, there is no particular protocol. you may want to read the help center http://math.stackexchange.com/help/answering
Answer: As mentioned in the last paragraph of the question, the least common multiple (LCM) of $3\times 3$ matrices $M_1$ and $M_2$ is a $3\times 3$ matrix $M'$ such that
$$\mathcal L(M')=\mathcal L(M_1)\cap\mathcal L(M_2),$$
where $\mathcal L(M)=\{ M\mathbf k:\mathbf k\in\mathbb Z^d\}$ is the lattice generated by the $d$ columns of $M$. In lattice theory, if the columns of $M$ are linearly independent, we say they form a $\mathbb Z$-basis of $\mathcal L(M)$. In this question, finding $M'$ is equivalent to finding a basis of $\mathcal L(M_1)\cap\mathcal L(M_2)$, which has been solved in the question Basis for the intersection of two integer lattices. Accordingly, I shall briefly describe how to compute the LCM of two integer matrices $M_1,M_2$.
Given a lattice $\mathcal L$, we define its dual lattice as
$$\mathcal L^\wedge=\{\mathbf v:\forall\mathbf w\in\mathcal L,\left<\mathbf v,\mathbf w\right>\in\mathbb Z\},$$
where $\left<\cdot,\cdot\right>$ stands for inner product. If $M$ is a basis of $\mathcal L(M)$, we have
$$\begin{aligned}
\mathcal L(M)^\wedge
&=\{\mathbf v:\forall\mathbf k\in\mathbb Z^d,\left<\mathbf v,M\mathbf k\right>\in\mathbb Z\}
\\&=\{\mathbf v:\forall\mathbf k\in\mathbb Z^d,\left<M^\text T\mathbf v,\mathbf k\right>\in\mathbb Z\}
\\&=\{\mathbf v:M^\text T\mathbf v\in\mathbb Z^d\}
\\&=\{(M^\text T)^{-1}\mathbf k:\mathbf k\in\mathbb Z^d\}
.\end{aligned}$$
Hence, $(M^\text T)^{-1}$ is a basis of $\mathcal L(M)^\wedge$. We can see that $(\mathcal L^\wedge)^\wedge=\mathcal L$ since $(((M^\text T)^{-1})^\text T)^{-1}=M$.
Given two lattices $\mathcal L(M_1),\mathcal L(M_2)$, denote
$$\mathcal L([M_1|M_2])=\{\mathbf v_1+\mathbf v_2:\mathbf v_1\in\mathcal L(M_1),\mathbf v_2\in\mathcal L(M_2)\},$$
which is generated by the columns of $M_1$ and $M_2$. Note that
$$\begin{aligned}
\mathcal L([M_1|M_2])^\wedge
&=\{\mathbf v:\forall \mathbf w\in\mathcal L([M_1|M_2]),\left<\mathbf v,\mathbf w\right>\in\mathbb Z\}
\\&=\{\mathbf v:\forall\mathbf w_1\in\mathcal L(M_1),\forall\mathbf w_2\in\mathcal L(M_2),\;\left<\mathbf v,\mathbf w_1+\mathbf w_2\right>\in\mathbb Z\}
\\&=\{\mathbf v:\forall\mathbf w_1\in\mathcal L(M_1),\left<\mathbf v,\mathbf w_1\right>\in\mathbb Z,\;\forall\mathbf w_2\in\mathcal L(M_2),\left<\mathbf v,\mathbf w_2\right>\in\mathbb Z\}
\\&=\mathcal L(M_1)^\wedge\cap\mathcal L(M_2)^\wedge
.\end{aligned}$$
An immediate corollary is
$$\begin{aligned}
\mathcal L(M_1)\cap\mathcal L(M_2)
&=(\mathcal L(M_1)^\wedge)^\wedge\cap(\mathcal L(M_2)^\wedge)^\wedge
\\&=\mathcal L([(M_1^\text T)^{-1}|(M_2^\text T)^{-1}])^\wedge
.\end{aligned}$$
The $3\times 6$ matrix $[(M_1^\text T)^{-1}|(M_2^\text T)^{-1}]$ can be turned into its Hermite normal form (HNF) via elementary column operations over $\mathbb Z$. In other words, we have
$$[(M_1^\text T)^{-1}|(M_2^\text T)^{-1}]=[H|\mathbf 0_{3\times 3}]U,$$
where $U\in\operatorname{GL}(6,\mathbb Z)$, and $H$ is a $3\times 3$ matrix whose columns form a basis of $\mathcal L([(M_1^\text T)^{-1}|(M_2^\text T)^{-1}])$. Therefore we obtain
$$\mathcal L(M_1)\cap\mathcal L(M_2)=\mathcal L((H^\text T)^{-1}).$$
So far, we see that $(H^\text T)^{-1}$ is a choice of $M_1N_1=M_2N_2$ such that $\left|\det(M_1N_1)\right|$ is minimal, since a basis of a lattice has the minimal nonzero absolute value of determinant, i.e., a primitive cell has the minimal nonzero volume.


How to record a successful Google+ share

Question: I have a google+ share link that someone can click to share (on their own stream) a url specified by the rails app (not the current page).
I want to be able to record if the link was clicked and successfully shared. Here is the google+ share link code I'm using

I know it can be done with the Twitter api:

But is there a way to do it with Google+
Answer: You cannot confirm if someone shared a post to their stream using the Share widget parameters or the JavaScript API. Niraj's answer is flawed and does not work, see this JSBin to try it.
In some situations, you can surround the widget with a div that you track the clicks on that div, but that too doesn't work.
The one option that might work though it definitely won't work all the time given that the majority of user's on Google+ don't share most of their posts publicly is that you could use the REST API's activities.search method and pass the URL that you're interested in as the search parameter, but you're not going to necessarily know that this particular user shared it, or it might be private, and depending on how popular your site is you might have to page through many pages of results possibly without luck.
Answer: It's possible to track a click on the button, but not the share itself. If you use the Google+ Web Share button, you can do something like the following:

The button has the data-onclick="trackShare" attribute set, which calls a JavaScript function to trigger logging.
The console.log( jsonParam ) in the trackShare function will return something like:
{
  "id": target URL,
  "type": hover|confirm
}

However, in my testing, it only ever returns type: hover, even if it was shared successfully.


Not able to focus on element in grid without clicking using Selenium C#

Question: I am automating a Grid in Shadow-Dom, my scenario is to get all the rows of the grid, grid is dynamic and i need to scroll. However when i am changing my focus on grid i am clicking on first row of grid this will open the new page. I there any way to bring focus on to grid without clicking so that i can scroll to the end?
Already used
ClickElement(element);
action.MoveToElement(GetElement(element)).SendKeys(pagingKey).Perform();

Comment: You can do it with js script
Answer: Scroll into view
var js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].scrollIntoView({block: \"center\", inline: \"center\"});", webElement);


Nowhere dense sets

Question: İ studied the definition of nowhere dense set and I really can't understand it very well is there simple explanation of the definition and the two following questions.
A set  is nowhere dense if  (the closure of  it ) contains no nonempty open ball.
Let  $
{(}{X}{,}\mathit{\rho}{)}
$
be metric space
1)Show that the complementary of nowhere dense set is every where dense.
is the converse is right ? Give an example.
2)on the same metric space .Show that the closure of nowhere dense set is nowhere dense too .
Comment: You wrote: "A set is nowhere dense if (the closure of it) contains no nonempty open INTERVALS." What is an "interval" in a metric space? Are you sure your question isn't just about nowhere dense subsets of the real line?
Comment: Part (2) seems easy. A set $A$ is nowhere dense if the closure of $A$ has some property. OK, then the closure of $A$ is nowhere dense of the closure of the closure of $A$ has that property. How is the closure of the closure of $A$ related to the closure of $A$?
Answer: Just write down the definitions, and write down their negations.
A set $A$ in a metrix space $(X,d)$ is nowhere dense if the closure of $A$
has empty interior, that is, equivalently - its closure does not contain an open ball of the metric space.
A set $B$ is a metric space $(X,d)$ is everywhere dense if for every open set $O\subset X$, the intersection $B\cap O$ is not empty.
Consider now a set $A\subset X$. If the complement is not everywhere dense,
then there is some non-empty open set $O\subset X$ such that $O\cap A^c=\emptyset$. It follows that $O\subset A$, and so $A$ has non-empty interior, hence its closure has non-empty interior, hence it is not nowhere dense. It follows that if $A$ is nowhere dense, then $A^c$ is everywhere dense.
As for the converse, the question is whether the complement of a dense set is nowhere dense. This is not true: Take the rational points in $[0,1]$, they are dense. Their complement is the set of irrationals, whose closure is $[0,1]$, so it is not nowhere dense.
The second question was already answered in the comments.
Comment: Really thanks  a lot ....(^__^)

Nowhere dense sets


If $\lim_{n\rightarrow \infty}a_{n} = 0$, then $ \lim_{n\rightarrow \infty}\frac{a_{1}+a_{2}+\cdots+a_{n}}{\sqrt{n(n+1)}} =$

Question: Let $\langle a_{n}\rangle$ be a sequence such that $\displaystyle\lim_{n\rightarrow \infty}a_{n} = 0$, Then $\displaystyle \lim_{n\rightarrow \infty}\frac{a_{1}+a_{2}+\cdots+a_{n}}{\sqrt{n(n+1)}} = $
$\bf{My\; Try:}$ I have assume $\displaystyle a_{n} = \frac{1}{n}$, Then $\displaystyle a_{1}+a_{2}+\cdots+a_{n} = 1+\frac{1}{2}+\frac{1}{3}+\cdots+\frac{1}{n}$
Now I did not understand how can I solve it.
Answer given as $ = 1$.
Help me. Thanks.
Comment: The answer is not $1$. All the $a_i$ can vanish.
Answer: First notice that $$\lim_{n\to\infty} \frac{a_1 + a_2 + \cdots + a_n}{\sqrt{n(n+1)}}$$ can be compared to $$\lim_{n\to\infty}\frac{a_1 + a_2 + \cdots + a_n}{n}$$ by means of: $$\lim_{n\to\infty} \left(\frac{a_1 + a_2 + \cdots + a_n}{\sqrt{n(n+1)}}\right) \left( \frac{n}{a_1 + a_2 + \cdots + a_n} \right) = 1$$
Which means that if $$\lim_{n\to\infty}\frac{a_1 + a_2 + \cdots + a_n}{n}$$ converges to zero, then the first limit must converge to zero as well, since otherwise the limit would diverge. Finally this last sequence converges to the same limit as $\lim_{n\to\infty} a_n$. This is a standard exercise in Real Analysis.
Answer: Since $\lim_{n\to\infty}a_{n}=0$ then for $\epsilon>0$ we can find $N$ large enough that for $n\ge N$ we have $\lvert a_{n}\rvert<\epsilon$. So if we choose M large we can say the following:
$$ \begin{aligned}
\left|\frac{a_{1}+...+a_{N}+a_{N+1}+...+a_{N+M}}{\sqrt{(N+M)(N+M+1)}}\right|  & =\left|\frac{a_{1}+...+a_{N}}{\sqrt{(N+M)(N+M+1)}}+\frac{a_{N+1}+...+a_{N+M}}{\sqrt{(N+M)(N+M+1)}}\right| \\
& \le\left|\frac{a_{1}+...+a_{N}}{\sqrt{(N+M)(N+M+1)}}\right|+\frac{\lvert a_{N+1}\rvert+...+\lvert a_{N+M}\rvert}{\sqrt{(N+M)(N+M+1)}}\\
&<\frac{\epsilon}{2}+\frac{M\epsilon}{\sqrt{(N+M)(N+M+1)}} \\
& =\frac{\epsilon}{2}+\frac{\epsilon}{\sqrt{(\frac{N}{M}+1)(\frac{N+1}{M}+1)}}<\frac{3}{2}\epsilon\\
\end{aligned}$$
Answer: Hint:
Part 1: Prove that if $a_n \to 0$ then
$$ \frac{1}{n}\sum_{k=1}^n a_k \to 0$$
You might want to check out Cesaro sums.
Part 2:
$$ 0 \leq \left| \frac{1}{\sqrt{n(n+1)}}\sum_{k=1}^n a_k \right| \leq \left|\frac{1}{n}\sum_{k=1}^n a_k\right|$$
QED
PS: The answer is not 1.
Comment: Be careful here. If the sum of the $a_k$'s is negative, the inequality is false.
Comment: You can correct this by placing absolute values around your sums $$0\le \left| \frac{1}{\sqrt{n(n+1)}} \sum_{k=1}^n a_k \right| = \frac{1}{\sqrt{n(n+1)}} \left|  \sum_{k=1}^n a_k \right| \le \left| \frac{1}{n} \sum_{k=1}^n a_k \right|$$
Comment: Forgot to add the ||. Thanks for the correction. I have made the necessary changes.
Comment: Usually that doesn't work, but in this case since the constant is positive and not inside of the sum, it is ok.


Cycle structure of the permutation $x \mapsto p·x\operatorname{mod}q$ for coprime $p,q$

Question: Let $[q] = \{0,\dots,q-1\}$, $p < q$.
Consider the function $\mathbf{p}: [q] \rightarrow [q]$ which sends $x \mapsto p·x\operatorname{mod}q$, i.e. the multiplication by $p$ modulo $q$ on $[q]$.
One finds that when $p$ and $q$ are coprime, $\mathbf{p}$ is a permutation of $[q]$ with $\mathbf{p}(0) = 0$.
Each such permutation – depending solely on $p$ and $q$ – has a specific cycle spectrum: $n_m$ cycles of length $m$.

How do I calculate the possible cycle lengths $m$ and their
  corresponding numbers $n_m$ just by looking at $p$ and $q$?
Answer: Let $H_q = \{ p^n \bmod q,n \ge 0\}$, it contains $|H_q| = $ "the order of $p\bmod q$" elements.

Assume $\gcd(a,q)=1$ then $a \in (\mathbb{Z}/q\mathbb{Z})^\times$ so $|aH_q| = |H_q|$
Otherwise let $g = \gcd(a,q)$. Then $\frac{a}{g} \in (\mathbb{Z}/q\mathbb{Z})^\times$ and $|a H_q|= |g \frac{a}{g} H_q|=|g H_q| = |g H_{\frac{q}{g}}| = |H_{\frac{q}{g}}|$
Thus for each $d = \frac{q}{g} | q$ there are $\frac{\varphi(d)}{|H_{d}|}$ cycles of length $|H_{d}| = $ the order of $p \bmod d$
To know the order of each $p \bmod d$, you can factorize $q = \prod_j p_j^{e_j}$ and compute the order of $p \bmod p_j^m,m \le e_j$, then $|H_{\prod_j p_j^{m_j}}|$ is the $lcm$ of the $|H_{p_j^{m_j}}|$
Comment: Would you mind to help me to align your answer with the special case 49:243 as depicted in my question? (It's not too obvious how to start off.)
Comment: https://www.wolframalpha.com/input/?i=Table%5B%7B3%5En,MultiplicativeOrder%5B+49,3%5En%5D%7D,%7Bn,0,5%7D%5D and $\varphi(3^n) = 2.3^{n-1}$ @HansStricker
Comment: This looks promising, but (i) What does $2.3^{n-1}$ mean? Should it be $2\cdot 3^{n-1}$? and (ii) I'm looking for an expression with a variable which I can set to $243$. (Actually I see only a variable which I can set to $49$. And $243$ comes only in the result.)
Comment: $3^n$ are the divisors of $243$ and $\varphi$ is the Euler totient. Do you understand how multiplication by 49 acts on the group of integers coprime with $243$ ? @HansStricker
Comment: I know the symbol and meaning of the Euler totient. And now I see: $3^1 = 3$, $3^2=9$, $3^3 = 27$, $3^4 = 81$, $3^5 = 243$ are exactly the divisors of $243$. That's interesting enough, I was not aware of.
Comment: To make it explicit: My question did concern how multiplication by $49$ mod $243$ acts on the set of integers $< 243$ - not on the group of integers coprime with $243$. But maybe it's the same?
Comment: Finally I got it: $\phi(243) = \phi(3^5) = 162 = 2\cdot 81 = 2\cdot 3^4$. That's really crazy. But: It's only a special case. What's the general lesson to learn?
Comment: What about the general case $\phi(p^q)$ - assuming or not that $p,q$ are prime or coprime? Nothing like $\phi(p^q) = (p-1)\cdot p^{q-1}$ will hold, or does it? (If so, it would be the greatest miracle of all times.)
Comment: @HansStricker I treated those coprime to $243$ in the first bullet : multiplication by $49 \bmod 243$ permute those in $\frac{2 . 3^4}{81}$ cycles of length $81$. Why 81 ? Because that's what wolframalpha told for the order of $49 \bmod 243$. The next step is to apply the same reasoning to those of the form $g b$ with $g | 243$ and $b$ coprime to $243/g$
Comment: To be sure and explicit: you prefer to write $2.3^n$ instead of $2\cdot 3^n$? It's OK, but I want to be sure.
Comment: Maybe you want to have a look at some visual examples in my answer below.
Answer: Having digested and finally understood user reuns' answer, let me share some visual examples:


How to prepare my data for SVM classifier in matlab

Question: I am new to SVM and Matlab. I would like to have an example how to prepare my data to be as input to the SVM classifer (using libsvm)
let us assume that i have a group of words
first i have extracted some attributes such as bigram and trigrams (Average Jaccard index) and I wanted to input these values to a classifier in order to classify them
I know that i have first to train my classifier with initial data (labled) I have these data
60000 words from dictionary and 40000 other terms
while I generate 100000 random strings
now i want to classify if the new words are random or not
I have calculated the Jaccard index for each one and also i have calculated some other features such as number of characters and number and some other features.
now how I can convert these data to metrix ? I am a bit confused about the next step
Comment: See my question over there.. if need help i can provide code as well. http://stackoverflow.com/questions/10792576/libsvm-java-implementation
Answer: you can get the answer in LIBSVM Frequently Asked Questions http://www.csie.ntu.edu.tw/~cjlin/libsvm/faq.html#/Q03:_Data_preparation
Answer: This thread is a bit older, but as a new learner to SVM as well, did you ever find a good resource for how to prepare datasets for svm reg or classification?
Comment: This is not an answer to the question.


Power BI :: Some credentials aren't validated as they are set to skip test connection

Question: My problem is very easy: I'm retrieving all stocks about lithium on the ASX market from this web page.
I created a Power BI dashboard that you can visualize here.
As the source is Web I would like to refresh it every day using the Gateway connection, so I have successfully installed it on my computer that I turn on every day:

The problem is that instead of a successful daily refresh I have a daily error:
Failed to test the connection to your data source. Please retry your credentials.
Some credentials aren't validated as they are set to skip test connection.

If I enter in the Edit credentials I see the error:
Failed to update data source credentials: The credentials provided for the Web source are invalid. (Source at https://www.marketindex.com.au/commodities/lithium.)Show details

This because I'm using Authentication method: Anonymous and Privacy level setting for this data source: Public. But this is exactly what I'm using on Power BI desktop and it's working!

What am I doing wrong here?
Why the same connection is working fine on Power BI Desktop but not the same dashboard uploaded online?
EDIT: the On-premises data gateway looks installed without problems
Comment: This is exactly what I'm looking for @MattKocak . How can I implement such thing?
Comment: I posted the solution. Let me know if anything is unclear or doesn't work and I can update it.
Answer: It seems like the issues you're experiencing may be caused by the link you're using (https://www.marketindex.com.au/commodities/lithium), although I'm not sure exactly why.
For example, as has been mentioned in the Do I Need a Gateway for Web post, one can use Web.Contents instead of Web.BrowserContents in the raw M code in the Power Query Editor to avoid using a gateway. However, when I test this implementation using the link that you provide, I get an error when refreshing from Power BI online.

If I test this implementation using an HTML table from the https://tradingeconomics.com/commodity/lithium website, though, and set the data source credentials as follows, then I am able to successfully refresh the dataset from Power BI online.

I tested this with another HTML table from a random webpage and an online refresh worked as well. So it seems like there is something odd about how Power BI online interacts with the Market Index website and this is causing your issue. Potentially because of some authentication configuration on the Market Index side of things? I'm not able to help with looking further into why this is occurring, though.
Would you be able to use a different website with similar information as a data source for your report? If so, you could avoid the issues you're experiencing and avoid using a gateway in general if you wanted.
If you go this route, it seems like using the included "Scheduled refresh" setup in Power BI online works, but I will include the Power Automate scheduled refresh setup below in case this is desired instead.
Power Automate Scheduled Refresh
One can use Power Automate to "schedule" dataset refreshes instead of the included "Scheduled refresh" functionality in Power BI online. The steps are a little too long to include here, but the Refresh your Power BI dataset using Microsoft Flow article outlines the process on setting this up. There are various triggers that you can use to trigger your flow. The linked article uses one that triggers based on a SharePoint action, but there is a Recurrence trigger that can be used to trigger your flow at regular intervals/times.

Just set up your flow, make sure that it is "turned on", and your dataset will refresh at regular intervals from the cloud.
Comment: After some more investigation, it seems like there was an update a few years ago where web connections do generally need a gateway. It seems like this could be avoided by using Web.Content instead of Web.BrowserContent in the M code. I will update the solution after I test this out.
Comment: I did some additional investigation and updated my solution to provide my results. It seems like it is a problem with the website that you're using as a data source.
Comment: I still cannot believe that Power BI has no built in automation for this and we have to use Flow. Absurd!
Comment: I tested the flow, it's not working. The Flow is successful but the data are still those of yesterday. I did it multiple times
Comment: The problem is not at Flow level but at Power BI: even if I click refresh from Power BI the dataset is not updated: https://snipboard.io/sfD3ER.jpg
Comment: If I click onto the error in Power Bi it's still asking for the data gateway: https://snipboard.io/56Zd0o.jpg
So the data gateway is still at the core of the refresh and even the manual refresh is not working.
Comment: It's odd that a gateway is required for this web connection. I will look into this. In the meantime, I found the following workaround to avoid a gateway https://community.powerbi.com/t5/Power-Query/WORKAROUND-How-to-use-scheduled-refresh-of-a-web-page-without/m-p/1434043#M44835
Comment: Good investigation. However that solution was already suggested here: https://stackoverflow.com/questions/72235312/power-bi-do-i-need-a-gateway-connection-when-importing-data-from-a-web-page .
I didn't checked if it worked because changing from `Web.BrowserContent` to `Web.Content` was breaking the table import. Let me know if this works for you, my previous dashboards was more complex so it might work. But damn Microsoft, this was supposed to be easier!
Comment: Today I also tested the use of `parameters` like in this example: https://learn.microsoft.com/en-us/power-bi/connect-data/incremental-refresh-configure . I now can see the parameters on my Power BI online dataset but they look like a variable I have appended there and there are no instruction about how to use them. But apparently this is one of the things that will allow you to use the scheduled refresh that Power BI propose out-of-the-box. This is also the reason why a manual refresh doesn't work, because we need parameters....
Mind-blowing how difficult this can be...
Comment: Thank you for testing. I tested too using HTML as source but my Data source credentials are grayed out:  https://snipboard.io/4cvEsd.jpg .
Comment: I also tested with the NBA ranging page https://www.nba.com/standings and it's the same. Do you have any page that I can use as test?
Comment: Hmm I haven't experienced the grayed out Data source credentials that you are describing. It worked fine for me with the Trading Economics link that I mention in the solution. But it seems like some other users have experienced this issue. Maybe specifically turning your gateway off would resolve the issue? https://community.powerbi.com/t5/Service/Data-Source-Credentials-Greyed-out/m-p/519216
Comment: Naah, there is no way to turn it ON/OFF https://snipboard.io/qsoi7b.jpg . Probably the greyed filed will be available once I install the gateway on an always on server somewhere. Anyway, thank you @Matt for your help. The bottom line is that setting up an easy refresh is not easy at all and the gateway path is probably the only one.
Answer: May this helps -
Go to Options and Settings >> Data source settings >> edit permissions >> organization level. Save your changes.
Then go to powerbi.com, and update the data source credentials.


React-native Routing (single page application)

Question: I am so much confused between react-native routing. I am new to react-native and i never worked on React.js.I want to ask Is react native application is single page application architecture just like angularJs?  there is so many ways for routing and navigation in react-native like
1 .react-native-router-flux
2.Navigator
and many other ways . someone please tell me is this SPA architecture and what is best way for routing in react-native which have more support . I want to make a side drawer menu and tab menu in my app . please help me . thanks in advance
Answer: You need to be clear in the different technologies being used. ReactJS is for building single page web applications (similar to AngularJS). Where as React-Native is developed using the ReactJS framework but it's used for building Native mobile apps.
In React-Native there is actually no concept of Single page application as everything is developed as a component and these components are used for navigation & routing from one screen to another.
For routing react-native-router-flux is extremely simple and easy to use.
You can also check Nativebase https://nativebase.io for providing additional components for React native apps with extended functionality including Side Drawer menu and other components. You can also use React-native's inbuilt component Navigator if you are trying to build a navigation based app and customize it to either navigator or tab based app style.
Comment: what is native-redux can u guide me ? @Gurdev


How to detect in JavaScript if request made in getTileUrl (Google Maps) was successful or not?

Question: I am new to the community,
I have a simple google Map overlay, I get the tiles (format png) from an external service, example: https://example.tiles.com/
I need to monitor or some mechanism in JavaScript to track or detect successful, failed requests made by getTileUrl to the external service, I have searched the official documentation and found nothing.
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Map</title>
    <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />

I have tried with the tilesloaded listener but it does not support function arguments.
google.maps.event.addListenerOnce(gmap, 'tilesloaded', function(){
..
});

tilesloaded
What is wanted is simply to count the successful requests made to https://example.tiles.com/ by getTileUrl
Comment: Do you mean that you want to send an alert when the map loads?
Comment: What do you mean by "does not support parameters"?
Comment: - What is wanted is simply to count the successful requests made to https://example.tiles.com/ by getTileUrl, I mean that the tilesloaded event does not support arguments.
Comment: It's because it gets triggered when the Maps Javascript tiles gets loaded. Not the example.tiles.com.
Answer: I tried using the 'tilesloaded' and it worked for me using this:
google.maps.event.addListenerOnce(gmap, 'tilesloaded', function(){
alert("Tile is loaded!")
});

I just changed the first parameter map into gmap because that's how you defined the map instance on your code.
Here's a snippet for you to check if this is how you want it to happen:

let gmap;
function initMap() {
  gmap = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 44.9648, lng: -93.252},
    zoom: 5
  });

  const layers = new google.maps.ImageMapType({
    getTileUrl: function(coord, zoom) {
        return ['https://example.tiles.com/', zoom, '/', coord.x, '/', coord.y, '/current.png'].join('');
    },
    tileSize: new google.maps.Size(256, 256)
  });
  gmap.overlayMapTypes.push(layers);
  google.maps.event.addListenerOnce(gmap, 'tilesloaded', function(){
    alert("Tile is loaded!")
  });
};
#map {
  width: 600px;
  height: 500px;
 }
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Map</title>
    <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />

What happens here is when the tilesloaded is triggered, it will send an alert with text "Tile is Loaded!".
Hope this helps.


Is my xgboost model overfitting? (timeseries)

Question: I am very skeptical looking at this, I haven't used the xgboost library that much before, maybe someone can help me out. The errors and the predictions on my test set are too good to be true. I mean, I normally don't see this type of performance. Is there any thing I am overlooking here?
To reproduce:
library(xgboost)
library(caret)

m <- as.matrix(data)
k <- round(nrow(data)*0.95)
train <- m[1:k,]
test <- m[(k+1):nrow(data),]

m1_xgb <- xgboost(
  data = train[,2:ncol(train)],
  label = train[,1],
  nthread = 16,
  nrounds = 2000,
  objective = "reg:squarederror",
  early_stopping_rounds = 20,
  max_depth = 3,
  eta = .25, verbose = 2)

pred_xgb <- predict(m1_xgb, test[,2:ncol(test)])
yhat <- pred_xgb
y <- test[,1]

plot(y,yhat, xlab = "Actual",ylab = "Predicted",main = "Actual",col="steelblue");box();grid()
abline(lm(yhat ~ y),col="red")
postResample(yhat, y)

plot(y,type='l',col="red");box();grid()
lines(yhat,col="green")
legend(200, 95.8, legend=c("Actual", "Predicted"),
       col=c("red", "green"), lty=1:2, cex=0.8)

     RMSE  Rsquared       MAE
0.07043080 0.99728270 0.05669385

Comment: Well, in your data set, columns ``y`` and ``x1``, ``x2`` are almost perfectly correlated, so I'd start there..
Comment: Yes, the problem was with leaking `x1` and `x2` into the future, extremely noob mistake
Answer: Whenever performance is too good to be true, the big two suspects are usually

an improper training/validation/test-split (the typical problem is not splitting time-series as past vs. future: when you randomly select validation records ignoring time, the model only needs to interpolate rather than to learn to predict into the future), and
target leakage, where something in the predictors gives away the answer, but cannot be use in real-life for prediction (e.g. predicting death and using whether the date of death field is missing (or not) as a feature, calculating some feature using future values e.g. when interpolating missing values etc.).

It's hard to tell whether (2) could be occuring in your case, but assuming that your time series is ordered by time in the original data matrix m item (1) may not be the problem.
Why do I sound like I expect that there is a problem? Well, I find that when a model performance is too good to be true, it is very often one of these two things (rather than a surprisingly good model performance).
Comment: You're right with #2, some features were leaking