If a document set is too small for running a topic model, can you simply multiply the document set by a factor of 10 to be able to run the model?

Question: Say I'm using Top2Vec as a topic model to capture the top 10 salient topics across documents. I have an array that contains the documents of the corpus. Initially, there are not enough documents to run the Top2Vec. There sample size is enough to run LDA, though, and get usable results. If next I multiply the array by, say, a factor of 10, there would then be enough documents to run Top2Vec. If I were to multiply the array of documents by 100 or 1000 instead, would the results always be the same assuming each original document is repeated proportionally (and identically) in the resulting array? Is scaling up this way trivial in terms of results, or would it distort results in some way? This is only for comparing the results of both approaches.
Edit:
I realize that multiplying the array of documents will not generate any new information, but the model won't even run without expanding the array somehow. I just need to get a sense of what the results would look like if Top2Vec were run. This is for the purposes of comparison to another model that already does generate meaningful results on the unaltered sample size, without any augmentation. The combined length is already 200,000 words without multiplying of the set. The question is whether such a comparison would be fair. Since no new information is generated by multiplying the set, it seems to me that augmenting just to get Top2Vec to run should be fine (it's not like results would change anyway whether it was multiplied by a factor of 10 or 100 since no new info is being generated, right?). I'm trying to make sure I'm not mistaken in that thinking, for the purposes of comparison. Even if the quality of Top2Vec's results is low on that amount of raw information, that would still be okay to show in order to demonstrate why the first model may be more suitable. Am I missing something?
Comment: Well, you can try out if you get a result (I don't know Top2Vec), however the problem really is the limited amount of information in your data, and what you propose doesn't add information. So even if you get a result, chances are this will be of low quality (or let's say the quality that your limited amount of documents will allow).
Comment: Out of interest, how many documents do you actually have?
Answer: Definitely not.

Initially, there are not enough documents to run the topic model.

This means that the number of documents you have does not provide enough information to generate a meaningful topic model. Duplicating documents to make the list of documents longer doesn't add any information, so does not solve the problem. In real life, a library with 10 copies of the same 5 books doesn't contain any more information than a library with 1 copy each.
The more interesting question is - why are you trying to run a topic model at all? If you only have a small number of documents, does it make more sense to just generate summaries of each (e.g. with GPT), rather than trying to force them into clusters?
Comment: Neither method is viable at this sample size, so you're truly better off with manual analysis. The value of statistical methods is characterizing uncertainty and aggregating over unreasonably large data. The error bars here would be so huge as to be uninformative, and this isn't so huge that you need computation anyway. (Look up "small-N studies".) Re: Top2Vec, just because it doesn't give uncertainty estimates doesn't make it better: you just don't know how uncertain it is! Using tools wrong to torture a number (or topic list) out of them isn't something anyone should ask of you.
Comment: Thanks for the reply. Of course, no new information will be added and the goal, believe it or not, isn't to get a usable result. I was asked to compare the results of Top2Vec on the sample with another model that can generate meaningful results on the small sample size. Even if the results are not usable from Top2Vec, I need to know if multiplying the sample set just to get it to run is bad practice, if only to be able to show what the results would look like. Note that Top2Vec will not even run without multiplying the array by at least a factor of 10.
Comment: Thanks. If it helps to know, the first method seems viable on the sample size (which already has over 200,000 words in combined length unaltered). The first method yields very usable and meaningful results. Even if Top2Vec doesn't yield meaningful results, that would be okay to show. I just need to know if multiplying the corpus to get Top2Vec to even run (it won't without any augmentation) makes the comparison meaningless
Comment: P.S even if it's just to show why Top2Vec is not suitable


How to solve the system of equations?

Question: How can I solve this system of equations? (without using any software of course)
$$\ e^{-y} \cos(x)= \frac{5 \pm3}{4}  \quad\text{and}\quad\ e^{-y} \sin(x)=0$$
Comment: Note that $e^{-y} > 0$ for all $y$.  Thus $e^{-y}\sin(x)=0$ only when $\sin(x)=0$.
Comment: therefore I'll know all the values that x can take? and with Alex's hits the y values. right?
Comment: Yes; once you find the solution values you need to double-check that $\cos x>0$ for your solutions (because squaring may give you extraneous solutions).
Answer: Hint: square each equation and add them together. This will eliminate $x$ because $\sin^2 x + \cos^2 x = 1. $

How to solve the system of equations?


Finding change over time from a table in R - fitting a model to the data

Question: this is the table that has the information, it is much larger but I have just included a small part of it
Part 1 : (solved) This might seem quite easy, but I am very stuck on creating code to make a graph which shows the change over time. The table shows infant mortality and I just need a graph showing how the infant mortality of one country has changed over time.
Part 2 : how can I fit a line to the data - for example, for just one country? I need to model the data as a linear response. How can I do this?

my_data <- structure(list(`1800` = c("Afghanistan", "Albania", "Algeria",
"Andorra", "Angola", "Antigua and Barbuda", "Argentina", "Armenia",
"Australia", "Austria"), `1801` = c(469L, 375L, 460L, NA, 486L,
474L, 402L, 371L, 391L, 387L), `1802` = c(469L, 375L, 460L, NA,
486L, 470L, 402L, 371L, 391L, 373L), `1803` = c(469L, 375L, 460L,
NA, 486L, 466L, 402L, 370L, 391L, 359L), `1804` = c(469L, 375L,
460L, NA, 486L, 462L, 402L, 370L, 391L, 346L), `1805` = c(469L,
375L, 460L, NA, 486L, 458L, 402L, 369L, 391L, 333L), `1806` = c(469L,
375L, 460L, NA, 486L, 455L, 402L, 369L, 391L, 321L), `1807` = c(470L,
375L, 460L, NA, 486L, 451L, 402L, 368L, 391L, 309L), `1808` = c(470L,
375L, 460L, NA, 486L, 447L, 402L, 368L, 391L, 325L), `1809` = c(470L,
375L, 460L, NA, 486L, 444L, 402L, 367L, 391L, 316L)), row.names = c(NA,
10L), class = "data.frame")

Comment: Please use `dput` to show a small reproducible example
Comment: did that work - I tried to add a reproducible example
Comment: Perhaps you need a `matplot` `matplot(t('row.names<-'(as.matrix(my_data[-1]), my_data[[1]])), type = 'l')`
Comment: what exactly does that show? I'm confused
Comment: What is the time variable? The columns' names are 1800, 1801, ..., 1809. The data doesn't seem to have a time variable.
Comment: Those are years, I don't know exactly how to add a time variable but there are new values every year etc
Comment: I'm voting to close this question because it is not a question
Answer: You can plot what the question asks for with package ggplot2.
This type of problems generaly has to do with reshaping the data. The format should be the long format and the data is in wide format. See this post on how to reshape the data from long to wide format.
library(dplyr)
library(tidyr)
library(ggplot2)

my_data %>%
  rename(country = `1800`) %>%
  pivot_longer(
    cols = starts_with('18'),
    names_to = 'time',
    values_to = 'mortality'
  ) %>%
  mutate(time = as.numeric(time)) %>%
  ggplot(aes(time, mortality, color = country)) +
  geom_point() +
  geom_line()

Comment: it keeps saying that it cannot find function pivot_longer - is there a reason for this? Thanks for your help
Comment: @000elizah000 `pivot_longer` is a new function in package `tidyr`, introduced in version `1.0.0`. See what `packageVersion('tidyr')` gives, maybe it's time to update.
Answer: We can use matplot from base R
matplot(t('row.names<-'(as.matrix(my_data[-1]), my_data[[1]])),
          type = 'l', xaxt = 'n')
legend("top", my_data[[1]], col = seq_along(my_data[[1]]),
          fill = seq_along(my_data[[1]]))


Select previous/next nodes of same content type programmaticaly in Drupal 7

Question: there are modules out there for my problem, but they are not stable and also i need to be able to manipulate the result so here we go:
i need to provide a block on a certain node type which offers a previous and next link to cycle through the nodes of the same content type.
how can i select the previous and next node programmatically using db_query() and then output the links to them?
thanks in advance for your help
Answer: Clive is right.
But $prev_nid is looking for the first node in the table.
So you could add an ORDER BY, like this:
<code>$prev_nid = db_query("SELECT nid FROM {node} WHERE type = 'my_type' AND created < :created ORDER BY created DESC LIMIT 1", array(':created' => $node->created))->fetchField();
$next_nid = db_query("SELECT nid FROM {node} WHERE type = 'my_type' AND created > :created ORDER BY created LIMIT 1", array(':created' => $node->created))->fetchField();
</code>
Answer: You haven't provided any indication of the sort order you want so I'll guess at created date:
<code>$prev_nid = db_query("SELECT nid FROM {node} WHERE type = 'my_type' AND created < :created LIMIT 1", array(':created' => $current_node->created))->fetchField();
$next_nid = db_query("SELECT nid FROM {node} WHERE type = 'my_type' AND created > :created LIMIT 1", array(':created' => $current_node->created))->fetchField();

if ($prev_nid > 0) {
  $prev_link = l('Previous', "node/$prev_nid");
}

if ($next_nid > 0) {
  $next_link = l('Previous', "node/$next_nid");
}
</code>
You'll need a reference to <code>$current_node</code> (i.e. the node relating to the current page). There are dozens of places you could put this code so I'll let you decide on that, but if you want an easy way to grab the node object associated with the node page you're on use this:
<code>$current_node = menu_get_object();
if (isset($current_node->nid) && $current_nid > 0) {
  // We're on a node page and $current_node is a valid, loaded node object
}
</code>
Hope that helps
Comment: changed the code to suit my needs and am using it in my template.php now. you helped a lot, thanks!


Ember.js passing parameters from views to controller functions

Question: I have an Ember.js app as follows (borrowed from this article on andyMatthews.net):
View:

App:
App = Ember.Application.create();

App.UserTextField = Ember.TextField.extend({
    insertNewline: function(){
        var term = this.get('value');
        App.recentUsersArray.pushObject(term);
    }
});

App.recentUsersArray = Em.ArrayController.create({
    content: ['noelle', 'evan', 'mason'],
    reverse: function(){
        return this.get('content').toArray().reverse();
    }.property('content.@each').cacheable(),
});

But I'd like to pass a parameter to App.recentUsersArray.reverse from the view (for example, to set the number of reversed items to be returned).  I run into a problem because while you can accept the parameter on the controller function, it doesn't seem like you can pass it from the view.  I was imagining something like this if you wanted to pass the parameter 3 to the reverse function on the controller:
{{#each App.recentUsersArray.reverse(3) tagName="ul"}}

{{this}}

{{/each}}

but it throws an error (Uncaught Error: Parse error)...thoughts?  The ultimate goal would be to create three
's, each with a different number of elements without creating a different function for each length (i.e., App.recentUsersArray.reverseThree(), App.recentUsersArray.reverseFive(), etc. ). I also don't want to make three different controllers, because each of the
's should be using the same data source, just sliced up differently.
Comment: You have to read about how computed properties work before understanding why what you're asking for doesn't make sense.
Answer: Yes, Ember can come across as an odd paradigm. Maybe try:
App.recentUsersArray = Em.ArrayController.create({
  recentCount: 3
  content: ['noelle', 'evan', 'mason'],
  reverse: function(){
      var max = this.get('recentCount');
      return this.get('content').reverse().slice(0, max)
  }.property('content.@each', 'recentCount').cacheable(),
});

//some event handler
App.recentUsersArray.set('recentCount', count)

I don't think toArray() is necessary, plus the docs say it does not guarantee the order of elements returned:
http://docs.emberjs.com/#doc=Ember.Enumerable&method=.toArray&src=false


Unable to run update.php or update modules from web interface

Question: I would really like to be able to install module updates through the web interface or run update.php when needed without changing settings.php, but something seems to be broken in my setup because it tells me I am not authorized to do so when I try.
In all attempts to make this work, I am using UID1, which besides any special properties that user has, it is an administrator which has the "Administer software updates" permission. In settings.php I have: $settings['allow_authorize_operations'] = TRUE; set explicitly, but I have also tried it in the default, not set, state which is also TRUE.
If I set $settings['update_free_access'] = TRUE; then I can run update.php, but that doesn't seem to help with the module updates and I would rather not have to change that setting every time I need to do an update.
I have tried all of the usual things I have seen mentioned including:

Rebuild the user permissions
Cleared the session table in the db
Verified correct permissions on relevant files/directories
Looked through various server logs for any obvious failures

My first real clue came from looking at the log an noticing that the "access denied" entry is tied to the anonymous user instead of the user I was logged in as. I have tried digging through the code a bit to see if I could track down where it is losing track of my user, but I am in a little over my head at that point. Obviously, the authentication is working in general because I am able to log in the admin site and do most things.
Has anyone had any idea why Drupal would lose knowledge of the logged in user just while trying to do update type operations?
Version: Drupal 8.7.6
Note: I have looked a little more into the code to try to track down my problem. As seen from the logs, the problem is not that my user doesn't have permission but rather that when I run those specific actions, drupal momentarily doesn't see me as being logged in. In the file core\authorize.php there is a method that gets called: authorize_access_allowed(Request) which is mostly checking to see if the logged in user has the 'administer software updates' permission. In that method, it doesn't believe I am logged in. As far as I can tell, there are two ways it might pull the user out of that passed in Request (reading PHP_AUTH_USER out of the get headers or getting the UID out of a cookie). The get headers are definitely not there, and while there is a session cookie, it doesn't seem to be able to pull a UID out of it. I have not been able to find the code that parses the Session string.
Answer: update.php does not update modules. It updates the database state if needed (after installing module updates, aka db-update).
Did you check the permissions of your /modules/contrib/* filesystem? When you update your modules with the admin UI, your webserver's user (apache or www-run...) needs to have write permission there.
Did you install your instance with composer? If so, do not use the admin UI.
Maybe, check the docs again: https://www.drupal.org/docs/user_guide/en/security-update-module.html
Comment: I realize now my wording wasn't particularly clear, but I am aware that update.php is not related to modules. Those are two separate actions that appear to be broken for me in the same way.

Whatever my problem is, I don't think it is associated with file permissions. I have gone through all of the recommended permissions and confirmed they are correct.
This site was not installed using Composer. Without the web interface, I am not sure how to update modules. I can replace the files on the server, but presumably something needs to run within Drupal to actually install the updated module.


Is there an efficient formula for computing point halving on elliptic curves in $\operatorname{char}F=p\ne2$?

Question: Consider the elliptic curve in $F_p$ and let $n$ be the order of the group.

Suppose the curve is the same as bitcoin: $y^2 = x^3 + 7$, I have a point $P=(x,y)$,how to compute $\frac{1}{2}P$.

Suppose $P=aG$ for some base point $G$(we know the points $P,G$, but the coefficient $a$),then is there efficient method to compute $\lfloor\frac{a}{2}\rfloor$G
Comment: Can you give the point doubling formula for this curve?
Comment: Anyway, the answer to the second question is surely negative. For otherwise the DLP would be trivial :-)
Comment: There are researches on this [Quartic equations and 2-division on elliptic
curves](https://arxiv.org/pdf/0706.4379.pdf). Also, you can see this post [Point halving on elliptic curves of even order](https://crypto.stackexchange.com/q/66106/18298) on Cryptography.SE
Comment: What @Mummytheturkey said is, of course, correct. But in the crypto side, in characteristic two, there is something called "halve-and-add" -algorithm (in addition/contrast to the more common "double-and-add"). I don't remember the details, but it offered some advantage in some situation. Anyway, on an abelian group of odd order halving is a well-defined process :-)
Comment: More seriously, if the order of $G$ is an odd number $\ell=2k-1$, then $\frac12aG$ exists for all $a$. This is because $\frac12 G=kG$. And if the order is even then $\frac12P$ either does not exist, or it has two possible answers. Again killing this line of attack to the DLP.
Comment: If $p \equiv 2\bmod 3$ then every element of $F_p$ has a unique 3rd root so $\# E(F_p)= p+1$, if the order of $P$ is odd then $\frac{p+1}{2^m} P=O$ where $2^m$ is the largest power of $2$ dividing $p+1$ so that $P=2 R$ where $R= \frac{p+1+2^m}{2^{m+1}} P$.
Comment: It should be noted that this question is not quite well definied. The map $[2] : E \to E$ has degree $4$, hence there can be up to $4$ "halves" of $P \in E$ (and there are precisely $4$ if $K$ is algebraically closed)
Comment: Sorry, I don't have the time to look for an informative link [within a search](https://duckduckgo.com/?q=%22halve+and+add%22+elliptic&t=ffnt&ia=web).
Answer: Case $P = \lfloor \frac a 2 \rfloor G$;
As said in the comments if possible this can help to break the DLog.
Case $P = \frac a 2 G$;
We may expect that it has two solutions $$P =\frac{x}{2} \cdot G =\frac{x + q}{2} \cdot G$$, however, the base point $G$ of the bitcoin curve has odd order. Therefore
int("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16)
115792089237316195423570985008687907852837564279074904382605163141518161494337

Therefore if there exists half of a point then it is unique.

The derivative of the equation $y^2 = x^3 + 7$

$\lambda = \dfrac{3x^{2}}
    {2(x^{3}  + 7)^{1/2}} \tag{1} \label{1}$

Write down the equation for the tangent line to $E$ at G:

$$y-p_y = \lambda(x-p_1) => y = \lambda(x - p_x) + p_y \tag{2}$$

Write the equation for the intersection of the tangent line with E:

$$y^{2} = (\lambda(x - p_x) + p_y)^{2} = x^{3} + 7 \tag{3}\label{3}$$

Write down $\lambda$ in terms of $p_x$:
If we extend the equation \ref{3} we will get a monic cubic polynomial, so the coefficient of $x^2$ will be the minus the sum of the roots. Therefore, $p_x$ will be double and $g_x$ will be a single root.  $$(\lambda (x - p_x) + p_y)^{2} = x^{3} + 7$$ $$\lambda^2 (x - p_x)^2 + 2 \lambda (x - p_x) p_y + p_y = x^{3} + 7$$ as we can see the term for $x^2$ is $\lambda$. Since the roots are the intersection point then $p_x$ will be a double point and $g_x$ will be a single point, so $2 p_x + q_x = \lambda^2$ $$\lambda^2 = 2 p_x + q_x  \label{4}\tag{4}$$

Form equation using equation \ref{4} and and replacing $x$ with $p_x$ in the equation \ref{1};
$$\lambda^{2} = 2p_x + q_x  =  \dfrac{9p_x^{4}}{4(p_x^{3}  + 7)} \tag{5} \label{5}$$ Simplify this equation and move everything over to the left-hand side will yield  $$ (2p_x + q_x)(4(p_x^{\,3}  + 7))  =  9p_x^{\,4}\\ -p_x^4 + 4 p_x^3 q_x + 56 p_x + 28 q_x= 0$$  a quartic polynomial in $p_x$. The roots of this polynomial are the x-coordinates of the half points of $G$. We are in the odd case, the factors of the quartic polynomial will be a linear equation and an irreducible resolvent cubic.

Small, SageMath Validation;
#Secp256K1 prime
p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f
#Secp256K1 order
q =  115792089237316195423570985008687907852837564279074904382605163141518161494337
#One of the roots
t = 82764486716702815285605477501188164702466527314352175978120539775788537185277
print("Expected root ", t)

#define ring of polynomials
R.<x> = PolynomialRing(GF(p),'x')

# x-coordinate of Q where Q = [2]P
qx =  Integer(84538659774007663836420160802839342215744092791779235474817172502887599548487)

#From equation (5)
g = (2 *x + qx)*(4*(x^3+7)) - (3*x^2)^2

gRoots = g.roots()

print("The roots of quartic = ", gRoots)

gEvalAt_t = ((2 *t + qx)*(4*(t^3+7)) - (3*t^2)^2 ) % p

print( "gg(t) =", gEvalAt_t)

Outputs
Expected root  82764486716702815285605477501188164702466527314352175978120539775788537185277
The roots of quartic =  [(82764486716702815285605477501188164702466527314352175978120539775788537185277, 1)]
gg(t) = 0

Note: this result is similar to this article

Quartic equations and 2-division on elliptic
curves,  George H. Hitching, 2018


Dicrete Math Interesting question about Tromino

Question: Prove that for a m$\times$n rectangle, if this rectangle can be covered completely by trominoes of the shape indicated in the picture, then mn is divisible by 3.

I came up with a tentative way to prove the statement above. There are two problems that are bothering me, first, I am not sure if I've covered all the cases in my proof; second, I am guessing there will be a more elegant way to prove this. I'd appreciate if you can help!
Assume that 3 divides m. Suppose that n is even, we can partition the rectangle into 3$\times$2 blocks(the following graph indicates how this would be done.) Suppose n is odd, clearly we can't have n=1. If m is even, the first three columns of the rectangle may be partitioned into 2$\times$3 blocks while the remaining can be partitioned into 3$\times$2 blocks. Supppose m is odd, obviously, we can't have m=3, or n =3, since we can only pack a 3$\times$n rectangle by partitioning it into 3$\times$2 blocks. But that requires n to be even. If m$\geq$9 and n$\geq$5, the first five columns of the first nine rows consist of a 9$\times$5 block(indicated below).

The remaining columns of these rows are partitioned into 3$\times$2 blocks. The remaining rows can be covered if and only if 3 divides mn. Provided that both m and b are greater than 1, and neither is equal to 3 when the other is odd.
Answer: The tromino's area is a multiple of 3, so if there's a covering by them then the total area is a multiple of the tromino's area and hence a multiple of 3. Read the problem carefully.
This is an example of what's called a necessary but not sufficient condition. If the rectangle is to be tilable then we have to have 3 divides $mn$, but that fact alone won't guarantee the rectangle is tilable.
Comment: Unless I'm missing something, the direct problem is rather trivial, and the converse is false (a 3x3 board is not coverable)
Comment: Okay, I see! Thanks!
Answer: Suppose that tromino is made of three squares with side lengths $x$. Then the area of tromino is equal to $3x^2$. The rectangle consists of $k$ trominos. As a result
$$mn=3x^2k,$$which is clearly divisible to $3$.


How to display forum on a custom URL on my site?

Question: The default URL of forum is ./forum but I want it to move to ./discuss/forum
How can i accomplish same?
Answer: You can use pathauto, url alias to  your forums to achieve the same.  if it is a custom menu you can use hook_menu_alter(). or an .htaccess re-direct if it is a permanent change
Comment: I have used pathauto but breadcrum is still showing
Home >> forum
instead they should show:
Home >> discuss >> forum
Menu item discussions is also not highlighted
Comment: is discussions having a separate page or a menu item, unless it does have menu item will not be linked or highlighed?
Comment: No, forums are on default URL ./forum
I have custom menu item linked to ./forum


How to indent multi line comment of c in vim

Question: I write multi line comment properly indented before every function I write in c code in the project I am working. I use gvim editor. Problem is many a times I make some changes in the function and have to re edit the comment, and reediting the comment makes the comment un indented. I again have to reindent the comment. I find it difficult to reedit the multi line comment. Is there any shortcut or utility in gvim using which I can easily indent multi line comment automatically?
I searched in net about this problem and could not find anything useful to solve this problem.  Here I am showing an example of multi line comment that I wrote before a function followed by the multi line comment after reediting(note it is now un indented) it followed by expected result.
I also have another question. Do you write comment before every function you write in c. If yes how to maintain the indentation of the comment if you make some changes in the function?
/*
 * Function: remove_item_from_list
 * --------------------
 *  Removes an item from a list. Here list is a sequence of same type objects.
 *  pItem is also same type object. This is a generic function in the sense
 *  that it can work for different type of objects. Currently pList will have
 *  only one copy of pItem w.r.t. the calling places. So whenever the item
 *  found a break statement is used.
 *
 *  pList : a sequence of objects
 *  pItem : object
 *
 *  returns: modified list
 */

Now I reedited the comment after making some changes int the function. Now the comment in gvim editor looks like as follows. My changes in the comment are present within ## ## block.
/*
 * Function: remove_item_from_list
 * --------------------
 *  Removes an item from a list. Here list is a sequence of same type objects.
 *  pItem is also same type object. This is a generic function in the sense
 *  that it can work for different type of objects. ##Currently it works for Animal and Bird type objects. If you want this function to work for some there type object then you have add check for that object. Note that this function assumes that pItem can't be NULL.## Currently pList will have
 *  only one copy of pItem w.r.t. the calling places. So whenever the item
 *  found a break statement is used.
 *
 *  pList : a sequence of objects
 *  pItem : object
 *
 *  returns: modified list
 */

/*
 * Function: remove_item_from_list
 * --------------------
 *  Removes an item from a list. Here list is a sequence of same type objects.
 *  pItem is also same type object. This is a generic function in the sense
 *  that it can work for different type of objects. Currently it works for
 *  Animal and Bird type objects. If you want this function to work for some
 *  there type object then you have add check for that object. Note that this
 *  function assumes that pItem can't be NULL.## Currently pList will have
 *  only one copy of pItem w.r.t. the calling places. So whenever the item
 *  found a break statement is used.
 *
 *  pList : a sequence of objects
 *  pItem : object
 *
 *  returns: modified list
 */

Comment: The term is not "indent", indent means the leading whitespace. What you want is text wrapping. See `:help textwidth` for some info on this, and check if `formatoptions` contains `c` flag. (and of course, `:help formatoptions` too).
Answer: You can use the gq command (:help gq). Run a visual selection around the paragraph to format and type gq. Based on the set textwidth (as mentioned @Michail), Vim will wrap the text properly, keeping in mind that it's a comment.
In this way, you can type your comment, edit it, come back to it, without caring much of the formatting, and formatting once you are happy with it.
Comment: `gq` also takes a motion, so `gqip` will reformat the whole paragraph. See `:h motion.txt`.
Comment: The suggestion you gave perfectly solves my problem, thanks a lot. Now I will be free from the pain.
Comment: Great @Ranju, if you are happy with it, don't forget to approve the response :-)


Converting an integer column to a character in mySQL

Question: My users table currently has a field sex which is either 1 or 2.  I want to convert those values to "F" or "M" and put them into a different column.  Is there any way to do this in mySQL?
I can write Ruby code to do this in the console, but I have on the order of 100K users and don't want to stall production while I loop.
Comment: you can use `CASE WHEN`
Comment: Do you mean you want to add an extra column to the table or do you just want to get F/M when you query the existing table.
Comment: I have a new column that should contain F/M while the original column contains 1/2
Answer: You can do it in 3 steps
step 1
Add a new column into the table
alter table table_name add column sex_n char(1);
step 2
Write an update query
update table_name
set sex_n = case when sex = 1 then 'M' else 'F' end ;

step 3
Verify if the data is populated correctly then do
alter table table_name drop column sex
alter table table_name change sex_n sex char(1);

If you do not want an extra column you can use select to convert as
select
case when sex=1 then 'M'
else 'F'
end as sex
from table_name

Comment: The last one is if you do not want to add another column into the table and using select you can modify and display, but the column will still contain `1 or 2` but while display via query it will show `M or F`
Comment: Does the latter work if the `sex` column is type integer?
Answer: Query:
UPDATE tbl_name SET sex = (CASE WHEN sex = 1 THEN 'M' WHEN sex = 2 THEN 'F' ELSE '' END);

Add extra column with name gender then:
UPDATE tbl_name SET gender = (CASE WHEN sex = 1 THEN 'M' WHEN sex = 2 THEN 'F' ELSE '' END);


Seek the partial derivative

Question: How to seek the partial derivative of the following formula
$\frac{\partial}{\partial x}a^{\top}XB(I+BXB)^{-1}B^{\top}X^{\top}a$, where $X \in \mathbb{R}^{n\times n}$, $B \in \mathbb{R}^{n\times n}$, $I \in \mathbb{R}^{n\times n}$, $a \in \mathbb{R}^{n}$, and $x$ is a parameter in $X$.
Answer: I guess that matrices scare you. Actually, just apply the product rule
$$\begin{align}&(a^TXB(I+BXB)^{-1}B^TX^Ta)'\\
=&a^TX'B(I+BXB)^{-1}B^TX^Ta+a^TXB[(I+BXB)^{-1}]'B^TX^Ta+a^TXB(I+BXB)^{-1}B^TX'^Ta
\end{align}$$
and then chain rule
$$\begin{align}[(I+BXB)^{-1}]'&=-(I+BXB)^{-1}(I+BXB)'(I+BXB)^{-1}\\&
=-(I+BXB)^{-1}BX'B(I+BXB)^{-1}\end{align}$$
The answer is now obvious.

Seek the partial derivative


Two limits with trigonometric functions as $x\to\infty$

Question:
Is  $\displaystyle\lim_{x\to \infty}\frac{3\cos x}{x+5}$ equal to $+∞$?
Is  $\displaystyle \lim_{x\to\infty}\left(x\sin{(\pi /x)}\right)$  equal to $1$?

I'm not sure how to go about solving this problem.
Comment: Do you mean $\cos x$?
Answer: For the first case, $|\cos x|\le1$ for real $x$
For the second, set $\dfrac\pi x=h,$ $$\lim_{x\to\infty}x\sin\frac\pi x=\pi\lim_{h\to 0}\frac{\sin h}h$$
Comment: for second does it equal π or 1 ?
Comment: @user155971,Could you follow  my short argument ?
Comment: yes, I followed and given me 1 as (sinh/h)=1
Comment: @user155971, where is the confusion ?
Comment: yes it's pi , sorry about this mistake
Answer: I gather $cox$ is $\cos(x)$.
For 1) you can use 2 easy arguments, first, $\cos$ is bounded and $x \to \frac{1}{x+5}$ have 0 for limit when $x$ tends toward $\infty$ then you have a product of a bounded function by an infinitesimal function, so you your product is infinitesimal.
Or you can use $-1\leq \cos(x) \leq 1$ and so $\frac{-1}{x+5} \leq \frac{\cos(x)}{x+5} \leq \frac{1}{x+5}$ and you'll have the same answer.
For 2), remember that $\lim\limits_{h \to 0} \frac{\sin(h)}{h}=1$ and $\lim\limits_{x \to \infty} \frac{1}{x}=0$
Comment: $\lim\limits_{h \to 0} \frac{sin(h)}{h}=1$
Comment: Oops yes, my mistake. :) ty


Too many initializer values while passing boolean array as function input

Question: Good day everyone. I'm working on this Game of Life problem and trying to pass an array of boolean:(Given)
game({0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0}, 15, 9);

into the function below:(Given)
void game(bool cells[], int size, int num_gen)

However, I'm getting this error: Too many initializer values C/C++ (146)
I tried to play around and was able to pass in values by declaring the array in the main function:
int main(void)
{
    int cells[]={0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0};
}

But this is my school assignment, so I'm not supposed to edit any given codes/inputs/functions.
I'm kinda lost now, will appreciate any inputs. Thanks in advance!
Comment: *But this is my school assignment* -- What computer language is this assignment supposed to be written in?  Is it C, or is it C++?
Comment: Which part exactly are you not allowed to edit? Because you will need to change either the call or the declaration
Comment: @PaulMcKenzie Technically it should be in C
Comment: @UnholySheep Both the input (test case) and game function were given. So we shouldn't modify those
Comment: So you have been given code that doesn't compile and are supposed to make it compile without changing anything? That is going to be difficult
Comment: @UnholySheep We are supposed to submit it via our course website, and it'll compile and return the results. Well, yea those were given although I'm not sure what's under the hood when it compiles, we have no access to the main function. So it's kinda difficult to code it ourselves in VScode
Answer:
void game(bool cells[], int size, int num_gen)

The first parameter of your function is not an array. Sure, you declared the parameter to be an array of unspecified length, but such parameter will be adjusted to be a pointer to element of such array. A function parameter is never an array in C++.
As such, you are attempting to initialise a pointer with a brace-enclosed list of values. There are more than one value, so it's wrong (and the types of the values are also incompatible with a pointer).
You can create an array, and pass a pointer to element of that array:
int cells[]={0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0};
game(cells, std::size(cells), 9);

Answer: You can use compound literal for this.
Something like
game((bool []){0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0}, 15, 9);

Comment: Note that this is C-only. C++ doesn't have compound literals. It's a shame that the OP has both tags.
Comment: @Ruslan Oops my bad. It should be in C, but I'll also like to know what can be done if it's in C++
Answer: A list of values in braces is not valid at an expression.  What you need is a compound literal:
game((bool []){0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0}, 15, 9);

The syntax that looks like a cast before the braced segment gives you the type.  You can also use this syntax for a struct literal.
Comment: Note that this is C-only. C++ doesn't have compound literals. It's a shame that the OP has both tags.


UIImagePickercontroller cancel button not display in iPad

Question: I'm getting saved images from photo album while clicking button. After dispalying photo album i don't have cancel button in iPad for cancel the photo album. After choosing anyone saved images from photo album then it closing and adding picking image to UIImageView. But without choosing image from gallery i'm not able to close the photo album. In iphone it's working with cancel.
<code>-(void)picker:(id)sender{

if ([self->popoverController isPopoverVisible]) {
 [self->popoverController dismissPopoverAnimated:YES];

 } else {
 if ([UIImagePickerController isSourceTypeAvailable:
 UIImagePickerControllerSourceTypeSavedPhotosAlbum])
 {
 imagePicker=[[UIImagePickerController alloc]init];

 imagePicker.delegate = self;

 imagePicker.allowsEditing =NO;

 imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

  self->popoverController = [[UIPopoverController alloc]
 initWithContentViewController:imagePicker];

 self->popoverController.delegate = self;

 CGRect popoverRect = [self.view convertRect:[self.view frame]
 fromView:[self.view superview]];

 popoverRect.size.width = MIN(popoverRect.size.width, 100) ;
 popoverRect.origin.x  = popoverRect.origin.x+10;

 [self->popoverController
 presentPopoverFromRect:popoverRect
 inView:self.view
 permittedArrowDirections:UIPopoverArrowDirectionAny
 animated:YES];

 }

 -(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
 //release picker

 //  [picker dismissModalViewControllerAnimated:YES];

 if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {

 [picker dismissViewControllerAnimated:YES completion:nil];
 }else{

 [picker dismissViewControllerAnimated:YES completion:nil];

 if (popoverController != nil) {
 [popoverController dismissPopoverAnimated:YES];
 popoverController=nil;
 }

 }

}

 -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{

 if (popoverController != nil) {
 [popoverController dismissPopoverAnimated:YES];
 popoverController=nil;
 }

 [picker dismissViewControllerAnimated:YES completion:nil];

 }
</code>
Answer: You are presenting the imagePickerController in a popoverController, so it will not have Manual Cancel button because you can tap anywhere outside the popover to dismiss it.
Answer: I've met this problem before. Please check the accepted answer in my question below. It worked for me.
UIImagePickerController inside UIPopoverController doesn't show Cancel button on iOS7


Why does the selected payment method comparison always fail?

Question: I'm trying with following simplified rule but nothing happens if using maro_credits as payment method!?
{ "rules_pay_with_maro_credits" : {
"LABEL" : "pay with maro credits",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules_conditional", "rules", "commerce_payment", "commerce_pos" ],
"ON" : { "commerce_pos_transaction_completed" : [] },
"DO" : [
{ "CONDITIONAL" : [
{
"IF" : { "commerce_payment_selected_payment_method" : { "commerce_order" : [ "order" ], "method_id" : "maro_credits" } },
"DO" : [ { "drupal_message" : { "message" : "aklfjaipwoejfipasjfijasdfas" } } ]
}
]
},
{ "LOOP" : {
"USING" : { "list" : [ "order:commerce-line-items" ] },
"ITEM" : { "list_item" : "Current list item" },
"DO" : []
}
},
{ "drupal_message" : { "message" : "test pos event" } }
]
}
}

However the orders in admin - store - orders show up with the payment method, as shown in this screenprint:
https://i.stack.imgur.com/Lbiow.jpg
Anyhelp?
Edit:
I used the mentioned selected_payment_method comparison method that pierre referenced below from start on.
cant add more than 2 links, so i have to add multiple pictures like this i guess:
first you see the selected_payment_method input for the version in the actions with conditional and the rule in the view also with what happens
i after changed the rule to use the conditions directly to show that also there it does not work
https://i.stack.imgur.com/UsxWa.jpg
is this more clear now? or you need more specification?
edit2: in the end i added some screens showing the fields that could be found (nothing with payment method)
Edit3:
Ok I added some descriptions in the pictures on imgur to clarify a bit.
In the end I want to be able to subtract user points form users that pay with "maro credits" (that part already works)
As you see in the screenshots I changed the rule having only the event pos transaction completed (that works!)
then condition selected payment method as shown
and action post a message
as you see in following screenshot that does not work (in the orders list you see there is the order with the payment method maro credits
I hope its clear now?
Ah forgot: in the last screenshots you see all the fields I would be able to chose from and there is none with payment method (and i think that is the problem...?)
Comment: "is this more clear now?" ... **not to me** ... "or you need more specification?" **yes**. Nowhere I see anything in your question WITHOUT using "conditional rules", I still wonder what you get (or not) if you use ONLY a rules condition related to that "selected payment method comparison" (as in my answer), combined with "entity has field". Completely different attempt: why does your rule depend on "commerce_pos"? And what is, in plain english, the business logic you try to implement with rules (you never explained that in your question). Sorry for all these question, but I don't get it ...
Comment: tried to be more specific clear now?
Comment: Feedback about your "edit3": answer to your "I hope it is clear now = ***NO*** , sorry. About your "Ah forgot": your question contains ZERO screenshots, only LINKS to another site. And in the last LiNK I DO NOT see anywhere "al the fields" (I just see "order"). it's not that I don't want to help, but you really, really need to improve your question. Get rid of all those links, replace them by ".JPG" files (or post a comment with links to such .JPGs and I'd be happy to edit your question to integrate them). And replace your edit 1, edit 2, edit 3 by a single question (no updates) ....
Comment: ... (continued). And include a copy/paste (in text format) of those "see all the fields" (I just see "order"). Let me know (extra comment) when you reworked your question. Sorry I still don't understand your real question, but I doubt I'm the only one who doesn't get it.
Comment: Hi Pierre, I understand your concerns, however before I rewrite everything: on this link https://imgur.com/a/5Ekiu to imgur, don't you see all the screenshots? It contains 11 screens - did you scroll down? I cannot add more than 2 links / pictures included in here count as links on stackexchange with my status...
Comment: ah no, I did not realize I have to hit some blue button to "load10 more images" ... give me some time now to go digest those 10 other ones (maybe still today) ... I will come back here whem I am done ... gggggrrrrrrrrrrreetings ...
Comment: OK, new try ... not sure it it will help / solve your issue,,,, but first have a look at [this answer to some other commenrce question](https://drupal.stackexchange.com/a/242013/39516). That seems a variation of your scenario: the tokens about some product details were not available either. So this is how I could get that one to work: (a) create an appropriate Rules Component (with an input parm, and with a "fetch entity by id"). (b) tranform the original rule in something that calls that rules component. In your case, try a rules component with parm "order" (not sure yet "what" to fetch). OK?
Comment: Hi also with that I have no way to get to the payment method from the actual order if I use the "Calculating the sell price of a product" Event
If I use the "After saving a new commerce payment transaction" Event I can see the payment mehtod field, however thats to early in the process... :/
Comment: Sorry to hear that didn't help either, but still I am convinced that a rules component with an action like Fetch entity by ID is what the solution will be. With the entity being your payment transaction. Back to your orders list: is that a View? If so how did it add the column with Payment Method? Via some relationship? If so: if Views can find those data, then via some type of fetch Rules must also be able to fetch it. What do you think?
Answer: Part 1 - Getting your rule to work
Try to add a Rules Condition Entity has field to make the appropriate field available for further processing in your Rules. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says:

The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type').

Don't believe me (yet) about my recommendation here ... first add an extra Rules Action as your very first Rules Action, to simply display the actual value of that field you try to use within the "If" of your Conditional Rules construct ... Without such "entity has field" Rules Condition, I bet the value of that field will be shown as empty (or blank). Which would then also explain why your "If" always results in a FALSE ...
For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.
Note: it's hard to tell from the current content of your question what the exact field (for which to add such Rules Condition) should be in your case. But my best guess is some field about the payment method (possibly method_id?)
Part 2 - Simplify your rule
From the current content of your rule, it seems that you want to perform a Rules Loop as a Rules Action, but only if some condition (the "If" you added using "Conditional Rules" module) is true. And then as the very last Rules Action the rule shows that test pos event message.
If this very last message is just for debugging (i.e if it is not really needed after you get it to work anymore), then it seems to me that you could replace that "If" (added using Conditional Rules) by a regular Rules Condition. And by doing so your rule would not require the Conditional Rules module anymore.
Plan B
As per the comment posted below this answer, you may want to try a completely different approach ... which is based on this commit, and related to issue # 1278156:

Use the Rules Condition Selected payment method comparison, located within the Commerce Payment group.
Check if its value is equal to your 'maro_credits'.
Comment: Hi there thanks first

so the Loop was just wrongly in there, there rule has to do much more in the end but im trying to debug so simplified it

the test pos is just for debug, to show the event works

so now the problem that selected payment method comparison wants an "order" as input and then has a dropdown showing what payment methods i can compare to. ok
BUT when i search for a payment method field (as you specified with entity has field or in the data selector somewhere in the rule) I cannot find any "payment method" field anywhere? :(
Comment: additional comment: i put it down to action with conditional to debug, cause in conditions it does not work and i couldnt test the test pos message to check the event ;)
Comment: comment plan b: that is exactly what i did, im using that conditional you specified and that asks for an order to then compare to a payment method form a drop down where i chose maro credits
Comment: http://imgur.com/a/5Ekiu
Comment: Sorry but I don't understand your latest comments ... please EDIT (expand) your question and include relevant screenprints (not links to images somewhere else). And clarify if those screenprints relate to the "if" (conditional rules) or to a regular Rules Condition. Then try to include 1 (and only 1) actual question. Without doing so, I have no other feedback/answer on top of what I already wrote. OK?
Comment: i tried to show more clearly, that the selected payment method comparison condition is not working - is that clarified enough?
Answer: The condition you are using checks $order->data['payment_method'], which is the payment method selected by the user during checkout. An order can actually have multiple payment methods, 1 per transaction, although on a standard setup usually only 1 can be selected initially. Since POS doesn't run through a checkout and allows the customer to pay with multiple methods, such as cash and then the remainder on card, it does not have a "selected" payment method.
I don't see any easy way to get the specific transaction info in rules, so it seems like you have 2 options.

Hacky - Add code to the completeTransaction action that the orders selected payment to the most recent transactions type
Better - Create a custom condition that will check if any of the transactions in an order contain the specific payment_method
Comment: for now I did option 3 hacky 2 :)
I made a rule on event "After saving a new commerce payment transaction" and just subtract the points there - I don't see a faster way atm


Qual tecnologia usar para desenvolver um Webservices para Android

Question: Estou iniciando no mundo Android e identifiquei que para a aplicação que estou projetando terei que seguir uma arquitetura WebServices usando um banco de dados em plataforma Cloud.
O banco de dados eu já defini que será MySQL. Já WebServices eu estou em dúvida se vou de Java ou .Net.
Olhando pelo lado de performance e custo, inclusive considerando a futura plataforma Cloud que terei que contratar (estou olhando UOL e Kinghost), vejo duas possibilidades:

Criar os Webservices em Java para ter tudo em um Cloud sobre Linux
Criar os WebServices em .Net para utilizar uma plataforma Windows

Quais são as vantagens e desvantagens de cada plataforma nesse contexto?
Comment: Ramaral, não entendi qual é o problema de respostas baseadas em opinião. Se eu quisesse uma resposta objetiva para um caso específico (problema técnico) eu teria perguntando de forma objetiva sobre o caso específico, mas essa não é minha necessidade, pois a intenção era mesmo saber a opinião dos profissionais que aqui participam frente a experiência que possuem no desenvolvimento de aplicações do tipo. Na minha opinião (sei que é proibido ter opinião aqui) é que essa restrição apenas limita a troca de experiências e de conhecimento, mas tudo bem, se é política do site então irei respeitar.
Comment: Marcio, bem vindo ao Stackoverflow! Compreendo que este seja o tipo de pergunta que nos surge quando começamos a desenvolver algo. No entanto, ela não se enquadra no escopo do site. Aqui as perguntas devem ser objectivas, sobre problemas de programação concretos. A sua pergunta originará resposta baseadas em opinião, algo que não é aceite aqui. Convido-o a ver como o site funciona na [tour](http://pt.stackoverflow.com/tour) e qual o [tipo de pergunta](http://pt.stackoverflow.com/help/how-to-ask) que se enquadra.
Comment: +1 Marcio. Acho que existem casos e casos @ramaral. E nesse caso uma resposta baseada na opinião e na experiência é a mais adequada para a pergunta do Marcio.
Comment: @Luiz A questão está em que, de acordo com as regras, tanto a pergunta como a resposta não deveriam ter ocorrido.
Comment: Marcio, bem-vindo ao [pt.so]! Editei sua resposta para evitar que ela seja muito opinativa. Dessa forma, acredito que seja possível responder de forma um pouco mais objetiva. Se não estiver contente, pode editar a pergunta novamente. Se tiver outras dúvidas, sugiro que vá criando perguntas diferentes, cada uma com um objetivo bem específico em mente. Abraço.
Answer: TL;DR
A verdade é que, do ponto de vista do App cliente, não faz diferença alguma em que tecnologia o Web Service é implementado. Esta é justamente a ideia de dos Web Services para começar.
Portanto, os fatores que podem levar à decisão de qual plataforma ou linguagem usar estão em outro lugar.
Alguns são...
Dois ambientes diferentes?
A não ser que você já seja um desenvolvedor .Net proficiente, se você já desenvolve em Java para Android, usar a mesma linguagem no servidor faz mais sentido.
Custo do servidor
A não ser que seja um projeto pessoal financiado do seu bolso e sem um retorno significativo, o custo da hospedagem não deve ser um problema.
Entretanto, saiba que para Java o custo inicial é maior, já que uma instância pequena de Java ocupa muita memória. A vantagem do Java é que a memória não é proporcional ao número de usuários.
Além disso, existem serviços como OpenShift que permitem um uso limitado gratuitamente.
Outras alternativas
Por outro lado, se você quer manter um custo mínimo ou não conhece bem nem Java nem .Net e quer um ambiente mais simples, poderia usar inclusive PHP ou Node.js para desenvolver seus Web Services.
Sistema operacional
O sistema operacional também não é importante no sentido de que ambos vão dar suporte.
Mas, em geral, o ambiente linux é mais flexível e leve. Existem distribuições feitas para uso na Nuvem que funcionam com pouca memória e pouco espaço de armazenamento.
O problema do Linux é que, caso você não esteja acostumado com esse tipo de ambiente e não domine o terminal, você pode facilmente perder muito tempo dando murro em ponto de faca até conseguir fazer coisas simples que, no Windows, poderia resolver em alguns minutos clicando em alguns menus.
Comment: utluiz, obrigado pelo retorno. Vou então partir para um ambiente Linux/Java/Mysql/Tomcat do lado do servidor WebServices/XML/Json, pois tenho maior proficiência em java/Linux uma vez que nunca programei em .NET. Quando eu precisar de algo para migração em produção irei pegar um plano cloud lá no Kinghost que a primeira vista atenderá minhas necessidades e tem bom preço. Com as respostas que tive aqui mais umas pesquisadas deu para fechar uma arquitetura que vai me atender e seja escalável com o tempo. Mais uma vez obrigado pelo retorno.
Comment: +1 por salvar a pergunta antes de responder :)
Answer: O WebService é pessoal tem que ser algo que atenda a sua necessidade com mais precisão, ou seja as duas opções são boas (Linux ou Windows). Isso é questão pessoal: facilidade pra você em desenvolver, preço, estabilidade, hospedagem etc.
Eu também aconselho a você dar uma olhada sobre WebService REST JSON, que é feito para aplicações que vão transportar dados não muito elevados, é rápido, fácil de utilizar e você poderá desenvolver em PHP sendo assim rodando em ambas as estruturas Linux ou Windows.
Uma dica: Se for transportar dados com muito conteúdos separados, utilize JSON ao invés de XML porque as tags do XML tornam muito grande o recebimento gastando assim mais processamento.
Comment: -1 Porque ao responder está incentivando perguntas que são fora do escopo do Stackoverflow.
Comment: -1 a resposta está completamente baseada em opinião.
Comment: Viniam a intenção do -1 é avisar ao autor que a resposta/pergunta não está boa, que ele deve melhorá-la, não é pra penalizar você ou usuario qualquer que seja. É intessante que você tenha conhecimento do funcionamento do site e suas regras, tudo pode ser encontrado na [central da ajuda](http://pt.stackoverflow.com/help)
Comment: ps: bons pra negativar e pra positivar também, esses seus 300 pontos não vieram do nada :P
Comment: Não tem que pedir desculpas. Sei que você só quis ajudar, mas é obrigação de cada um de nós zelar pelas regras do site.
Comment: Sim @DiegoFelipe, eu devia ter feito notar isso também.
Comment: Caraca vocês são bons para negativar heim, Onde fica a consideração? rsrs, Mas tá tranquilo. Talvez se negativassem menos e ajudasse mais a comunidade seria melhor.
Comment: Não se sinta visado, o que é levado em consideração é o conteúdo da resposta e não quem responde.
Comment: Viniam, 3 dicas para evitar esse tipo de negativo, mesmo quando é algo que envolve opinião. Primeiro, evite simplesmente dizer "isso é questão pessoal", pois mesmo que seja, cada decisão envolve fatores positivos e negativos, vantagens e desvantagens que são relativamente objetivos, então seria útil se falasse sobre alguns desses aspectos. Segundo, ao invés de simplesmente dizer que se pode usar ou fazer isso ou aquilo, tente embasar sua opinião em termos mais técnicos, mais uma vez focando nas vantagens e desvantagens. Terceiro, formate melhor sua resposta, tem 3 ideias em um só parágrafo.
Comment: Uma dica, remova a resposta que os negativos deixam de ser contados na sua reputação.
Comment: Putz, Eu não sabia, Desculpe, Eu só queria ajudar, Poxa desnegativa aí.
Comment: Viniam, obrigado pelo retorno e desculpe pelo problema que lhe causei ao me ajudar. Avaliando sua resposta, vi que outra opção é utilizar REST/Json que parece ser uma forma mais "econômica" de trafegar dados, eu estava só com WebServices na cabeça e sua resposta me fez considerar outra alternativa. Estou com algumas dúvidas mas me limito a não perguntar já que provavelmente irão se enquadrar em opinião, mas por fim, vou dar mais uma estudada e detalhar mais a arquitetura linux/mysql/webservices java/rest/json que provavelmente irá me atender. Mais uma vez, obrigado pelo retorno.
Comment: Eu tinha até negativado mas mudei de idéia, achei que dar uma formatação mais profissional no texto alivia um pouco o problema
Comment: Os +3 no meu primeiro comentário obrigam-me a esclarecer que responder a uma pergunta "baseada em opinião", só por si, não justifica dar -1. O que quis realçar é que respostas do tipo desta, que opinam sem dar justificação, incentivam a que hajam outras, tornando o poste como se de um *forum* se tratasse. Nunca daria -1 à resposta do utiliz.


Animação de carregamento ao enviar formulário

Question: Coloquei o plugin Pace Master em minha página que faz uma barra carregar na parte superior enquanto a página esta carregando, como a do YouTube, entretanto, quero fazer com que essa mesma barra carregue ao enviar o formulário que contém na página, caso ele esteja devidamente preenchido. Ja vi isso em uma infinidade de sites, e parece ser bem simples mas não tenho muito conhecimento em JavaScript ainda, por isso das formas que tentei não funcionou.  Tentei chamar a função do loading com onclick mas não funcionou, estava querendo que funcionasse no mínimo sem verificar se o form esta preenchido pois o principal seria que o usuário tivesse um feedback quando clicasse em enviar o form.
    5. Se possível, liste alguns sites que você gosta, incluindo as URLs.
    <textarea name="questao5" id="questao5" required></textarea>
    <button class="btn" id="enviar" name="enviar" type="submit">Enviar</button>

.pace {
-webkit-pointer-events: none;
pointer-events: none;

-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}

.pace-inactive {
display: none;
}
.pace .pace-progress {
background: #8BB006;
position: fixed;
z-index: 2000;
top: 0;
right: 100%;
width: 100%;
height: 2px;
}

-JavaScript do plugin-
Link GitHub
-JavaScript do formulário-
$('.formphp').on('submit', function() {
    var emailContato = "firstname.lastname@example.com"; // Escreva aqui o seu e-mail

    var that = $(this),
            url = that.attr('action'),
            type = that.attr('method'),
            data = {};

    that.find('[name]').each(function(index, value) {
        var that = $(this),
                name = that.attr('name'),
                value = that.val();

        data[name] = value;
    });

    $.ajax({
        url: url,
        type: type,
        data: data,
        success: function(response) {

            if( $('[name="leaveblank"]').val().length != 0 ) {
                $('.formphp').html("

");
                $('#form-erro').html("Falha no envio!
Você pode tentar novamente, ou enviar direto para o e-mail " + emailContato + "
")
                .hide()
                .fadeIn(1500, function() {
                $('#form-erro');
                });
            } else {

                $('.formphp').html("

");
                $('#form-send').html("Mensagem enviada!
Em breve eu entro em contato com você. Abraços.
")
                .hide()
                .fadeIn(1500, function() {
                $('#form-send');
                });
            };
        },
        error: function(response) {
            $('.formphp').html("

");
            $('#form-erro').html("Falha no envio!
Você pode tentar novamente, ou enviar direto para o e-mail " + emailContato + "
")
            .hide()
            .fadeIn(1500, function() {
            $('#form-erro');
        });
        }
    });

    return false;
});

Answer: Segundo a documentação, você pode reiniciar a animação com o seguinte comando:
Pace.restart();

Basta inserir o código na função do evento que detecta o submit do formulário:
$('.formphp').on('submit', function() {
    Pace.restart(); // inicia a animação
...

O exemplo abaixo é apenas para ilustrar o funcionamento do comando:

function anima(){
   Pace.restart();
}
.pace {
-webkit-pointer-events: none;
pointer-events: none;

-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}

.pace-inactive {
display: none;
}
.pace .pace-progress {
background: #8BB006;
position: fixed;
z-index: 2000;
top: 0;
right: 100%;
width: 100%;
height: 2px;
}

<button class="btn" onclick="anima()" name="enviar" type="submit">Clique aqui</button>


checkpoint utm-1 edge concurrent users

Question: I am considering to buy a UTM-1 firewall. However, I didnt get exactly what concurrent users mean. There are three models for Concurrent Users 16/32 or Unlimited. What does this mean ? How is concurrent user measured ?
Answer: Each seperate IP address any machine on your network tries to cross the firewall with (even if it is blocked) counts as a single user.
Comment: Thanks James. Do you know what happens if this limit is exceeded ? Are packets dropped or put into a wait queue or something like that ?
Comment: It will mark those ips as blocked and log an error that you have exceeded your limit. from this handy faq http://www.cpug.org/forums/check-point-utm-1-edge-appliances/6341-utm-1-edges-faq.html

checkpoint utm-1 edge concurrent users


gstreamer-0.10 print pipeline string

Question: I would like to print out the pipeline of a gstreamer-0.10 element. How can this be done?
The code that a external developer wrote for us:
static GstElement* jpgPipeline  = NULL;
pipedef = g_strdup_printf("appsrc name=jpgsrc ! ffmpegcolorspace %s %s %s %s %s  ! ffmpegcolorspace ! jpegenc quality=%i ! multifilesink name=jpgsink location=\"image.jpg\"",cropStr, scaleStr, sharpenStr,vbStr,gammaStr,quality);
jpgPipeline = gst_parse_launch (pipedef, &error);
bus = gst_pipeline_get_bus(GST_PIPELINE(jpgPipeline));
gst_element_set_state (jpgPipeline, GST_STATE_PLAYING);

I'm trying to see the pipeline with:
g_print(gst_element_info(jpgPipeline));

But I get many warnings when I try to compile it.
main.c:331:2: warning: implicit declaration of function 'gst_element_info' [-Wimplicit-function-declaration]
  g_print(gst_element_info(jpgPipeline));
  ^
main.c:331:2: warning: passing argument 1 of 'g_print' makes pointer from integer without a cast [enabled by default]
In file included from /usr/include/glib-2.0/glib.h:62:0,
                 from /usr/include/gstreamer-0.10/gst/gst.h:27,
                 from main.c:5:
/usr/include/glib-2.0/glib/gmessages.h:265:17: note: expected 'const gchar *' but argument is of type 'int'
 void            g_print                 (const gchar    *format,
                 ^
main.c:331:2: warning: format not a string literal and no format arguments [-Wformat-security]
  g_print(gst_element_info(jpgPipeline));
main.c:(.text.startup+0x651): undefined reference to `gst_element_info'

Comment: pipedef is already your pipeline, just g_print(pipedef) would work.
Answer: 1st and most important: please use 1.0, 0.10 is obsolete for years now.
This gst_element_info doesn't exist AFAIK. What do you expect to be printed as a string about the pipeline? The elements in it? How do you want to represent links?
Maybe using the dot representation would be better. Found some instructions here: https://developer.ridgerun.com/wiki/index.php/How_to_generate_a_Gstreamer_pipeline_diagram_%28graph%29 or https://www.freedesktop.org/software/gstreamer-sdk/data/docs/latest/gstreamer-0.10/gstreamer-GstInfo.html#GST-DEBUG-BIN-TO-DOT-FILE:CAPS

gstreamer-0.10 print pipeline string


Initialize Observable Collection using Anonymous Method

Question: Just trying to do something basic and am getting stuck. Want to initialize an observable collection in my model class (See code below) and cant seem to get it working. I have put in _ for the part which is not working.
Can somebody please provide pointers
public class StockModel : ObservableCollection<KeyValuePair<string, TickerDetails>>
{
    #region Properties
    public string TickerSymbol { get; set; }
    public TickerDetails Ticker { get; set; }
    #endregion

    public StockModel()
    {
        init();
    }

    public void init()
    {
        Add(new KeyValuePair<string, TickerDetails> { "ABC", new TickerDetails {TickerName="ABC", LastPrice=30, Ask=40, Bid=50, Volume=60 }});
    }

    public ObservableCollection<KeyValuePair<string, TickerDetails>> getData()
    {
        return this;
    }
}

public class TickerDetails
{
    public string TickerName { get; set; }
    public int LastPrice { get; set; }
    public int Bid { get; set; }
    public int Ask { get; set; }
    public int Volume { get; set; }
}

I know I can do the traditional way (like below) but want to learn the above methodology
Dictionary<int, StudentName> students = new Dictionary<int, StudentName>()
{
    { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},
    { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317}},
    { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198}}
};

Comment: Are you sure you want StockModel to actually inherit ObservableCollection? Its unclear what you want StockModel to be since it has a single string as the Ticker, and a single set of details, yet is a collection...
Comment: One oddity, in your Add() method, you are adding a different type to the ObservableCollection.  The collection has KVP> and you are adding a KVP.
Comment: Yes - The reason I am building it this way is because this is the model - which will then be injected into ViewModel and further displayed into the view. This is the mini version of StockModel - still need to add more properties for Diff charting controls all which will be based on this StockModel
Comment: Steve -Sorry just updated that error - initially I was trying to do this with a List but later changed to a object since it made more logical sense for my purpose. Have updated the code.
Comment: just a suggestion, i'd make more sense of this if you had posted compilable code with notations as comments...
Comment: Sorry everybody - Since I had posted the mis-mash version of the code. Have now updated to the correct one and am still getting this error - Cannot initialize type 'System.Collections.Generic.KeyValuePair with a collection initializer because it does not implement System.Collections.IEnumerable
Comment: That makes sense, change the {} after your KVP to ()
Answer: Look at the type on your inherited ObservableCollection:
ObservableCollection<string, List<int>>

This makes your type a collection of strings and lists, not strings and TickerDetails. Change your inherited type to string, TickerDetails and you'll be able to initialize. However you'll also need to change the signiture of getData() to match the new inherited signiture, or provide a transformation from TickerDetails to List, Int
Answer: Isn't that
Add(new KeyValuePair<string, object> { "ABC", new TickerDetails { TickerName = "tick tock", LastPrice = 10 }});

?
You just have to instantiate a new TickerDetails as well.
Anyway, that doesn't match an ObservableCollection<KeyValuePair<string, List<int>>> so it's more like:
Add(new KeyValuePair<string, List<int>> { "ABC", new List<int> { 1, 2, 3, 4 }});

EDIT: with your latest edit, the first example should work.
Comment: Or perhaps `Add(new KeyValuePair("ABC", new TickerDetails { TickerName = "tick tock", LastPrice = 10 }));` since the element type is `KVP` and KVP has a constructor with key and value argument.
Comment: Sorry everybody since I had posted the mis-mash version of the code. Have now updated to the correct one and am still getting this error - Cannot initialize type 'System.Collections.Generic.KeyValuePair with a collection initializer because it does not implement System.Collections.IEnumerable


nginx - php-fpm: access restrictions for some php pages

Question: I have a folder containing some PHP files served with php-fpm (fastcgi); inside tihs folder, I have a file which I want to be allowed for internal IPs and deny for external.
The problem I have is that with this configuration...
# PHP
location ~ ^\/some\/path\/(.*\.php)$ {
  alias /some/path/;
  fastcgi_split_path_info ^(.+\.php)(/.+)$;
  # # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
  #
  # # With php5-cgi alone:
  # fastcgi_pass 127.0.0.1:9000;
  # # With php5-fpm:
  fastcgi_pass unix:/var/run/php5-fpm.sock;
  fastcgi_index index.php;
  include fastcgi_params;
  # Changes due to the alias declaration
  fastcgi_param SCRIPT_FILENAME $document_root/$1;
  fastcgi_param SCRIPT_NAME /$1;
}

# PHP: phpinfo() access restrictions
location = /some/path/phpinfo.php {
  allow 10.0.0.0/24;
  deny all;
}

...access to /some/path/phpinfo.php is managed correctly but the fastcgi rules are not applied (I download the phpinfo.php file); while with this configuration...
# PHP
location ~ ^\/some\/path\/(.*\.php)$ {
  alias /some/path/;
  fastcgi_split_path_info ^(.+\.php)(/.+)$;
  # # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
  #
  # # With php5-cgi alone:
  # fastcgi_pass 127.0.0.1:9000;
  # # With php5-fpm:
  fastcgi_pass unix:/var/run/php5-fpm.sock;
  fastcgi_index index.php;
  include fastcgi_params;
  # Changes due to the alias declaration
  fastcgi_param SCRIPT_FILENAME $document_root/$1;
  fastcgi_param SCRIPT_NAME /$1;
}

# PHP: phpinfo() access restrictions
location ~ ^\/some\/path\/phpinfo\.php$ {
  allow 10.0.0.0/24;
  deny all;
}

.../some/path/phpinfo.php is interpreted correctly but access restrictions are not applied.
How can I fix the configuration in order that /some/path/phpinfo.php gets interpreted and access restrictions are applied?
Answer: nginx only applies one location block at the same level, so it's either going to apply the first one (with the FastCGI but no access control) or the second one (with access control by no FastCGI). To have them both applied you need to nest them like so:
location ~ ^\/some\/path\/(.*\.php)$ {
    fastcgi_pass unix:/var/run/php5-fpm.sock;

    location /some/path/phpinfo.php {
        allow 10.0.0.0/24;
        deny all;
    }
}


CSS box-shadow fall behind flash player in firefox

Question: I want to create a dropdown menu with css box-shadow around it and I have a few content using flash, the problem's when dropdown show up and have flash behind it, box-shadow is not show.
actually the box-shadow fall behind flash player
I simplfy the structure

I'm using Firefox 17.0.1 , chrome 23.0.1271.97 and flash player 11.5.502.135
Style
.test { position:absolute; z-index: 100; left:50%; top:30px; border:3px solid blue;width:200px; height:200px; background:gray; box-shadow:50px 50px 130px #000}
#flash{ position:absolute; left:50%; z-index:-100}

HTML Structure

<object width="100%" height="400" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000">
<param value="28bc2_2.swf" name="SRC">
<embed width="100%" height="400" src="28bc2_2.swf">
</object>

Anybody know what happens and the solution, thanks for helping :)
Answer: Try addding: -moz-box-shadow:50px 50px 130px #000000;
Comment: thanks dude for your response. but it seems not work. when I tried not even single shadow show.
Comment: oh ya I have thought maybe firefox not support any -moz-box-shadow anymore. because Firefox 17.0.1 alredy using css3 w3c standard box-shadow
Answer: To get the box-shadow crossbrowser you need the following code:
box-shadow: 50px 50px 130px #000;
-webkit-box-shadow: 50px 50px 130px #000;
-moz-box-shadow: 50px 50px 130px #000;

Also try adding wmode parameter to embed flash:

<object width="100%" height="400" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000">
<param value="28bc2_2.swf" name="SRC">
<param value="transparent" name="wmode">
<embed width="100%" height="400" wmode="transparent" src="28bc2_2.swf">
</object>

Comment: Ahhh thanks dude, the problem is wmode paramater. After I put the parameter, box-shadow now work perfectly. Oh ya for info -moz-box-shadow seems not work for this FF version (17.0.1)
Comment: @Finn How nice! I only ask, please, tell you what my answer as correct. Thank you.
Comment: yes fred, your answer is correct. adding wmode parameter will fix the problem :)
Comment: @Finn Please, read section "How to ask" in FAQ: [http://stackoverflow.com/faq#howtoask](http://stackoverflow.com/faq#howtoask)
Answer: In addition to using cross-browser css... (-moz- and -webkit- like others have mentioned)
Try setting the z-index value of .test higher than the z-index value of #flash. Also, try placing #flash within the div with .test class.
Right now it seems that you set the z-index of your flash div to -100, and the z-index of your test (is this your menu?) to 100... so naturally your flash content would be behind .test.
Comment: In addition to using cross-browser css... (-moz- and -webkit- like others have mentioned)
----> it seems -moz not work on this version Firefox 17.0.1, dont know why
Comment: Try setting the z-index value of .test higher than the z-index value of #flash. Also...
----> sorry it not possible, the html structure suppose to be like that. because .test is dropdown menu and #flash is content page.

Right now it seems that you set the z-index of your flash div to -100, and the z-index of your...
---> ya, flash content is right behind .test with this z-index. but still the shadow fall behind flash content.  Oh ya, I tried using small z-index like 50 (not minus), stil not work :(


Dimensionality of space given N points and distances between them

Question: A dilettante question here.
Let's say we have N points and distances between them. All distances are non-zero and are defined for all pairs.
What should be the dimensionality of space where all points can be properly placed, given the distances between them?
I think there are two subquestions here: (1) what should be the dimensionality in a general case, i.e. given arbitrary distances? and (2) how can dimensionality be reduced in specific cases, i.e. with specific constant distances? I'm more interested in (1). So:
For 2 points the 1-dimensional space is sufficient.
For 3 points it would be a triangle in the 2-dimensional space.
However the 4-point case already seems complicated to me, since (intuitively) the 3-dimensional space is not sufficient for placing 4 points. We can form 2 triangles with a shared side, meaning that the distance between the two "free-hanging" vertices can not have an arbitrary distance between them. If this is correct, does it mean the 4-dimensional space would be sufficient?
And finally, what about N number of points with arbitrary distances between them?
Comment: Does this answer your question? [Minimum dimension to hold $N$ points with given distances?](https://math.stackexchange.com/questions/1000006/minimum-dimension-to-hold-n-points-with-given-distances)
Comment: Euclidean distance?
Comment: @mvw I don't know of any others :)
Comment: This problem seems to be: Given all $\DeclareMathOperator{dist}{dist}\dist(P_i, P_j)>0$ for $N$ points $P_i$, decide if it is possible to assign $n$ dimensional coordinates to each point, such that the given distances result.
Comment: @mvw I think my question is slightly different: what is the smallest dimensionality  where coordinates can be assigned to all points given arbitrary distances? I.e. the general case.
Comment: P.S. a problem where you could find for example that N points can be placed in a 1-dimensional space for a specific matrix of distances is a different problem.
Comment: Does [this](https://math.stackexchange.com/questions/1000006/minimum-dimension-to-hold-n-points-with-given-distances) answer your question?
Comment: @A.Γ. looks a bit too complicated to me, I would appreciate a simplified answer, in "layman terms". (And if it's true that the problem has no general solution then it would be interesting to create an N-dimensional space where it does?)
Comment: @mojuba You may also look through Related question in the link above to the right.
Answer: We assume that we are using Euclidean spaces. The problem with "given arbitrary distances" becomes apparent with 3 points. The three distances must satisfy the triangle inequality, thus the distances can not be completely arbitary. This requirement does not depend on the dimension of the Euclidean space. That is, if the triangle inequality is not satisfied, there is no way to embed the 3 points in any Euclidean space. Read the Wikipedia article Inner product space.
A similar situation arises for 4 points which you mentioned. The distance between the two "free-hanging" vertices can not have an arbitrary distance. It has to satisfy an inequality also. Similarly, if that inequality is not satisfied, there is no way to embed the 4 points in any Euclidean space. Read the Wikipedia article Ptolemy's theorem for details about Ptolemy's inequality.
Comment: OK, but is there a proof that no such Euclidean space exists for arbitrary distances between, say, only 3 points? N points?


testing Intel SGX Remote Attestation

Question: Is it possible to use a server with Intel SGX to test Remote attestation? Is it possible to use my own local machine (which I use to connect to the SGX server) as cache service? how can I do this?
Answer: Before all, I suggest you read this page, it contains almost everything you need to know about RA.
Then: in terms of RA, client and server might have interchangeable roles, so I will stick to this documentation that states: the server holds the secrets and attests a client's enclave.
In this setup, the server doesn't need to have an enclave, so yes, you can use any computer to run this part of the process.

testing Intel SGX Remote Attestation


Finding a conformal map to the upper half plane

Question: Let
$$
\Omega = \{z \in \mathbb{C} : |z| > 1, z \notin \mathbb{R}_{< -1}, z \notin \mathbb{R}_{\ge 2}\}.
$$
Find a conformal map which maps the region $\Omega$ to the upper half plane.
I would want to know what I am supposed to do first. I tried to shift by $1$ to the right $(z+1)$ then used $1/z$ but I was not sure about how the points around $z=-1$ and $z=2$ moved by these two maps if it is a good way to start this problem.
Thank you in advance.
Answer: To start, apply the map $f_1(z)=z+1/z$ which collapses the unit circle onto the segment $[-2,2]$; the exterior of the unit circle is mapped onto the exterior of the circle. Then you have a plane with two slits, and things should become clearer.
Comment: @YeonjooYoo You can see a plot [here](http://math.fullerton.edu/mathews/c2003/JoukowskiTransMod.html). Also, what you really want to know is where the slits $[-\infty,-1]$ and $[2,+\infty]$ go. Both lie on the real line, so it's really a question about real function $x+1/x$ which you can plot easily, e.g., by typing "plot x+1/x" into Google search. And by the way, 2+1/2 is 5/2. not 3/2.
Comment: Thank you for the answer. I am still not sure how the point outside of the disk are mapped. Because when I try to plug in poins on the vertical line with Re(z)=2,I am not sure how the points are mapped by z+1/z. In particular z=2,it is mapped to 3/2 but I do not see any pattern of the points on the line.


If odds is uniformly distributed, what is the distribution of probability?

Question: Suppose $\pi=\frac{\theta}{1-\theta}$ where $\theta$ is between $[0,1]$.
If we set a uniform prior for $\pi$, what is the induced prior on $\theta= \frac{\pi}{1+\pi}$?
I'm stuck on this problem. Can someone help me out?
Comment: As $\theta$ ranges from $0$ to $1$, $\pi$ ranges from $0$ to $\infty$.  There is no uniform distribution on that.
Answer: If $0\le \pi \le 1$ then $0\le\theta\le\frac 1 2 .$
\begin{align}
f_\theta(t) & = \frac d {dt} \Pr(\theta\le t) \\[8pt]
& = \frac d {dt} \Pr\left( \frac \pi {1+\pi} \le t \right) \\[8pt]
& = \frac d {dt} \Pr\left( 1 - \frac 1 {1+\pi} \le t \right) \\[8pt]
& = \frac d {dt} \Pr\left( \frac 1 {1+\pi} \ge 1-t \right) \\[8pt]
& = \frac d {dt} \Pr\left( 1+\pi \le \frac 1 {1-t} \right) \\[8pt]
& = \frac d {dt} \Pr\left( \pi \le \frac 1 {1-t} -1 \right) \\[8pt]
& = \frac d {dt} \frac 1 {1-t} \\[8pt]
& = \frac 1 {(1-t)^2} \quad \text{for } 0\le t \le \frac 1 2.
\end{align}


How to deal with 'internal:' in your link->uri?

Question: I have a link field, which I can populate with both internal and external links:

/node/123

I'm building an API that parses the node and returns the URL from the link field:
$node->my_field->uri
Which returns internal:/node/123 which makes this URL useless.
If I try using use Drupal\Core\Url; and Url::fromUri($node->my_field->uri), I get a 500 error!
So what is the correct approach for getting a formatted URL, that can parse both internal and external links?
Answer: just kidding. To help future devs with this issue, check the logs *duh and you'll see this:

PHP message: Uncaught PHP Exception InvalidArgumentException: "The URI '' is invalid.

So, check for the uri value first!
$node->my_field->uri ? Url::fromUri($node->my_field->uri)->toString() : null,
Comment: You can also use $node->get('my_field')->get(0)->getUrl(). you still need to check it for not being empty though


How to reference *.d.ts in vscode globally

Question: To enable intellisense in vscode for frameworks such as jasmine, we need to reference the typing file explicitly at the top of every typescript file like below:
/// <reference path="./node_modules/@types/jasmine/index.d.ts" />

Is there a way to globally reference all the typing files in vscode so we don't need to reference them in each typescript file?
Comment: They generally get picked up automatically unless you have specified the `types` array in tsconfig. If you have, add jasmine to it. In fact, excluding types is what is hard
Comment: I assume you were writing test suites. To enable ts, you have to create a  `tsconfig.json` under your test files directory. In most cases, there is something wrong with `tsconfig.json` when intellisense is not working.
Answer: If you have a tsconfig.json, typings from node_modules/@types should be picked up automatically. You can make sure you TS file is part of your tsconfig.json by running the TypeScript: Go to Project Configuration command in VSCode
If you have a tsconfig.json but still are not seeing the jasmine typings, try updating your tsconfig.json to explicitly include the jasmine types:
{
    "compilerOptions": {
        ...
    },
    "typeAcquisition": {
        "include": [
            "jasmine"
        ]
    }
}

If that still isn't working, please file a bug
Comment: Note this assumes you are using TypeScript 2.2+


About prime ideals in lattice theory

Question: Can anyone help me with this question?
If I and J are two ideals in a complete lattice and their intersection is contained in a prime ideal P ,then is it true that either I is a subset of P or J is a subset of P
Answer: Suppose that $I \cap J \subseteq P$ and $I \nsubseteq P$, and conclude that $J \subseteq P$.
If $I \nsubseteq P$ then there exists $x \in I$ such that $x \notin P$, whence $x \notin J$.
Take $y \in J$ (we wish to prove that $y \in P$).
Since $x \in I$ and $y \in J$, we have $x \wedge y \in I \cap J$. (Can you see why?)
Thus $x \wedge y \in P$.
As $P$ is prime and $x \notin P$, we must have $y \in P$.

About prime ideals in lattice theory


Autosys JIL ignoring success conditions

Question: I hope someone can point me in the right direction or shed some light on the issue I'm having.  We have Autosys 11.3.5 running in Windows environment.
I have several jobs setup to launch on a remote NAS server.
I needed JOB_1 in particular to only run if another completed successfully.
Seems straight forward enough. In UI there's a section to specify Condition such as: s(job_name) as I have done and I'm assuming that ONLY if the job with name job_name succeeds that my initial job should run.
No matter what I do, when I make the second job fail on purpose (whether manually setting its status to FAILURE) or changing some of its parameters so that its natural run time causes it to fail. The other job that I run afterwards seems to ignore the condition altogether and complete successfully each time.
I've triple checked the job names (in fact I copy and pasted it from the JIL definition of the job so there are no typos), but it's still being ignored.
Any help in figuring out how to make one job only run if another did not fail (and NOT to run if it DID fail) would be appreciated.
Comment: This question is about server management software. Unless you are writing software with the autosys SDK, your question should be asked on [sf] instead.
Answer: If both the jobs are scheduled and become active together, then this should not happen.
The way i think is, you must be force starting the other job while the first is failed. If thats the case, then conditions will not work.
You need to let both the jobs start as per schedule, or at least the other job start as per schedule while the first one is failed. In that case the other job will stay in AC state until the first one is SU.
Let me know if this is not the case, i will have to rephrase another solution then.
Comment: Thank you for replying.  I attempted to follow your advice (I hope I understood you correctly).  I've modified the JOB2 on which JOB1 depends to fail and let it run on its usual time and fail naturally instead of force execute it or set any status to it in any way.
JOB2 run, FAILED on it's own, JOB1 run afterwards still having the condition clause s(JOB2) and it run successfully. My understanding was it was not suppose to run at all, yet it did run.  How do I prevent JOB1 from running if JOB2 has status of FAILURE.  Thanks in advance!!!
Comment: I still think it should not. If its still on, I would need more details on the job setup. Like are they in the same box or are two stand alone jobs. if you could get me the jil for the jobs would be more appropriate.

Autosys JIL ignoring success conditions


How prove this diophantine equation $3^x-2^y=k$ have finitely many integral solutions

Question:
For any $\forall k\in N^{+}$ show that the diophantine equation $3^x-2^y=k$ have  finitely many integral solutions.

My try: if $k=2m$,then
$$3^x=2^y+k=2^y+2m$$ It is clear there is no integer solution,
But for
$k=2m+1$, I can't prove three finitely many integral solution.
Thank you.
Comment: This is a result of Størmer's theorem.
http://en.wikipedia.org/wiki/Størmer's_theorem
Comment: Hello,Thank you,can you find somepaper reseacher this problem,I find sometime,I can't find paper.
Answer: This is a result of a theorem due to Carl Størmer.  His theorem can be stated as follows:
Let $S=\left\{ p_1^{e_1} p_2^{e_2} \cdots p_j^{e_i} \mid e_i \in \mathbb{N}_0 \right\}$, where $p_1$, $p_2 \cdots p_j$ is a finite collection of prime numbers.  Then there are a finite number of pairs $x,y \in S$ such that $x-y=k$ (for fixed $k$).
Unfortunately, the wikipedia page for the theorem only considers the $k=1$ case, when in fact Størmer had proven it for all integer values of $k$.
Sources:

http://projecteuclid.org/download/pdf_1/euclid.ijm/1256067456
http://en.wikipedia.org/wiki/Størmer's_theorem
Comment: @abiessu Stormer's theorem guarantees that there are at most a finite number of solutions, and provides method to construct every solution.
Comment: It's not immediately clear how $k=1$ could have any solutions, since $S$ would be a single-element set...
Comment: Ah, oops, inconsistent variables.  This is what happens when I'm running low on sleep..
Comment: Hello,this theorem how prove it?
Comment: @math110 Check the first link, an article titled "On a problem of Stormer" by D. Lehmer.  Also I have heard of an article titled "A generalization of the Stormer theorem and some applications" which I have not read, but it sounds promising.  These should provide constructive proofs.
Comment: Does stormers theorem guarantee that there exist solutions, or only that there can be at most a finite number of them?


Diffeomorphism between upper hemisphere $S^{2}_+$ and $B^2(0,1)$

Question: I have confusions about how exactly the process of showing homeo-/diffeomorphism differs between embedded manifolds and ones that are just on their own. Here we have a hemisphere in $\mathbb{R}^3$ and the unit ball in $\mathbb{R}^2$.
So, the open upper hemisphere, $S = \{x \in \mathbb{R}^3 \mid \|x\|_2 = 1 \text{ and } x_3 > 0 \}$, and the open unit ball $B^2(0,1)$.
Obviously there is a diffeomorphism between the two: you flatten the sphere and that's about it, but I'm getting stuck on details about the dimensions and the implicit function theorem.

The only way of finding a diffeomorphism I know is by the inverse function theorem, for which I need an invertible Jacobian and $C^1$ function, but let's say I map the sphere as such: $f(x,y,z) = (x,y)$. The Jacobian is not square and not invertible.
Using the implicit function theorem, I couldn't really figure out how to use it, here. What exactly to parameterise, all that. $x^2 + y^2 + z^2 - 1 = 0$. No getting a useful Jacobian, nor a map to $\mathbb{R}^2$. There's probably some way to work it through here, but I've not been able to figure it out.

I was also looking at $f(x,y) = (x,y,\sqrt{1-x^2-y^2})$, which seems very promising. Maintains the zeros of the implicit function, at least. Well, I'd appreciate some help concerning specifically these ideas. Thanks.
Answer: Identify $(x,y,0)\cong (x,y).$ It is easy to check that the projection $\pi(x,y,z)=(x,y,0)$ maps the upper hemisphere bijectively onto the disk. In fact, the inverse is $\pi^{-1}(x,y,0)=(x,y,\sqrt{1-x^2-y^2})$ so they are homeomorphic. However, this map does not provide a diffeomorphism (why? Hint: what happens at the boundary?)
But the stereographic projection $\sigma:\mathbb R^2\setminus \{(0,0,1)\}\to \mathbb R^2\times \{0\}\cong \mathbb R^2$ from the north pole $\sigma(x,y,z) = \frac{(x,y,0)}{1-z}$  has  inverse $\sigma^{-1}(x,y,0)=\frac{(2x,2y,\sqrt{x^2+y^2}-1)}{\sqrt{x^2+y^2}+1},$ and you can check that $\sigma^{-1}$ maps the closed disk diffeomorphically onto the lower hemisphere.
Comment: Yes, vertical gradients, but my confusion about that case is much simpler: suppose I only care about the open disc. The Jacobian determinants are all 0 due to the projections. How do I get around this? Or, are you saying I simply can't use the inverse function theorem and have to characterise differentiability manually for $\pi$ and $\pi^{-1}$?
Comment: Look at the composition $(x,y)\overset{i}\rightarrow(x,y,\sqrt{1-x^2-y^2} \rightarrow (x,y)$
Comment: Hmm... how about this: there is clearly a homeomorphism between the $S^2_+$ and $B^2$, so $S^2_+$ is a 2-manifold, and then because the rank of the derivative of $\pi^{-1}$ is $2$, we get that it's a differentiable manifold?


Binomial Probability Problem Involving Processors Breaking

Question:
An electronics company distributes a particular type of processor. When someone orders  this particular processor, they are sent a box containing $20$. The company's newest employee, Peter, is tasked with testing the quality of the order before it is dispatched. The company tells Peter there is $1\%$ chanced that a new processor is faulty, therefore, they always keep a box of $5$ spares next to his workstation.
However, someone has accidentally added the wrong processor to the 'replacements box'. We will call this processor, 'processor $A$'.
What is the probability that processor $A$ is added to the box that needs to be shipped? You may assume that each processor is independent of each other processor and that the shipment goes ahead even if there's insufficient processors.

My solution,
Let $X$ be the number of faulty processors out of $20$.
$\begin{align} Pr(X \geq 1) & = 1 - Pr(X = 0)\\&=1 - {20\choose 0}(0.01)^0(0.99)^{20}\\ &= 0.82 \end{align}$
Let $A$ be processor $A$ is drawn from the spares box,
$Pr(A) = \dfrac{1}{5}$
Now, for the probability that processor is used,
$\begin{align} Pr(X \geq 1)\times Pr(A) & = 0.82 \times \dfrac{1}{5} \\ &= 0.16 \end{align}$
Therefore, Peter has a $16\%$ chance of adding the wrong processor.
Is this correct? I feel like I can't multiply the probabilities like I have above.
Answer: The probabililty that processor $A$ is drawn from the spares box equals to $1/5$ only for the case when there is exactly one wrong processor found.
If Peter will find $2$ wrong processors, the probability that $A$ will be drawn from the replacement box along with some other processor is $2/5$. For three wrong processors this probability is $3/5$ and so on. For the case when Peter find $5$ or more wrong processors, $A$ will appear in the box certainly.
So, denote by $A$ the event that processor $A$ is drawn from the spares box.
$$
\begin{align}
& Pr(A\mid X=1)=\frac15,\\ & Pr(A\mid X=2)=\frac25, \\ & Pr(A\mid X=3)=\frac35,\\ & Pr(A\mid X=4)=\frac45,\\ & Pr(A\mid X\geq 5)=1.
\end{align}
$$
And $Pr(A\mid X=0)=0$.
By  Law of Total Probability,
$$
P(A)=P(X=1)Pr(A\mid X=1)+\ldots+P(X=4)Pr(A\mid X=4)+P(X\geq 5)Pr(A\mid X\geq 5).
$$
So you should calculate all the probabilities about $X$ separately and use it in the above formula.


Count function from 2 tables in database

Question: I have 2 tables like these
rental_tabel
id |    date       |   cust_id               |     driver_number
1     2019-01-02          1                         F 3350 NN
2     2019-04-02          2                         AX 111 Z
3     2019-05-02          3                         S 787  X
4     2019-05-02          4                         T 9090 M
5     2019-06-02          3                         P 8989 L

user_table
cust_id |   name
1          John
2          Doe
3          Michael
4          Leonard
5          Steve

How do I count customer name who's shown more than once in the rental table?
I have using count function, and I can count the id shown more than once, but I still can't get the name of customer
Here's my count query
SELECT COUNT(rental_table.cust_id) AS total FROM rental_table WHERE rental_table.cust_id>'1'

and the result is
| total   |
-----------
|   2     |

Where's I can add to get the customer name from that count function?
Comment: Use a HAVING clause for COUNT() conditions.
Answer: You can use GROUP BY cust_id with the following HAVING clause :
SELECT u.name
  FROM rental_table r
  JOIN user_table u
    ON u.cust_id = r.cust_id
 GROUP BY cust_id
HAVING count(cust_id) > 1

Comment: @IkramShabri thank you, too. Btw, please consider using related DBMS tag for your SQL questions in the future.