How do I change the content text programmatically?

Question: I have enabled the anonymous comment setting. And its E-mail form appears as shown below.

Now, I want to change the text "The content of this field is kept private and will not be shown publicly." to "E-mail address will not be shown publicly."
How can I change this programmatically.
For information the HTML part I have copied through fire-bug which is as below.

     E-mail *
     <input id="edit-mail" name="mail" value="" size="30" maxlength="64" class="form-text required" type="text">

The content of this field is kept private and will not be shown publicly.

Answer: This value is defined in the comment_form function. More specifically, it is the description in this section:
  // Add author e-mail and homepage fields depending on the current user.
  $form['author']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-mail'),
    '#default_value' => $comment->mail,
    '#required' => (!$user->uid && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
    '#maxlength' => 64,
    '#size' => 30,
    '#description' => t('The content of this field is kept private and will not be shown publicly.'),
    '#access' => $is_admin || (!$user->uid && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
  );

You could create a custom module and implement hook_form_FORM_ID_alter. Your custom module file would contain below lines in a .module file and a basic .info file.
<?php

function MODULENAME_form_comment_form_alter(&$form, &$form_state, $form_id) {
  $form['author']['mail']['#description'] = t('E-mail address will not be shown publicly.');
}

Alternatively there are some options for overriding strings outlined here: Drupal 6 & 7 - Change default strings (text) without using full translation system
Comment: Hi, Thanks for answer. Instead of creating module, can I just put this function in template.php? I just tried and it is working perfectly. Is this the right way to do? Or I will have to create module? Thanks again.
Comment: In Drupal there is a thin line between modules and themes. I guess it is save to leave it there.


Como definir o nome do meu pacote no PyPi?

Question: Estou criando um modulo python para distribuir no pypi, estou estudando o processo de criação de distribuição dos módulos por alguns tutoriais e pelo próprio guia do pypi, mas mesmo assim ainda estou com algumas duvidas. Segue a arvore do meu projeto para ajudar com as perguntas:
    |_ meupacote
      |_ DESCRIPTION.rst
      |_ LICENSE
      |_ README.md
      |_ setup.cfg
      |_ setup.py
      |_ src
        |_ __pycache__
        |_ __init__.py
        |_ __main__.py
        |_ meupacote.py
      |_ tests
      |_ venv

Eu queria saber:
1 - Qual vai ser o nome que vai ficar no modulo, se vai ser "meupacote" ou vai ficar "src"?
2 - Como que vai ficar na hora de importar, depois que o modulo estiver pronto e distribuído?
3 - Tem alguma coisa que eu possa fazer em "setup" ou em outo lugar pra especificar como eu quero que fique o modulo/pacote?
Ps.: O nome "meupacote" é meramente ilustrativo.
Comment: considere a possibilidade de edtar o titulo da pergunta para refletir melhor o conteúdo. Algo como "Como definir o nome do meu pacote no PyPi?"
Comment: Obrigado pela sugestão Lucas
Answer: Todas as meta-informações do seu pacote (como nome, versão, autor, etc) ficam no arquivo setup.py. Aqui um exemplo de arquivo desse tipo:
from distutils.core import setup

setup(
  name = 'YOURPACKAGENAME',
  packages = ['YOURPACKAGENAME'],
  version = '0.1',
  license='MIT',
  description = 'TYPE YOUR DESCRIPTION HERE',
  author = 'YOUR NAME',
  author_email = 'firstname.lastname@example.com',
  url = 'https://github.com/user/reponame',
  download_url = 'https://github.com/user/reponame/archive/v_01.tar.gz',
  keywords = ['SOME', 'MEANINGFULL', 'KEYWORDS'],
  install_requires=[
          'validators',
          'beautifulsoup4',
      ],
  classifiers=[
    'Development Status :: 3 - Alpha',
    'Intended Audience :: Developers',
    'Topic :: Software Development :: Build Tools',
    'License :: OSI Approved :: MIT License',
    'Programming Language :: Python :: 3',
    'Programming Language :: Python :: 3.4',
    'Programming Language :: Python :: 3.5',
    'Programming Language :: Python :: 3.6',
  ],
)

Note que PACKAGENAME é o nome que seu pacote vai receber no PyPi e que você vai usar para importar.
Esse setup.py de exemplo eu tirei desse texto. Sempre uso ele quando crio um novo pacote.
Se quiser ver um exemplo prático, veja os arquivos desse pacote que criei recentemente.


Asp.net Identity Role in Razor Pages

Question: I have this working RoleController and its View which list all the roles
RoleController class:
public class RoleController : Controller
{
    RoleManager<IdentityRole> roleManager;

    public RoleController(RoleManager<IdentityRole> roleManager)
    {
        this.roleManager = roleManager;
    }

    public IActionResult Index()
    {
        var roles = roleManager.Roles.ToList();
        return View(roles);
    }
}

Index View
@model IEnumerable<Microsoft.AspNetCore.Identity.IdentityRole>
@{
    ViewData["Title"] = "Index";
}

List of Roles

Create

            Id
            Name

        @foreach (var role in Model)
        {

                @role.Id
                @role.Name

                    <form asp-action="Delete" asp-route-id="@role.Id" method="post">
                        <button type="submit" class="btn btn-sm btn-danger">
                            Delete
                        </button>
                    </form>

        }

Now, I would like to migrate these code to Razor Pages. And this is what I have created:
public class IndexModel : PageModel
{
    RoleManager<IdentityRole> roleManager;

    public IndexModel(RoleManager<IdentityRole> roleManager)
    {
        this.roleManager = roleManager;
    }

    public async Task<IActionResult> OnGetAsync()
    {
        var roles = await roleManager.Roles.ToListAsync();

        return Page();
    }
}

In MVC version, it returns roles to the View. But for Razor Pages version, what should it returns since it has model binding feature?
Comment: Roles and views don't exist in Razor Pages. You're thinking of MVC.
Answer: Here is a working demo:
Index.cshtml:
@page
@model IndexModel
@{
    ViewData["Title"] = "Index";
}

List of Roles

Create

            Id
            Name

        @foreach (var role in Model.roles)
        {

                @role.Id
                @role.Name

                    <form asp-action="Delete" asp-route-id="@role.Id" method="post">
                        <button type="submit" class="btn btn-sm btn-danger">
                            Delete
                        </button>
                    </form>

        }

Index.cshtml.cs:
public class IndexModel : PageModel
{
    RoleManager<IdentityRole> roleManager;

    public IndexModel(RoleManager<IdentityRole> roleManager)
    {
        this.roleManager = roleManager;
    }
    public List <IdentityRole> roles { get; set; }
    public async Task<IActionResult> OnGetAsync()
    {
        roles = await roleManager.Roles.ToListAsync();

        return Page();
    }
}

Result:

Update:
Index.cshtml.cs:
namespace IdentityRazor3_1.Pages
{
    public class IndexModel : PageModel
    {
         //...
    }
}

Index.cshtml:
@page
@model IdentityRazor3_1.Pages.IndexModel

If you do not want to specify the same namespace every time,you could add the following code to your _ViewImports.cshtml:
@using IdentityRazor3_1.Pages

Or:
@namespace IdentityRazor3_1.Pages

Comment: Check your IndexModel's namespace.And add reference to it.And be sure you have created the correct razor pages project.Refer to [here](https://learn.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/razor-pages-start?view=aspnetcore-3.1&tabs=visual-studio).Check my updated answer.
Comment: I tried your code. Just that there is a syntax error at `@model IndexModel` which says `The type or namespace name 'IndexModel' could not be found (are you missing a using directive or an assembly reference?)`

Asp.net Identity Role in Razor Pages


Warning: mysql_num_rows() expects parameter 1 to be resource, null given in (not a boolean)

Question: I know a similar question has been answered but with my case i'm not using booleans I get this error

Warning: mysql_num_rows() expects parameter 1 to be resource, null given in /home3/arm103/public_html/battle.php on line 19

here is battle.php from line 1 to 25
<?php
session_start();
include("header.php");
if(!isset($_SESSION['uid'])){
    echo "You must be logged in to view this page!";
}else{
  if(isset($_POST['gold'])) {
    $energy = protect($_POST['energy']);
    $id = protect($_POST['id']);
    $user_check = mysql_query("SELECT * FROM `stats` WHERE `id`='".$id."'") or        die(mysql_error());
if(mysql_num_rows($user_check) ==0) {
  output("There is no user with that ID!");
}elseif($energy < 1 || $energy > 10) {
  output("You must attack with 1 - 10 energy!");
}elseif($energy > $stats['energy']){
  output("You do not have enough energy!");
}elseif($id == $_SESSION['uid']) {
  output("You can not attack yourself!");
}elseif(mysql_num_rows($attacks_check) > 9) {
  output("This person has been already attacked the maximum of 10 times in the last 24 hours!");
}else{
    $enemy_stats = mysql_fetch_assoc($user_check);
    $attack_effect = $energy * 0.1 * $stats['attack'];
    $defence_effect = $enemy_stats['defence'];

It would be great if someone could show me the problem thanks
Comment: possible duplicate of [mysql\_fetch\_array() expects parameter 1 to be resource, boolean given in select](http://stackoverflow.com/questions/2973202/mysql-fetch-array-expects-parameter-1-to-be-resource-boolean-given-in-select)
Comment: Where exactly would `$attacks_check` come from? :)
Answer: $attacks_check is not defined, and is therefore null. You will need to initialize it as a resource before you can pass it as a parameter to mysql_num_rows().
}elseif(mysql_num_rows($attacks_check) > 9) {

As a side note, please be aware that the mysql_* functions are deprecated in favor of mysqli or PDO. Please consider updating your code to improve security and stability.
Comment: sorry this post can be deleted now thanks george cummins for explaining it in my case
Answer: There is no more support for mysql_* functions, they are officially deprecated, no longer maintained and will be removed in the future. You should update your code with PDO or MySQLi to ensure the functionality of your project in the future.
You are referencing a variable that is not defined $attacks_check is not assigned and so is null.
Answer: You used $attack_check but it was not definied
}elseif(mysql_num_rows($attacks_check) > 9) {

This is causing the error since variable is empty
Then I would like you to remember that mysql_* functions are deprecated so i would advise you to switch to mysqli or PDO


ASP.Net MVC auto slugify Routes

Question: i have this code in my Controller:
string APIBaseurl = "https://sub.domain.de/";
    [Route("VerseExkurs/Technologien/{technologie}")]
    public async Task<ActionResult> Details(string technologie)
    {
        TechnologieRootobject TechnologieInfo = new TechnologieRootobject();

        using (var client = new HttpClient())
        {
            //Passing service base url
            client.BaseAddress = new Uri(APIBaseurl);

            client.DefaultRequestHeaders.Clear();
            //Define request data format
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //Sending request to find web api REST service resource GetAllEmployees using HttpClient
            HttpResponseMessage Res = await client.GetAsync("items/technologien/" + technologie + "?access_token=token");

            //Checking the response is successful or not which is sent using HttpClient
            if (Res.IsSuccessStatusCode)
            {
                //Storing the response details recieved from web api
                var TechnologieResponse = Res.Content.ReadAsStringAsync().Result;

                //Deserializing the response recieved from web api and storing into the Employee list
                TechnologieInfo = JsonConvert.DeserializeObject<TechnologieRootobject>(TechnologieResponse);

            }
            //returning the employee list to view
            return View(TechnologieInfo.data);
        }
    }

But the Problem is, the "{technologie}" Variable is in some Cases with Spaces. Is there any way to automatically convert spaces in underdashes?
Answer: You have few options.

Utilize string.Replace() method

    HttpResponseMessage Res = await client.GetAsync("items/technologien/" + technologie.Replace(" ", "_") + "?access_token=token");

Write a helper function that returns correct string

string removeSpaceFromString(string inputString)
{
     return inputString.Replace(" ", "_"); // or some other method of doing that
}

Comment: Seems like this question's title, then the last thing they person asks is a little out of sync.

ASP.Net MVC auto slugify Routes


Divergence Theorem for a Parabola

Question: Let $E$ be defined in $\mathbb{R}^3$ as the area between the parabola $z = x^2 + y^2$ and the plane $z = 2$. Given the vector $\vec{F} = \langle 2x, 2y, 0 \rangle$, find the flux integral
$\iint_S \vec{F}\cdot\mathrm{d}\vec{r}$ using the divergence theorem.
So, we are looking for $$\iiint_E \text{div}\,\vec{F}\,\mathrm{d}V$$
Finding the divergence of $\vec{F}$ is easy, but I've been having trouble with the bounds. How do you set up the bounds for this integral?
Comment: Do you really need to set up a triple integral, there is an easier way to calculate the required volume using a single integral.
Comment: Do you have a picture of what this region looks like? It may help to sketch cross sections.
Comment: @WW1 Yes, it needs to be a triple integral. I thought of this too—why not just think of it as the continuous sum of circles? But they are specifically asking for how to set up the integral.
Comment: @TomKern I do, and it left me more confused than when I started.
Comment: Can you work out what the shadow of the region is in the $xy$ plane? That should give you the $x,y$ bounds (or $r,\theta$ if you want cylindrical coordinates)
Comment: You really should have learned how to evaluate a triple integral of a rather common shape before moving on to the divergence theorem.  Anyway, $\iint_S F dS + \iint_D F \ dD = \iiint_E \nabla\cdot F \ dE,$  where $D$ is a disc in the plane $z = 2.$  That is the real meat of this exercise.  To evaluate $\iiint_E \nabla\cdot F \ dE,$ I would use cylindrical coordinates.  $\int_0^{2\pi}\int_0^{\sqrt 2}\int_{r^2}^2 r\ dz\ dr\ d\theta$
Comment: That last part was what I was missing! $x^2 + y^2 \leq z \leq 2 \implies r^2 \leq z \leq 2$.
Answer: $$ V=\int_0^2   \int _{-\sqrt z} ^{\sqrt z} \int_{-\sqrt{z-y^2}}^{\sqrt{z-y^2}}dxdy dz $$
$$ V=2\int_0^2   \int  _{-\sqrt z} ^{\sqrt z} \sqrt{z-y^2} dy dz $$
let $y =\sqrt z \sin \theta$ so that $$.$$ $dy = \sqrt z \cos\theta d \theta$ $$.$$and $\sqrt{z-y^2}  = \sqrt z \cos \theta$
$$ V=2\int_0^2   z\int _ {-\frac \pi 2} ^{\frac \pi 2} \cos ^2 \theta d\theta dz $$
$$ \implies V = \pi \int_0^2 z\; dz = 2 \pi$$
Which is the same answer you get by integrating cross sections parallel to the $x-y$ plane, which are circles having radius $r = \sqrt z$ so each infinitesimal cylinder has volume $dV = \pi z dz$

Divergence Theorem for a Parabola


Showing that $\int_0^{\infty} \frac{\sqrt{x}}{1+x^2}\,dx = \frac \pi {\sqrt 2}$

Question: I want to show that $\int_{0}^{\infty}\frac{\sqrt{x}}{1+x^2}\,dx = \frac \pi {\sqrt 2}$.
I'm following much the same approach as in this answered question (i.e., integrating around the keyhole contour in the complex plane), $\int_{0}^{\infty}\frac{\sqrt{x}}{1+x^2}\,dx$
but have gotten stuck at the same place as the original poster. Namely, I want to calculate $2\pi i \sum \text{Residues}$ of $f(z) = \frac{\sqrt z}{z^2 + 1}$. Since there are simple poles at $z = i, -i$ inside the contour. my calculations seem to keep getting $\frac 1 {\sqrt 2}$ as the sum of the residues, and I suspect I'm not using the branch cut correctly. However, I'm not sure how to do the residue calculations w.r.t the branch cut correctly.
Comment: https://math.stackexchange.com/questions/97653/what-contour-should-be-used-to-evaluate-int-0-infty-frac-sqrtt1t2-dt
Comment: @SineoftheTime I read that question but was not sure which part could apply here, since the OP there use a different contour (not the keyhole contour)
Answer: Substitute $t=\sqrt x$ in the integral. Then write the integrand as $$\frac{2t^2}{1+t^4}=\frac{2t^2}{(t^2-\sqrt 2{\space} t+1)(t^2+\sqrt 2 {\space}t+1)}$$ Break the integrand apart by partial fractions. Integrate from $t=0$ to $t=b.$ Take the limit as $b \rightarrow \infty$


Am I on the right track? - long run profit problem

Question: Let time be measured in milliseconds, and let us focus on market buy orders only. Assume
that the market imbalance can be in any of the three states: high (H), medium
(M), or low (L). The imbalance may change in either direction for different reasons:
because of an incoming market order, or due the cancellation or addition of the standing
orders. If the imbalance is low, at the next time step it can either remain the same
or increase to medium – both with probability $1/2$ – and no market buy orders can
arrive at this time step. If the imbalance is medium, at the next time step it can either
decrease to low, with probability $1/3$, or increase to high. When the imbalance
increases from medium to high, it may happen for two different reasons: either due
to the new market buy order that arrived within this time step, which happens with
probability $1/2$, or without any new market buy order arriving, which happens with
probability $1/6$. If the imbalance decreases from medium to low, no market buy orders
can arrive within this time step. Finally, if the imbalance is high, at the next time
step it either decreases to medium or stays at high – both with probability $1/2$ – and,
independent of this, a market order arrives with probability $2/3$.
Consider Betty who always keeps a unit standing sell order in the exchange. Assume
that every market buy order will execute Betty's order (after which she will post
another one). Every execution gives Betty $1$ cent (e.g. from commission or from
clever re-purchasing). What is Betty's long-run profit per unit of time?
Hint: you need to construct the appropriate Markov chain, whose state space should
include more than just H, M and L.
So my solution is: state space :{Hnew, Hnone, M, L}
$$P=\begin{bmatrix} 0.5 & 0 & 0.5 & 0  \\ 0.5 & 0 & 0.5 & 0 \\0.5 & 1/6 & 0 & 1/3  \\ 0 & 0 &0.5 &0.5  \end{bmatrix}$$
And the stationary distribution is [$ 0.3889, 0.0556, 0.3333, 0.2222]$
At Hnew, $\pi=0.3889$, and since the probability of new order is $2/3$, so long run profit is
$$2/3 * 0.3889 = 0.2593$$
Am I on the right track?
Background information: An auction-style exchange has two types of trading orders: standing (limit)
and aggressive (market) orders. The investors providing limit orders specify whether they want to sell or to buy, and the price at which they want to trade, and wait until one of the market orders executes their limit order. Of course, each market order can be of a "sell" or a "buy" type: a market sell order executes the standing buy orders, and a market buy order executes the standing sell orders. A popular predictor of the type of the next market order is the so-called "market imbalance": a ratio of the total
size of all standing buy orders to the total size of all standing sell orders. The higher is market imbalance, the more likely it is that the next market order is of a "buy" type.
Answer: The transition matrix seems correct to me. But probability of a market order is seemingly $1/2$ in state M and $2/3$ if the state is high, i.e. either Hnew or Hnone. So the asymptotic probability of a market order would be
$$
\frac{1}{2} 0.3333 + \frac{2}{3}0.3889 + \frac{2}{3}0.0556 = 0.46298
$$


Python Usando .replace() com list comprehension

Question: Alguém consegue me dizer se consigo fazer isso funcionar:
a = ['<a1>', '<a2>', '<a3>', '', '<a5>']
b = ['<b1>', '<b2>', '<b3>', '', '<b5>']
txt = '<a1> test <a2> test <a3> test <a4> test <a5>'
txt.replace(''.join([i for i in a if i is not '']),''.join([j for j in b if j is not '']))

Comment: Qual é o resultado pretendido, o que queres que `txt` seja no final?
Comment: @Miguel quero que `txt` tenha os valores de `a` substituídos pelos de `b`
Answer: Tenta isto, não é com list compreession mas a lógica a adotar será esta:
ab = zip(a, b) # relacionar os elementis das listas
for a_val, b_val in ab:
    txt = txt.replace(a_val, b_val)

http://ideone.com/TPQpBz
Ou pelos indices:
for idx, val in enumerate(a):
    txt = txt.replace(val, b[idx])

http://ideone.com/OQCqjm


prove that composition of 2 functions is not differentiable

Question:
Given that:
  $$f(x) = \begin{cases}a \qquad x \ge 2 \\
b \qquad x <2
\end{cases}$$
  $$g(x) = \frac{1}{x^2-2x}$$
  and $-1<a<0<b<1$
prove that $f$ and $g$ are not differentiable at $x=2$ and that $g(f(x))$ is not differentiable at $x=2$.

Please let me know if my logic is correct. Since $a \neq b$ the one-sided limits of $f(x)$ are not equal therefore $f(x)$ is not continuous at $x=2$ thus $f(x)$ is not differentiable at $x=2$.
If we try to calculate the limit of $g(x)$ at $x=2$ we get $\lim_{x \to 2} \frac{1}{x^2-2x}$. We can see that $g(x)$ is not defined at $x=2$ and again one-sided limits are unequal: $-\infty$ and $+\infty$. Thus $g(x)$ is not continuous and thus not differentiable.
Regarding $g(f(x))$:
$$g(f(x)) = \begin{cases}\frac{1}{a^2-2a} \qquad x \ge 2 \\
\frac{1}{b^2-2b} \qquad x <2
\end{cases}$$
It is given that $-1<a<0$ and also that $0<b<1$ so $0<-2a<2$ and $-2<-2b<0$. Immediately we can see that $\frac{1}{a^2-2a}>0$. It is worth noting that squaring a rational number ($a$ and $b$ are not integers) will result either in a smaller number or equal therefore $b^2<b<2b \Rightarrow \frac{1}{b^2-2b}<0$. Therefore $\frac{1}{a^2-2a} \neq \frac{1}{b^2-2b}$ Therefore one-sided limits of $g(f(x))$ at $x=2$ are unequal $\Rightarrow g(f(x))$ is not continuous at $x=2 \Rightarrow g(f(x))$ is not differentiable at $x=2$.
Comment: Unless you've made a mistake, $g$ is perfectly well-defined and differentiable at $x=2$. Should it be $\dfrac{1}{x^2-4}$?
Comment: sorry, made a mistake
Comment: @OlivierMoschetta based on OP's formulation for $g(f(x))$ I'm guessing that $g(x)$ should be $\dfrac{1}{x^2-2x}$.
Comment: But you cannot suppose that $a=-1$ nor $b=3$ as it's out of given range
Comment: So $f(x), g(x),$ and $g\circ f(x)$ are all discontinuous at 2.
Answer: One fix:

It is worth noting that squaring a rational number ($a$ and $b$ are not integers) will result either in a smaller number or equal

This is not true. For example, $3/2$ is rational but $\left(\frac32\right)^2 \not< \frac32$.
It is true that $b^2 < b < 2b$, but the reason is because $0 < b < 1$.  We don't know that $b$ is rational, and this is not a property of rational numbers anyway.
Comment: You're right, but I meant rational in the sense that it's a fraction. I guess this what I should've said
Comment: So could I say that squaring a fraction given that the nominator is less than denominator will result in a smaller or equal number?
Comment: @Yos, no, don't say that either.  Fraction sort of implies rational, but more importantly, fraction most certainly doesn't imply "between $0$ and $1$."  For example, $3/2$ is a fraction.  Even if you qualify the numerator should be smaller, you're excluding irrationals.  For example, $0 < \pi - 3 < 1$, but how do you express $\pi-3$ as a fraction?  It's safest to say "$b^2 < b < 2b$ because $0 < b < 1$."
Comment: Ok, but regarding my solution overall is it correct?
Comment: @Yos, yes, nevermind, otherwise looks fine.


Static field overriding is working just fine in java 7

Question: I was trying to understand static variables in Java and what I see is following behaviour
public class TestParent {
     protected static String name = "parent";
}

public class TestChild extends TestParent{
    public TestChild(){
          super.name="child";
    }
}

Now if
TestParent tp = new TestParent();

output:
parent
else if,
TestParent tp = new TestChild();

output:
child
Can someone explain to me what exactly is happening? I know this question sounds very simple but I am not able to understand the reason.
Thanks.
Comment: See http://stackoverflow.com/questions/11579953/static-fields-on-a-null-reference-in-java .A static field can be accessed on *any* expression of the correct type; the actual instance - or lack of - is irrelevant. It is generally best to only use the "obviously static" form (ie. `TestParent.name`) to avoid confusion such as this.
Comment: The `super.name` is a "lie". This is why `((TestParent)null).name = "foo";` would also work.
Comment: Can you please explain why ((TestParent)null).name = "foo"; would work?
Comment: @AlienOnEarth Added in my answer
Answer: static fields never attach to instances rather than classes. They only need type to access.
Since super references to the type TestParent, it looks like you are overriding it but you can do that from out side Child as well with it's Class name (TestParent).
Inshort to access static fields you just need type, no need of instance. For ex
TestParent test = null;
System.out.println(test.name);

That works because the type of test is TestParent it invoke name on that type.
Why does Java compiler allow static variable access through null object?
Update on your question update :
When you do TestParent tp = new TestChild();
You are invoking child class constructor and in that constructor you are doing
 super.name="child";

Hence that is changing the value of name to child
Though you are changing in child, since static variables are bind to Parent class and not to instances, you can see the change across all the instances.
Answer: Static fields doesn't get inherited, which means child classes don't get their own copy of those static fields they only existed once which in in the parent class.
Now when you are doing this.
     TestParent tp = new TestParent();
it will print parent. Because value parent is assigned to the field name and you haven't called new TestChild(); yet, which will change the value.
So when you are doing
TestParent tp = new TestChild();

inside the TestChild constructor the value of name being changed to child. here you are changing the variable of the class TestParent and the change affected in the name variable of class TestParent. That's why you  are getting child when printing.
You can do a little more experiment. if you do
TestParent tp = new TestChild();

first and print (which will give child as output ),
and then
TestParent tp = new TestParent();

and print it will also give child as output.


Who will get the point in this case?

Question: We need your help about this case in our badminton match (shuttlecock side (A) and racket side (B)):
The shuttlecock and racket both touch the net at the same time (the shuttle isn't falling down, it's just touchs the net).
Can anyone tell me who will get the point in this case (shuttlecock side or racket side)? And it would be great if you can tell us that's following what are the rules/laws?
Answer: It depends on who hit the shuttle in which situation. According to the Laws of badminton:

§188.8.131.52 It shall be a let if, after the service is returned, the shuttle after passing over the net is caught in the net;

So if the racket side hit the shuttle during the rally, it's a let, i.e. you replay the rally.
In all other cases, it's a fault of the side which hit the shuttle:

§13.2.2 It shall be a fault if, in service, the shuttle after passing over the net, is caught in the net.
§13.3.2 It shall be a fault if, in play, the shuttle fails to pass over the net;

While the shuttle is in flight, the latter rule does not apply. Per §15.1, only if the shuttle is caught in the net and starts to drop down, the fault is called.
So much for the shuttle side. When the racket touches the net, it's a fault as well:

§13.4.1 It shall be a fault if, in play, a player touches the net (..) with racket (..).

Assuming the shuttle side hit the shuttle last, you have to evaluate what happened first - per §15.3, the first fault ends the rally.

If the racket touched the net before the shuttle hit the net, it's a fault of the racket side and the point goes to the shuttle side.
If the shuttle hit the net and started falling downwards (even a little bit of tumbling) before the racket hit the net, then it's a fault of the shuttle side and the point goes to the racket side.
If the shuttle got caught in the net just as the racket hit the net and you can't decide which happened first, it's a let, per §14.2.7.
Comment: The shuttlecock and racket both touch the net in the same time.
Comment: We're thinking about the rules: 15.1 and 15.2 (13.4.1 also). We want to make sure who will get the point in this case.
Comment: I have amended the answer. If shuttle and racket hit the net at the same time and you can't decide what happens first, it's a let. In a match without an umpire, as a general rule of thumb it's also a let whenever there is disagreement. On the chair, I'd call whichever fault I saw first.
Comment: This is an image only so we suppose the shuttecock and the racket both touch the net at the same time + the shutte isn't falling down (see the image, it only touchs the net). The situation: we only see the image and how to know who will get the point that's all.
Comment: Just by the image, there's no way to decide. For instance, if the racket side served and the shuttle got stuck in the net, the point would definitely go to the shuttle side. You can speculate (maybe the net deformation indicates that the shuttle was hit from the shuttle side), but there's no way to be sure. You can just list all possibilities, which is what I tried in the answer.
Comment: We think the shuttle is still in the match because it doesnt hit the court (15.2) or its not falling downwards also (15.1) so the racket touch the net while the shuttle in the play so it's falut of the racket side (13.4.1). Is this right ?
Comment: Or we think it's fault of the racket side because if the racket didnt touch the net then the shuttle won't flight like that (normally, it can fly/flip on the net...)
Comment: That is certainly a valid interpretation, even a likely one. In practice, umpiring does not happen on still pictures, but on games with situations. That's also the reason why all of the umpire tests and discussions I ever had were in the form of descriptions or videos.
Comment: One could reasonably assume that the shuttle got smashed into the net from the left, thereby moved the net, and only then the net and racket touched.
Comment: Yes, we thought that case. If the racket didn't touch the net (and shuttlecock also - see image) then the shuttle can flip the net (the shuttle in the play and we don't know what happen with it, so don't touch the net when its in the play = its fault of the racket) :-)

Who will get the point in this case?


Routing Error - No route matches when attempting to visit a new_deck_path

Question: I'm receiving the following error when linking to the new_deck_path
No route matches {:action=>"show", :controller=>"decks", :id=>#<Deck id: nil, name: nil, created_at: nil, updated_at: nil, user_id: 3>}

My server is displaying the following:
Started GET "/decks/new" for 127.0.0.1 at 2013-05-29 00:08:01 -0400
Processing by DecksController#new as HTML
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 3]]
  CACHE (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 3]]
  Rendered decks/new.html.erb within layouts/application (2.6ms)
  CACHE (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 3]]
Completed 500 Internal Server Error in 29ms

ActionController::RoutingError (No route matches {:action=>"show", :controller=>"decks", :id=>#<Deck id: nil, name: nil, created_at: nil, updated_at: nil, user_id: 3>}):
  app/views/layouts/application.html.erb:51:in `_app_views_layouts_application_html_erb__3049462299863220867_2194729200'

  Rendered /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/routing_error.erb within rescues/layout (0.9ms)

Why is the error telling me that there's no route matches? The routes are showing up when I run rake routes. Also, why is the "show" action being displayed in the error? The action that is being run is #new and I can confirm this based on the output in my server. I want to simply allow the user to click "New deck" and go to the New Deck page. I can't figuring out what is going on here...
application.html.erb

                <% if signed_in? %>
                    <% if current_page? root_path %>

<%= link_to "My decks", decks_path %>

<%= link_to "Sign out", session_path, method: :delete %>

                    <% elsif current_page? decks_path %>

<%= link_to "New Deck", new_deck_path %>

<%= link_to "Sign out", session_path, method: :delete %>

                    <% elsif current_page? deck_path(@deck) %>

<%= link_to "View decks", decks_path %>

<%= link_to "Add card", new_deck_card_path(@deck) %>

<%= link_to "Sign out", session_path, method: :delete %>

                    <% else %>

<%= link_to "Back to #{@deck.name}", deck_path(@deck) %>

<%= link_to "Sign out", session_path, method: :delete %>

                    <% end %>
                <% else %>

<%= link_to "Sign in with Twitter", "/auth/twitter" %>

<%= link_to "Sign in", new_session_path %>

<%= link_to "Sign up", new_user_path %>

                <% end %>

        <a href="<%= root_path %>">
Flashy

     <%= yield %>

routes.rb
Flashy::Application.routes.draw do

  match "/auth/:provider" => redirect("http://#{DOMAIN_NAME}/auth/#{:provider}"), :as => :signin
  match '/auth/:provider/callback' => 'sessions#create'
  match '/signout' => 'sessions#destroy', :as => :signout

  resource :session, only: [:new, :create, :destroy]
  resources :users, only: [:new, :create]

  resources :decks do
    resources :cards, except: :index
  end

  root :to => "homes#index"

end

decks_controller.rb
class DecksController < ApplicationController
  before_filter :authenticate

  def index
    @decks = current_user.decks
  end

  def new
    @deck = current_user.decks.new
  end

  def show
    @deck = find_deck
    @cards = @deck.cards
  end

  def create
    @deck = current_user.decks.new(params[:deck])
    @deck.save
    redirect_to decks_path
  end

  def edit
    @deck = find_deck
  end

  def update
    @deck = find_deck
    @deck.update_attributes(params[:deck])
    # redirect_to @deck <-- Polymorphic path
    redirect_to deck_path(@deck)
  end

  def destroy
    @deck = find_deck
    @deck.destroy
    redirect_to decks_path
  end

  private

    def find_deck
      current_user.decks.find(params[:id])
    end

end

rake routes
          root        /                                        homes#index
        signin        /auth/:provider(.:format)                :controller#:action
                      /auth/:provider/callback(.:format)       sessions#create
       signout        /signout(.:format)                       sessions#destroy
       session POST   /session(.:format)                       sessions#create
   new_session GET    /session/new(.:format)                   sessions#new
               DELETE /session(.:format)                       sessions#destroy
         users POST   /users(.:format)                         users#create
      new_user GET    /users/new(.:format)                     users#new
    deck_cards POST   /decks/:deck_id/cards(.:format)          cards#create
 new_deck_card GET    /decks/:deck_id/cards/new(.:format)      cards#new
edit_deck_card GET    /decks/:deck_id/cards/:id/edit(.:format) cards#edit
     deck_card GET    /decks/:deck_id/cards/:id(.:format)      cards#show
               PUT    /decks/:deck_id/cards/:id(.:format)      cards#update
               DELETE /decks/:deck_id/cards/:id(.:format)      cards#destroy
         decks GET    /decks(.:format)                         decks#index
               POST   /decks(.:format)                         decks#create
      new_deck GET    /decks/new(.:format)                     decks#new
     edit_deck GET    /decks/:id/edit(.:format)                decks#edit
          deck GET    /decks/:id(.:format)                     decks#show
               PUT    /decks/:id(.:format)                     decks#update
               DELETE /decks/:id(.:format)                     decks#destroy

application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery

  def current_user
    if cookies[:user_id]
      user_id = cookies.signed[:user_id]
      User.find_by_id(user_id)
    else
      User.find(session[:user_id]) if session[:user_id]
    end
  end
  helper_method :current_user
end

sessions_controller.rb
class SessionsController < ApplicationController
  def new
  end

  def create
    if !request.env["omniauth.auth"].nil?
      auth = request.env["omniauth.auth"]
      user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth)
      session[:user_id] = user.id
    else
      user = User.find_by_email(params[:session][:email])
      sign_in(user)
      cookies.signed[:user_id] = user.id
    end
    redirect_to decks_path
  end

  def destroy
    if cookies[:user_id].nil?
      session[:user_id] = nil
    else
      cookies.delete(:user_id)
    end
    redirect_to root_path, notice: "Signed out!"
  end
end

Answer: I think this causes the error, right?

<%= link_to "Back to #{@deck.name}", deck_path(@deck) %>

You try to link to show action with nil id
Comment: That doesn't appear to be the issue. I removed the line and it's still producing an error. Also, that line never gets him. The if/else statement stops at:
Comment: <% elsif current_page? decks_path %>                                <%= link_to "New Deck", new_deck_path %>
Answer: The @deck is producing an error because it hasn't been saved yet. I solved the problem by placing a content_for helper method in the view instead of in the layout.
<% content_for :nav do %>

<%= link_to "New Deck", new_deck_path %>

<% end %>

                <% if signed_in? %>
                                     <%= yield :nav %>
                <% else %>

<%= link_to "Sign in with Twitter", "/auth/twitter" %>

<%= link_to "Sign in", new_session_path %>

<%= link_to "Sign up", new_user_path %>

                <% end %>

        <a href="<%= root_path %>">
Flashy


Calculate elevation (view) angle with incidence angle

Question: I want to calculate the elevation (view) angle of a satellite using the incidence angle.see image
On this site there is a tool which you can use to calculate it but without description.
https://www.intelligence-airbusds.com/en/8719-angle-conversion
Does any body have an idea how I could do that?
Additionally I have the satellite position and the earth is an ellipsoid.
Comment: I've added a bounty to this question. I presume this was Pleiades imagery you were working with, which is my case. With that imagery, there is the following metadata provided: acquisition time, azimuth, incidence, illumination(sun) azimuth, illumination(sun) elevation, along track incidence, and across track incidence.
Answer: As far as I see the drawing is following:


Como fazer com que ao criar varios imageview , ele ir para o lado do outro?

Question: Como fazer com que ao criar varios imageview , ele ir para o lado do outro , e ao acabar o espaço na coluna ele passar para a próxima? tentei usar o linear porém quando acaba a coluna , ele continua colocando na mesma coluna , e diminuindo o tamanho para que caiba tudo

<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.paivadeveloper.lolvoices.AhriActivity"
tools:showIn="@layout/activity_ahri"
android:background="@color/corFundo">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:paddingTop="30dp">

    <ImageButton
        android:id="@+id/imageButton6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        app:srcCompat="@drawable/ahriicon" />

    <ImageButton
        android:id="@+id/imageButton5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        app:srcCompat="@drawable/ahriicon" />

    <ImageButton
        android:id="@+id/imageButton4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        app:srcCompat="@drawable/ahriicon" />

    <ImageButton
        android:id="@+id/imageButton3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        app:srcCompat="@drawable/ahriicon" />

    <ImageButton
        android:id="@+id/imageButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        app:srcCompat="@drawable/ahriicon" />

</LinearLayout>

</android.support.v4.widget.NestedScrollView>

Answer: Tu consegue fazer isso utilizando um RecyclerView.
Voce vai criar um adapter, que vai gerenciar quando voce adicionar uma nova imagem para que abra um novo quadrado do lado. Ficaria mais ou menos assim:
RecycleImageAdapter
public class RecycleImageAdapter extends RecyclerView.Adapter<RecycleImageAdapter.ViewHolder>  {

private Context context;
private LayoutInflater inflater;
private List<Uri> itens;
boolean view;

public RecycleImageAdapter(Context context, List<Uri> itens, boolean view){
    this.context = context;
    this.itens = itens;
    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.view = view;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    View v = inflater.inflate(R.layout.item_add, viewGroup, false);
    RecycleImageAdapter.ViewHolder mvh = new RecycleImageAdapter.ViewHolder(v);
    return mvh;
}

@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
    Uri imagem = itens.get(position);
    prepare(viewHolder, imagem, position);

}

private  void  prepare(final ViewHolder viewHolder, final Uri imagem, int position){
    if(imagem != null) {

   // Aqui tu vai exibir a sua imagem utilizando Picasso, Fresco ou afins

    }else{
        viewHolder.imageadd.setVisibility(View.VISIBLE);
    }

}

@Override
public int getItemCount() {
    return itens.size();
}

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener{

    ImageView image;
    ImageView imageadd;

    public ViewHolder(View itemView) {
        super(itemView);
        image = ((ImageView) itemView.findViewById(R.id.image));
        imageadd = ((ImageView) itemView.findViewById(R.id.imageadd));

    }
  }

e na sua Activity, tu vai colocar um RecyclerView onde voce quer exibir as imagens, e ficaria assim:
XML
     <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="15dp"
        android:id="@+id/lista">
    </android.support.v7.widget.RecyclerView>

Activity
        RecyclerView lista = (RecyclerView) findViewById(R.id.lista);
        lista.setHasFixedSize(true);

    LinearLayoutManager llm = new LinearLayoutManager(this);
    llm.setOrientation(LinearLayoutManager.VERTICAL);
    //Aqui voce vai setar quantos itens por coluna quer exibir
    lista.setLayoutManager(new GridLayoutManager(this, 3));

    imagens.add(null);

    imageAdapter = new RecycleImageAdapter(this, imagens,false);
    lista.setAdapter(imageAdapter);

Como pode ver, quando voce adicionar uma nova imagem, deve adicionar outro item na lista com valor null, pois é ele quem vai criar o proximo quadradinho do lado.
Item XML

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginRight="10dp">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/imageadd"
        android:scaleType="centerCrop"
        android:src="@drawable/placeholder"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/image"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>

Item xml é meu xml do adapter.
Comment: Então eu crio uma classe separada e coloco o recyclerimageadapter né? Esse recyclercview eu substituo o linear layout por ele ?
Comment: Isso amigo, o `adapter` é uma classe separada.  No caso do recycler no lugar do linear, ai vai de seu layout. O que deve tirar sao todos os image buttons.
Comment: Coloco o image button dentro do recycler né
Comment: Vale ressaltar também que eu tratei meu adapter para 2 image views diferentes. Uma chamada _image_, e outra _imageadd_. No seu caso, vc pode utilizar apenas 1 e na hora de comparar, mostrar um placeholder caso image seja `null`
Comment: eu editei minha resposta colocando o _itemadd_, layout que tu vai utilizar no adapter


How do I sanitize data from users before sending it to mySQL?

Question: I am making a forum at this moment.
I would like to sanitize my input data (that is, the posts from users) before sending it to the MySQL database.
I already have been searching some functions to do that, but I'm not sure if I have used enough of them and if they're all secure enough. Any suggestions are welcome.
Here is the code I have:
$message=$_POST['answer'];
$message=nl2br($message); //adds breaks to my text
$message=stripslashes($message); //removes backslahes (needed for links and images)
$message=strip_tags($message, '
'); //people can only use tags inside 2nd param
$message = mysql_real_escape_string($message); //removes mysql statements i think (not sure)

edit: Please tell me if I should add some tags to the strip_tags function. Maybe I have forgotten some.
Comment: [When inserting in db](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) and when [displaying the data on a page](http://php.net/manual/en/function.htmlspecialchars.php).
Comment: Since your comment says you're not sure what `mysql_real_escape_string()` does, you should [read its documentation](http://php.net/manual/en/function.mysql-real-escape-string.php) and while you're at it, [read about SQL injection](http://en.wikipedia.org/wiki/Sql_injection) to understand why this is so important.
Comment: Still allows XSS in attributes like ``
Comment: @jannesbraet just read the links I posted
Comment: nl2br() is for helping control output to a HTML block. stripslashes() is basically of no real value, it helps ''undo'' (bad) output escaping that  may have previously been applied (most useful for strings in a Javascript block). strip_tags() is a poor man's way of attempting to avoid cross-site scripting, that is only valid in one particular HTML output-context. None of these 3 functions things have anything to do with databases and will only serve to corrupt your data.
Answer: Try using PDO instead. It has great binding function, which really improves security. Here's some examples: http://php.net/manual/pl/pdostatement.bindvalue.php
PDO is by default in PHP5, so pretty much everywhere these days.
Comment: If you have PHP 4.4.9 you may have much bigger problems. It has many security vulnerabilities and no longer receives any upstream security updates. Check that your distribution is still supported and you are receiving and applying regular patches from the OS-provider. If not, you really need to upgrade your OS
Comment: If you write your own app use php5.3+.
Comment: i'm using a host server but it's from a dad from my friend so i can't contact them
Comment: Like NomikOS said, you should really switch to PHP5 (switch host?), especially with your security concerns.
Comment: is mysql_real_escape_string() so unsafe then? i was just wondering
Comment: Not "that" unsafe, but PDO or MySQLi is more reliable for sure.
Answer: If you want to allow limited HTML to be used in forum (as seen by the way you are using strip_tags()), use HTMLPurifier; otherwise you are vulnerable to javascript in attributes of those tags.
By the way, right now you are stripping the
 tags you've added
Answer: When you save to DB:
$message=strip_tags($message, '
'); //people can only use tags inside 2nd param
$message = mysql_real_escape_string($message); //removes mysql statements i think (not sure)

When you output:
$message=nl2br($message); //adds breaks to my text
$message=stripslashes($message); //removes backslahes (needed for links and images)

Besides, use htmlspecialchars when you write into html input elements like text or textarea
OBS: Don't reinvent the wheel. Learn some PHP framework like codeigniter that provides very secure ways to manage data.
.


HandleBars Check if Index in Each is Divisible by four

Question: Not very familiar with handlebars, but I'm using it in a reporting setting, and working with output intended to be printed. The document I'm printing should be four per page, so I want to do a check like if(index%4 === 0) but I'm a little unsure of how to do it.
I'm going through an array of objects with {{#each dataset}}
here is the basic layout, and my attempt for my four-per-page report.

    {{#each Badges}}

{{Event}}

{{Email}}

{{Name}}

{{Address}}

{{City}} {{State}} {{Zip}}

{{Event}}

{{Name}}

                    {{City}}
 {{State}}

    {{#if @index%4 === 0}}

    {{/if}}
    {{/each}}

The Container will have margins and padding set properly, and each of the reports are contained within the .card class, and the .container class is for the pagination.
What should go in the IF?
This is going to go into jsreport which I'm also not fully familiar with. Not sure if I can register a helper.
Answer: Handlebars does not have a lot of built-in support for logic. If your template requires some simple math, you are going to have to create one or more helpers.
In your case, you need to add 1 to your @index and determine if this result is evenly divisible by your desired page size of 4.
In the interest of having our helpers do one thing, I would recommend splitting this functionality into two helpers; I will call them sum and isDivisor.
sum will take any number of Numbers as arguments and return the result of adding them all together:
Handlebars.registerHelper('sum', function () {
    return Array.prototype.slice.call(arguments, 0, -1).reduce((acc, num) => acc += num);
});

isDivisor will take two Numbers as arguments and will return true if the first Number is a divisor of the second; otherwise false:
Handlebars.registerHelper('isDivisor', function (num1, num2) {
    return num1 !== 0 && num2 % num1 === 0;
});

Handlebars' subexpressions are delimited by parentheses, so what should go in your IF is the following:
{{#if (isDivisor 4 (sum @index 1))}}

For reference, I have created a fiddle.
However, although the above answers your question, I believe there is a better way to solve your problem.
I think the better solution would be to create a block helper that will slice your Array into chunks of your desired page size and then apply a template to each chunk, before concatenating and rendering the result. Such an implementation would look like the following:
Handlebars.registerHelper('page', function (arr, pageSize, options) {
    var result = [];
    for (var i = 0; i < arr.length; i += pageSize) {
        result.push(options.fn({ items: arr.slice(i, i + pageSize) }));
    }
    return result.join('');
});

The options.fn bit is the interesting part. It is applying our template block to a data object with a single property, items, which is a paged slice of our original array. The way we would use this helper in our template is as follows:
{{#page Badges 4}}

        {{#each items}}

                {{! TODO: Copy inner template and paste here. }}

        {{/each}}

{{/page}}

For reference, I have created another fiddle.


How to match character instead of using backslash in PERL

Question: Assume that my string is "sample text – and so on.."
in perl we have use backslash while matching in some cases like : sample text \&\#x2013\; and so on..
I want to know is there any other way to match any string instead of using backslashes while matching?
Comment: `perldoc -f quotemeta`
Comment: Please give an example to show what it is you want to do. Are you writing a regex pattern to match a particular string? Note that none of the characters in the string you show need escaping. `/–/` is fine
Answer: Anytime you want to use a literal string for comparison inside a regular expression, just use quotemeta on it.
There are also some helpful escape codes to shortcut that process, \Q ... \E, which can be included inside a double quoted string or regex LHS to escape special characters.


Using ajax with mysql to validate before rendering

Question: i am pretty new to ajax but what i might ask might be simple for some of you.
I am looking for a best way to check that what a user is posting to my checkdata.php is verily to the price in the database.
I have a very long database which works find but I need to do this validation.
product
pid      name                  size     price
1        chocolate              12        30.00

I have a form and in my form I am posting pid name and size
In my PDO statement I am doing this
SELECT pid, price, name, size from Product WHERE pid=:pid AND size=:size AND name=:name

This works fine.
But I want to use ajax to check that what the user is the same as whats in the database and its equal to the same price in the database.
If everything is not the same then it should have an alert message saying "don't mess with the code."
I have a very long table. sorry I cant show the code it too long
in the table i have name which i echo from the database
size is a dropdown list
and pid is an hidden input.
I currently have this jquery
$(document).ready(function(){
    $('#selected').hide();
    $('#button').click(function(){
        var pid = $('#pid').val();
        var size = $('#size').val();
        var Qty = $('#Qty').val();
        var price = '\u00A3' + parseInt($('#pricetag').text().replace(/^\D/, ''), 10) * Qty;
        var size = $('#size').val();
        if (!/^[1-9]\d?$/.test(Qty)){
            alert('Quantity should not be below 1 or null');
            return false; // don't continue
        }
        else {
        $('#sprice').text(price);
        $('#ssize').text(size);
        $('#selected').slideDown();
        }
        $.ajax({
            url: 'checkdata.php',
            type: 'POST',
            data: { pid:pid, size:size, Qty:Qty},
            success: function(data)
            {

            }
        });
    });
});

<?php
session_start()

if(isset($_POST['pid']) && isset($_POST['size']) && isset($_POST['Qty']) && isset($_POST['name'])){
    $pid = $_POST['pid'];
    $size = $_POST["size"];
    $qty = $_POST['Qty'];
    $name= $_POST['name'];

.
.
.

 somewhere in the php tag I have a statement to get the right price based on what data is getting posted
   SELECT pid, price, name, size from Product WHERE pid=:pid AND size=:size AND name=:name

?>

Summary
How can i use ajax to check that what is getting posted is the same as it is on the database before I render the page.
Comment: Why do you need to re-check the price? If the user picks a size and quantity you should only pass the pid, size, and qty and when processing this you will pull the price from your database and not a passed variable.
Comment: @ChristopherMorrissey I am posting `pid, size, and qty` then i am using it to find the price but the issue I am facing is that if some idiot change the value of the size. in the cart it will still render the page but they will be nothing in it. I thought by checking the price before rendering the page I will be able to stop this from happening
Comment: @yourcommonsense no point disliking the question, if you can't answer it
Comment: @ChristopherMorrissey I have updated the question if you are still looking to answer this question. Thanks
Comment: why would they be able to change the size of a product if that size is not available for that product ?
Comment: @ChristopherMorrissey the size is a dropdown list.... so the choose from the list. Lets  say someone wanted to be stupid and click the value using something like firebug or chrome inspect element or whatever and posted it... I want to be able to cross reference that what is getting posted is validate to what is in the database.
Comment: based on what you have I wouldn't worry about if some one is changing the code, if they submit a product that is invalid and it isn't added to the cart its not added to the cart that's fine ... they know why.
Answer: You shouldn't be round-tripping the prices through the client anyways. It's one thing to pull up a price and display it to a user, but you should NEVER accept a price value BACK from the user. Always fetch a fresh copy from the database when it comes time to actually calculate costs.
If you want to "fix" the price so that if the item is in the shopping cart for a prolonged duration, and you're changing prices in the database, then keep the price in the user's session. That's a purely server-side data structure, and can't be meddled with directly.
That'd let you say things like "item price has changed since you added it to the cart. accept new updated price or remove from cart?".
Comment: i am not posting the price... as u see from the question I am only posting variables which I am using to find the price.
Comment: Then why the "don't mess with the code" stuff? Let the user meddle with the price in their browser all they want - your system should be utterly ignoring that hacked-up price
Comment: I am posting pid, size, and qty then i am using it to find the price but the issue I am facing is that if some idiot change the value of the size. in the cart it will still render the page but they will be nothing in it. I thought by checking the price before rendering the page I will be able to stop this from happening
Comment: i know i shouldnt be bothered if the wanna piss about with the code but it doesn't look nice if the page still renders and they is nothing inside
Comment: then you're doing something wrong. shopping cart data should be kept in a session. you may want to allow them to edit the cart, e.g. change quantities or add/remove items. but sizing and pricing information should only ever go server->client. If they're messing with the code ontheir client and break the quicky "display updated price now" javascript in the cart page, then they deserve to have their cart emptied.
Comment: you kinda get what I am saying but you don't. Try going on a shopping website and change the value of an idea then add to cart. 2 things might happen. 1) will be that you might get an error message 2) will be that what you added to cart will not show up in your shopping basket.
Comment: My question  relates to 2 things things.
Comment: I have updated the question from the `php` tag to show the select statement I have
Answer: I'm not sure what your asking about.
Assume that if you're looking for validating the user discount coupon or etc, you may want to check the user Session in checkdata.php. Such as
$member_coupon=$_SESSION['MEMBER_COUPON'];

SELECT pid, name, size from Product where pid=:pid and coupon_id=$member_coupon

then
if(result){echo 'SUCCESS';}
else{ echo 'dont mess around';}

and ajax can use
success: function(results) {
alert(results);
}

Comment: thanks for trying but your answer if off the topic and question I asked but this just semi gave me an idea. My question is how do I stop the checkdata page from rendering if someone change the value getting posted. The page render but its empty. I want to alert the use if what is getting posted doesn't match anything in the database


What does it mean when there is a letter c in front of the tempo on a score?

Question: For example, "c. 108". I need to practice and I have absolutely no idea what it means!
Comment: My guess would be "circa" ("approximately").
Answer: The c. stands for circa which means about or approximately. You may also see it as ca. Pretty much it means means that you should play the piece around a tempo of 108 bpm. You could play it a little faster or slower the 108 it just to get you in the range of where the composer would want you to play it.


Save a Site Collection As A Site Template (.stp) File

Question: I would like to be able to save a SharePoint 2007 site collection as a site template (.stp) file. Is this possible?
Thanks, MagicAndi
Answer: If I'm not mistaken you can do this by going to the site, selecting the Site Actions link, selecting Site Settings and then selecting the option "Save site as template". Or does that just save the site and not the site collection?
Comment: joeqwerty, this saves just the current site, and not the site collection.
Answer: I work on the SharePoint team. I don't believe this is possible


What's a hіt іn halfpіpe?

Question: I've watched a lot of halfpіpe snowboarding іn the past but have no recollectіon of any reference to a "hіt".
This year, іt seems as though іt's standard јargon that any enthusіast should know.
What exactly іs a "hіt"?
Answer: It's the number of times that the competitor reaches the side and performs a trick.
From theconversation.com

The halfpipe event consists of three runs lasting around 20-30
seconds, and involves between six and eight "hits" of the pipe. A
"hit" is an aerial trick (jump, rotation and twist) off the top of the
pipe.

It does seem like the usage feels "normal" enough that I think many lists of snowboard jargon don't feel the need to include it.  But REI placed it in their glossary.

Hit: The takeoff point on a half-pipe or jump.

What's a hіt іn halfpіpe?


Breadcrumb displays overridden page label instead of node title

Question: Configuration:

Drupal 8.1.5
Panels 8.x-3.0-beta4
Page Manager 8.x-1.0-alpha23
Layout plugin 8.x-1.0-alpha22
Panelizer 8.x-3.0-alpha2

Main menu:

About

Team
Technology
...

When visiting page /about/team, the breadcrumb shows Home About.

With Page Manager, I have overridden the default /node/{node}, and created a couple of panel variants based on path.

With this configuration, when visiting page /about/team, the breadcrumb shows Home Node view. So, instead of the node title for the /about page, the label of the custom page managed by Page Manager is displayed.

Is this a bug or expected? How to fix it?
Answer: This is an issue related with page_manager module.
Check out the d.org issue queue https://www.drupal.org/node/2665328


Estimating auto-correlation with unequally spaced data

Question: I'm working on a time series problem where the spacing between observations is usually 12 or 24 hours, but this is not guaranteed.  I'd really like to estimate the auto-correlation function, and I've coded up a solution in R (shown at the bottom of this question).  Basically, I'm looping through all the observations in the dataset and for each observation I'm looking for other observations 1,2,3,... days in the past.  If that observation exists, then I use this pair in my computation of the acf, otherwise I don't.
To verify my function works, I've been comparing it with R's base acf() on a simulated dataset where the spacing is equal.  The agreement is close but not perfect (for n=10000 there's hardly any difference in the estimated acf's, but at n=100 I'm seeing differences as large as 0.05).
My question is: how is the acf computed, exactly?  I realize it's a correlation between lagged observations, but what estimates do we use?  For example, I'm using:
$$S_{X,Y} = \frac{\sum X_{i+t} X_i - (\sum X_{i+t}) (\sum X_i)/n}{n-1}$$
$$S_{X,X} = \frac{\sum X_i^2 - (\sum X_i)^2/n}{n-1}$$
$$\widehat{AR(1)} = S_{X,Y}/S_{X,X}$$
where $X_i$ is the current observation, $X_{i+t}$ is the observation that is exactly 1 day (or 2,3,...) in the past, and all summations are over pairs that have exactly that difference.  So, I'm guessing that one of my $n$'s should be $n-1$ or vice versa, as asymptotically my estimator agrees with R's, but I can't figure it out.  Any suggestions?
<code>acfUnequal = function( data, data.col=5, maxLags=10 )
{
  lags = 1:maxLags
  data = data[!is.na(data[,data.col]),] # Can't use for acf
                       #anyways, and causes problems in calcs
  reqCols = c("Date", "Hour")
  test = reqCols %in% colnames(data)
  if( any(!test) )
    stop(paste0("Missing the following columns: ",
                paste(reqCols[!test],collapse=", ")))
  if(ncol(data)<data.col)
    stop("data.col is larger than ncol(data)")

  diffT = as.numeric(diff(data$Date)) + diff(data$Hour)/2400
  Exy = rep(0,length(lags)) #E(XY), computed by adding up all X*Y
                            #then dividing by count
  Exx = rep(0,length(lags)) #E(X^2), computed by adding up all X^2
                            # then dividing by count
  Eyy = rep(0,length(lags)) #E(Y^2), computed by adding up all Y^2 then dividing by count
  Ex = rep(0,length(lags)) #E(X), computed by adding up all X then
                           #dividing by count
  cnt = rep(0,length(lags)) #Count, used to compute E(XY), E(X),
                            #E(Y)
  for(i in 2:nrow(data))
  {
    diffCurr = 0
    j = i
    for(lag in lags)
    {
      while(diffCurr<lag-0.05 & j>=2)
      {
        j = j-1
        diffCurr = diffCurr + diffT[j]
      }
      if(!diffCurr>lag+.05) #time lag within 0.05 days detected,
                            #use data to compute acf
      {
        Exy[lag] = Exy[lag] + data[i,data.col]*data[j,data.col]
        Exx[lag] = Exx[lag] + data[i,data.col]*data[i,data.col]
        Eyy[lag] = Eyy[lag] + data[j,data.col]*data[j,data.col]
        Ex[lag] = Ex[lag] + data[i,data.col]
        Ey[lag] = Ey[lag] + data[j,data.col]
        cnt[lag] = cnt[lag] + 1
      }
    }
  }
  sxy = (Exy - Ex*Ey/cnt)/(cnt-1)
  sxx = (Exx - Ex^2/cnt)/(cnt-1)
  acf = sxy/sxx
  return(acf)
}
</code>
Answer: Ok, I figured out the problem.  In my formula, I'm essentially estimating $E(X)$ twice: once by computing $\sum X_i$ and once by computing $\sum X_{i+t}$.  In R, $E(X)$ is estimated by using all the observations instead of these two subsets, and the divisor is the number of observations used to estimate $E(X)$.  Also, $S_{XX}$ is estimated using all the observations as well.


mongoose query low performance when using with populate

Question: I need help with this query.
I am querying 8000 documents in AppVisitorwith 4 collections populated.But it is not returning any result. Means it get stuck and after some time nodejs server return 404 error for route in which this query is executed.

<code> let Keys = yield AppVisitor.find(condition).sort({ createdAt: -1 })
                .populate({ path: 'userDeatils' })
                .populate({ path: 'details' })
                .populate({
                    path: 'skills',
                    match: {
                        $and: [{ value: { $ne: '' } }, { value: { $ne: null } }, { value: { $not: /({R[\d]+})/g } }]
                    }
                })
                .populate({ path: 'courses' });</code>
Comment: Hey did you find any solutions?
Answer: I guess trying to restructure your collections could help, and use populate function less as its quite a heavy operation.Make sure you know what you are doing when you use populate.


Background com degradê e ondulações

Question: Gostaria de saber se é possível criar o efeito da imagem abaixo usando CSS. Fazer o degradê é tranquilo, mas estou com dificuldades de fazer as ondulações.

#teste {
  width: 100%;
  height: 300px;
  background-image: linear-gradient(to top, #30cfd0 0%, #330867 100%);
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

Meu Conteúdo vai aqui

Answer: Tem duas formas de fazer, uma com ClipPath 100% com CSS, e outra usando SVG, mas o SVG pode ser direto dentro do HTML como eu fiz no exemplo. Se vc quiser pode usar base64 tb, mas acho que não vale a pena...
Exemplo com clip-path (site para vc fazer seu path, o meu ficou meio grosseiro mas é só um exemplo. https://bennettfeely.com/clippy/) Quanto mais pontos, mais fluida vão ser as curvas, como eu usei poucos pontos as curvas ficaram grosseiras como falei.

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    background-image: linear-gradient(to top, #30cfd0 0%, #330867 100%);
}
body {
    background-image: linear-gradient(to top, #30cfd0 0%, #330867 100%);
}
.footer {
    width: 100%;
    height: 100vh;
    position: absolute;
    bottom: 0;
    left: 0;
    -webkit-clip-path: polygon(41% 54%, 53% 64%, 66% 60%, 89% 59%, 100% 73%, 100% 100%, 0 100%, 0% 70%, 10% 58%, 24% 51%);
    clip-path: polygon(41% 54%, 53% 64%, 66% 60%, 89% 59%, 100% 73%, 100% 100%, 0 100%, 0% 70%, 10% 58%, 24% 51%);
    background-color: #ffffff;
}

Exemplo com SVG.

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    background-image: linear-gradient(to top, #30cfd0 0%, #330867 100%);
}
body {
    background-image: linear-gradient(to top, #30cfd0 0%, #330867 100%);
}
.footer {
    width: 100%;
    height:50vh;
    position: absolute;
    bottom: 0;
    left: 0;
    fill: #ffffff;
}

        <svg viewBox="0 0 869 344" xmlns="http://www.w3.org/2000/svg">
            <path d="M 272 0.0130308C 164.8 1.21303 46 85.1797 0 127.013L 0 342.013L 867 342.013L 867 6.51303C 779 0.013031 684.5 127.013 616.5 127.013C 548.5 127.013 406 -1.48697 272 0.0130308Z"/>
        </svg>

O SVG tb não ficou perfeito, mas é só pra exemplo mesmo! Site para vc fazer seus SVG figma.com

Background com degradê e ondulações


Scala implicit constructor

Question: Is it possible, in Scala, to instanciate an object without actually calling its name ?
In particular, I have :
val foo = Thing(
  Thingy(1,2,3),
  Thingy(4,5,6)
)

And I wonder if it would be possible to call it like that
val foo = Thing(
  (1,2,3),
  (4,5,6)
)

Comment: Use implicit as automagic conversion is generally a bad idea considering readability and maintenance
Answer: Here's another approach:
case class Thingy(a: Int, b: Int, c: Int)

case class Thing(x: Thingy, y: Thingy)

object Thing {
   def apply(t1: Tuple3[Int, Int, Int], t2: Tuple3[Int, Int, Int]): Thing =
     Thing(Thingy(t1._1, t1._2, t1._3), Thingy(t2._1, t2._2, t2._3))
}

Answer: You can use implicit conversion from Tuple3 to Thingy:
package example

case class Thingy(v1:Int, v2:Int, v3:Int)

object Thingy {
   implicit def tuple2Thingy(t: Tuple3[Int, Int, Int]) = Thingy(t._1, t._2, t._3)
   //add conversion in companion object
}

then you can use it like this:
import example.Thingy._

val foo = Thing(
    (1,2,3),
    (4,5,6)
)

If Thingy is vararg:
case class Thingy(v1:Int*)

object Thingy {
   implicit def tuple2ToThingy(t: Tuple2[Int, Int]) = Thingy(t._1, t._2)
   implicit def tuple3ToThingy(t: Tuple3[Int, Int, Int]) = Thingy(t._1, t._2, t._3)
   //etc until Tuple22
}

Comment: @Dranna You'd have to create implicit conversion for every tuple, from Tuple2 until Tuple22. It's boilerplate, but there is probably no other way.
Comment: It's easy to do it with shapeless: `implicit def make[Tuple](tuple: Tuple)(implicit toArray: shapeless.ops.tuple.ToArray.Aux[Tuple, Int, Array[Int]]): Thingy = Thingy(toArray(tuple): _*)`
Comment: Thanks, I accepted it as an answer, but if you can edit to allow unknown-size Thingy, that would be perfect !

Scala implicit constructor


Add custom CSS to shortcodes

Question: I'm developing a wordpress plugin. This plugin will use shortcodes to display larges chunks of HTML that are styled with Bootstrap 3. However, I cannot depend on whether or not the theme has bootstrap 3 enabled. Is there a way, from my plugin, to ensure that the bootstrap 3 libraries get added to the page?
I've looked through the documentation and nothing seems clear enough. I have a feeling it has to do with wp_enqueue_script, but not sure of the hooks I'd need  to use to tie into the CSS/JS on the main page/post pages/theme header, etc.
Answer: The summary is, when your plugin is loaded, you should register bootstrap :
add_action( 'wp_enqueue_scripts', 'my_plugin_register_scripts' );
function my_plugin_register_scripts(){
     wp_register_script('bootstrap','//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js',array('jquery'),'3.3.2',true);
     wp_register_style('bootstrap','//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css', array(), '3.3.2');
}

Then, when your shortcode is called, you enqueue bootstrap :
wp_enqueue_script('bootstrap');
wp_enqueue_style('bootstrap');

Comment: I think that answers my question ... simply by calling `wp_enqueue_script`/`wp_enqueue_style`, that will put the script/style within the theme page? Should I call the `enqueue` scripts in my shortcode function, or in my plugin init?
Comment: register gets wordpress ready for it, but does not actually push it out to the browser.  When you are certain you need it, you fire the enqueue function which will push it out to the browser.
Comment: yes, but should I call the `wp_enqueue_...` during my function that renders my shortcode, or somewhere else -- for example, the `init` hook.
Comment: for most efficiency, during your function that renders your shortcode.
Comment: But that calls js as well as css in the footer. Any Idea how to get this into the header?
Comment: Set the last argument in `wp_register_script` to false.

Add custom CSS to shortcodes


Camel Restlet maxThreads Component Option

Question: I have a problem. The apache camel documentation states that for the camel-restlet component (starting from 2.10 version) is possible to define the max number of threads that will service requests (http://camel.apache.org/restlet.html).
How can i specify this parameter?
This is the route that I made
from(
            "restlet:http://localhost:" + config.getEmergencyRESTPort()
                    + "?restletMethods=post,get&restletUriPatterns=#emergencyUriTemplates&maxThreads=64").process(
            new EmergencyServerProcessor(config, emergencyService));

I used the maxThreads parameter in the url but it doesn't work.
What is the error?
Answer: maxThreads is not a URI option but rather it is a component option.
You can configure your restlet component by creating a bean like this:
<bean id="restlet" class="org.apache.camel.component.restlet.RestletComponent">
    <property name="maxThreads" value="50"/>
</bean>


How to form a meaningful statistical indicator to reflect user interaction with a website

Question: A given user can interact in multiple ways with a website. Let's simplify a bit and say say a user can:

Post a message
Comment a message
"like" something on the website via Facebook

(after that we could add, following the site on twitter, buying something on the site & so on, but for readability's sake let's stick to these 3 cases)
I'm trying to find a formula that could give me a number between 0 and 100 that reflects accurately the user interaction with the given website.
It has to take the following into account:

A user with 300 posts and a one with 400 should have almost the same score, very close to the maximum
A user should see his number increase faster at the beginning. For instance a user with 1 post would have 5/100, a user with 2 would have 9/100, one with 3 would have 12/100 and so on.
Each of these interactions have a different weight because they do not imply the same level of involvement. It would go this way: Post > Comment > Like
In the end, the repartition of data should be a bit like the following, meaning a lot of user around 0-50, and then users really interacting with the website.

This is quite specific and data-dependent, but I'm not looking for the perfect formula but more for how to approach this problem.
Comment: give some example data (even fake)....we could compare the proposals.
Answer: Suggestion: Assign values to each post, "like" and etc. For example, one post is worth $0.1$. So if I have posted eight times, I have $0.8$ points.
Now, display my score as $S=100-\frac{100}{P+1}$ where $P$ is the sum of my points. In our example, $S=100-\frac{100}{1.8}\approx 44$. Note that if I haven't done anything, $S=0$. If I have posted $50$ times, my score will be $S=98$.
More generally, I suggest a function $S=100(1-f(P))$ where $f(0)=1, f(\infty)=0$ (and $f$ is monotonically decreasing). Other examples could be $S=100-\frac{100}{\sqrt{P+1}}, S= 100-\frac{100}{(P+1)^2}$ and so on. I suggest playing around with these until you find one that seems to match what you want out of the score.
Answer: Collect all the indicators and try to combine them as described here: How do I develop a metric for comparisons that involves a combination of variables at different scales?
There is no general advice as the distribution of the scores will depend on the population of your visitors and will tend to change as it changes whatever metric you choose.


Banco de Dados com Back-End embutido

Question: Existe algum tipo de banco de dados que possa tratar e armazenar os dados como se fosse 2 em 1?
BackEnd e Bando de dados ao mesmo tempo.
Comment: Não sei se entendi o que deseja mas, me parece, que é algo do tipo "embedded". Neste caso avalie o SQLite https://sqlite.org/index.html
Comment: É conveniente que seus dados estejam bem organizados. Certamente um "bando" de dados não terá muita utilidade.
Comment: Não sei se era o que queria, mas sua dúvida não está clara. Em geral o backend (serviços, lógica de negócio, Integrações) é separado do SGBD, que pode ser "standalone" (rodar num servidor separado) ou "embedded" (embutido), como está na pergunta que linkei. Podem existir stored procedures e triggers no banco para tratar dados mas via de regra é mais recomendado para manutenção que se prefira fazer separado.
Answer: Não entendi muito bem sua pergunta, mas você pode se conecta com o banco de dados pela sua própria aplicação
exemplo de um código em Java script (node js) usando o mysql:
<code>const mysql = require('mysql')// Aqui é uma dependência instalada e esta sendo chamada

const con = mysql.createConnection
({
    host: '', // O host do banco. Ex: localhost
    user: '', // Um usuário do banco. Ex: user
    password: '', // A senha do usuário. Ex: user123
    database: '' // A base de dados a qual a aplicação irá se conectar
});

con.connect((err) => {

   if (err) {
        console.log('Erro connecting to database...', err)
        return
    }
   else {
   console.log('Connection established!')
   }
})
</code>
Aqui você já se conectou com o banco de dados, é só prosseguir com a sua aplicação

Banco de Dados com Back-End embutido


Filter com 2 Array de Objetos

Question: Preciso fazer um filter utilizando 2 array de objetos para que o primeiro nao tenha as mesmas informações que o segundo ex:
valorA = [{nome: 'rafael', valor: 29}, {nome: 'diego', value: 21},{nome: 'tiago', value: 12}]

valorB = [{nome: 'rafael', valor: 29}, {nome: 'diego', value: 21}]

// valorA tem que vir somente com tiago,
valorA = valorA.filter(valor => {
     return valor.nome != valorB[index].nome
})

Estou tentando algo mais ou menos assim mais nao sai, alguem pra me ajudar?
Answer: Para fazer isto você precisa verificar para cada elemento de A se o mesmo existe dentro B, você pode fazer de diversas formas, uma simples seria usando o Find Index, basicamente para cada valor em A você procura pelo correspondente index do mesmo em B, se não existe agora a condição do filter será satisfeita e o novo array terá os valores diferentes de A e B.

const valorA = [{nome: 'rafael', valor: 29}, {nome: 'diego', value: 21},{nome: 'tiago', value: 12}]
const valorB = [{nome: 'rafael', valor: 29}, {nome: 'diego', value: 21}]

const valorC = valorA.filter(valor => valorB.findIndex(vB => vB.nome === valor.nome) === -1);

console.log(valorC)

Filter com 2 Array de Objetos


django how to implement a dynamic (bootstrap) modal

Question: I'm trying to change the interaction of a page so that additional info about a product appears in a modal rather than an element that is shown/hidden when a button is clicked.
The bit I'm not sure about is making the modal adapt it's contents to each product. (I'm not sure if django must prepare 3 different modals first of all at the backend - if this is possible or whether there is a simpler way?)
Previously I had the template:

Cheapest

    {% include 'components/quote_summary_item.html' with quote=first_quote %}

{% include 'components/quote_detail.html' with quote=first_quote %}
Where quote_summary_item.html is:

.........

  Select

Your Quote Details

{{ quote.Name }}

    {{ quote.Type }}

    .....

  <button class="btn btn-cta-secondary" data-id="{{ quote.priceId }}">Info</button>

and quote_detail is:

About this quote:

  {{ quote.synopsisText|safe }}

          Information

          {{ quote.Something }}

          Name
          {{ quote.Name }}

          {{ quote.payType }}

       .......

And the .js used was:

I've set up a modal template wrapper around quotes_detail.html however I'm not sure how to change the .js needed to pass in the relevant quote data to something like:
{% include 'components/quotes_modal.html' with quote=my_quote %}
and pass in the relevant quote based on the button id clicked.
Answer: There are two decent ways to do this.  Implement multiple modals if there aren't too many of them or use ajax to retrieve the contents if there are lots of them.
There is no need to have a .js file as all the required js is built into bootstrap.
Control each modal with eg a button:
<button type="button" class="btn btn-cta-secondary" data-toggle="modal" data-target="#{{ quote.priceId }}" data-id="{{ quote.priceId }}">More Info</button>

Then include the modal template in the relevant page:
{% include 'components/quote_detail.html' with quote=second_quote %}
{% include 'components/quote_detail.html' with quote=first_quote %}

with components/quote_details.html

 .....

with the rest as per bootstrap docs.
To do this via ajax have a look at https://www.abidibo.net/blog/2015/11/18/modal-django-forms-bootstrap-4/


ARKit or RealityKit – How can we detect a real world object?

Question: I need to detect a suitcase in AR and then estimate its size.
How can we achieve it using ARKit or RealityKit in iOS?
Comment: What have you tried so far?
Comment: I am very new to AR. I am able to detect planes with ARAnchor. Then I thought I can also detect real world object using ARObjectAnchor but could not succeeded.
Answer: To detect a real-world object use the following code using ARKit/SceneKit classes:
import ARKit

extension ViewController: ARSCNViewDelegate {

    func renderer(_ renderer: SCNSceneRenderer,
                 didAdd node: SCNNode,
                  for anchor: ARAnchor) {

        if let _ = anchor as? ARObjectAnchor {

            let sphereNode = SCNNode(geometry: SCNSphere(radius: 0.25))
            node.addChildNode(sphereNode)
        }
    }
}

class ViewController: UIViewController {

    @IBOutlet var sceneView: ARSCNView!
    let config = ARWorldTrackingConfiguration()

    override func viewDidLoad() {
        super.viewDidLoad()

        sceneView.delegate = self

        guard let obj = ARReferenceObject.referenceObjects(inGroupNamed: "AR Resources",
                                                                 bundle: nil)
        else { fatalError("See no reference object") }

        config.detectionObjects = obj

        sceneView.session.run(config)
    }
}

You need to put in Xcode's AR Resources folder all needed reference objects.
A size of object is known in this case.

Afterword

If you need a controlled object detection or object recognition features for different suitcases use CoreML or Vision frameworks that allow you use pre-trained .mlmodel (you can create it in Apple Create ML app or in Xcode Playground) with up to 10K images inside.
Comment: Your answer is helpful but it seems that we can only detect objects that we have already scanned. Is it possible tha i scan one suitcase and then detect some other suitcase. i think no right ?
Comment: Just a note about marrying computer vision with AR. Watch out for the fact the frames from ARKit always come through in a specific orientation and predictions from CoreML have the origin in the lower left. Eventually you end up with a point (center of prediction) you can then ray-cast into the scene. Getting that point correct for all device orientations is hard.
Answer: I think what you are looking for might be what is called "semanticization of objects", which ARKit supports in a very limited fashion: ARMeshClassification
If you enable .sceneReconstruction on your ARWorldTrackingConfiguration (after checking if that function is actually supported by the respective device with supportsSceneReconstruction(_:)) ARKit is able to classify very simple objects like chairs, tables and walls, but (as far as I know) without supplying a resource for ARKit to reference, it won't be able to recognize a suitcase as an actual suitcase object out of the box.
Answer: If your goal is real-time recognition of suitcases in general--as opposed to some specific suitcase--then ARKit will not do what you want.
Apple's CoreML framework could be used to build a suitcase recognition app. Here is some Apple sample code that demonstrates this using the Vision Framework (rather than ARKit) to do object recognition: Recognizing Objects in Live Capture
I don't have any advice on how you would jump from CoreML recognition to recognizing and measuring the suitcase's edges in two or three dimensions, but I imagine you would need to identify not only the object, but it's vertices (which also sounds like a machine learning task).  Once you had those, then you might be able to place them in 3D space and measure the distances between them, calculating height, width and depth of the suitcase.


How to take the average for percent error?

Question: I have roughly 39 data points that are values for % error. I have been researching and found that it is not correct to simply take the average of the % errors. Is this correct? If so, what is the correct way to take the average for % error values? All of the data values are weighted the same. Thanks!
Answer: You certainly can average the percent error values.  That is a well defined operation.  As Dilbert says, you can multiply them, too.  Whether or not it expresses what you want can be very subtle.  You are probably remembering the fact that averaging the percentage errors will not give the same result as dividing the average error by the average true value.  If you explain carefully what you want to express, it will lead to the correct way to compute it.
Comment: I want to say, our average percent error for all data sets is XX.
Comment: Say you have two samples, one with true value 10 and measured at 9 for 10% error and one with true value 100 and measured at 99 for 1% error.  Do you want to say the average percentage error is 5.5%?  The absolute error is 1 in both cases, so you could say the average percent error is 1 out of the average value of 55 for about 1.8%.  If the true values are close together the naive averaging of percent errors will be fine.  If not, you need to think about what you are trying to do.
Answer: I assume that you have given the errors in one direction and not the absolute error.
Let $r_i$ the deviation from the real data point in decimal notation.
Then the average deviation is
$$d=\sqrt[n]{(1+r_1)\cdot (1+r_2)\cdot (1+r_3)\cdot \ldots\cdot (1+r_n)}-1$$
$r_i$ can be negative and positive. For instance, if the real value is 120 and the deviation is $-12$, then $r_1=\frac{-12}{120}=-0.1$ and consequently $1+r_1=0.9$.
To get the value in percentage you have to multiply $d$ by $100\%$.
Comment: I am using the absolute error... Actual-theoretical/theoreticalX100
Comment: The forumula you have posted in you comment is not for the absolute error. It is the same formula as I have used in the answer.$ \frac{108-120}{120}=\frac{-12}{120}=-0.1$
Comment: If you have given the percentage deviations then you have to transform them in decimal notation. In general $-x\%=-0.0x$. Numerical example: $-3.2\%=-0.032$


Where should the play restart from an offside?

Question: I got my referee license recently, and am wondering where the restart should be for an offside offense.
One instructor told me the second to last defender, while another told me where the attacker was offside. Where should the restart actually be taken?
Answer: The answer has now changed, see the 2022/23 revisions to the Laws of the Game. Law 11.4, Offside - Offences and Sanctions now states:

If an offside offence occurs, the referee awards an indirect free kick where the offence occurred, including if it is in the player's own half of the field of play.
Comment: @WS2 it is possible: If you're in an offside position in the opponent's half at the time of a pass and you have to run back into yours because the pass is too short you'll eventually reach the ball in your own half. That's still an offside offense and the free kick would then be awarded at your position in your own half.
Comment: How can that be the case? The laws of the game state that a player cannot be offside in his own half of the field.
Answer: The restart should be from where the offside player is:

The restart for an offside sanction is an indirect free kick for the opponent at the place where the off-sided player was at the time the teammate passed or touched the ball. This is defined as where the infringement took place.

Source:
 Wikipedia


How can I calculate t-score without knowing true population mean?

Question: I am studying now t-scores. As far as I understand, t-scores are used when we don't know true population parameters (such as: standard deviation and population mean) and cant use z-scores. Here is formula that is in books and in Internet for calculating t-score:
$$t= \frac{\bar{X}-\mu }{\frac{S}{\sqrt{n}}}$$
As far as I know μ is used to define true population mean. So in formula above I need true population mean μ to calculate t-score. But as I said before when calculating t-score we don't know true population parameters, in this case true population mean μ. So what number I should use in μ and how to calculate it?
Also to make it clear, it will be very helpful if you provide example of actual t-score calculation.
Comment: In a hypothesis testing, the u is the hypothesis value.
Comment: Basically, when doing a t-test, you assume something for u. Calculate the sample's average. Use those values to do the test. You simply don't need the true population mean.
Comment: @Student T You mean I should use for `μ` the mean of many other samples? But if I have only one sample (consisting of 30 elements)?
Comment: Are you talking about a t-test? In a t-test, the u is the value specified in the null hypothesis. This statistic is really trying to transform your sample average into the standard normal to significance testing. I don't think it has anything to do many other samples.
Comment: @Student T I am talking about t-score to find estimated standard error when we don't have true population parameters (standard deviation and population mean).
Comment: But haven't you already given me the standard error in the formula? S / sqrt(N) is the standard error.
Comment: Please take a look https://en.wikipedia.org/wiki/Standard_error#Standard_error_of_the_mean you already have the standard error!!!!!
Comment: @Student T Sorry about that, you are right. But If we want to find t-score for finding probabilities and we don't know true population mean and deviation score. How can we find t-score for this?
Comment: This is just the standard t-test. You just need to calculate sample average and standard deviation. Plug those values into the formula you've given. The formula doesn't need anything about the population. Calculate the t-test statistic and then get the p-value. I recommend you read the section about t-test on wikipedia.
Comment: @StudentT I read in wikipedia but don't completely understand. Here is screenshot of my book http://i.imgur.com/I5L7qez.png Why they want me to use `μ` there?
Answer:
As far as I know μ is used to define true population mean.

Not quite, and here's the rub.  μ represents whatever the true mean is.  It's defined by the problem for which this little bit of statistical inference is the analysis, not by the data itself (that would make it an estimate, not a hypothesis)

So in formula above I need true population mean μ to calculate t-score.

You need a hypothesis about what it is, that is: a possible value for it.  You dont need to know what that value really is.

But as I said before when calculating t-score we don't know true population parameters, in this case true population mean μ. So what number I should use in μ and how to calculate it?

An example, done a few ways
Assume for a moment that you ask that a pool of subjects estimate the price of something - say a new college textbook, for concreteness - and you're interested whether they over- or underestimate the true price.
Here you can look up the true price, so if it's 45 dollars and the price guesses are in dollars too, then the μ=45.  If the subjects average guess is 60 then your t-test is testing whether there is enough evidence that they are systematically overestimating the price or whether their guesses could have have come from a population of subjects that neither under nor overestimated the textbook price.
Looking at this another completely equivalent way, you might subtract the true price from each subject's guess.  Then you are looking at deviations from the correct price and the test would set μ=0 (unbiased price guessing)
Looked at a third way, you might think about running this test for all values of μ (you wouldn't really do this, but bear with me).  For μs near the subjects' average, the test will 'not reject', but for μs quite far away from the subjects' average, the test will reject that the data came from a distribution with that value of μ.  The region of μ values for which the test does not reject is, in a sense, the region of μ values that are 'reasonable' in the light of the data.  This is one way to motivate the idea of (and sometimes actually construct) a confidence interval.  When the confidence interval (the region of non-rejected μs) does not overlap 45 (or zero in the second formulation), then we reject the hypothesis that this population is unbiased in its textbook price guessing.
Each of these approaches get you to the same place in a different way.  None of them require knowing the true value of μ.  The first two are the ones to consider in your case.
Comment: Thank you for detailed explanation. One more clarification, the t-test and finding value of `t` for the our sample is different right? For t-test we use formula that is at my question and for finding value of `t` for our sample we are using abbreviated `t` score table that shows the values of `t` corresponding to different areas under the normal distribution for various sample sizes (degrees of freadom), am I right? So for finding value of `t` for our sample we need only sample size `n`, the percentage of area in tail (or tails) and abbreviated t score table, am I right?
Comment: Here is screenshot of abbreviated t score table from my textbook: http://i.imgur.com/Odbm0Qc.png
Comment: From the sample you compute a) the degrees of freedom, which here is one less than the number of observations (n), b) the average vaue of the sample (X-bar), the sample standard deviation (s).  When you make a hypothesis about the population mean (μ) then you have everything ready to compute the statistic (t).  The 't-score table' allows you to choose from some different 'levels of significance' for your test.
Comment: Following my example, hypothesise that the population mean was 45 (μ=45). You get prices from ten people (n=10) and these guesses average fifty (X-bar=50) with standard deviation five (s=5). So the statistic t is 3.16. The middle column gives numbers that t should be larger in absolute value than to reject (that μ=45) in a two-tailed test at 'level' 0.05 for various degrees of freedom. Here you have n-1=9 so the number to be larger than is 2.262. 3.16 is larger than this, so you can reject p<.05 that μ=45 in the population from which this is a sample.
Comment: I can also calculate t score for individual element of my sample, right? Which formula to use for it `t=(X-μ)/S` or `t=(X-μ)/estimated standard error` ? I think I need to use first one, am I right? In that formulas `μ` is sample size, `X` is element value, `S` sample standard deviation.
Comment: First a notational clarification: μ is a hypothesis about the true mean and n is the sample size. These are not the same thing.  X is *an* observation, but X with a bar on top (what I called X-bar above) is the *average* of all the observations.  If the estimated standard deviation is S, then the *standard error* is S divided by the square root of n (that is: the denominator in your original question).
Comment: Second, your questions: First, no, there would be no point computing a t for each observation.  You are doing this whole thing in order to use all the observations *at once* to learn about the true value of μ.  Second, you use the formula that you put in the original question.
Comment: Your explanation is great! I understand it now. Thank you very much for help.
Answer: There are two different $\mu$'s involved here:

the hypothesized mean that you use in the numerator of your
t-statistic for a t-test (sometimes denoted as $\mu_0$), and
the true population mean, $\mu$.

The t-test is actually to see whether the true population mean differs from the hypothesized mean -- that is, it's a test for a null hypothesis $H_0\!:\, \mu=\mu_0$.
Don't confuse $\mu$ with $\mu_0$. Only one of the two is known.