Como resolver problema com Add-Migration no VSCode?

Question: Bom dia!
Olá, Bom dia!
Estou aprendendo a utilizar o Vs Code. Para isso comecei por um exercício do curso sobre Entity Framework utilizando o método Code first. Estruturei todo o código seguindo os passos do curso e instalei as packages Microsoft. O problema surge quando tento utilizar o comando para adicionar migração. Abaixo segue o código:
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello gamers!");

        GamesDB games = new GamesDB();

        videogame novo = new videogame();

        novo.Title = "COF 2";
        novo.Plataform = "PS4";

        games.VideoGames.Add(novo);
        games.SaveChanges();

    }
}

 public class videogame
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Plataform { get; set; }

}

public class GamesDB : DbContext
{

    public DbSet<videogame> VideoGames { get; set;}

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("SERVER=(localdb)\\MSSQLLOCALDB; DATABASE=videogames; TRUSTED_CONNECTION=TRUE;"); //Atenção à dupla \ pois esse caracter é especial em C#!

    }
}

Aqui é a mensagem que o Vs code retorna quando tento adicionar a migração:
Comando: dotnet ef migrations add videogames

Could not execute because the specified command or file was not found.
Possible reasons for this include:
  * You misspelled a built-in dotnet command.
  * You intended to execute a .NET Core program, but dotnet-ef does not exist.
  * You intended to run a global tool, but a dotnet-prefixed executable with this name could not be found on the PATH.
 Testando %

Gostaria de saber se o erro está no comando que eu escrevi, ou se há uma package específica do Add-Migration...
Me ajudem, por favor. Tenho um projeto para desenvolver e não consigo avançar sem entender esta parte.
Desde já, muito obrigado!
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Tentar conferir string de conexão do "GamesDB" e remover o pacote tool e reinstalar e limpar a solução.
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: Como vai, Josias?! Obrigado à resposta! Tentei sua solução, entretanto sem sucesso.
Comment: Blz, e boa sorte na sua resolução do problema.


Sortable items MySQL Structure

Question: I have a list of items in a file table, which way is the most practical to sort records based on how the user has positioned them? There could be possibly hundreds of records per user. Perhaps there is a better way to do this and I've boxed my thinking in?
Option 1: I have a table with the order included. I can easily sort by the order column, however when I add a new field or re-order them on the front-end, I may have to update MANY records, *eg: If there are 50 files, changing file_id 1 to position 50, could renumber the order of every row in turn requiring 50 updates..*
table: file
file_id | name  | order
------------------------
1       | test  | 2
2       | other | 1

Option 2: Organize the file table based off an order table. This requires much more work and error checking, and it's a bit more difficult. Yet I would be updating one row with CSV values and transforming them into Arrays to sort the file column.
table: file
file_id | name
----------------------
1       | test
2       | other

table: order
file_order
----------------------
2,1

Answer: for option 1 you could use these SQL requests :
i added a field user_id to your file table
to make the 50th file as 3rd position:
UPDATE table SET order=3 WHERE id=50 AND user_id = xxx

UPDATE table SET order=order+1 WHERE id>3 AND id<50 AND user_id = xxx

to make the 3rd as 50th position:
UPDATE table SET order=50 WHERE id=3 AND user_id = xxx

UPDATE table SET order=order-1 WHERE id>3 AND id<50 AND user_id = xxx

Sortable items MySQL Structure


How to store image as URL in Laravel 8.*

Question: In my application I add photos that are then scaled, I call them to my views using {{asset()}}
Everything works fine, but for my mobile app I need to send to API URL of image instead of just image path called from db.
That's how I save images now:
        $image = $request->photo_patch;
        $filename = time() . '.' . $image->extension();
        $event->photo_patch = $filename;
        $image_resize = Image::make($image->getRealPath());
        $image_resize->resize(1200, 630);
        $image_resize->save('storage/images/' . ($filename));

        $event->save();

Example of saved image name:
1630531230.jpg

That's how I get image on view:
photo_patch) }}">

What I tried:
$url = Storage::url($filename);
        $event->photo_patch = $url;

After this file name looks like this
"/storage/1631043493.png"

But that isnt really URL
What can I do to save photo path like this:
"localhost/storage/images/1631043493.png"

Edit:
@ Фарид Ахмедов suggested to call whole URL in API.
How can I do that then?
This is what I tried:
Route::get('/events/{id}', function($id){

    return [
    Event::findOrFail($id),
    'image' => asset('storage/images/'.$this->photo_patch)
    ];
});

Answer: That's it.
url(Storage::url($filename));

But I think, you don't need to save the whole path. You can convert it to full URL before sending response.
Comment: So I would stick to code that i've got now and then in API I can convert it to full URL? How can I do that then?
Comment: Hmm... where you have a controller and a method that returns a URL, make a modification there. I didn't quite understand the question.
Comment: Line of code you added is the same that I did. But I was thinking about giving to api 'image' as URL (editied question, its at the bottom of it)
Comment: But this is all that is needed. `asset` helper already returns full URL, that you can use in mobile app as a link. If I understand correctly, you want to send an image, not a link. Then use `return response->file($path)`, that return Blob (binary format), and you can render image on client side.
Comment: I don't see a problem
Comment: Attached updated code is not correct, btw. `$this` is not defined


Is it possible to Swizzle NSAttributedString.init(string:attributes)?

Question: I am trying to swizzle NSAttributedString but getting a compile error:
extension NSAttribtuedString {

   @objc convenience init(swizzledString: String, attributes: [NSAttributedString.Key : Any?] {
       .....
   }
}

Error
Method cannot be marked @objc because type of parameter 2 cannot be represented in Objective C

The error makes sense. Any way we can solve this to keep the function signature and swizzle the init function?
Comment: why did you use `@objc` tag for convenience initializer?
Comment: @emrcftci because I need to swizzle it
Answer: You get the error, because swift's dictionary type does not exist in objective-c. You would have to use NSDictionary:
@objc convenience init(swizzledString:String, attributes:NSDictionary)


Tensorflow Feature Column for 0 and 1

Question: For Tensorflow feature columns contain boolean value 0 and 1.
Should I be using tf.feature_column.numeric_column
or tf.feature_column.categorical_column_with_vocabulary_list?
Comment: can you explain a bit what you want to do?
Answer: You can use sequence_categorical_column_with_identity :
tf.feature_column.sequence_categorical_column_with_identity('YOUR_FEATURE',2)

the second parameter is the number of buckets. If you have n consecutive integers [0,1,2 .. ,n-1] in your feature, you then write :
tf.feature_column.sequence_categorical_column_with_identity('YOUR_FEATURE',n)

Answer: I would recommend tf.feature_column.categorical_column_with_vocabulary_list.
I would think you would want to treat the data as categories, rather than as scalars.

Tensorflow Feature Column for 0 and 1


Three touching spheres in d dimensions

Question: There are two $d$-dimensional unit spheres centred at $A$ and $B$ in $\mathbb{R}^d$. They are touching at location $I$. How can I find the centre of a third $d$-dimensional unit sphere $C$ that touches the first two spheres? I know that:

|A-B|=|A-C|=|B-C|=2,
|A-I|=|B-I|=1.

I don't know how to proceed from here. I know there can be multiple locations for $C$. In fact the set of possible locations forms a $(d-1)$-sphere. But how to find its radius and centre?
Comment: @JeanMarie yes it is.
Comment: *Hint*: Reduce it to two circles touching in $\mathbb{R}^2$.
Comment: In 2 dimensions there are two locations for C and I know how to find them. But I don't know what to do in higher dimensions.
Comment: Is $d$ the dimension of ambient space $\mathbb R^d$ ?
Comment: Why the minus? :(
Answer: From the fact that
$$ \lvert A - B\rvert = \lvert A - C\rvert = \lvert B - C\rvert = 2 $$
you know that $A, B, C$ are vertices of an equilateral triangle of side $2$.
It doesn't matter how many dimensions you are working in, three non-collinear points still make the vertices of a triangle and if all three sides are equal then the triangle is equilateral.
Given that $\triangle ABC$ is an equilateral triangle of side $2$,
what is the relationship of $C$ to the midpoint of side $AB$?
The point $C$ must be on the perpendicular bisector of $AB$ at a distance $\sqrt3$ from $AB.$
Noting that $I$ is the midpoint of $AB,$ we have $CI = \sqrt3$ and $C$ lies on the $(d-1)$-plane through $I$ orthogonal to the line $AB,$
since that $(d-1)$-plane contains all lines through $I$ perpendicular to $AB$ and all lines through $I$ perpendicular to $AB$ are in that plane.
In summary, the sphere you are looking for has center $I$ and radius $\sqrt3$
and lies in the $(d-1)$-plane through $I$ orthogonal to $AB.$
Comment: OK, I see this is not a question that needs to be drawn out in hints, so I've finished describing the locus of $C.$ Anyway it just confirms what you already figured out.
Comment: I believe the midpoint of $AB$ is $I$ and $|C-I|=\sqrt 3$.
Comment: That's most of the information you need to construct the $(d-1)$-sphere.
Comment: I think I found the answer, but not sure if it is correct. I need to construct a $(d-1)$-plane between the spheres going through point $I$. The location of $C$ can be all points on that plane that have a distance of $\sqrt 3$ from $I$. In other words the intersection of the plane and a sphere. By the way, this is not a homework assignment as it may seem. In fact I am working on the kissing number problem.
Comment: Thank you David. I really appreciate your help.

Three touching spheres in d dimensions


Task based on Copy appears not to execute()

Question: I have the following code in my build.gradle file:
task untarServer(type:Copy) {
    from tarTree('build/libs/server.tar.gz')
    into project.ext.tomcat + '../'
} << {
    println 'Unpacked, waiting for tomcat to deploy wars ...'
    sleep 10000
}

task deploy << {
    tarball.execute()
    untarServer.execute()
    stopTomcat.execute()
    startTomcat.execute()
}

Everything works great except untarServer, which appears not to run at all. Untar is based on an example from the documentation. Probably I've done something silly due to the late hour, but I'm missing it. How can I fix this? I have in the back of my mind that I could drop down to using ant.untar, but I'd like to do it the native gradle way if possible.
Edit: How do I know it's not running? because the println statement never shows up, the buld does not pause for 10 seconds, and the contents of the tarball do not show up in the "into" location.
Answer: I haven't seen the } << { syntax before; I'd change it to doLast { ... } inside the curly braces or untarServer << { (as a separate statement). Also, you should never call execute() on a task. It's totally unsupported and bad things will happen. Instead you should establish a task relationship (dependsOn, mustRunAfter, finalizedBy).
Comment: `<<` is a short cut for doLast (http://www.gradle.org/docs/current/userguide/tutorial_using_tasks.html#N10222) I would love to not call execute, except it's the only way to actually make tasks happen in a unique order without changing their order for other operations. See discussion around http://issues.gradle.org/browse/GRADLE-427, and the confusing and also re-use inhibiting `mustRunAfter` http://www.gradle.org/docs/current/userguide/more_about_tasks.html#sec:ordering_tasks
Comment: I know what `<<` is. :-) Just saying that the way you apply it is unconventional (when I saw it, I wasn't even sure if it would work at all). I'm aware of the current limitations of task relationships, but it's nevertheless often possible to get around calling `execute()`. I'm pretty sure it's possible in this particular case. Anyway, even with your current code I'm fairly sure that `untarServer` will get executed (but not any dependencies it might have). You may be misinterpreting the effects that you are seeing.
Comment: It's definately not having the side effects desired. See my edit.
Comment: In that case, your best bet is to get rid of the `execute()`. I don't know any details about your build, but startTomcat-dependson-untarServer-dependsOn-tarball seems like a good start.


XNA Beginner: How do I merge arrays of vertices into a single vertex buffer

Question: I've just recently started using XNA and now I face a beginners problem, performance. The objects I draw has their own vertex buffer, so when I have ~50k objects, the fps goes down dramatically (from 60 to 5-12).
I got the tip that I should merge my vertices into chunks, but I don't know how to do that..
Would appreciate any help I can get with code examples.
Edit: This is the code I came up with, with help from Blau
var cubes = newChunk.Where(c => c != null && !badIndex.Contains(c.BlockType));
VertexPositionColorTextureNormal[] verts = new VertexPositionColorTextureNormal[cubes.Sum(c => c.Vertices.Count)];
int VertexOffset = 0;
var inTheRightOrder = cubes;
foreach (var cube in inTheRightOrder)
{
    var cb = cube.Vertices.ToArray();
    for (int v = 0; v < cb.Length; v++)
    {
        verts[VertexOffset + v] = cb[v];
    }

    VertexOffset += cb.Length;
}
VertexBuffer newVB = new VertexBuffer(device, VertexPositionColorTextureNormal.VertexDeclaration, verts.Length, BufferUsage.WriteOnly);
newVB.SetData(verts);
var ck = new Cube { Vertices = verts, BoundingBox = BoundingBox.CreateFromPoints(verts.Select(i => i.Position)), Buffer = newVB, Cubes = cubes.Count() };
Cubes.Add(ck);

Comment: 50.000 objects? maybe you need to clip objects before draw...
Comment: The objects are made with only visible vertices, so if a cube is only visible from the top, only the top vertices are made.
Answer: To merge them you have to something similar to this.
int NumVerts = Objects.Sum(o => o.Vertex.Length);
int NumIndexes = Objects.Sum(o => o.Index.Length);

VertexPositionColor[] Vertex = new VertexPositionColor[NumVerts];
int[] Index = new int[NumIndexes];

int VertexOffset = 0;
int IndexOffset = 0;
foreach (Object object in Objects)
{
    for (int v=0; v<object.Vertex.Length; v++)
    {
        Vertex[VertexOffset+v] = object.Vertex[v] + VertexOffset;
    }

    for (int i=0; i<object.Index.Length; i++)
    {
        Index[IndexOffset+i] = object.Index[i] + VertexOffset;
    }

    VertexOffset += object.Vertex.Length;
    IdnexOffset += object.Index.Length;
}

Comment: Thank you, this meant a lot to me, now I just gotta split all transparent blocks, so I draw them after all other blocks have rendered.


Likert item results reporting from Likert index

Question: I have a likert scale developed from a pilot survey, an EFA, and Cronbach's alpha.  The survey questions are on an agree/disagree 5-point scale.
We are reporting the index score - calculated as the average individual-item mean of the 6-item index for each participant, so an average of averages.
However, I also want to inform my stakeholders on how to improve their index score.  Would the most helpful form of reporting at the individual item-level for the index be: the mean of each individual item, a distribution of responses for each item, a distribution of score groupings to show the percent top-box and the percent bottom-box, a median, a mode?
What is the reasoning?
Results reporting example image attached.
Answer: Importance of sample size. Crucially, you do not reveal your sample sizes. Proportions and
averages can be quite meaningless without them. As an extreme example,
4 heads in 10 tosses of a coin is hardly evidence of a biased coin,
but 400 heads in 1000 tosses is pretty good evidence of bias.
Simulated data for illustration. Here is an experiment with simulated data with two groups of 1000
subjects each. Specifically, let's look at a 2-sample t test of
differences in 'average' Likert scores and a 2-sample test whether
two proportions in favor differ significantly.
Here are two groups of Likert scores sampled from
somewhat different populations.
set.seed(2020)
x1 = sample(1:5, 1000, rep=T, p=c(4,6,20,40,30))
x2 = sample(1:5, 1000, rep=T, p=c(5,5,15,30,45))

Pretending that Likert scores are numerical, we get a mean of 3.9
in one group of 1000 and and a mean of 4.1 in a second group of 1000.
summary(x1); sd(x1)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
    1.0     3.0     4.0     3.9     5.0     5.0
[1] 1.042635  # sample SD

summary(x2); sd(x2)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  1.000   4.000   4.000   4.064   5.000   5.000
[1] 1.11855  # sample SD

Proportions in the two 'favorable' categories are about 72% and 76%,
respectively.
n1 = sum(x1 > 3); n2 = sum(x2 > 3)
n1; n2
[1] 717
[1] 758

Welch t test. A Welch 2-sample t test (which does not assume equal variances in the
two populations) to test whether the two sample means differ significantly
shows a highly significant difference (P-value about $0.001 << 0.05).$
t.test(x ~ g)

        Welch Two Sample t-test

data:  x by g
t = -3.3916, df = 1988.2, p-value = 0.0007086
alternative hypothesis:
   true difference in means is not equal to 0
95 percent confidence interval:
 -0.25883252 -0.06916748
sample estimates:
mean in group 1 mean in group 2
          3.900           4.064

Test of binomial proportions. A test whether the two proportions 'in favor' differ significantly (P-value
$0.037 < 0.05).$ [With samples as large as these, no continuity correction is needed. The test assumes binomial proportions are approximately normally distributed, which they are for samples as large as 1000.]
prop.test(c(n1,n2),c(1000,1000), cor=F)

        2-sample test for equality of proportions
        without continuity correction

data:  c(n1, n2) out of c(1000, 1000)
X-squared = 4.3416, df = 1, p-value = 0.03719
alternative hypothesis: two.sided
95 percent confidence interval:
 -0.079524487 -0.002475513
sample estimates:
prop 1 prop 2
 0.717  0.758

Which interpretation of data is best in your situation? So, for my simulated data, looking at Likert means seems to give very
strong evidence that the two groups differ and looking at proportions
'in favor' gives significance at the 5% level.
Do Likert data reliably behave as interval data? You may be surprised that I strongly prefer looking at the proportions
'in favor'. These proportions are unquestionable and direct results
of the ordinal Likert responses. By contrast, the 'means' require interpretation of the Likert scores as if they were numbers, which they
are not. They are ordinal categories. Whether two 'in favor' precisely
balances one 'strongly opposed' can be a topic of controversial discussion.
Over the long run, I think one does better to analyze exactly what
the data say, rather than what they may confess to after coercion.
Wilcoxon signed-rank test. I am not saying that looking at proportions 'in favor' is the very best way for you to look at your data.
A 2-sample nonparametric Wilcoxon rank sum test treats the data
as ordinal categories. Roughly speaking, it may be taken as a test whether
scores in one group may be 'shifted' relative to those in the other group.
(Some people take this as a test whether the two sample medians are
significantly different. For some data this is OK.)
Originally, the Wilcoxon test was not formulated
for use with data having many ties (as yours do), but for large samples, the version of this test in R
accommodates to ties without error messages. The (highly significant) results of this test are shown below. I think it may make good sense
to use results of the Wilcoxon rank sum test because the test treats
the data as the categorical categories they actually are.
This test asks and answers a different question than does the test of
proportions. The issue is which question is an appropriate one for your
data.
wilcox.test(x ~ g, cor=F)

        Wilcoxon rank sum test

data:  x by g
W = 439580, p-value = 7.483e-07
alternative hypothesis:
  true location shift is not equal to 0


Similarity between two sets of random values

Question: I have two sets of random floats between [0,1], each one with a different number of elements:
$$A = \{0.3637852, 0.2330702, 0.1683102, 0.2127219, 0.0152532, ..., N_A\}$$
$$B = \{0.4541056, 0.7521812, 0.0266602, 0.5099002, 0.3468181, ..., N_B\}$$
where $N_B > N_A$.
I need to asses the similarity between these two sets disregarding the difference in number of elements (ie: the fact that $N_B > N_A$ should not play a role in the similarity assesment) since I'm only interested in how the values are scattered between [0,1], not how many of them there are in each set.
So far I've applied the 1D kde.test available in Duong's R package 'ks' (see page 27) which returns a p-value, and I've also applied the python function scipy.stats.ks_2samp which is a 1D Kolmogorov-Smirnov statistic which returns a "KS statistic" and a "two-tailed p-value".
My questions are:
1- Is one of these statistics (KDE's p-value, KS statistic or the two-tailed p-value) recommended for my needs? If so, why?
2- What is the difference between the "KS statistic" and a "two-tailed p-value"?
3- Will the difference in the number of elements in each set affect the outcome of these statistics? If so, how can I avoid that? Is it even possible?
Comment: Have you considered a [Q-Q plot](http://en.wikipedia.org/wiki/Q%E2%80%93Q_plot)? It will truly help you *assess* the similarity rather than merely testing the hypothesis that they are drawn from the same distribution.
Comment: First time I've heard of a Q-Q plot. Does it give you a _number_ quantifying the assessment? Because I really need one.
Comment: It does far better than a single number: it produces a graph showing how the datasets differ in detail.  From this graph a whole host of numbers can be produced, depending on *how* you wish to measure the dissimilarity of the datasets.
Comment: @whuber please see http://stats.stackexchange.com/questions/77907/generate-q-q-plot-for-sets-of-different-size, I'm a bit lost. Thank you.
Answer:
1- Is one of these statistics (KDE's p-value, KS statistic or the two-tailed p-value) recommended for my needs? If so, why?

Your needs as expressed do not seem to be sufficiently clearly defined as to differentiate between them. They both test for a difference in distribution.

2- What is the difference between the "KS statistic" and a "two-tailed p-value"?

The two sample Kolmogorov-Smirnov statistic is the largest difference in ECDFs for the two samples:

(The data here is the same data I generated for your other question. Here the A sample is red and the B sample is blue.)
The height difference in ECDFs at x=35 is 1/6 or about 0.1667 (indeed anywhere in $[34.50717,35.32252)$ ), the same as the value produced by calculating the statistic:
> ks.test(A,B)

        Two-sample Kolmogorov-Smirnov test

data:  A and B
D = 0.1667, p-value = 0.6228
alternative hypothesis: two-sided

The meaning of the p-value is as for any hypothesis test - the probability of obtaining a statistic at least as unusual (in this case, at least as large) if the null hypothesis were true.

3- Will the difference in the number of elements in each set affect the outcome of these statistics?

No, the KS test, and (to my understanding) the KDE-based one both handle different sample sizes.
Here's approximate data values, in case anyone needs them
> print(A,d=3)
 [1] 41.34 25.92 55.30 50.06 75.67  3.03 61.81 34.51 34.33  9.62 94.95 24.73
[13] 30.41 11.77 25.13 90.75 12.62 36.14 56.91 29.76 15.34 62.58 33.03 36.44
[25] 47.90 66.01 42.49 18.21 31.58 58.30 17.63 70.81 73.86 46.63 10.24 12.02
[37] 47.14 15.56 80.27 12.76 33.61 52.08 41.64 13.19 32.96 64.21 81.15 32.37
[49] 33.79 40.43
> print(B,d=3)
 [1] 39.43 57.93 72.91 12.81  3.76 39.02 56.02 40.28 30.25 75.31  2.46 81.44
[13] 11.74  9.32 60.85 75.39 44.58 62.05 53.33 63.63 29.90 31.41 59.82 50.37
[25] 41.17 49.49 20.34 35.32 33.82 35.47
>

All that said, I recommend you consider whuber's words most carefully. There's a lot of good advice packed into very few words.
Comment: Thank you very much @Glen_b, I'll certainly consider whuber's comment.


Try-except, IndexError, Alternativas para solucionar o erro

Question: Estou com um trabalho da faculdade pra fazer, de certo modo eu terminei ele, mas com umas gambiarras que queria ajeitar e deixar o código menos confuso e etc.
Funcionamento do programa:
Basicamente ele cria uma tela 600x400 com um x número de bolas (esse número é passado por parâmetro da função de cria as bolas) andando pela janela, quando batem nas bordas elas tomam outra trajetória de forma que sempre fiquem na tela.
Explicação das funções:

criaBola: Coloca as informações como tag, x, y e aceleração vertical/horizontal;
criaBolas: Quando o programa é iniciado ele espalha as bolas aleatoriamente pela tela, ao longo do programa essa função é usado para fazer as bolas andarem pela tela;
verificaBolasArea: Verifica se onde foi clicado com o mouse existe uma bola, se existir retorna o index da lista;
removeBola: Apaga a bola da tela, essa função é usada tanto pra fazer as bolas andarem tanto para 'estourar' elas;
moveBola: Esse é o coração do programa, faz as bolas mudarem de direção, passa os index da lista pras demais funções, etc;

Parte que eu preciso de ajuda:
Na função moveBola eu precisei colocar um try-except para IndexError, o que acontecia é quando eu iniciava o programa tudo funcionava perfeitamente, eu clicava em algumas bolas e elas iam estourando como previsto, mas sempre que chegava na última bola o programa dava erro "IndexError: list index out of range"; esse erro também acontecia vez ou outra com as outras bolas sem ser a última. Esse foi o único jeito que eu consegui fazer o programa rodar sem dar erro, mas queria saber se há mais alternativas de como solucionar esse tipo de problema.
from Tkinter import *
import random, time

largura = 600
altura = 400
diametro = 50
bola = ['', 0, 0, 0, 0]
bolas = []

def randPos():
    pos = [0,0]
    pos[0] = random.randint(1, (largura - diametro))
    pos[1] = random.randint(1, (altura - diametro))
    return pos

def randCor():
    R = random.randint(100, 255)
    G = random.randint(100, 255)
    B = random.randint(100, 255)
    cor = '#%02x%02x%02x' % (R,G,B)
    return cor

def criaBola(id, novaBola):
    if novaBola == True:
        posr = randPos()
        bolas[id][1] = posr[0]
        bolas[id][2] = posr[1]
    tela.create_oval(bolas[id][1], bolas[id][2], bolas[id][1] + diametro, bolas[id][2] + diametro, fill=randCor(), tags=bolas[id][0])
    tela.update()
    print 'bola[index:{}]'.format(bolas.index(bolas[id])),bolas[id][0], randCor(), "POS: X:{} Y:{}".format(bolas[id][1], bolas[id][2])

def criaBolas(quantidade):
    for n in range(quantidade):
        print "CRIA BOLAS INDICE N ", n
        bola[0] = ('bola{}'.format(n))
        bola[3] = 10
        bola[4] = 10
        bolas.append(bola[:])
        print bolas
        criaBola(n, True)
    print(bolas)

def removeBola(idBolaList, idBolaTela):
    print "REMOVENDO BOLA[{}]".format(idBolaTela)
    print type(idBolaList)
    if idBolaList == 999:
        print 'REMOVENDO BOLA PARA ATUALIZACAO DE COORDENADAS'
    else:
        print "PRINTANDO BOLA A SER APAGADA IDBOLALIST", idBolaList, idBolaTela
        bolas.pop(idBolaList)
    tela.delete(idBolaTela)

t = Tk()
tela = Canvas(t, width=largura, height=altura)
tela.pack()

def verificaBolasArea(px1, py1):
    for ii in range(len(bolas)):
        if (bolas[ii][1] <= px1) and (px1 <= (bolas[ii][1]+diametro)) and (bolas[ii][2] <= py1) and (py1 <= (bolas[ii][2] + diametro)):
            print 'O mouse clicou dentro da bola\nA bola[{}] esta nas coordenadas ({},{}) - (X,Y)'.format(bolas[ii][0],bolas[ii][1], bolas[ii][2])
            r = [bolas.index(bolas[ii]), bolas[ii][0]]
            return r
        else:
            print 'bola nao encontrada'

def motion(event):
    print 'tamanho lista:',len(bolas)
    mx, my = event.x, event.y
    r = verificaBolasArea(mx, my)
    removeBola(r[0], r[1])
    print "--->uma bola foi removida", bolas
    print('{}, {}'.format(mx, my))
t.bind('<ButtonRelease-1>', motion)

def encerra(event):
    t.destroy()
t.bind('<ButtonRelease-3>', encerra)

def attPos(id):
    print "ATTPOS ID PASSADO ",id, bolas[id][0]
    print bolas
    bolas[id][1] += bolas[id][3]
    bolas[id][2] += bolas[id][4]

def moveBola(idBola = []):
    i=0
    while i>-1:
        try:
            while i<=len(bolas):
                print "WHILE I MOVE BOLAS:" ,i
                index = idBola.index(idBola[i])
                if ((bolas[i][1]+diametro) > largura) or (bolas[i][1] < 0):
                    bolas[i][3] *= -1
                if ((bolas[i][2]+diametro) > altura) or (bolas[i][2] < 0):
                    bolas[i][4] *= -1
                time.sleep(0.0299)
                tela.update()
                print "******************",index
                print len(bolas), bolas, index
                removeBola(999, idBola[i][0])
                attPos(index)
                criaBola(index, False)
                i+=1
                if i == len(bolas):
                    i=0
        except IndexError:
            if len(bolas) <= 0:
                i=-1
                tela.create_text(largura / 2, altura /2, text="PARANBENS! VOCE ESTOUROU TODAS AS BOLAS.\nClique com o botao direito do mouse para fechar o programa.", font=("Arial Black", "12"), tags='Fim', fill='red')
            else:
                i=0
            print len(bolas)*100

criaBolas(10)
moveBola(bolas)

t.mainloop()

Comment: Não precisa dizer que é trabalho da faculdade, isso não ajuda em nada. Vá direto ao ponto.
Answer: O len retorna um valor que começa a partir do 1, e não do 0. Porém, a contagem das posições começa a partir do 0.
while i<=len(bolas):

Vamos supor que o len(bolas) é igual a 10:
As posições das bolas são de 0 à 9, o que fecha 10 números (valor de len), o i começa em 0 e vai até 10 (pois while i<=len(bolas)), porém, o array não vai até a posição 10, e sim até a 9.
Creio que trocar while i<=len(bolas): por while i<len(bolas): irá resolver seu problema, não necessitando assim de try/except.


Problem with lyrics and horizontal alignment of notes in measure

Question: If I have this code :
\version "2.18.2"
\language "italiano"

solistsMelody =
  \relative do'' {
    \time 2/4
    \repeat volta 2 {
    %en las alturas
    <mi, la>8 <mi la>8 si'4\rest
    %paz a los hombres que ama el senor
    si4\rest <mi, mi'>16 <mi mi'>8 <re re'>16 <do do'>8 <la la'>8
    \tuplet 3/2 {<re re'>8 <si si'>8 <sol sol'>8}
    \bar "||"}

    \alternative {
        {<la la'>4 si'4\rest}
        {<la, la'>4 do'8 do8}
      }
    }

solistsWords =
  \lyricmode {
    hom -- bres
      paz a los hom  -- bres que~a -- ma~el -- se -- ñor Te~a -- la --
  }

womenMelody =
  \relative do' {
    \time 2/4
    \repeat volta 2 {
      si'4\rest
      <<
        { \voiceOne mi16 mi8 re16 do8 la8 mi'4 ~ mi4 }
        \new Voice {
          \voiceTwo fa,4 ~ fa4 la4 ~ la4 }
      >> \oneVoice
      <fa sol>4 (
    }
    \alternative {
      { <mi la>4) <mi la>8 <mi la>8 }
      { <mi la>4 si4\rest }
    }
  }

womenWords =
  \lyricmode {
               paz a los hom -- bres paz __
               Ah __ Glo -- ria~a ah
             }

menMelody =
  \relative do' {
    \clef bass

    \time 2/4

    \repeat volta 2 {
      % paz paz ah gloria a
      <<
        { re,4\rest <re do'>4 ~ <re do'>4 }
        \addlyrics { paz __ }
      >>
      <re do'>4 ~ <re do'>4 <sol, re'>4 (
    }
    \alternative {
      { <la mi>4) <mi la>8 <mi la>8 }
      { <mi la>4 <mi la>8 <mi la>8 }
    }
  }

\score {
  \new ChoirStaff <<

    \new Staff = "solists" \with {
      instrumentName = #"Solist "
    }
    <<
      \new Voice = "solists" {
        \voiceOne
        \solistsMelody
      }
    >>

    \new Lyrics = "solists"

    \context Lyrics = "solists" {
      \lyricsto "solists" {
        \solistsWords
      }
    }

    \new Staff {
      \new Voice = "women" {
        \womenMelody
      }
    }

    \new Lyrics = "women"

    \new Staff {
      \new Voice = "men" {
        \menMelody
      }
    }

    \context Lyrics = "women" {
      \lyricsto "women" {
        \womenWords
      }
    }
  >>

}

As you can see, after paz a los hombres for the women, the la mi for women and re do for men should be aligned horizontally (because the lyrics are in common here)
So, I wanted to do a minimum example taking off the soloist voice and here's what I got :

It's even worse, the re do for men has shifted to the next measure.
Answer: I don't have this problem on 2.19.54, so you might try updating your LilyPond version to fix it.
With that said, I've spotted the culprit in 2.18.2: if you comment out \addlyrics { paz __ }, the music aligns correctly. As such, I recommend using lyricmode for menMelody like you do for the soloists and women; this should clear up the problem.
Comment: Yep, I noticed the thing about the lyrics but my problem is, in the rest of the score, the men voices have the same lyrics as the women so I don't want to create a `lyricmode` for them (well, I could if I knew how to explicitly append the start of the lyrics to a precise note).
Comment: Thanks for the update tip. I don't like unstable versions that much, usually, but well, it works so... ;-)


FPGA measure accurate times

Question: We are checking how fast is an algorithm running at the FPGA vs Normal Quad x86 computer.
Now at the x86 we run the algorithm lots of times, and take a median in order to eliminate OS overhead, also this "cleans" the curve from errors.
Thats not the problem.
The measure in the FPGA algorithm is in cycles and then take the cycles to time, with the FSMD is trivial to count cycles anyway...
We think that count cycles is too "pure" measure, and this could be done theoretically and dont need to make a real measure or running the algorithm in the real FPGA.
I want to know is there exist a paper or some idea, to do a real time measure.
Answer: If you are trying to establish that your FPGA implementation is competitive or superior, and therefore might be useful in the real world, then I encourage you to compare ** wall clock times ** on the multiprocessor vs. the FPGA implementation.  That will also help ensure you do not overlook performance effects beyond the FSM + datapath (such as I/O delays).
I agree that reporting cycle counts only is not representative because the FPGA cycle time can be 10X that of off the shelf commodity microprocessors.
Now for some additional unsolicited advice.  I have been to numerous FCCM conferences, and similar, and I have heard many dozens of FPGA implementation vs. CPU implementation performance comparison papers.  All too often, a paper compares a custom FPGA implementation that took months, vs. a CPU+software implementation wherein the engineer just took the benchmark source code off the shelf, compiled it, and ran it in one afternoon.  I do not find such presentations particularly compelling.
A fair comparison would evaluate a software implementation that uses best practices, best available libraries (e.g. Intel MKL or IPP), that used multithreading across multiple cores, that used vector SIMD (e.g. SSE, AVX, ...) instead of scalar computation, that used tools like profilers to eliminate easily fixed waste and like Vtune to understand and tune the cache+memory hierarchy.  Also please be sure to report the actual amount of engineering time spent on the FPGA vs. the software implementations.
More free advice: In these energy focused times where results/joule may trump results/second, consider also reporting the energy efficiency of your implementations.
More free advice: to get most repeatable times on the "quad x86" be sure to quiesce the machine, shut down background processors, daemons, services, etc., disconnect the network.
Happy hacking!

FPGA measure accurate times


getting response but not getting key value while calling get api in flutter ,some rendering issue till i seached for the same

Question: {success: true}
E/flutter (16591): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter (16591): Receiver: null
E/flutter (16591): Tried calling:
Future _onSubmitClick(String ifscdataa) async{
//String profile = url+ifscdataa;
final uri = url+ifscdataa;

paramsToken = widget._token;

final headers = {
  'Content-Type': 'application/x-www-form-urlencoded',
  'X-Requested-With': 'XMLHttpRequest',
  //'Authorization': 'Bearer $paramsToken',
  'Authorization': widget._token,
};

print('Bearer $paramsToken');

Response response = await get(
  uri,
  headers: headers,
);
var res = json.decode(response.body);
print(res);

if (response.statusCode == 200) {
  setState(() {
    bank_name = res['data']['BankName'].toString() ?? "";
    distrcit_name = res['data']['DistrictName'] ?? "";
    branch_name = res['data']['BranchName'] ?? "";
    state_name = res['data']['StateName'] ?? "";

    print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>$distrcit_name');
    print(bank_name);

  });

} else if (response.statusCode == 401) {
  Fluttertoast.showToast(msg: res['message'], timeInSecForIos: 3);

} else {
  Fluttertoast.showToast(msg: res['message'], timeInSecForIos: 3);
}

}
Comment: it is helpful to attach your code along with question
Comment: this is my response from api -{
    "success": true,
    "data": {
        "BankName": "///// BANK OF ////",
        "StateName": "Rajasthan",
        "DistrictName": "//// city",
        "BranchName": "//// /// ROAD, //// city"
    }
}
Comment: @SriDattaYalla please check i add my code
Comment: @nvoigt no not helpfull in my case
Comment: https://medium.com/@diegoveloper/flutter-widget-size-and-position-b0a9ffed9407 this solution relate to my case or not.?
Answer: I think error is raising here
bank_name = res['data']['BankName'].toString() ?? "";
distrcit_name = res['data']['DistrictName'] ?? "";
branch_name = res['data']['BranchName'] ?? "";
state_name = res['data']['StateName'] ?? "";

Instead of accessing res['data'] directly, make a check that does it even exist in the first place
bool hasData = res['data']!=null;
if(hasData){
  bank_name = res['data']['BankName'].toString() ?? "";
  distrcit_name = res['data']['DistrictName'] ?? "";
  branch_name = res['data']['BranchName'] ?? "";
  state_name = res['data']['StateName'] ?? "";
}
else{
  bank_name = "";
  distrcit_name = "";
  branch_name = "";
  state_name = "";
}

Comment: ok i try this with updated one.
Comment: I've edited the answer, please try that
Comment: ok can you share in detail
Comment: have you tried above answer? now I've edited it match your need.
Comment: Tell me if that solved your issue
Comment: yes i tried its going in else condition.
Comment: tried tthis -  bool hasData = res['data']!=null;
        if(hasData){
         //now assign data
          bank_name = res['data']['BankName'].toString() ?? "";
        distrcit_name = res['data']['DistrictName'] ?? "";
        branch_name = res['data']['BranchName'] ?? "";
        state_name = res['data']['StateName'] ?? "";
        }
        else{
          bank_name = "daTAAA";
          distrcit_name = "null";
          branch_name = "null";
          state_name = "null";
        }
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/224140/discussion-between-s-j-and-sridatta-yalla).


You provided 'undefined' where a stream was expected. Error in HttpInterceptor

Question: I have seen and tried a lot of other threads describing the same issue, but couldn't find the solution. I am a beginner in angular technology. I am using angular 11. I am trying to refresh the JWT token in the HttpInterceptor class
this.loginService.checkRefreshToken(this.refreshtoke).pipe(
switchMap((tokenResponse: any) => {
          if (tokenResponse) {
            localStorage.setItem('authToken', tokenResponse.Token)
            localStorage.setItem('refreshToken', tokenResponse.RefreshToken)
            this.tokenSubject.next(tokenResponse);
            console.log('token refreshed');
            return next.handle(this.attachAuthToken(request));
          }
          else return <any>this.loginService.LogOutUser();
        })
      );

The above is my interceptor class calling login service
checkRefreshToken(data : Irefreshtoken) : Observable<any> {
        var body = JSON.stringify(data)
    const httpOptions = {
      headers: new HttpHeaders({
          'Content-Type': 'application/json',
          'Authorization': 'my-auth-token'
      }),

    };

    const postURL = this.constants.API_ENDPOINT + this.constants.CheckRefreshToken;

    return this.http.post<any>(postURL,data,httpOptions)
        .pipe(
            tap((result: any) => {
            localStorage.setItem('authToken', result.Token)
            localStorage.setItem('refreshToken', result.RefreshToken)
        })
    );

This is my login service function
[HttpPost]
        [Route("CheckRefreshToken")]
        public async Task<IActionResult> CheckRefreshToken(RefreshToken data)

This is my controller method
The post call is not hitting the back end and is always ending up with error
ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
    at subscribeTo (subscribeTo.js:27)
    at innerSubscribe (innerSubscribe.js:69)
    at CatchSubscriber.error (catchError.js:36)
    at XMLHttpRequest.onLoad (http.js:1700)
    at ZoneDelegate.invokeTask (zone-evergreen.js:402)
    at Object.onInvokeTask (core.js:28499)
    at ZoneDelegate.invokeTask (zone-evergreen.js:401)
    at Zone.runTask (zone-evergreen.js:174)
    at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:483)
    at invokeTask (zone-evergreen.js:1596)

I know that this is a general error in angular. Any help will be much appreciated. Correct me if I am wrong somewhere. These codes were copied from tutorial codes
Thanks for your help
Answer: You can remove the pipe in you checkRefreshToken and just return this.http.post<any>(postURL,data,httpOptions). The logic to save in the local storage is already done in the interceptor.


Finding the derivative of $x$ to the power something that is a function of $x$

Question: if $y = x^{(x+1)^\frac12}$
then how can I get the first derivative of $y$?
Comment: Write $y=\exp\bigl((x+1)^{1/2}\ln x\bigr)$ and use the chain rule.
Comment: Do you mean $(x^{(x+1)})^{(1/2)}$ or $x^{((x+1)^{1/2})}$?
Comment: @Ben I mean your second choice.
Answer: $$y=x^{(x+1)^{1/2}}=x^{\sqrt{x+1}}=e^{\sqrt{x+1}\log x}$$
and since
$$(\sqrt{x+1}\log x)'=\frac{\log x}{2\sqrt{x+1}}+\frac{\sqrt{x+1}}{x}=\frac{x\log x+2x+2}{2x\sqrt{x+1}}$$
we get, applying as suggested the chaing rule, that
$$y'=y\frac{x\log x+2x+2}{2x\sqrt{x+1}}=x^{\sqrt{x+1}}\cdot\frac{x\log x+2x+2}{2x\sqrt{x+1}}$$
Answer: Another way to solve it is to take $\ln$ of both sides, and apply implicit differentiation:
$$y=x^{(x+1)^{\frac {1}{2}}}$$
$$\ln y=\ln x^{(x+1)^{\frac {1}{2}}}$$
Rewriting using $\log$ properties:
$$\ln y=(x+1)^{\frac {1}{2}} \cdot \ln x$$
Now take the derivative implicitly:
$$\frac{1}{y}\cdot y' = \frac{1}{2}(x+1)^{-\frac{1}{2}} \ln x + (x+1)^{\frac {1}{2}} \cdot \frac{1}{x}$$
We want $y'$, so we multiply $y$ on both sides to isolate $y'$.
$$ y' = y \cdot \left( \frac{1}{2}(x+1)^{-\frac{1}{2}} \ln x + (x+1)^{\frac {1}{2}} \cdot \frac{1}{x} \right)$$
We want the right hand side to be in terms of $x$. The original problem says $y=x^{(x+1)^{\frac {1}{2}}}$, so
$$ y' = \big( x^{(x+1)^{\frac {1}{2}}} \big) \cdot \left( \frac{1}{2}(x+1)^{-\frac{1}{2}} \ln x + (x+1)^{\frac {1}{2}} \cdot \frac{1}{x} \right)$$
Answer: In general, if $y = x^{f(x)}$ then $y = (e^{\ln(x)})^{f(x)} = e^{f(x)\ln(x)}$
Now the derivative should be easy: $y' = e^{f(x)\ln(x)}\cdot \frac{d}{dx}(f(x)\ln(x))$, by the chain rule.
This simplifies. The first part turns back to the original expression: $y'=x^{f(x)}\cdot \frac{d}{dx} (f(x)\ln(x))$
Or, in other words, $y' = y\cdot(f'(x) \ln(x) + f(x)/x)$.


Am/C guitar chord help

Question: On this site http://jguitar.com/chordsearch?chordsearch=Am%2FC is said Am/C to be played like this:
X    O
------
||||O|
||OO||
|O||||
||||||
but in another tutorial site I saw this
X X  O
------
||||O|
|||O||
|O||||
||||||
Which is correct?
Comment: Both seem correct. The second one is missing an E, but it's not essential as there's another E present on the open ①.
Comment: @anatolyg You can strum the second one too, muting that string is not hard on that position.
Comment: If you want to strum, the first version seems much more appropriate (to the point that you could call the second one "incorrect")
Answer: Both are correct. Chords can be played in more than one way.
Am/C means "A minor with C as the lowest note".
A minor: A C E
A minor with C as the lowest note: C A E
The order of A and E doesn't matter on this case, as long as C is the lowest note in the chord. The number of As, Es, and Cs doesn't matter either, again, as long as C is the lowest note in the chord.
The notes on the first example are: C E A C E
The notes on the second example are: C A C E
Both are examples of Am/C. The second one has one less E, but it's still a Am/C chord. It still has A, E, and C; with C being the lowest note.
Which one to use? Whichever you want, whichever sounds better to you.
Comment: It's worth noting that pretty much every chord can be played in more than one way.
Answer: As JCP says, both are correct. However, one may suit you better to play, or to listen to, or to fit against a particular part of a melody. You'll find, as slim points out, many, many different VOICINGS of the same chord, particularly on guitar. The choice is yours. Context is important, as maybe is the moving from one chord fingering to another. One's ear is probably the best decision maker of all.

Am/C guitar chord help


Why can my view not access the data of a new node when using Rules event After saving new content?

Question: Using the Rules module and Drupal 7, I set up a rule "After saving new content of type X".
This is what I want to happen when adding a new content of type "X":

Based on its nid, call a view, which returns back a JSON, from where I fetch the info to work later. The info I need is on this view, not in the node I am inserting, but to get this view I need the nid and some other info from the node I am creating

The problem is that even if I get the nid of the new node, when I call the view it just returns an empty result. It seems like the data it's still not on Drupal database, so the view results empty. I tried to add a sleep(10) before calling the view, giving some time to Drupal, but no success.
The Content is published, and I added also a 'Save entity' Action to the Rule
Hope with this code here helps to understand; it's in Editing action "Execute custom PHP code", "After saving new content of type X"
dsm($node);  //I can see al attributes from the node I am inserting

$url="http://localhost/bopa/?q=export_cultivos/$node->nid";

dpm($url);

//it gives me a correct URL, that tested later directly on the browser, works
//If instead of $node->nid I use an existing nid, I get back results correctly, so the code below is correct

sleep(10);
$data=file_get_contents($url);

$data2 = json_decode($data,true);

dsm($data2);
//EMPTY array

Answer: IMO your "issue" (about "It seems like the data it's still not on Drupal database, so the view results empty") is because of the event (= "after saving new content") you are using, which might simply not be the right event.
Moreover, have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module  works ...).
A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component (eg X secs or mins "after saving that new user account" ... if your cron job runs frequent enough, if not it'll be next time cron runs). This compromise will ensure that at the time the Rules Component is executed, the content is for sure saved ... (so that can't be the reason anymore then why it would still be empty ...).
Answer: It sounds like a permissions problem with the view. Is $node->uid getting set properly?
Also, ensure the following:

The anonymous user has permission to the view that you're trying to access. Check this by using Privacy/Incognito mode in your browser.
Ensure the view can be seen by others.

On the View editing page, under Page Settings, there will be an item that says Access.
Ensure that it says None.
Note that even though the item says "Access" it is short for "Access Restrictions" and having it set to none simply means that it won't be disabled.

You may need to change the view to 'bypass access control' so that an anonymous user can see entries. To do this:

Go to the view you're editing and expand Advanced. (1)
Click on the link to access Query Settings. (2)
Disable SQL-rewriting.
Save your view and try again.


$b^x\leq(\frac{\ln(c)}{\ln(bc)})^2$

Question: Let $n$ be a natural number bigger than 2 and $b \in [\frac{1}{n},1]$ and $c \in [n+\frac{1}{n},n+1]$. Prove that for any positive real number $x$
$b^x\leq(\frac{\ln(c)}{\ln(bc)})^2$.
First I wrote $\ln(bc) = \ln(b)+\ln(c)$ and I tried doing some comparisons and I tried differentiating but I think the function is decreasing. I'm not fully sure the inequality is true so if it isn't please provide a counterexample.
I think I found a solution but I'm not sure it's right. Because $b \leq 1$, $b^x \leq 1$. And $\frac{\ln(c)}{\ln(b)+\ln(c)} \geq 1$ because $\ln(c) \geq \ln(2+\frac{1}{2}) > 0$ and $\ln(b) \leq \ln(1) = 0$. Equality is achieved when $b=1$.
Comment: Maybe turn your add-/edition into an answer.
Comment: Not sure what you deem a proof, but as you say clearly the LHS is $\leq 1$ for the given values of $b$ and $x$ while the RHS is clearly $\geq 1$.
Answer: $x>0$ so $b \leq 1$ implies $\ln(b)\leq 0$ and $b^x \leq 1$. But $(\frac{\ln(c)}{\ln(bc)})^2 = (\frac{\ln(c)}{\ln(b)+\ln(c)})^2$ and because $c \geq 2$, implying $\ln(c)>0$, $(\frac{\ln(c)}{\ln(b)+\ln(c)})^2 \geq 1 \geq b^x$. Equality is reached when $b=1$.

$b^x\leq(\frac{\ln(c)}{\ln(bc)})^2$


Delete white spaces on html5 video tag in Ionic

Question: I have a video tag in my Ionic app, video element is added after click on a button.
function addVideo(videoId){
        var path = $scope.getVideo(videoId).newVideoLocation.nativeURL;
        path = $sce.trustAsResourceUrl(path);

        var container = document.getElementById('videoContainer' + videoId);
        var video =  document.createElement('video');

        video.src = path;
        video.setAttribute('id', 'video' + videoId);
        video.setAttribute('poster', $scope.getVideo(videoId).thumbnailPath);
        video.setAttribute('width', '100%');

        container.appendChild(video);
    };

Video is added successfully but there are bottom and top white spaces / bars:

After click play button spaces are no longer there:

I set border to all elements to know what is happening. Blue border is video tag:

It could be margin o padding however I set them to 0:
* {
    border: 1px solid red !important;
  }

  video {
    border: 2px solid blue !important;
    margin: 0;
    padding: 0;
  }

Any idea what is the problem?
Comment: Have you tried to set `vertical-align:top`on `video`element
Comment: It might be size of poster, when you click poster is replaced with video
Answer: After a lot of research I found a solution.
I start understanding what happened after read HTML 5 Video stretch post:

Video content should be rendered inside the element's playback area
  such that the video content is shown centered in the playback area at
  the largest possible size that fits completely within it, with the
  video content's aspect ratio being preserved. Thus, if the aspect
  ratio of the playback area does not match the aspect ratio of the
  video, the video will be shown letterboxed or pillarboxed. Areas of
  the element's playback area that do not contain the video represent
  nothing.

Then in google books I found and explanation how works video width, the book is call The Definitive Guide to HTML5 Video
If width and height are not same aspect ratio as original video it doesn't work. Set a 100% to width doesn't mean you want video to fit the container. So I decided to calculate width and height of the container and set to video element:
function addVideo(videoId){
    var path = getTrustUrl($scope.getVideo(videoId).newVideoLocation.nativeURL);

    // Create container element and get padding
    var container = document.getElementById('videoContainer' + videoId);
    var paddingLeft = window.getComputedStyle(container, null).getPropertyValue('padding-left');
    var paddingRight = window.getComputedStyle(container, null).getPropertyValue('padding-right');

    // Get only numeric part and parse to integer
    paddingLeft = parseInt(paddingLeft.slice(0,-2));
    paddingRight = parseInt(paddingRight.slice(0,-2));

    //Get internal width of container and calculate height
    var width = container.offsetWidth - paddingLeft - paddingRight;
    var height = (width * 9 ) / 16; // TODO, if not 16:9 error

    // Create video element and set attributes
    var video =  document.createElement('video');
    video.src = path;
    video.setAttribute('id', 'video' + videoId);
    video.setAttribute('poster', $scope.getVideo(videoId).thumbnailPath);
    video.setAttribute('width', width);
    video.setAttribute('height', height);

    // Append video to container
    container.appendChild(video);
};

I don't see it straightforward... if someone know another solution let me know!


How do I put a taxonomy term on a panel page?

Question: I'd like to put several hand-picked taxonomy terms on a panels page, each term as a panels pane, showing their descriptions, with a more link to the term's view page, and maybe some of the fields that I have added.  Is there any module to do this?
Right now for each term I have to create a page, panelize it, add a view pane of the term to it, and then add the page to the panels I want them to show up. Seems to be working nicely enough but still too troublesome for ordinary editors to do it themselves.
Comment: I you want to clarify your question it would be better if you would edit it :)
Comment: I'm not sure if I understand exactly what you want to do, but perhaps a mini-panel, taking a taxonomy argument, would give you a re-usable component solving your problem?
Comment: It might.  Off to try it now.
Comment: Hmm. Not sure how to create a mini-panel that takes an argument.  If I add a required context, the mini-panel just won't show up in the "Add Content" dialogue.
Comment: Then the required context isn't available. :) What is the source of the terms? You need to add the term, either manually, a single term directly to the page, or map a url argument.
Answer:
Create a Page
Give it a %term argument and map it to a taxonomy term
Create a view pane that takes a taxonomy term as argument.
Create a mini panel that requires a taxonomy term argument.
Add the View to the mini panel. Configure it to use the taxonomy term.
Add the mini panel to the Page.
Answer: Are you confortable with custom coading?..If so here is an approach that might be friendly:

Create a Select field with simple yes/no option, to taxonomy term vocab (whose terms you want to be displayed in panels pane). lets call this "field_check". For each terms you want to be placed in panels, you will select yes, others will default to no.
In a custom module implement hook_block, to generate a block for all terms, which have the above field checked.

for example:
/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks = array();
  $vocab = taxonomy_vocabulary_machine_name_load('vocab_name');
  $vid = $vocab->vid;
  //get the taxonomy terms by vocab id
  $terms_array = taxonomy_get_tree($vid);
  foreach ($terms_array as $key => $voc) {
    if($voc->field_check['und'][0][value] == 'yes') {
      $blocks['term:' . $voc->tid]['info'] = $voc->name;
    }
  }
}

Also implement a corresponding hook_block_view().

This will create a separate block for each term you have chosen to be exposable to be added to panels. Now your content editor can just go in and add the blocks to the panels as panes.
Please remember the output will depend on the implementation of hook_block_view corresponding to each term you have exposed.

Hope this helps.
Comment: "separate block for each term" which is one of the reasons to absolutely not use blocks.


Particular solution of ordinary differential equation

Question: Solve the following initial value problem:
$$y'' + y = \sin x, \quad y = y(x).$$
I can't seem to find the particular solution. I have tried many times but it doesnt seem to work out.
I have tried:
$$ \begin{align}
y(x)&=A\, \cos {x}+B\, \sin{x} \\
y(x)&= A \, x^2  \, \sin{x}\\
y(x)&=A \, x \, e^{ix}
 \end{align}$$
but nothing seems to work out.
Comment: You can use the particular solution $y_p=\Im[kx\ e^{icx}]$ since one of two roots of the auxiliary equation is equal to $ic$. In this case $c=1$.
Comment: See [this](http://math.stackexchange.com/questions/768755/how-to-solve-y-y-2-sinx/768785#768785) answer.
Answer: Hint
Find a particular solution on the form $y(x)=axe^{ix},\;\; a\in\Bbb C$ of the differential equation
$$y''+y=e^{ix}$$and then take the imaginary part.
Edit
Substituting the particular solution in the differential equation  gives:
$$2iae^{ix}=e^{ix}$$
so we have $a=-\frac i2$ and then the imaginary part is $-\frac x2\cos x$ which 's a particular solution for the given differential equation.
Comment: this doesnt seem to work out for me?
Comment: Certainly it works even we can simplify by taking $b=0$.
Comment: i get 2aie^(ix)=sin(x)
Comment: No the second member of the differential equation is $e^{ix}$ so we have $2iae^{ix}=e^{ix}$ and then $a=-\frac i2$
Comment: sorry but im confused as to how you turned the sin(x) into e^ix
Comment: I edited my answer.
Comment: I changed the second member on the form $e^{ix}$ since we know the form of a particular solution if the second member is $P(x)e^{ax}$ where $P$ is a polynomial.@cf12418
Answer: You may use the method of variation of parameters. Since you know the solution of the homogenous part of the equation, i.e., $y(x) = A y_1 + B y_2$, with $y_1 = \cos{x} $ and $y_2 = \sin{x}$.  Assume then that the solution is given by:
$$y(x) = A(x) y_1,$$ for example (you might consider $y(x) = B(x) y_2$ or even $y(x) = A(x) y_1  + B(x) y_2 \ $!). Plug this information into the original equation to obtain:
$$ A'' y_1 + 2 A' y_1 + A y_1'' + A y_1 = \sin{x} \ \Rightarrow \  y_1 A'' + 2 y_1' A' + A \underbrace{(y_1 '' + y_1 )}_{=0} =  \sin{x}, $$ so we come up with an equation for $A$, provided that $y_1 \neq 0$:
$$ A'' + \frac{2 y_1'}{y_1} A' = \frac{\sin{x}}{y_1} \Rightarrow \frac{d}{dx}\left(y_1^2A' \right) = y_1 \sin{x}.$$ Solve now for $A(x)$ and do not forget about the constants of integration so, after further simplifications, you will obtain the solution of the original equation in the form:
$$y(x ) = \alpha \, y_1 + \beta\, y_2 + y_p, $$ where $y_p$ is your desired particular integral of the ODE and $\alpha$ and $\beta$ are constants.
Cheers!
Answer: $\newcommand{\+}{^{\dagger}}
 \newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\down}{\downarrow}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\isdiv}{\,\left.\right\vert\,}
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}
 \newcommand{\wt}[1]{\widetilde{#1}}$
With $\ds{y' \equiv z}$:
\begin{align}
{y'\choose z'} - \ic\
\overbrace{\pars{\begin{array}{cc}0 & -\ic\\ \ic & 0\end{array}}}
^{\ds{\color{#c00000}{\equiv A}}}\ {y \choose z}
={0 \choose \sin\pars{x}}
\quad\imp\quad\totald{}{x}\bracks{\expo{-\ic Ax}{y \choose z}}
=\expo{-\ic Ax}{0 \choose \sin\pars{x}}
\end{align}

$$
\expo{-\ic Ax}{{\rm y}\pars{x} \choose {\rm z}\pars{x}}
=\int\expo{-\ic Ax}{0 \choose \sin\pars{x}}\,\dd x + {\bf u}\,,\quad
{\bf u} = \mbox{constant vector.}
$$

Since $\ds{A^{2} = \mbox{identity}}$,
$\ds{\expo{-\ic Ax}=\cos\pars{x} -\ic\sin\pars{x}A
=\pars{\begin{array}{cc}\cos\pars{x} & -\sin\pars{x}\\ \sin\pars{x}&\cos\pars{x}\end{array}}}$

$$
\expo{-\ic Ax}{{\rm y}\pars{x} \choose {\rm z}\pars{x}}
=\int{-\sin^{2}\pars{x} \choose \sin\pars{2x}/2}\,\dd x + {\bf u}
={1 \over 4}{\sin\pars{2x} - 2x \choose -\cos\pars{2x}} + {\bf u}
$$

\begin{align}
{\rm y}\pars{x}&
={1 \over 4}\braces{\cos\pars{x}\bracks{\sin\pars{2x} - 2x} + \sin\pars{x}\cos\pars{2x}} + {\bf u}_{1}\cos\pars{x} - {\bf u}_{2}\sin\pars{x}
\end{align}

$$\color{#00f}{\large%
{\rm y}\pars{x}
={1 \over 4}\bracks{\sin\pars{3x} - 2x\cos\pars{2x}}
+{\bf u}_{1}\cos\pars{x}
- {\bf u}_{2}\sin\pars{x}}
$$
  $\ds{{\bf u}_{1}}$ and $\ds{{\bf u}_{2}}$ are constants to be determined by the 'initial conditions'.

$\large\tt\mbox{Another Simple Method:}$
Define $\ds{\xi \equiv y' + \ic y}$ such that $\ds{y'' + y = \xi' - \ic\xi}$
and $\ds{y = \Im\xi}$. In this way, we just have to solve a first order equation:
$$
\xi' - \ic\xi=\sin\pars{x}\quad\imp\totald{\pars{\expo{-\ic x}\xi}}{x}
= \expo{-\ic x}\sin\pars{x} = \half\ic\pars{\expo{-2\ic x} - 1}
$$


How to understand taking a simple sample to compute the Confidence Interval, using CLT?

Question: Suppose there is a population distribution having mean M and standard deviation SD. We want to estimate the Confidence Interval by using a single sample using CLT. We take a sample and compute it's mean(say SM) and standard deviation(say SSD). The distribution of Sample Means is normally distributed with a standard deviation close to SD/sqrt(n) where n is the sample size, and mean(say MSM) close to M.
We can understand this process in two ways:

That what we are trying to compute is the range MSM +/- 2SD/sqrt(n). This is what our Confidence Interval is.
Now:

We approximate(replace) MSM with SM.

SD and SSD are quite close, so SD/sqrt(n) can be written as SSD/sqrt(n).

Now, we can compute the Confidence Interval(MSM +/- 2SD/sqrt(n)), using the
sample mean and sample standard deviation.
But the problem with this understanding is that as a result of our process using CLT and a single sample, we can end up taking a sample having an exact mean of MSM + 2SD/sqrt(n) or MSM - 2SD/sqrt(n), with a 95% probability. In such cases, the Confidence Interval we will be computing are: MSM to MSM + 4SD/sqrt(n) or MSM - 4SD/sqrt(n) to MSM, which will be 50% off the confidence interval we were meant to calculate. So, how one solves this contradiction? The second way might have the answer.

That we assume MSM is actually quite close or same as M (Population Mean). Then we say that we have a 95% chance of taking out a single sample which has the mean within range MSM +/- 2SD/sqrt(n), in which case it will be 100% certain that our MSM(or Population Mean) is within 2SD/sqrt(n) of the SM (Sample Mean). In other words, there is a 95% chance of our Population Mean lying within 2SD/sqrt(n) of the SM. So, that is how it comes out to be our Confidence Interval.

But if the second approach is indeed correct, that would mean forgoing the idea that the distribution of Sample Means provides a Confidence Interval of the Population Mean(M) around it's mean(MSM). And will that be correct?
Thanks
Answer: So let's start by breaking down the formula for confidence intervals (CIs), Let's consider this in a little more generality then in your question. Let's say we want a confidence interval for an estimator of some parameter of the population, $\hat\theta$ (this could be the sample mean, or a regression coefficient, etc.). The population (true) parameter will be $\theta_0$. The CI is given by
$$[\hat\theta - c/\sqrt{n}, \hat\theta + c/\sqrt{n}]$$
$c$ is a critical value that we need to choose so that the CI will include $\theta_0$ with probability $1-\alpha$. This is our significance level. Setting $\alpha = 0.05$ is where you get that 95% figure. So what we want is that,
$$\Pr[\theta_0 \in [\hat\theta - c/\sqrt{n}, \hat\theta + c/\sqrt{n}]] = 1-\alpha$$
We can rewrite this probability as,
$$\Pr[\sqrt{n}|\hat\theta - \theta_0|\leq c]$$
This is easy to see just subtract out $\hat\theta$ from the upper and lower bounds and multiply by $\sqrt{n}$.
Now I am not sure how much statistics that you have but $\sqrt{n}|\hat\theta-\theta_0|$ is a very common expression. In many estimators, this will have an asymptotic distribution that can be proven to be normal using the CLT. Given this normal asymptotic distribution, we can use what we know about normal distributions to pick a $c$ in which we have $1-\alpha$ coverage.
To see this in action let's go back to your example of normal means. Let's let ${X_1, \dots, X_n}\sim N(\mu, \sigma^2)$ and iid. Let us assume both the mean and $\sigma^2$ are known for simplicity. Then $\hat\theta=\bar X_n$ or the sample mean. Then we have,
$$\Pr[\frac{|\bar X_n - \mu|}{\sigma \sqrt{n}}\leq c/\sigma] = \Pr[|Z|\leq \frac{c}{\sigma}]$$
To see that notice that all we did was divide by $n$ and $\sigma$ on both sides (noticing both are positive). Now we immediately know that $\frac{|\bar X_n - \mu|}{\sigma \sqrt{n}}$ is a z-score and is distributed normal and so we replace it with $Z\sim N(0,1)$. In other cases we will use the fact $\sqrt{n}{(\hat\theta-\theta)}\to^d N(0,V)$ to do the same thing.
Now that we are this far all we need to do is invert the test and determine what $c$ should be for our desired confidence value. That is we want to find $z_\alpha$ such that,
$$\Pr[Z\leq z_\alpha]=\alpha$$
To do this we need to look at the inverse of the normal pdf which is what you do when you look through a Z-table. Once we find this value we can set $c/\sigma=\sigma z_{1-\alpha/2}$ (two-sided stat). To get the confidence set,
$$[\bar X_n - \frac{\sigma}{\sqrt{n}}z_{1-\alpha/2}, \bar X_n + \frac{\sigma}{\sqrt{n}}z_{1-\alpha/2}]$$
which will have $1-\alpha$ coverage.
So to wrap up this is where the normal approximation is coming from and how the CLT is used. You will notice we never replaced the population mean (parameter) with the sample mean (parameter). Rather we just found a region around the sample parameter for which we can be sure (to a $1-\alpha$ level of confidence) that the population parameter lives in using our normal approximation.
Comment: Where the issue is: (Xn with bar) is a parameter, not a single value. You urself say: "we just found a region around the sample parameter for which we can be sure that the population parameter lives..". We are taking a single sample, NOT a lot of samples. If u read my question properly(I have edited it a bit), my issue is precisely that. Also, you can read the other answer and my comment on it, and tell ur views about that.
Comment: Based on the comments in the other answer it sounds like the speaker may be generating multiple samples. This does not really change the procedure for building confidence sets. So the above should still apply.
Answer: "M and SM are quite close and so, M can be replaced with SM." No, M is nowhere replaced by SM, and you don't need to assume they are close. The CLT makes a statement about the distribution, i.e., the variation of the SM, its distance from M. It doesn't require anywhere that this distance is small (although it is expected to become small for large n as a consequence of the theorem).
"Let us suppose that the normal distribution of sample means, has an exact mean of MSM." The mean of the distribution of the sample means is always M, even without CLT, normality, and asymptotics (as long as M exists).
"...what we are trying to compute is the range MSM +/- 2SD/sqrt(n)." No, we're fine with SM +/- 2SD/sqrt(n), no need to involve MSM.
"So, how one solves this contradiction?" By not introducing MSM in the first place.
"2. That we assume MSM is actually quite close or same as M (Population Mean)." These are the same anyway, see above.
Comment: PS: It may be that the speaker in the video simulated many samples and showed the mean of those, so his "MSM" may be the simulated one, therefore slightly different from the precise one, which, as I wrote, is equal to M. Chances are this is correct but you may have confused the simulated MSM with the theoretical one.
Comment: So, if I understand you correctly, what you are saying in essence is that the second approach is indeed correct and we should forego the idea that the distribution of Sample Means provides a Confidence Interval of the Population Mean(M) around it's mean(MSM). But if that is correct, then is what is said from 2:00 - 2:40 in this video is wrong?: https://www.youtube.com/watch?v=-P0sTR8LcS4&list=PLRJdqdXieSHMtmKxr4s78F7U88l-SawAj&index=19
Comment: I have edited my question. You can take a look.
Comment: I had a quick look at 2:00 of the video but don't have time to watch it in full, so I can't comment on it. Your "second approach" still is based on a distinction between M and MSM, so I don't think this is correct - it may be more confused than incorrect though.
Comment: No, actually in my second approach I clearly say that MSM is same as M, so I am presuming both of them to be the same or very close to each other. And I think you have hit the nail on the head: When trying to take a single sample and deriving CI from it, we have to take the theoretical MSM which is same as M. And when taking a lot of samples and then calculating CI through their sample means - first approach will be applicable. Please correct me if I am wrong.
Comment: Also, apart from the distinction between M and MSM, do you find any other issues/errors in the logic of the second approach?
Comment: You write "we assume MSM is actually quite close or same as M" but this is not an assumption, it is a mathematical necessity that these are the same. Also you write "it will be 100% certain that our population mean M(or MSM) is within 2SD/sqrt(n) of the SM (Sample Mean)" but this is not 100% certain, and generally the CI doesn't allow to make statements about the probability that the true population mean is anywhere, as the population mean is not a random variable.
Comment: You misunderstood, read again. The 100% certainty is for the cases where our single sample mean is within the range MSM +- 2SD/sqrt(n). And the probability of that happening(SM falling in that range) is 95%. So, the probability of MSM(or Population Mean) being within 2SD/sqrt(n) of our single SM is 95%. So I am proposing that that's how we come out with a 95% CI.


Command "generate-votes" is not defined

Question: I'd like to use Drush 10.3.6 to generate votes on my development server.
Based on these instructions for a previous Drush version (8.x), there is some kind of module/extension for this.
drush generate-votes

However, when I try it, it doesn't work for me. The error message I get is the following one.

Command "generate-votes" is not defined.

Has this feature been removed or deprecated? Is there any other way I can generate votes from the command line?
Comment: Is that official docs site?
Comment: @Kevin I'm not sure but I would guess it's not, it seems buggy.
Answer: This command doesn't come from Drush core but from the Voting API module. This command simply doesn't exist yet in the currently latest Voting API release: 8.x-3.0-beta2.  See, the directory /src/Commands where Drush commands since Drush version 9 get registered now simply isn't there yet.
You need to get the latest Voting API dev:
$ composer require 'drupal/votingapi:3.x-dev@dev'

There the /src/Commands directory contains a VotingApiCommands.php file with all the commands in it. The module needs to be enabled to use them, of course.

Voting API version 3.0-beta2 only contains the legacy votingapi.drush.inc file for Drush commands up to Drush version 8.

Command "generate-votes" is not defined


Why do training plans having you running many days of the week?

Question: I noticed that a lot of training plans have you running most every day with a day or 2 off at different intervals.  Why is this?
I am currently training for a half marathon.  If I run on Sunday (6.5) I take Monday and Tuesday off and then run the same distance on Wednesday.  I would then take Thursday and Friday off and on Saturday I would run 7.8.  I would then take 2 days off and continue this interval.
It has worked really well for me.
If I followed the marathon training plans out there I would be running more often at less distances.
I know there has to be a reason for training the way the marathon training programs suggest.  I am curious as to why those are better than my 1 day on / 2 days off, upping by distance each week.
Answer: For good or bad, the authors of many training plans are or were serious runners.  Elite athletes who take the approach that "any day I am not running is a day my competition just got faster than me".  These training plans also assume that you recover quickly and that you are not prone to injury.
These programs are only better if you want to keep improving your performance. Presuming you can handle the workload and not get injured, you will become stronger and a better runner the more you run.
If your goals are more fitness-oriented or you run for pleasure or social reasons than it could be that your approach is better.  I hope this answers your question.
Comment: Most of these programs are written for average runners looking to prepare for a marathon. They are designed to reduce injury risk. Running a marathon is a stress on your body, and many inexperienced runners are prone to injury. The plans are often written by coaches who have spent time working with beginners (like high school students who have never run before), and are well versed in injury prevention
Answer: It all really depends on what kind of running you are doing. I know that there are some who run distance workouts and take two days off in-between, but I also know some who do tempo interval workouts and take one day off a week. The long run can be the most beneficial, but also can cause the most damage if done too hard, too long, and too frequently. So you can continue doing your individual workout, especially if it seems to be working for you, but be careful with your body as to not overwhelm it. You only get one haha. Throwing some sporadic tempo interval runs may be beneficial for you, as training in only one area may decrease your abilities in another. Many believe there is only one way to run, but there are many different factors and abilities that are tested. Having tempo interval runs will allow you to work on running through tiredness towards the end of the race, and force you to focus on your running form, which one may not necessarily work on if they simply do distance runs and nothing else.
Answer: I have run 8 marathons and the first 4 I did using traditional programs that involved 5 or 6 days a week of running. But the last 4 I changed it up.
I am a huge fan of the FIRST program. Essentially it focuses on quality runs not quantity so you don't get burned out and you have a less chance of being injured.  One day is track, one day tempo and the other a long run.  You are supposed to cross train (bike, swim or row) 2 more days but I have not found it necessary.  You have to really commit to the distances and times so the runs themselves are hard but you only have to do 3 a week.  The program was detailed in the book Run Less, Run Faster by Bill Pierce, Scot Murr and Ray Moss.
Comment: https://runnersconnect.net/why-run-less-run-faster-doesnt-work/ this result explains why Run Less, Run Faster is what people want to work, but not what actually works. You may have adaptation after already training for 4 marathons, but working hard for 3 days a week exposes you to injury, even if it is convenient.
Answer: Key takeaway: Use Consistency to adapt
Some serious running books with relevant chapters:

The Science of Running by Steve Magness
Daniels' Running Formula by Jack Daniels
Build Your Running Body by Pete Magill et al
The Lore of Running by Tim Noakes

Standard training programs try to minimize injury using consistency and gradual changes. By training on a near daily basis, creates a much more regular routine for your body, and building up mileage slowly also helps your body adjust.
Muscles
Muscle building is very adaptable. You may be sore in the days after you run, but if you drink and eat well, muscles should recover quickly. Building up mileage will help your muscles prepare for longer distance runs. If you strain a muscle (possible if you run while you are sore and/or take a bad step), you might need a few days of rest. 2 days off might be enough! Muscle recovery slows drops off quickly after your run, so recovery 2 days after a run will be significantly slower. A short run (just 1 or 2 miles will work) on a day off has been shown to improve recovery.
Tendons and Ligaments
These are not quite as adaptable as muscles, but providing muscle-bone and bone-bone connections, the running will add stress to them. They will slowly adapt over the course of months, and regular exercises and stretching can help loosen them. Common issues like achilles injuries crop up when training is adjusted too quickly. Tears are unlikely, but even soreness can hang around for weeks.
Bones
Bones can support a volume of stress over time (maybe 20 miles a week of running), but are gradually damaged by repeated use. If you overwhelm your bones, you can have a minor contusion or a fracture, with recovery times from 2 weeks-3 months. With a fracture it is likely you will not run in the marathon you are targeting. The best protection is to slowly build the volume you run each week. Running many days allows you to build high regular volume over the course of training. Many runners will run quite a bit farther (20 miles) in the weeks leading up to the marathon. If your running volume is 25 miles normally, and you run 35 or 40 miles 2 weeks before your marathon, you are much higher risk for a stress injury. By building large regular volume, you can avoid the big jump.
Conclusion: Reduced Injury Risk
In general, running more regularly reduces injury risk, even if some runs are short. This doesn't mean you will get injured if you run inconsistently. You are also not invincible just because you are consistent. Consistency doesn't protect you from a bad step. But consistency reduces risk.


Não perder o texto de input ao trocar de página

Question: Bom dia, estou precisando fazer o seguint: O usuário digita algum texto num input e esse texto não se perde se ele trocar de página. Esse input não tem nenhum botão de submit. Como posso fazer isso? Tem como fazer sem uso de BD?
Comment: você tem que ter algo que relacione as duas páginas, se você usa php você pode gravar em uma $_SESSION se você tem um arquivo js que esta vinculado as duas páginas pode colocar em uma váriavel global
Answer: Podes utilizar jQuery para ler o texto escrito nesse input:
Javascript:
 $("#teu_input_id").keyup(function(){
    var input = $(this).val();

    $.post("/backend.php", {"input": input});
});

PHP:
session_start();
$_SESSION['input'] = filter_var($_POST['input'], FILTER_SANITIZE_STRING);

Nas páginas onde não queres perder a informação:
PHP
session_start();
$input = filter_var($_SESSION['input'], FILTER_SANITIZE_STRING);

HTML
<input type="text" name="teu_input" id="teu_input_id" value="<?=$_SESSION['input']" />

Answer: Você pode gravar o valor do input em uma variável e depois resgatar ela com algum evento como onchange, onclick e etc.
Exemplo funcional:

    <title>Teste</title>

<form name="frm">

<input type="text" name="valor1"  size="10" >

<button type="button" onclick="mostrarValor();">Veja os valores</button>
</form>

Comment: Obrigado :D Ajudou bastante
Comment: @RicardoAfonso Sempre as ordens!


visual studio c linker wrap option?

Question: From this article Unit testing with mock objects in C:

This is done by using the --wrap linker option which takes the name of the wrapped function as an argument. If the test was compiled using gcc, the invocation might look like:
$ gcc -g -Wl,--wrap=chef_cook waiter_test.c chef.c

How can I do this when compiling a C project in visual studio?
Comment: +1 This is what I would like to know too, it appears that in VS (i.e. MSVC compiler) you can only use #defines to manually override the actual implementation.
Answer: The --wrap in ld can be emulated by the /ALTERNATENAME option in MSVC Linker.
We start from two compilation units, say foo.o compiled from foo.c, whose external functions are declared in foo.h, and main.o from main.c.
(If foo has been compiled as a library, things won't change much.)
// foo.h
int foo();

// foo.c
int foo() {
    return 0;
}

// main.c
#include <stdio.h>
#include "foo.h"
int main() {
    int x = foo();
    printf("%s\n", x ? "wrapped" : "original");
}

The return value of int foo() is 0, so the snippet of code above will output "original".
Now we override the actual implementation by an alias: The #include "foo.h" in main.c is replaced by
#define foo real_foo
#include "foo.h"
#undef foo
#pragma comment(linker, "/alternatename:real_foo=foo")

Let me explain what happens here:

by #define foo real_foo, the function declaration in foo.h is modified as int real_foo().
However, the symbol in foo.o is still named after int foo(), instead of the alias int real_foo(). That's why we need the /alternatename linker switch.
"/alternatename:real_foo=foo" tells the linker that, if you cannot find the symbol called real_foo, try foo again before throwing an error.
Apparently there is no definition of int real_foo(). MSVC Linker will search for int foo() and link it instead at each occurrence of int real_foo().

As the previous implementation has been aliased, now we redirect int foo() to our new implementation by a macro:
int wrap_foo() {
    return real_foo() + 1;
}
#define foo wrap_foo

And we are done here. At last the main.cpp looks like:
#include <stdio.h>

#define foo real_foo
#include "foo.h"
#undef foo
#pragma comment(linker, "/alternatename:real_foo=foo")

int wrap_foo() {
    return real_foo() + 1;
}
#define foo wrap_foo

int main() {
    int x = foo();
    printf("%s\n", x ? "wrapped" : "original");
}

Built in MSVC, it will output "wrapped".

visual studio c linker wrap option?


Bolzano -Weierstrass Theorem and uniform Continuity

Question: The following problem has hints, but I am unable presently to use it.

Suppose $f$ is uniformly continuous on $(a,b]$, and let $\{x_n\}$ be any fixed sequence in $(a,b]$ converging to $a$. Show that the sequence $\{f(x_n)\}$ has a convergent subsequence (Hint: Use the Bolzano Weierstrass Theorem)
Now let $L$ be the limit of the convergent subsequence of $\{f(x_n)\}$. Prove, using the uniform continuity of $f$ on $(a,b]$, that $$\lim_{x\to a^+}f(x)=L.$$
Comment: This is strange. It follows directly from the definition of uniform continuity that $(f(x_n))$ is Cauchy (since $(x_n)$ is), thus convergent.
Answer: $f$ is uniformly continuous on $(a,b]$ and is therefore bounded. $x(n)$ is a fixed sequence in $(a,b]$ converging to a so $f(x(n))$ is a bounded sequence. By Bolzano Weierstrass $f(x(n))$ has a convergent subsequence. Let $L$ be the limit of the convergent subsequence, $x(n_k)\to x$ so therefore $$f(x(n_k))\to f(x)$$ as $f$ is uniformly continuous. So as a sequence can only have one limit, $$f(x(n))\to L.$$
Comment: Why does uniform continuity imply boundedness??
Comment: For all delta >0 such that exists an epsilon >0 such that for all x,y with abs x-y<epsilon implies abs fx-fy <delta put delta =1 now the diferrence between the sup and inf of f is at most a-b / epsilon
Answer: Hint: Bolzano Weierstrass says that every bounded real sequence has a converging subsequence. If $x_n \to a$ and $f$ is uniformly continuous. Is $(f(x_n))_{n\geq 1} \subset \mathbb{R}$ bounded?
Comment: Hi and thanks for your answer , I still cannot see why (f(x(n)) is bounded ,I can see that if I prove this then I can use the B-W theorem , but how to prove it??
Answer: Since $f$  is uniformly continuous on $(a,b]$, it is bounded. Moreover, $\lim\limits_{x\rightarrow a}f(x)$ exists, say $c$.  So we can define \begin{align} g(x)=\begin{cases}f(x), \,\,\,x\in (a,b]\\
c,\,\,\,x=c.\end{cases}\end{align} Then $[a,b]$ is a closed and bounded interval by the intermediate value theorem. Then applying Bolzano-Weierstrass theorem on $g([a,b])$ yields the result.


A program to visualize Linear Algebra?

Question: I am asking here because I believe you have some idea of a good visualizer 3d program to see what are really: eigenvectors, subspaces, rowspaces, columnspaces and just answers on normal matrix multiplication visualized.
It's easy to calculate, but it's hard to visualize I think.
Answer: It depends how you want to go about it. With this I mean that you need to structure the way you want to visualize things for example eigen vectors a good way to visualize them is by doing 3D or 2D orthogonal transformations a very cool application with great visual implications is Principal components analysis for example.
If you are familiar with programing I would recommend matplotlib its python and its very easy syntax and like I said you can visualize things such as linear transformations on 3D objects in very nice ways.
Additionally wolfram alpha gives you little matrix heatdiagrams and graphs for adjecency matrices if you are after something like.

A program to visualize Linear Algebra?


Desenvolver layout com 3 colunas

Question: Suponhamos que tenho um layout contendo 3 divs lado a lado.
A primeira dessas divs possui um tamanho fixo de 100px, a terceira div não pode possuir tamanho fixo pois ela dependerá do texto inserido nela, contudo, ela não poderá quebrar o texto.
Já a segunda div, vai ter que se adaptar ao tamanho das outras divs. Dessa forma, ela será a única que poderá quebrar o texto. Como posso alcançar isso?
A imagem abaixo descreve melhor aquilo que pretendo fazer:
Comment: ja tento usa boostrap ? eu usaria uma table pra fazer essa linha ou um ajax que calcule o tamanho da terceira div e setasse o valor da segunda. mas com uma table seria bem mais simples
Comment: c vc quiser posso postar uma resposta utilizando table
Comment: Vou pesquisar a respeito... ATT
Answer: Veja se assim resolve seu problema
css
td span{
  font-size:30px;
  background:blue;
  width:auto;
  min-width:1px;
  text-align:right;
  float:right;
  white-space:nowrap;
}
td p{
  background:yellow;
  float:left;
}

html

SEU TXT AKI FORMATADO yg uyg yug uyg ykjg jg fyjkf ygf htj fhg fhg fgh f yjhf

         R$ 3,50

SEU TXT AKI FORMATADO

         R$ 153,50

segue o fiddle dele funcionando
https://jsfiddle.net/3mLffz19/
Comment: Eu havia feito com .resize() jquery, mas a sua solução é melhor. Gostaria de saber se há algum problema com a semântica em usar table na criação de um layout do tipo?
Comment: cara no meu ver não ha problemas pois ate o boostrap usa table para vários fins. vou dar uma pesquisada para ver se ha outra forma mais eficiente de fazer

Desenvolver layout com 3 colunas


In DDD, where should validations involving more than one context be done?

Question: Suppose we have the Customer and Order contexts in a monolithic application.
When creating the Order I need to verify that the customerId exists, otherwise the system could remain in an inconsistent state.
Would I have to call the Customer application service from the Order service? eg. customerAS.exist(customerId)
Could I call the Customer repository directly from the Order application service ?
Comment: This is not explicit in your question, but the tags suggest you want an answer regarding switching your monolithic application to DDD, is that correct ?
Comment: Also are **Customer** entities handled in the same bounded context than **Order** or not ?
Comment: No @ArwynFr, is DDD in a monolithic application, but from the conceptual point of view it is the same as if it were a microservice or a monolithic. Customer and Orders are in different BC.
Comment: DDD is based on having a domain component where all business code go, and other component(s) where non-business code go. This requires at least a layered-architecture. Unless you want to oppose monolithic to front/api ?
Comment: Also if Customer and Orders are in different BC they cannot be in the same monolith.
Comment: Why not? DDD was born in the era of monoliths
Comment: The concept of a monolith is having a single structure with everything inside. If you make two bounded context, then this is not a monolith anymore, since you have more than one component.
Comment: You can have an application with multiple modules running in the same process.
Answer:
Could I call the Customer repository directly from the Order application service ?

The DDD police will not arrest you if you do it
...but it would be better to don't do it.
The fact is that in that way you are coupling the implementation of the Order domain with the implementation of the Customer domain, and in case later on you want to change the customer domain to don't use repositories, or you want to separate them into two different deployables you will have to refactor this integration point and use something else instead of the repository directly.
Using an interface that explicit the contract and the queries/commands of a domain (the service) helps in decoupling what you need to do with how you do it, and you will be more free to change the how you do certain stuff reimplementing the same contract the service was already exposing
Answer:
Suppose we have the Customer and Order contexts in a monolithic application. When creating the Order I need to verify that the customerId exists, otherwise the system could remain in an inconsistent state.

What's the business impact of being inconsistent in this way:  One dollar? Ten dollars? One hundred billion dollars?
If the business impact of the error is inconsequential, then don't compromise your design and performance to mitigate it.
If the impact would be catastrophic, then you are probably going to need to design your system so that it locks all of the information that must be consistent with making a change.  (You probably don't have this problem, because a microsecond difference in timing shouldn't make a difference to the business.)  That will normally mean abandoning the idea that customers and orders are separable systems; perhaps they merge, or parts of the two get moved to a new third system that can manage these information relationships.
In between, we can consider "best effort" mitigations, like consulting an unlocked copy of the information, and hoping the answer found there is fresh.  For instance, we could ask the Customer system for a copy of the answer, but we need to be aware of the fact that the real answer could change while the answer is in flight.
In a microservices design, you probably wouldn't want to use a synchronous call to another system that might be down for maintenance or upgrade, but instead to use a locally cached copy of the answer, which is intermittently refreshed using some asynchronous mechanism.
Horses for courses.
Comment: I think that the worst case would be to have a public api with many clients that can misuse it, either by mistake or maliciously. I don't think that Facebook or Twitter APIs don't perform that kind of validation.
Comment: It may be less than you think.  Recall that context boundaries are something that you can control with your design.  It might be useful to review Udi Dahan's "Finding Service Boundaries...." talk.
Comment: I disagree, reference ids between contexts are quite common. Let's not talk about whether to validate if a user is suspended or disabled or in any possible state.


Como vários containers Docker atendem a mesma URL (microserviços)

Question: Estou iniciando com Docker e com aplicar com microserviços e fiquei com uma dúvida, como instância do meu micro serviço que sobe tem um novo IP, como faço para que ao chamar uma única URL eu consiga distribuir as requisições entre os diversos containers do meu serviço?
Answer: Eles não atendem diretamente. Há um intermediador, que pode ser um load balancer ou um proxy reverso.
Em um deploy docker, dificilmente você usa diversas portas, você em geral usa apenas as portas 80 e 443 se estivermos falando de tráfego http.
O roteamento dentro da infra do docker é feito a partir desse princípio, onde hospedamos um proxy reverso escutando essas portas, e o proxy reverso tem as configurações de roteamento e distribuição para cada cenário.
Produtos/Projetos comuns nesse papel:

NGINX
Traefik
HAProxy
Envoy


jQuery on() not working on loaded elements

Question: Im doing everything like said in documents but it just isn't firing.
    //Magnific Popup Background Blur

    $('a.video-popup').on('click', function(e) {

        $('.main-wrapper').addClass('blur');
        $('header').addClass('blur');

        console.log('Easy!');

    });

    $('document.body').on('click','.mfp-wrap', function(e) {  //mfp-wrap is background

        console.log('Finallly!!');

        $('.main-wrapper').removeClass('blur');
        $('header').removeClass('blur');
    });

First function works very well but the second one..
Situation:

If a.video-popup is pressed, popup appears with background
Popup elements are not in DOM when page is loaded
Popup elements are directly under body if loaded
If background is clicked, popup closes
I get nothing - doesn't remove classes or give consol.log, also no errors

SOLUTION:
$('document.body').on('click','.mfp-wrap', function(e)

to
$(document).on('click','.mfp-wrap', function(e)

Comment: Can include `html` at Question ?
Answer: in this selector
$('document.body')

means document node which contain body class not body node
and there is no node which name is document
Try like this
$(document).on('click','.mfp-wrap', function(e)

Answer: Try substituting
$(document.body).on('click','.mfp-wrap'
for
$('document.body').on('click','.mfp-wrap'
Comment: Can include `html` at Question ? , create stacksnippets , jsfiddle http://jsfiddle.net to demonstrate ?


Upgrade SSL/TLS/Openssl?

Question: I have a requirement to upgrade SSL/TLS/OpenSSL. The server is RHEL 6 Enterprise.
In that server I am going to remove apache, which has not been not in use for a  long time. After uninstalling apache , is it stil necessary to upgrade ssl/tls/openssl?
Or even broader, since neither a web server nor a webbrowser will be installed is there any need for OpenSSL at all?
Comment: Is there a particular vulnerability you're worried about? Or are you just looking to reduce the number of packages to reduce your attack surface?
Comment: Hi everybody..sorry, One correction..I want to use web browser. After uninstallation of web server, is there any need for ssl/tls/openssl at all?
Comment: Yes. Because of vulnerability reason I have got this requirement.
Answer: Take a look at the output of
<code>yum remove openssl
</code>
It will list all of the packages that will also be removed because they depend upon the openssl package. Eventually it will quit with the error message

Error: Trying to remove "yum", which is protected

Removing openssl from your system is not practical or desirable.
Keeping it up-to-date with that provided by your distro is though desireable and practical.
Answer: Removing unneeded software is typically a good idea.
The openssl package is actually needed for a lot of required core functionality in a RHEL system.
<code> sudo yum remove openssl
</code>
will fail but also show what also would have to be removed since it depends on openssl.
So do the right thing and upgrade the openssl package to the current patch level.
Comment: @Ratheesh We'll leave that as a learning exercise for you.
Comment: Dear Lain and HBruijn...whatabout SSL and TLS ??
Comment: openssl is the most commonly used shared software library to provide SSL/TLS functionality and features to other software.

Upgrade SSL/TLS/Openssl?


imap-login director is not restarted after each auth request

Question: imap-login by default in dovecot mail server is restarted after every login request keeping security in mind to avoid leak of critical data. But in a director config, the imap-login director process is not restarted on each auth request. Can somebody explain why this design decision is taken?
Answer: imap-login deal with sensible data like user's login/pass that potentially can be extracted from the hacked process. Director have no sensible data inside so there is no reasons to hack/strength it.
When each user have its own imap-login process there is physical limit for simultaneous connections number (by RAM). Single shared process have no such limit.
Comment: Imap-login director process will get the user auth details right to lookup passdb. Am I missing something here?
Comment: `director` maintain the mapping between user and imap-server user attached to. That is used for clustering to ensure user will be directed to the same host each time. And then `imap-login` process perform authentication.
Comment: Director also has imap-login process which uses director socket for passdb lookup. This process is not renewed after successful logins