How to make a html page using excel as data source in python

Question: I want to make a simple html page which looks like this:

The text colored in Orange is the dynamic text. I want to filter the excel table on the webpage and print the specified technology and subTechnology data in the html as output.
import pandas as pd
filter = 'LTE2'
df = pd.read_csv("data.csv", delimiter=';')
df = df[df['subTechnology'] == filter]
df.to_html('index.html', index=False)

With the help of a thoughtful contribution, the df.to_html works well for the data but I still don't know how to deal with the text above the table as shown in the screenshot.
And here is my data source:
Technology;subTechnology;Package;Type;Date
4G;LTE2;2.0.5;Major Update;08.10.2017
4G;LTE2;4.4;Normal Update;09.10.2017
2G;GSM2;4.4.2;Major Update;02.12.2017
5G;5G2;1.1.2 mQ1;Major Update;02.01.2020
2G;GSM2A;1.0.7Q;Delivery;03.01.2020
4G;LTE20A;3.0.7;Normal Update;02.03.2020
2G;GSM17A;39142;Major Update;02.04.2020
5G;5G2A;0.2TD;Delivery;03.04.2020
3G;3G20;GF20 2.3;Normal Update;04.04.2020
2G;L2B;1.0TD;Delivery;02.07.2020
5G;5G2A;0.5TD;Delivery;02.08.2020
2G;GSM2B;1.0TD;Delivery;03.08.2020
2G;L2A;1.0.6Q;Delivery;02.10.2020
4G;LTE20A;6.0;Normal Update;02.11.2020

I am familiar with tools like xlsx2html and apsose.cells but I don't know how to filter the data as per the specified subTechnology and show only customized excel in the html. Any documentation or suggestions would be really appreciated.
Comment: What you want is to be able to filter in the website or to filter it locally and the build the website?
Comment: StackOverflow isn't a code-writing service - please edit the code of your honest attempt to solve this problem into your question as a [mre] and exalpin what goes wrong/isn't correct about the output. If there's an error message include the _full_ text of this __as text__. Include some minimal sample data in the code.
Comment: @edoelas Ideally I want to be able to filter through the data on the webpage but I assume dealing with the dynamic content on a signle html page can be difficult, so I can even hardcode the "subTechnology" locally and generate the results to html.
Answer: You have pandas and python in your tags so I will answer using those technologies.
import pandas as pd

filter = 'LTE2'

# Load data as CSV
df = pd.read_csv("./data.csv", delimiter=';')
# Fitler data
df = df[df['subTechnology'] == filter]
# Save data in HTML format
df.to_html('./output.html', index=False)

Comment: Thankyou. Do you also know if there a possibility to be able to select/filter the "subTechnology" in the html page itself?
Comment: I would recommend you to search for a js library that takes care of it. Now I can't think of any but I am sure there are plenty. Please, if my answer helped you mark the answer as accepted.


Schedule a C# console application

Question: I've given a task to create an email C# console application which targeted to run as batch. I'm very new to C# area and hence I have no idea about my direction. This C# console application will be deployed on a server and expect to run in certain time based on server time.
After some research, most of the suggestions are about using task scheduler or window services, but I'm wondering if this C# console application is somehow possible to run own its own? Maybe after execute it, it then register itself into the server and the server will handle it periodically?
Answer: If you want to manage the scheduler by code have a look at Quartz.NET: http://quartznet.sourceforge.net/
This library provides the creation of jobs and triggers.
e.g. (directly from: http://quartznet.sourceforge.net/tutorial/lesson_3.html):
<code>// construct a scheduler factory
ISchedulerFactory schedFact = new StdSchedulerFactory();

// get a scheduler
IScheduler sched = schedFact.GetScheduler();
sched.Start();

// construct job info
JobDetail jobDetail = new JobDetail("myJob", null, typeof(DumbJob));
// fire every hour
Trigger trigger = TriggerUtils.MakeHourlyTrigger();
// start on the next even hour
trigger.StartTime = TriggerUtils.GetEvenHourDate(DateTime.UtcNow);
trigger.Name = "myTrigger";
sched.ScheduleJob(jobDetail, trigger);
</code>
Now this means your console application should run continuously which makes it not really suitable for the job.
Option 1. Add a task via task scheduler (real easy) that executes your console application. See example task: http://www.sevenforums.com/tutorials/12444-task-scheduler-create-new-task.html
Option 2. Create a windows service (not to complicated) that uses a library like Quartz.NET or .NET's Timer class to scheduele jobs and executes a batch operation. See for creation of windows service http://msdn.microsoft.com/en-us/library/zt39148a.aspx
Option 3. Make your console application implement a scheduele library like Quartz.NET or /Net's Timer class and run it as a service (a bit more complex): Create Windows service from executable
Answer: As long as it requires no user input, it will be able to run on it's own. You can schedule the program to run in Windows Task Scheduler for example.
Comment: @IsaacLem, you know the `Main` method in your program? It defaults to accepting a parameter named `args`. This string array will contain the arguments you are passing in. It's just up to you to read them and do something depending on what you've been given.
Comment: This console application is somewhat tricky, it should be having 2 options which is daily and yearly and the code to be executed accordingly. Meaning it requires the Windows Task Scheduler to actually pass in the parameter? Is that even possible?
Comment: @IsaacLem, of course, have you tried it yourself? There's an `Add arguments` box to use when you create a task. Alternatively, why not use a configuration file of some sort?
Comment: Yes task scheduler can pass on fixed parameters as command line attributes. If I understand correctly you will have one task which should be ran once a year? Then create a task for this calling yourapp.exe /year. Then another for daily which is called with another parameter.
Comment: @Arran: Yes I saw that Add arguments and I'm wondering how my C# console application get to read the argument?

Schedule a C# console application


Is function surjective?

Question: For a function $f: R \to R$
$f(x)=x^3$. How is it a onto function.
3 can be codomain of this function. If that is the case, then $x$ must be $\sqrt[3]{3}$.
$\sqrt[3]{3}$ is not a rational number.
Maybe my understanding regarding to this concept is not correct. Can anyone explain to me?
Comment: $\mathbb R$ is the real numbers, not the rational numbers.  You are correct that this is not onto as a function from rational numbers to rational numbers.  But it is onto as a function from real numbers to real numbers.
Comment: Usually $R$ (or better $\Bbb R$) means *reals* and $\Bbb Q$ means *rationals*.
Answer: When you write $f\colon \mathbb{R}\to\mathbb{R}$, $f(x) = x^{3}$ you mean that $f$ has both real inputs and outputs, so there is no reason that $\sqrt[3]{3}$ can't be in the domain.  If you modified the function definition to be $f\colon \mathbb{Q}\to \mathbb{Q},$ for example, then you would be correct that $\sqrt[3]{3}$ is not in the domain.

Is function surjective?


"attempt to write a readonly database" with BrowserTestBase Functional tests

Question: I have a functional test that is currently empty. I run it with the following command;
php core/scripts/run-tests.sh --sqlite /db/drupal.sqlite --php /usr/local/bin/php --verbose --directory modules/custom/

I have tried with and without the --sqlite command, as well as trying a non-existant file like tmpfs/drupal.sqlite, but I always get the same error:

Drupal\Tests\answers\Functional\AnswersTest::testAddContentPage
Exception: Drupal\Core\Database\DatabaseExceptionWrapper:
SQLSTATE[HY000]: General error: 8 attempt to write a readonly
database:

From that error I have gathered that the issue is that the user doesn't have write-access to the database, but without knowing where the database file is I'm not sure how to check this. I tried settings the permissions on /db/drupal.sqlite to 777 but this didn't help either.
Answer: I don't quite understand why this fixes the problem, but in my case the issue was caused by my executing the core/scripts/run-tests.sh script as root. By running it as www-data instead the issue went away.
I can only assume that the sqlite DB gets created by root and then the script switches itself over to www-data and can't access the DB anymore.


Finding bounds to solve integral over domain.

Question:
Let $\mathcal{D} = \lbrace (x,y)\in\mathbb{R}^{2}:1<xy<2,x^{2}<y<2x^{2}\rbrace.$  What is $$\iint_{\mathcal{D}} x^{3}+y^{3}\,\mathrm{d}y\,\mathrm{d}x \ \ ?$$
$(i)\ \ \frac{3}{4},$
$(ii) \ \ 1,$
$(iii) \ \ \frac{36}{37},$
$(iv) \ \ \frac{37}{36}.$

How can I find the bounds of my integrals here? The one for $\mathrm{d}y$ is evident it's $ x^2 $ to $ 2x^2,$
but what about the bounds on $x$ which has to be fixed in order to integrate?
Comment: [This](https://www.desmos.com/calculator/rqqy18d69o) might help you visualize the region.
Comment: I see the region I just have trouble computing the bounds for a fixed x
Answer: Try rewriting the inequalities like this:
\begin{gather}
\frac1x < y < \frac2x \\
x^2 < y < 2x^2
\end{gather}
Now how is it "evident" that the bounds of $dy$ are $x^2$ to $2x^2$?
Why aren't they $\frac1x$ to $\frac2x$?
Look again at the graph of the region (credit: @DMcMor).
A good first step is to find the "corners" of that region where the curves that form the different pieces of the boundary intersect.
Then decide whether you want $dx$ or $dy$ to be the inner integral.
If you want $dx$ to be the outer integral, as suggested in the question,
find the points in the region that are farthest to the left and farthest to the right. Those will be lower and upper limits of $x,$ but not necessarily lower and upper limits of the same integral. Sometimes you need to "slice" a region into multiple pieces, cutting it along vertical lines, and do a separate $dx$ integral on each side of each line.
Answer: Substitute $u=xy$ and $v=\frac{y}{x^2}$ so that the limits on both integrals are $[1,2]$.
On application of the Jacobian, the integrand is $$\frac{x^2}{3y}(x^3+y^3)=\frac 13(\frac{u}{v^2}+u^2)$$
The integrals are now very straightforward, and the answer you get is $\frac{37}{36}$ so the answer is (iv).


How to use/deploy Logger from Log4J with remote jboss container?

Question: I'm checking out the tutorial http://arquillian.org/guides/getting_started/. Everything runs fine. But if I try to add Logger from Log4J with a log4j.xml (placed in src/main/resources) only the embedded containers weld and glassfish runs fine with console log-appender. On the console I got my message:
2012-04-23T15:27:21,859 INFO  call greet (ejbtest.Greeter)

The remote jboss fails.
My deployment:
  @Deployment
  public static JavaArchive createDeployment()
  {
    final JavaArchive deployment = ShrinkWrap.create(JavaArchive.class)
        .addClasses(Greeter.class, PhraseBuilder.class)
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml").addAsResource("log4j.xml");
    return deployment;
  }

The stacktrace-snippet:
    15:33:11,375 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-2) MSC0000
1: Failed to start service jboss.deployment.unit."a680b2b8-2dd6-4b0b-bc87-9082f2
4fc88d.jar".WeldService: org.jboss.msc.service.StartException in service jboss.d
eployment.unit."a680b2b8-2dd6-4b0b-bc87-9082f24fc88d.jar".WeldService: org.jboss
.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for t
ype [Greeter] with qualifiers [@Default] at injection point [[field]

I also tried with adding Logger.class to the JavaArchive, but that also fails with the following stacktrace-snippet:
15:36:50,031 WARN  [org.jboss.modules] (MSC service thread 1-3) Failed to define
 class org.apache.log4j.Logger in Module "deployment.eb8033fe-29d7-4fa5-986f-303
4a1949020.jar:main" from Service Module Loader: java.lang.LinkageError: Failed t
o link org/apache/log4j/Logger (Module "deployment.eb8033fe-29d7-4fa5-986f-3034a
1949020.jar:main" from Service Module Loader)

What is my mistake?
Answer: JBoss has it's onw built in log4j. I guess you have conflict.
Comment: That's right, but there should be a workaround as described here: http://stackoverflow.com/questions/9584787/using-log4j-with-jboss-7-1. But that also doesn't works for me. I always get an instance of org.jboss.logmanager.log4j.BridgeLogger.


$\|x+y\|^2=\|x\|^2+\|y\|^2$ iff $x=cy$ with $c\gt0$?

Question: $ || \vec{x} + \vec{y} ||^2 = ||\vec{x}||^2 + ||\vec{y}||^2 $ iff $ \vec{x} = c\vec{y}$ with $ c>0$
Is this statement correct or not, if not not, please explain. I just started a self-study of Linear Algebra a week ago so my knowledge of it is not too big yet.
Comment: As written, no.  You've squared 2 out of the 3 terms.  Is that intentional?
Comment: Oh, no, not intentional sir, I edited it.
Answer: $||\vec x+\vec y||^2 = (\vec x+\vec y)(\vec x+\vec y) = \vec x\vec x+2\vec x\vec y+\vec y\vec y=||\vec x||^2+||\vec y||^2+2\vec x\vec y$.
Thus equality holds iff $\vec x\vec y=0$, i.e. $\vec x$ and $\vec y$ are orthogonal.
Comment: So in particular, we *can't* allow $\vec x=c\vec y$ with $c>0$.
Comment: only if it's $L_2$ norm
Answer: If $x = cy$, $c \geq 0$, you have $||x+y|| = ||x|| + ||y||$, not $||x+y||^2 = ||x||^2 + ||y||^2$. (BTW, if you have $c \leq 0$, you get $||x+y|| = \left|||x|| - ||y||\right|$)
This is because you then have (in the non-squared case, $c \geq 0$ again) $$
||x+y|| = ||x + cx|| = ||(1+c)x|| = (1+c)||x|| = ||x|| + c||x|| = ||x|| + ||cx|| = ||x|| + ||y||.$$
In the squared case with $c \geq 0$ you end up with $(1+c)^2||x||^2$ on the left side, and $(1+c^2)||x||^2$ on the right side, which is in general not the same.
To see why that is the case, look at these things geometrically. $||x+y||$ is the length of the vector $x+y$. Now, how does the length of two vectors behave if you add them? In general, the resulting length will be smaller than the individual lengths. If the vectors point in the same direction (which is what $x=cy$, $c \geq 0$ means), the resulting length will be the sum of the individual lengths, though.
If you add the squares of the lengths instead, the vetors have to be orthogonal (i.e., the angle between them has to be 90 degree). It works then because for an orthogonal triangle you have $a^2 + b^2 = c^2$ if $a$,$b$ and the lengths of the orthogonal sides, and $c$ is the length of the third side. Note that the third side if interpreted as a vector is the same as the sum of the two other sides, if also interpreted as vectors.
Comment: What you wrote is true if $c>0$. In general you have $\|(1+c)x\|=|1+c|\cdot\|x\|$ and $\|cx\|=|c|\cdot\|x\|$.
Comment: @MartinSleziak Ups, yeah, I was a bit sloppy there. Will edit to fix.


XML tag colors in Visual studio

Question: I can't find any according item in VS2010 color settings to change "<" and "/>" elements color.
Give me a tip how to change that element's default color.
Answer: Tools > Options > Environment > Fonts and Colors > XML Delimeter is what you're looking for.
Comment: Maybe it's a VS2010 specific thing but it doesn't work. Color remains default.
Comment: Strange. Works in both 2005 and 2008.

XML tag colors in Visual studio


What does "silonveut" mean?

Question: I am typesetting a Cambini Quartet. In the score for the cello part I see the following phrase:

What does it mean? It appears to say "silonveut".
This is the context (I don't think the piece is contemporary enough to consider the salamander-looking thing to be part of the music; apologies for that):

(Bonus points: Is the measure supposed to be 8va or is that just a slur?)
Answer: I assume it's french "si l'on veut" - "at one's pleasure" - "ad libitum". It means that the performer may decide freely playing the triples as written or to octavate them (as IMHO it isn't a slur but a 8va bracket).
Comment: Important addendum to this: in older cello music such as this, when written in the treble clef it is to be played an octave lower than written. So the 8va would actually make it be sounding pitch.
Comment: @PatMuchmore This is good to know.

What does "silonveut" mean?


Gráfico de barras com frequência relativa e acumulada

Question: Estou tentando fazer um gráfico de barras com a contagem em cima das barras e as frequências relativas e acumulada dos lados esquerdo e direito respectivamente mas não estou conseguindo.
Os dados são:
dput(x2)
    c(1L, 5L, 3L, 3L, 5L, 3L, 4L, 1L, 2L, 2L, 7L, 3L, 2L, 2L, 3L,
    3L, 2L, 1L, 5L, 4L, 4L, 3L, 5L, 2L, 6L, 2L, 1L, 2L, 5L, 5L, 5L,
    3L, 6L, 4L, 5L, 4L, 6L, 7L)

As distribuições de frequência
table(x2)
x2
1 2 3 4 5 6 7
4 8 8 5 8 3 2

Frequências relativas
prop.table(table(x2))
x2
         1          2          3          4          5          6          7
0.10526316 0.21052632 0.21052632 0.13157895 0.21052632 0.07894737 0.05263158

O que estou tentando fazer é exatamente como na imagem abaixo
Answer: Isto é resolvido com o pacote ggplot2. Em primeiro lugar, eu construo um data frame com tudo o que necessita ser plotado, com nomes que tenham algum significado neste contexto:
dados <- c(1L, 5L, 3L, 3L, 5L, 3L, 4L, 1L, 2L, 2L, 7L, 3L, 2L, 2L, 3L,
           3L, 2L, 1L, 5L, 4L, 4L, 3L, 5L, 2L, 6L, 2L, 1L, 2L, 5L, 5L, 5L,
           3L, 6L, 4L, 5L, 4L, 6L, 7L)

dados.plot <- data.frame(table(dados), table(dados)/sum(table(dados)),
  cumsum(prop.table(table(dados))))
dados.plot <- dados.plot[, -3]
names(dados.plot) <- c("Categoria", "FreqAbsoluta", "FreqRelativa",
  "FreqCumulativa")
dados.plot$FreqRelativa <- dados.plot$FreqRelativa*100
dados.plot
  Categoria FreqAbsoluta FreqRelativa FreqCumulativa
1         1            4    10.526316      0.1052632
2         2            8    21.052632      0.3157895
3         3            8    21.052632      0.5263158
4         4            5    13.157895      0.6578947
5         5            8    21.052632      0.8684211
6         6            3     7.894737      0.9473684
7         7            2     5.263158      1.0000000

Com o data frame dados.plot preparado, eu crio um gráfico de barras com a coluna FreqRelativa. A seguir, coloco os valores da FreqAbsoluta acima das barras do gráfico. Por fim, utilizo a função sec_axis para incluir um segundo eixo. Perceba que fiz uma transformação nos dados de FreqCumulativa, de modo que a linha acabasse na mesma altura do valor máximo das barras. Bastou tomar 100 (valor máximo de FreqCumulativa) e dividir pelo máximo de FreqRelativa.
library(ggplot2)

ggplot(dados.plot, aes(x=Categoria, y=FreqRelativa)) +
  geom_bar(stat="identity") +
  geom_line(aes(y=FreqCumulativa*max(FreqRelativa), group=1)) +
  labs(x="Categoria", y="Frequência Relativa (%)") +
  geom_text(aes(label=FreqAbsoluta), vjust=-0.8) +
  scale_y_continuous(
    sec.axis=sec_axis(trans=~ .*100/(max(dados.plot$FreqRelativa)),
    name = "Frequência Cumulativa (%)"))

As cores, legendas e outras características do gráfico podem ser ajustadas após uma consulta ao help do ggplot2.
Comment: É quase isso, mas não exatamente, a frequência relativa é o quociente da frequência absoluta de cada classe e a soma das frequências, que em geral é colocada em porcentagem. No lado esquerdo você colocou a frequência absoluta, que no caso eu gostaria de colocar em cima de cada barra.
Comment: De fato, eu não havia atentado para alguns detalhes. Veja o novo gráfico, por favor.
Comment: Perfeito, era exatamente isso.


where to unlock mutex in pthread?

Question: Is it a good practice to lock a mutex from the main thread, and release from another thread?
Or should I make sure a thread will do it all in one? ie: lock, and unlock
Comment: This question is not great by any means, but why did it deserve a -1? +1 to compensate..
Answer: http://www.manpagez.com/man/3/pthread_mutex_unlock/
(also from the POSIX spec site: http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_lock.html)

If the current thread holds the lock on mutex, then the
  pthread_mutex_unlock() function unlocks mutex.
Calling pthread_mutex_unlock() with a mutex that the calling thread
  does not hold will result in undefined behavior.
Comment: +1 for correct answer, but I suggest referencing the [POSIX spec](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_lock.html) rather than "manpagez.com".  (The spec is normative.)
Answer: A mutex can only be unlocked by the same thread that locked it. A program that violates this rule has undefined behavior and is not portable or stable; it may seem to work at times and fail horribly at other times, when compiled on a slightly different system, during a different phase of the moon, or after you upgrade.
If you really need this sort of behavior (locking by one thread and unlocking by another), a semaphore may meet your needs. Semaphores do not have owners, and any thread may call sem_post or sem_wait at basically any time.
Answer: It is bad practice to lock in one thread and unlock in another thread as this will require the two threads to communicate with each other. A thread should perform its own locking and unlocking.
Answer: It's never good practice to lock from one thread and unlock from another.  The name says it all -- mutual exclusion.  A thread that takes it holds it until done.

where to unlock mutex in pthread?


Properties of a differential equation

Question: Question:
Let $u,v \in C^1 ([0,1], \mathbb{R}^+)$ such that $u$ is increasing and $v$ is deacreasing and $u(0)=v(1)=0$. Suppose furthermore that the real function $0 \le x(t)\le 1$ satisfies $x'=(1-x)u(x) - xv(x)$. From here can we deduce that the system admits a unique stationary point other than the trivial $x=1$ and $x=0$?
Answer: Under the stated assumptions on $u$, $v$ we cannot deduce the existence of another stationary point. Also if such a point exists it does not have to be unique.
For the first claim (the existence of stationary points in $(0,1)$ is not a necessary condition) consider for example $u(x)=x^2$ which is strictly increasing with $u(0)=0$ and $v(x)=1-x$ which is strictly decreasing with $v(1)=0$. Then,
$$x'=(1-x)u(x)-xv(x)=(1-x)x^2-x(1-x)=-x(1-x)^2$$
for which the only stationary points are $x=0$ and $x=1$.
For the second claim the obvious selection $u(x)=x$, $v(x)=1-x$ yields an infinite number of stationary points (all points in $[0,1]$).

Properties of a differential equation


Como organizar o Diretório do Tema

Question: Estou com uma duvida de como dividir os arquivos CSS e Javascript no meu diretório do meu projeto ASP.NET
Adquiri o tema METRONIC, o diretório do tema possui uma pasta onde fica todos os arquivos css e js chamada de "assets".
Exemplo css:
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css"/>
<link href="../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
<link href="../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css"/>
<link href="../assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="../assets/global/plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css"/>

<link href="../assets/global/plugins/gritter/css/jquery.gritter.css" rel="stylesheet" type="text/css"/>
<link href="../assets/global/plugins/bootstrap-daterangepicker/daterangepicker-bs3.css" rel="stylesheet" type="text/css"/>
<link href="../assets/global/plugins/fullcalendar/fullcalendar/fullcalendar.css" rel="stylesheet" type="text/css"/>
<link href="../assets/global/plugins/jqvmap/jqvmap/jqvmap.css" rel="stylesheet" type="text/css"/>

Exemplo JS:

Então como eu deveria separar eles? pois todos estão na mesma pasta. Devo colocar cada arquivo css na pasta CONTENT e o JS na pasta SCRIPTS?
Ou posso colocar só a pasta ASSENT dentro do content e apontar tudo para ela?
OBS: a duvida é básica mas não queria começar o projeto de maneira errada
Answer: A localização dos seus scripts/styles é algo bem pessoal, você pode colocar estes arquivos na pasta Script/Content ou em alguma pasta reservada para os frameworks e blibiotecas de terceiros.
Eu particularmente colocaria a pasta assets dentro de ~/lib/metronic/assets/..., assim como eu faria com outras blibiotecas e frameworks, como o Bootstrap, jQuery, etc... como no exemplo abaixo.:

bootstrap -> ~/lib/bootstrap-sass/assets/...
jQuery -> ~/lib/jquery/src/...

Ou seja, de forma geral, organizo os as blibiotecas que utilizo em ~/lib/{nome_da_blibioteca}/{arquivos_da_blibioteca}/..., ja à pasta Content e Scrypt, eu reservaria apenas para os scripts e styles de minha autoria.
Um outro ponto, tente utilizar alguma ferramenta para minificar e unificar os seus scripts e styles, você pode começar utilizando o Microsoft Optimization Framework por ser mais simples, para saber mais veja o seguinte Guia.: Bundling and Minification.
Já no meu caso, eu utilizo o Gulp para minificar, unificar e transpilar (no caso de utilizar o TypeScript e SCSS).

Como organizar o Diretório do Tema


Number Theory: Prove $a_1 = a_2 = ... = a_{mn+1}$

Question:
We have a set of integers $a_1, a_2, ..., a_{mn+1}$. If we put one
  number aside, we can divide the rest to $m$ groups each with $n$ number in a
  way that sum of numbers in each group is same. Prove that $a_1 = a_2 =$
  $... = a_{mn+1}$

How can i prove this statement?
Comment: I assume you mean that the condition holds if you put *any* number aside
Comment: Do you mean that for a given choice of a deleted element, all $\dfrac{(mn)!}{(m!)(n!)^{m}}$ partitions of the $mn$-set are such that the sum of the $n$ elements in each of the $m$ sets is the same?
Answer: Let $i$ be such that $a_i$ is the smallest number in the set. Let us now consider the set $\{a_1-a_i,\dots,a_{mn+1}-a_i\}$: every number in this set is non-negative, and at least one number is $0$, and this set clearly has the same property the original set had. Let us put $b_j:=a_j-a_i$, so that $b_i=0$.
Let $S:=\sum_{j=1}^{mn+1}b_j$. If we remove $b_i=0$, by the property of the set we deduce that $S$ is divisible by $n$. If we remove any other $b_j$, then by the property $S-b_j$ is divisible by $n$, which implies that every $b_j$ is divisible by $n$. We can then consider the set $\{b_1/n,\dots,b_{nm+1}/n\}$, which again has the property of the initial set. Since we can repeat this argument an infinite number of times, the $b_j$ had to be all equal to $0$.
Comment: Why should S be divisible by n when $b_i$ is removed ? Wouldn't this imply that the sum of all the $a_i$ be divisible by n, a property that is not stated. Thanks
Comment: You are right. What I meant by $n$ was actually $m$.
Answer: I am going to build on @Leo163's answer.
Assume no two $a_i$ are the same.
Consider the set $(b_1, b_2, ..., b_i, ... b_{mn+1})$ and assume WLOG $b_i = 0$.
Let $N = \sum_{i=1}^{mn+1}b_i$.
Let $S_k$ represent the sum of the numbers in the groups when $b_k$ is removed.
$N = mS_1 + b_1$
$N = mS_2 + b_2$ etc except
$N = mS_i$ as $b_i = 0$
So we can see that $m \mid b_k$ for $1 \le k \le mn+1$
Now we can construct another set $(b_1/m, b_2/m,...,b_i/m, ... b_{mn+1}/m)$ with similar properties such as the original set.
We can keep going on this infinite descent $\implies b_k = 0$ for $1 \le k \le mn+1$
$\implies a_i = a_j$ for $i \ne j$


What would (theoretically) cause ESP LTD strats with Floyd Roses to play easier than an MIM Strat?

Question: Well, my beliefs are being challenged again about guitars' ease of playing. I once thought my strat was as good as it got, but no. Amazingly enough, a $250 LTD guitar (along with other similar models, including Ibanez's and Jackson's) played incredibly well AT GUITAR CENTER! I'm not sure how other people's experiences have been there, but let me tell you- 90% of their guitars are not set up properly! The action is out of whack, the intonation is off, sometimes strings are broken, floating tremolos having 1 inch gaps, etc. The particular model isn't too important, but I'll state that it's an MH-103 anyway.
My question is, is there anything significant about a Floyded 25.5 inch strat model guitar that makes it easier to play than a properly set up Fender Stratocaster, and if so, what? The obvious would be things like intonation, action, tremolo setup, truss rod, and bridge and nut lubrication.
NOTE: In case it needed to be said, because "ease" is fairly arbitrary, I mean minimal amount of force required to push the string down and bend it.
Comment: Without doing research my first guesses are scale length and neck geometry.
Comment: The scale lengths are identical.
Comment: As others have said, it's almost certainly the neck and fret geometry.
The strat has quite a curved fretboard and skinny frets, modern guitars tend to have flatter fretboards and fatter frets (which helps with speed). Then there's the curve of the neck itself. You'll probably find there's not much difference between the strat neck and the LTD. Both will have fairly  modern flat oval profiles. unless you have an old strat.. in which case, sell it and buy 5 modern superstrats :)
Answer: Since we are living in the age of affordable high-precision CNC, it is reasonably easy to produce a highly playable guitar.  What precision milling is not going to buy you is high quality wood and working carefully with the grain and sensitivities of the material.
In five years, your Strat is likely to be just as playable as it is now, given reasonable treatment.  The cheap guitars, not so much.
Wood warps over time.  This affects the tolerances you work with, and the materials.  Working with small tolerances results in higher playability, and in higher susceptibility to problems due to warping.  High turnaround products choose different compromises that allow them to be surprisingly nice at sale time, given a short shelf live.
Answer: All the things you mention are important to playability - and can be adjusted. The factors that can't are the scale length (obvious), and the neck profile and fingerboard radius. Those two things are very subjective - they either get liked by the player, or not. Often because they are similar to a favourite instrument. String spacing and indeed strings come into the equation, too. I think my guitars with .008s are wonderful to play, a friend who prefers .011s thinks they're awful. I don't like playing his guitars, funnily enough. As said earlier, action is adjustable, and is a personal choice. As is the vibrato set up. Intonation is absolute, so it's going to be impossible for a shop to have guitars that are ideal for everyone. Maybe that's why there are so many different sorts...
Comment: I didn't think about the radius. Maybe that's it? I don't see how that impacts the playing so much though. I'll have to get the radius of that LTD guitar to be sure :P
Comment: The LTD guitar has a 350mm radius while the strat has a much lower 185mm radius. :(


Probability With replacement

Question: A bag contains blue, red and white discs. In an experiment, 24 students in a class take turns to remove a disc from the bag, record its colour and replace it. This is repeated 10 times. At the end of the experiment the relative frequencies are:
Red: 118/240, blue: 83/240, white: 39/240
Anne suggests that there are 10 discs in the bag. Is this a reasonable suggestion?
Based on the information, how many discs of each colour do you think are in the bag?
Answer: Firstly I agree with John Chessant in the sense of the ratio of the various coloured discs, i.e. R:B:W = 3:2:1.
As to whether Anne's suggestion is "reasonable" or not, there  is a somewhat subjective element to this question.
I'm inclined to think that Anne must of had some prompting factor to suggest 10, she may have gave such a number because she could clutch all or most of the discs in the one hand thereby giving her a fair guesstament as to the number of discs.
 A statistician would deem it blatantly unreasonable, Anne's mother would deem it highly reasonable. I waver somewhere in between, after all it is not outside the realm of possibilities that the results can occur with the ratios of 5:3:2 however unlikely. But personally believing the ratio is most likely 3:2:1 with the actual numbers being 6,4,2, for Red, Blue and White respectively, then Anne's guesstament is out by only 2, if this is the case I still hold the same view regarding her suggestion i.e. Not unreasonable ( call me a softie).
In light of what I have said in the above I give my answer to the second question as----
Red=6
Blue=4
White=2
Answer: I think that $10$ discs is not a reasonable suggestion. It is most likely to be a multiple of $6$. In that case, there would be $3n$ red discs, $2n$ blue discs, and $n$ white discs, for a total of $6n$ discs.
To see why, notice that since $240$ discs were recorded, the numerators give the number of times each disc was chosen (i.e., $118$ red, $83$ blue, and $39$ white). Notice that these are about a $3:2:1$ ratio! (One way to see this is to estimate $118\to 120$, $83\to80$, and $39\to40$.)
So the number of red discs is three times the number of white discs, and the number of blue discs is two times the number of white discs.
(Edit: Of course, it is possible that, given $10$ discs, the recorded numbers of discs would still be as above, but it is extremely unlikely.)
Comment: I think there are $8888$ discs in the bag, since it is quite heavy, but feels like a lucky bag. The results are absolutely consistent with that.
Comment: Thank you. Yes, it is most likely a multiple of $6$, and most likely $12$ discs. Maybe I should have clarified.
Comment: We're working with probability. It doesn't HAVE to be a multiple of 6, the results merely suggest it should.

A better explanation for why 10 discs is unlikely would be that if we assume 10 discs, we expect about a multiple of 24 sightings for each color, but both blue and white strongly suggest that's not the case.

Based on Anne's suggestion, I'd assume the total number of discs is 12, since she reached in and presumably guessed 10 based on how many discs she felt (not doing the math).
Comment: And you would be right. There is nothing to say that there can't be $8888$ discs in the bag.

Probability With replacement


Error after importing Android project

Question: I moved an Eclipse-based Android project from another machine to the machine that I am working with. I imported the project using Android Project from Existing Source. Everything is working well when I code but when I deploy it using emulators and phones, it's producing weird exceptions. What might be the problem?
I have attached the exceptions produced with the questions for information.
<code>12-06 08:15:20.957: E/AndroidRuntime(767): FATAL EXCEPTION: main
12-06 08:15:20.957: E/AndroidRuntime(767): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.innolabmm.discoverlioncity/com.innolabmm.discoverlioncity.FeedActivity}: java.lang.ClassNotFoundException: Didn't find class "com.innolabmm.discoverlioncity.FeedActivity" on path: /data/app/com.innolabmm.discoverlioncity-1.apk
12-06 08:15:20.957: E/AndroidRuntime(767):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
12-06 08:15:20.957: E/AndroidRuntime(767):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
12-06 08:15:20.957: E/AndroidRuntime(767):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-06 08:15:20.957: E/AndroidRuntime(767):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
12-06 08:15:20.957: E/AndroidRuntime(767):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-06 08:15:20.957: E/AndroidRuntime(767):  at android.os.Looper.loop(Looper.java:137)
12-06 08:15:20.957: E/AndroidRuntime(767):  at android.app.ActivityThread.main(ActivityThread.java:5041)
12-06 08:15:20.957: E/AndroidRuntime(767):  at java.lang.reflect.Method.invokeNative(Native Method)
12-06 08:15:20.957: E/AndroidRuntime(767):  at java.lang.reflect.Method.invoke(Method.java:511)
12-06 08:15:20.957: E/AndroidRuntime(767):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-06 08:15:20.957: E/AndroidRuntime(767):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-06 08:15:20.957: E/AndroidRuntime(767):  at dalvik.system.NativeStart.main(Native Method)
12-06 08:15:20.957: E/AndroidRuntime(767): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.innolabmm.discoverlioncity.FeedActivity" on path: /data/app/com.innolabmm.discoverlioncity-1.apk
12-06 08:15:20.957: E/AndroidRuntime(767):  at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65)
12-06 08:15:20.957: E/AndroidRuntime(767):  at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
12-06 08:15:20.957: E/AndroidRuntime(767):  at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
12-06 08:15:20.957: E/AndroidRuntime(767):  at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
12-06 08:15:20.957: E/AndroidRuntime(767):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
12-06 08:15:20.957: E/AndroidRuntime(767):  ... 11 more
</code>
Comment: Does your project contains 3rd party jar files?
Comment: It does. It makes use of Facebook SDK.
Comment: possible duplicate of [ClassNotFoundException after ADT update](http://stackoverflow.com/questions/16610190/classnotfoundexception-after-adt-update)
Answer: Try this:
Go to Project/Properties/Java Build Path/Order and Export -- Make sure there's a check in front of Android Dependencies and the support library, if you use it.Mark all checkboxes and Click on Apply and clean the project.
Hope this helps.
Comment: The problem persists and Eclipse is spewing out these exceptions.

12-06 08:44:06.674: E/AndroidRuntime(1277): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.innolabmm.discoverlioncity/com.innolabmm.discoverlioncity.FeedActivity}: java.lang.ClassNotFoundException: Didn't find class "com.innolabmm.discoverlioncity.FeedActivity" on path: /data/app/com.innolabmm.discoverlioncity-2.apk
Comment: Did you mark all check boxes, cleaned the project and then ran project?

Error after importing Android project


How can I convince someone that $1/3$ is a real number?

Question: How can I convince someone that $1/3$ is a real number? I've tried explaining to them that you can draw it on a number line but they argue that (and I quote) "there is no number there, what's the number?" when I reply back that it can be written as $0.333...$ in decimal, they say "that's not a number".
I've also tried explaining that you can write the number in a different base system (say, base 12), and it won't have a repeating decimal, but then they go on about numbers must have a base 10 form or something along those lines. They also say that $0.999...$ is not a number and it does not equal $1$ ("there's a bunch of nines, each nine is getting closer, and the difference is $0.000...1$" they say).
Is there a clear and straightforward argument for this, or is it impossible?
Comment: What is his or her definition of a real number?
Comment: You have to consider the possibility the one you are teaching is intentionally acting dumb.
Comment: https://math.stackexchange.com/questions/11/is-it-true-that-0-999999999-dots-1
Comment: Give them a practical exercise that forces them to divide by three in a general setup (like: divide something in such a way that one person has twice the other) and demote them if they fail.
Comment: @rogel They believe that 0.5 is a number, 0.25, etc., just nothing with a repeating decimal when written decimally.
Comment: Ask them what a real number is.  Why *isn't* $\frac 13$ a real number?  Then work with them on what the actual definitions is.  It seems you are *both* working *without* a definition and both think a number is "something you can see on a number line" which is circular at best (your interpretation) and wrong at worse (your friend who thinks that means only integers).
Comment: With this person's belief of what a number is, they will not accept that $1/3$ is a number. Just like people who don't vaccinate their children, there is nothing you can do to change their mind.
Comment: One third is a value.  You can cut things into three equal parts.  The real numbers are every possible value.  So it has to be a number.  If someone thinks $\frac 13$ is not a real number then either 1) they think "real number" has a special meaning it doesn't or 2) they just are refusing to think.  If the former, explain the misconception, If 2) then ... while I like B. Goddards advice about teaching pigs to sing.
Comment: @yusef Okay... can you just try to introduce them to base 3? In base 3, $1/3$ has a finite decimale expansion.
Comment: What does bases and finite decimals have to do with anything?  Decimals aren't magic.  Being able to write something in decimal has nothing to do with whether something is a number.  Fractions are numbers.  Period.  Fractions are numbers.  Decimals are *one* (incomplete) way of writing numbers but they do not *define* numbers and not every number can be written as a finite decimal.  (They can be written as an *infinite* decimal but that is a *hard* and advanced concept to be proven--- it is NOT a definition)  And that is the mistake.  People think decimals *DEFINE* numbers. They don't.
Comment: Hit them with a two-by-four, and shout in their ear "Decimals do not make numbers; decimals are a *tool* to describe numbers; but they don't make numbers."
Answer: You can prove that the existence of $\frac13$ is as valid as the existence of $1$ with a compass and straightedge.

Let $AB=1$.  (As your friend has indicated that $1$ is a valid point on the number line, you can ask what such a representative distance would be.)  On a separate ray, construct points $C,D,E$ such that $AC=CD=DE$.  Construct a line parallel to $\overline{EB}$ that passes through $C$.  That line will intersect $\overline{AB}$ at $F$.
$\angle AFC\cong\angle ABE$ and $\angle ACF\cong\angle AEB$, because these are corresponding angles of parallel lines cut by a transversal.  Therefore, $\triangle ACF\sim\triangle AEB$, and therefore, their sides are in proportion.  This means that $\frac{AB}{AF}=\frac{AE}{AC}=3$.
So we have a physical line segment $\overline{AF}$ that has a length that satisfies $3AF=1$.  How long is it?  If one believes that there is not an "intrinsic" number that signifies its length, hopefully one would acknowledge that this is a sufficiently relevant situation that we would need to artificially construct such a number.  In either event, we will call that number $\frac13$.
Comment: This is much cooler than what I expected from answers to this question
Comment: I think you will need to explicitly state $\overline AB$ is the abstract (but in the friends mind very real) "number line" and that $A$ **is** zero and $B$ **is** $1$.  The friend is likely to think this is mumbo jumbo and makes no sense but... it is a point an the line.
Comment: @fleablood Agreed.  If the friend acknowledges that answering the question "Where is it on the number line?" will satisfy them, and especially if they acknowledge that they are bisecting the number line to find the dyadic rationals, then a fair-minded skeptic ought to be persuaded by this argument.  (And, by contraposition, anyone not persuaded by this argument is not being fair-minded. ^_^)
Comment: @MaximilianJanisch This is essentially how the Greeks came to terms with $\sqrt2$ being a number even though they knew it couldn't be the ratio of two natural numbers.
Answer: I've had this issue too. I like to pose the question in the opposite direction. I would ask them, what numbers ARE real, then? They might answer the integers, or the naturals. But then, it should be possible to argue that the naturals are just as arbitrary as the rationals, they just happen to be more intuitive.
The only valid stances on the issue, in my opinion, is the stance that all numbers are "real", or none of them are.
Comment: what about complex numbers :-)?
Comment: @J.W.Tanner I think real and imaginary are terrible names, frankly. I fall in the camp of all numbers being equally fake, so I don't really know.
Comment: Those are just subsets of the algebraic numbers.
Comment: @RoddyMacPhee What are you referring to here?
Comment: I give up ... you people can comment anything even irrelevant crap, I make comment like thst, nobody seems to know math.
Comment: What here is irrelevant?
Answer: I think your friend has gotten it through their head that a "real number" is DEFINED to be anything that can be written as a decimal.
This is simply wrong.  That is not the definition.  It is backwards.  Eventually (but not now) it will be proven that if all numbers can be written as a decimal if you allow infinite decimals.  DON'T worry about teaching your friend that step yet.  It will just confuse them.
Instead decimals were invented (not discovered, invented) as a way to express numbers in a way that we can compare sizes of numbers that are not whole numbers.
So what IS a real number?  It's any value.  Period.  That's all.
And $\frac 13$ is a value.  You can divide things evenly.  HOW you divide things evenly is another issue but that isn't relevant.  $\frac 13$ is a very obvious value.
Now it is interesting that we can express $\frac 13$ as a fraction but not as a finite decimal.  But that is not relevant.  Decimals do not define numbers.  Not being able to express $\frac 13$ didn't make $\frac 13$ disappear out of the universe.  We can still talk about $\frac 13$.  What is $\frac 13$ then if it isn't a number?  A rabbit?  A non-number?  Ah, I know!.... A "fraction"; a magical beast like a chimera gryphon that doesn't actually exist.
Sorry.  It is a real value.  Hence it is a "number"
Decimals do not define numbers.  They are ONE way to (inefficiently and incompletely[*]) describe numbers but they don't magically turn some values into numbers and magically turn other values into chimeras.
All values are real numbers.  What else could they be?
=====
[*] Unless you allow infinite decimals.  But that's a lesson for later.


Editar registros de um clientdataset de campos advindo de um join

Question: Tenho um exemplo simples, porém em três camadas, com sqldataset + datasetprovider + clientdataset. Não carrego nenhum field no sqldataset. No datasetprovider deixo o updatemode em upwherekeyonly.
No datasetprovider eu deixo allowcommandtext como true para poder receber commandtext do lado cliente via clientdataset. No lado cliente eu carrego os fields com Select * ... e durante o tempo de execução envio o commandtext com um join de forma que traga so os campos já carregados. Quando tento editar algum registro e dar o applyupdates no evento onreconcileerror recebo:
Unable to Find Record. No Key especified

Uso xe5+dbexpress+mysql. A pergunta é como devo configurar os componentes para editar e atualizar registros vindo de um command com join?
RESUMINDO A DISCUSSÃO
Pode-se deixar todas as configurações padrão do delphi, a unica coisa que é preciso é colocar no evento OnGetTablename do datasetprovider o nome da tabela a ser atualizada, isso resolveu todos os meus problemas.
Answer: Artur, isto acontece porque para o DataSet entende que todos os campos pertencem a mesma tabela.
Para corrigir o problema, você deve configurar quais campos não são campos de dados da tabela, qual a chave e qual a tabela a ser atualizada.
Configurar corretamente os campos
Uma forma de se fazer isso é setando a propriedade ProviderFlags para vazio, dizendo que o campo não deve aparecer nem no Where e nem ser atualizado (pfInWhere, pfInUpdate).
CampoA.ProviderFlags := [];

Ou alterando o FieldKind para fkInternalCalc.
CampoA.FieldKind := fkInternalCalc;

Outra coisa importante é definir o campo chave primária, para garantir que o provider identifique corretamente a chave a ser utilizada, e para isso você deve setar o ProviderFlag para pfInKey
CampoChave.ProviderFlags := CampoChave.ProviderFlags + [pfInKey];

ou
    CampoChave.ProviderFlags := [pfInUpdate, pfInKey];
Definir o nome da tabela a ser atualizada
Além disso, é recomendado implementar o evento onGetTableName do TDataSetProvider, para que ele saiba em qual tabela dar update.
procedure DataSetProvider.onGetTableName(Sender: TObject);
begin
    Result := 'NomeDaTabelaASerAtualizada';
end;

Comment: @Capauto obrigado pela resposta quando chegar no pc te retorno. Só lembrando, como disse acima, no meu inner join não trago campos de outra tabela, apenas de uma, eu faço tipo duas filtragens em uma tabela, mestre/detalhe.
Comment: Nesse caso ignore a parte de tirar campos do update e where, mude apenas o campo key e defina o nome da tabela. Faz um bom tempo que não mexo com datasets mas se bem me lembro fazíamos assim.  Qualquer coisa só notifica aqui que posso ajudar mais se não resolver.
Comment: deu certo, realmente o problema era não ter o evento ongettable o nome da tabela, muito obrigado!
Comment: agora o problema é que não edita nem deleta, mas salva, aparece: Unable to find record. No key specified.
Comment: Consegui resolver, coloquei em vez de upwherekeyonly, upwhereall. Muito obrigado mais uma vez.


Automatically update dynamic variable in Winform text field

Question: I would like to specify a variable in a text field in a winform. This should then update automatically in winform.
First, a WMI event is registered, which checks whether a USB device is connected or not. The result is stored in the $Global:ConnectionStatus variable.
This also works, the variable changes as soon as a USB device is connected or not. The initial entry of the status in Winform also works. Just don't update it.
Script:(Should work everywhere).
###Register event to watch changing usb drives

#Query for finding all device arrival events
$query = "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType=2"

#Register an event subscription
Register-WmiEvent -Query $query -Action {
    $volumeName = (Get-WMIObject -Class Win32_LogicalDisk -Filter "DeviceID='$($Event.SourceEventArgs.NewEvent.DriveName)'").VolumeName
    $Global:ConnectionStatus = "Laufwerk $volumeName verbunden"
} | Out-Null

#Query for finding all device Removal events
$query = "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType=3"

#Register an event subscription
Register-WmiEvent -Query $query -Action {
   $Global:ConnectionStatus = 'Nicht verbunden'
} | Out-Null

#region windows forms
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
#
#Create main form
#
$Form = New-Object System.Windows.Forms.Form
$Form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle #modifies the window border, not able to resize
$Form.Text = "Test"
$Form.Size = New-Object System.Drawing.Size(946, 580)
$Form.StartPosition = "CenterScreen"
$Form.AutoScroll = $True
$Form.AutoSize = $True
$Form.AutoSizeMode = "GrowOnly" #GrowAndShrink or GrowOnly
$Font = New-Object System.Drawing.Font("Microsoft Sans Serif", 12)
$Form.Font = $Font
$Icon = [system.drawing.icon]::ExtractAssociatedIcon($PSHOME + "\powershell.exe")
$Form.Icon = $Icon
#
#Create textbox
#
$Textbox1Connection = New-Object 'System.Windows.Forms.TextBox'
$Textbox1Connection.Font = [System.Drawing.Font]::new('Microsoft Sans Serif', '9.75')
$Textbox1Connection.Location = New-Object System.Drawing.Size(36, 45)
$Textbox1Connection.Size = New-Object System.Drawing.Size(180, 22)
$Textbox1Connection.Text = "$Global:ConnectionStatus"
$textbox1Connection.TextAlign = 'Center'
$Textbox1Connection.ReadOnly = $True
$Form.Controls.Add($Textbox1Connection)

#Activate the form
$Form.Add_Shown({$Form.Activate()})
[void]$Form.ShowDialog()

#Unregister event
#Get-EventSubscriber | Unregister-Event

I tried
$Textbox1Connection.add_TextChanged({ $displayLabel.Text = $Global:ConnectionStatus })
but that dosen`t work.
Answer: Since you need to present a modal Dialog that is subsequently updated when WMI events notify of changes related to status of the local drives, you cannot execute the two parts in the same Runspace.
The modal Dialog blocks the current Thread, so the notifications coming from the WMI events can only be accessed when the Dialog closes.
You can subscribe to these events in a different Runspace, and use a Synchronized HashTable (for example) to exchange data between runspaces.

You can do the opposite, create the Form in a secondary Runspace. In this case, you have to explicitly set the Runspace.ApartmentState to ApartmentState.STA (single-threaded apartment), since some underlying Activex objects require this.

Create the Form and add a TextBox Control to it:
Note (1): I'm setting the Font of the Form. All child Controls, by default, inherit the Font from their direct Parents, hierarchically.
Note (2): The code is presented in separated parts, but it's of course the same script.
Note (3): The script uses the older Register-WmiEvent, not available in PowerShell Core. When updating to PowerShell Core becomes necessary, see  Register-CimIndicationEvent
using namespace System.Drawing
using namespace System.Windows.Forms

Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.Windows.Forms

[Application]::EnableVisualStyles()
[Application]::SetCompatibleTextRenderingDefault($false)
Clear-Host

$form = [Form] @{
    ClientSize = [Point]::new(946, 580)
    Font = [Font]::new("Segoe UI", 9.75)   # Never use Microsoft Sans Serif
    FormBorderStyle = [FormBorderStyle]::FixedSingle
    Icon = [Icon]::ExtractAssociatedIcon($PSHOME + "\powershell.exe")
    StartPosition = [FormStartPosition]::CenterScreen
    Text = "Test"
}

$textboxConnection = [TextBox] @{
    Location = [Point]::new(36, 45)
    ReadOnly = $true
    Size = [Size]::new(300, 0) # Height auto-sizes to inherited Font height
    TextAlign = [HorizontalAlignment]::Center
}

$form.Controls.Add($textboxConnection)
$form.add_Shown({$form.Activate()})

Create a synchronized HashTable, using Property-based access.
I'm storing references to the Form and the child TextBox here
$hash = [hashtable]::Synchronized(@{})
$hash.Value = ""
$hash.Window = $form
$hash.TextBox = $textboxConnection

Create a second Runspace (somewhat verbose) and add a script that subscribes to the WMI events (see RunspaceFactory.CreateRunspace() and PowerShell.Create() for more details).
When an event is raised, the script calls a local function that updates the content of the TextBox. Since we're in a cross-Thread scenario, we need to marshal the call to the Thread the window belongs to.
Here, I'm using the reference to the Form previously stored in the HashTable, to call is BeginInvoke() method, which invokes the standard dispatcher asynchronously (we cannot block event handlers in any way).
The Action delegate sets the Text property of the TextBox to the new value.
$iss = [InitialSessionState]::CreateDefault2()
$runspace = [RunspaceFactory]::CreateRunspace($iss)
$runspace.Open()
$runspace.SessionStateProxy.SetVariable("hash", $hash)

$shell = [PowerShell]::Create($iss)
$shell.Runspace = $runspace
$shell.AddScript({
    $query = "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType=2"
    Register-WmiEvent -Query $query -Action {
        $volumeName = (Get-WMIObject -Class Win32_LogicalDisk -Filter "DeviceID='$($Event.SourceEventArgs.NewEvent.DriveName)'").VolumeName
        $hash.Value = "Laufwerk $volumeName verbunden"
        Update-Window
    } | Out-Null

    $query = "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType=3"
    Register-WmiEvent -Query $query -Action {
        $hash.Value = "Nicht verbunden"
        Update-Window
    } | Out-Null

    Function Update-Window {  # You can of course pass the text as a parameter
        $hash.Window.BeginInvoke([action]{
            $hash.TextBox.Text = $hash.Value
        })
    }
}) | Out-Null  # When the session terminates, the subscriptions are canceled

$runspaceHandle = $shell.BeginInvoke()
[void]$form.ShowDialog()

$shell.EndInvoke($runspaceHandle)
$runspace.Close()
$shell.Dispose()

You can also use a Timer to poll the $hash.Value.
Probably less efficient and it may cause some flickering, but it works anyway.
# [...]
$timer = [Timer] @{ Interval = 250 }
# No need to BeginInvoke() here
$timer.add_Tick({$textboxConnection.Text = $hash.Value})
# [...]
$form.add_Shown({$form.Activate(); $timer.Start()})
$form.add_FormClosed({$timer.Dispose()})
# [...]

Comment: Wow, thanks, that works great and looks much more professional than what I've found meanwhile. I will use this way in the future!
Except for one point about which I "lied" before.
During the initial call, the status is not displayed correctly in the text field. It is emty! (I always had the variable available in the PS ISE while my test, so I was wrong). This doesn't work your way either. I have a "botched" solution that works like your second way with a timer. Before that, however, I have to determine and enter the initial status of the drive.
Comment: Well, of course the initial status is undetermined, if you don't query it beforehand. The updates are based on events, raised when *something happens*. When the script is first run, nothing has happened yet. Make a query (in the main runspace) to check the status of the drive, then initialize `$hash.Value` to that value instead of an empty string. This assumes you're monitoring a volume with a specific name (`Caption`), `Model` or `SerialNumber` and its `MediaLoaded` property is set to `true`
Comment: This may be helpful: [Get the serial number of USB storage devices in .Net Core 2.1](https://stackoverflow.com/a/51806262/7444103) (not just about the serial number, as you an see) -- You could also make a query that checks whether any drive with `InterfaceType = 'USB'` is inserted at that time. I don't know what you're actually monitoring
Answer: My own, "potched" way:
    function TextBox-Update
{
  $Textbox1Connection.Text = "$Global:ConnectionStatus"
}

#Get acual status, name and driveletter of usb device
$MP3PlayerConnected = Get-disk | Where-Object bustype -eq 'usb' | Where-Object {$_.FriendlyName -like 'FC-1307 SD*'} | get-partition | get-volume
if ($MP3PlayerConnected.FileSystemLabel -like 'Rock')
{
  $Global:ConnectionStatus = "Laufwerk" + " " + $MP3PlayerConnected.DriveLetter + ":" + " " + "verbunden"
}
else
{
  $Global:ConnectionStatus = 'Nicht verbunden'
}

###Register event to watch changing usb drives

#Query for finding all device arrival events
$query = "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType=2"

#Register an event subscription
Register-WmiEvent -Query $query -Action {
    $volumeName = (Get-WMIObject -Class Win32_LogicalDisk -Filter "DeviceID='$($Event.SourceEventArgs.NewEvent.DriveName)'").VolumeName
    $Global:ConnectionStatus = "Laufwerk $volumeName verbunden"
} | Out-Null

#Query for finding all device Removal events
$query = "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType=3"

#Register an event subscription
Register-WmiEvent -Query $query -Action {
   $Global:ConnectionStatus = 'Nicht verbunden'
} | Out-Null

#region windows forms
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
#
#Create main form
#
$Form = New-Object System.Windows.Forms.Form
$Form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle #modifies the window border, not able to resize
$Form.Text = "Test"
$Form.Size = New-Object System.Drawing.Size(946, 580)
$Form.StartPosition = "CenterScreen"
$Form.AutoScroll = $True
$Form.AutoSize = $True
$Form.AutoSizeMode = "GrowOnly" #GrowAndShrink or GrowOnly
$Font = New-Object System.Drawing.Font("Microsoft Sans Serif", 12)
$Form.Font = $Font
$Icon = [system.drawing.icon]::ExtractAssociatedIcon($PSHOME + "\powershell.exe")
$Form.Icon = $Icon
#
#Create textbox
#
$Textbox1Connection = New-Object 'System.Windows.Forms.TextBox'
$Textbox1Connection.Font = [System.Drawing.Font]::new('Microsoft Sans Serif', '9.75')
$Textbox1Connection.Location = New-Object System.Drawing.Size(36, 45)
$Textbox1Connection.Size = New-Object System.Drawing.Size(180, 22)
$Textbox1Connection.Text = "$Global:ConnectionStatus"
$textbox1Connection.TextAlign = 'Center'
$Textbox1Connection.ReadOnly = $True
$Form.Controls.Add($Textbox1Connection)
#
#Create timer to update texbox over fuction TextBox-Update
#
$Timer = New-Object System.Windows.Forms.Timer
$Timer.Interval = 2000
$Timer.Add_Tick({TextBox-Update})
$Timer.Enabled = $True

#Activate the form
$Form.Add_Shown({$Form.Activate()})
[void]$Form.ShowDialog()

#Unregister event
#Get-EventSubscriber | Unregister-Event

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


How many times an MLB team has won a game with no hits?

Question: The Los Angeles Dodgers and Pittsburgh Pirates tied 0-0 at the end of the 9th inning on August 23rd 2017. With one out and a runner on the second base, the pirates had a chance to win the game with no hits in the 9th. Dodgers' pitcher Rich Hill went on to throw a no hitter game through 9 innings.
The commentators mentioned that winning without a hit is a rarity, so I'm wondering how many times it has happened in MLB history.
Answer: From an ESPN article and MLB article about a game between the Dodgers and Angels played in 2008:

The final score was 1-0, marking the fifth time since 1900 that a team
  did not get a hit but won the game.

Complete List:
  Cnt Date          Tm   Opp GmReslt  PA  AB  R  H 2B 3B HR RBI BB IBB SO HBP SH SF ROE GDP SB CS LOB Batrs
+----+-------------+---+----+-------+---+---+--+--+--+--+--+---+--+---+--+---+--+--+---+---+--+--+---+-----+
    1 1992-04-12(1) CLE  BOS W  2-1   32  25  2  0  0  0  0   2  7   0  6   0  0  0   1   0  6  1   6     9

    2 1990-07-01    CHW  NYY W  4-0   31  26  4  0  0  0  0   0  5   0  3   0  0  0   3   0  1  1   3    11

    3 1967-04-30(1) DET @BAL W  2-1   40  24  2  0  0  0  0   0 10   1  3   2  4  0   1   1  1  0  11    14

    4 1964-04-23    CIN @HOU W  1-0   31  29  1  0  0  0  0   0  2   0  9   0  0  0   2   0  0  0   3    10

    5 2008-06-28    LAD  LAA W  1-0   29  24  1  0  0  0  0   1  3   0  9   1  0  1   1   0  1  0   4    13
Source: Baseball Reference (Included code is of respective website.)
Wikipedia article on these win:

five times a team has been no-hit and still won the game: two notable victories occurred when the Cincinnati Reds defeated the Houston Colt .45s (now called the Houston Astros) 1–0 on April 23, 1964 even though they were no-hit by Houston starter Ken Johnson, and the Detroit Tigers defeated the Baltimore Orioles 2–1 on April 30, 1967 even though they were no-hit by Baltimore starter Steve Barber and reliever Stu Miller.

Another list that may be helpful from Baseball Reference.
Answer: When the Cincinnati Reds played the Pittsburgh Pirates at PNC Park on May 15, 2022, Hunter Green and Art Warren combined for 8 innings with no hits, but Cincinnati lost the game 1-0 after three walks and an RBI fielders choice grounder.
Comment: Welcome to Sports Stack Exchange. This is not a no-hitter as defined by the MLB, as Pittsburgh did not pitch nine innings. It does answer the question, as the only requirement is "no hits" rather than a no-hitter.
Comment: Made a few more edits.  I did change the date format, which normally we wouldn't do, but this is such an american-nearly-only sport that it seemed more appropriate - if you care strongly about the date I don't mind reverting it.


Find total year spans in an array with gaps

Question: I need to draw a stacked bar graph for this array which should have 2 bars separated with a white-space of 2 years span (from year 1998 to 2000)
The Problem:
the first bar should be like,
*1998-1997* - *2 years gap*  - *2000-2008*

The bars should merge shorter year-spans within like it did in taking 2000 from array0 and 2008 from array 1
Array
(
    [comp_name] => C++
    [parent_cat_name] => Information Technology
    [sub_cat_name] => Programming
    [total_years] => 6
    [last_year] => 2006
    [start_year] => 2000
)

Array
(
    [comp_name] => .NET
    [parent_cat_name] => Information Technology
    [sub_cat_name] => Programming
    [total_years] => 7
    [last_year] => 2008
    [start_year] => 2001
)

Array
(
    [comp_name] => API
    [parent_cat_name] => Information Technology
    [sub_cat_name] => Programming
    [total_years] => 1
    [last_year] => 1998
    [start_year] => 1997
)

Comment: So where's the bar-graphing code?
Comment: the bar graph coding is not the problem but to find the year gaps is
Comment: Can you post your graphing script so we can see what you actually mean you are graphing? This seems quite unclear.
Comment: from the array above, are we able to see how many different year spans we have? for instance, we have 2 in the above array
one is 2000 to 2008 since they both lie in each other and the other is 1997 to 1998
Answer: You want to merge two array items, if they are adjacent according to some condition AND have some equality condition on some other fields.
You might do:
for(;;)
{
    $merge = array();
    $n     = count($data);
    for ($i = 0; empty($merge) && $i < $n-1; $i++)
    {
        for ($j = $i+1; empty($merge) &&  $j < $n; $j++)
        {
            // Are $i and $j congruent?
            if ($data[$i]['parent_cat_name'] != $data[$j]['parent_cat_name'])
               continue;
            if ($data[$i]['sub_cat_name'] != $data[$j]['sub_cat_name'])
               continue;

            // Are $i and $j adjacent?
            if ($data[$i]['last_year']+1 == $data[$j]['start_year'])
            {
                $merge = array($i, $j);
                break;
            }
            if ($data[$j]['last_year']+1 == $data[$i]['start_year'])
                $merge = array($j, $i);
                break;
            }
            // They are congruent but not adjacent, try the next
        }
    }
    // If we get to the end and find nothing mergeable, exit.
    if (empty($merge))
        break;
    list($i, $j) = $merge;
    // We add $j to $i
    $data[$i]['last_year'] = $data[$j]['last_year']
    $data[$i]['total_years'] += $data[$j]['total_years']
    // We destroy $j
    unset($data[$j]);
    // Dirty renumber
    $data = array_values($data);
    // Now data has been modified, let's do this again.
}


Redis + Lua. Can I return result without storing it in memory?

Question: I have the following Lua script executed in Redis environment:
<code>    local result = {}
    local comment_ids = redis.call('smembers', 'comment:all')
    for _, key in ipairs(comment_ids) do
        local comment_text = ...
        local article_name = ...
        local user_name = ...

        result[#result+1] = {article_name, user_name, comment_text}
    end
    return result
</code>
Basicly, what happens here is we fill 'result' table with some aggregated data (article_name, user_name, comment_text) and return it.
As far as I understand this table will be fully stored in memory until return statement.
My main question is, can I return data row by row, without storing full response in memory?
And also, is it appropriate to use Lua scripts for aggregation purposes? (Like I am trying to do it here).
Thanks.
Answer: No, you can not stream the result.
WRT the also - it is very appropriate.
Comment: Thanks for help! I've just started experimenting with Redis and Lua, so I don't know almost anything about common practises in this area,
Comment: Everybody starts sometime, and you seem to be on the right path.


Understanding a Proof in COMBINATORICA 3 ( 3 - 4 ) (1983) 325--329

Question: Preliminary words on notation:

$[n]$ denotes the set $\{1, 2, \ldots, n\}$.
For two vectors $x, y \in [k]^n$ we write $a(x, y) = h$ to denote that they agree on $h$ positions.
For some fixed $v \in [n]^k$ we denote by $g(v)$ the least amount of questions necessary to determine v if all questions are of the form "What is $a(v, q)$ for some question vector q?" and all questions are asked simultaneously.

In his proof on an upper bound on $g(v)$, Chvátal proposes the following sufficient condition on the amount of questions needed to determine $v$:

Proof. By a difference pattern, we shall mean a nonempty set $I$ of subscripts along with two distinct colors $x_i$, $y_i$ for each $i \in I$; we shall say that this difference pattern
  is split by a question $q$ if the number of subscripts $i \in I$ with $q_i \neq x_i$ differs from the number of subscripts $i \in I$ with $q_i \neq y_i$. Note that every two distinct candidates $x, y$ for the mystery vector $v$ define a unique difference pattern by $i \in I$ iff $x_i \neq y_i$, and
  that this difference pattern is split by a question q if and only if $a(q, x ) \neq a ( q , y)$. Thus we only need establish the existence of a set $Q$ of questions such that every difference pattern is split by some question in $Q$ ...

My two questions about this proof concern the two emphasized parts of the cited text:

Is the first assertion (i.e. ... if and only if $a(q, x ) \neq a ( q , y)$ ...) true? Consider for example $x = [0 \, 1]$, $y = [1 \, 0]$, $I = \{2\}$ and $q = [1 \, 1]$. Certainly, by definition, we see that the subvectors induced by $I$ are split by $q$ as $x_2 = q_2 \neq y_2$. On the other hand we have $a(q, x) = 1 = a(q, y)$. This seems to contradict the author's claim, what did I miss?
I flat out fail to grasp the second assertion: Why does splitting every difference pattern imply that the set of questions $Q$ suffices to recover $v$?
Comment: The wording of the author seems to suggest that this is about me missing some dead simple argument. Also about the bound: Sure, it works, but the one obtained by the author's line of thoughts is $\mathcal{O}(n / \log{n})$.
Comment: something which may help is the term "Hamming distance". But also, if you are proving an upper bound on $g(v)$, what's wrong with $[n]^k$ has $n^k$ elements, and so by asking all $n^k$ questions simultaneously, there will be one and only one vector $q$ which has $a(v,q)=k$, which determines the vector $v$.
Comment: that is indeed better than my bound, i thought you just wanted **a** bound.
Comment: Well the difficulty lies precisely in arguing how to combine the information from different guesses; each guess $q$ and the following information $a(v, q)$ reduce the ambiguity but how much is enough?
Comment: Careful with your variables: Chvátal's bound is $O(n / \log n)$ for vectors from $[k]^n$, assuming fixed $k$.
Comment: You're right of course, I should have added that I was about a fixed value of $k$.
Comment: Actually my main point in that comment was $[n]^k$ vs $[k]^n$.
Comment: Thank you for pointing that out. I have fixed the problem statement.
Answer:

Is the first assertion (i.e. ... if and only if $a(q, x ) \neq a ( q , y)$ ...) true? Consider for example $x = [0 \, 1]$, $y = [1 \,
> 0]$, $I = \{2\}$

No.

$x, y$ ... define a unique difference pattern by $i \in I$ iff $x_i \neq y_i$

If $x = [0 \, 1]$, $y = [1 \, 0]$ then $I = \{1, 2\}$.
The contributions to $a(q, x)$ and $a(q, y)$ of the indices not in $I$ are equal by definition of $I$.

I flat out fail to grasp the second assertion: Why does splitting every difference pattern imply that the set of questions $Q$ suffices
  to recover $v$?

Suppose you cannot recover $v$. Without loss of generality we can select two distinct candidates $u$ and $w$ which are compatible with the answers given to $Q$. But by definition of $Q$ it contains a question $q$ which splits the difference pattern of $u$ and $w$, so they cannot both be compatible with the answers given to $Q$. Therefore by contradiction there are not two distinct candidates for $v$.

As an aside, the thing which I see as an error is (my emphasis)

Note that every two distinct candidates $x, y$ for the mystery vector $v$ define a unique difference pattern by $i \in I$ iff $x_i \neq y_i$

This is trivially wrong, but it doesn't seem that the proof actually relies on it at all.
Comment: Dreadfully simple, as suspected.
I believe my "issue" with the first statement is somewhat similar to what you mention to be an error and has to do with a lack of clarity (at least to me) in the author's writing: It seems reasonable to think that the author is talking only about one direction, i.e., if $x_i \neq y_i$ for $i \in I$ then we get the desired (unique in the sense of "only one") difference pattern. On the other hand that pattern might of course results from various choices of $x$ and $y$ (i.e. unique not in the sense of bijections).
Comment: I did consider that interpretation of "*unique*", but in that case it's so obvious that $x, y, I$ completely define the difference pattern that it's completely superfluous. Ah well.


Checking work of C# String.Intern method through ProcessHacker

Question: I'm playing around with C# String.Intern method and have one questions. Suppose I have a program that reads a text file line by line and adds this lines to a list of strings. Let's assume that this file consists of thousands of lines of the same string. If the text file is big enough I can see that my program consumes decent amount of RAM. Then if I use String.Intern method when I add lines to my list, consumptions of memory drops significantly and this means that string interning works fine. Then I want to check how many strings my dotnet process has through ProcessHacker. But whether I use String.Intern or not ProcessHacker shows the same huge amount of duplicating string. I expect it would show only one instance of the string since I use String.Intern.
What do I miss?

static void Main(string[] args)
    {
        List<string> list = new List<string>();
        string filePath = @"C:\Users\User\Desktop\1.txt";

        using (var fileStream = File.OpenRead(filePath))
        {
            using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
            {
                String line;
                while ((line = streamReader.ReadLine()) != null)
                {
                    list.Add(line);
                    //list.Add(String.Intern(line));
                }
            }
        }
    }

Comment: *Do a GC.Collect();GC.WaitForPendingFinalizers();GC.Collect()* The *string*s have been generated before being interned.
Comment: "consumptions of memory drops significantly" - this probably means you have no idea what you are measuring and what you are looking for... Or you are not willing to properly spell out what you are measuring. There is no commonly agreed upon "memory consumption" term... There are a lot of different ways to measure different aspects of memory usage - like multiple variants of per-process memory usage, memory usage reported by GC,... I don't believe code shown here will change process level memory usage with/without interning for example as it had to allocate exactely the  same number of strings.
Answer: Every streamReader.ReadLine() will always create a new string which will be garbage collected but until GC it will exist in memory. Your memory consumption can drop cause String.Intern returns the system's reference to string, if it is interned; otherwise, a new reference to a string with the value of string and your list will consist from references to the same instance of string which was interned making the ones created by streamReader.ReadLine() available for GC.
var str = "Test"; // compile time constant will be interned by default
var str1 = new string(str.ToArray()); // simulate reading string
Console.WriteLine(object.ReferenceEquals(str1, string.Intern(str1))); // prints false

Comment: I see you point - make sense. Also OP has tiny sample "thousands of lines of the same string" - there is very unlikely even  Gen0 collection to happen...
Comment: Why the number of allocated strings would be different with/without `Intern` call? There will be difference in alive objects, but I don't get why do you think there will be less allocations...
Comment: @AlexeiLevenkov TBH has never worked with PorcessHacker, so maybe this question is not correct, removed it. Yes, it seems my assumption is not very valid, based on screenshot OP has only 6k of strings which are not that big.


Converting an SPSS file to a SAS file?

Question: (I'm asking this question for a friend,  honest...)

Is there an easy way to convert from
  an SPSS file to a SAS file, which
  preserves the formats AND labels?
  Saving as a POR file gets me the
  labels (I think) but not the POR file.
  I tried to save to a SAS7dat file but
  it didn't work. Thanks,
Comment: I think you should change the title to reflect the concern with keeping the formats and labels. Actually saving the file in the other softwares format is trivial, keeping the labels and value labels is the hard part.
Comment: Invite your friend here!
Comment: I totally want to, but she's too busy writing academic articles.  In general, I wonder how many non-R statisticians we've got on the site.
Comment: Hi @TalGalili I mostly use SAS but also R
Answer: I would just suggest they make the syntax to relabel and reformat the variables. You can use the command, display dictionary. in PASW (aka SPSS) to output the dictionary in a table that you can copy and paste the variable names and labels. Looking at this example of making SAS labels it should be as simple as pasting the text in the appropriate place.
Formats may be slightly harder, but I could likely give a suggestion if pointed to a code sample of formats in SAS (if copy and paste from the display dictionary command won't suffice for value labels or data formats).
Comment: Looking at this document, http://support.sas.com/publishing/pubcat/chaps/59498.pdf, their also appears to be differences in definitions between SAS and SPSS that could cause confusion. Formats in SPSS appear to be referred to as informats in SAS. Value labels in SPSS appear to be referred to as formats in SAS.
Comment: Thank you for the suggestion Andy.  I forwarded it to my friend - and I hope she will find it useful.
Answer: SPSS writes SAS7dat format files normally with no problems.  When you it did not work, what actually happened?
Comment: I took the problem to not be actually writing a usable file, but to transporting the value labels to SAS. I don't have a copy of SAS handy to see if the export to SAS7dat files normally saves this or not.

Converting an SPSS file to a SAS file?


How would you explain logit coefficients to someone with no statistical background

Question: Similar question here.
The question I highlighted above provides an overview of how generalized linear models work. However, I find people often want more and ask about how the coefficients were calculated, and how the coefficients are then turned into odds-ratios or predicted probabilities.
So if I were explaining logit models to someone with no experience with statistical modeling, how would you explain the process of going from data to coefficients, and then on to odds ratios and/or predicted probabilities with as limited math as possible?

How does the model take data and produce specific coefficients?
How do we get useful information from these coefficients? It's
difficult to avoid math on this one, as it's important to
point out how the probability curve or odds ratios are calculated.

My question deals more with 1. than 2.
Comment: If I had only a short period (say an hour) to discuss something like this w/ an audience that has no statistical background, I simply wouldn't try to explain these things. I would just say something like, 'we believe $X_1$ is related to whether or not we get a success, but that $X_2$ isn't'. Even 'simple' concepts like what odds & odds ratios are, are pretty foreign to most people & take a while to come to grips w/ (e.g., see my answer here: [interpretation of simple predictions to odds ratios in logistic regression](http://stats.stackexchange.com/questions/34636//34638#34638)).
Answer: Like @gung I would avoid part 1 altogether. But I think the odds and odds ratio can be explained fairly simply. People are familiar with odds (from betting) and a ratio is a fraction. I wrote logistic regression on my blog, it is written for neophytes.
Answer: I've had some success at explaining logistic regression to educated non-statisticians by drawing the logistic curve, with the y-axis as probability from 0 to 1, and explaining how the coefficient indicates that marginal change in location along the S curve, which corresponds to a given probability.  It helps people understand that the model assumes that the coefficients are only additive on the logit scale, which is quite nonlinear and uses a different interpretation than, say, a linear probability model.  For example, a large coefficient (on a dummy variable for example) means less when the intercept is very large or small than it would if the intercept is near zero.


Change spring config server endpoint based on profile

Question: I have about 10 spring boot microservices which I am calling config clients. One another spring boot service is config server.
For dev environment all these 11 services run on localhost, config server specifically on port 8888.
Now in my staging environment (on AWS), the config server launches on a VM with IP say a.b.c.d:8888
To make this discoverable in all my other services bootstrap.yml is configured as:
spring:
  application:
    name: application-name

---

spring:
  profiles: staging
  cloud:
    config:
     uri: http://a.b.c.d:8888

The problem is that I have to hardcode the IP in 10 services here. Is there some way I can make this a central configuration.
All services are built using maven and do share a common parent pom if that relates to this.
PS:  is I want a central configuration for locating central config server :)
Comment: There is a feature that allows config server to found via discovery. http://projects.spring.io/spring-cloud/spring-cloud.html#eureka-first-bootstrap
Comment: True. You can either have config discovered from discovery server or discovery server found through config. Benefit of later is that even eureka server config can be committed to config repo and so I am using that.
Answer: The bootstrap.yml or bootstrap.properties are static to the best of my knowledge. It is loaded first and must know where the config server is located to get the rest of the properties for the application.
You just hit one issue about Microservices.  Code duplication.  Sometimes there is no way to avoid it.
Comment: How I solved this or say found a better way is that I configured a dns and gave a name mapping to my config server machine. I can at least change the IP now as long as I update the mapping. Thanks.


How can I change the way content titles are generate and displayed?

Question: I'm a total amateur working on the website for my community radio station via Drupal 7. (Here for reference) Each show on the station has their own content type called a Program Page, which displays, at the bottom of the page all the Program Playlists (a type of content) they have created by clicking a link on the Program Page and filling out the 'Create Program Playlist' form (http://www.cjsf.ca/node/add/station-playlist/685).
Currently these playlists are listed by an automatically-generated title that is just the date the episode aired (a field within the 'Create A Program Playlist' form), and we'd like to be able to assign custom titles to these playlists.
I can't for the life of me figure out how to do this. I've tried editing the content type for the Program Playlist but all I have there is an un-editable 'Title' field and I can't get much further than that.
Help!
Answer: If the title field is uneditable, that might have been done through another module or custom code (Automatic Entity Label?) that is setting the title text. I would edit the content type, and look down at the bottom and see if there are any content type settings that would be determining the title (not the "manage fields" page, but the main edit page for the content type). You might be able to re-enable editing.
https://www.sierraclub.org/admin/structure/types/manage/station_playlist (? not sure if this link is exactly right, a guess...)
A work around would be to add a custom field that is your custom title, and then edit your view(s) to use the custom title if it exists. (The short version of how to do that would be to make the regular title hidden, and then add the new field, and use the if empty setting to populate with the text from the title.)
But figuring out how the title field is made uneditable and fixing it from there would probably be best in the long run.


Find conditional expectation of two normally distributed variables given correlation coefficient

Question: $X \sim N(0,\sigma_x^2)$ and $Y \sim N(0, \sigma_y^2)$, $\rho(X,Y) = \rho$. Find E[X|Y].
Attempt to the solution:
Firstly, I tried to use that $cov(X,Y) = \rho_{XY}\sigma_x\sigma_y = cov(Y, E[X|Y])$, but I didnt manage to find something meaninful.
Then I tried to use the definition $E[X|Y]:=\int{  {{f_{XY}(x,y)}\over{_{Y}(y)}}}$, but I am struggling with finding the joint distribution of X and Y. What can I do?
Comment: I doubt if $E(X|Y)$ can be determined without assuming that joint distribution is normal.
Comment: The joint distribution may not be normal and my suspicion is that the problem is ill-posed.
Comment: but it may not be normal, as far as I understand. Am I right? I supposed that we can find joint distribution if we know basic distributions and correlation. It seems pretty plausible to me.
Comment: Are $X$ and $Y$ independent?
Comment: @EkeshKumar well, I think, no, if $\rho$ is not equal zero.
Comment: @KaboMurphy and if the joint distribution is normal, then we can just calculate it using an integral equation, which I have written previously?
Comment: There is not need to write down joint density. See my answer.
Answer: If $X$ and $Y$ are jointly normal then $cov (X-cY,Y)=0$ when $c=\frac {EXY} {EY^{2}}=\frac {\rho} {\sigma_y^{2}}$. This implies that $X-cY$ and $Y$ are independent (since they have a joint normal distribution). Hence $E(X|Y)=E(X-cY|Y)+cE(Y|Y)=0+cY=cY$.
Comment: Thank you, maybe it was supposed that they are jointly normal.


Alluvial plot vs. Sankey diagram

Question: Is there any difference between an Alluvial plot and a Sankey diagram? Are these two names for the same thing?
Answer: I'm not sure there's any consensus on this.
Wikipedia says that an alluvial diagram is a type of Sankey diagram "that uses the same kind of representation to depict how items re-group"
RAWGraphs likewise says:

Alluvial diagrams are a specific kind of Sankey diagrams: they use the same logic to show how the same set of items regroups according to different dimensions.

Azavea says:

A Sankey diagram visualizes the proportional flow between variables (or nodes) within a network. The term "alluvial diagram" is generally used interchangeably. However, some argue that an alluvial diagram visualizes the changes in the network over time as opposed to across different variables.

Datasmith says they "are profoundly different types of diagram":

Alluvial plot:

Shows how a population of facts is allocated across categorical dimensions.
Left/right position has no particular significance; dimensions could be in any order.
'Nodes' are lined up in columns.
Is useful for showing how features of a population are related — for example, answering questions like 'how many people have features A and B, compared to how many have B but not A?'

Sankey diagram:

Shows how quantities flow from one state to another.
Left/right position shows movement or change.
'Nodes' could be anywhere, and must be laid out by an algorithm.
Is useful for showing flows or processes where the amount, size, or population of something needs to be tracked — for example, answering questions like 'out of the energy in system A, how much came from systems B and C and where will most of it go?'

This seems opposite of the Azavea definition?
The Data Visualisation Catalogue Blog tries to distinguish between them:

Like with a Flow Chart, a Sankey Diagram can include cycles, which is
something that distinguishes them from Parallel Sets and Alluvial
Diagrams.

Also, the flow paths in a Sankey Diagram can combine or split apart at any stage of the system's process. Whereas on Parallel Sets and Alluvial Diagrams, you tend to get a group of flow paths only going from one side to the other.

Parallel Sets and Alluvial Diagrams aren't too different from one another.  However, the main difference between these two chart types is that Parallel Sets display a part-to-the-whole relationship, while Alluvial Diagrams only visualise quantities between dimensions.

Parallel Sets will have line-sets that are all uniform in length, while Alluvial Diagrams will have a lot more variation.

Alluvial plot vs. Sankey diagram


Tensor product in Paul r halmos book

Question:
This is the definition of tensor product in the book. But my question is
"Does for every $z\in \scr U \otimes \scr V$ there exists $x\in \scr U $ , $y\in \scr V$ such that $z = x\otimes y ?$"
Comment: There is a more inuitive approach to the [tensor product](https://kconrad.math.uconn.edu/blurbs/linmultialg/tensorprod.pdf), which actually constructs it, and then shows it satisfies a certain universal property, which is really what you're interested in anyway.
Answer: Of course no, the tensor product is the set of finite linear combnation of elements of the form $x \otimes y$. Read further in the book where the author established basis for the tensor product, which means the tensors are linear combinations of the basis elements. Elements of the form $x \otimes y$ are called simple tensors.

Tensor product in Paul r halmos book


Erro pra executar um map no JS: react-refresh-runtime.development.js:315 Uncaught TypeError: todo.map is not a function

Question: Estou usando o react junto com o firestore, e estou buscando os dados do db colocando dentro de todo, mas quando eu tento fazer um todo.map acontece esse erro dizendo que o todo.map não é uma função.
estou dando um console.log no getTodoList pra garantir que sim, está retornando um array do meu db...
import { useEffect, useState } from "react";
import "./App.css";
import { db, doc, getDocs, collection, addDoc, deleteDoc } from "./firebase";

function App() {
  const [todo, setTodo] = useState("");

  // Dar entrada em uma nova mercadoria
  async function newProduct(event) {
    event.preventDefault();
  }
  // Deletar uma Mercadoria
  async function deleteProduct(id) {
    const productDoc = doc(db, "toDo", id);
    await deleteDoc(productDoc);
  }

  // Buscar os dados dentro da coleção
  useEffect(() => {
    const toDoCollectionRef = collection(db, "toDo");
    const getTodoList = async () => {
      const data = await getDocs(toDoCollectionRef);
      const toDoList = data.docs.map((doc) => ({
        ...doc.data(),
        id: doc.id,
      }));
      setTodo(toDoList);
      console.log(toDoList);
    };
    getTodoList();
  }, []);

  return (

Lista de Mercadoria

      <form>
        <input type="text"></input>
        <button>Add</button>

          {todo.map((li) => {
            return
{li.todo}
;
          })}

      </form>

  );
}
export default App

Answer: Fala Luis,
Tente inicializar o todo com [] ao invés de "". Creio que esse erro aconteça porque uma string não contém o método map. A variável todo só se torna um array depois que os dados do banco são retornados, o que é um processo assíncrono. Antes que você tenha os dados, o react já tentou dar o render e por isso o erro acontece.
Comment: É isso mesmo, muito obrigado pela ajuda!
Comment: se puder votar como certa, fico agradecido (=
Comment: desculpa, aqui está dizendo que nao tenho reputação... só com 15 pontos


The problem when installing mongodb on MacOS

Question: I tried to install mongodb on my Mac. But the error message below appeared.
Someone please tell me the solution.
Updating Homebrew...
==> Installing mongodb-community from mongodb/brew
==> Downloading https://fastdl.mongodb.org/osx/mongodb-macos-x86_64-4.4.1.tgz
Already downloaded: /Users/t17akeru/Library/Caches/Homebrew/downloads/d46781539dca95a7ced7d9b466b13bd4cc0202f17a8bf4bd499a5e1a4a241262--mongodb-macos-x86_64-4.4.1.tgz
Error: Failed to install plist file
Warning: The post-install step did not complete successfully
You can try again using `brew postinstall mongodb/brew/mongodb-community`
==> Caveats
To have launchd start mongodb/brew/mongodb-community now and restart at login:
  brew services start mongodb/brew/mongodb-community
Or, if you don't want/need a background service you can just run:
  mongod --config /usr/local/etc/mongod.conf
==> Summary
  /usr/local/Cellar/mongodb-community/4.4.1: 11 files, 136.8MB, built in 4 seconds
==> `brew cleanup` has not been run in 30 days, running now...
Error: Permission denied @ apply2files - /usr/local/share/5.2/luarocks/add.lua

Answer: MongoDB was correctly installed. The problem is the installation of the plist file (which allows you to launch MongoDB when your computer starts, for example).
You can still run MongDB using mongod --config /usr/local/etc/mongod.conf.
Also, brew seems to have some permission problem. Here are some possible resolutions from this GitHub issue:
Reinstalling Brew
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Resetting permissions in /usr/local
sudo chown -R $(whoami):admin /usr/local/* \
&& sudo chmod -R g+rwx /usr/local/*

You can then try to run MongoDB's post-install script using brew postinstall mongodb/brew/mongodb-community
Hope it helped !
Comment: thank you for replying. but i could not do even "mongod --config /usr/local/etc/mongod.conf"

Error opening config file: Is a directory
try 'mongod --help' for more information


Example vector field with index $-2$

Question: I am looking at theory about vector fields in the plane and about their indices, I have found classic examples but I was wondering if anyone knows a plane vector field that behaves as follows:

Considering that the lines in the image start the plane in equal parts, I have managed to obtain that the index is $-2$, but I do not know which face this vector field has. If anyone has a reference to where I can find examples of vector fields that have indices $+2$, $+3$ or $-3$, $-4$, I would ask you to mention a reference. Thanks in advance.
Answer: Rather than writing down a formula, let me tell you how to write it down for yourself. The resulting vector field, with a singularity at the origin of index $1-n$, will be denoted $\vec v_n(x,y)$.
Here's the clue for deriving a formula for $\vec v_n(x,y)$: in complex coordinates, the $n$ inward rays pass through the $n^{\text{th}}$ roots of unity. I presume that you already have in your hands a formula for $\vec v_2(x,y)$, whose $2$ inward rays pass through the square roots of unity.
Consider the "function" of a complex variable given by $w = F(z) = z^{2/n}$; in fact one can choose any branch of this function defined on the complement of any ray, although as usual you'll need at least two branches to cover the whole complex plane.
Write this function in real coordinates $w = u+iv$, $z=x+iy$, obtaining
$$(u,v) = F(x,y) = (f(x,y),g(x,y))
$$
Compute its total derivative $D_{(x,y)} F$.
So, starting from a formula for $\vec v_2(x,y)$, for $(u,v) = F(x,y)$ we have
$$\vec v_n(u,v) = D_{(x,y)} F(\vec v_2(x,y))
$$
Again, I'll emphasize that one needs to use two well-defined functions $F$ to verify this computation, but in the end one will get a well-defined formula expressed in $(u,v)$ coordinates. A key feature of this computation is that the vector field, while continuous at $(0,0)$, is not smooth at $(0,0)$.
Comment: Wow how fast!!! Thank you very much, I see something complicated at first glance but I'll try it in a few moments. This method in which reference can I find it? Or was it a development of yours?
Comment: One learns about this in [Teichmuller theory](https://mathoverflow.net/questions/114787/what-is-teichmüller-theory-and-its-history), specifically when studying [quadratic differentials](https://en.wikipedia.org/wiki/Quadratic_differential), which I first studied when reading [FLP](https://press.princeton.edu/books/paperback/9780691147352/thurstons-work-on-surfaces-mn-48).

Example vector field with index $-2$