How do I set a table header in Views 3?

Question: How exactly do I get a table header to appear above the table?
In views-view-table.tpl.php I can see a
 section, but what causes it to actually get rendered?
Where do I specify the column header text?
I tried various options in the settings page, but to no avail.
Answer: The title can be defined from the Main views form.  Each column of the table is associated with a field.  If you select the field you can "add label" by selecting the checkbox and providing a name.  The Label will appear in the header of the table.
Comment: Thanks JoeS, I knew this was something silly simple [blush]
Comment: Fortunately, I have never been in your position !!!!! :D
Comment: Somehow I only believe in your original answer ;-) Thanks though!
Comment: I'm used to remove labels when setting up views. This is one of the few cases I needed to add them. Your solutions is pretty accurate to get table headers :)

How do I set a table header in Views 3?


Does using modules Metatags and Metatags Quick together cause SEO problems?

Question: I am checking the SEO of my Drupal 7 site, where I installed the Metatag and the Metatag Quick modules.
Does using both the modules together on a site cause SEO problems?
Comment: I can't imagine you would need both modules. The Metatag module is extremely powerful and should be able to handle any task without the need of Metatag Quick.
Answer: You have to be careful so that the output of each module won't overlap. For instance, the same meta should not be present twice and even worse with even slightly different values. I am not aware of the exact SEO penalty depending on the engine, but it is common sense.
You can examine the output of the modules for the  tag with the browser's inspector, or Firebug.


My only user is not allowed to login into my postgresql server, what can I do?

Question: I think that, accidentally, I changed my user to a role with no log in allowed. Now I can't even log in to give log in privileges to the role. Is there something I can do?
I think there was only 1 user and I don't know how to list all my users if I can't log in first.
Thanks
Addendum
I reinstalled postgres and it seems that no postgres user exists. I installed it via brew:
Answer: The main superuser account is set up by initdb when run and will default to the current system user name, not postgres, unless an explicit -u/--username argument is given.  From your above \du output it's clear that when you set up the server you did it with your laygr system user as that user is the database server's main superuser account.
Should you mess up your login privileges or forget your password you can get back into the server if you have write access to it's data directory in order to be able to edit pg_hba.conf.  Just change the auth-method on the relevant line to trust and reload the server's config via pg_ctl reload.  You can then log in, fix your user/password, and then revert the changes you made to pg_hba.conf and reload the config again.
Answer: Use the default user postgres to login and re-enable your account. Sure, you need to know the postgres user's password...
Comment: As far I know, a postegres user is *always* present on a postgres installation. If you can not find it, try with user `pgsql`
Comment: Ok, so you basically disabled/impaired your superuser account. I think re-installation is the only possibility in this case. However, I suggest you to ask on postgresql mailing list for more information.
Comment: Maybe it's because I installed postgres via brew, but there is no postgres user...
Comment: I already reinstalled postgresql and I can say that when doing `psql \l` and `psql \du` no postgres user or role is shown.
Comment: So, what users are shown on a fresh installation?
Comment: I added a screenshot to the question so that you can see that only one user and role exists. That user/role wouldn't log in since I removed by accident its log in privileges.


Jenkins is not recognizing toolchains.xml file

Question: Could you please help me out with the following issue.
I have installed Jenkins in my Windows 7 OS using Windows Installer.

My project has settings.xml and toolchains.xml, which are placed under conf directory of Maven.Neither.
settings.xml or toolchains.xml files are present under /usr_home/.m2/ directory.
I can successfully build project manually , but when tried to build with Jenkins , toolchains.xml file is not getting identified. I have been receiving error message

Please make sure you define the required toolchains in your ~/.m2/toochains.xml file.

I tried putting toolchain.xml file in /usr_home/.m2/ , but didn't work.

Any kind of help will be really appreciated.
Comment: Possible duplicate of [Maven toolchains.xml location under Jenkins](http://stackoverflow.com/questions/11902652/maven-toolchains-xml-location-under-jenkins)
Answer: When I experienced the problem, toolchains.xml were not read from the maven conf library, only settings.xml.
You would have to either place toolchains.xml in you ~/.m2 folder or use
mvn -t <path> to point to a secondary toolchains file.
The -t option was not available initially, so you may have to be at mvn 3.2 I think or higher.
Comment: And most probably Jenkins runs as a specific user, so home is probably \users\jenkins or something.
Answer: Thanks Niels for the reply. I finally managed to fix the issue. It seems like an existing issue in maven3.3.3 with Jenkins in Window OS where -t option will not work with Jenkins.
https://issues.jenkins-ci.org/browse/JENKINS-28629
So I replaced it with maven3.0.5 and it did the wonder.
Regards,
Jibi


Passing Two Values to PHP File Via AJAX

Question: right now I'm successfully passing one value to a Bootstrap modal via AJAX, however when I attempt to pass a second value my code stops working.
JavaScript
function claimOrder(str, stre){
if (str=="") {
document.getElementById("txtH").innerHTML="Blank Order ID";
return;
}
if (stre=="") {
document.getElementById("txtH").innerHTML="Blank User ID";
return;
}

if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtH").innerHTML=xmlhttp.responseText;
}
}xmlhttp.open('GET','assignuser.php?q='+str'&w='+stre,true);
 xmlhttp.send();
}

Button That Triggers Function
echo 'Claim
';

Modal Called by Button

Loading...

PHP
<?php
$q = intval($_GET['q']);
$w = intval($_GET['w']);

etc... No changes were made to the PHP that worked before adding the second variable to the AJAX call except the extra line defining $w. If I remove the extra parameter from the function and function call line assignuser.php runs fine and the modal is populated, so I'm pretty sure the problem is somewhere in the JavaScript.
Answer: You forgot a + in this portion of the code:
xmlhttp.open('GET','assignuser.php?q='+str'&w='+stre,true);

So you will need to adjust it to:
xmlhttp.open('GET','assignuser.php?q='+str+'&w='+stre,true);

Comment: That's all it will take
Comment: Thank you, I've added the + but still no luck
Comment: When you output both values, are you getting any results?
Comment: Nope, if I replace the statement replacing the modal text with the response text with a statement outputting the values I get no results, as if the function wasn't running
Comment: Ahhh I believe the additional issue is that I was trying to pass a string to w, when the php code to handle is: $w = intval($_GET['w']); How should I edit this php to accept a string?
Comment: $w = $_GET['w']; should suffice.
Comment: Odd that this doesn't work... if I change the second variable to an integer and use $w = intval($_GET['w']); it works, when I replace it with a string variable (or predefined string) and $w = $_GET['w']; it doesn't. Is there something in the JS I need to change for it to pass the string along?

Passing Two Values to PHP File Via AJAX


Half oval 3 over notes

Question: I'm a bit confused about this graphic, notice the half ovals on top with the 3 in the center:

Is that a "triplet" and the same as this graphic in guitar pro?

Please note that I have searched but I am asking because  one has a oval kind of thingy on top and the second has a bracket kind of thingy.
Some of the answers I found are:
What exactly does a 3 mean over a quarter note and an 8th note?
I just want to double check instead of getting my ground/foundation wrong as I am very much still learning this stuff.
Are they the same and are they both triplets or something else?
Comment: It could be a combination of a triplet and a slur - a slurred triplet - although normally I would expect to see t he slur under the heads not over the beam. Also for beamed triplets the bracketing isn't needed since the beam performs the role of the bracketing.
Answer: Yes they are both triplets.
If they were not eigth note triplets, the measure would not add up to 4 quarter notes, but instead 5 quarter notes. Another thing to note is notice how the notes are beamed to make 4 groups. This is  to clearly show each beat i.e. each quarter note. As you can see, those notes form  one group together equaling 1 quarter note so there's no doubt that they are triplets.
Comment: It does not matter. Sometimes it is notated with just a number three above the triplets
Comment: @Ryan I'm sure it's just the style of whatever software created it. The bracket is much, much more common, but they are equivalent.
Comment: Thanks for replying! Is there any particular reason one is curved (half oval) and the other "brackety"? New style or just differences in the software or 'old' vs 'modern' way of writing it?
Comment: Thanks, I'll make a note that the "graphic" does not really matter, if there is a 3 on top, its a triplet. Feel free to correct me if I am wrong. Cheers!
Comment: My impression is that the curved bracket was much more common in older music. I started music lessons a half-century ago, and the square bracket is actually less familiar to me.
Comment: Note the number 3 is printed with italics. That way it is different from fingering suggestions. Regarding square brackets: This way it is different from slurs.

Half oval 3 over notes


How to use string indexing with IDataReader in F#?

Question: I'm new to F# and trying to dive in first and do a more formal introduction later.  I have the following code:
type Person =
    {
        Id: int
        Name: string
    }

let GetPeople() =
    //seq {

    use conn = new SQLiteConnection(connectionString)
    use cmd = new SQLiteCommand(sql, conn)

    cmd.CommandType <- CommandType.Text

    conn.Open()
    use reader = cmd.ExecuteReader()
    let mutable x = {Id = 1; Name = "Mary"; }

    while reader.Read() do
        let y = 0
        // breakpoint here
        x <- {
        Id = unbox<int>(reader.["id"])
        Name = unbox<string>(reader.["name"])
        }
    x

    //}

let y = GetPeople()

I plan to replace the loop body with a yield statement and clean up the code. But right now I'm just trying to make sure the data access works by debugging the code and looking at the datareader.  Currently I'm getting a System.InvalidCastException.  When I put a breakpoint at the point indicated by the commented line above, and then type in the immediate windows reader["name"] I get a valid value from the database so I know it's connecting to the db ok.  However if I try to put reader["name"] (as opposed to reader.["name"]) in the source file I get "This value is not a function and cannot be applied" message.
Why can I use reader["name"] in the immediate window but not in my fsharp code?  How can I use string indexing with the reader?
Update
Following Jack P.'s advice I split out the code into separate lines and now I see where the error occurs:
    let id = reader.["id"]
    let id_unboxed = unbox id // <--- error on this line

id has the type object {long} according to the debugger.
Answer: Jack already answered the question regarding different syntax for indexing in F# and in the immediate window or watches, so I'll skip that.
In my experience, the most common reason for getting System.InvalidCastException when reading data from a database is that the value returned by reader.["xyz"] is actually DbNull.Value instead of an actual string or integer. Casting DbNull.Value to integer or string will fail (because it is a special value), so if you're working with nullable columns, you need to check this explicitly:
let name = reader.["name"]
let name_unboxed : string =
  if name = DbNull.Value then null else unbox name

You can make the code nicer by defining the ? operator which allows you to write reader?name to perform the lookup. If you're dealing with nulls you can also use reader?name defaultValue with the following definition:
let (?) (reader:IDataReader) (name:string) (def:'R) : 'R =
  let v = reader.[name]
  if Object.Equals(v, DBNull.Value) then def
  else unbox v

The code then becomes:
let name = reader?name null
let id = reader?id -1

This should also simplify debugging as you can step into the implementation of ? and see what is going on.
Answer: You can use reader["name"] in the immediate window because the immediate window uses C# syntax, not F# syntax.
One thing to note: since F# is much more concise than C#, there can be a lot going on within a single line. In other words, setting a breakpoint on the line may not help you narrow down the problem. In those cases, I normally "expand" the expression into multiple let-bindings on multiple lines; doing this makes it easier to step through the expression and find the cause of the problem (at which point, you can just make the change to your original one-liner).
What happens if you pull the item accesses and unbox calls out into their own let-bindings? For example:
while reader.Read() do
    let y = 0
    // breakpoint here
    let id = reader.["id"]
    let id_unboxed : int = unbox id
    let name = reader.["name"]
    let name_unboxed : string = unbox name
    x <- { Id = id_unboxed; Name = name_unboxed; }
x

Comment: @User If it's a `long` then you need to unbox it as an `int64` (F# syntax for `long`). I think you'll need to unbox it to the correct type (`int64`) *then* cast it to an `int` if that's what you need -- you can't just unbox it directly (that's causing the error you're seeing now).
Comment: This was helpful. The line `let id_unboxed = unbox id` has the error.  Looking at the type of `id` in the debugger it shows `object {long}`.  In the immediate window, `id is long` returns true while `id is int` returns false. So I'm guessing it has something to do with int vs long casting.  Will experiment further.
Comment: If I change my Person type to use `int64` instead of `int` it works.  Not sure why it's pulling the id as long from the db.
Comment: Just found out that SQLite uses int64's for integer primary keys so that explains it: http://sqlite.org/version3.html


Parameter estimation for random variables where a control parameter is another r.v

Question: Let $\{X_i\}$ a sequence of independent random variables.
Each $X_i$ has a p.d.f $p(m, \theta)$. Where $\theta$ is a real unknown parameter and $m$ the outcome of another random variable $M$ with p.d.f $p(m)$.
I have the next protocol to get a sample $\bar{x}=\{x_1,...,x_n\}$:
First, I get the value $m_1 \sim p(m)$.
Then I obtain the value $x_1 \sim p(m_1 \theta)$.
And I repeat the process $n$-times.
The aim is to estimate the value of $\theta$ from $\bar{x}$.
My questions:

the maximum likelihood estimator is the best way to do that?
Are there lower bound inequalities for the variance of the estimator for $\theta$?

When $m$ and $\theta$ are real unknown parameters, I know that there is the Cramér-Rao Bound, and when one has a parameter that is a random variable there exists the Van Trees inequality. But in this situation, I don't know if there is a standard inequality.
Answer: Regarding your questions:

I think there is a confusion: it does not really make sense to ask if the MLE is a "good way" to estimate $\theta$. As its name suggests, the MLE is your best estimate of $\theta$ that maximizes the likelihood of your observation, so yes, it is pretty good ^^ But a more relevant question is how to obtain your MLE. Given that you have both observed variables $X_i$ and hidden variables $M_i$, I would suggest using the Expectation-Maximization algorithm.
You can indeed use the Cramér-Rao bound. In this case, the likelihood used to compute the Fisher Information is the likelihood of your observations $X_i$, obtained by marginalizing the joint distribution of the observed and hidden variables:

$$
p(X_i|\theta) = \sum_{M_i}p(X_i|M_i,\theta)p(M_i)
$$
I highly recommend this article, in which the authors use the EM algo to obtain the MLE of a vector of parameters $\theta$, and also compute the Fisher Information matrix: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4867027/
Answer: The (complete information) likelihood in this model is$$\prod_i p(x_i|m_i,\theta)\tag{1}$$which can be maximised or used in a Bayesian analysis, providing a prior $p(\theta)$ is chosen. (There is no "best way to estimate" a quantity, it all depends on the utility function for running the estimation.)
In the event the $m_i$'s are not observed, the (observed) likelihood becomes$$\prod_i \int p(x_i|m,\theta)\,p(m)\,\text{d}m\tag{2}$$
If there exists an unbiased estimator of $\theta$ in this setting, $T_n(X_1,\ldots,X_n|m_1,\ldots,m_n)$ then it satisfies the Cramér-Rao
inequality$$\text{cov}(T_n(X_1,\ldots,X_n|m_1,\ldots,m_n)) \ge I_n^{-1}(\theta;m_1,\ldots,m_n)$$where $I_n(\theta;m_1,\ldots,m_n)$ is the (complete) Fisher information matrix associated with (1):
$$I_n(\theta;m_1,\ldots,m_n)=-\sum_{i=1}^n\mathbb{E}_\theta \left[
 \dfrac{\partial ^2}{\partial \theta \, \partial \theta^\text{T}} \log p\left(X| m_i,{\theta}\right)\right]$$
Once again, if the $m_i$'s are not observed, the observed Fisher information become
$$I_n(\theta)=-n \mathbb{E}_\theta \left[
 \dfrac{\partial ^2}{\partial \theta \, \partial \theta^\text{T}} \log p\left(X| {\theta}\right)\right]=-n \mathbb{E}_\theta \left[
 \dfrac{\partial ^2}{\partial \theta \, \partial \theta^\text{T}} \log \int p\left(X| m,{\theta}\right)p(m)\,\text{d}m \right]$$
Comment: I am not absolutely sure about the way you define the likelihood in the model. Here, you seem to consider the conditional likelihood of $x_i$ given $m_i$. But I guess the original question implies that $m_i$ is a hidden variable, to which we do not have access. If this is the case, we should define the likelihood of the observations as $p(x_i|\theta) = \sum_{m_i}p(x_i|m_i,\theta)p(m_i)$


MySql - Pivot Table

Question: I'm trying to pull some data out of the wp_postmeta table which is basically a series of key/value pairs tied to a numeric post_id. As such, when I try to extract various values for a post, this is what I get:

This is the current query I'm using to get that output:
select post_id,meta_key,meta_value from wp_postmeta
where meta_key in ('_sku','_length','_width','_height')
and post_id in (
    select post_id from wp_postmeta
    where meta_value in ('28-005080','28-005287')
    )
    order by post_id DESC

What I'm trying to do is format the information like this:

I've tried to look at the MySql pivot table examples, but I'm not sure if they quite fit this specific scenario. Frankly, I don't know where to start with accomplishing this task.
Comment: Consider handling issues of data display in application code
Comment: Forgive me, but what exactly do you mean by this suggestion?
Comment: You mentioned Wordpress, so evidently you have some access to /awareness of things beyond MySQL.
Answer: You can use conditional aggregation:
select post_id,
    max(case when meta_key = '_sku'    then meta_value end) as sku,
    max(case when meta_key = '_length' then meta_value end) as length,
    max(case when meta_key = '_width'  then meta_value end) as width,
    max(case when meta_key = '_height' then meta_value end) as height
from wp_postmeta
where
    meta_key in ('_sku','_length','_width','_height')
    and post_id in (select post_id from wp_postmeta where meta_value in ('28-005080','28-005287'))
group by post_id
order by post_id desc

Actually, we might be able to replace the subquery in the where clause with a having clause:
select post_id,
    max(case when meta_key = '_sku'    then meta_value end) as sku,
    max(case when meta_key = '_length' then meta_value end) as length,
    max(case when meta_key = '_width'  then meta_value end) as width,
    max(case when meta_key = '_height' then meta_value end) as height
from wp_postmeta
group by post_id
having max(meta_value in ('28-005080','28-005287')) = 1
order by post_id desc

MySql - Pivot Table


SQL question conjunction

Question: Let's say you have a simple table with two fields: account and item:
An account can have multiple items.  For example:
Account    Item
11         Apples
11         Pears
11         Crackers
12         Apples
12         Bannanas
12         Cookies
13         Pears
13         Carrots
13         Apples

How would I write a query so that I could select all accounts with some specified set of items.   For example, how would I write  query so that I would select accounts where the fields are assigned both Apples and Pears (in the example accounts 11 and 13).
Thank you for your help.
Elliott
Comment: BTW: The term for this is [Relational division](http://www.simple-talk.com/sql/t-sql-programming/divided-we-stand-the-sql-of-relational-division/)
Answer: You could construct a query that will leave only the apples and pears in the set, then group by account and count the distinct items. If it matches the count expected (2 in this case) then the account has the full set.
select account
from tbl
where item in ('apples','pears')
group by account
having count(distinct item) = 2

Comment: +1 You seem to be the only one that actually understood what was asked
Answer: SELECT DISTINCT account From Table WHERE item in ('Apples','Pears')

Answer: You can use a self-join to access information from two rows of the same table at once:
SELECT ai0.Account
FROM accountitems AS ai0
JOIN accountitems AS ai1 ON ai0.Account=ai1.Account
WHERE ai0.Item='Apples'
AND ai1.Item='Pears'

Comment: You are missing a `DISTINCT` or a `GROUP BY`
Comment: Only if completely identical rows were permitted, which would be an unusual approach IMO.
Answer: You could use a query like this.
SELECT Distinct Account From MyTable WHERE Item = 'Apple' or Item = 'Pears';

This query will return a list of all the accounts, that have the item is apple or pears.  The Distinct ensures that each account only shows up once.

SQL question conjunction


How to Numerically Solve an integral equation.

Question: First I really doon't have any background with integral equations! That said, I would like to solve the following:
$$\int_a^b \frac{K(t)}{t-x} \phi(t) dt=f(x) , a<x<b$$
where$$\int_a^b \phi(t) dt=0$$
Specifically, $a=-1, b=1$, $K(t) = \sqrt{\frac{1-t}{1+t}}$, and $f(x)=1$.
I'd like to turn this into a linear system $MX=Y$ where $X_i=\phi(t_i)$ and $Y_j=f(x_j)$
I've chosen $t$ to run from -1 to 1 with $dt=.2$ and I've chosen x to be the midpoints between the $t_i$'s to avoid any zero denominators.
My dilemma is how to create M. What should be in M actually. How does the condition that the integral of $\phi$ being zero come into play?
Comment: How can you have "chosen $x$ to be the midpoints between the $t_i$s"? In the first formula, $x$ appears to be a free variable, which doesn't change during the integration. The condition on $\phi$ also seems not to be much of a constraint. Maybe it would be more useful to edit the question so that you start a few steps _before_ you get to this integral, and explain how you got it.
Answer: Partial answer : Because of the kernel $1/(t-x)$, the integral exists only as a Cauchy principal value, so naive methods of quadrature will give you gibberish. Your equation is not the usual Fredholm integral equation, but a singular integral equation.
As it happens, this particular equation has nice closed form solutions (For instance, look at the text by Kanwal and Estrada). If you have taken a complex variables course, you should be able to follow it. The other thing is that you have to specify what class of solutions you are interested in (bounded at both ends, unbounded at both ends or mixed). Without that, the equation does not have a unique solution.
Your scheme of choosing the x locations to be midway between the t is not guaranteed to minimize the error in quadrature. This is why numerical methods for singular equations use orthogonal polynomials in a way to minimize the error (in this case, you would use Chebychev polynomials). It is too long to summarize here, but Chebychev polynomials have nice closed form expressions for their cpv, e.g. with the weight function $\sqrt{1-s^2}$
$$
p.v. \int_{-1}^{1} \dfrac{U_n(s)\sqrt{1-s^2}}{s-t} = -\pi T_{n+1}(t)
$$
where $U$ and $T$ are Chebychev polynomials of the first and second kind.


Where are Spring cacheable objects stored?

Question: I'am using Spring cache in my project and i want to analyse the java memory using visualVm, i would like to know where the cache objects

Are really stored in the heap?
Are there stored in the eden or in the old memory?

Thanks.
Comment: Hmm... They can be stored in either area... or niether at all, depending on the type of GC you use. This has nothing to do with Spring, it's up to the JVM to decide where to put an object and when to move it from one area to another.
Answer: It is not possible to know where any object is stored, not just Spring objects. An object might be in eden, a survivor space, or tenured. In JDK 7 or earlier, certain things such as classes are stored in perm gen (per this Oracle blog post: "Permanent generation has been completely removed in JDK 8".).
The garbage collector can and will move objects around under the covers. When and how that happens depends on the specific garbage collector you're using, which flags you're using to specifiy GC behavior, and what the rest of your application is doing with memory (reads and writes).
Eden, survivor, and tenured are all on heap. For older JVMs, some things will be allocated in perm gen which is off heap. Take a look at the "Monitoring Memory Consumption" in this document on JConsole usage for more details.
Also from that doc, this is a nice summary of heap vs. non-heap:

Heap and Non-Heap Memory
The Java VM manages two kinds of memory: heap and non-heap memory, both of which are created when the Java VM starts.

Heap memory is the runtime data area from which the Java VM allocates memory for all class instances and arrays. The heap may be of a fixed or variable size. The garbage collector is an automatic memory management system that reclaims heap memory for objects.

Non-heap memory includes a method area shared among all threads and memory required for the internal processing or optimization for the Java VM. It stores per-class structures such as a runtime constant pool, field and method data, and the code for methods and constructors. The method area is logically part of the heap but, depending on the implementation, a Java VM may not garbage collect or compact it. Like the heap memory, the method area may be of a fixed or variable size. The memory for the method area does not need to be contiguous.


Ricci curvature with positive lower bound...

Question: There is a theorem of Reilly concerning the first Dirichlet eigenvalue $\lambda$ of the Laplacian on a n-dimensional compact Riemannian Manifold $(M,g)$ whose Ricci curvature $Ric$ has a positive lower bound $(n-1)K$ for some constant $K>0$. Namely, it states that $\lambda \geq nK$. (Note, that the manifold has non-empty boundary.)
I would like to know, what does the condition $Ric\geq (n-1)K$ precisely means, because the left hand side is a rank 2 tensor and the righthand side is a real number. How can I check that condition?
Remark: Sometimes the conditions is also writen as $Ric(M)\geq(n-1)K$.
Answer: It means ${\rm Ric} \ge (n-1)Kg$ in the sense of quadratic forms; i.e. that the 2-tensor $${\rm Ric} - (n-1)Kg$$ is non-negative definite. More explicitly, $${\rm Ric}(v,v) \ge (n-1) K|v|^2$$ for all $v \in TM$.
Comment: @sand: these conditions make no difference, since both sides are quadratic in $v$.
Comment: Are there any further conditions concerning the choice of $v$, such as $v\neq 0$ or $|v|=1$?


Show that $\int_0^de^{-tx}g(x)dx\sim_{t\rightarrow\infty} \frac{g(0)}{t}$

Question: Let $d>0$. Let $g\in C^0([0,d])$  such that $g(0)\ne0$.
Show that $$\int_0^de^{-tx}g(x)dx\sim_{t\rightarrow\infty} \frac{g(0)}{t}$$
How can I prove that ?
It's the first time I see this kind of exercise
Thank you in advance for your time
Comment: @JLBarba The limit is $t$ not $d$. Thanks
Answer: Here is a start. Making the change of variables $y=tx$ yields

$$ \int_0^de^{-tx}g(x)dx = \frac{1}{t}\int_{0}^{td} g\left(\frac{y}{t}\right)e^{-y} dy. $$

I think you can advance now.
Note:

$$ \int_{0}^{\infty} e^{-y}dy = 1. $$
Comment: @Cryme: Good job. You are very welcome.
Answer: Actually this limit is zero.
Proof.
Let's use the definition of limit:
$\forall\epsilon , \exists\delta \ |\int_0^de^{-tx}g(x)dx|<\delta$
As $g\in C^0([0,d])$, $|g|<c$, is bounded
In addition, it's known that $\lim_{t\rightarrow\infty}e^{-tx}=0$. Therefore for above $\epsilon ,\exists\delta_1 $ such $ |e^{-tx}|<\delta_1$
Putting all together:
$$\left|\int_0^de^{-tx}g(x)dx\right|< c \left|\int_0^de^{-tx}dx\right| < c \ d \ \delta_1 = \delta$$
This should be all.


Product of $n(n-1)/2$ polynomials of the same degree is symmetric

Question: I am trying to prove a simple fact about polynomials in the multivariate polynomial ring $\mathbb{C}[x_1,x_2,...x_n]$, for $n \gt 3$ but I've been getting stuck.
EDIT: After a comment by Tad I realized that as stated the question is incorrect. A slightly different, and I think more correct, version of the question is this:
Suppose we have a set of $n(n-1)/2$ distinct polynomials $P=\{P_1,P_2,...,P_{n(n-1)/2}\}$, each of the same degree, such that the product $\prod_{i=1}^{n(n-1)/2}P_i$ is symmetric with respect to the usual action of $S_n$ on $\mathbb{C}[x_1,x_2,...x_n]$.Then $\forall P_i,P_j \in P$, there exists an automorphism $\phi$ of $\mathbb{C}[x_1,x_2,...x_n]$ such that $\phi(P_i)=P_j$. Below is the question in its original formulation.
Suppose we have a set of $n(n-1)/2$ distinct polynomials $P=\{P_1,P_2,...,P_{n(n-1)/2}\}$, each of the same degree, such that the product $\prod_{i=1}^{n(n-1)/2}P_i$ is symmetric with respect to the usual action of $S_n$ on $\mathbb{C}[x_1,x_2,...x_n]$. Then $\prod_{i=1}^{n(n-1)/2}P_i$ is either of the form $c(x_1+x_2)(x_1+x_3)....(x_{n-1}+x_n)$ or $c(x_1x_2)(x_1x_3)...(x_{n-1}x_n)$, where $c \in \mathbb{C}$; i.e. the set $P$ contains the factors of the first form or the factors of the second form.
I guess another way to put it is that the symmetric polynomials $c\prod_{i\lt j}(x_i+x_j)$ and $c\prod_{i \lt j}(x_ix_j)$ both have $n(n-1)/2$ factors (not counting $c$) and are the only symmetric polynomials in $n$ variables that have $n(n-1)/2$ factors and where the degrees of the factors are pairwise the same.
Is this true? It makes sense to me but there may be something missing. I've been trying to do it by contradiction (contradict the fact that it is a symmetric polynomial), but so far I haven't gotten anywhere. Another thought I had was to try to show that every factor must have 2 distinct variables. Any help or a counterexample would be greatly appreciated.
Comment: why can't $P_{ij}$ be an arbitrary symmetric function of $x_i$ and $x_j$?
Comment: I hadn't considered that. Do you mean something like $x_1^2+x_1+x_2+x_2^2$? I guess that means my question as stated is incorrect. My main motivation though was to show that each factor must be of the same form. For example, if we have the polynomial above, then another factor would have to be $x_3^2+x_1+x_3+x_1^2$. Would this be true?
Comment: Also, it seems that there could only be two variables per factor
Comment: Yes, that's what I had in mind.  Also, it's *not* true that there can be only two variables per factor; you could have $P_{ij}=f(\sigma(x_1,\ldots,x_n),g(x_i,x_j),h(x_1,\ldots,\hat{x_i},\ldots,\hat{x_j},\ldots,x_n))$ where $\sigma$ is $S_n$-invariant, $g$ is $S_2$-invariant, $h$ is $S_{n-2}$-invariant and depends on all variables except $x_i$ and $x_j$, and $f$ is arbitrary.
Answer: This conjecture is false.  Choose a multiple $d=k n$ of $n$, such that $n(n-1)/2$ divides $d$ (that is, $d/\binom{n}{2} = 2k/(n-1)$ is an integer $r$.)  The monomial $x_1^k\cdots x_n^k$, which has total degree $d$, can be divided up into $n(n-1)/2$ degree-$r$ factors in any number of arbitrary ways, having no invariance properties whatsoever.
Comment: Thank you for your response! I am almost convinced. In your example, it is true that the product is invariant with respect to S3 and that it can be divided into the appropriate number of factors, but each factor is not distinct (there are two $x_2x_3$'s). We could also (trivially) factor $x_1^2x_2^2x_3^2$ into $(x_1^2)(x_2^2)(x_3^2)$, and thereby define 6 automorphisms of $\mathbb{C}[x_1,x_2,x_3]$ that permute the factors. Also, that is the only way to factor the monomial so that all the factors are distinct. Off the top of my head, it seems that this would hold for any $n$ and $d$, as well.
Comment: I am far from certain though
Comment: You could also factor it as $(x_1x_2)(x_2x_3)(x_3x_1)$.
Comment: In that case you can find automorphisms of the polynomial ring in three variables that permute the factors. For example, define $\phi_1:\mathbb{C} [x_1,x_2,x_3] \to \mathbb{C}[x_1,x_2,x_3]$ by $\phi_1(x_1)=x_2$, $\phi_1(x_2)=x_1$, and $\phi_1(x_3)=x_3$. Then $\phi_1(x_1x_2)=\phi_1(x_1)\phi_1(x_2)=x_1x_2$, $\phi_1(x_2x_3)=...=(x_3x_1)$ and $\phi_1(x_3x_1)=x_2x_3$. You can similarly define five more $\phi_i$'s so that the set $\{\phi_1,\phi_2,...,\phi_6\}$ is isomorphic to $S_3$. So you're right you can factor it in multiple ways, but the only permissible ways to factor it support the conjecture
Comment: A better example: $x_1^4x_2^4x_3^4=(x_1^3x_2)(x_1x_2x_3^2)(x_2^2x_3^2)$; none of the factors are equivalent under any automorphism.  Incidentally it's interesting to point out that the standard $3\times3$ magic square $\begin{matrix}6&1&8\\7&5&3\\2&9&4\end{matrix}$ yields a factorization of $x_1^{15}x_2^{15}x_3^{15}$ into three factors, where all the individual exponents which occur are different.
Comment: Okay, I'm convinced. That is interesting about the square. I guess the conjecture is completely blown out of the water. I wonder though if there still might be an extra condition which might make it true. Maybe bounding the degree of the factors with respect to $n$? Just a thought.


Não sei onde estou errando na criação do store procedure

Question: Alguem me ajuda?
CREATE PROCEDURE 'sp_pessoas_insert' (  pessoa INT(11),
    name VARCHAR(20),
    lastname VARCHAR(55),
    age CHARACTER(2),
    genre boolean,
    countrie CHARACTER(2),
    state INT(11),
    city INT(11),
    income CHARACTER(8),
    email VARCHAR(100),
    password VARCHAR(100) ) BEGIN

    INSERT INTO person VALUES(pessoa, name, lastname, age, genre, countrie, state, city, income, email, password)

    SELECT * FROM person WHERE id =  LAST_INSERT_ID();
     END

Me retorna o erro:

Já vasculhei em tudo e não consigo resolver este problema ao criar a procedure, podem me ajudar e explicar se for possível oque está ocorrendo?!
Comment: Essas aspas simples no nome da procedure existem na sintaxe do SQL?
Comment: como o @AndersonCarlosWoss observou deve ser esse o problema, no `mysql` se usa a crase no lugar das aspas simples para nomes
Comment: Obrigado a todos voces que reservaram um tempo pra me ajudar. realmente o erro era as aspas simples, estou começando a  mexer com procedures e também sou novo aqui no stack, quero ate pedir ajuda de como avaliar a resposta de vocês.
Answer: O erro, como apontado nos comentários é que você está utilizando aspas simples ( ' ) no lugar do apóstrofe ( ` ) para o identificar o nome da procedure.
Outra coisa que não é um erro, mas é uma sintaxe de será descontinuada é o integer display width (aqueles números entre parêntesis de pois do INT). Você não precisa deles.
Segue uma versão modificada da procedure compilando no mysql 8.
DELIMITER $$

CREATE  PROCEDURE `sp_pessoas_insert` (
    pessoa INT,
    name VARCHAR(20),
    lastname VARCHAR(55),
    age CHARACTER(2),
    genre boolean,
    countrie CHARACTER(2),
    state INT,
    city INT,
    income CHARACTER(8),
    email VARCHAR(100),
    password VARCHAR(100) )
BEGIN
    INSERT INTO person VALUES(pessoa, name, lastname, age, genre, countrie, state, city, income, email, password);
    SELECT * FROM person WHERE id = LAST_INSERT_ID();
END$$

DELIMITER ;

Comment: Vlw de novo fabiano vou avaliar a resposta, e se não for pedir muito como posso marcar a questão como resolvida?
Comment: Claro! Valeu.
:)


Subspaces dimensions in $\mathbb{R}^7$

Question: if $U$ and $W$ are subspaces of $\mathbb{R}^7$  and $\dim U = \dim W =4$
then in $U \cap W$ there's a vector different then $0$.
I think that it's true, am I correct?
Answer: Yes.  If their intersection was $\{0\}$, then their sum $U+W$ would be a direct sum, so $\dim (U+W)$ would be equal to $8$, which is impossible, since it is a subspace of $\mathbb{R}^7$.
Answer: Yes, since $\dim (U+W)=\dim U +\dim W - \dim (U\cap W)$.
In your case: $\dim (U+W)=8 - \dim (U\cap W)$, and note that $\dim (U+W) \leq 7$.

Subspaces dimensions in $\mathbb{R}^7$


Automatic methods to forecast many monthly sales time series

Question: I'm barely a student in his internship, so I don't have a lot of experience, but I am facing an issue with a project I'm having at my work. I'm a bit in the dark because I find it hard to understand what is a satisfactory analysis given the situation, so please bear with me a few more lines. If the question is not relevant for this community, excuse my mistake and let me post it in on StackOverflow or take it down.
I need to provide "decent" forecasts of monthly sales in FMCG company. Expectations are not high, since it is known that some series have missing data or even multiple consecutive months without sales(that is a 0 value data point). Best series, so far, have around 28 months of sales.
I use an extremely unorthodox method, but one cannot just perform 5000 forecasts manually. The way I approach this is as follows:

I created 2 functions that choose best model fits for SARIMA and ets() wrapper to find best models per series for each family according to AIC(I use MAPE)
I chose the model fit that scores best from each of the model family (SARIMA/ETS) and perform out of sample forecasting
Then, I compare the out of sample accuracy measures(MAPE/RMSE) between the 2 and choose the best scoring one with its parameters or orders
Ultimately, I forecast the desired horizon with the specifications(sarima order or ets arguments) that i obtained above
When new data comes in(variously scattered during a month), my code automatically takes in consideration the newest data points and thus, updates the models.
)

My method does not take in consideration assumptions, normality of data, homogeneity of residuals. I know this is quite counter-intuitive, but I'm considering to create a score/rank or so to filter out unacceptable forecasts.
My data is imported from SQL Server to RStudio. Here, the code splits each data set into lists of train and test sets that will be used for choosing a model. I use only 3 points for out of sample in the first few months as some series have 24+3=27 data points and I wanted a better capture of seasonality(relevant?). After choosing the best model, I perform the forecast which will be ultimately pushed into SQL Server to be used for reporting/visualizations.
[![rough depiction of the flows][1]][1]
Questions, finally:

Since the "project" will yield forecasts for the next 12 periods and updates every month(model, accuracy, predicted values). Do you think 26-27 are plenty data points for the moment? Or do I simply have to accept a lower prediction accuracy or generalizability?
Is there be a method to filter out models that are extremely dangerous(hideously non-normal series distribution, a sort of ranking based on the various out of sample accuracy measures and AICc/BIC?
What could there be improved?
Comment: Have you taken a look at the `forecast` package and its function of the same name? I think it was designed with exactly this kind of use case in mind.
Answer: Your approach sounds reasonable. With fewer than 28 historical data points, your options are limited, anyway.
Which gives you the answer for your first question: no, 28 monthly data points is not a lot. You have observed less than three years of data. Once you hold out a couple of data points for method selection or similar, you will be left with only two years, which is very little to fit a SARIMA model. (And yes, seasonality may well be relevant. Or not. It depends completely on what kind of consumer products you are forecasting. Toilet paper is non-seasonal. Sunscreen is seasonal.) Then again, many CPG products will not even be available for more than three years until they are superseded (in which case you may be able to stitch time series together).
So, you seem to be doing good things for a start. You may be able to do something more fancy by leveraging, e.g., product hierarchies and product similarities. However, that would require some deeper understanding of your data than we can likely provide here. You may profit from the excellent free online book Forecasting: Principles and Practice (2nd ed.) by Athanasopoulos & Hyndman.
One simple "sanity check" would be to find series where your forecast is higher than the highest historical observation, or higher than the historical 90% quantile. This often signals trouble, except possibly for very new products that are ramping up. Ultimately, your sanity checks will depend on the kind of data you have.
One thing to keep in mind is that the MAPE may lead you towards biased forecasts, especially for slow moving products.
Comment: AIC should reduce the bias, compared to MAPE. Given promotions, you may want to run regressions on these external factors and possibly model residuals with time series methods. Good luck!
Comment: Thank you for the insightful answer. The products are described by quite varied seasonality, promotions, discounts etc. I'm aware that it is impossible to account for all of the effects. My strategy is to forecast on aggregated brands(multiple products per brand), then calculate previous year's product share and split each brand accordingly to sum (100%) of the forecast.
To combat the bias, I thought about putting in perspective other measures, like RMSE or so, and to create a formula. But even there, I do not want to add apples and pears in an equation. Would relying on AIC reduce bias?


My server went offline only for few regions?

Question: I am using Amazon AWS service for hosting my website, as of my website is hosted in EC2 free-tier with 1GB ram only.
It has been working fine for a while, but today suddenly my website was not accessible from the browser, FTP or ssh for nearly 5 minutes but only from my region. People from US, UK and around the globe were able to still access the site and when I tried changing my proxy to US it worked too but not from India.
Currently my server is in North California and I am using ubuntu.
During that 5 mins even my account in Amazon AWS console was not opening and was giving the same error.
When it went offline I got an error in the browser saying that my website is taking too long to respond.
This is the first time it has happened.
Answer: There is nothing you could have done to fix this. Internet routing problems happen, and when they do, they frequently only affect part of the Internet.
There are high availability architectures you can build to deal with this, but those also come with more complexity and cost.
Perhaps the easiest way to hedge against this is to put Cloudflare in front of your site.
Comment: I am not aware of it. SO can you elaborate more on it, so that i can understand it better.
Comment: @SusanWilliams Cloudflare is a content delivery network. https://www.cloudflare.com/ should give you what you need.
Comment: @MarkHenderson thanks, but i asked about the **high availability architectures** that can deal with it, as of now i am using MaxCDN also..
Comment: @SusanWilliams apologies. Your comment did not specify what you were asking him to elaborate on.
Comment: @yea i got. Sorry for that..but can you explain the **high availability architectures**
Comment: Read up on architecture at the AWS Architecture Center, or get some architecture training / consulting. https://aws.amazon.com/architecture/


C# Generating a random IP Address

Question: I have been working on some mocking for IOT devices and I need to generate a random IP address in C#. What is the most simple way to create a random IP address is C#?
Answer: If you want to use an IPAddress object:
var data = new byte[4];
new Random().NextBytes(data);
IPAddress ip = new IPAddress(data);

Note: If you are doing this several times, you should create just one Random object and reuse it.
If you want to ensure that the first element is not zero, you should OR it with 1 before passing it to the IPAddress constructor:
data[0] |= 1;
...

If you want an IPV6 address, replace the first line with:
var data = new byte[16];

and you'll get an IPV6 address.
Comment: this could also produce `0.x.x.x` which is invalid
Comment: @fubo It's not invalid as far as the `IPAddress` class is concerned; it will happily create such an address, but I guess you should account for it if it is significant for the unit test.
Comment: @fubo Aye, easiest way is to OR it with 1 (thereby still keeping the randomised top 7 bits).
Answer: Based on using visual studio 2017 and string interpolation
    public string GetRandomIpAddress()
    {
        var random = new Random();
        return $"{random.Next(1, 255)}.{random.Next(0, 255)}.{random.Next(0, 255)}.{random.Next(0, 255)}";
    }

Comment: better to say c# 6.0 or greater (or .net framework 4.6). You can use string interpolation with visual studio 2015, not neccessary 2017

C# Generating a random IP Address


Is the set of pseudo-complements of the elements of an ideal in a pseudocomplemented lattice a filter?

Question: Let $L$ be a pseudocomplemented distributive lattice with $0$ and $1$, $I \subseteq L$ an ideal and set $F = \{\neg x \; | \; x \in I\}$, where $\neg x$ is the pseudocomplement of $x$. My question is: is $F$ a filter? It's clear that, for any two elements $x, y \in F$, their meet $x \wedge y$ is in $F$, but it's not entirely clear to me that, if $x \in F$ and $x \leq y$, then $y \in F$. In particular, this would seem to imply that every element that is greater than a pseudocomplement is the pseudocomplement of another element, yet I'm not entirely sure if this holds (in fact, my attempted at proving that $F$ is a filter stumbled precisely at this point).
I've been trying to think of counterexamples, but I'm unsure if I'm on the right track. I thought of using the structure $\langle \mathcal{P}(\mathbb{R}), \cap, \cup, \emptyset, \mathbb{R}, \neg \rangle$ as a counterexample, where $\neg X = \operatorname{int}(\mathbb{R} \setminus X)$. If this is a pseudocomplemented lattice, then, if we consider the order generated by inclusion, then taking the ideal generated by, say, the interval $(0, 2)$, and then taking the pseudocomplements of its elements won't generate a filter, as there will be many closed intervals which will be left outside of this set. Is this on the right track?
Answer: I would just take the lattice $\tau$ of open sets in $\Bbb R$ with the usual topology. Then for any $U\in\tau$ you do indeed have a pseudo-complement $\neg U=\operatorname{int}(\Bbb R\setminus U)=\Bbb R\setminus\operatorname{cl}U$. Note that all pseudo-compements are regular open sets.
If $U$ is a regular open set other than $\Bbb R$ itself, $\neg U$ is a non-empty regular open set. Let $(a,b)$ be any open interval contained in $\neg U$, fix $c\in(a,b)$, and let $V=U\cup(a,c)\cup(c,b)$. Then $U\subseteq V$, but $V$ is not regular open, since $c\in(\operatorname{int}\operatorname{cl}V)\setminus V$, so $V$ is not a pseudo-complement in $\tau$. Thus, every filter containing $U$ must contain a set that isn't a pseudo-complement.
Comment: Thanks! I know that, if $L$ is a Boolean algebra, then (almost trivially) the set of complements of the elements of an ideal *is* a filter. Do you know what further condition a lattice must satisfy between being a pseudocomplemented lattice and being a Boolean algebra in order for this to work? Or is this true just for Boolean algebras?
Comment: @Nagase: You're welcome! I don't know, I'm afraid, at least not off the top of my head; I'm a topologist, and what I know of lattice theory I've picked up in bits and pieces along the way.
Comment: @BrianMScott - I was re-reading your answer and I have a doubt. Your conclusion states that every filter containing $U$ will contain a set that isn't a pseudo-complement; however, what is needed for a counter-example is the proposition that every filter containing $\neg U$ contains a set that isn't a pseudo-complement, right?
Comment: @Nagase: The point is if $U$ is any open set at all (other then $\Bbb R$), any filter containing it will contain a set that isn't a pseudo-complement. In particular, you can take $U$ to be $\neg V$ for some non-empty $V\in\tau$.
Comment: @BrianMScott - Ahh, got it. That makes sense. Thanks a lot again!
Comment: @Nagase: My pleasure!


How can I create a custom view other than content types?

Question: How can I create a view that's based on a custom table from a custom module.
Actually in creating views path I can see options of view types as:

View type:
Node: Nodes are a Drupal site's primary content.
Comment: Comments are responses to node content.
File: Files maintained by Drupal and various modules.
Node revision: Node revisions are a history of changes to nodes.
Term: Taxonomy terms are attached to nodes.
User: Users who have created accounts on your site.

But when selecting the node option I can only select from node table and selecting user I can select from the user table for displaying the data from these tables. But if I need to display data from the custom tables how can I select that table on creating the query and display them on the view pages?
Answer: You need to implement hook_views_data to tell Views about your tables and how the data in your tables relates to other tables defined to Views (if it does).  Here's a good tutorial to get you started:
http://www.grasmash.com/article/demystifying-views-api-developers-guide-integrating-views
Depending on the nature of your data, you may, alternatively, consider defining your custom data as a custom entity type.  If you do that through the Entity API module, then it will provide Views integration "for free".
Comment: How it differ from the hook_theme system ?
Comment: It's similar only in that they're both hooks.  `hook_theme` is a completely separate hook which does totally separate things.
Comment: There is **MODULENAME.views.inc** and i can send the data processed through **hook_views_data()** function , but how clearly it handles the html view  files ? or how can i show data in html files
Comment: Is there any view.tpl.php file specific to a module function ?
Comment: Views tpl suggestions are determined based on a number of factors including the name of the view, name of the display, display plugin used, and a variety of other things.  If you want to provide a general way to customize the look of a view you need to write a display plugin. If you want to override the look of a specific view then your theme can implement an appropriately-named tpl.  I'm confused, though, because none of this has anything to do with exposing your custom tables to Views.
Comment: I need more explanation on the display plugin , i know the second part though. and by default how the views from content types having  a theme suggestions ?
Comment: There's just too much to explain here. Sorry.


Como eu coloco essa div vertical no canto superior esquerdo da tela?

Question:

  <title>Impressão de Carnê</title>

  <form method="POST">

              Loja:

              Cliente:

              Contrato/OS:
Vencimento:

              Parcela:
Valor:

              Recebido Por:_____________________________

Data:________________ Hora:______________

  </form>

Answer: Use transform-origin para controlar o ponto de rotação da tabela em um dos vértices como eu fiz abaixo, no caso eu usei transform-origin: top left;.
O transform-origen default é center, por isso vc precisou usar o margin-top, mas agora é desnecessário e deixei ele comentado

.vertical {
  transform: rotate(270deg) translateX(-100%);
  transform-origin: top left;
  /* margin-top: 165px; */
  display: inline-block;
  border: 1px solid black;
}
<form method="POST">

            Loja:

            Cliente:

            Contrato/OS:
Vencimento:

            Parcela:
Valor:

            Recebido Por:_____________________________

Data:________________ Hora:______________

</form>
Comment: Entendi, muito obrigado pela explicação.


Should I use Google Maps API for creating Gaming maps?

Question: Hi I just want to ask about those custom Google maps that you can put on your web page, I was thinking of using them for a couple a "maps" in a game to show where certain items are on one "layer", location of destructable objects in another layer, spawn points and all that. I was wondering if the Google API can cover all these or should I make one myself?
Answer: The layers would be conceptual (ie, the GMaps API doesn't know about layers) but yes. You can store the markers you add in your own layers array. Each member of that array would be an array of markers corresponding to each type. You can create your own custom markers, spawn them at any point in the map and so on.
The API may be too slow for a game where markers move real time, for a turn based one it's certainly possible.
What you can't do is to copy the image and redistribute it, so your game would have to run on top of Google Maps.
Comment: ahh, thanks I should of worded it correctly. It's actually a resource map to help people playing a game. So I can add tables within hotspots and display data a-okay without too much problems?
Comment: Yes. I reiterate that you cannot take a screenshot of the output and place it as a static image though, due to licensing terms.
Answer: You can use Custom Overlays or Ground Overlays (for map-like objects and "layers"), and markers (for item-like objects).
Comment: Would this whole process take longer than making it in Dreamweaver. It's just a click/show web map.
Comment: @PUFFY: I don't have any experience with Dreamweaver, so I can't compare =| Shouldn't take long though - load an image as the ground overlay, set sprites, done.
Comment: Those aren't actually layers in the GIS sense of the word (where you can have a polygon layer (with many polygons) or a line layer (with many lines) or a point layer (with many points) as a single unit). Don't know if the OP tried to mean layer in a GIS-sense though.
Comment: Yeah, I was about to start this for our weekend guild quests, I just happened to stumble across Google Maps API on a search and found it, hoping that it would be faster rather than making it in Dreamweaver. I have absolutely NO experience with this, just the fact that Google makes user friendly things bought me. If I were to explain the "layers" it would be like Photoshop. The base layer would just be the raw map of the game level. on top would show different things like an item layer would be circles placed on where to items are etc etc.


Turning my Windows Server 2016 into a remote file server

Question: my company purchased a Windows Server 2016 instance with AWS in order to replace our current Windows Server 2008 (which resides in a closet in our office).
However it has proven more difficult than expected to replace all the functionality. Our 2008 server essentially has a file drive that all users on the network can map a drive to as a network location. It serves files stored by other users and by applications with user permissions, ect.
The problem I am encountering when trying to do this with an instance on the cloud is that the server is no longer connected to the same network, so it must be opened up over the internet. This opens up a whole can of worms with security and networking. I have been researching and trying for months to get connected over the internet to this instance and have been unsuccessful at mapping a single drive.
I am really looking for a good guide of what to do. Aside from the last 4-5 months of research and my limited experience managing our local Windows Server 2008, I am relatively inexperienced when it comes to networking. Step by Steps are better than high level constructs. (I am familiar with tools like server manager, windows server essentials, ect but not with specific services like AD, Direct Access, VPN, ect.)
Details:

Company has approximately 15 users
We have branches in different locations we would like to give access to the files.
Looking to host our files, and install applications that manipulate these files (so dropbox is not a good alternative)
Server instance is on AWS.
Users must be able to "map network location" to this server as they currently do so that everything stays the same for the users.
I am pretty familiar with Amazon Web Services.

Thank you!
Comment: This is not what AWS EC2 is designed for. EC2 is not a 1:1 replacement for on-premises servers, and it requires a different architecture for doing things - as you have discovered. You probably _can_ do what you're requesting with a VPC VPN, but that requires even more networking configuration.
Comment: I know you've said that your preference is to use/stay with AWS, but SharePoint Online via an Office 365 subscription may be the closest you're going to get to the functionality you need without resorting to some "hack" solution that proves untenable over the long term.
Answer: You have at least two options:

The probably-less-good option: Create a VPN between the firewall protecting your office and your AWS account, so that you can connect to the AWS VM in question via that VPN tunnel. Then it will be like connecting to a file server at a remote site.
The almost certainly better option: Research and implement Amazon S3 (Simple Storage Service), possibly with an on-site S3 gateway. This will give you the cloud resilience and availability with easier maintenance than a VM instance and low latency local caching via the on-site storage gateway. Also, users can merely connect to the share on the gateway instead of initiating a connection all the way to the cloud service. This may mean you don't need the VM instance any more. Spin it down and stop paying for it.

One thing to be aware of when migrating services to public cloud offerings is that it's usually not best to go one-for-one VM to VM. Just because you are using server on-prem for a service doesn't mean you want to replicate that server in the cloud. Using Office 365/Exchange Online to replace on-prem Exchange servers is probably the most famous and common example of this.
Comment: Interesting. I have taken a look at Amazon S3 before but it seemed to be an "object" storage service and not a "file" storage service. Is there a fundamental difference?
Comment: @JonathanMongeau Yes, there is a difference but you would use the storage gateway as a kind of storage proxy. Clients could connect to the storage gateway using SMB just like any Windows file share and then the storage gateway uses Amazon's S3 protocol to leverage the S3 object storage to keep a cloud copy of the file data. Note that Microsoft Azure has a similar service called StorSimple. The real takeaway is that you might want to engage a consultant who is an expert to do a migration to public cloud. It's fairly complicated.


How to extend lan to offsite location

Question: I would like to extend my LAN to another site.
I have people who work on both sites and I want it to be as if they are in the same LAN, regardless of where they are.
I have servers on both sites and they should not be aware that they are separated by the internet.
So What I want is to have a "virtual network cable" that connects my 2 sites.
Any suggestions?
Please keep in mind that it has to be as if I have a real network cable connecting the switch of site 1 with the switch of site 2!
Thanks in advance!
Johan
Answer: Literally a "virtual network cable" would be a VPN in TAP mode, simulating link layer (L2), both end having the same subnet. However, things will work as required even if you have different subnets on every site i.e. use VPN in TUNneled mode, simulating network layer (L3). Actually the TUN mode has advantages: for example Windows domain is site-aware and can refer to the nearest domain controller, causing less network traffic between the sites.
If you don't want to setup everything from scratch, which is not a good idea if you don't have much knowledge on VPN technology, you may want to have routers/firewalls that have easy out-of-box wizard based site-to-site VPN setup.
Comment: Thank you for your answer. We went with 2 different ip subnets, changed the IP's of the servers and it all works great. I expected problems after changing the IP addresses but there weren't any.
Comment: We have Sophos UTM9 on both sides, but all I can find is examples with 2 different ip subnets. I would like to have just one, so all servers and clients are in the same address range etc. Is that possible with our setup?
Comment: With Sophos UTM9 it's by design that you should have different subnets. However, that shouldn't be a problem in your use case. It's completely normal to have routing between the sites and they are still in the same private network.
Answer: As you don't specify the operating system or others needs I would confirm that you need a VPN. You could check out the OpenVPN software.

OpenVPN is a full-featured SSL VPN which implements OSI layer 2 or 3 secure network extension using the industry standard SSL/TLS protocol, supports flexible client authentication methods based on certificates, smart cards, and/or username/password credentials, and allows user or group-specific access control policies using firewall rules applied to the VPN virtual interface. OpenVPN is not a web application proxy and does not operate through a web browser.

How to extend lan to offsite location


Explain relation between EWQL,Vienna Symphonic Library and FL Studio

Question: I'm a noob at music software conventions , So can someone tell me what are East west QL , FL Studio and vienna symphonic library. And how are they different and related? I saw somebody using FL studio by linking it to EWQL .
IS FL Studio just a platform for editing external data like Audacity is? or does it has its own library of samples? same question about EWQL and vienna , do they come with editor or just libraries? what are they?
Comment: Didn't you think to do a Google search on these terms?
Answer: FL Studio is both a platform for editing external data like Audacity (or more like Ableton Live) and it has its own virtual instruments and sample libraries. (also like Ableton Live and many other packages like Apple Logic, etc.) (Source)
East West Quantum Leap is a virtual instrument and sample library suite of products (with some player/articulation capabilities), mainly marketed as symphonic sounds for soundtrack scoring. (Source)
Vienna Symphonic Library is a product in direct competition with EWQL and it is pretty much the same thing, except VSL is more focused on the symphony orchestra and its sounds exclusively. It is also marketed for soundtrack scoring with a little more emphasis on music composition and music production than EWQL. (Source)
Often, a product like FL Studio (or Audacity) is called a DAW (Digital Audio Workstation). Most products like EWQL and VSL require a "host application" like a DAW to be played, although some (maybe most, these days) come with a standalone player that one can use to play the sounds even without a DAW. Still, the intention is that one would use some kind of DAW to control playback of virtual instruments and sample libraries.
There are many competing DAWs on the market. FL Studio is popular with dance, house, dubstep, and related genres, but it can do almost anything. Another product popular with those same types of musicians is Ableton Live. For straight up audio recording, Reaper, ProTools, Logic, Sonar, and Cubase are popular. All of the ones I have just mentioned can act as host applications for EWQL and VSL, and all of them except Reaper come with their own virtual instruments and sample libraries (of varying qualities and types).
Unlike the DAWs I have listed, Audacity can only process audio, and it does not act as a host application for virtual instruments or sample libraries. (Source)


Calculate rate from log file timestamps

Question: From postfix's logfile I can grep all the lines that indicate the delivery of one message:
Jan  3 15:28:21 mail postfix/pipe[1040]: [...] status=sent
Jan  3 15:28:21 mail postfix/pipe[1157]: [...] status=sent
Jan  3 15:28:22 mail postfix/pipe[980]: [...] status=sent

I'd like to group them together by timestamp, so I can calculate the messages per second for a given time range. How can I do that?
Answer: This should do it:
$ cut -d " " -f 4 postfix.log  | sort -n | uniq -c

If you want to select a given time range, just throw another grep before this with your desired regex.

Calculate rate from log file timestamps


Sequence of Radon Measures $\mu_n$ on $\mathbb{R}$

Question: Problem: Find a sequence of signed Radon Measures $\mu_n$ on $\mathbb R$ such that $\langle \mu_n, \phi \rangle \to 0$ for every $\phi \in C^1_c(\mathbb R)$, and $|\mu_n|([0,1]) \to +\infty$.
Attempt: I tried to define $\mu_n([a,b]):= \int_a^b f_n(x) dx$ with $f_n:=\chi_{[0,\frac{1}{n}]}$ or similar. I can realize the first property or the second but not them together!
Thanks!
Comment: I believe you can use a quickly oscillating sine wave whose amplitude grows (not too quickly) as $n$ grows.
Comment: @CalvinKhor I feel like I'm missing the definition of $(\mu, \phi)$. Is it $\int_{\mathbb R} \phi(x) d\mu$?
Comment: Thats right. My idea was to use Riemann-Lebesgue, but grow the amplitude a little to accomplish $|\mu_n| [0,1] → ∞$.
Answer: Take $f_n=n^{3/2}\chi_{[0,1/n]}-n^{3/2n}\chi_{[1/n,2/n]}$ and $\mu_n(A)=\int_A f_n(x)dx$. Then clearly $|\mu_n|[0,1]=2n^{1/2}\to\infty$. We need to show that $\int \phi d\mu_n\to 0$ for all $\phi\in C_c^1(\mathbb{R})$.
Now fix $\phi\in C_c^1(\mathbb{R})$. Again, since $\phi'$ is continuous and compactly supported, it is bounded. This and the Mean Value Theorem imply that there exists a constant $C>0$ (depending only on $\phi$) such that for all $x,y\in\mathbb{R}$, $|\phi(x)-\phi(y)|\leq C|x-y|$.
Now we calculate
$$\int\phi d\mu_n=n^{3/2}\left(\int_0^{1/n}\phi(t)dt-\int_{1/n}^{2/n}\phi(t)dt\right)$$
Let's look at the first term:
$$\int_0^{1/n}\phi(t)dt=\int_0^{1/n}\phi(t)-\phi(1/n)dt+\frac{\phi(1/n)}{n}$$
and to deal with the first term in the RHS,
$$\int_0^{1/n}\phi(t)-\phi(1/n)dt\leq\int_0^{1/n}|t-1/n|Cdt\leq\int_0^{1/n}C\frac{2}{n}=\frac{2C}{n^2}$$
In simpler terms,
$$\int_0^{1/n}\phi(t)dt=\frac{\phi(1/n)}{n}\pm\frac{2C}{n^2}$$
The same arguments show that
$$\int_{1/n}^{2/n}\phi(t)dt=\frac{\phi(1/n)}{n}\pm\frac{2C}{n^2}$$
Therefore,
\begin{align*}
\left|\int\phi d\mu_n\right|&=n^{3/2}\left|\int_0^{1/n}\phi(t)dt-\int_{1/n}^{2/n}\phi(t)dt\right|\leq n^{3/2}\frac{4C}{n^2}=\frac{4C}{n^{1/2}}
\end{align*}
which goes to $0$.
Comment: @Maffred Yes! Thanks for pointing that out.
Comment: That seems great! Is the first $|\mu_n|=2n^{1/2}$??
Answer: Let $f_n(t) = \sqrt {n}\cos (nt)\cdot \chi_{[0,1]}(t).$ Define $\mu_n (E) = \int_E f_n(t)\,dt.$ Then
$$|\mu_n|([0,1]) = \sqrt n \int_0^1 |\cos (nt)|\, dt \to \infty.$$
Let $\phi \in C_c^1(\mathbb R).$ Then
$$\int_{\mathbb R} \phi \,d\mu_n = \int_0^1 \phi(t) \sqrt n \cos (nt)\, dt.$$
On the right we can integrate by parts to get
$$\phi (1)\frac{\sin (n)}{\sqrt n} - \int_0^1 \frac{\sin (nt)}{\sqrt n}\, \phi'(t)\, dt.$$
This is $0(1/\sqrt n)$ as $n\to \infty,$ so we're done.


I need help interpreting Definition 1.10 in Rudin's PMA.

Question: While I have a basic understanding of what this definition states, I've been running into trouble interpreting the results when I test it with certain sets other than the traditional examples used to show that the Rationals do not have this property.
$\textbf{Definition 1.10:}$
"An ordered set  is said to have the least-upper-bound property if the following is true:
$$\text{If }\subset\text{, }E \text{ is not empty, and }  \text{ is bounded above, then } \sup() \text{ exists in } ."$$
$\\$
I am interpreting this as a series of nested conditional statements:
$$\Big[ \big( \left( E\subset S \right) \land \left( E \neq \varnothing \right) \land \left( E \text{  bounded above}\right) \big) \implies (\ \sup(E) \text{ exists in }S)\ \Big] \implies S \text{ has LUB property}$$
From here, we usually let $S=\mathbb{Q}$ and $E=\{q\in\mathbb{Q}:q^2<2 \}$ to show that $\mathbb{Q}$ does not have the LUB property. This makes sense to me because while the antecedent within brackets is true, the consequent is false. Thus the bracketed conditional is false, forcing the entire definition to be true.
But what about if (for example) $S=\mathbb{Q}$ and $E=\{q\in\mathbb{Q}:q^2<-1\}$ ?
In this case, $E=\varnothing$, thus the antecedent within the brackets is false. This renders the entire conditional in brackets true. Then the whole definition can only be true if $\mathbb{Q}$ has the LUB property - which is clearly wrong.
Can someone help me track down my misunderstanding?
Comment: $S$ has the LUB property if **all** non-empty bounded-above subsets have a supremum.
Comment: You should have an extra universal quantifier for $E$. $[\text{for all $E$, } [\text{your big square brackets' stuff}]]\implies \text{$S$ has LUB property}$. I know Rudin doesn't state explicitly the quantifier over $E$, but it is something the reader is expected to 'know' is there by context.
Comment: It was really that simple!  Thank you both for pointing it out!
Answer: There is something wrong with your series of conditionals: $E$ is a free variable. That means that the statement depends on both $S$ and $E$.
But "$S$ has the least upper bound property" doesn't depend on $E$, so we need to make $E$ a bound variable by using a universal quantifier:
$$\Big[ \forall E : \left\{ \big( \left( E\subset S \right) \land \left( E \neq \varnothing \right) \land \left( E \text{  bounded above}\right) \big) \implies (\ \sup(E) \text{ exists in }S)\ \right\} \Big] \leftrightarrow S \text{ has LUB property}$$
Comment: It was really that simple!  Thank you for pointing it out!
Comment: @SuzuHirose Thanks for the guidelines (I'm new here). In fact, the first of the answers that solved my problem were given as replies to the initial question. I can't give them green checks, so I've just green checked this one.
Answer: You found a set which has a least upper bound in $\mathbb Q$. But to satisfy the LUB property, there must be a least upper bound for EVERY set $E$, not just one that you choose.
Comment: It was really that simple!  Thank you for pointing it out!

I need help interpreting Definition 1.10 in Rudin’s PMA.


F1 teams to win their first grand prix

Question: I saw a social media post which claimed

Brawn GP is one of just four teams to have won their very first race.

I presume one of the other three teams is Alfa Romeo, who won the first ever official F1 grand prix. I have also found out that Mercedes won their first F1 race, in 1954, at the hands of Fangio.
Who is the final team?
Comment: Brawn was in fact the old Honda team - https://en.wikipedia.org/wiki/Brawn_GP
Comment: @davidjwest indeed - Brawn was formerly Honda, which was formerly BAR, which was formerly Tyrrell. So the "new" Brawn team actually had a continuous F1 heritage of nearly 40 years.
Answer: That would be Wolf, at the 1977 Argentine Grand Prix. I admit I had to Google to confirm my guess.
Source

F1 teams to win their first grand prix


Which of the following statistics courses are the most applicable and useful in finance/tech industry?

Question: I'm in the process of selecting 3 statistics classes to take for my Applied Math course cluster (doing my concentration in actuarial science or statistical analysis). Which 3 classes out of the following do you think are most useful/applicable in finance/tech/paired with Computer Science?

Stochastic Processes (Random walks, discrete time Markov chains, Poisson processes)
Linear Modeling: Theory and Applications
Introduction to Time Series
Modern Statistical Prediction and Machine Learning
Game Theory
Introduction to Econometric Analysis (Cross-enrollment between Stats & Econ)
Comment: But it is also expert advice that is useful to the OP.
Comment: Congratulations on landing a HNQ (Hot Network Question) on your first question, but this is obviously _"primarily opinion-based"_, so I'm voting to close.
Comment: @MichaelChernick _"Many good questions generate some degree of opinion based on expert experience_, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise."
Comment: OP here, I didn't realize I could use other Stack Exchange accounts for this one. Also I'm sorry if this question was off-topic, I didn't realize it was, and that it'd pick up this much traction. Thanks for the responses everyone!
Answer:
Linear Modeling (the basics)
Introduction to Time Series (important for finance and tech, where there are lots and lots of measurement occasions)
Modern Statistical Prediction and Machine Learning (for the fancy new prediction stuff, also important for finance and tech)
Comment: Your choices are good too.  It is difficult to pick just three when the concentration is in actuarial science or statistical analysis in general. We agreed on the first two and differ on the third.  I just assumed that if actuarial science is a concentration in applied math then a serious course in survival analysis would be important.
Answer: I would recommend Linear Modeling and Introduction to Time Series.  If you only have three electives and you decide to concentrate in actuarial science, I would take a course in survival analysis if one is available.
Answer: Working as a Data Scientist at one of the biggest consultancies of the world I can just give my two cents which one is useful for a job like mine. All courses are cool and have applications both in research, development as well as consulting. However some courses might be more important for practical application. Disclaimer: This does not reflect the opinion of my employer and I have also only seen several departments in Germany.
THE MOST USEFUL COURSES:

Introduction to Time Series

If you are working as a Data Scientist you will definitely make forecast occasionally. It is important that you understand patterns such as trends, unit roots, seasonalities, etc.
In practice you will be facing data with different frequencies such as monthly or quartely data.
Read Forecasting principle and practice in order to get an understanding of the applications of forecasting.

Modern Statistical Prediction and Machine Learning

This course will raise your chances of getting a highly paid job. Machine Learning is correlated with higher salaries than classical statistics. It is definitely worth knowing things such as training and test data. You will always built a model and test it.
It is also due to the importance of Machine Learning that this page is called CrossValidated. hahahaha
ALSO USEFUL:

Linear Modeling: Theory and Applications
Introduction to Econometric Analysis (Cross-enrollment between Stats & Econ)

These courses seem pretty similar to me. I presume both are mainly dealing with Longitudinal Data and Pannel Data. However Most regression problems you will face as a Data Scientist deal with Time Series. I just had one project with Heckman selection modell/ Tobit regression and some small stuff where I faced Count Data and Survival Analysis. Overall classification tasks are more widespread at my company than regression tasks.
You are most likely to work in a team with Mathematicians, Statisticians and Computer Scientists. They will not stick to econometric modells. Nonetheless a solid understanding of linear models and econometric analysis will help you to deal with time series and forecasting issues.
It also depends on the programming language you prefer. R (and even more particularly Stata) are very handy for regression models. Python is rather useful for other tasks.
As Michael Chernick already stated Microeconometric issues are widely used at insurances. If you work for in a life insurance department survival analysis will be crucial. However most data scientist do not face such tasks.
You can go through this applied econometric foundation course by UCLA and reflect in how far you will face such questions in your future job.
RATHER IRRELEVANT:

Stochastic Processes (Random walks, discrete time Markov chains, Poisson processes)

This will be hardly useful as a Data Scientist. Maybe you can face such models if you are working in a Quantitative Finance department of a bank.

Game Theory

Game theory is a theoretical concept which is barely directly applied in practice. In economic and psychological research it might be helpful, however it is not in the classical scope of a data scientist.
Please don't hesitate to ask if I should be more specific about some courses.
Answer: As someone who works for a bank in a quantitative role, I disagree with the other answers. Stochastic processes are very important.  A good knowledge of stochastic processes allows you to understand the intuition behind many of the other classes you mention, especially time series models.  It is also a differentiater (in my experience a good knowledge of stochastic processes is rare).
I would take

Stochastic Processes
Modern Statistical Prediction and Machine Learning
Linear Modeling: Theory and Applications


how to setup secure access to a host on internet?

Question: we are planning to setup a source code repo + bug tracker for multiple users across the globe. Hence the network is internet - that is the host has public IP address provided by the ISP.
since this host is not a registered domain or IP on the internet, how can the problem of access from internet to this host be solved?
what software , hardware is required
Comment: If the ISP can provide you with an IP, why not get a domain name to use for this, the cost is minimal.
Comment: I always feel that if you need to ask the question you really shouldn't be doing this yourself. Get someone who knows what they're doing and fully understands the risks and consequences to do it for you.
Comment: Indeed, and while your at it, get an SSL for the secure part.
Answer: You could get a virtual server with Amazon EC2 instance or a VPS provider. With Amazon you get free static IP and then you either access it by IP address or register a domain name. For security, if it is linux then IPtables is the key word. Alternatively and if you go with amazon, you are also getting free virtual firewall that is more then adequate. And for connectivity make sure you use encrypted connections (ssl, ssh) and you will be fine. If you concerned about DOS attacks the talk to professional - there is no easy solution for this. Hope this helps.
Comment: can I setup this virtual server on my own? please eloborate
Comment: Just create account with amazon, then login to the console and create your server. They only charge you if server is running and you can start from as low as few cents per hour and then grow as you need. You will have a few choices for operating systems - Windows, CentOS, Ubuntu and probably SUSE.
Comment: BTW, Amazon is just one example. Another option that comes to mind is [rackspace cloud](http://www.rackspace.com/cloud/) or you can even go with VPS from almost every web-hosting provider (GoDaddy for example).
Answer: When you plan this setup i think its better you take a server from an internet hoster. Then you get an ip and domain and webspace.
When you want to put the server in your local intranet then you need to forward the port to your server. But then you have opened your system for people from outside and you need an external ip-adress. If you don't get one you can use something like "dyndns" but i think its not the best way.


On a basis of three dimensional vector space over the field of rational numbers

Question: Let $V$ be a vector space over $\mathbb Q$ of dimension $3$. Let $u,v,w\in V$ be vectors such that $u\ne 0$ and there exists a linear map $T: V\to V$ such that $T(u)=v, T(v)=w$ and $T(w)=u+v$.
Then how to show that $\{u,v,w\} $ is a basis of $V$ ?
My try: It is enough to show that $\{u,v,w\} $ is linearly independent. So let $au+bv+cw=0$ for some $a,b,c\in \mathbb Q$. Then applying $T$ we get $cu+ (a+c)v+ bw=0$ and applying $T$ one more time, one gets $bu+(b+c)v+(a+c)w=0$. Writing out these equations in matrix form the corresponding determinant of the coefficient $a,b,c$ matrix is very cumbersome
https://www.wolframalpha.com/input/?i=determinant+of+%7B%7Ba%2Cb%2Cc%7D%2C%7Bc%2C+a%2Bc%2C+b%7D%2C%7Bb%2C+b%2Bc%2C+a%2Bc%7D%7D
So I'm not sure what to do next. I think I have to apply that the base field is $\mathbb Q$ somehow, but I don't exactly know how.
Please help.
Answer: You are correct about your guess that you need to use that $\mathbb Q$ is the underlying field. My solution pretty much relies on the Rational Root Theorem (RRT).

Claim 1. $\{u, v\}$ is a linearly independent subset of $V$.
Proof. Suppose not. As $u \neq 0$, we can conclude that $v = \lambda u$ for some $\lambda \in \mathbb{Q}$. (How?)
Now, as $T$ is linear, we know that $T(v) = T(\lambda u) = \lambda T(u) = \lambda v = \lambda^2 u.$
On the other hand, we know that $T(v) = w$.
Thus, we get that $w = \lambda^2 u$.
Now substitute this in $T(w) = v + u.$
$\implies T(\lambda^2 u) = \lambda u + u$
$\implies \lambda^3 u = \lambda u + u$
$\implies (\lambda^3 - \lambda - 1) u = 0$
$\implies \lambda^3 - \lambda - 1 = 0 \qquad (\because u \neq 0)$
This is a contradiction as $\lambda = \pm 1$ is not a root and by RRT, there are no other (rational) roots.

Claim 2. $\{u, v, w\}$ is a linearly independent subset of $V$.
Proof. Suppose not. As we have already shown that $\{u, v\}$ is linearly independent, our assumption gives us that $w = a_1u + a_2v$ for some $a_1, a_2 \in \mathbb{Q}$. (How?)
We are given that $T(w) = u + v$. Using linearity, we perform the following calculations:
$T(a_1u + a_2v) = u + v$
$\implies a_1T(u) + a_2T(v) = u + v$
$\implies a_1v + a_2(a_1u + a_2v) = u + v$
$\implies (a_1 + a_2^2 - 1)v + (a_1a_2 - 1)u = 0$
By Claim 1, it follows that $a_1 + a_2^2 = 1$ and $a_1a_2 = 1$. Using the second equation, we plug $a_1 = a_2^{-1}$ in the first equation to get:
$$1 - a_2 + a_2^3 = 0.$$
(Note: It follows from $a_1a_2 = 1$ that $a_2 \neq 0$ and thus, the substitutions are legal.)
However, once again, by RRT, it follows that the above equation has no (rational) root and hence, $\{u, v, w\}$ is a linearly independent subset of $V$ which tells us that it is a basis.

Remark. To show that it is indeed necessary to use the properties of $\mathbb{Q}$, consider any field $\mathbb{F}$ such that $\lambda^3-\lambda-1=0$ does have a root in $\mathbb{F}$. (For example, $\mathbb{F} = \mathbb{R}$.)
Consider $V = \mathbb{F}^3.$
Let $u = [1\;0\;0]^T,\; v = \lambda_0u,\; w = \lambda_0^2u$, where $\lambda_0$ is any root of $\lambda^3-\lambda-1=0$.
Define $T:V \to V$ as $T(x) = \lambda_0x$.
Verify that these objects do indeed satisfy all your conditions.

Both the "(How?)"s have a similar argument. Use the fact that if $S$ is a linearly independent subset of $V$ and $v \in V$, then $S \cup \{v\}$ is linearly dependent iff $v \in \operatorname{span} S$.


Measure theory, notation question, a.e.

Question: I have in my notes
$$\|f\|_\infty := \inf\{c\in \mathbb{R} : |f(\omega)|\leq c \quad a.e. \}$$
Can I take that to mean
$$\|f\|_\infty := \inf\{c\in \mathbb{R} : |f(\omega)|\leq c \quad \forall \omega \in A \; st\; \mu(A^c)=0 \}$$
Comment: How do you find your set $A$?
Comment: @AritroPathak The definition of a.e. that I have doesn't really describe an easy way to construct $A$.
Comment: That is incorrect. Take $f (x) = -x$ on $[0,1]$ then $\|f\|_\infty = 1$ but the above has $\sup\{c\in \mathbb{R} : f(\omega)>c \quad a.e. \} = -1$.
Comment: @copper.hat I fixed it. But I'm still puzzled about the definition of almost everywhere. That is what I want to know. Also I'm not even sure, is $\|f\|_\infty$ as defined here, a function or a constant?
Comment: I'm pretty sure $\|f\|_\infty$ is an upper bound and not a function cause otherwise the a.e. condition would not make sense, right?
Comment: @ColdHeartOfStone: Are you asking about how measure zero is defined or how it is used in the context of the essential supremum?
Comment: @copper.hat I am trying to understand how exactly to interpret a.e. but I think I now have the answer. Is it correct to say $\|f\|_\infty = \inf\left\{c \in\mathbb{R} : \mu(\{\omega\in\Omega : |f(w)|>c\}) = 0               \right\}$
Comment: @ColdHeartOfStone: Yes, that is a better definition. Another, equivalent one is $\inf_{g \sim f} \sup_x |g(x)|$. The notation $g \sim f$ means  $g$ is equal to$f$ ae.
Answer: No, your notation is incorrect.  When you write something like $$\forall \omega \in A \; \text{such that}\; \mu(A^c)=0$$ you are quantifying over $\omega$, and the variable $A$ is free.  So this expression only is meaningful if you have already given a definition of $A$, and you are making an assertion about all $\omega$ which are in this $A$ with the property that $\mu(A^c)=0$ (which is a queer thing to say, since the condition $\mu(A^c)=0$ does not involve $\omega$ at all).
Instead you could say something like
$$\|f\|_\infty := \inf\{c\in \mathbb{R} : \exists A \text{ such that } \mu(A^c)=0 \text{ and } \forall\omega\in A,  |f(\omega)|\leq c \}.$$
More simply, you could also just pick a specific $A$, since if any $A$ works, then $A=\{\omega:|f(\omega)|\leq c\}$ works.  So you could just say $$\|f\|_\infty := \inf\{c\in \mathbb{R} : \mu(\{\omega:|f(\omega)|>c\})=0\}.$$

Measure theory, notation question, a.e.


Show image on solr search result page

Question: I want to show image in my solr search result page.
For that, I have created one field in my content type called media.
In db, Images are saving in field_data_field_media table in the form of field_media_value
Any help very much appreciated.
Best,
Latika
Comment: Can you please add tag of Drupal version.
Answer: Have you considered helping yourself with this similar question?
showing an image field from solr index on custom solr search page
To display image in your search-result.tpl.php you can follow below link also.
https://www.drupal.org/node/953096
Comment: I tried both. It's not working for me. Mu image is not in CCK editor. I have created one field. How I get this image/image path/nid ?
Comment: Are you saying that you are not getting image field which you have indexed for content type in search results in solr? Is your relation correct there?

Show image on solr search result page


Adicionar campos na página conforme a opção selecionada em um menu de opções select

Question: Eu estou criando um formulário e quero que conforme a opção selecionada no menu um código html diferente seja mostrado na tela. Estou usando jquery pra adicionar os novos campos. Porém a cada opção selecionada os novos campos são concatenados, ou seja, a cada vez que uma opção é selecionada um novo valor é mostrado, eu queria que fosse mostrado apenas uma vez. Segue o código.
$(document).ready(function() {
$( ".form-control" ).change(function(){
    var varURL = $("option:selected", this).val();
    $(".form-group").append('O valor selecionado é: ' + varURL);
});
});

Comment: troca o `append` por `html`
Comment: Eu já tentei, porém o conteúdo é substituído e o menu de opções desaparece.
Comment: então cria uma div dentro desse `form-group` só pra receber o `html()`
Comment: Fiz isso e deu certo!
Comment: assim ele não apaga o menu
Answer: Cria uma nova div dentro do form-group, para receber os valores, depois usando html() você adiciona os valores nessa div:
$(document).ready(function() {
    $( ".form-control" ).change(function(){
        var varURL = $("option:selected", this).val();
        $("ID_DA_NOVA_DIV").html('O valor selecionado é: ' + varURL);
    });
});


Como publicar arquivos de imagem usando Firebase Storage em modo offline?

Question: Olá,
Estou desenvolvendo um código dentro do Android Studio que permita o cadastro de dados num formulário com campos texto e um arquivo de imagem de modo offline (celular sem nenhuma conexão com internet). Funciona muito bem com
FirebaseDatabase.getInstance() mas com o FirebaseStorage.getInstance(), ou seja, com os dois juntos, (texto e imagem) ocorrem erros.
a idéia é salvar os dados (textos e sua imagem em anexo) localmente no Smartphone (inclusive consultar) e quando o mesmo se conectar em alguma rede de internet o mesmo sincronizar os dados no servidor do Firebase.
Fiz testes usando apenas textos e funciona muito bem, mas se tiro uma foto e anexo a mesma no formulário, nada acontece.
Alguma sugestão? Alguém já enfrentou algum problema similar a este?
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //
        mFirebaseData = FirebaseDatabase.getInstance();
        mDatabaseReference = mFirebaseData.getReference("Data");
        mDatabaseReference.keepSynced(true);
        //storage
        mStorageReference = FirebaseStorage.getInstance().getReference();

Answer: Aqui vai um exemplo prático do que você perguntou:
Nesse exemplo, vamos fazer o upload de uma imagem para o FirebaseStorage. Para isso, suponho que os passos para aquisição da imagem via camera ou galeria seja conhecida antecipadamente.
Você pode iniciar background thread a partir de um botão:
     saveStoreData.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (isFormFieldsFilled()) {

                DocumentReference docRef = DatabaseRouter.getStoresCollectionRef().document();
                String key = docRef.getId();

                // Create a Constraints object that defines when the task should run
                Constraints constraints = new Constraints.Builder()
                        .setRequiredNetworkType(NetworkType.CONNECTED)
                        .build();

                // Passing data to the worker class
                Data.Builder builder = new Data.Builder();
                builder.putString("image_uri", profileImageUri.toString());
                builder.putString("image_pushkey", key);
                Data inputData = builder.build();

                // ...then create a OneTimeWorkRequest that uses those constraints
                OneTimeWorkRequest uploadWorkRequest = new OneTimeWorkRequest
                        .Builder(UploadImageToServerWorker.class)
                        .setConstraints(constraints)
                        .setInputData(inputData)
                        .build();

                // Execute and Manage the background service
                WorkManager workManager = WorkManager.getInstance(getActivity());
                workManager.enqueue(uploadWorkRequest);

            }

        }
    });

Agora é só criar a classe Worker: UploadImageToServerWorker
public class UploadImageToServerWorker extends Worker {

    // https://www.raywenderlich.com/6040-workmanager-tutorial-for-android-getting-started

    private static final String TAG = "debinf UploadWorker";

    public UploadImageToServerWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        String imageUriInput = getInputData().getString("image_uri");
        String imagePushKey = getInputData().getString("image_pushkey");
        Log.i(TAG, "doWork: BACKGROUND WORK STARTED FOR KEY: "+imagePushKey);

        final Result[] result = {Result.retry()};
        CountDownLatch countDownLatch = new CountDownLatch(1);
        StorageReference storageRef = DatabaseRouter.getStoresStorageRef(imagePushKey).child(imagePushKey+".jpg");
        storageRef.putFile(Uri.parse(imageUriInput)).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                if (task.isSuccessful()) {
                    Log.i(TAG, "onComplete: image uploaded successfuly!");
                    result[0] = Result.success();
                } else {
                    Log.i(TAG, "onComplete: image NOT uploaded - RETRYING");
                    result[0] = Result.retry();
                }
                countDownLatch.countDown();
            }
        });

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result[0];
    }
}

Pronto! Não sei se esse é o método mais apropriado, mas dá conta do serviço.
"Problemas" que eu encontrei:
1) O envio da imagem é feito sem conexão com a internet, mas a conexão com a internet é reestabelecida antes do tempo limite de conexão com FirebaseStorage: O método doWork() é executado 2 vezes.
2) O envio da imagem é feito sem conexão com a internet e a conexão com a internet é reestabelecida depois do tempo limite de conexão com FirebaseStorage: O médoto doWork() não é executado assim que a internet retorna.
Bem... Espero ter ajudado e boa sorte!
Answer: Salve suas imagens usando banco de dados local e use a biblioteca Workmanager que trabalha em background para sincronizar com o firebase quando houver internet disponível.
Comment: Certo, muito grato pela dica.Algum exemplo de implementação disso? link com exemplos ou documentação talvez?
Comment: Sim meu amigo.... de uma olhadinha neste vídeo para você poder entrar no assunto: https://www.youtube.com/watch?v=P3DO1MRN89M
Comment: Depois você pode buscar por mais exemplos....
Comment: Vou olhar sim, obrigado pelas dicas.


Array JavaScript com objecto JSON

Question: Eu tenho os seguintes objectos:
var category = [
    {"category" : "fruity"},
    {"category" : "Cakes"}
]

e
var products = [
    {"description" : "Apple", "price" : 12.99, "category" : "Fruity"},
    {"description" : "Peach", "price" : 12.99, "category" : "Fruity"},
    {"description" : "Cake one", "price" : 12.99, "category" : "Cake"}
]

Pretendo disponibilizar essa informação no seguinte formato:
[
    {
        "category": "fruity",
        "products": [
            {
                "description" : "Apple",
                "price" : 12.99
            },
            {
                "description" : "Peach",
                "price" : 17.99
            }
        ]
    },
    {
        "category": "Cakes",
        "products": [
            {
                "description" : "Cake one",
                "price" : 12.99
            }
        ]
    }
]

Estou a um tempo trabalhar nisso e o resultado não tem sido satisfatório. Eis o meu código:
var j=0;
var i=0;
var entraP = { prod : [] }

if (category[i].category == products[j].category ){

  entrarP.c = category[i].category;

  while(category[i].category == products[j].category ){

    entrarP.prod.push(products[j]);

    j+=1;
  }
  i+=1;
}

console.log(entrarP);

Agradeço uma ajuda.
Answer: O código que está a utilizar para tentar agrupar os produtos tem algumas coisas que não jogam com o objetivo.
Começa por verificar se a primeira categoria joga com a primeira categoria do primeiro produto:
if (category[i].category == products[j].category ){

O que torna impossível de agrupar caso os produtos apareçam por outra ordem.
Tem também uma erro no nome da variável que fica com o resultado:
entrarP.c = category[i].category;

Que tinha sido anteriormente declarada como entraP e não entrarP.
Mas a lógica em si também não iria funcionar pois o while executa enquanto as categorias forem iguais:
while(category[i].category == products[j].category ){

Logo mal uma seja diferente este termina de imediato.
Como solução pode utilizar a função reduce do javascript para "reduzir" o array original de produtos de acordo com as suas categorias, da seguinte forma:
var produtosAgrupados = products.reduce(function(acumulador, corrente){

  //verificar se o acumulador(o resultado) já tem a categoria corrente obtendo a sua posição
  let indice = acumulador.map(x => x.category).indexOf(corrente.category);

  //-1 indica que não tem logo cria um novo objeto com categoria e produtos com 1, o corrente
  if (indice==-1){
    acumulador.push({
      category: corrente.category,
      products: [{
        description:corrente.description,
        price:corrente.price}]
    });
  }
  else { //se ja tem a categoria adiciona nessa posição o novo produto
    acumulador[indice].products.push({
        description:corrente.description,
        price:corrente.price});
  }

  return acumulador; //retorna o objeto corrente para a próxima iteração
},[]); //começa o reduce com um array vazio

Para esta solução o array original que tinha apenas as categorias nem seria necessário.
Exemplo:

var products = [
    {"description" : "Apple", "price" : 12.99, "category" : "Fruity"},
    {"description" : "Peach", "price" : 12.99, "category" : "Fruity"},
    {"description" : "Cake one", "price" : 12.99, "category" : "Cake"}
];

var produtosAgrupados = products.reduce(function(acumulador, corrente){

  let indice = acumulador.map(x => x.category).indexOf(corrente.category);

  if (indice==-1){
    acumulador.push({
      category: corrente.category,
      products: [{
        description:corrente.description,
        price:corrente.price}]
    });
  }
  else {
    acumulador[indice].products.push({
        description:corrente.description,
        price:corrente.price});
  }

  return acumulador;
},[]);

console.log(produtosAgrupados);
Comment: obrigado pela ajuda. Funciona perfeitamente.

Array JavaScript com objecto JSON