Domain management by other hosting provider

Question: I have one domain in Australia, named mydomain.id.au , but the hosting company does not provides me with Domain management at all.
Actually i want to get rid of my local domain name server, running on my machien, i want to migrate it to some other domain manager.
Is it possible that i can use Domain management features of other domain manager for my site? for example, of NameCheap or Godaddy?
Answer: There are any number of companies that will provide DNS hosting; some for free, some for a nominal fee, and some for an exorbident amount of money.  We don't give specific shopping recommendations here, though, as the answers get out of date too quickly, and trying to deduce your specific needs is a lengthy question-and-answer process that doesn't help anyone but you, anyway.
Answer:
Is it possible that i can use Domain management features of other domain manager for my site?

Yes, it's possible. Location of host in domain and ns-servers of domains are unrelated things. You have to have only always correct data about NSes in registar records


Sort entityQuery by date published

Question: I'm attempting to perform a query to retrieve only the three most recent nodes of a certain content type.
<code>$query = \Drupal::entityQuery('node')
    ->condition('type', 'blog_post')
    ->sort('field');
$nids = $query->execute();
</code>
I understand that I can use sort to specify the field I want the results to be sorted by. But how would I sort by the dates the nodes were published?
Answer: <code>$query = \Drupal::entityQuery('node')
                ->condition('status', 1)
                ->sort('created' , 'DESC');
</code>
Answer: 'created' was the field.
I was able to find this by looking at the fields being used in Core\Modules\node\src\Entity\Node.php
Comment: Note that created is not the date when the node was *published*, it is when the node was created. That can but most not be the same. Drupal by default doesn't store a publication date.
Comment: However, this is the value shown and editable in the "Authored on" field.
Answer: <code>\Drupal::entityQuery('node')
    ->condition('status', 1)
    ->sort('changed' , 'DESC');

//Available fields
public function fields() {
  $fields = array(
    'nid' => $this
      ->t('Node ID'),
    'type' => $this
      ->t('Type'),
    'title' => $this
      ->t('Title'),
    'body' => $this
      ->t('Body'),
    'format' => $this
      ->t('Format'),
    'teaser' => $this
      ->t('Teaser'),
    'node_uid' => $this
      ->t('Node authored by (uid)'),
    'revision_uid' => $this
      ->t('Revision authored by (uid)'),
    'created' => $this
      ->t('Created timestamp'),
    'changed' => $this
      ->t('Modified timestamp'),
    'status' => $this
      ->t('Published'),
    'promote' => $this
      ->t('Promoted to front page'),
    'sticky' => $this
      ->t('Sticky at top of lists'),
    'revision' => $this
      ->t('Create new revision'),
    'language' => $this
      ->t('Language (fr, en, ...)'),
    'tnid' => $this
      ->t('The translation set id for this node'),
    'timestamp' => $this
      ->t('The timestamp the latest revision of this node was created.'),
  );
  return $fields;
}

</code>

Source

Sort entityQuery by date published


How to  calculate these summations?

Question: How to find the values of these kind of summations:
$$\large\sum_{i=0}^6(6-i)\;\ast\;\sum_{j=1}^6(7-j)\;\ast\;\sum_{k=2}^7(8-k)\;\ast\;\sum_{\ell=3}^8(9-\ell)$$
Comment: @m.woj * means multiplication here.
Comment: abhinav8, Zev Thanks. (Question was: what does asterisk mean in that context?)
Answer: Hint: Use the following formula.

$\displaystyle \sum\limits_{i=1}^{n} i = \frac{n \cdot (n+1)}{2}$.
$\displaystyle \sum\limits_{i=0}^{6} (6-i) = \sum\limits_{i=0}^{6} (6 - i) = 6 \cdot \bigl(1+1+1+1+1+1+1\bigr)- \sum_{i=0}^{6} i =6 \times 7 - \frac{6 \cdot 7}{2}$

Similarly you can calculate the other summation's  as well and then multiply them.
Comment: I may be completely mistaken, but you value of $\sum_{i=0}^6 (6-i)$ seems completely wrong. Why would $i$ start first at 0 then 1? Why would $\sum_{i=1}^6 6 = 6 \cdot (1+2+3+4+5+6)$?
Comment: Huh? How would that work in this case?
Comment: @Gigili: I have edited my answer.
Comment: Should the answer be $1+...+6 = 21$?
Comment: @copper.hat: Yeah. $21 = \frac{6 \cdot 7}{2}$
Comment: $6 \times 21 - \frac{6 \cdot 7}{2} = 105$
Comment: @copper.hat: Yeah that wil be the value of the first sum
Comment: @N.I yeah u are right. I think i made a stupid mistake. The value of $\sum_{i=0}^{6} 1 = 6$
Comment: @N.I sorry i didnt know my caps lock was on.
Comment: Your answer is still wrong: $$6\times 6-\frac{6\cdot 7}{2}=36-21=15$$
Comment: @Zev:Yes I know the reason why.It should have been $6 \times 7 - \frac{6 \cdot 7}{2}$
Comment: I've removed my downvote.
Comment: @ZevChonoles No problem. You had a reason to downvote :)
Answer: Or the formula:
$$\sum_{i=k_1}^{k_2} (p-i) =  (k_2-k_1+1)(p-\frac{1}{2}(k_1+k_2)).$$
Comment: The answer to the original question is 194,481.
Answer: Use that $$\begin{align}\sum_{t=a}^b(c-t)&=\left(\sum_{t=a}^bc\right)-\left(\sum_{t=a}^b t\right)\\\\&=\left(\sum_{t=a}^bc\right)-\left(\sum_{s=0}^{b-a} (s+a)\right)\\\\ &=\left(\sum_{t=a}^bc\right)-\left(\sum_{s=0}^{b-a} s\right)-\left(\sum_{s=0}^{b-a}a\right)\\\\ &=(b-a+1)c-(b-a+1)a-\left(\sum_{s=0}^{b-a} s\right)\\\\&=(b-a+1)(c-a)-\left(\sum_{s=0}^{b-a} s\right)\\\\&=(b-a+1)(c-a)-\frac{(b-a)(b-a+1)}{2}\\\\&=(b-a+1)(c-a-\tfrac{b}{2}+\tfrac{a}{2})\\\\&=(b-a+1)(c-\tfrac{b}{2}-\tfrac{a}{2})\end{align}$$
for each term. For example,
$$\sum_{i=0}^6(6-i)=6+5+4+3+2+1=\fbox{21}=7\cdot 3=(6-0+1)(6-\tfrac{6}{2}-\tfrac{0}{2})\qquad\checkmark$$
Comment: you seems to be wrong in last two steps of your equation, (c-a-(b/2)+(a/2)) should be equal to (c-(b/2)-(a/2)) but you have got (c-(b/2)+(a/2)).pls check and correct me if i am wrong.
Comment: @abhinav8: Thanks for catching that! You're correct, I made a careless error. I've edited my answer with the correct expression.

How to  calculate these summations?


How many constructors is too many?

Question: I am currently working on a class which represents one thing. That one thing can have multiple representations. The representation for any given instance of that thing is fixed when constructed. Depending on which representation is being used depends on what data is being stored.
For (an abstracted) example:

An enum where each value is the type of a representation, e.g; Alpha, Beta, Charlie.
All three representations have an Id and Name field.
Beta also has an Attributes field.
Charlie also has an ChildId field.
All three representations share a number of methods, e.g. IsValidFor(...), TriggeredBy(...).
All three representations are stored in the same database table.

This has led me to have one class with three specialised constructors, for example:
public enum RepresentationType { Alpha, Beta, Charlie }

public class Representation
{
    ...
    public Representation(Guid id, String name) { Type = RepresentationType.Alpha, ... }
    public Representation(Guid id, String name, String attributes) { Type = RepresentationType.Beta, ... }
    public Representation(Guid id, String name, Guid childId) { Type = RepresentationType.Charlie, ... }
}

I can see why I've ended up here, and in some ways this approach makes sense; the class represents a single type of thing, and it has a lot of shared functionality.
However its also problematic for a number of other reasons:

Each representation ends up with its own specialised constructor which typically involves repeating code. I've attempted to improve this by chaining constructors but then I'm ending up with long chains of functions.
For a given object its not guaranteed that all the properties will be set which causes issues later on when I'm working with the data again.

I'm considering refactoring this all into a set of sub classes, e.g. RepresentationAlpha, RepresentationBeta, RepresentationCharlie. This means I'll have to write some more code, but nothing too onerous. I can see problems further down the line however when I need to work with a representation from a collection and I don't know which representation I'm actually looking at.
Is this a sensible course of action? Am I just trading one problem for another? Is there a design pattern I should be looking at? How many constructors is too many?
Edits based on comments:

If I sub-class I would probably also use inheritance.
I have a factory pattern for creating each individual representation, it's the storage of each representation I'm interested in.
Less important, if I do sub-class I will probably also keep the type as its important for the data I'm working with.
Comment: It's hard to tell from just this, but have you considered inheritance rather than using enums to differentiate your objects?
Comment: "I can see problems further down the line however when I need to work with a representation from a collection and I don't know which representation I'm actually looking at." Don't invent problems that don't exist yet.  I would rather deal with that problem when it happens that one uber class that has many different "flavors"
Comment: At a glance, I'm wondering if this might be a good use case for a Factory pattern?
Comment: I'm with Nathan.  It sounds like you need a base class and subclasses rather than one class and a "type" property that determines which fields are appropriate.
Answer: There is nothing really wrong with several constructors. If class actually represent "one thing" having single class makes sense.
To avoid non-initialized fields consider shared (maybe private) constructor that will be called from all of your other constructors to initialize common fields.
Inheritance often lead to more problems than it worth (i.e. if JSON serialization is involved), so I'd wait till you must have it and only at that point consider adding inheritance.
On other hand if "one thing" is just loosely defined and types have vastly different in behavior - try inheritance, but also see if common interface for non-related classes would work.
Answer: There's a strong advantage in having no more than one constructor.
Once you've lost the advantage in having two, there's diminishing down-sides to each. Having half a dozen or more is not unusual for some sorts of classes where each overload can be clearly justified.

I've attempted to improve this by chaining constructors but then I'm ending up with long chains of functions.

This isn't such a bad thing, as each step of the chain should be obvious enough considered in isolation. If it isn't, then that's a sign of a bigger problem, which may suggest that it isn't so much a matter of two many constructors, as too few classes, and they should be separated out into different classes entirely (though perhaps sharing a common base or implementing a common interface).

How many constructors is too many?


Having trouble with limit

Question: $$\lim \nolimits_{a\to b}\frac{a^{2}-(b+1)a+b}{a^{3}-b^{3}} $$
Need some help to solve it.
I tried hopitals but cant get the answer.
Comment: What went wrong with what you tried?
Comment: **HINT**: Try factorizing the numerator and denominator first
Answer: Hint:
Factor $a^3-b^3=(a-b)(a^2+ab+b^2)$ and rearrange the numerator as well $a^2-(b+1)a+b=(a-1)(a-b)$.
Answer: Hint: show that $\frac{(a^2-(b+1)a+b}{a^3-b^3}=\frac{a-1}{a^2+ab+b^2}$
Answer: Since we have the following equivalences for $a\neq b$
\begin{align*}
\frac{a^2-(b+1)a+b}{a^3-b^3}&=\frac{a^2-ab-a+b}{(a-b)(a^2+ab+b^2)},\qquad a\neq b\\
&=\frac{(a-b)(a-1)}{(a-b)(a^2+ab+b^2)},\qquad a\neq b\\
&=\frac{a-1}{a^2+ab+b^2}
\end{align*}
It follows $$\lim_{a\to b}\frac{a^2-(b+1)a+b}{a^3-b^3}=\frac{b-1}{3b^2}$$
Answer: In the numinator we have $a^2  -(b+1)a + b$ =$(a-b)(a-1)$. Moreover the denominator $a^3 - b^3$ can be written as $(a-b)(a^2  + ab + b^2)$. Evaluating the fraction gives $\frac{a-1}{a^2+ab+b^2}$ and so the limit is $\frac{b-1}{3b^2}$ as $a$$\rightarrow$$b$.

Having trouble with limit


Attempt at Proving a Theorem about Integrals

Question: Let $f,g$ $[a,b]$ $\rightarrow$ $\mathbb{R}$ two continuous functions ang $g$ positive. Show that there exists $\xi$ $\in$ $[a,b]$ such that $\int_a^b f(x)g(x)dx$ = $f(\xi) \int_a^b g(x)dx$
attempt at proof
The intermediate theorem for integrals implies that: $\exists$ $\xi$ $\in$ $[a,b]$ such that:
$\int_a^b f(x)g(x)dx$ = $f(\xi)g(\xi)(b-a)$
But we have $g(\xi)(b-a)$ = $\int_a^b g(x)dx$
Therefore $f(\xi)g(\xi)(b-a)$ = $f(\xi)\int_a^b g(x)dx$
Is that proof valid?
And if not, what's a valid proof?
Comment: It's not valid, the points $\xi$ and $\zeta$ with $\int_a^b f(x)g(x)\,dx = f(\xi)g(\xi)(b-a)$ and $\int_a^b g(x)\,dx = g(\zeta)(b-a)$ generally aren't the same. Note that $m \leqslant f(x) \leqslant M \implies mg(x) \leqslant f(x)g(x) \leqslant Mg(x)$.
Comment: The proof is invalid since the "$\xi$'s" are different.
Comment: When you say "But we have..." there is a mistake: there is no reason to believe in $g( \xi) (b-a)= \int_a^b g(t) dt$
Answer: HINT:
Note that since $g(x)>0$, and then $$\inf_{x\in[a,b]}\{f(x)\}\,g(x)\le f(x)\,g(x)\le \sup_{x\in[a,b]}\{f(x)\}\,g(x) \tag 1$$
Then, apply the intermediate value theorem to the continuous function $f$.
SPOILER ALERT:  Scroll over the highlighted area to reveal the solution

Let $m=\min_{x\in[a,b]}\{f(x)\}$ and $M=\max_{x\in[a,b]}\{f(x)\}$.  Using $(1)$ we can write $$m \le \frac{\int_a^b f(x)\,g(x)\,dx}{\int_a^b g(x)\,dx}\le M\tag 2$$From the intermediate value theorem, for any number $I$ such that $m\le I\le M$, there exists a number $\xi \in(a,b)$ such that $f(\xi)=I$.  Applying this to $(2)$ we find that there exists a $\xi\in(a,b)$ such that $$f(\xi)=\frac{\int_a^b f(x)\,g(x)\,dx}{\int_a^b g(x)\,dx} \tag 3$$Multiplying both sides of $(3)$ by the positive number $\int_a^b g(x)\,dx$ yields the coveted result $$\int_a^b f(x)\,g(x)\,dx=f(\xi)\int_a^bg(x)\,dx$$ for some $\xi\in(a,b)$ as was to be shown!
Comment: how did you pass from 1 to 2, how did you get $m \le \frac{\int_a^b f(x)\,g(x)\,dx}{\int_a^b g(x)\,dx}\le M\tag 2$ from 1?
Comment: Since $f$ is continuous, its infimum and supremum are its minimum and maximum, respectively.   Then, since $g>0$, $mg\le fg\le Mg$ and $\int_a^b mg(x)\,dx\le \int_a^b f(x)g(x)\,dx\le \int_a^b Mg(x)\,dx$.


Problema com ToString no Android Studio

Question: Tenho variáveis do tipo String e variáveis do tipo Int. Quando faço getText.ToString() em uma variável do tipo int o Android Studio apresente erro devido ao tipo de variável não ser uma String.
Alguém saberia qual opção eu posso usar para as variáveis do tipo Int?

package studio.com.projetofinal;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.util.List;

public class CadastroActivity extends AppCompatActivity {

   private DBcadastro dh;
    EditText etnome, etcpf, etidade, ettelefone, etemail;
    Button InserirDB;
    Button ListarCadastro;

    Button btvoltar;

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

        btvoltar = (Button) findViewById(R.id.voltar);
        btvoltar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                voltarHome();
            }
        });

        this.dh = new DBcadastro(this);
        etnome = (EditText) findViewById(R.id.etnome);
        etcpf = (EditText) findViewById(R.id.etcpf);
        etidade = (EditText) findViewById(R.id.etidade);
        ettelefone = (EditText) findViewById(R.id.ettelefone);
        etemail = (EditText) findViewById(R.id.etemail);

        InserirDB = (Button) findViewById(R.id.InserirDB);
        ListarCadastro = (Button) findViewById(R.id.ListarCadastro);

        InserirDB.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if (etnome.getText().length()>0 && etcpf.getText().length()>0 && etidade.getText().length()>0 && ettelefone.getText().length()>0 && etemail.getText().length()>0){
                    dh.insert(etnome.getText().toString(),etcpf.getText().toString(),etidade.getText().toString(),ettelefone.getText().toString(),etemail.getText().toString());
                    AlertDialog.Builder adb = new AlertDialog.Builder(CadastroActivity.this);
                    adb.setTitle("Sucesso");
                    adb.setMessage("Cadastro Realizado!");
                    adb.show();

                    etnome.setText("");
                    etcpf.setText("");
                    etidade.setText("");
                    ettelefone.setText("");
                    etemail.setText("");

            }else {
                    AlertDialog.Builder adb = new AlertDialog.Builder(CadastroActivity.this);
                    adb.setTitle("Erro");
                    adb.setMessage("Todos os campos devem ser preenchidos!");
                    adb.show();

                    etnome.setText("");
                    etcpf.setText("");
                    etidade.setText("");
                    ettelefone.setText("");
                    etemail.setText("");
                }
        }

    });

     ListarCadastro.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {

             List<cadastro> cadastro = dh.queryGetALL();
             if(cadastro == null){
                 AlertDialog.Builder adb = new AlertDialog.Builder(CadastroActivity.this);
                 adb.setTitle("Mensagem");
                 adb.setMessage("Não há registros cadastrados!");
                 adb.show();

                 etnome.setText("");
                 etcpf.setText("");
                 etidade.setText("");
                 ettelefone.setText("");
                 etemail.setText("");
                 return;
             }

             for (int i=0;i<cadastro.size();i++){
                 cadastro cadsatro = (cadastro) cadastro.get(i);
                 AlertDialog.Builder adb = new AlertDialog.Builder(CadastroActivity.this);
                 adb.setTitle("Registro "+ i);
                 adb.setMessage("Nome: "+ cadsatro.getNome()+ "\nCPF: "+ cadsatro.getCpf() + "\nIdade: "+ cadsatro.getIdade() +
                         "\nTelefone: " + cadsatro.getTelefone() + "\n Email: " + cadsatro.getTelefone());
                 adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                     @Override
                     public void onClick(DialogInterface dialog, int which) {
                         dialog.dismiss();
                     }
                 });

                 adb.show();
             }

         }

     });

    void voltarHome(){
        Intent intent = new Intent();
        intent.setClass(CadastroActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}

Comment: Provavelmente na função `dh.insert` você deve recer int, então faça o parse: `Integer.parseInt(campo.getText().toString())` ou `Integer.valueOf(campo.getText().toString())`, não lembro
Comment: Ok Guilherme Costamilam esta solução que você sugeriu funcionou.
Answer: O Android Studio está reclamando que o método insert() espera 3 parâmetros do tipo int, mas você os está passando como String, justamente por utilizar o método toString(). Não faz muito sentido.
Nesse caso, você tem que usar a classe wrapper Integer, mais especificamente o método parseInt(), que vai pegar o conteúdo do EditText e convertê-lo para um valor inteiro, retornando um int:
Integer.parseInt(campo.getText().toString())

Comment: Ok StatelessDev esta solução que você sugeriu funcionou.
Comment: Se a resposta lhe ajudou, marque-a como correta para ajudar futuros usuários que tenham um problema similar ao seu.

Problema com ToString no Android Studio


Why the following set {max(f,g) < b} can be written as an intersection?

Question: In one of the notes I have they say the following:
$$
\{max(f,g) < b\} = \{f < b\} \cap \{g < b \}
$$
and
$$
\{min(f,g) < b \} = \{f < b \} \cup \{g < b \}
$$
where $f,g$ are extended real-valued functions and b is a real number. I can't understand why these hold. Can anyone explain it?
Answer: We have $\max(f(x),g(x))<b$ if and only if both $f(x)<b$ and $g(x)<b$, this easily follows from the definition of a maximum. Hence $x\in \{\max(f,g)<b\}$ iff $x$ is in both $\{f<b\}$ and  $\{g<b\}$, iff $x\in \{f<b\}\cap\{g<b\}$.
Similarly, $\min(f(x),g(x))<b$ if and only if $f(x)<b$ or $g(x)<b$.
Answer: Let $x\in\{max(f,g)<b\}$. Let $f(x)\leq g(x)$ without loss of generality. Then $f(x)\leq g(x)<b$, thus both $f(x)<b$ and $g(x)<b$ hold. Hence $x$ lies in both $\{f(x)<b\}$ and $\{g(x)<b\}$.
As for the second, pick $x$ in $\{\min(f,g)<b\}$. Assume again that $f(x)\leq g(x)$. Then $f(x)<b$, hence $x$ lies in $\{f(x)<b\}$, hence in the union $\{f(x)<b\}\cup\{g(x)<b\}$.


Is there a way to smooth out the transition of a graphics component from one point to another using Timer class in Java?

Question: I am trying to get a simple animation done smoothly in Java using Timer class, i.e. to move a target from its current position to the farthest end-of-frame horizontally.
I have used the graphics component's current position inside the Timer class's actionPerformed() method and have been increasing the x location of the component by a certain amount but when I try to run it the component instantly jumps to the next location and waits for the timer to complete and repaint to a new location. (I apologize if I am not phrasing the problem properly.)
I have included the code as a whole so as to provide the entire context:
public class FireAtBill extends JPanel {
    private static final long serialVersionUID = 4682094035006759518L;

    private int hits, misses;
    private Point targetPos;
    private Timer t;
    private BufferedImage crosshair, target;

    public FireAtBill() {

        Random random = new Random();
        targetPos = new Point(random.nextInt(500),random.nextInt(500) );
        t = new Timer(500, new TimerListener());
        t.start();

        setForeground(Color.WHITE);
        setBackground(Color.BLACK);

        try {
            crosshair = ImageIO.read(new File(System.getProperty("user.dir")+ "/crosshair.jpg"));
            target = ImageIO.read(new File(System.getProperty("user.dir")+ "/target.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void paintComponent(Graphics g) {

        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.drawString("hits: " + hits + "  misses: " + misses, 0, 10);
        g2.drawImage(crosshair, 125, 50, this);
        g2.drawImage(target, targetPos.x, targetPos.y, this);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Fire At Bill");
        frame.setSize(500,500 );
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        FireAtBill fireAtBill = new FireAtBill();
        frame.getContentPane().add(fireAtBill);
        frame.setVisible(true);
    }

    private class TimerListener implements ActionListener{
        double x = targetPos.getX();
        public void actionPerformed(ActionEvent event) {
            if (x <= 500||targetPos.getX() >= 0) {
                if (x<250) {
                    targetPos.setLocation(targetPos.getX()+15, targetPos.getY());
                }
                else {
                    targetPos.setLocation(targetPos.getX()-15, targetPos.getY());
                }
            }
            repaint();
        }

    }

}

I expect the target to move smoothly across the screen horizontally, but the target is jumping from one location to another.
I have tried to increment the x position of the target using smaller values and while this smooths out the movement, it does so at the cost of the speed of the target which I hope to implement as a variable which can be altered by changing its value.
Thanks in advance.
Answer: Okay, I found that by decreasing the delay value when initializing the Timer object I can speed up the repaint process here t = new Timer(500, new TimerListener()); by changing 500 to something like 50. Decreasing this value will speed up the animation.
And the smoothing can be implemented by decreasing the increment value inside the actionPerformed() method of the TimeListener class here targetPos.setLocation(targetPos.getX()+15, targetPos.getY());by changing the increment value 15 to something like 3. Decreasing this value will help smooth the animation.
Comment: Decrease the time between updates to `5` milliseconds (I think that's about 200fps), then adjust the delta.  You might need to use a `double` value instead, but you'll get a much smoother and more control over the process
Comment: @MadProgrammer 200 fps sounds sweet... my system barely reaches 100. I'll go with 10 then. I agree with you on the delta, a `double` value would be smoother than the snail. Thanks.


Why not sample action from Q values?

Question: When collecting experience from which to estimate a Q(s,a) function, one common technique in the literature is to follow an epsilon greedy-strategy. In this strategy, the agent selects a random action with a probability of epsilon, and the action associated with the maximum Q value otherwise.
Alternatively, why not treat the Q values as a distribution from which to sample an explorative action?
Eg: Take the softmax of the q values, and then sample from the softmax distribution to select the action.
Since Q-Learning is off-policy, it should be mathematically sound to do so. Are there any studies where this was considered?
Answer: Yes, it's a common thing to do so it's called Boltzmann exploration. It's like softmax but you have additional temperature hyperparameter $T$. The full distribution is
\begin{equation}
p(a) = \frac{e^{\frac{Q(s,a)}{T}}}{\sum_{a'} e^{\frac{Q(s,a')}{T}}}
\end{equation}
Hyperparameter $T$ decides how random/greedy you want to be. For large values of $T$ distribution will tend to uniform distribution which means we are randomly picking actions no matter how large their Q-values are. For small value $T$ we will tend to be greedy and pick action with highest Q-value

Why not sample action from Q values?


How does vundle treat breaking changes if uses configuration with links to git repositories?

Question: If I do :PluginUpdate, how could I be sure developers of the plugins listed in .vimrc as links to git repositories have not updated their repositories with breaking changes?
For example, I am using link to the repository Plugin 'tpope/vim-fugitive' and I don't want this dependency to introduce breaking changes on the next upgrade.
In general, does development of vim plugins entail convention of not putting breaking changes into the latest master branch? I doubt such convention exist, but still, is there kind of policy for vim plugins to avoid breaking configuration with plugins upgrade?
Answer: In general, you have to trust the plugin developer on this one.

Most plugins have a changelog in some form; ideally, you would check that before the update (but doing that would reduce the automation benefits of :PluginUpdate). If you notice that a plugin got broken, manual upgrade steps should be found in the changelog, and help you to quickly resolve the problem.
Some plugins tag releases or offer a stable branch for tested official releases. Using that as the basis for the update should greatly reduce the opportunities for regressions caused by using intermediate development snapshots.
Ideally, there would be separate stable/major-version branches, and the plugin would follow Semantic Versioning, so you're guaranteed to only receive compatible changes automatically, and switching to a new incompatible version would be a manual, controlled step.


Let T be a spanning tree of a connected graph G..

Question: Let $T$ be a spaning tree of a connected graph $G$ and let $e$ be an edge of $G$ not in $T$.Show that $T+e$ contains a unique cycle.
So we know that if $T$ is spanning tree $\rightarrow$ $T$ is maximally acyclic, which means adding any edge will create a cycle, $\rightarrow$ $T+e$ creates a cycle. We can assume by contradiction that $T+e$ is not unique cycle which means that $\exists$ another cycle which is a contradiction, since spanning tree $T$ does not have any loops or cycles, since removing one edge from spanning tree will make the graph disconnected, since spanning tree is minimally connected.
I don't know if this is enough to say that i "solved" this problem, maybe i should add something more?
Thanks in advance.
Answer: not exactly, but close.  you need to prove e forms a cycle as well.  It is pretty simple, but it is necessary.  (also T+e contains a unique cycle, not is a unique cycle)
Comment: also need to show that the vertices that e connects only have one common parent so that it only creates one cycle.  All of this is quite easy, but necessary.

1.  there wasnt a cycle b4

2.  the edge creates exactly 1 cycle
Comment: So we know that if $T$ is spanning tree $\rightarrow$ $T$ is maximally acyclic, which means adding any edge will create a cycle, $\rightarrow$ $T+e$ creates a cycle. We can assume by contradiction that $T+e$ is not unique cycle which means that $\exists$ another cycle which is a contradiction, since spanning tree $T$ does not have any loops or cycles, since removing one edge from spanning tree will make the graph disconnected, since spanning tree is minimally connected. That would be enough?
Comment: (sorry for formatting, still getting used to stack)  That is most likely good enough, ya.  i would of said assume T+e has more then 1 unique cycle while T has no cycle, These unique cycles must all use e.  so for e to be an edge from node A to B that has 2 unique cycles through it, there must be 2 unique paths from A to B without e.  this would mean there is a cycle through these two paths that does not have e in it, which is a contradiction.


Display Image logo along with site slogan and site name

Question: I  am using Impact theme for my site. It either displays text logo(site name, site slogan) or image logo. I want both image logo and text logo for my site.
Any help is welcome.
Answer: I would recommend to use the "Panels" module to do that. Create a "mini-panel" and while editing one of it's panes (boxes of content) choose on the edit menu "Page elements" and then add "Logo, "Site name", and "Site slogan" respectively. Make sure you arrange them as your liking.
The second part of your work is to do some CSS for this. The Panels css system takes some time to learn --- You should use DOM tags carefully to isolate the Id's and classes of the right div's and manipulate them in relation to their upper div's, but it's worth the shot.
If your site is responsive you should add some responsiveness with a Media query, i.e:
@media screen and (max-width:519px) {#panel-col-first {width:100%;} #panel-col-last {width: 100%;}}

In Panels, make sure that after you choose basic details and layout you navigate in "content" tab. Then, Add the aforementioned details - Here is a screen that'll show you how:
Answer: I assume you have created a sub-theme, in that case, copy the page.tpl.php from the parent Impact Theme to your sub-theme if you haven't already, and delete the else statement (line 73):
<?php if (theme_get_setting('image_logo','impact_theme')): ?>
  <?php if ($logo): ?>
<a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>">
    <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

<?php endif; ?>

<?php else: ?>

  <hgroup id="site-name-wrap">

      <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>">
        <?php print $site_name; ?>

    <?php if ($site_slogan): ?>
<?php print $site_slogan; ?>
<?php endif; ?>
  </hgroup>
<?php endif; ?>

Be aware that the setting for deciding whether to use the logo or the text will no longer work in a either/or scenario, it would force all or nothing. You can get rid of the IF statement entirely, and the setting becomes useless
Comment: I haven't created child theme
Comment: Well its a good idea to always work from a sub theme but failing that you can make the same changes to the impact themes page.tpl.php
Comment: I deleted else statement as per you instruction but now none of the text logo or image logo is displayed. Section above menu are not displaying now
Comment: check the settings for theme - as I said, if you only delete the else statement, it changes it from either/or, to all or nothing, so the setting for logo verses site name is probably still set - as I also said, you can delete the if statement entirely to remove the functionality of that setting
Comment: Thanks @Geoff I deleted If statement as well and now it is working fine.


create order - drupal commerce

Question: I'm developing an eCommerce website using Drupal Commerce.
I've been asked from my management to allow several users to use the 'create order' page in the admin store section (orders page) to stimulate sales.
The 'create order' page is sufficient by itself, but adding a product (line item) isn't that friendly, so I need to figure out a way to develop a 'browse products' function that'll allow me to add products to the order I'm creating.
Is there an easy way to do so? Maybe creating an all new 'create order' page? If so, what is the best appraoch without changing the drupal core code?
Comment: Are you using Drupal version 7 or 8?
Comment: am using drupal 7
Answer: Of course you can create custom order form and page in new custom module. I think you understand drupal 7 FORM API, so you have to create new page with form.
You can process form values (i mean in form submit funtion) using entity API.
To create an order for current user:
<code>global $user;

$order = commerce_order_new($user->uid, $status = 'pendig', $type = 'commerce_order');
commerce_order_save($order);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
</code>
To add billing info:
<code>$profile = new stdClass();
$profile->type = 'billing';
$profile->uid = $user->uid;
$profile->status = '1';

$profile->commerce_customer_address['und'][0]['country'] = $your_country;
$profile->commerce_customer_address['und'][0]['locality'] =$your_locality;
$profile->commerce_customer_address['und'][0]['postal_code'] = $your_postal_code;
$profile->commerce_customer_address['und'][0]['thoroughfare'] = $address;
$profile->commerce_customer_address['und'][0]['first_name'] = $first_name;
$profile->commerce_customer_address['und'][0]['last_name'] = $last_name;

commerce_customer_profile_save($profile);

$order_wrapper->commerce_customer_billing = $profile->profile_id;
</code>
Then you can add products to this order:
Presume that $products is an array of arrays of products ids and quantity of this product user is buying (EG.
<code>$products = array(
array('product_id' => 22, 'quantity' => 1),
 array('product_id' => 23, 'quantity' => 3),
);

foreach ($products as $item) {
$product = commerce_product_load($item['product_id']);
$line_item = commerce_product_line_item_new($product, $item['quantity'], $order->order_id);
commerce_line_item_save($line_item);
$order_wrapper->commerce_line_items[] = $line_item;

}
//to save line items and billing info in your order
commerce_order_save($order);
</code>
Comment: Thank you for providing the code, i'll try it and get back to you...cheers

create order - drupal commerce


AngularJS v1.4.4 'expected identifier' error on IE10

Question: I am creating an MVC5 with Angular JS project (angular version v1.4.4) in VS2013. I was coding along and everything was fine and then suddenly I started getting this error on launch:

JavaScript critical error at line 5395, column 34 in http://localhost:63937/Scripts/angular.js\n\nSCRIPT1010: Expected identifier

I only get this error on IE10, it works fine on Chrome.
My references are in a layout file and look like this:
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/Site.css" rel="stylesheet" />

The HTML page contains the reference to the App.js file. I could post some code, but it doesn't even seem to be hitting the App.JS file. Anyone ran into this issue or have any suggestions as to where I should start looking for the issue? As far as I know, I reverted my code back to the point where it was working in IE10 but it still wont run.
Here is the specific function in the angular.js file that contains the line number from the error. The specific line is in return statement in the 'catch' function:
getPromise: function() {
  if (!this.defer) {
    this.defer = $q.defer();
  }
  return this.defer.promise;
},
then: function(f1,f2) {
  return this.getPromise().then(f1,f2);
},
'catch': function(f1) {
  return this.getPromise().catch(f1);
},
'finally': function(f1) {
  return this.getPromise().finally(f1);
}

Any help would greatly be appreciated.
Comment: I would recommend you use version `1.3.18` since it's the last stable release. As of today the AngularJS team haven't released a stable `1.4.x` release yet.
Comment: @yvesmancera, are you sure? In Visual Studio 2013 NuGet Manager it's listed as a stable version
Comment: My bad, It looks like you're right, 1.4.4 is a stable release.
Comment: I found this [issue](https://github.com/angular/angular.js/issues/4641) on AngularJS, it says it affects IE8 but it might also be affecting IE10. It doesn't allow `catch` as an identifier since it's a reserved word on ES3.
Answer: It looks like this was recently introduced specifically in v1.4.4 according to the changelog:

$animateCss: make sure that skipBlocking avoids the pre-emptive transition-delay styling

To expand a bit more the line that's throwing the error for some context:
var $CoreAnimateCssProvider = function() {
  this.$get = ['$$rAF', '$q', function($$rAF, $q) {

    var RAFPromise = function() {};
    RAFPromise.prototype = {
      done: function(cancel) {
        this.defer && this.defer[cancel === true ? 'reject' : 'resolve']();
      },
      end: function() {
        this.done();
      },
      cancel: function() {
        this.done(true);
      },
      getPromise: function() {
        if (!this.defer) {
          this.defer = $q.defer();
        }
        return this.defer.promise;
      },
      then: function(f1,f2) {
        return this.getPromise().then(f1,f2);
      },
      'catch': function(f1) {
        return this.getPromise().catch(f1);
      },
      'finally': function(f1) {
        return this.getPromise().finally(f1);
      }
    };
//... more code

This $CoreAnimateCssProvider wasn't included in 1.4.3 so it's definitely new.
My suggestion is that you try version 1.4.3 for now, until this bug is fixed.
Comment: I tried 1.4.3 and angular.min.js just threw a new error: SCRIPT5007: Object expected File: angular.min.js, Line: 7, Column: 238. And this was in IE 11.0.9600. Also tried 1.6.1 with another error at a .catch.
Answer: I had a similar issue in IE 11.0.9600. I tried 1.4.3 and angular.min.js just threw a new error:
SCRIPT5007: Object expected
File: angular.min.js, Line: 7, Column: 238.

Also tried 1.6.1 which threw another error at a different ".catch" in the js.
However, this error could also be caused by the doctype being screwed up and IE trying to parse things in an old mode. To fix, either add to your web.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <clear />
        <add name="X-UA-Compatible" value="IE=10" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

Or, in your master layout page add:
<meta http-equiv="X-UA-Compatible" content="IE=11" />

And also check your doctype declaration is the simple:
<!doctype html>

On a side note, there are several other gotchas with using angularjs in IE browsers (even the newest ones), which comes down to using:

ng-style tags instead of style="{{ someCss }}"
ng-attr-type tags instead of type="{{ someExpression }}" in buttons
ng-attr-value tags instead of value="{{ someExpression}}"
ng-attr-placeholder tags instead of placeholder="{{ someExpression }}"

See IE compatibility with angular


Tabelas de MYSQL

Question:
Como mostra a imagem, tenho a tabela adms_unidade onde já consigo mostrar as unidades listadas, e tenho a tabela adms_equipamentos com vários equipamentos cadastrados.
Quero mostrar quantos equipamentos cadastrados possuo em cada unidade usando o adms_unidade_id que é a chave estrangeira da tablea adms_equipamentos referente a chave primary da tabela adms_unidades.
já vi alguns exemplos e maneiras, mas não sei se é erro de digitação ou não.
Comment: Faça um INNER JOIN das tabelas e utilize a função de agregação COUNT com a clausula GROUP BY. Postar imagens no lugar dos códigos não é uma atitude bem vista neste site, o mesmo para não postar o código da consulta que tentou com a explicação de porque considera o resultado errado.
Answer: Boa noite,
basta fazer a ligação da tabela adms_equipamentos com a adms_unidades com left outer join, no caso de não existir equipamentos cadastrados para aquela unidade, e então você agrupa pela unidade e conta quantos registros existem para cada agrupamento.
select au.nome_da_unidade, count(*) qtd_equipamentos
from adms_unidades au
left outer join adms_equipamentos ae
on ae.adms_unidade_id = au.id
group by au.nome_da_unidade

Tabelas de MYSQL


Why isn't RANSAC most widely used in statistics?

Question: Coming from the field of computer vision, I've often used the RANSAC (Random Sample Consensus) method for fitting models to data with lots of outliers.
However, I've never seen it used by statisticians, and I've always been under the impression that it wasn't considered a "statistically-sound" method. Why is that so? It is random in nature, which makes it harder to analyze, but so are bootstrapping methods.
Or is simply a case of academic silos not talking to one another?
Comment: I wonder one thing about computer vision methods vs. statistics methods: performance in the first is a must. Maybe there's a trade-off between performance and "correctness", and computer vision and statistics have different weights for those variables.
Answer: I think that the key here is the discarding of a large portion of the data in RANSAC.
In most statistical applications, some distributions may have heavy tails, and therefore small sample numbers may skew statistical estimation. Robust estimators solve this by weighing the data differently. RANSAC on the other hand makes no attempt to accommodate the outliers, it's built for cases where the data points genuinely don't belong, not just distributed non-normaly.
Comment: Great answer. I have seen RANSAC most used in CV to estimate homographies. This is most widely used when we know that some of the corresponding measurements are hugely unreliable. Also, real time performance and other considerations has made this technique quite popular as it can be easily parallelised.
Answer: For us, it is just one example of a robust regression -- I believe it is used by statisticians also, but maybe not so wide because it has some better known alternatives.
Comment: The mostly known and the simplest is the Median-Median regression, well known from smart calculators (Sigh!). Consult also Wikipedia  http://en.wikipedia.org/wiki/Robust_regression and maybe CRAN's Robust task view http://cran.r-project.org/web/views/Robust.html
Comment: Can you give examples of alternatives? I'd like to look into that.
Comment: Are there alternatives to RANSAC which not only give you the unbiased regression but also the data points from which the model has been estimated? Thanks
Answer: This sounds a lot like bagging which is a frequently used technique.
Comment: RANSAC is very different - in bagging, all samples are taken into account in some way. RANSAC is used in cases where up to 50% of the data should be completely discard.
Answer: You throw away data with RANSAC, potentially without justifying it, but based on increasing the fit of the model. Throwing away data for increased fit is usually shun as you may loose important data. Removal of outliers without justification is always problematic.
It is ofcourse possible to justify it. E.g. if you known the data should follow a given pattern, but that there also are deviation in the data from the pattern due to error in the measurements.


How many different telephone numbers are possible in city A?

Question: The local seven-digit telephone numbers in city A have $555$ as the first three digits. How many different telephone numbers are possible in city A?
Answer: There are $10$ possibilities ($0, 1, 2, 3, 4, 5, 6, 7, 8, $ and $9$) for the fourth digit,
$10$ for the fifth digit, $10$ for the sixth digit, and $10$ for the seventh digit -- $10^4$ altogether.
Answer: There are seven total digits. The first 3 are already selected, so there is a choice for 4 digits.
There are 10 possible choices for each of the other 4 digits, so there are a total of $10×10×10×10$ or $10^4$ choices
Answer: $10^4=10000$, because for the remaining $4$ digits, all $10$ options are possible.


Generate / create mdump files for in my app

Question: Im looking for a way to generate minidump files in my applications simular to what ProcDump does but prefarably with code and not having to extract a 3dparty tool to do it.
The main reasons for not wanting to use ProcDump is:
1) Size of the binary would increase greatly ( This is a problem because my apps are freeware, and bandwith is not free).
2) Feels dirty.
3) No way i can port that app to run inn windows mobile.
My requirements are:
1) Ability to generate mdump files in a fatale crash.
2) Abilityt to do "pause" the app do a dump, and contiune would be a bonus.

If this is not realy a option, is there a way to get the values of local varibales in the current context dynamicly?
Side note:
I did find this article, but its very old so i so im hesitant to base my work of it.
There seems to either be a issue with IE 9 or with the site, so i had problems with tags.
Comment: any final good solution about this issue? with good sample application source code in .NET ?
Answer: So there is one solution that comes to mind and meets the following goals:

Size of the binary would increase by around 300k
Ability to generate mdump files in a fatale crash.
Ability to do "pause" the app do a dump, and contiune would be a bonus

I'll give this requirement a complete unknown:

No way i can port that app to run inn windows mobile.

So what's the solution?
Integrate the required parts you need from the Microsoft Sample for MDbg.exe to provide you with a 'just-in-time' debugger that attaches, dumps, and detaches from the crashing process.
Step 1 - Start by downloading the source code to the mdbg from here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=38449a42-6b7a-4e28-80ce-c55645ab1310&DisplayLang=en
Step 2 - Create a 'crash' handler that spawns a debugger process and waits for completion.  I used the following few lines of code to re-launch the same exe with a few extra arguments to invoke the debugger and output an xml file to std::out.
string tempFile = Path.GetTempFileName();
Mutex handle = new Mutex(true, typeof(Program).Namespace + "-self-debugging");
try
{
    Process pDebug = Process.Start(typeof(Program).Assembly.Location,
        "debug-dump " + Process.GetCurrentProcess().Id + " " + tempFile);
    if (pDebug != null)
        pDebug.WaitForExit();
}
catch { }
finally
{
    handle.ReleaseMutex();
}

Console.WriteLine(File.ReadAllText(tempFile));

Step 3 - Write the debug dump routine, this can be in the same exe or in a different exe.  You will need to reference (or include the source from) the 'raw', 'corapi', and 'mdbgeng' modules from the sample.  Then add a few lines to your Main():
public static void Main(string[] args)
{
    if (args.Length > 0 && args[0] == "debug-dump")
    {   //debug-dump process by id = args[1], output = args[2]
        using (XmlTextWriter wtr = new XmlTextWriter(args[2], Encoding.ASCII))
        {
            wtr.Formatting = Formatting.Indented;
            PerformDebugDump(Int32.Parse(args[1]), wtr);
        }
        return;
    }
    //... continue normal program execution
}

static void PerformDebugDump(int process, XmlWriter x)
{
    x.WriteStartElement("process");
    x.WriteAttributeString("id", process.ToString());
    x.WriteAttributeString("time", XmlConvert.ToString(DateTime.Now, XmlDateTimeSerializationMode.RoundtripKind));

    MDbgEngine e = new MDbgEngine();
    MDbgProcess me = e.Attach(process);
    me.Go().WaitOne();

    try
    {
        x.WriteStartElement("modules");
        foreach (MDbgModule mod in me.Modules)
            x.WriteElementString("module", mod.CorModule.Name);
        x.WriteEndElement();

        foreach (MDbgThread thread in me.Threads)
        {
            x.WriteStartElement("thread");
            x.WriteAttributeString("id", thread.Id.ToString());
            x.WriteAttributeString("number", thread.Number.ToString());
            int ixstack = -1;

            foreach (MDbgFrame frame in thread.Frames)
            {
                x.WriteStartElement("frame");
                x.WriteAttributeString("ix", (++ixstack).ToString());
                x.WriteAttributeString("loc", frame.ToString(String.Empty));
                string valueText = null;

                x.WriteStartElement("args");
                try
                {
                    foreach (MDbgValue value in frame.Function.GetArguments(frame))
                    {
                        x.WriteStartElement(value.Name);
                        x.WriteAttributeString("type", value.TypeName);
                        try { x.WriteAttributeString("value", value.GetStringValue(1, false)); }
                        finally { x.WriteEndElement(); }
                    }
                }
                catch { }
                x.WriteEndElement();

                x.WriteStartElement("locals");
                try
                {
                    foreach (MDbgValue value in frame.Function.GetActiveLocalVars(frame))
                    {
                        x.WriteStartElement(value.Name);
                        x.WriteAttributeString("type", value.TypeName);
                        try { x.WriteAttributeString("value", value.GetStringValue(1, false)); }
                        finally { x.WriteEndElement(); }
                    }
                }
                catch { }
                x.WriteEndElement();
                x.WriteEndElement();
            }
            x.WriteEndElement();
        }
    }
    finally
    {
        me.Detach().WaitOne();
    }

    x.WriteEndElement();
}

Example Output
<process id="8276" time="2010-10-18T16:03:59.3781465-05:00">
<modules>
<module>C:\Windows\assembly\GAC_32\mscorlib\18.104.22.168__b77a5c561934e089\mscorlib.dll</module>
...etc
</modules>
<thread id="17208" number="0">
<frame ix="0" loc="System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop (source line information unavailable)">
    <args>
        <this type="System.Windows.Forms.Application.ComponentManager" value="System.Windows.Forms.Application.ComponentManager
    oleComponents=System.Collections.Hashtable
 cookieCounter=1
    activeComponent=System.Windows.Forms.Application.ThreadContext
 trackingComponent=<null>
 currentState=0" />
        <dwComponentID type="N/A" value="<N/A>" />
        <reason type="System.Int32" value="-1" />
        <pvLoopData type="System.Int32" value="0" />
    </args>
    <locals>
        <local_0 type="System.Int32" value="0" />
        <local_1 type="System.Boolean" value="True" />
        <local_2 type="System.Windows.Forms.UnsafeNativeMethods.IMsoComponent" value="<null>" />
        <local_3 type="N/A" value="<N/A>" />
        <local_4 type="N/A" value="<N/A>" />
        <local_5 type="N/A" value="<N/A>" />
        <local_6 type="System.Windows.Forms.Application.ThreadContext" value="System.Windows.Forms.Application.ThreadContext
   contextHash=System.Collections.Hashtable
   tcInternalSyncObject=System.Object
 totalMessageLoopCount=1
    baseLoopReason=-1
  currentThreadContext=System.Windows.Forms.Application.ThreadContext
    threadExceptionHandler=System.Threading.ThreadExceptionEventHandler
    idleHandler=<null>
   enterModalHandler=<null>
 leaveModalHandler=<null>
 applicationContext=System.Windows.Forms.ApplicationContext
 parkingWindow=<null>
 marshalingControl=System.Windows.Forms.Application.MarshalingControl
   culture=<null>
   messageFilters=<null>
    messageFilterSnapshot=<null>
 handle=912
 id=17208
   messageLoopCount=1
 threadState=1
  modalCount=0
   activatingControlRef=<null>
  componentManager=System.Windows.Forms.Application.ComponentManager
 externalComponentManager=False
 fetchingComponentManager=False
 componentID=1
  currentForm=Program.MainForm
   threadWindows=<null>
 tempMsg=System.Windows.Forms.NativeMethods.MSG
 disposeCount=0
 ourModalLoop=False
 messageLoopCallback=<null>
   __identity=<null>" />
        <local_7 type="N/A" value="<N/A>" />
        <local_8 type="N/A" value="<N/A>" />
        <local_9 type="N/A" value="<N/A>" />
        <local_10 type="N/A" value="<N/A>" />
        <local_11 type="N/A" value="<N/A>" />
        <local_12 type="N/A" value="<N/A>" />
        <local_13 type="System.Boolean" value="False" />
        <local_14 type="System.Windows.Forms.NativeMethods.MSG[]" value="array [1]
 [0] = System.Windows.Forms.NativeMethods.MSG" />
    </locals>
</frame>
<frame ix="1" loc="System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner (source line information unavailable)">
    <args>
        <this type="System.Windows.Forms.Application.ThreadContext" value="System.Windows.Forms.Application.ThreadContext
  contextHash=System.Collections.Hashtable
   tcInternalSyncObject=System.Object
 totalMessageLoopCount=1
    baseLoopReason=-1
  currentThreadContext=System.Windows.Forms.Application.ThreadContext
    threadExceptionHandler=System.Threading.ThreadExceptionEventHandler
    idleHandler=<null>
   enterModalHandler=<null>
 leaveModalHandler=<null>
 applicationContext=System.Windows.Forms.ApplicationContext
 parkingWindow=<null>
 marshalingControl=System.Windows.Forms.Application.MarshalingControl
   culture=<null>
   messageFilters=<null>
    messageFilterSnapshot=<null>
 handle=912
 id=17208
   messageLoopCount=1
 threadState=1
  modalCount=0
   activatingControlRef=<null>
  componentManager=System.Windows.Forms.Application.ComponentManager
 externalComponentManager=False
 fetchingComponentManager=False
 componentID=1
  currentForm=Program.MainForm
   threadWindows=<null>
 tempMsg=System.Windows.Forms.NativeMethods.MSG
 disposeCount=0
 ourModalLoop=False
 messageLoopCallback=<null>
   __identity=<null>" />
        <reason type="System.Int32" value="-1" />
        <context type="System.Windows.Forms.ApplicationContext" value="System.Windows.Forms.ApplicationContext
 mainForm=Program.MainForm
  userData=<null>
  ThreadExit=System.EventHandler" />
    </args>
    <locals>
        <local_0 type="System.Windows.Forms.Form" value="<null>" />
        <local_1 type="System.Boolean" value="False" />
        <local_2 type="N/A" value="<N/A>" />
        <local_3 type="N/A" value="<N/A>" />
        <local_4 type="N/A" value="<N/A>" />
    </locals>
</frame>
... etc
</thread>
</process>

Since you have the full power of a debugger there is nothing stopping you from writing as much or as little as you like, but the above example should get you started.
UPDATE
This works with the .Net 2.0 and/or 3.5 runtime without any further dependencies.
This can debug .Net 2.0/3.5 code running in a .Net 4.0 process; however, it does not work with 4.0 (yet).
For 4.0 CLR see this post:
http://blogs.msdn.com/b/rmbyers/archive/2008/10/27/icordebug-re-architecture-in-clr-4-0.aspx
Comment: @csharptest.net - According to the page you linked it requires .Net 2.0 SDK to be installed which might not be available on the client computer. Also, does it support .Net 4 programs?
Comment: this is a real thing to consider - maybe someone knows minimal requirements for end-user deployment?
Comment: Though I have not verified it I do not believe there are any requirements besides the .net runtime. As to .net 4.0 you should only need the sample from that version of the SDK (assuming MS has updated it? IDK, it may even work as it's all COM based. I'll try it without the sdk installed when I get to work.
Comment: @csharptest.net - I've been playing with it and the values of local variables are most of the time N/A (like in your example). Any idea why this is happening and how to avoid it?
Comment: @Giorgi, you might want to make this a separate question.  Post a link to the follow-up question here and I'll see what I can come up with in the mean time.
Comment: @csharptest.net - I'm playing with it so if I don't find anything myself I'll post a question.
Comment: Here is one discussion on the topic: http://social.msdn.microsoft.com/Forums/en-US/netfxtoolsdev/thread/85f54cb7-38d1-42be-b430-d137745b9937
Seems that it may be a result of JIT optimizations, since your not launching the process with a debugger.
Answer: You can call MiniDumpWriteDump  from AppDomain.UnhandledException or Application.ThreadException event handler to create the minidump. This article explains the function in great details: Effective minidumps
You can also use this library which has other functionality too: Catch All Bugs with BugTrap!
Edit
Looks like getting a useful minidump is not that easy. First of all sos.dll complains when the dump is not full (full dumps are about 100-150MB). Secondly, writing dump in catch block is not recommended: Getting good dumps when an exception is thrown.
If you have a winforms application this question has some usefull info: How does SetUnhandledExceptionFilter work in .NET WinForms applications?
Comment: Im already trapping unhanlded Exeptions, but i need to get local variable values. And im basicly looking for a way of doing that dynamicly. And i dont think i can create full dumps, if thats the only option i will do that, but would prefere minidumps yes.
Comment: @EKS - you will need dump for that.
Comment: I figured that, gonna test out what you posted tomorrow.  At a lan party atm :)
Comment: can you please take a look at this: http://stackoverflow.com/questions/3963542/net-runtime-2-0-error-user-machine-what-next I have all the exception handles in place, but they aren't caught anyway.... any experience?


Importing Commerce Orders and Users

Question: I am revamping a website which is uses Drupal Commerce. I want to actually mirror the website and work on it offline before bringing it back onto the server as the newer version.
Obviously while I am doing this there is likely to be orders made and new users registered.
How can I import these or somehow bring the revamped website upto date with all users and orders?
Can anyone see any other issues with doing this also?
Answer: You can use the Commerce Migrate  and import your orders, and Feeds to import users.
From Commerce Migrate project page:

Commerce Migrate is a general-purpose migration framework extending
  Migrate Module for bringing
  store information into Drupal
  Commerce.

Also, there is a thread about this here.

Importing Commerce Orders and Users


NPM library: Converting Milliseconds to Timecode help needed?

Question: Can someone help with a quick script that will convert Milliseconds to Timecode (HH:MM:SS:Frame) with this NPM library?
https://www.npmjs.com/package/ms-to-timecode
I just need to pass a miliseconds number (ie 7036.112) to it and output the converted timecode. I've installed npm and the ms-to-timecode library on my debian server. I know perl/bash, and never coded with these library modules.
Any help is greatly appreciated.
-Akak
Comment: Thanks for the help! These both worked, While I liked the short 3 liner, I do have multiple fps values to pass. I'd like to find out how to pass to STDIN, but can probably google that. Thanks again!
Comment: Check it out: http://kiria.duckdns.org/mstc
Answer: You need to write a javascript code to use this npm module.
const msToTimecode = require('ms-to-timecode');
const ms = 6000;
const fps = 30

const result = msToTimecode(ms, fps)
console.log(result) // Print 00:00:06:00

Comment: Awesome this almost works! Is there a way to pass the ms value in through STDIN?
Answer: If you are using the npm module ms-to-timecode then:
const msToTimecode = require('ms-to-timecode');

const timeCode = msToTimecode(7036, 112);

console.log(timeCode); // displays 00:00:07:04

If you don't want to use the npm module then:
function msToTimeCode(ms, fps) {
    let frames = parseInt((ms/1000 * fps) % fps)
    let seconds = parseInt((ms/1000)%60)
    let minutes = parseInt((ms/(1000*60))%60)
    let hours = parseInt((ms/(1000*60*60))%24);

    hours = (hours < 10) ? "0" + hours : hours;
    minutes = (minutes < 10) ? "0" + minutes : minutes;
    seconds = (seconds < 10) ? "0" + seconds : seconds;
    frames = (frames < 10) ? "0" + frames : frames;

    return hours + ":" + minutes + ":" + seconds + ":" + frames;
};

console.log(msToTimeCode(7036, 112));  // displays 00:00:07:04


What is the greatest remainder if you divide a 2-digit number by its digit sum

Question: I just found this problem and tried to solve it.
I wrote $x=90a+b$ and tried to maximize the function $f(a,b)=\frac{9a+b}{a+b}$ but did not come to any solution.  Then I considered $10a+b = x\pmod{a+b}$ which simplified to $9a = x \pmod{a+b}$.  Then I just tried some numbers.  The biggest remainder I could find was $13$ since $98 = 13 \pmod{17}$.  However, there has to be a more sophisticated way to determine this.  Another question would be, if there even is a generalization for $n$-digits.
Comment: Except that the digit sum of $63$ is $9$ and $63 \equiv 0 \pmod 9$  I think you meant $79$
Comment: @Deavor: Just mentally ran down the list.  I  can't think of anything useful for $n$-digit numbers. The answer will probably be not far from $9n$.
Comment: What about $79$? Trying things seems like the reasonable thing to do, we fairly quickly run out of things to try.
Comment: Guess I overlooked 63 = 15 (mod 16). How did you determine that value? And how about the same question for n-digits? Thank you for your contribution.
Comment: Forgot to tell that, I considered 9a = x(mod a+b) which is equivalent to 10a+b=x(mod a+b)
Comment: Alright. Thank you for your help.
Answer: Once you have found $98 \equiv 13 \pmod {17}$, you only have to consider numbers with digit sums $14$ and above, even $15$ and above if you want to beat $13$.  There are not many of those.  We get $$\begin {array}{c | c} \text {n}&\text {rem} \\\hline 99&9\\98&13\\97&1\\96&6\\95& 11\\89&4\\88&8\\87&12\\86&2\\79&15 \end {array}$$ and now that we find $79 \equiv 15 \pmod {16}$ we are done.
Comment: No, the relationship between numbers and the sum of their digits is rather random, so I suspect you are down to what I would call intelligent brute force.  The intelligent comes from realizing that you only need to check numbers with large enough digit sums.
Comment: Hmm, neat approach. Do you think there is a way which does not need bruteforce?


Exponentiation of Sets Proof

Question: So I am currently attempting to dive into Axiomatic Set Theory but before that I am trying to get a good solid base of Naive Set Theory.
I am stuck on how to prove the following three Theorems:
If $ X^{Y \cup Z} \sim  X^Y$ x $X^Z$
If ($X_1$ x $X_2$)$^Y$ $\sim X_1^Y$ x $X_2^Y$
If $X^{Y x Z} \sim (X^Y)^Z $
Where $\sim$ means that there exists a bijection.
My attempt at the first proof:
If $ F \in X^{Y \cup Z} $ then $ F: {Y \cup Z} \to X $
where $ f_1 : Y \to X$ and $f_2 : Z \to X $
and $ G \in$ $X^Y$ x $X^Z$
where $ g_1: Y \to X $ and $g_2: Z \to X $
then $G(g_1 , g_2) = h $
I am currently unsure as to what g is.
My attempt at the second proof:
If $ f \in $ ($X_1$ x $X_2$)$^Y$ then $ f: Y \to$ ($X_1$ x $X_2$)
and $ g \in $ $X_1^Y$ x $X_2^Y$  then $ g: $  ?
My attempt at the third proof:
Let $\phi: X^{Y x Z} \to (X^Y)^Z $
then $\phi(F)=G, G\vert_y (z) = H, H(y)= F(y,z)$.
Comment: Are $Y$ and $Z$ disjoint?
Comment: Yes, and if it were the case that they were not, from my understanding, you can create a bijections that will make said sets dijoint.
Answer: Well if $f$ is defined on $Y\cup Z$ then $f$ can take as input elements of both $Y$ and $Z$. To construct an element of $X^Y\times X^Z$ you need two maps, one which acts on elements of $Y$ and another which acts on elements of $Z$.
For the second attempt, again you need to create a pair of maps. One from $Y$ to $X_1$ and another from $Y$ to $X_2$. Remember that $f$ will give you pairs of elements in $X_1\times X_2$.
Comment: Thank you, this really helped get the ball rolling, I just edited my question.
Comment: You have to define the map $f_1$. What value should $f_1(y)$ take for $y\in Y$? Remember to use your given data $F$.
Answer: Take $F: X^Y \times X^Z \rightarrow X^{Y \cup Z}$ such that if $f: Y \rightarrow X$ and $g: Z \rightarrow X$ then $F(f,g)=h$ where $h: Y \cup Z \rightarrow X$ is such that $\left.h\right|_Y = f$ and $\left.h\right|_Z = g$.
Take $F_2: X_1^Y \times X_2^Y \rightarrow (X_1 \times X_2)^Y$ such that if $f: Y \rightarrow X_1$ and $g: Y \rightarrow X_1$ then $F_2(f,g)=h$ where $h: Y \rightarrow X_1 \times X_2$ is such that $h(y) = (f(y), g(y))$.
Comment: Thank you.  Thinking about it a little more I started editing it and then saw this response.
Comment: The third one is harder, can't think in a bijection right now.
Comment: @Antioquia3943 BIG ERROR.  I meant the cartesian product of the sets, not the union.  The union would never work.
Comment: Actually i think it's correct with union. If they're disjoint. Disjoint union if they're not.
Comment: @ziggurism I am speaking in reference to the third Theorem.  I initially had $X^{Y\cupZ$ but I meant cartesian product of the sets.
Comment: Oh ok. Why don't you get the first problem before moving on to the third?
Comment: The third one seemed a bit easier for me to grasp. I was just unsure as to how to handle the cross of two exponentiated sets. I just edited my attempt for the third one. I would appreciate if someone could look it over.

Exponentiation of Sets Proof


Include images in Aggregator feed

Question: Drupal 7.  I'm bringing in an RSS feed, and for the most part it's working.  It's not, however, bringing in the images with each entry.  I tried adding an  to the list of allowed tags in the admin screen, to no avail.  The lines come across as this:
<media:thumbnail url="http://www.bjtonline.com/uploads/tx_bjt/FINAL3_Flexjet_thumb_b.jpg"/>

Any ideas?
Comment: That is the correct way (AFAIK) for embedding a thumbnail into an RSS feed. What result are you seeing and what result would you expect?
Comment: The aggregator is simply bringing in the title - which is linked, correctly, to the articles' URL.

I wanted to know how we can modify the module to we can also bring in the image.
Comment: Any ideas?  I see where the module is bringing the data in, I guess I can customize it there...
Answer: As I've not gotten anywhere with this, I'm working around it.  I'm only interested in bringing in the most recent article from a site that's on our own servers - so I'm writing a script that will import it into the node table and I'll use Views for the block.
I'll set the script to run nightly. Thanks for the help guys.
Comment: instead of this you should show up your script.
Answer: You can use Feeds: MediaRSS module to fetch media:thumbnail type of data.
This is from the projects page, currently only supports following media types.

media:content - WORKING
media:title - WORKING
media:description- WORKING
media:keywords (csv)- WORKING
media:thumbnail (url) - WORKING
media:categories (csv)- WORKING
media:player (url) - WORKING

For further reading on media rss:
http://www.rssboard.org/media-rss

Include images in Aggregator feed


How to get friday last week in MYSQL

Question: How to get friday last week  ?
I have tried code the folllowing, but it not forward not backward.
SELECT DATE_FORMAT(LAST_DAY(NOW()) - ((7 + WEEKDAY(LAST_DAY(NOW())) - 4) % 7), '%Y-%m-%d') last_friday;

The result that i need should be: 2013-05-24 not 2013-05-31.
Please change my coding.
Comment: I am getting 2013-05-25 in Mysql DB. Probably the calculation part needs attention.
Comment: why i get 2013-05-31 in mydb?
Comment: Result is 2013-05-25 [5.0.51b-community-nt-log]
Comment: Is your server clock correct?
Comment: 2013-05-25, last Saturday it shows
Comment: now, on my pc 2013-05-27, Friday last week not Friday next week.
Answer: Dude, try this one:
SELECT DATE_FORMAT(DATE_SUB(NOW(), INTERVAL ((7 + WEEKDAY(DATE_SUB(NOW(), INTERVAL 1 WEEK)) - 4) % 7) DAY), '%Y-%m-%d');

Comment: I gave a +1 simply because you said dude.
Comment: @JosephCho haha thanks dude! Does this count for another +1?
Answer: In MySQL, the WEEKDAY function returns an integer from 0 to 6: 0 for Monday, 1 for Tuesday etc. If you take that value as the number of days and subtract it from the current date, i.e. like this:
NOW() - INTERVAL WEEKDAY(NOW()) DAY

you will always get the current [ISO] week's Monday.
Knowing that, you will only need to subtract 3 more days to get the last week's Friday. So, the final expression would go like this:
NOW() - INTERVAL WEEKDAY(NOW()) + 3 DAY

You can take a look at this SQL Fiddle demo as well.
Comment: This can also be accomplished using the `DAYOFWEEK` function which is 1 based and starts on Sunday.

`DATE_SUB(CURDATE(), INTERVAL WEEKDAY(curdate()) + 1 DAY)`
Comment: Yes, DAYOFWEEK is more appropriate if the first day of the week is Sunday, while WEEKDAY would work for weeks starting on Monday.
Comment: Your explanation is highly helpful.
Answer: Try This
SELECT date_sub(curdate(), INTERVAL
CASE weekday(curdate()) -- weekday will give you the index of the day ( 0 = Monday, 1 = Tuesday, 2 = Wednesday, ... 6 = Sunday)
WHEN 0 THEN 3 -- If Monday then sub 3 days
WHEN 6 THEN 2 -- If Sunday then sub 2 days
ELSE 1 -- Else sub 1 day
END DAY);

Answer: If on Friday you want last Friday, on Saturday you want yesterday
select now() - interval (weekday( now())+ 2)% 7+ 1 day 'Previous Friday';

I was likewise looking for a solution for accounting, where I need a full Friday of data. So if today is Friday, then I need now()- interval 7 day. However, I may get excited and want to run the query on Saturday, and would expect now()- interval 1 day. In view of this, the interval should always be between 1 and 7 in my case. I looked at all previous answers, however for me they did not quite meet my needs. Here is a chart showing each person's "subtract interval" for each possible weekday (0= Monday):
+---------+---------+------+----------+------+-----------+
| weekday |    mine | KaeL | Andriy M | dArc | dquinonez |
+---------+---------+------+----------+------+-----------+
|       0 |       3 |    3 |        3 |    3 |         3 |
|       1 |       4 |    4 |        4 |    4 |         1 |
|       2 |       5 |    5 |        5 |    5 |         1 |
|       3 |       6 |    6 |        6 |    6 |         1 |
|       4 |       7 |    0 |        7 |    7 |         1 |
|       5 |       1 |    1 |        8 |    8 |         1 |
|       6 |       2 |    2 |        9 |    9 |         2 |
+---------+---------+------+----------+------+-----------+

mysql> select i 'weekday',
  (i+ 2)% 7+ 1 'mine',
  ((7+ i- 4)% 7) 'KaeL',
  i+ 3 'Andriy M',
  ((7+ i- 4)% 14) 'dArc',
  case i when 0 then 3 when 6 then 2 else 1 end 'dquinonez'
from (select 0 i union select 1 union select 2 union select 3
  union select 4 union select 5 union select 6 ) q;

'Kael' stays on today when today is Friday (you may want that.)
'Andriy M' and 'dArc' go back 2 Fridays on Saturday and Sunday (which is good if you don't want to look at last Friday until the weekend has past.) Also 'dArc' gives the last Friday of the month using 'last_day', which the original post was using, so this may have been what the original question actually was.
'dquinonez' works for me on Sat, Sun, and Mon - which is good if I know I will be running the query on those days only. His method is also the most readable when filled out with the other days - and easiest to modify for special cases.
Answer: try this
SELECT DATE_FORMAT(LAST_DAY(NOW()) - ((7 + WEEKDAY(LAST_DAY(NOW())) - 4) % 14), '%Y-%m-%d') last_friday;

How to get friday last week in MYSQL


How to grab all instances of a partial class name

Question: I'm trying to reinitialize a variable that gets all instances of a class name. Here's my code for reinit:
newContent = $(".product-sample-field[class^='appended']");

And for reference, my HTML looks like this:

...

...

...

And so forth.
So I'm trying to grab all instances of .product-sample-field and .appended where .appended is dynamically getting a number appended to the class name.
Comment: As an aside to the question, it's cases like this where incremental id and class attributes are an anti-pattern. I'd strongly suggest you change the classnames to all be the same and use DOM traversal to relate/target the necessary elements
Comment: If you feel you *must* use an incremental id (*protip: you don't*) - then change your `.addClass("appended" + idx)` to `.addClass("appended appended" + idx)` and make your life much simpler.
Answer: This returns all instances under .product-sample-field and class names start with "appended". Use * instead of ^.
$(".product-sample-field[class*='appended']");

Comment: Aaah, got it. Thank you!


How to extract zipcode from very meshy string using regular expression in SAS?

Question: I am trying to extract 5 number zipcode from the address field. I have included the sample data (see below). The data has 5 digit street fields in the beginning, and also 5 digit PO Box number in the middle part and 5-9 digit zipcodes, some in middle part and some in the end of the string. my objective is to extract the 5 digit zipcode from the string but not the 5 digit street and PO Box number using regular expression in SAS. Please take a look at the sample data and help me resolve this issue. I would highly appreciate your kind assistance.
13001 NW42 AVE OPA LOCKA FL 33054 USA
13001 NW 42 AVENUE OPA LOCKA FL 33054 USA
PO BOX 98748 CHICAGO IL 60693 USA
601 W 80TH STREET CHICAGO IL 60620 2502
12651 S DIXIE HWY, SUITE 321 MIAMI,FLORIDA33156
12713 SW 125TH AVE MIAMIFL 331865932

Comment: is the pun intentional?
Comment: Do you want only 5 digit ones from the end, or if it is using the 9 digit zip, you want that 9 digit extracted as well? So like `12713 SW 125TH AVE MIAMIFL 331865932` would extract `331865932` and `601 W 80TH STREET CHICAGO IL 60620 2502` would extract `60620 2502`?
Answer: This would work for your specific example.
data have;
length str $150;
infile datalines truncover;
input @1 str $150.;
datalines;
13001 NW42 AVE OPA LOCKA FL 33054 USA
13001 NW 42 AVENUE OPA LOCKA FL 33054 USA
PO BOX 98748 CHICAGO IL 60693 USA
601 W 80TH STREET CHICAGO IL 60620 2502
12651 S DIXIE HWY, SUITE 321 MIAMI,FLORIDA33156
12713 SW 125TH AVE MIAMIFL 331865932
;;;;
run;

data want;
set have;
z_Re = prxparse('`(\d{5}) ?(?:$|USA|\d{4})`o');
rc_z = prxmatch(z_re,trimn(str));
if rc_z then zip = prxposn(z_re,1,str);
put zip=;
run;

You can either adjust that to include other things, or do some reasonability checks for the possible places a 5(+) digit string might appear that is a zip code.  For example, you might require it to be within 10 characters of the end-of-string, and at least 10 characters from beginning-of-string:
data want;
set have;
z_Re = prxparse('`^.{10,}\D(\d{5}).{0,10}$`o');
rc_z = prxmatch(z_re,trimn(str));
if rc_z then zip = prxposn(z_re,1,str);
put zip=;
run;

I have to include a \D to make sure it matches 33186 instead of 65932 in the last match.  This rule may be better or may be worse depending on your various other possibilities; depending on your data it's possible no match is good enough to catch 100%.  You might consider doing both methods, and looking at the records where they disagree.
Answer: There is a dataset that comes with all SAS installations called SASHELP.ZIPCODE.  It contains a pretty up to date list of all US zipcodes (or you can download the most recent from the SAS site here).  Simply extract anything that looks like a 5-digit zip then bash it against the list.
If you want to be extra careful, you could pull the statename (or state abbreviation) from the zipcode table and make sure that the name of the state can be found somewhere in the string containing the zip also.


Prove that if a random variable $X$ with mean $\mu$ and variance $\sigma^2$ and $\sigma=0$ then $X=\mu$ with probability $1$

Question: I'm looking at a question that says if you have a random variable $X$ with mean $\mu$ and variance $\sigma^2$ and $\sigma=0$ then prove that $X=\mu$ with probability 1. I'm pretty sure it has to be solved using Chebyshev's inequality. My approach was,
$$P(|X-\mu|<k\sigma) \geq 1-\frac{1}{k^2}$$
And then assuming that (for the moment) $\sigma > 0$, choose $k=\frac{\epsilon}{\sigma}$ Then taking the limit as $\sigma \rightarrow 0$ would give the result but I'm not sure if that's right. Thanks.
Answer: You are using a hammer to kill a fly. Recall that
$$
Var(X)=E(X-EX)^{2}
$$
Now if $\sigma_{X}=0$, then $Var(X)=0$. Since $(X-EX)^{2}\ge 0$, if $X$'s value is different from $EX$ with positive probability, you would have
$$
E(X-EX)^{2}=\int_{x:x\not= \mu} f_{X}(x)(x-\mu)^{2}dx>0
$$
Therefore $X$ must be essentially a constant except on a set with probability zero.
Answer: Hint : $\mathbb{P}(|X-E(x)|>\epsilon )\leq \frac{\sigma ^2}{\epsilon ^2}=0$ (Markov inequality).


.NET Core application with multiple search paths

Question: I am working on a complex migration to .NET Core 6 application which has a set of shared assemblies which are located in a different path than the main application assemblies due to our deployment strategy.
The libs are statically linked so I can't use AssemblyLoadContext or AppDomain to extend the resolving process, sadly. I saw that the runtimeconfig.json offers the possibility to add APP_PATHS which seem to work, BUT I only managed to use absolute paths - which is nonsense as I won't know the actual paths on the target machines.
Can't I use relative paths? Whenever I try even sub-paths I get an exception that the runtime cannot be created. Is there a magical syntax to that? It can't be so complicated to have the assemblies in multiple folders.... I feel stupid.
Has somebody an idea here? I can't just change the deployment structure / process.
Thanks
Update: After carefully subscribe to AssemblyLoadContext.Default and ensuring that only that happens in the static main, not some static constructors interfering, it works. Thanks for the heads up.
Comment: I don't see why you can't use `AssemblyLoadContext`. Assemblies are used at compile to verify types but you can redirect where they load from at runtime if they are missing from the applications folder.
Answer: An example to my comment. I have three projects: Library A, Library B, and Application C.
A.csproj and B.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>

ClassA in project A.
using System.Runtime.CompilerServices;

namespace A
{
    public static class ClassA
    {
        [MethodImpl(MethodImplOptions.NoInlining)]
        public static int Plink()
        {
            return 1;
        }
    }
}

ClassB
using System.Runtime.CompilerServices;

namespace B
{
    public class ClassB
    {
        [MethodImpl(MethodImplOptions.NoInlining)]
        public static int Plonk()
        {
            return 2;
        }
    }
}

C.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>exe</OutputType>
    <TargetFrameworks>net8.0</TargetFrameworks>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <ProjectReference Include="..\A\A.csproj" Private="false" />
    <ProjectReference Include="..\B\B.csproj" Private="false" />
  </ItemGroup>
</Project>

Program.cs

using System.Runtime.CompilerServices;
using System.Runtime.Loader;

using A;
using B;

namespace C
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            SetupAssemblies();
            Foo();
        }

        private static void SetupAssemblies()
        {
            AssemblyLoadContext.Default.Resolving += Default_Resolving;
        }

        private static System.Reflection.Assembly? Default_Resolving(AssemblyLoadContext arg1, System.Reflection.AssemblyName arg2)
        {
            Console.WriteLine($"Attempting to resolve {arg2}");

            string assemblyPath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), $@"..\deps\{arg2.Name}.dll"));
            return AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private static void Foo()
        {
            Console.WriteLine(ClassA.Plink() + ClassB.Plonk());
        }
    }
}

I structured my output as follows
~\Projects\SO\C\BIN\DEBUG
│
├───deps
│       A.dll
│       B.dll
└───net8.0
        C.deps.json
        C.dll
        C.exe
        C.pdb
        C.runtimeconfig.json

Program output:

Attempting to resolve A, Version=188.8.131.52, Culture=neutral, PublicKeyToken=null
Attempting to resolve B, Version=184.108.40.206, Culture=neutral, PublicKeyToken=null
3
Comment: The odd thing is that I get an FileNotFound Exception even before the Main-Method is hit
Comment: Update: I realized... my nemesis is called static-constructors. I had to rewrite the Program a bit, now it works ... gosh ...


How can I order views Attachments in views page

Question: I have created to views attachments and placed them after my views page.
But the issue is the order of the attachments is in reverse.
How can I add weight to them?
Answer: Actually Drupal have re-order display, but I think it is for admin page only.
I also got same problems as you, but finally I found a way.
1) Click to ADVANCE.

2) Click to the machine name and edit it by ABC order.
Hope it will help.


In search for a library that knows to detect support for specific Audio Video format files

Question: I`m building a mobile-web app, and I am implementing Video & Audio tags. Apparently not all devices know to run all file formats. Modernizr knows to return to me the Codec, but how can I know if my file has this specific codec?
I can identify the file extension or mim-type, but than I`ll need to compare the codec with the file extension, and maintain an array with this data, and this seems like a sisyphic task.
What do you guys say? Any one knows on a good library that knows provide us with this information? Or maybe my approach is wrong and theres a better way to achive that.
Please not that Firefox OS for example display a msg to the user that specific file format isn't supported by the OS, but he doesn`t provide this msg when dealing with Audio files. Which means that I need to provide this feedback to the user, and I also prefer to do it in a customised visual way to my application.
An example:
I got video.mp4. Modernizr returns Codec of H264. this two pieces of information don't relate.
I cannot place fallbacks for my video to run in all video formats available. The app is a browser of a Cloud Files Hosting (like dropbox) and if the user uploaded a file which cannot run on FirefoxOS, than he must see understand why its file don`t run, and for that I need this library, instead of managing this compression by myself.
Some references:

Mozile - Supported media formats
Dive Into HTML5 - detect video formats

Thank you.
Answer: If you have access to the mime type you could simply use the audio or video's canPlayType() method:
canPlay = (function(){
  var a = document.createElement('audio'),
      v = document.createElement('video');

  function canPlayAudio(type){
    var mime = 'audio/';
    if (a && a.canPlayType) {
      if (type.indexOf(mime) === -1) type = mime+type;
      return !!a.canPlayType(type) || !!a.canPlayType(type.replace(/^audio\/(x-)?(.+)$/, mime+'x-$2'))
    } return false
  }

  function canPlayVideo(type){
    var mime = 'video/';
    if (v && v.canPlayType) {
      if (type.indexOf(mime) === -1) type = mime+type;
      return !!v.canPlayType(type) || !!v.canPlayType(type.replace(/^video\/(x-)?(.+)$/, mime+'x-$2'))
    } return false
  }

  return {
    audio: canPlayAudio,
    video: canPlayVideo
  }
})();

Then you can perform the tests like this (note: including the "audio/" or "video/" part is optional):
canPlay.audio('audio/mpeg')  // true
canPlay.audio('m4a')         // true
canPlay.audio('wav')         // true
canPlay.audio('flac')        // false
canPlay.audio('audio/ogg')   // true

canPlay.video('video/mpeg')  // false
canPlay.video('video/mp4')   // true
canPlay.video('m4v')         // true
canPlay.video('video/webm')  // true
canPlay.video('avi')         // false

Comment: Thank you @idbehold for this great direction. In order to get Probably I must pass the codec. Any idea how can I achieve that?
Comment: Man- do you have an answer for me regarding Codec recognition, so I`ll be truly able to fully award you with my bounty?
Comment: @NeoSwf I don't believe there's a programatic way to deal with the codecs. If you know of some mime types that require the codec be included I can attempt to add specific checks for them. Just let me know what they are.
Comment: I already do this check against extensions manually, in order to reach probably. Thank you man. I guess there isnt


What scale or mode is this?

Question: The notes of the scale or mode in question are:
G A B-flat D E F.  Does this combination of notes have a name?
Comment: Can it have a C note? Does adding a C break the modal feeling you're after?
Answer: With just a B♭ ( other notes all naturals), the parent key will be the major one with that one flat. That's key F. Since your scale/mode starts on the second note of the F major scale, and incorporates all the same notes, it is called the G Dorian.
Each of the modes has exactly the same note pattern - TTSTTTS, just starting at a different point in that sequence. Dorian starts on the 2nd T, so that pattern is TSTTTST.
Just noticed there's no C note. Most diatonic scales have 7 - one letter name for each note. This answer is dependent on there being a C. No C = no named scale!
Except:- Raga Manavi (many thanks to @Mac), a hexatonic scale (hence no P4 interval from root). Is there any set of notes which doesn't have a name..?
Comment: According to "ianring.com", the Dorian scale without the 4th degree becomes the scale called "Raga Manavi": https://ianring.com/musictheory/scales/1677 - so if you wanted to be technical about it...
Answer: That would be the G Dorian Mode, a mode consisting of the steps W H W W W H W.
Comment: Looks like we both missed the missing C note - unless OP missed it.

What scale or mode is this?


Partial differential equations with related functions

Question: Suppose we have $f(x, y) \geq 0$ and $g(x, y) \leq 0$ continuous, such that $\frac{d^2f}{dx^2} = \frac{d^2g}{dy^2}$. Can you show that $\frac{df}{dx} = 0$ or provide a counterexample?
EDIT: $f, g: \mathbb{R}^2 \rightarrow \mathbb{R}$
Answer: Maybe you meant prove that $\frac{df}{dx}(0,0)=0$. I assume by $df/dx$ you mean $\partial f/\partial x$. There are many easy counterexamples. Consider $f(x,y)=\sin x + 1$ and $g(x,y)=f(x,y)-2$. Obviously, the 2nd derivatives will match and $\frac{df}{dx}=\cos(x)\neq 0$.
Comment: I don't think this works. Note that the derivative of g is with respect to y, so they don't actually match. There is no typo, I wish to show that df/dx(x,y)= 0.
Comment: I'm slightly confused; $dg/dy=0$, but isn't $df/dx$ still non zero?
Comment: Your example doesn't work since d^2f/dx^2 = -sin(x), while d^2g/dy^2 = 0. The goal is to show that two functions satisfying the criteria must be such that df/dx = dg/dy = 0.
Answer: By chosing the domain $\mathbb{R}_+ \times \mathbb{R}_+$ and setting:
$$
f(x,y)=xy \geq 0\\
g(x,y)=-xy \leq 0
$$
Then we have
$$
f_{xx}=0=g_{yy}
$$
But
$$
f_x=y \neq 0
$$
If you want an answer for $\mathbb{R}^2$ as the "whole space", just specifiy it in your question. But this answer just came to my mind while reading your question.
Comment: Thanks, edited.


On scroll parent page show div element css or javascript

Question: I have a widget that a user can use in his/her own website by inserting a javascript code like this below.
Code:

Now I would like on scroll the main page when the user rich the div (adform-outstream which by default is set to display none) to change from display no to display block.
Here is what I want Scroll demo exactly the same, try to scroll to the bottom.
Here is my solution.
$(document).scroll(function () {
    var y = $(this).scrollTop();
    if (y > 800) {
        $('#adform-outstream').fadeIn();
    } else {
        $('#adform-outstream').fadeOut();
    }

});

Now my solution works only when the height is greater than 800, but I want when the user riches the specified div adform-outstream because now is if the height is less than 800 it will remove the div
What do I need to do to solve my problem?
Answer: The following code is bound on load of the page. When #adform-outstream is scrolled to, we add a class to it and visually reveal it. I used CSS for the transition, but you can handle it however you see fit. One important detail is to remove the scroll listener once the scroll trigger has been reached. Otherwise, it will continue to fire and slow things down.

$(window).scroll(scrollHandler);
var scrollToElement = "#adform-outstream";

function scrollHandler() {
  function elementScrolled(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    var elemTop = $(elem).offset().top;
    return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));
  }

  if (elementScrolled(scrollToElement)) {
    $(scrollToElement).addClass("show");

    // Important: remove scroll handler
    $(window).off('scroll', scrollHandler);
  }
}
#adform-outstream {
  max-height: 0;
  transition: max-height 0.5s, background-color 2s;
  overflow: hidden;
  padding: 1em;
  background-color: transparent;
}

#adform-outstream.show {
  max-height: 20em;
  background-color: yellow;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nulla earum beatae aliquid libero debitis velit omnis ea perferendis minus et, soluta architecto blanditiis nobis sed, eaque accusantium! Minima, voluptatum, a!
    Odio, repellat placeat non ad neque, harum unde rem officiis sit, sapiente rerum, explicabo. Reiciendis libero tenetur unde repellat. Voluptates est itaque autem quia vitae rerum. Beatae cum, rerum optio.
    Quis necessitatibus cumque eligendi, quibusdam porro nihil, ipsa sapiente soluta neque voluptatem ullam! Culpa obcaecati eaque modi eum tempora voluptatibus distinctio iste delectus aut! Minima dolorem, ducimus dolor error laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nulla earum beatae aliquid libero debitis velit omnis ea perferendis minus et, soluta architecto blanditiis nobis sed, eaque accusantium! Minima, voluptatum, a!
    Odio, repellat placeat non ad neque, harum unde rem officiis sit, sapiente rerum, explicabo. Reiciendis libero tenetur unde repellat. Voluptates est itaque autem quia vitae rerum. Beatae cum, rerum optio.
    Quis necessitatibus cumque eligendi, quibusdam porro nihil, ipsa sapiente soluta neque voluptatem ullam! Culpa obcaecati eaque modi eum tempora voluptatibus distinctio iste delectus aut! Minima dolorem, ducimus dolor error laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nulla earum beatae aliquid libero debitis velit omnis ea perferendis minus et, soluta architecto blanditiis nobis sed, eaque accusantium! Minima, voluptatum, a!
    Odio, repellat placeat non ad neque, harum unde rem officiis sit, sapiente rerum, explicabo. Reiciendis libero tenetur unde repellat. Voluptates est itaque autem quia vitae rerum. Beatae cum, rerum optio.
    Quis necessitatibus cumque eligendi, quibusdam porro nihil, ipsa sapiente soluta neque voluptatem ullam! Culpa obcaecati eaque modi eum tempora voluptatibus distinctio iste delectus aut! Minima dolorem, ducimus dolor error laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nulla earum beatae aliquid libero debitis velit omnis ea perferendis minus et, soluta architecto blanditiis nobis sed, eaque accusantium! Minima, voluptatum, a!
    Odio, repellat placeat non ad neque, harum unde rem officiis sit, sapiente rerum, explicabo. Reiciendis libero tenetur unde repellat. Voluptates est itaque autem quia vitae rerum. Beatae cum, rerum optio.
    Quis necessitatibus cumque eligendi, quibusdam porro nihil, ipsa sapiente soluta neque voluptatem ullam! Culpa obcaecati eaque modi eum tempora voluptatibus distinctio iste delectus aut! Minima dolorem, ducimus dolor error laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nulla earum beatae aliquid libero debitis velit omnis ea perferendis minus et, soluta architecto blanditiis nobis sed, eaque accusantium! Minima, voluptatum, a!
    Odio, repellat placeat non ad neque, harum unde rem officiis sit, sapiente rerum, explicabo. Reiciendis libero tenetur unde repellat. Voluptates est itaque autem quia vitae rerum. Beatae cum, rerum optio.
    Quis necessitatibus cumque eligendi, quibusdam porro nihil, ipsa sapiente soluta neque voluptatem ullam! Culpa obcaecati eaque modi eum tempora voluptatibus distinctio iste delectus aut! Minima dolorem, ducimus dolor error laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nulla earum beatae aliquid libero debitis velit omnis ea perferendis minus et, soluta architecto blanditiis nobis sed, eaque accusantium! Minima, voluptatum, a!
    Odio, repellat placeat non ad neque, harum unde rem officiis sit, sapiente rerum, explicabo. Reiciendis libero tenetur unde repellat. Voluptates est itaque autem quia vitae rerum. Beatae cum, rerum optio.
    Quis necessitatibus cumque eligendi, quibusdam porro nihil, ipsa sapiente soluta neque voluptatem ullam! Culpa obcaecati eaque modi eum tempora voluptatibus distinctio iste delectus aut! Minima dolorem, ducimus dolor error laborum.

adform-outstream adform-outstream adform-outstream adform-outstream adform-outstream

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nulla earum beatae aliquid libero debitis velit omnis ea perferendis minus et, soluta architecto blanditiis nobis sed, eaque accusantium! Minima, voluptatum, a!
    Odio, repellat placeat non ad neque, harum unde rem officiis sit, sapiente rerum, explicabo. Reiciendis libero tenetur unde repellat. Voluptates est itaque autem quia vitae rerum. Beatae cum, rerum optio.
    Quis necessitatibus cumque eligendi, quibusdam porro nihil, ipsa sapiente soluta neque voluptatem ullam! Culpa obcaecati eaque modi eum tempora voluptatibus distinctio iste delectus aut! Minima dolorem, ducimus dolor error laborum.

jsFiddle
Comment: @user9964622 Updated to use only a single element. I removed `scrollTrigger` altogetherl
Comment: Thank you, Anthony , am checking now , brb
Comment: nice solution but I cant have multiple divs , can we solve the problem without using ` `?
Comment: By using ur solution I have added a video inside a div and changed max-height to 576px when shows in a dom, the problem is now when I just start scrolling it shows the div which is wrong, I want the same as this demo here: https://test.adform.com/banners/video/outstream/preview.html meaning we nead to show the div until we the area where the div is , as the above demo shows
Answer: If Im understanding your question correctly, in order for the div adform-outstremto fade in your first must understand if the div is within the field of view. Piggybacking off of myfunkyside answer here. In addition, I would recommend using fadeTo since fadeOut removes the element from the page as said here

$(document).scroll(function () {
    var y = $(this).scrollTop() + $(this).innerHeight();

      var objectBottom =   $('#adform-outstream').offset().top + $(this).outerHeight();

      if (objectBottom <y) {
     if ( $('#adform-outstream').css("opacity")==0) { $('#adform-outstream').fadeTo(500,1);}
      } else {
        if ( $('#adform-outstream').css("opacity")==1) { $('#adform-outstream').fadeTo(500,0);}
      }

})

Comment: Hi darek your solution , shows the div when I pass the below the div , so that is not working , here is what I want : https://test.adform.com/banners/video/outstream/preview.html  try to scroll to bottom see what happens