Baer sum of $\mathbb{Z}_9$ and $\mathbb{Z}_9$

Question: I am working on trying to figure out the third extension of $\mathbb{Z}_3$ by $\mathbb{Z}_3$, I know one is $\mathbb{Z}_9$ and the neutral element (with respect to baer sum) $\mathbb{Z}_3\oplus \mathbb{Z}_3$. I know from $\text{Ext}(\mathbb{Z}_3,\mathbb{Z}_3)\cong\mathbb{Z}_3$. So there is another extension availiable. I know therefore that $\mathbb{Z}_9+_B\mathbb{Z}_9$ must result in another extension but I am running into trouble trying to recognise how it looks like. Let our extension be
$$0\to\mathbb{Z}_3\xrightarrow{3}\mathbb{Z}_9\xrightarrow{\pi}\mathbb{Z}_3\to 0$$
I know for the baer sum we have that the module we're after is the quotient of
$$X=\{a\oplus b:\mathbb{Z}_9\oplus\mathbb{Z}_9:\pi(a)=\pi(b)\}$$
and
$$N=\{3n\oplus -3n:n\in\mathbb{Z}_3\}$$
That is our baer sum is $X/N$. All dandy so far, I have determined that
$$X=3\mathbb{Z}_9\oplus3\mathbb{Z}_9 \cup(3\mathbb{Z}_9+1)\oplus(3\mathbb{Z}_9+1)\cup(3\mathbb{Z}_9+2)\oplus(3\mathbb{Z}_9+2)$$
Which is hardly pretty but this comes from $\pi(a)=\pi(b)$ if and only if $a=b+3n$ for some $n$.
Our $N$ is easier to determine as we get
$$N=\{(0,0),(3,-3),(6,-6)\}$$
or
$$N=\{(0,0),(3,6),(6,3)\}$$
This of course gives us $27/3=9$ elements in our module, I have checked on paper and even used programs and from what I can see it seems to be isomorphic to $\mathbb{Z}_9$ which makes no sense to me so I probably did some screwup along the way. The isomorphism I found would be $\phi(1)=1\oplus 1$ and it'll generate all 9 elements. I have even checked the orders of elements and then coincide with all orders of $\mathbb{Z}_9$. What am I doing wrong here?
Comment: One needn't perform the Baer sum explicitly. If one has a SEC of the form $0\to \Bbb Z_3\to M\to \Bbb Z_3\to 0$ then one can conclude that $M$ has order $9$, so it must be $\Bbb Z_3^2$ of $\Bbb Z_9$, which are the only groups of order $9$.
Comment: @PedroTamaroff This doesn't tell you why there are $3$ extensions, up to isomorphism of group extensions.
Comment: @Christoph That's true, but that can be handled by calculating the order of the extensions group as the OP did. =)
Answer: Your computation are correct. The last extension is still isomorphic to $\mathbb{Z}_9$. By the way, in a short exact sequence like this, the order of the middle group is the product of the order, and you should know that up to isomorphism there are only two (abelian) groups of order 9.
Note that $\operatorname{Ext}^1(A,B)$ classifies the extensions of $A$ by $B$ up to isomorphism of extensions, but not up to isomorphism.
In other words, can you find the vertical arrow with (?) here :
$$\require{AMScd}
\begin{CD}
0@>>>\mathbb{Z}_3@>\times 3>>\mathbb{Z}_9@>\times 2>>\mathbb{Z}_3@>>>0\\
@.@|@V?VV@|@.\\
0@>>>\mathbb{Z}_3@>\times 3>>\mathbb{Z}_9@>\times 1>>\mathbb{Z}_3@>>>0
\end{CD}
$$
There is no such map (?). This mean that the two short exact sequences above define two different classes of extension in $\operatorname{Ext}^1(\mathbb{Z}_3,\mathbb{Z}_3)$, and of course the trivial extension define the third one.
Comment: Hmmmm ah yes, good lord I keep forgetting that
Comment: Would you happen to know an extension that is simple to identify where I could illustrate baer sum and get something that looks more different?
Comment: For $\operatorname{Ext}^1(\mathbb{Z}_4,\mathbb{Z}_4)\simeq\mathbb{Z}_4$ you get 3 different abelian groups. The one that is twice a generator is maybe "different"... What to you think ?
Comment: I gotta do the hard work to see how it looks :) Unless you could just do a quick show of it but I'll just do the brunt work then.
Comment: Just note that there is a short exact sequence $$0\rightarrow Z_4\rightarrow Z_8\oplus Z_2\rightarrow Z_4\rightarrow 0$$ where the left map is $n\mapsto (2n,n)$ and the right map is $(a,b)\mapsto a+2b$. This should appear as the baer sum of $$0\rightarrow Z_4\rightarrow Z_{16}\rightarrow Z_4\rightarrow 0$$ with itself.


Retornar um endereço

Question: Estou finalizando um projeto onde abrirá um alertDialog. Assim que o usuário pressionar OK irá fazer uma confirmação e sua localização será informada por um toast. Gostaria de saber como eu consigo retornar o local onde o usuário está.
Answer: Faça desse jeito:
public class main extends AppCompatActivity {

    LocationListener locationListener;
    LocationManager locationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Faço o objeto da classe
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationListener = new MyLocationListener();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        assert locationManager != null;
        //Requesto a localização, os parâmetros 500 e 0 são intervalo que irei pegar o localização e a variação em metros que irei pegar respectivamente
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 0, locationListener);

    }

    public class MyLocationListener implements LocationListener {

            @Override
            public void onLocationChanged(Location loc) {

                   //Peguei a latitude e longitude
                   double lat = loc.getLatitude();
                   double log = loc.getLongitude();

                   //Agora transformo em endereço:
                   String cityName = null;
                   Geocoder gcd = new Geocoder(context, Locale.getDefault());
                   List<Address> addresses;
                   try {
                        addresses = gcd.getFromLocation(loc.getLatitude(),
                        loc.getLongitude(), 1);

                        if (addresses.size() > 0) {

                           //Aqui você chama seu alert, o endereço se pega da maneira abaixo:
                           //Endereço = addresses.get(0).getLocality());

                           System.out.println(addresses.get(0).getLocality());
                           cityName = addresses.get(0).getLocality();

                        }
                    }catch (IOException e) {
                           e.printStackTrace();
                    }

                   //Depois de pegar a localização eu para o onLocationChanged
                   locationManager.removeUpdates(this);

            }

            @Override
            public void onProviderDisabled(String provider) {}

            @Override
            public void onProviderEnabled(String provider) {}

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {}

        }
}

Mais mastigado que isso só se eu fizer seu alertDialog kkkkkkkkkk, lembre-se de fazer um método que checa se o GPS está ativo antes de tentar pegar a localização, pois pode ocorrer uma exceção se ele estiver desligado.
Lembrando que você deve adicionar no Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Comment: kkkk muito obrigado salvou dms, o alert ja ta pronto kk
Comment: @BrunoSIlva então marca como aceita aí pra fortalecer a amizade kkkk
Comment: claro kkk, vlw parceiro
Comment: Aqui mais uma duvida, e se eu quiser chamar o alert e dependendo do que ele solicitar ai sim eu retorno a localização?
Comment: No ok no alert vc chama: `locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 0, locationListener);`
Comment: Vlw novamente, brigadao
Comment: De nada parceiro :)

Retornar um endereço


Como ordenar questões de forma aleatória?

Question: Estou finalizando um projeto de jogo Quiz Unity em C#, deixa eu tentar explicar o que preciso, já faço as perguntas aleatórias, porém eu quero que as respostas também sejam exibidas aleatórias.
tenho uma lista com 5 questões, cada questão tem 4 alternativas, as questões são selecionadas por um ID.
hoje o código esta assim:
            pergunta.text = perguntas[idPergunta];
            respostaA.text = alternativa1[idPergunta];
            respostaB.text = alternativa2[idPergunta];
            respostaC.text = alternativa3[idPergunta];
            respostaD.text = alternativa4[idPergunta];

no campo respostaA, quero que recebe um valor aleatório entre alternativa1, alternativa2, alternativa3, alternativa4.
por exemplo, o random diz que no campo respostaA.text recebe a alternativa4, então respotaB.text não pode receber essa alternativa, o random teria que gerar outra alternativa.
Answer:  using System.Collections.Generic;

[...]
List<string> temp = new List<string>();

temp.Add(alternativa1[idPergunta]);
temp.Add(alternativa2[idPergunta]);
temp.Add(alternativa3[idPergunta]);
temp.Add(alternativa4[idPergunta]);

var r = new Random();

var c = r.Next(4);
respostaA.text = temp[c];
temp.RemoveAt(c);

c = r.Next(3);
respostaB.text = temp[c];
temp.RemoveAt(c);

c = r.Next(2);
respostaC.text = temp[c];
temp.RemoveAt(c);

respostaD.text = temp[0];

Answer: O método mais prático:
void Shuffle<T>(List<T> objetos)
{
  Random r = new Random();
  objetos.Sort(Comparer<T>.Create((a,b) => { return r.NextDouble() > 0.5 ? 1 : -1; }));
}

Então:
List<string> objetos = new List<string>();

objetos.Add("A");
objetos.Add("B");
objetos.Add("C");
objetos.Add("D");
objetos.Add("E");
objetos.Add("F");
Shuffle(objetos);

foreach (var item in objetos)
{
    Debug.WriteLine(item.ToString());
}

Comment: Esse código pode ser simplificado: objetos.Sort(Comparer.Create((a, b) => r.Next(2)-1));
Comment: Com essa otimização ganha-se uns 3~5 nano segundos por comparação. É uma solução prática e não a mais ótima. Com certeza é possível otimizar isso ainda mais sem utilizar o algoritmo de ordenação (que é meio estúpido ordenar de um jeito embaralhado LOL)
Comment: Acredito que a implementação do .Net seja um quick sort, que é N Log N, mas isso é facilmente linearizável.


Finding where f is well conditioned

Question: I am looking for help with part b. I'm not sure where f is well conditioned in a relative sense given that $\kappa(x)$ is a constant. Is f merely well condition at this point ($\frac13$)? If so, how do I know this? Is $\kappa(x)$ of "moderate size"? I'm not sure how to interpret this constant. For C(x) I can input a value and see how this effects the output but for $\kappa(x)$ this isn't possible. Any help would be much appreciated!
Let $f(x) = \sqrt{x^3}$
(a) Find the absolute and relative condition numbers of f.
(b) Where is f well conditioned in an absolute sense? In a relative sense?
(c) Suppose $x=10^{-17}$ is replaced by $x=10^{-16}$. Using the absolute condition number of f, how much of a change is expected in f due to this change in the argument?
(a)$f(x) = x^{1/3}$, $f'(x)=\frac13x^{-2/3}$
absolute condition number = $C(x) =\frac13x^{-2/3}$
relative condition number = $\kappa(x) = xf(x)/f'(x)$ = $\frac{x \frac13 x^{-2/3}}{x^{1/3}}=\frac13$
(b) f is well conditioned in an absolute sense as x approaches infinity as large values of x produce a small change in f.
Comment: You are missing some absolute value signs which matter very little for this example. More importantly, exactly how have the condition numbers been defined in your class? Where you given an abstract definition from which these formula were systematically derived or where the formulas derived using energetic hand waving?
Comment: $|(y-\hat{y})|=|f(x)-f(\hat{x})| = |\frac{f(x) - f(\hat{x})}{x-\hat{x}}| |(x-\hat{x})|$

$\approx|f'(x)||x-\hat{x}|$

Thus $C(x) = |f'(x)|$, where $x \approx \hat{x}$ This is the absolute codition number.

Similarly, $|\frac{y-\hat{y}}{y}|$ = $|\frac{xf(x)-f(\hat{x})}{x-\hat{x}}||\frac{x}{f(x)}||\frac{x-\hat{x}}{x}|$

Thus, $|\frac{y-\hat{y}}{y}| \approx|\frac{xf'(x)}{f(x)}||\frac{x-\hat{x}}{x}|$

$\approx |\frac{xf'(x)}{f(x)}|= \kappa({x})$where $x \approx \hat{x} $ This is the relative condition number.
Answer: In general, conditions numbers represent the limiting behavior of the worst case scenario. If the condition number is small, then the function is insensitive to sufficiently small changes of input. If the condition number is large, then it is possible to find a small change of the input, which will change the output dramatically.
To be precise, let us consider the proper definition of the relative condition number $\kappa_f(x)$ for a function $f : \mathbb{R} \rightarrow \mathbb{R}$ at a point $x \in \mathbb{R}$.
We begin by defining an auxiliary function $\kappa$ given by
\begin{equation}
    \kappa_f( x, \delta) = \sup \left\{ \left|  \frac{f(x) - f(y)}{f(x)} \right| \big{/} \left| \frac{x-y}{x} \right| \: : \: 0 < |x-y| < \delta|x| \right\}.
\end{equation}
It is straightforward to verify that $\delta \rightarrow \kappa_f(x,\delta)$ is a nonnegative and nondecreasing function of $\delta$. This implies that the limit
\begin{equation}
    \underset{\delta \rightarrow 0_+}{\lim} \kappa_f(x,\delta)
\end{equation}
exists and is nonnegative. Since we are primarily interested in small values of $|x-y|/|x|$ we will use this limit to characterize the sensitivity of $f(x)$ to perturbations of $x$ which are small relative to $x$. This is why we formally define
$$ \kappa_f(x) = \underset{\delta \rightarrow 0_+}{\lim} \kappa_f(x,\delta).$$
We will now discuss how the relative condition number imposes a hard limit on the accuracy which can be achieved when using $f(y)$ to approximate $f(x)$.
Let $\delta > 0$ and let $y \in \mathbb{R}$ be any number such that $0 < |x-y| < \delta|x|$. Then
\begin{equation}
       \left|\frac{f(x) - f(y)}{f(x)} \right| \leq \kappa_f(x,\delta)\left|\frac{x-y}{x} \right| \leq \kappa_f(x,\delta) \delta.
\end{equation}
Moreover, if $\delta$ is sufficiently small, then
\begin{equation}
    \kappa_f(x,\delta) \approx \kappa_f(x)
\end{equation}
is a good approximation. It follows that we cannot expect that the relative error is smaller than
\begin{equation}
       \left| \frac{f(x) - f(y)}{f(x)}\right| \approx \kappa_f(x)\left|\frac{x-y}{x}\right|.
\end{equation}
It is painful to compute the condition number directly from the definition. However, if $f$ is also differentiable, then
$$ \kappa_f(x) = \left| \frac{xf'(x)}{f(x)} \right|.$$
In particular, if $f : (0,\infty) \rightarrow \mathbb{R}$ is given by $$f(x) = x^p,$$ where $p \ge 0$, then $$ \forall x \in (0, \infty) \: : \: \kappa_f(x) = p.$$
In the case of $p \in [0,1)$ we see that the application of $f$ diminishes the relative error on the input and produces output which is more accurate than the input. This is as good as it gets and such a function $f$ certainly deserves to be classified as well-conditioned in the relative sense.
Comment: @user551155 Thank you very much for your kind words. The abstract approach extends to absolute case as well as vector functions of multiple variables. It gets more technical, but the core idea is preserved, i.e., condition numbers measure the limit of the worst case behavior.  This is an [answer](https://math.stackexchange.com/a/3643352/307944) to a question on normwise condition numbers for vector functions of multiple variables. It gives the two best reference that I know.
Comment: Thanks so much Carl! This is really good stuff! I'd buy you a pint if I could:)

Finding where f is well conditioned


asp.net mvc core 2 select value is always 0 in view model

Question: I have a select in a view that always returns 0 to my view model, and I don't know why:
View Model:
// CreateLifeInsuranceViewModel.cs
using InsuranceListManager.Models.EntityFrameworkModels;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace InsuranceListManager.Models.ViewModels.Home
{
    public class CreateLifeInsuranceViewModel
    {
        [Required]
        public int CustomerId;

        public IList<CustomerModel> Customers { get; set; }

        [Required]
        public string InsuredPersonCPF { get; set; }
    }
}

Controller
public class HomeController
{
    public IActionResult CreateLifeInsurance()
    {
        var customers = (
            from c in _db.Customers select c
        ).ToList();

        var model = new CreateLifeInsuranceViewModel
        {
            Customers = customers
        };

        return View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> CreateLifeInsurance(CreateLifeInsuranceViewModel model)
    {
        if (ModelState.IsValid)
        {
            var category = _db.InsuranceCategories.Where(c => c.Id == InsuranceCategoryModel.LIFE_INSURANCE).First();

            var insurance = new InsuranceModel
            {
                CategoryId = category.Id,
                CustomerId = model.CustomerId
            };

            _db.Add(insurance);
            await _db.SaveChangesAsync();

            var lifeInsurance = new LifeModel
            {
                InsuranceId = insurance.Id,
                InsuredPersonCPF = model.InsuredPersonCPF
            };

            _db.Add(lifeInsurance);
            await _db.SaveChangesAsync();

            return RedirectToAction(nameof(Index));
        }

        return BadRequest(ModelState);
    }
}

View:
@model InsuranceListManager.Models.ViewModels.Home.CreateLifeInsuranceViewModel

@{
    ViewData["Title"] = "New Insurance";
}

New Insurance

<form asp-action="CreateLifeInsurance">

            Customer
            <select class="form-control" asp-for="CustomerId" asp-items="@(new SelectList(Model.Customers, "Id", "Name"))">
                <option value="">Select the customer</option>
            </select>

            Insured Person CPF
            <input type="text" class="form-control" asp-for="InsuredPersonCPF" placeholder="CPF" />

        <input type="submit" value="Create" class="btn btn-primary" />
        Cancel

</form>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

in the rendered HTML, the select has the correct values, as you can see in the screeshot:

But for some reason, the value that I receive from this select in the view model is always zero:

Also, the asp validation won't catch if I don't select any item from the select.
I've been researching this for the last 4 hours and found not a single similar issue around.
I am using Asp.Net MVC Core 2, .Net Core SDK 2.2, Windows 10 Pro and Visual Studio 2017 Community Edition.
Answer: You are seeing the value 0 because that is the default value of int.
When the form is submitted, the default model binder will try to read the form data and assign the values to the corresponding properties of the view model object. Model binder will be able to successfully do so if CustomerId is a property and the property is settable.
In the code you shared, you are not creating a property but a field. Hence the model binder cannot set the value for that.
To fix the problem, change the CustomerId property to be settable by specifying the set and get property accessors.
[Required]
public int CustomerId { set; get; }

Comment: its not exactly about "property being settable" but the fact that it needs to be a property while he has used a field. you are not wrong, just the terminology
Comment: It has to be a property with `set` property accessor for model binder to set the value. `public int CustomerId {  get; }` will not work even though it a property.
Comment: Agreed. It is surely worth mentioning that the property needs to be set as well. I was just mentioning, we can't call his refer to his `CustomerId` field as a "property without set".
Answer: The problem in my case was that i forgot to edit Bind attribute (ref: https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.bindattribute?view=aspnet-mvc-5.2) that was left there when I scafollded my controllers.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("Id,Name,BenchmarkScore,PicturePath,Price")] PcComponentItemVM componentVM)
    }
    {

Answer: Just add the name attribute to the element:
<select class="form-control" asp-for="CustomerId" name="Model.Customers.CustomerId" asp-items="@(new SelectList(Model.Customers, "Id", "Name"))">
    <option value="">Select the customer</option>
</select>


Session variable is not displayed online but displayed locally

Question: In the bellow code i have printed a session variable on the output page
<?php ob_start();
session_start();
include("database.php");
include("tracking-header.php");
?>

Sorry

The Vehicle number <?php print $_SESSION['vehicleno']; ?>, not found.
please try again.

<input type="button" value="BACK" name="back" style="float:left;margin:17px 25px 16px;"  />
<?php include("tracking-footer.php");?>

in this print $_SESSION['vehicleno']; is displayed on local but when i upload this file online and then this is not displayed on the page. can any one say what is the problem in it?
Comment: where in the code have you set this session variable?
Comment: When is the $_SESSION variable being created? Have you verified that it is being created correctly?
Answer: Try by switching place of ob_start and session_start function like below
<?php
session_start();
ob_start();
include("database.php");
include("tracking-header.php");
?>

Sorry

The Vehicle number <?php print $_SESSION['vehicleno']; ?>, not found.
please try again.

<input type="button" value="BACK" name="back" style="float:left;margin:17px 25px 16px;"  />
<?php include("tracking-footer.php");?>

Comment: @Hardeep Pandya Do you mean session won't work if it not at first line
Comment: @PavanKumar I just said to try in this way. That doesn't mean session_start wont work if after ob_start function.


In finitely generated group, if $\{H_n\}_{n \in \mathbb{N}}$ is an infinite sequence of distinct cyclic group then $\cap{H_n}=\{e\}$.

Question: I think it is true. But I don't know the proof. And what about in countably generated group? More general, in which group it is true. Any kind of help will be appreciable.
Comment: For the countably generated case consider $G=\Bbb Q$ and $H_n=\frac1n\Bbb Z$.
Comment: Ok, Good. But what about in a finitely generated group?
Comment: Every countable group embeds into into a finitely generated group. Hence from the previous countable example you could deduce mechanically a finitely generated one. For instance, in the Baumslag-Solitar group $BS(1,m)=\langle t,x| txt^{-1}=x^m\rangle$ for given $m\ge 2$, take $H_n=\langle t^{-n}xt^n\rangle$.
Comment: It's true in every group in which every nontrivial cyclic subgroup has a cyclic centralizer. This holds in torsion-free hyperbolic groups, among others.
Answer: Let
$$G=\Bbb Z\rtimes\Bbb Z$$
as induced by the only non-trivial action,
or if you prefer
$$G=\langle \,a,b\mid ba=a^{-1}b\,\rangle,$$
or completely down to earth:
$$G=\Bbb Z\times \Bbb Z$$ with multiplication rule
$$ (a,b)\cdot (c,d):=(a+(-1)^bc,b+d).$$
Now let $H_n$ be generated by $(n,1)$. Then $(n,1)\cdot(n,1)=(0,2)\in H_n$ for all $n$.
Comment: Thanks for the beautiful example.


How to make expandable boxes when hovered over?

Question: I am currently trying to make a few divs or boxes open and animate downward when hovered over. I went onto bootstrap docs and see no way to do it on their docs. I was thinking maybe using JS to do the job, but i dont have much knowledge regarding JS, and i went online to see if i could find some clues n what kind of JS i could use to make them expand on hover, and remain collapsed when not hovered.

What you Get

        Our Services

Unique Orders, Unique Adventures

Your vision, our creation. Explore Cherrybery Studios' unique order service, where you can request
            custom mods tailored to your preferences. Elevate your gaming experience with personalized addons and
            plugins.

Gaming Beyond Boundaries

Join the adventure with Cherrybery Studios' game servers. Immerse yourself in a world where passion
            meets innovation. Explore unique gameplay experiences hosted on our servers and redefine your gaming
            journey.

Crafting Your Perfect Experience

Embark on unparalleled gaming adventures with Cherrybery Studios' meticulously crafted mods, plugins,
            and addons, introducing innovative features and seamless integrations to elevate and enrich your
            favorite games.

Curated Theme Packs

Dive into themed gaming with Cherrybery Studios' curated theme packs. Experience a fusion of mods,
            plugins, textures packs, integrations, and addons designed around many different specific themes or
            genres!

Answer: Is this what you're looking for (see interactive snippet below)?
Using the mouseover and mouseout event listeners, the blue div expands when hovered over, and returns to its original size when the mouse leaves its bounds.  The rate at which the div expands or contracts is proportional to the distance remaining before it reaches its maximum or minimum height. This gives a "snappier" looking animation than if the height were to change at a constant rate.
It should be pretty straightforward to customize this, like tweaking the expand/contract rate, adjusting the min/max height of the div (remember to change the starting value in the style element as well as the values in the script!), or extending the functionality to multiple boxes using getElementsByClassName instead of getElementById.

var expandingBox = document.getElementById("expanding");
var boxHeight = {min: 60, max: 250, current: 60};

// Return a value which does not exceed the specified bounds (this is modeled on the p5.js constrain() function)
function constrainedValue(val, minV, maxV) {
    return (val < minV) ? minV : ((val > maxV) ? maxV : val);
}

function expand() {
    if (boxHeight.current < boxHeight.max) {
        expandVelocity = Math.max(0.1*(boxHeight.max - boxHeight.current), 1);
        boxHeight.current = constrainedValue(boxHeight.current + expandVelocity, boxHeight.min, boxHeight.max);
        expandingBox.style.height = boxHeight.current + "px";
        boxHeight.expandTimer = setTimeout(expand, 10);
    }
}

function contract() {
    if (boxHeight.current > boxHeight.min) {
        contractVelocity = Math.max(0.1*(boxHeight.current - boxHeight.min), 1);
        boxHeight.current = constrainedValue(boxHeight.current - contractVelocity, boxHeight.min, boxHeight.max);
        expandingBox.style.height = boxHeight.current + "px";
        boxHeight.contractTimer = setTimeout(contract, 10);
    }
}

expandingBox.addEventListener("mouseover", function() { if (boxHeight.contractTimer !== undefined) { clearTimeout(boxHeight.contractTimer); boxHeight.contractTimer = undefined; } expand(); });
expandingBox.addEventListener("mouseout", function() { if (boxHeight.expandTimer !== undefined) { clearTimeout(boxHeight.expandTimer); boxHeight.expandTimer = undefined; } contract(); });
#expanding {
    background-color: lightblue;
    overflow: hidden;
    height: 60px;
    width: 50%;
    padding-left: 2%;
}

 Hover over the blue box to expand it.  The box will return to its original size when the mouse is removed.

            A quick brown fox jumped over the lazy dog.

            Peter piper picked a peck of pickled peppers.

            She sells seashells by the seashore.

            You'll be able to see this line once the box has expanded.


Is $X_n = o_p(\sqrt{n})$ equivalent to $X_n = O_p(1)$?

Question: Suppose $X_n = o_p(\sqrt{n})$, I want to show it is equivalent to $X_n = O_p(1)$.
Since $X_n = o_p(\sqrt{n})$, we have $X_n = \sqrt{n} o_p(1)$. Since $\sqrt{n}=O_p(1)$, we have $X_n = O_p(1)O_p(1) = O_p(1)$.
Conversely, suppose $X_n = O_p(1)$, then $\frac{1}{\sqrt{n}}X_n = \frac{1}{\sqrt{n}}O_p(1) = o(1)O_p(1)$, which implies $\frac{1}{\sqrt{n}}X_n =o_p(1)$, i.e. $X_n =o_p(\sqrt{n})$.
I used the fact that $\sqrt{n}=O_p(1)$ and $\frac{1}{\sqrt{n}}=o(1)$ in above argument. However, while knowing $\sqrt{n}=O(1)$ is incorrect for sure, I highly doubt $\sqrt{n}=O_p(1)$.
Answer: Careful! The equivalence you are trying to prove is actually not true!
First, let's tackle the proof you provided: unfortunately we have that $\sqrt{n}≠O_p(1)$, so the proof for $X_n = O_p(1)$ if $X_n = o_p(\sqrt{n})$ is not correct.
To verify that this is the case we can just show that $\sqrt{n}$ does not satisfy the definition for being in $O_p(1)$. This is evident because for any $M$ when we take $n$ big enough we have that
$$\mathbb{P}\left(\frac{\sqrt{n}}{1}>M\right) = 1,$$
as $\sqrt{n}$ diverges to $\infty$, which implies what we wanted to prove.
However, it turns out that the statement is false. Consider the sequence of random variables $X_n = n^{1/4}$. Then we have both that $X_n = o_p(\sqrt{n})$ and that $X_n ≠ O_p(1)$. Once again, to prove these facts we can just verify that the sequence satisfies the definitions.
The proof that $X_n ≠ O_p(1)$ is very similar to the proof that $\sqrt{n} ≠ O_p(1)$: just replace the square root by the fourth root.
Then we just need to prove that $X_n = o_p(\sqrt{n})$. But that happens because
$$\frac{X_n}{\sqrt{n}}=\frac{1}{n^\frac{1}{4}}$$
so in particular the sequence converges almost surely (and then in probability) to 0.
As a remark, some intuition that may prove useful in making sense of this: note that $o_p(\sqrt{n})$ could be thought of as "a little bit smaller than $\sqrt{n}$...", but since that sequence diverges there are many other sequences in between constant sequences and this one that also fall in this category, some of which diverge. I got my example thinking about this, but other sequences can also be proposed: $n^\alpha$ with $\alpha < \frac{1}{2}$, $\log(n)$, and many others.
Finally, the proof for the other implication is indeed correct, and it does hold that $O_p(1) \subseteq o_p(\sqrt{n})$.


Minimum number of money to make each element in list greater than or equal to 0?

Question: Given list with positive and negative integers.We have to make each element greater than or equal to zero.There are two types of moves first increase all elements by 1 requires P unit of money, second increase a particular element by 1 requires 1 unit of money.
Find the minimum unit of money to make all elements greater than or equal to zero.
Integers limit $(-10)^9$ to $10^9$
List length - $10^5$
Answer: Why not just find the most negative element and increase all elements by $1$ enough times to get to zero?  This is the minimum number of steps, though there may be other equally short paths.
Added: now that we are given that increasing all elements costs $P$, we are better off increasing all as long as there are more than $P$ that are negative.  When exactly $P$ are negative, it is a breakeven, and when less are negative it is cheaper to increase them individually.  So the new algorithm is: 1)find the $P^{\text{th}}$ most negative element. 2)increase all until it is zero 3)increase all the remaining negative ones individually until they reach zero.
Comment: But the OP wanted to minimize the *cost* of getting all the numbers to be nonnegative. With the list $\langle\,-7, -2, -1\,\rangle$, increasing all would cost $7P$, but increasing each individually would cost $7+2+1$ so if $P\le 10/7$ your technique would be cheapest, but if $P>10/7$ the second would be cheaper. It gets even more complicated....
Comment: @RickDecker:  That wasn't part of the question when I answered it.  I'll update.
Comment: i am sorry for updating the question  after your answer Ross


Where can i find a good example of archiving objects for persistence for the iphone sdk

Question: I have an object that contains about half a dozen properties. I expect to save maybe a dozen or more of these objects to my documents folder. My solution is to save the data using NSEncoding and NSKeyed/Archiver/Unarchiver. Anyone have a better strategy or approach.
Answer: NSKeyedArchiver/Unarchiver will work fine. If each file only has a half dozen properties, you might consider whether putting the entire object list in one file would be simpler for you to load/save/keep consistent.


How can I get the Style Name of a vsf file (VCL Style file)?

Question: I have an application written  in delphi-xe2, now i'm adding VCL styles support, So i want to build a menu to choose the vcl style file to load and apply, this part is working fine , the menu is build in runtime based in the content of a folder which has the style files. But now I want to display the name of the vcl style instead of filename just like this image

How I can get the name of the style of an vcl style file?
Answer: You can use the TStyleManager.IsValidStyle function, passing a TStyleInfo record which return this and another info related to the vcl style.
Check this sample app
{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  Vcl.Styles,
  Vcl.Themes;

var
 Style : TStyleInfo;
begin
  try
    if TStyleManager.IsValidStyle('C:\Users\Public\Documents\RAD Studio\9.0\Styles\RubyGraphite.vsf', Style) then
    begin
       Writeln(Format('Name           %s',[Style.Name]));
       Writeln(Format('Author         %s',[Style.Author]));
       Writeln(Format('Author EMail   %s',[Style.AuthorEMail]));
       Writeln(Format('Author URL     %s',[Style.AuthorURL]));
       Writeln(Format('Version        %s',[Style.Version]));
    end;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  readln;
end.


How to prove that $C(\mathbb{R})$ does not have the Heine-Borel property

Question: The space $X=C(\mathbb{R})=\{f:\mathbb{R}\to\mathbb{C}: f \text{ is continuous}\}$ is metric (not normed) and a Frechet space. I want to show that this space does not satisfy the Heine-Borel property (which means that any closed and bounded subset of $X$ is compact)
I feel like the collection $\{\exp(2\pi inx):n\in\mathbb{N}\}$ is a suitable candidate for a counterexample, since it is clearly bounded. How can I show that this set is closed, but not compact in the topology generated by the metric?
Comment: What metric are you using?
Comment: Or if it's easier to describe, what countable family of seminorms are you using?
Comment: If you show the sequence has no convergent subsequence, this will show it is closed (because it has no limit points) and not compact (by Bolzano-Weierstrass).
Comment: I'm going to guess that $\|f\|_k=\sup_{x\in[-k,k]}|f(x)|$.
Answer: I'm going to guess that $\|f\|_k=\sup_{x\in[-k,k]}|f(x)|$. If $m<n$, then $$\exp(2\pi inx)-\exp(2\pi imx)=\exp(2\pi imx)\Big(\exp(2\pi i(n-m)x)-1\Big)\;,$$ which at $x=\frac1{2(n-m)}$ is $-2\exp\left(\frac{\pi im}{n-m}\right)$. Let $f_n(x)=\exp(2\pi inx)$; then $\|f_n-f_m\|_k=2$ for all $k\in\Bbb Z^+$, and $\|f_n-f_m\|_0=0$, so $$d(f_n,f_m)=\sum_{k\ge 1}\frac{\|f_n-f_m\|_k}{1+\|f_n-f_m\|_k}2^{-k}=\frac23\sum_{k\ge 1}2^{-k}=\frac23\;.$$ Clearly $\langle f_n:n\in\Bbb N\rangle$ can have no Cauchy subsequence and hence no convergent subsequence.
Comment: @MarianoSuárez-Alvarez This is boring and not challenging :) Brian M. Scott (+1).
Comment: It is simpler to just pick any non-zero function with support contained in $[0,1]$ and consider the set of its integer translates.
Answer: $f_k = k$ on $supp(f_k)=[k-1,k]$.
$V_n= \{|f|_n<n\}$ is an open cover of $\{f_k\}$ $(f_k\in V_{k+1}\ )$ with  no finite subcover.


Infinite Matrices

Question: Does anyone know how to prove that the set of all $K\times K$ column finite matrices over a ring $R$ $[\mathrm{CFM}(R)]$ forms a ring? I am also confused about the definition of multiplication in $\mathrm{CFM}(R)$? Is it the standard matrix multiplication?
Answer: Yes, multiplication is the standard matrix multiplication in the sense that if the matrices are indexed by $K \times K$, then $\sum_{j\in K} a_{ij}b_{jk}$ gives the $i,k$ entry of the product matrix.
You can either show this makes a multiplication directly, and that would not be substantially different from proving that sets of square matrices are rings under matrix multiplication. Or else you can work to show that it is just a matrix representation of $End(V_F)$ where $V$'s dimension is the cardinality of the set $K$ indexing the rows and columns of your matrices.
You would view the matrices as acting on the left of column vectors representing the coordinates for your vector space. The proof is not substantially different from the one you might use for the finite dimensional case.
Comment: How do you show that if $A, B \in CFM(R)$, then $AB$ is still a column finite matrix?
Comment: @CalebParks You can view the product $AB$ as the columns of $B$ combining columns of $A$. A finite linear combination of columns with finitely many nonzero entries produces another column vector with finitely many nonzero entries.
Comment: @CalebParks Alternatively you can use the definition of multiplication directly, as Matt describes.
Answer: Multiplication of $A=(A_{ij})$ and $B=(B_{ij})$ is defined by
$$(AB)_{ij}=\sum_{k=1}^{\infty}{A_{ik}B_{kj}}$$
Since $B_{kj}=0$ for sufficiently large $k$, this is well defined.
To see that it is column finite, note that with fixed $j$ the $A_{ik}$ for which $B_{kj}$ is not zero will vanish for sufficiently large $i$.
Associativity is a pain to prove directly, but straightforward. Addition is easily shown to turn the set into an abelian group, and what's left is to check if the distributive laws hold, which you should be able to do.
Comment: How do you show that if A,B∈CFM(R), then AB is still a column finite matrix?
Comment: See edit please.

Infinite Matrices


conda environment broken after deactivate/activate

Question: I am new to conda and am using conda environments in Ubuntu 16.04 for the first time and have come across an issue which I cannot find a solution for.
Starting with a basic miniconda installation I create an environment and install the packages I require for this project. I then run my code and everything works with no errors.
If I then deactivate the environment and activate it again my code does not work. I have libraries which cannot be found.
The only solution I have so far is to create a new environment each time and install the required packages again.
This is the process I use to create the environment etc:
$ conda create --name env
$ source activate env
$ conda install (theano, tensorflow, keras, other required packages)
$ (run scripts to train a cnn, this works without any issues)
$ source deactivate
$ source activate env
$ (run same script as above, does not work, cannot find -lcudnn)

I only get to the last line shown below before I start to experience issues. Theano cannot find -lcudnn even though it worked without any issue when the environment was first created.
from __future__ import absolute_import
from __future__ import print_function

import sys
import os
os.environ['KERAS_BACKEND'] = 'theano'

import pylab as pl
import matplotlib.cm as cm
import itertools
import numpy as np
import theano.tensor as T

Any help would be much appreciated.
Comment: My command for creating the environment is 'conda create --name env', I start the environment 'source activate env', Install relevant packages such as theano and keras, run my code to train a dnn' deactivate with 'source deactivate', reactivate in the same way and run the same code and theano cannot find -lcudnn
Comment: Can you please show the exact commands that you use, and show your code?
Comment: Can you please show the actual code that generates the error message?
Comment: I have updated the question above to show the code which causes issues. Thanks.
Answer: I had the same issue and in my case updating the conda solved the problem.
conda update -n base -c defaults conda


Whenever i try run my python code with pygame the window opens and then stops responding after a second or any input

Question: heres all the code i have currently, it is just a start of a pacman game i am creating all that should be shown is a tab with press space to play
ive looked at previous responses to similar questions and i have what i should need to make it work but it still doesn't... i hope someone can help, thanks.
import os
import sys
import pygame

Start_window_font = 'arial black'

pygame.init()
vector=pygame.math.Vector2

class RPMGame:
    def __init__(self):
        self.screen = pygame.display.set_mode((450, 600))
        self.clock = pygame.time.Clock()
        self.running = True
        self.state = 'startwindow'
        self.load()
        self.node_width = 450//25
        self.node_height = 600//30
def run(self):
    while self.running:
        if self.state == 'startwindow':
            self.startwindow_events()
            self.startwindow_update()
            self.startwindow_draw()
        if self.state == 'gaming':
            self.gaming_events()
            self.gaming_update()
            self.gaming_draw()
        #fps
        self.clock.tick(60)
    pygame.quit()
    sys.exit()

def draw_text(self, words, screen, position, size, colour, font_name, centered = False):
    font = pygame.font.SysFont(font_name, size)
    text = font.render(words, False, colour)
    text_size = text.get_size()
    #centering the starting text##
    if centered:
        position[0] = position[0]-text_size[0]//2
        position[1] = position[1]-text_size[1]//2
    screen.blit(text, position)

def load(self):
    self.gameboard = pygame.image.load('pacmanmaze.png')
    self.gameboard = pygame.transform.scale(self.gameboard, (450, 600))

def draw_maze(self):
    for x in range(450//self.node_width):
        pygame.draw.line(self.screen, 107,107,107, (x*self.node_height, 0), (x*self.node_width, 600))

def startwindow_events(self):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            self.running = False
        ###key used to start game##
        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            self.state= 'gaming'

def startwindow_update(self):
    pass

def startwindow_draw(self):
    ####colour of background##
    self.screen.fill(0,0,0)
    ##start game text (text, position, text size, colour, centering)##
    self.draw_text('CLICK TO START GAME', self.screen, (225,300), 16,(255,0,0),
    Start_window_font, centered= True)
    self.draw_text('HIGH SCORE', self.screen, [5,0] ,(225,300), 16,(255,255,255),
    Start_window_font)
    pygame.display.update()

def gaming_events(self):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            self.running = False

def gaming_update(self):
    pass

def gaming_draw(self):
    self.screen.blit(self.gameboard, (0,0))
    self.draw_maze()
    pygame.display.update()

game = RPMGame()
game.run()

**edit
i realised that i forgot to change the variable for one of my states which was needed for the stop part
Comment: the initial state is `'begin'`, but you are not checking for that state anywhere so it will skip all of the `if` statements in the main loop and just call the clock tick... forever (until the program is forcibly stopped)
Comment: The indentation in the shown code is incorrect. Every function after the constructor is not part of the class. Also, I highly doubt you'll need 60fps for a basic pacman game
Answer: You have a number of minor issues.  When the app started and then immediately stopped, did you not notice that you're getting syntax and runtime errors on the console?
In this line:
self.screen.fill(0,0,0)

fill accepts one parameter, which is an RGB tuple:
self.screen.fill((0,0,0))

You have the same problem in draw_maze:
        pygame.draw.line(self.screen, 107,107,107, (x*self.node_height, 0), (x*self.node_width, 600))
... should be ...
        pygame.draw.line(self.screen, (107,107,107), (x*self.node_height, 0), (x*self.node_width, 600))

Then, in this call:
    self.draw_text('HIGH SCORE', self.screen, [5,0] ,(225,300), 16,(255,255,255),

I don't know what the [5,0] was trying to do, but draw_text isn't expecting that parameter.  Just remove it.
Then, in this code:
    if centered:
        position[0] = position[0]-text_size[0]//2
        position[1] = position[1]-text_size[1]//2
    screen.blit(text, position)

you pass in position as a tuple.  You can't modify a tuple.  You need to build a new tuple, or just change to a list:
        pos = list(position)
        if centered:
            pos[0] = pos[0]-text_size[0]//2
            pos[1] = pos[1]-text_size[1]//2
        screen.blit(text, pos)

With that, your app at least starts for me.


É correto declarar métodos GET/SET dentro de uma classe STRATEGY?

Question: Fiquei com uma dúvida quando fui criar um padrão de projeto do tipo Strategy. É correto declarar métodos GET e SET em uma classe que implementa uma interface Strategy? Não sei se fui bem claro, segue o exemplo:
Strategy:
public interface Strategy {
    String getNome();
}

Classe Imovel:
public abstract Imovel {
    protected String nome;

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }
}

Classe utilizando padroes Factory e Strategy:
public class Apartamento extends Imovel implements Strategy {

    public Apartamento() {
        tipo = "apartamento";
        status = "disponivel";
    }

    @Override
    public float getNome() {
        //TODO
    }
}

Answer: TL;DR
Não é necessário declarar getters e setters para nenhum objeto, a menos que você pretenda usá-los.
Dito isto, há várias coisas que você precisa entender sobre o Java, Orientação a Objetos e os padrões citados na pergunta para então conseguir compreender a resposta para a pergunta.
Problemas
Padrões Strategy e Factory
O exemplo da pergunta não implementa o padrão Strategy. Esse padrão consiste em que a superclasse implemente um algoritmo e um ou mais passos desse algoritmo são implementados pelas subclasses. Apenas usar uma interface não é o mesmo que implementar o padrão de projeto.
Um exemplo de Strategy:
abstract class PizzaMaker {
    public Pizza fazerPizza() {
        Pizza pizza = new Pizza();
        adicionarCobertura(pizza);
        Forno.assar(pizza);
        return pizza;
    }
    abstract void adicionarCobertura(Pizza pizza);
}

Então você pode implementar as diferentes estratégias de como cobrir uma pizza.
Exemplo
class MussarelaPizzaMaker extends PizzaMaker {
    void adicionarCobertura(Pizza pizza) {
        pizza.add("Molho");
        pizza.add("Mussarela");
        pizza.add("Orégano");
    }
}

E quanto ao padrão Factory, o exemplo da pergunta também  não o implementa, pois não há nenhum método que retorna um objeto.
No exemplo que eu coloquei acima, o método fazerPizza é um factory method e também pode-se considerar que essa classe implementa o padrão Factory porque cada subclasse vai retornar um tipo diferente de pizza.
Portanto, esse exemplo mostra como usar os padrões Strategy e Factory em conjunto.
Outros problemas
No seu exemplo há alguns erros e problemas.
Por exemplo, o método getNome em Apartamento tenta sobrescrever o getNome de Imovel, porém o tipo de retorno muda. Isso não é possível em Java.
Além disso, não faz muito sentido sobrescrever o método nesse caso sendo que ele já vai ser herdado pela classe Apartamento. A não ser, é claro, que houvesse algo diferente no novo método, o que não parece ser o caso.
Um problema conceitual com o exemplo é que não me parece muito razoável aplicar os padrões Strategy e Factory em classes que aparentam ser classes de domínio, gerando assim uma hierarquia de tipos.
Seria melhor ter os seus tipos básicos sendo POJOs, com getters e setters necessários, depois implementar outras classes para atuar como fábricas e ainda outras classes para implementar algoritmos possivelmente usando diferentes estratégicas. Claro que existe exceção para tudo, mas em geral é assim que se faz para evitar classes com múltiplas responsabilidades.
Enfim, classes de domínio como Imovel não necessariamente precisa de subtipos para cada tipo de imóvel. Isso pode ficar bonito no diagrama para mostrar ao professor ou cliente, mas na prática é um pesadelo de manutenção.
Ter um atributo tipo e alguns atributos opcionais geralmente é mais que suficiente para lidar com pequenas variações a não ser que no contexto do seu sistema cada tipo de imóvel seja um cidadão de primeira classe, isto é, possa ter regras de negócio distintas e um ciclo de via próprio.


Por que NaN é maior que qualquer número?

Question: Um exemplo prático dessa afirmação é:
parseInt(50) > parseInt('a');

Ao executar essa operação em um console, por exemplo, o resultado é false.
O código real que me trouxe a essa questão é parecido com esse:
variableB = parseInt(jQuery('some-element').html());
if(parseInt(variableA) > variableB)
     // Faça isso.
else
     // Faça outra coisa.

As vezes o some-element não vai ser preenchido com absolutamente nada, causando o valor de variableB ser NaN. Mas como some-element não foi preenchido com nada, eu gostaria que fosse avaliado como se tivesse sido preenchido com 0. Ou seja, se variableA for um positivo maior que 0, a comparação deveria retornar true.
Comment: Você poderia colocar uma condição com NaN ou apenas um 'e' no if
Comment: Pergunta no SO inglês -> http://stackoverflow.com/questions/26982881/why-nan-is-greater-than-any-number-in-javascript
Comment: Não seria bom colocar a referência do link na própria pergunta?
Answer: Com base na pergunta do SO Inglês que você "copiou"
Edit -
Com base na pergunta do SO Inglês que você "fez lá e aqui"
https://stackoverflow.com/questions/26982881/why-nan-is-greater-than-any-number-in-javascript
Verificações com NaN sempre dão FALSE.
NaN não é maior que nenhum número
NaN não é igual que nenhum número
NaN não é menor que nenhum número
Apenas a verificação booleana será false.
Comment: Ah, então assim sim.
Comment: Ééééééé José!!!!! Ta certo!
Comment: [Introduzindo conteúdo relevante ao site](http://meta.pt.stackoverflow.com/a/2171/1544), [Perfil de Pergunta](http://meta.pt.stackoverflow.com/questions/4285/stack-overflow-perfil-de-pergunta) e [Geração de Conteúdo](http://meta.pt.stackoverflow.com/questions/115/%C3%89-util-fazer-perguntas-que-geram-conte%C3%BAdo-para-a-net)


How do I restore the comment body field I deleted from a content type?

Question: I deleted the comment body from the content type settings, and replaced it with  another field. When posting comments, I get this error:

Notice: Undefined property: stdClass::$comment_body in function comment_submit() (line 2201 in file /modules/comment/comment.module).

Can this error be avoided?
It was needed to delete the field comment_body becase field permissions are inherited for all the content types and that is why another field was created and this one was deleted.
Comment: Yes, despite the comment body is a field that can be removed from the UI, the Comment module assume the field is always present.
Comment: Oh, it is a little bit confusing. Can it be fixed in any way?
Comment: Did you try making a field with same machine name and type?
Comment: In this case I need to delete the field comment_body becase field permissions are inherited for all the content types and that is why I created another field and deleted this one. Yes, if I add it back, it is restored but this action doesn't completely solve the problem.
Answer:
Create a random content type
Restore the comment_body field from existing field`s, because it's existing now
Delete the random content type
Comment: I need to delete the field comment_body becase field permissions are inherited for all the content types and that is why I created another field and deleted this one
Comment: You can turn off required option on the field comment_body and hide via css.
Another solution https://www.drupal.org/node/1038652#comment-10968421
Comment: I tried to do the same but with 'author' and 'subject' fields but non of them are in the 'Select an existing field' list. Any ideas?
Answer: There is also a patch which actually needs review in Drupal Core concerning this issue: https://www.drupal.org/node/2717717
I applied it and it works.
Answer: First delete that field and clean Drupal's Cache, if that doesn't work just try to use this patch:
https://www.drupal.org/files/issues/1038652-comment-body-field-95-test-and-fix-D7.patch
Comment: I need to delete the field comment_body becase field permissions are inherited for all the content types and that is why I created another field and deleted this one
Answer: I recovered comments with recreating the tables (take care: all the comments will be removed):

comment,
field_data_comment_body,
field_revision_comment_body;

and reset statistics with:
UPDATE node_comment_statistics SET comment_count = 0;

Where to get SQL query to recreate them? Get it from another Drupal installation with comments.


Views 3: template suggestion file for header/footer parts?

Question: In Views 3, is there any type of template suggestion for header and footer parts of a view?
I know I can paste Full HTML into Global Header and Footer fields, but - as I have the main part themed in a tpl file - I'd also find it more comfortable to have the header/footer parts laid out in an external text file.
Comment: How can we get header and footer variables for view ? https://drupal.stackexchange.com/questions/273196/how-to-get-views-header-and-footer-in-view-block-template
Answer: There's no template that I know about, but nothing can stop you from overriding the header and footer values in a view's general template like views-view.tpl.php, or even include a separate file instead of outputing the variable directly.


Ratio of an increasing monotonic function and its integral is infinity

Question: Inspired by the fact that for functions at the form: $f(x) = \frac{1}{x^\alpha}$ where $\alpha \ge 1$, the intgeral: $\int_{0}^{1} f(x)dx$ diverges to $\infty$ , and the ratio: $\frac{f'(x)}{f(x)}$ approaches $-\infty$ as $x$ approaches zero (from the right), I developed the following hypothesis:
let $f: [0,1) \to \mathbb{R}$ be a continuous monotonic function such that $\int_{0}^{1} f(x)dx = \infty$, then $\lim_{x\to 1^{-}} \frac{f(x)}{\int_{0}^{x} f(t)dt} = \infty$, however I was unable to solve this problem completely, and wanted to ask for some help with it, here's what I got so far:
I know that if I define: $g(x) = \ln(\int_{0}^{x} f(t)dt)$, then: $g'(x) = \frac{f(x)}{\int_{0}^{x} f(t)dt}$, meaning the desired ratio is unbounded, I also know that if I define: $f(x) = \frac{1}{(1-x)^2}|\sin(\frac{1}{1-x})|$, then the desired limit does not exist, meaning I have to use the fact that $f(x)$ is monotonic, somehow in the proof, my guess, is that it implies  that the ratio is also montonic (because that also when happens with $f(x) = \frac{1}{x^\alpha}$), or at least that the ratio is monotonic from some point, and from there, the claim is obvious.
Answer: Assume that $f$ is positive and $\displaystyle\lim_{x\to 1^-} f(x) = +\infty$. Fix some $\varepsilon > 0$ then
$$
\frac{f(x)}{\int_0^{x}f(t)\, dt} = \frac{f(x)}{\int_0^{1 - \varepsilon}f(t)\, dt + \int_{1 - \varepsilon}^xf(t)\, dt}\ge \frac{f(x)}{\int_0^{1 - \varepsilon}f(t)\, dt + \varepsilon f(x)},
$$
hence we have
$$
\liminf_{x\to 1^-}\frac{f(x)}{\int_0^{x}f(t)\, dt}\ge \liminf_{x\to 1^-}\frac{f(x)}{\int_0^{1 - \varepsilon}f(t)\, dt + \varepsilon f(x)} = \frac{1}{\varepsilon}.
$$
The conjecture follows.
Comment: Yes, you are right the inequality $x > 1-\varepsilon$ is essential, it can be assumed since $x$ tend to $1$. And yes, the liminf is for the existence
Comment: Thanks a lot, I really struggled with this problem, I just a have a couple of small questions for clarification: 1) don't you also require that $1-\epsilon < x$?. 2) the reason you used lim inf instead of a regular limit was to ensure existence?
Comment: Great, thanks a lot, you really helped.


How do the random effects relate to the fixed effects in the output from a mixed model?

Question: When I run my output from the lmer function for random effects, I get something like this:
form_lmer1 <- "y  ~   1 + Var1 + (1+Var1 | group)"
fm3        <- lmer(as.formula(form_lmer1), df, REML=FALSE, verbose=TRUE)
ranef(fm3)
# $group
#      (Intercept)                    Var1
# 500  0.044211088           -0.0127878291
# 501 -0.047100911            0.0779782538
# 502  0.038150455           -0.0073571972
# 504  0.040368393           -0.0089280108
# 505  0.062128815           -0.0308154532
# 506  0.004291613            0.0265210988

Are these just the differences of the fixed effects / coefficients?
fixef(fm3)
#  (Intercept)                    Var1
#  0.970103582             0.001630575

So if I wanted to calculate the new coefficients by group, I would just add/subtract from the fixed effect?
Answer: You have the gist of it.  With a mixed model you are estimating a population distribution, which is assumed to be normal.
Consider a simple model with only an intercept (and a random effect for the intercept).  The 'fixed effect' for the intercept is the mean of the population, and the variance of the reported random effect is the population variance.  The fitting algorithm can further compute 'BLUP's for each group as a function of that group's data and the estimated model parameters.  (For more information, it may help to read my answer here: Why do the estimated values from a Best Linear Unbiased Predictor (BLUP) differ from a Best Linear Unbiased Estimator (BLUE)?)
If you add a slope to the model and fit random effects for that, you are assuming there is a population distribution of group slopes.  The fixed effects are the population distribution means, and the random effect variances are the variances of those distributions.
The regression line determined by the fixed effects for the intercept and slope is just the population mean, but that doesn't necessarily reflect the line that an specific individual group varies around.  To get the best guess for that line, you would add the fixed effect for the intercept with the BLUP for the intercept for that group, and compute the slope likewise.
In the outputted lmer object, you should be able to use coef(object), and get the summed fixed and random effects, or you can get the individually (as you do here), and sum them yourself.


Can nginx block ~20000 ips?

Question: Can nginx block ~20.000 ips?
And should i block ips (https://lists.blocklist.de/lists/all.txt) with nginx?
Answer: Theoretically yes, you could block those IPs by using the deny config option in nginx: e.g., with the file /etc/nginx/denyip.conf
deny 220.127.116.11;
deny 184.108.40.206/24;
deny 126.96.36.199;

And then in /etc/nginx/nginx.conf in your HTTP block
include denyip.conf;

However, you shouldn't really be blocking IP addresses with Nginx. It is much better to block them with your firewall, so they can't connect to your server at all, instead of being able to connect to everything but Nginx.
Comment: tx, makes sense now you mention it. So you would block them at the Ubuntu ufw level for instance or at the router level?

Can nginx block ~20000 ips?


An intuitive understanding for Möbius equivalent of totient function?

Question: $$\varphi(n)=\sum_{d\mid n}d\cdot \mu\left(\frac{n}{d}\right)=n\sum_{d\mid n}\frac{\mu(d)}{d}$$
This describes the totient function in terms of the Möbius function. I understand what the Möbius function does but I don't understand this derivation at all. Is there an easy way to understand why this is so?
I'm not looking for some lengthy mathematical proof, but rather an intuitive understanding. I've seen plenty of papers showing the proof, but I just don't get what's happening.
Comment: You may want to look at the [Principle of Inclusion-Exclusion.](http://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle)
Comment: @user51819: While I'm glad my answer was helpful, you don't have to accept my answer so quickly - there may be other perspectives on this identity (or simply better explanations of the one I described) that will be useful to you!
Comment: @ZevChonoles Sorry, I figured it was a sufficient explanation. Would you perhaps be willing to contribute an example of what you mean to make things even clearer? Say phi(24)?
Comment: "Möbius", or equivalently "Moebius", is the correct spelling.  "Mobius" is different.
Answer: $\varphi(n)$ counts the number of integers $k$ between $1$ and $n$ that are relatively prime to $n$.
The term $d=n$ gives us our starting value of $n\cdot\mu(\frac{n}{n})=n\cdot 1=n$, i.e. all of the integers $1\leq k\leq n$.
For each prime $p$ dividing $n$, the term $d=\frac{n}{p}$ throws out the multiples of $p$ from among the numbers between $1$ and $n$; specifically, there are $\frac{n}{p}$ multiples of $p$ between $1$ and $n$, and the $d=\frac{n}{p}$ term in the sum contributes $\frac{n}{p}\cdot\mu(p)=-\frac{n}{p}$.
Unfortunately, the result is still not quite right - for any distinct prime divisors $p_1$ and $p_2$ of $n$, we counted as if we had to remove multiples of $p_1p_2$ twice, when of course we only remove them once. The terms $d=\frac{n}{p_1p_2}$ correct for this, because they contribute $\frac{n}{p_1p_2}\cdot \mu(p_1p_2)=\frac{n}{p_1p_2}$, the number of multiples of $p_1p_2$ between $1$ and $n$.
But then we must account for the numbers between $1$ and $n$ that we originally triple-counted, and which our correction above over corrects for, etc. - the alternating nature of the Möbius function is what makes it do this the way we need.
Comment: I [answered](http://math.stackexchange.com/a/800180) a similar [question](http://math.stackexchange.com/q/800118) recently, and while searching for other answers, came across this answer, which also uses inclusion-exclusion. (+1)


WebService PHP+JSON - Como ler retorno

Question: Ola!
Pessoal, gostaria de entender como ler o retorno, com a seguinte estrutura:
$ws = array(

   'categoria' => array(
      array(
         'cat1' => array(
            'dado1' => $dado1,
            'dado2'=>$dado2
         ),
         'subcategoria'=>array(
            'dado3'=>$dado3,
            'dado4'=>$dado4,
         )
      ),
   ),
);

$json = json_encode($ws, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);

$url = 'https://link.com';
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Content-Length: ' . strlen($json),
"Content-Type: application/json",
));

$jsonRet = curl_exec($ch);
curl_close($ch);

Com o código acima realizo o envio. Agora como faço para extrair individualmente os dados de retorno?
Ele vem nesse formato:
{"data":{"nome1":João,"status":["ativo"]}}

Quero poder interpretar somente o status, ou o nome1, separadamente com php.
Answer: tente isso
$retorno = json_decode($jsonRet);
 $status = $retorno['data']['status'];
Comment: kkk espera ai eu q errei aqui o correto seria $status = $retorno->data->status; tente ai ai vc da um echo pra ver se imprime o valor
Comment: Testei assim:
 $retorno = json_decode($jsonRet);
 $status = $retorno['data']['status'];                                                                               echo $status;                                                                                * Mas não houve visualização, ocorreu erro na sintaxe...
Comment: dê um var_dump($retorno); e poste aqui o q foi exibido
Comment: Parse error: syntax error, unexpected '$retorno' (T_VARIABLE)
Comment: parece q a $jsonRet n esta retornando um valor; tente da um var_dump dela pra ver o q aparece
Comment: Eu havia esquecido de colocar o parenteses no var_dump(); Com o $retorno fica tudo em branco, nada aparece na tela. e com o $jsonRet aparece:     string(208) "{"data":{"nome1":João,"status":"[ativo]",
Comment: $retorno = json_decode($jsonRet); transforma o obj json em array... vc pode postar o código q gera o retorno?
Comment: Sim, coloquei nesse formato como você indicou no inicio, json_decode($jsonRet); Mas no var_dump() nada acontece, fica vazio a tela...nada aparece
Comment: Perfeito! =D ...Você pode colocar esse trecho como resposta? Assim marco como resolvido para finalizarmos
Answer: $retorno = json_decode($jsonRet);
 $status = $retorno->data->status;
Comment: Resolvido! Muito obrigado...

WebService PHP+JSON - Como ler retorno


Find all functions $f$ such that $f:\mathbb{R}\rightarrow \mathbb{R}$ and $f\big(f(x)-x+y^2\big)=yf(y)$.

Question:
Find all functions $f$ such that $f:\mathbb{R}\rightarrow \mathbb{R}$ and $$f\big(f(x)-x+y^2\big)=yf(y)\,.$$

If $y=0$ we get $f(f(x)-x)=0$.
If $b=f(1)$, then putting $x=y=1$ we get $\boxed{f(b)=b}$, so $f$ has a fixed point.
If $x=b$ we get $\boxed{f(y^2)=yf(y)}$ for all $y$, so pluging $y=0$ we get $\boxed{f(0)=0}$.

Nothing usefull really. Any idea how to do it?
Comment: If $f(f(x)-x+y^2) = g(y)$ then $f(x)-x = C$
Comment: If $f$ is continuous, then there are only two solutions: $f(x)=0$ and $f(x)=x$.  I am not sure yet how to deal with non-continuous case.
Comment: Oh, I was trying this problem yesterday when I found it [here](https://artofproblemsolving.com/community/c6h1953559_functional_equation). There's some solutions in that thread now - so I'm sure someone will eventually post one of those as an answer to this question.
Answer: Suppose $f:\Bbb R\to \Bbb R$ satisfies
$$f\big(f(x)-x+y^2\big)=yf(y)\tag{1}$$
for all $x,y\in \Bbb R$.  Plugging in $x,y=1$ in $(1)$, we get
$$f\big(f(1)\big)=f(1).$$
Hence, substituting $x=f(1)$ in $(1)$, we obtain
$$f(y^2)=yf(y).\tag{2}$$
This shows that $f(0)=0$ and for $y\ne 0$,
$$-yf(-y)=f\big((-y)^2\big)=f(y^2)=yf(y),$$
so $f(-y)=-f(y)$.  Hence $f$ is an odd function.
From $(1)$ and $(2)$, we get
$$f\big(f(x)-x+y^2\big)=f(y^2)$$
for all $x,y\in\mathbb{R}$. Substitute $-x$ for $x$ in the last equation and using the fact that $f$ is odd, we get
$$f\big(f(x)-x-y^2\big)=f(-y^2)$$
for all $x,y\in\mathbb{R}$.  Hence,
$$f\big(f(x)-x+y)=f(y)\tag{3}$$
for all $x,y\in\mathbb{R}$.
Define $P$ to be the additive subgroup of $\mathbb{R}$ generated by $\big\{f(x)-x\big|x\in\Bbb R\big\}$.  Then, we see that for any $z\in\mathbb{R}$ and $p\in P$, we have
$$f(z+p)=f(z).\tag{4}$$
Consequently $f$ is an odd periodic function which is invariant under translation by elements of $P$.
We claim that $P=f^{-1}(0)$.  First if $p\in P$, then $f(p)=f(p+0)=f(0)=0$, so $p\in f^{-1}(0)$.  Conversely, suppose that $p\in f^{-1}(0)$, then with $x=p$ in $(3)$, we have
$$f(-p+y)=f\big(f(p)-p+y\big)=f(y)$$
so that $p\in P$.
For each $p\in P$, we see that
$$f\left(\left(\frac{1+p}{2}\right)^2\right)=f\left(\left(\frac{1-p}{2}\right)^2+p\right)=f\left(\left(\frac{1-p}{2}\right)^2\right)$$
From $(2)$, we have
$$\frac{1+p}{2}f\left(\frac{1+p}{2}\right)=\frac{1-p}{2}f\left(\frac{1-p}{2}\right).$$
However
$$f\left(\frac{1+p}{2}\right)=f\left(\frac{1-p}{2}+p\right)=f\left(\frac{1-p}{2}\right).$$
This means
$$f\left(\frac{1+p}{2}\right)=0$$
for all $p\in P$ such that $p\ne 0$.      Hence, for $p\in P\setminus\{0\}$, $\frac{1+p}{2}\in P$, so $1+p \in P$, making $1\in P$.  This shows that either $P=\{0\}$ or $\mathbb{Z}\left[\frac12\right]\subseteq P$.
If $P=\{0\}$, then $f(x)-x=0$ for all $x\in \Bbb R$.  Therefore, $f(x)=x$ for every $x\in \Bbb R$.  This yields one solution of $(1)$.  From now on $P\neq \{0\}$.  Thus $\mathbb{Z}\left[\frac12\right]\subseteq P$.  We want to show that $P=\Bbb R$, so that $f(x)=0$ for every $x\in \Bbb R$, and this is another solution of $(1)$.
For an arbitrary $y\in\mathbb{R}$, we see that
$$f\left(\left(y+\frac{1}{2}\right)^2\right)=\left(y+\frac{1}{2}\right)f\left(y+\frac{1}{2}\right)=\left(y+\frac{1}{2}\right)f(y),$$
since $1/2\in P$.  That is
$$f\left(\left(y+\frac12\right)^2\right)=\frac{1}{2}f(y)+yf(y)=\frac12f(y)+f(y^2).$$
Consequently
\begin{align}f\left(\left(y+\frac12\right)^2\right)-\left(y+\frac12\right)^2&=\frac{1}{2}f(y)+f(y^2)-\left(y+\frac12\right)^2\\&=\left(\frac{1}{2}f(y)-y\right)+\left(f(y^2)-y^2\right)+\frac14.\end{align}
Because $f\left(\left(y+\frac12\right)^2\right)-\left(y+\frac12\right)^2$, $f(y^2)-y^2$, and $\frac14$ are all elements of $P$, we conclude that
$$\frac{1}{2}f(y)-y\in P.$$
Therefore,
$$\big(f(y)-y\big)-y=2\left(\frac{1}{2}f(y)-y\right)\in P.$$
As $f(y)-y\in P$, we get $y\in P$.
Comment: This is really nice answer. Don't know why didn't  accept and upvote it before. Perhaps I anticpated more elementary solution. But heck, this one is nice.
Comment: The whole point is the continuity. We have two properties to play with: 1. for any $x$, $f$ is periodic with period $d = f(x) - x$; 2. $f(x^2) = xf(x)$. I guess these suffice for determining $f$, but we need some more idea.


Android - Custom CursorAdapter keeps calling BindView when ViewFlipper flips

Question: I've built a custom CursorAdapter that needs to populate a ListView with tweets... Just simple date and tweet will be shown...
It works great, the only thing is that if I add a Log entry I notice that the BindView method is getting called continuously every 8 seconds for every item...Which corresponds with a ViewFlipper's flipDuration elsewhere on the screen...(Verified by changing the duration and seeing BindView being called with the new interval times)
The ViewFlipper does use the same layout xml as the ViewList and the same data (though I make 2 separate calls to the DB to load them in)
Is this normal behaviour?
Method that renders the List and Flipper:
public void loadTwitterFeed(){
    ListView twitterList = (ListView) findViewById(R.id.twitterList);

    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    dbHelper dbh = new dbHelper(this);

    dbh.openRead();

    twitterDbAdapter adapt = new twitterDbAdapter(this, dbh.getTweets());

    twitterList.setAdapter(adapt);

    ViewFlipper flipper = (ViewFlipper) findViewById(R.id.twitterFlipper);

    ArrayList<twitterTweet> tweets = dbh.getTweetsAsList();

    for( twitterTweet obj : tweets){

        View tItem = (View) inflater.inflate(R.layout.twitter_item, flipper, false);

        TextView tv1 = (TextView) tItem.findViewById(R.id.textView1);
        TextView tv2 = (TextView) tItem.findViewById(R.id.textView2);

        tv1.setText(obj.getDate());
        tv2.setText(obj.getText());

        flipper.addView(tItem);

    }

    dbh.close();

    flipper.setFlipInterval(5000);
    flipper.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left));
    flipper.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.slide_out_right));
    flipper.startFlipping();

}

My custom adapter:
public class twitterDbAdapter extends CursorAdapter{
private LayoutInflater inflater;

public twitterDbAdapter(Context context, Cursor cursor){

    super(context, cursor);
    inflater = LayoutInflater.from(context);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
    Log.i("extra","binding");
    TextView textView = (TextView) view.findViewById(R.id.textView1);
    TextView textView2 = (TextView) view.findViewById(R.id.textView2);

    textView.setText(cursor.getString(cursor.getColumnIndex("createdat")));
    textView2.setText(cursor.getString(cursor.getColumnIndex("tweet")));

}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    View view = inflater.inflate(R.layout.twitter_item, parent, false);
    return view;
}

}

Answer:
It works great, the only thing is that if I add a Log entry I notice
  that the BindView method is getting called continuously every 8
  seconds for every item

I doubt that bindView is called for all the items in the ListView, most likely the method is called for the visible items(plus a few extra calls).
As the ViewFillper flips through it's children Android needs to re-layout the current screen content, this is probably the cause for your bindView method being called at the ViewFlipper's switching interval. It shouldn't matter for you.
Answer: It's normal behavior, as Luksprog explained. Method bindView is called whenever a row needs to be displayed, each and every time. If you're concerned about performance (with lists and broad audience, you often should be) and don't change list's contents (rows) with each flip, you may want to consider overriding newView instead of bindView, if/where applicable, caching, etc.


Prove inequality involving integral

Question: The exercise consists of proving the following:
$$\frac{4}{21}\cdot 2^{3/4}  \leq \int_{0}^{\sqrt{\frac{\pi}{2}}}t^{2}\cos(t^{2})dt$$
With $1-\frac{x^{2}}{2} \leq \cos(x) , \forall  x\in [0,\pi ]  $ (already proven, got it from Taylor polynomials) my idea was to use something like this $x^{2} (1-\frac{x^{4}}{2})  \leq \int_{0}^{\sqrt{\pi /2}}t^{2}\cos(t^{2})dt$. The problem is I don't see any of either $4/21$ or $2^{3/4}$ showing up.
Any hint or tip on this?
Edit:
I have the solution for this but it seems odd to me.
Basically it goes from this
$$cos(x^{2}) \geq 1-\frac{x^{4}}{2}, \ for \ 0 < x < 2^{1/4} \\ cos(x^{2}) \geq 0, \ for \ 2^{1/4} \leq x \leq \sqrt{\pi / 2}$$
and then it proceeds with integration (but from there it's easy). These steps look random to me, plus $cos(x^{2})$ is always greater than $1-\frac{x^{4}}{2}$ so why separate into that two cases?
Answer: For simplicity, set $u=t^2$: $$\int_{0}^{\sqrt{\frac{\pi}{2}}}t^2\cos(t^2)~dt = \dfrac{1}{2}\int_0^{\frac{\pi}{2}}\sqrt{u}cos(u)~du \geq \dfrac{1}{2}\int_{0}^{\sqrt{2}} \sqrt{u}\cos(u)~du \geq \dfrac{1}{2}\int_{0}^{\sqrt{2}} \sqrt{u}\left(1 - \frac{u^2}{2}\right)~du$$
And I'm sure you can take it from here :)
Comment: That change from $\pi / 2 \ to \ \sqrt{2}$ is really badass, wow. I don't see myself coming with this in the middle of the test though (this was an exercise from a test) =(
Comment: As you've noticed, at first sight $2^{3/4}$ sounds weird as an outcome from the integral, but not that much when you realize that $u^{3/2}$ will appear after the integration, and  $2^{3/4} = (\sqrt{2})^{3/2}$...
Comment: And what about the solution I posted, do you have anything to say?

Prove inequality involving integral


Confused on how to approach this (writing a function, returning a string)

Question: So I have to write a function plusLettuce that accepts one parameter as an argument and the function has to return a string that has my argument and the phrase "plus lettuce". So I'm guessing if I type in plusLettuce("Onions"); into my console I should get "Onions plus lettuce" as my output.
This is what I have so far .. so I wrote my function with a parameter and I'm confused what to do next. (I'm a total noon sorry) Do I  make a variable word? I'm just stuck on what my next step has to be. Please help.
var plusLettuce = function(word) {
   var word =
}

Comment: @PauloAvelar that book is aimed at people who already know it.
Comment: If you're learning Javascript, I really recommend the book "Javascript: The Good Parts" (O'Reilly collection). This will help you learn it the right way. :)
Comment: The whole book, yes. But I wish I'd read it before learning a lot of wrong stuff. This is the kind of book you should read a first time and get 20% out of it, then read it again a year later and fill a lot of gaps. It may be really advanced, but the language and the line of thought is very straightforward.
Answer: You can use the addition operator + to concatenate strings, and the return statement to return the result of the function call:
var plusLettuce = function(word) {
   return word + " plus lettuce";
};
plusLettuce("Onions"); // "Onions plus lettuce"

Comment: @rockerest Yes, or also `word.trim() + " plus lettuce"`.
Comment: Could also use `word.slice( -1 )` or `word[ word.length - 1 ]` to check for a space at the end of the input and conditionally apply that leading space. Obviously not part of the question, but I figure it's good to be proactive?
Answer: JS uses + for string concatenation.
You're also overwriting your word (which is already there, in your function), when you declare a new var word.
So
function plusLettuce (phrase) {
  // I don't say `var phrase`, because it already exists
  var phrasePlusLettuce = phrase + " plus lettuce"; // note the space at the start
  return phrasePlusLettuce;
}

Answer: When you give a function a parameter, it automatically becomes a local variable for that function. Meaning that you can immediately use it as a variable too.
var plusLettuce = function(word) { // I take the var word from here...
   return word + ' plus lettuce'; // ...and then use it here.
};
console.log(plusLettuce('Onions')); // This is where I assign the var word.

So what's happening here is that I'm telling the plusLettuce function to return whatever the user gave as a parameter plus ' plus lettuce'. Then call it in the console.log();
Answer: In programming this is called string concatenation, what your been asked to do is make a static string concatenate with a dynamic one.
function plusLettuce (phrase){
  var staticWord = ' plus lettuce';
  return phrase + staticWord
}
console.log(plusLettuce('Onions'))

Remember that a parameter/argument is a variable accessible by the function only, the static part meaning it will always be the same can be a assign to a variable to keep the code clean. and the dynamic part which is the parameter will be different every time according to what is passed on to the function each time is called.


Dependent or Independent samples?

Question: I have an assignment where I have to determine if the samples are dependent or independent. The sample is of 100 people, where their reaction times from their dominate and non-dominate hands was recorded when an image is flashed in front of them. The results where recorded in seconds. Now because the hands are separate items and results not dependent on on the other ones outcome or reaction time I assume that they are independent. But my friend thinks because they come from the same person they are dependent—e.g., if you take one person away both samples would be effected so they are dependent. I'm so confused!
Comment: Do you have a data set to go along with this assignment?
Comment: The dependence you suggested is also called "repeated measurement" in which the same subject is measured again and again. Yet, dependence can exist in many forms, since both hands are connected to the same nervous system, they can also be considered as dependent. For instance, a younger person may have fast time in both hands, compared to an older subject.
Answer: Here's a hint: if your data points are all sampled independently, that means, roughly, that seeing one data point doesn't tell you anything about other, yet unseen data points (not counting what you learn by using the data to estimate the underlying model). So the question is, if you know somebody's reaction time with one hand, should that information be expected to have any bearing on their reaction time with the other hand?

Dependent or Independent samples?


mhddfs Gives Permission denied Error When Writing File to It's Mounted Volume

Question: Running mhddfs 0.1.38 on Ubuntu-12.04 and have two NFS volumes exported from two different servers and mounted to this box.  I can successfully create the mhddfs volume, I can read and list from it, but can not create or edit any files on it.  If I try to edit a file via it's NFS mountpoint, there is no problems; only via the mhddfs mount.
user1@mhddfs-1:~$ ls -l /mnt/virtual/
total 4
-rw-rw-r-- 1 user1 user1 1511 May  7 17:50 testfile.txt
user1@mhddfs-1:~$ echo "hello" >> /mnt/virtual/testfile.txt
-bash: /mnt/virtual/testfile.txt: Permission denied
user1@mhddfs-1:~$ echo "hello" >> /mnt/nfs1/testfile.txt
user1@mhddfs-1:~$ ls -l /mnt/virtual/
total 4
-rw-rw-r-- 1 user1 user1 1517 May  7 18:19 testfile.txt
user1@mhddfs-1:~$ mhddfs --version
mhddfs version: 0.1.38
user1@mhddfs-1:~$ tail -1 /etc/fstab
mhddfs#/mnt/nfs1,/mnt/nfs2  /mnt/virtual fuse defaults,allow_other,logfile=/var/log/mhddfs.log,loglevel=0 0 0
user1@mhddfs-1:~$ mount | grep mhddfs
/mnt/nfs1;/mnt/nfs2 on /mnt/virtual type fuse.mhddfs (rw,allow_other)
user1@mhddfs-1:~$

I have debugging turned on for logging and the only relevant entries are:
mhddfs [2015-05-07 17:50:43]: [140344990897920] mhdd_stat: /testfile.txt
mhddfs [2015-05-07 17:50:43]: [140344999290624] mhdd_fileopen: /testfile.txt, flags = 8401
mhddfs [2015-05-07 17:50:43] (info): [140344999290624] mhdd_internal_open: /testfile.txt, flags = 0x8401
mhddfs [2015-05-07 17:50:43] (info): [140344999290624] mhdd_fileopen: error: Permission denied

I saw a previous answer where this was fixed with an entry in /etc/fuse.conf, but that did not work for me:
user1@mhddfs-1:~$ cat /etc/fuse.conf
# Set the maximum number of FUSE mounts allowed to non-root users.
# The default is 1000.
#
#mount_max = 1000

# Allow non-root users to specify the 'allow_other' or 'allow_root'
# mount options.
#
user_allow_other
user1@mhddfs-1:~$

I can write to the NFS mount, so that piece is good, I just can't write to the mhddfs mount.
Any thoughts?
Answer: It appears that this is an issue with nfs-kernel-server and how it works with fuse.  Something with how it presents it's exported volume to the client and that that doesn't play well with fuse.  It was suggested to try a user-mode NFS server like Ganesha but even Ganesha had this same issue.


Find out which fields to modify on drupal view for a module

Question: I would like to implement a hook on a view that grabs the fields that would be displayed and modifies one of the slightly before displaying it.  However, I am stuck at the first part which is just finding out how to view/see the fields that I can manipulated.  Based on a couple of other post I have read it seems like I should use the parseurl_views_pre_render which seems to make sense.  But, I don't even only how to see what the data looks like.
Any pointers or help would be greatly appreciated.
Thanks,
Derek
Answer: I think you can do what you need with hook_views_pre_render.
Here is what you can do to find out what the data you need to manipulate looks like:

Install & enable the devel module - https://drupal.org/project/devel
Create a custom module (if you haven't already)
Add a function based on HOOK_views_pre_render(&$view)
In your function, use the dpm function like so: dpm($view);
Reload the page with the view you want to alter
Explore the data rendered through Krumo which is provided by devel

So, ultimately, your function will start something like this:
<code>function your_module_views_pre_render(&$view) {

  if (($view->name == 'viewname') && ($view->current_display == 'displayname')) {

    dpm($view);
</code>
Comment: Thanks Dave this is very helpful and spot-on the information I needed.


Undefined class 'DragSelectionUpdateCallback' in flutter

Question: From flutter version 3.10.0 'DragSelectionUpdateCallback' has been removed from text_selection.dart
What is the alternative to this function?
Answer: Instead of DragSelectionUpdateCallback, you can use the new TextSelectionGestureDetector class to handle text selection gestures.
<code>import 'package:flutter/material.dart';

class MyTextSelectionGestureDetector extends StatelessWidget {
  final TextEditingController controller;
  final Function(TextSelection) onSelectionChanged;

  MyTextSelectionGestureDetector({required this.controller, required this.onSelectionChanged});

  @override
  Widget build(BuildContext context) {
    return TextSelectionGestureDetector(
      behavior: HitTestBehavior.translucent,
      onTapDown: (_) => controller.selection = TextSelection.collapsed(offset: controller.text.length),
      onSelectionChanged: onSelectionChanged,
      child: TextField(
        controller: controller,
      ),
    );
  }
}
</code>


Is it safe to truncate a field revision table?

Question: I noticed D7 creates a field_revision table for every field, and duplicates the content from its field table counterpart even if one has revisions turned off.
I have a big text table and it is taking up a lot of space (several GBs).
Would it be safe to truncate the revision table?
PS: Meanwhile, I have also reported this as a bug.
Comment: Possible duplicate of [How I can delete all node/field revisions?](http://drupal.stackexchange.com/questions/16471/how-i-can-delete-all-node-field-revisions)
Comment: I have plenty, but I dont think this has anything to do with contrib modules. Just look inside your db, and you will see every field has a field_revision table associated...
Comment: This is actually a good question! I think the table is created by core but only gets records inserted if revisions is enabled.
Comment: Thanks :) that was what I expected as well, but it seems D7 creates revision copies regardless. This was confirmed here http://drupal.stackexchange.com/questions/7027/data-in-field-revision-with-create-new-revision-unchecked/7790 . Perhaps a core bug?
Comment: I will categorize this as a feature, not a bug ;) I think the logic beyond that is that if you change your mind and activate revisions, it would be way to much overload on the DB to suddenly populate all the `field_revision_*` tables.
Comment: Even then I don't see why it would need an exact duplication right from the start...Only when there is a change in the field, then it would need to store the previous and the new values in the revision table...
Comment: Which non-core modules enabled on your site?  (Watching http://drupal.org/node/1369250)
Comment: Did you find out out if it is safe just to truncate the table? I have some tedious manual work for a ton of nodes and not having to apply these to field_revision tables would make my day.
Comment: I have the same issue. RKS, did you tried truncating the field_revision table? Is it safe?
Answer: I think there the Field SQL norevisions module will help you out:

Field SQL norevisions provides a field storage backend that prevents
  entity revisions from being saved to the MySQL storage backend.
The purpose of the module is to reduce the amount duplicated data that
  is saved on large Drupal sites that do not use revisions. It has the
  additional performance benefit of halving the number of queries during
  creating entities with fields.

This module will not allow revision fields to be created so it will increase your performance as number of queries will get reduced, besides that you will have no revisions on nodes further.
Also you can use some custom module codes provided on following URL:
http://www.ambidev.com/make-your-drupal-7-faster-by-removing-all-revisions/
and this module to delete revision entries:
https://www.drupal.org/project/node_revision_delete
Answer: You should have a look at this How I can delete all node/field revisions?, and perhaps subscribe to http://drupal.org/node/1063266#comment-5268252
Comment: No offense, but he was asking if it was safe to truncate the field_revisions, not how to delete them.
Answer: No, it is not safe. I am using Drupal 7.
I use quiz module on my website, and I noticed there at least were two error when I emptied all the field_revision_*
one with variable error which I do not really remember, and the other one was the questions were disappeared.
Oddly enough, answer options were there, but all the questions were gone. I did not look into more details, I put the field_revision_* tables back and it started working properly.
All I can say is if you use quiz module and go to myPHPAdmin and truncate these tables, you will get errors. If you don't use quiz module, I don't know. but it is not bulletproof. I would recommend using some proven modules to clear your revisions.


Drawing from a vector of objects using sfml

Question: I have a class named Particle and i want to create a vector of particles. The problem is that my code is not drawing the objects stored in the vector. I tried different implementations, the first one was:
std::vector<Particle> particles(10);
and then i filled the vectors:
for(size_t i = 0; i < 10; ++i) particles.emplace_back(new Particle(false));
for drawing i used:
for(const auto& x: particles) window.draw(x);
the problem is that this is drawing just one object. Then i tried to create a class of particles container with a vector of shared_ptr:
std::vector<std::shared_ptr<Particle>> particle_container;
And the problem is the same, it just draws one particle, i don't know if theres something wrong with my implementation of the class particle or something wrong in the waay i use the draw function of sfml. This is my Particle class:
#include "SFML/Graphics.hpp"
#include <random>
#include <cmath>
#include <limits>
#include <memory>
using namespace sf;
class Particle : public sf::Drawable{
    sf::CircleShape particle;
    Vector2f position; //current position of the particle
    Vector2f velocity;  //velocity of the particle
    double radius; //radius of each particle
    double mass; //mass of the particle
    int count; //number of collisions of each particle
    bool sick; //if the particle is infected
    Color color; //color of the particle
public:
    //constructors
    Particle(Vector2f _position, Vector2f _velocity, double _radius, double _mass, bool _sick);
    Particle(bool sick);
}:

the Particle.cpp:

#include "Particle.h"

template<class T>
double Rand(T first, T last) {
    std::random_device dev;
    std::default_random_engine eng(dev());
    std::uniform_real_distribution<double> dis(first, last);
    return dis(eng);
}

Particle::Particle(Vector2f _position, Vector2f _velocity, double _radius, double _mass, bool _sick) {
    position = _position;
    velocity = _velocity;
    radius = _radius;
    mass = _mass;
    sick = _sick;

    if(sick) color = sf::Color::Green;
    else color = sf::Color::Red;

    //giving values to the particle
    particle.setPosition(position);
    particle.setRadius(radius);
    particle.setFillColor(color);
}

Particle::Particle(bool sick) {
    position.x = Rand(0.0, 550.0);
    position.y = Rand(0.0, 550.0);
    velocity.x = Rand(-0.005, 0.005);
    velocity.y = Rand(-0.005, 0.005);
    radius = 2.0;
    mass = 0.5;

    if(sick) color = sf::Color::Green;
    else color = sf::Color::Red;

    particle.setPosition(position);
    particle.setRadius(radius);
    particle.setFillColor(color);
}

And this is the particles_container
class particles_container : public sf::Drawable {
    std::vector<std::shared_ptr<Particle>> particle_container;
    //std::vector<Particle> particle_container;
    virtual void draw(sf::RenderTarget &renderTarget, sf::RenderStates renderStates) const;
public:
    //default constructor
    particles_container();

    //constructor with a number of given particles
    explicit particles_container(size_t size);

    //default destructor
    ~particles_container() override;

    //returns the container
    std::vector<std::shared_ptr<Particle>> getContainer();

    //another function to draw
    void drawContainer(sf::RenderWindow &window);
};

the particles_container.cpp:
void particles_container::draw(RenderTarget &renderTarget, sf::RenderStates renderStates) const {
    for (const auto & i : particle_container) {
        renderTarget.draw(*i);
    }
}

particles_container::particles_container(size_t size) {
    if(size > 0){
        for(size_t i = 0; i < size; ++i) particle_container.emplace_back(new Particle(false));
    }
}

std::vector<std::shared_ptr<Particle>> particles_container::getContainer() {
    return particle_container;
}

void particles_container::drawContainer(RenderWindow &window) {
    for (auto & i : particle_container) {
        window.draw(*i);
    }
}

and finally this is my main.cpp:
#include "Particle.h"
#include "particles_container.h"
int main() {
    sf::RenderWindow window(sf::VideoMode (600, 600), "PF");
    std::vector<Particle> particles(10);
    for(size_t i = 0; i < 10; ++i) particles.emplace_back(new Particle(false));
    Particle p1(sf::Vector2f(45.0,45.0), sf::Vector2f(0.01,0.005), 2, 0.5, false);
    particles_container parts(100);
    Particle p3(true);
    std::vector<std::shared_ptr<Particle> > my_vector(10);
    for(size_t i = 0; i < 10; ++i) my_vector.emplace_back(new Particle(false));

    while(window.isOpen()){
        sf::Event event;
        while(window.pollEvent(event)){
            switch (event.type) {
                case sf::Event::Closed:
                    window.close();
                    break;
            }
        }
        window.clear();
        //parts.drawContainer(window);
        //window.draw(parts);
        for(const auto& x: particles) window.draw(x);
        window.display();
    }
}

this is the output:
output
Any help or advice would be greatly appreciated, thanks.
I am using:
SFML 2.5.1 and c++17
Comment: Welcome to SO! You draw by `window.display()`, but you don't show its code, nor any code to trace which `Particle` is rendered when. We can't look for the issue.
Comment: Not the real problem but `std::vector particles(10)` already constructs a vector with 10 default-initialized Particles. No need to then push another 10 Particles on top of it. Also, use `make_shared(false)` instead of passing `new Particle` to `emplace_back`.
Comment: Sorry, that function is implemented in the sfml library. should i post that code to? because i don't know  if i can edit that.
Comment: thanks for the advices Botje
Comment: If you don't get an answer here, try building it up from something simpler. You probably don't need to use `std::shared_ptr` - just store the particles directly, as you were doing previously (note the comment above about how you're using `std::vector` though). Start by just rendering a couple of particles by brute force, as individual objects (not in a vector). Then put them in a vector and render them 'manually', one at a time. Then try them in a loop, and so on. Keep going until it stops working (if it does). I think this approach will be likely to reveal where the problem lies.
Comment: I did that, i tried everything but i never thought it would be something with the Rand function. Anyways thanks for the advice.
Answer: Your Rand function constructs a new random device every time, which has a high probability to always return the same number sequence. Move the construction of dev out of your Rand function.
Comment: Thank you so much for the help. That was the problem.


Including datetime in parameter for step function params.json

Question: I have a section of my params.json input for a set of step functions, and I would like to modify some of the parameters to include a datetime that gets rendered in the input parameters.
"Predictor": {
    "PredictorName": "normal_name_/*DATETIME HERE*/",
    "ForecastHorizon": 181,
    . . .
    },

I am currently doing it by modifying the input parameters in the first step of the function, however this is problematic as every time I run it it will re render the datetime and I'd like to "lock in" the date as whenever the step function execution was created. Is this possible?
Answer: This can be done within the State Machine definition itself.  The execution's start time is available as an IS0 8601 string from the Context Object.  Using the intrinsic function States.Format, concatenate the date-time with your name prefix in a Pass Task.
"TimestampNamePass": {
  "Type": "Pass",
  "ResultPath": "$.Predictor",
  "Parameters": {
    "Name.$": "States.Format('normal_name_{}', $$.Execution.StartTime)"
  },
  "Next": "Success"
},

"Predictor": {
    "PredictorName.$": "$.Predictor.Name",
    "ForecastHorizon": 181,
    . . .
    },

TimestampNamePass Output:
{
  "Comment": "Insert your JSON here",
  "Predictor": {
    "Name": "normal_name_2022-01-27T14:09:19.196Z"
  }
}

Comment: this is perfect, thank you so much