cairngorm vs mate framework comparison in flex

Question: I have been developing applications in cairngorm framwork in flex for over 2 years.
Now I have to develop applications using Mate framework. I have no idea about Mate framework and which one is better than the other. I also need to know where to start to learn Mate framework, if somebody has idea about both the frameworks, kindly throw the light on this area.
Comment: http://aparnachaudhary.wordpress.com/2009/02/13/mate-vs-cairngorm/ this might  be help full
Answer: Likely if you've been working with one of the older versions of Cairngorm, you're going to have a hard time getting out of the mindset of reaching out and touching the Framework from everywhere that's induced by its Singleton based architecture.  What you'll want to retain from what you've learned is your respect for event based communication. Probably not much else will be useful to you if you've been using the old Cairngorm.  If you've been using CairnGorm 3, you will likely find yourself right at home, because Mate and Parsley are very conceptually similar, and Mate developers tend to perfer the Presentation Model pattern.
Here's a great video that will help you understand Mate at a conceptual level http://tv.adobe.com/watch/360flex-conference/mate-flex-framework-by-laura-arguello/ .
Here are some articles of mine that you might frind useful as well http://www.developria.com/2010/05/mate-for-framework-beginners.html
http://www.developria.com/2010/05/refactoring-with-mate.html
Unfortunately the source code is not available at this time, as my subdomain that hosted them is down.
Comment: Isn't Mate still view based for the events?  That doesn't bode well for me.
Comment: Mate encourages use of the Presentation Model, which means that you can choose to dispatch on the event bus.
Comment: Gotcha, must be newer because when I used it everything was event map based on the view. Thanks for clearing that up.
Comment: Check out this article, which has been around for a while now http://www.developria.com/2010/02/photo-gallery-mate-framework-w.html
Comment: I agree with Amy, it is also event driven framework. So in my point of view mate is more flexible than cairngorm.
Answer: Quick answer, don't use either.  They're both view based frameworks which are more of a hassle than anything.  Use Parsley or RobotLegs.  Parsley is more robust, but "heavier" with a steeper learning curve.  RobotLegs is smaller and simpler, but less flexible.
Cairngorm 3 is dependent on the Parsley extension framework.
I prefer Parsley because I seldom come to a Flex project that isn't large and needs a good way to be able to manage it.  It's the most use Flex framework in the financial industry.  There's a vibrant developer community and the lead developer is awesome.  It's also open source.
Comment: thanks , I have decided to start project in Mate now. It looks simple than Cairngorm and has lots of tutorials and docs available on internet.
Comment: I would agree with J_A_X that Robotlegs is a better Framework and has much better current support and documentation (though the OP sounded like it wasn't his decision to use Mate). I'd say if you have the power to make of influence the decision, Mate is the better one to go with.

MPO is that Robotlegs has more guidance than Parsley to keep developers from trying to go "around" the Framework, so it's probably a better way to go if your organization doesn't have much experience with Frameworks that aren't based on Singletons.


How to manually run an Airflow task if it has never ran before

Question: I've ran into this issue several times, and I can't find a solution. I have a DAG in Airflow that runs every day, which works great. Sometimes I add new tasks to this DAG, which are then included during the next scheduled DAG run, which is also great.
Sometimes, however, I want to run the new task right away because I want to use the result right away. This only seems possible by running the entire DAG, which I don't want to do. If a task has already ran, you can click on it, clear it's status, run it manually, and do all kinds of stuff. However, if it's a new task that has never ran before, you can do none of these things, because it shows a "stop" sign when hovering it (and it says "DAG has yet to run"), and you can't click on it. Some of this makes sense (you can't reset a status because it hasn't ran, so it doesn't have a status). However, I still want to be able to run it manually, like I can do with existing tasks. It feels like this should be possible, but I can't figure out how.
Menu for existing task:

Hover for new task:
Answer: If the task has an upstream or downstream task, you can "Mark Success" using the "Upstream" or "Downstream" button next to "Mark Success". After that, you can click and clear the task. Or you can do it using CLI with help of https://stackoverflow.com/a/58607672/16260639
Comment: This is great, thank you! NO idea why OP hasn't accepted this answer, it works a treat!


Unity 3D: Change rotation with normalized vector3

Question: Right now it seems the only way to rotate a game object is to input the rotation based on degrees. Is there a way to rotate a game object using a normalized Vector3, where its x,y,z are between -1 and 1.
I have tried just multiplying the Vector3 by 90 instead which seems to work. But I was wondering if there is a better solution.
Comment: What do you mean exactly? There are many ways how objects can be rotated in Unity .. and there are many `Vector3` and `Quaternion` helper methods to achieve that ... What exactly are you trying to achieve? What does `-1` and `1` stand for? `-180` to `180`? Or `-360` to `360`? ... If it is just about mapping then yes simply do e.g. `transform.rotation = Quaternion.Euler(yourVector * 180);`
Comment: I'm trying to rotate an object using a Vector3 where all its values are between -1 and 1.  For example a value of (1, 0, 0) would mean the object is facing forward on the x-axis.
Answer: From what you describe it sounds like you simply want to do e.g.
transform.forward = directionVector;

or you could also use Quaternion.LookRotation
transform.rotation = Quaternion.LookRotation(directionVector);


Como selecionar somente as pessoas com o primeiro nome

Question: Gostaria de saber como fazer para selecionar as pessoas que possuem apenas o primeiro nome, ou seja, não possuem nenhum sobrenome.
Exemplo:

Nome
----------
Leonardo Roberto
Ana
Júlio
Maria Ana

Resultado esperado:

Ana, Júlio
Comment: Bem vindo ao SOPT. Teria como [edit] seu post e acrescentar o código que esta utilizando, ou o que tentou fazer até o momento? Assim podemos analisar e sugerir uma alteração. Consulte a página [ask] para obter ajuda para o esclarecimento desta pergunta.
Answer: Apesar da sua questão estar pouco clara, penso que será simples chegar a uma solução.
Vamos supor que tem a tabela abaixo (exemplo muito básico):
CREATE TABLE Pessoas
(
    Nome VARCHAR(255)
)

Tabela que contém a seguinte informação:
INSERT INTO Pessoas VALUES('Leonardo Roberto')
INSERT INTO Pessoas VALUES('Ana')
INSERT INTO Pessoas VALUES('Júlio')
INSERT INTO Pessoas VALUES('Maria Ana')

Para obter os nomes que não tenham sobrenome, basta procurar aqueles que não tenham espaços:
SELECT  *
FROM    Pessoas
WHERE   STRPOS(LTRIM(RTRIM(Nome)), ' ') = 0

Answer: Uma alternativa seria uma chamada à função POSITION(); considerando que o nome com sobrenome será sempre separado por um espaço (), pode usar o seguinte:
SELECT *
FROM pessoa
WHERE POSITION(' ' in nome) > 0;


Erro "Expression expected"

Question: Peguei esse código que até certo ponto funcionou. Porém o método updateLabel eu não consigo fazer pois da problema:

Preciso pegar a data selecionada do calendário. Estou usando uma forma em que ao clicar na editText, o calendário abre.
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            // TODO Auto-generated method stub
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateLabel(myCalendar);

        }

    };

    editText.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new DatePickerDialog(AgendamentoActivity.this, date, myCalendar
                    .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                    myCalendar.get(Calendar.DAY_OF_MONTH)).show();

            //Toast.makeText(getBaseContext(), "8:00 - 9:00", Toast.LENGTH_LONG).show();
        }
    });

    private void updateLabel(Calendar) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd hh:mm:ss 'GMT'Z yyyy");
        System.out.println(dateFormat.format(myCalendar.getTime()));

        //editText.setText(sdf.format(myCalendar.getTime()));
    }

Answer: Me parece que você está colocando seu método updateLabel() dentro do onCreate quando na verdade deveria estar fora. Veja um exemplo:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}

public void updateLabel(){
    // aqui você coloca o código desejado
}

Comment: Não, está tudo fora do onCreate.
Comment: @GustavoSevero você tem que colocar o código na pergunta e não a imagem do código. Fica mais fácil te ajudar.
Comment: Coloquei a parte do código que está dando errado acima da foto
Comment: @GustavoSevero só isso não da pra descobrir o erro. ehe
Comment: Agora coloquei todo o código
Comment: Cara, o erro é exatamente o que estou te dizendo. você está colocando o método no lugar errado. Parte disso ai deveria estar dentro do oncreate e somente o método  updateLabel poderia estar fora.
Comment: OK, vou tentar isso.
Comment: Deu certo kkkkk Agora está dando outro erro depois que seleciono a data e clico em OK.
Comment: Não reconhece esse método:
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd hh:mm:ss 'GMT'Z yyyy");
Comment: @GustavoSevero isso ai já seria outro erro! Se quiser pode validar essa resposta e fazer outra pergunta com o novo erro! =D
Comment: Blz, é o que vou fazer.
Comment: @GustavoSevero boa sorte ai! =D
Answer: Receba seu Calendar em updateLabel(Calendar myCalendar) e passe como argumento a esse mesmo método dentro do onDateSet.
Comment: Coloquei o novo errado que dá, após fazer o que vc sugeriu. Veja na descrição do post.
Comment: Poderia postar ela toda?
Comment: Coloquei todo o código

Erro "Expression expected"


UML-RT Modeling Tool

Question: I'm looking for a modeling tool which supports UML-RT, but I'm not able to find any.
I already have MS Visio (2010), Power Designer (2008) and Rational Rose but it seems that non of them contains UML-RT features (like Capsule). any idea?
Answer: Eclipse with Papyrus component, explore the following link:
http://www.eclipse.org/papyrus/
Comment: After installing papyrus, you can get the UML-RT optional component installed - although it appears to be there by default in the nightly builds for Luna.
Comment: thank you @Blatorg for the hint,Does UML-RT will replace MARTE as what MARTE did(replaces SPT profile)?
Comment: @Melisa, No, UML-RT is not intended to replace MARTE. MARTE does provide additional information that can be useful when developing embedded or "real time" software (e.g., information specifying constraints of the system, a bit like SysML). I would hope that, in the future, UML-RT code generators would be able to use MARTE information and that, potentially, MARTE information could be used to define test systems - but we are not close to being there...
Comment: Just a quick note that there is now a  Papyrus for Real Time that implements UML-RT as a DSML on top of Papyrus.
Answer: IBM's Rational Software Architect, which is an Eclipse-based modelling environment, exists in a Real-Time Edition (RSARTE).
The company I work for is an IBM/Rational partner; feel free to contact us for further information (the web site is listed in my profile).
RSA product home page
RSARTE support portal

UML-RT Modeling Tool


Mixing PHP with HTML

Question: I'm making a form where I need to insert 2 values for X and Y to create a table with X lines an Y rows. But I'm not able to make the Table appear. The function is being called but the HTML is being ignored, for some reason, I only get a line with the content "Line 1 Line 2 Line3... Row 1, Row 2, ...."
Here is my code:

<form method="post" action="<?php $_SERVER['REQUEST_URI'] ?>" >

    X= <input type="text" name="x"  />

    Y= <input type="text" name="y"  />

    Diferença=  <select name="expressao">
                    <option value=">"> > </option>
                    <option value="<"> < </option>
                    <option value="="> = </option>
                </select>
    <input type="submit" value="enviar"  />
    <input type="hidden" name="enviar" value="1" />

</form>

<?php

function tabela () {
    tabelashow ();
}

if (!empty($_POST['enviar'])) {

    $x=$_POST['x'];
    $y=$_POST['y'];
    $expressao=$_POST['expressao'];

    echo "O valor da expressão $x $expressao $y é ";

    if ($expressao == ">") {
        if ($x > $y) {
            echo "Verdadeiro";
            tabela ();
            }
        else {
            echo "Falso"; }
    }

    elseif ($expressao == "<") {
        if ($x < $y) {
            echo "Verdadeiro"; }
        else {
            echo "Falso"; }
        }

    else {
        if ($x == $y) {
            echo "Verdadeiro";
        }
        else {
            echo "Falso"; }
        }
}

?>

<?php
function tabelashow () {
    for ($t=1; $t<=3; $t++) {
        echo "
";
        for ($u=1; $u<=3; $u++) {
            echo("Coluna $u 	");
        }
        echo "
";
    }
}
?>

Comment: Why was this migrated? O.O
Answer: You missed a semicolon and the word echo or print on the first line
<?php print $_SERVER['REQUEST_URI']; ?>

And do what jessh said too.  Seems legit.
Answer: You are calling tabelashow (); before it's defined, way towards the bottom.
Switching where you call the function (https://gist.github.com/jshawl/7981130#file-so-php-L20)
with where you define it (https://gist.github.com/jshawl/7981130#file-so-php-L60) Should do the trick.
Answer: The actual problem is that the HTML code for the table is output before the  tag.
Here is what your PHP outputs:
O valor da express�o 3 > 2 � Verdadeiro
Coluna 1 	Coluna 2 	Coluna 3

Coluna 1 	Coluna 2 	Coluna 3

Coluna 1 	Coluna 2 	Coluna 3

One way to solve this would be to put the
 tag above the call to tabela() like this:
</form>

<?php

function tabela () {
    tabelashow ();
}

if (!empty($_POST['enviar'])) {
...

OR you could echo the table tag in the tabelashow() function like this:
function tabelashow () {
    echo '
';
    for ($t=1; $t<=3; $t++) {
        echo "
";
        for ($u=1; $u<=3; $u++) {
            echo("Coluna $u 	");
        }
        echo "
";
    }
    echo "
";
}

I just tried it on my own server and it works either way.
Answer: use echo short tag to action attribute of form ..
<form method="post" action="<?= $_SERVER['REQUEST_URI']; ?>" >

Answer: What an old post. Just in case it could help somebody.
<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>" >

    X= <input type="text" name="x"  />

    Y= <input type="text" name="y"  />

    Diferença=  <select name="expressao">
                    <option value=">"> > </option>
                    <option value="<"> < </option>
                    <option value="="> = </option>
                </select>
    <input type="submit" value="enviar"  />
    <input type="hidden" name="enviar" value="1" />

</form>

<?php
$tabela_poner = false;

if(isset($_POST['enviar'])){
    $x = $_POST['x'];
    $y = $_POST['y'];
    $expressao = $_POST['expressao'];

    function tabelashow(){
        global $tabela_poner;
        if($tabela_poner):
            global $x, $y;
            ?>

                <?php for($i = 1; $i <= $x; $i++): ?>

                    <?php for($j = 1; $j <= $y; $j++): ?>
                    Fila #<?php echo $i; ?> / Coluna #<?php echo $j; ?>
                    <?php endfor; ?>

                <?php endfor; ?>

        <?php endif; // ($tabela_poner)
    }

    function tabela(){
        global $tabela_poner;
        $tabela_poner = true;
    }

    echo "O valor da expressão $x $expressao $y é ";

    // verdad o no
    switch($expressao){
        case '>':
            if($x > $y){
                echo 'Verdadeiro';
                tabela();
            }
            else
                echo 'Falso';
            break;
        case '<':
            echo $x < $y ? 'Verdadeiro' : 'Falso';
            break;
        case '=':
            echo $x === $y ? 'Verdadeiro' : 'Falso';
    }
    ?>
<?php
}
?>
<?php tabelashow(); ?>

Mixing PHP with HTML


Postgresql insert stopped working, duplicate key value violations

Question: About 8 months ago I used a suggestion to set up a holding table, then push to the formal table and prevent duplicate entries, per this post: Best way to prevent duplicate data on copy csv postgresql
It's been working very nicely, but today I noticed some errors and gaps in the data.
Here's my insert statement:

And here's how the index is set up:

And here's an example of the error I'm getting, although on the next chron insert, it went through.
Here's it going through fine:

I haven't noted any large changes in the data incoming.  Here's what the data looks like that's coming in now:

In summary, I've noticed recent oddities with the insert statements, and success is erratic, resulting in large data gaps in the database.  Thanks for any help, and I'm happy to provide more details, but I wanted to see if my information sounds like something someone else has already dealt with.
Thanks very much for any help,
S
Comment: Posting screen shots of text isn't a great idea, why not post the text itself?
Comment: I thought I may get asked that.  Because I'm using a remote desktop connection for the db, and it's lame at best when trying to copy/paste.  Plus, I thought it was more of a conceptual question versus readers trying to recreate the code and test it.
Comment: Please check if column `"time"` has `null` values. `null` values break `not in` comparisons
Comment: I am making the column time "not null" as we speak.  It's a big table so taking a while.  Thanks for the suggestion!
Answer: As Gordon pointed out in his answer to your previous question, this approach only works if you have exclusive access to the table. There is a delay between the existence check and the insert itself, and if another process modifies the table during this window, you may end up with duplicates.
If you're on Postgres 9.5+, the best approach is to skip the existence check and simply use an INSERT ... ON CONFLICT DO NOTHING statement.
On earlier versions, the simplest solution (if you can afford to do so) would be to lock the table for the duration of the import. Otherwise, you can emulate ON CONFLICT DO NOTHING (albeit less efficiently) using a loop and an exception handler:
DO $$
DECLARE r RECORD;
BEGIN
  FOR r IN (SELECT * FROM holding) LOOP
    BEGIN
      INSERT INTO ltg_data (pulsecount, intensity, time, lon, lat, ltg_geom)
      VALUES (r.pulsecount, r.intensity, r.time, r.lon, r.lat, r.ltg_geom);
    EXCEPTION WHEN unique_violation THEN
    END;
  END LOOP;
END
$$

As an aside, DELETE FROM holding is time-consuming and probably unnecessary. Create your staging table as TEMP, and it will be cleaned up automatically at the end of your session. You can easily build a table which matches the structure of your import target:
CREATE TEMP TABLE holding (LIKE ltg_data);

Comment: Thanks so much for these ideas!  I do have exclusive access to the table.  It's only modified every 10 min when the insert script is run.  I do access the table to view the data on occasion.

So should I still try the "insert...on conflict do nothing" statement?  And should the "on conflict" portion replace the "where" portion of my original insert statement?

Could it be something else now that you know we have exclusive access?  Also, it's a 7mil row table.  Don't know if that size affects anything.
Comment: The fact that it works when you re-run it indicates that the state of the table has changed; I'm not sure how this could happen without another writer involved. How long does the import take? Any chance that the cron jobs are overlapping? If this isn't it, [statement logging](http://blog.endpoint.com/2012/06/logstatement-postgres-all-full-logging.html) might provide some insight. Re the `ON CONFLICT` clause, it's probably a better approach regardless of your current issues, and yes, it would take the place of your existing `WHERE` clause.


ElasticSearch painless scripts - Way to output variable values besides the final score?

Question: I am using a painless script to implement a custom scoring function while querying the ES index, that's being used as a basis for our recommendation engine. While calculating the final score in the painless script, I use a product of intermediate variables such as recency and uniqueness, calculated within the painless script.
Now, it is trivial to get the final scores of the top documents as they are returned within the query response. However, for detailed analysis, I'm trying to find a way to also get the intermediate variables' values (recency and uniqueness as in the above example). I understand these painless variables only exist within the context of the painless script, which does not have standard REPL setup. So is there really no way to access these painless variables? Has anyone found a workaround to do this? Thanks!
E.g. If I have the following simplified painless script:
def recency = 1/doc['date'].value
def uniqueness = doc['ctr].value

return recency * uniqueness

In the final ES response, I get the scores i.e. recency * uniqueness. However, I also want to know what the intermediate variables are i.e. recency and uniqueness
Answer: You can try using a modular approach with multiple scripted fields like:

recency -- get the recency field
uniqueness -- get the uniqueness field
access the fields like a normal ES field in your final painless script

if(doc.containsKey('recency.keyword') && doc.containsKey('uniqueness.keyword'))
{
  def val1 = doc['recency.keyword'].value;
  def val2 = doc['uniqueness.keyword'].value;
}

Hope it helps
Comment: thanks for response aritra! It doesn't solve the issue so I think I was unclear in my question - I've added a clear example so hopefully it will help! Thanks
Comment: well my suggestion still holds true if you do not mind having 3 scripted fields instead of one. However, if you really want to have just a single field - you may try to return a map ...

```
def recency = 1/doc['date'].value
def uniqueness = doc['ctr].value

def result = recency * uniqueness
def returnMap = ['recency': recency, 'uniqueness': uniqueness, 'result': result]
```
Comment: so I tried using script fields and obtain the following fields in the result `fields': {'recency': [5669752], 'uniqueness': [8504628.0]}` But now I can't access them in my final painless script. I tried using your method but it doesn't work for me. Do I to create separate mappings for recency and uniqueness in my index prior?
Comment: Also, referring to your returning map solution, how can you return a map in a painless script since the script is expecting a single score to sort on?
Answer: There is not direct way of printing it anywhere i suppose.
But here is what you can give it a try to check the intermediate output of any variable.

create another scripted field which will return only the value of that variable.

For Ex: in your case,
"script_fields": {
"derivedRecency": {
      "script": {
        "lang": "painless",
        "source": """
            return doc['recency'].value;

          """
      }
    }
}


Swimming and respiratory infections

Question: This is a serious athletic training issue that affects me and certain of my athletes: some swimmers are prone to ENT and respiratory infections such as in the ear, sinuses, throat and lungs.  Last year I only had 7 weeks to train before a 4.4mi open water swim because of pneumonia.  Given that even treated pool water can be a vector for bacteria, what can a swimmer do to help prevent infections?
Comment: Thanks Peter. I will now be grossed out any time I step into a pool ~ever again~.
Comment: this is a medical question and should be taken up with your doctor.
Comment: @PeterDeWeese sorry, misread the question. Still a medical question. You might look into the type of filtration your local pool uses. Some filters are better at dealing with bacteria than others (DE filters are better than sand or cartridge filters)...Doesn't help with open water, but its something
Comment: @PeterDeWeese no, but if you are having constant infection issues then you might be able to affect change at your facility by making a complaint, or switching facilities (you likely aren't the only ones).
Comment: I'm not discussing fitness swimming, but a training concern for the sport of swimming. According to the faq, this is for 'participants in team and individual sport activities.'
Comment: I'm going to take up a question with my doctor for any of my athletes that want to prevent infections while training? Bizarre suggestion.
Comment: Unfortunately, swim teams don't typically have control over the pool facility.
Comment: @glowcoder, if you've ever been to a pool that children can access, you may have other possible reasons to be grossed out. :)
Comment: @PeterDeWeese did you find any studies/references to support the point of swimming increasing the risc for such infections? It's slightly off-topic. But as Dynamo has indicated this might make this Q even better for the future. Btw, you can count me in on your personal statistics. I've dropped swimming from my list of sports after a year and three severe colds.
Answer: Since crickets were chirping in here I did a little more research, and found that chlorine itself will cause irritation and irritated sinuses are more likely to become infected.  This seems true to me, because I don't often hear of athletes getting infections from long open water swims in rather dirty water.  Ear and nose plugs are not very useful while swimming because they prevent pressure equalization, but one can breathe out of their nose while diving and turning to prevent chlorinated water from entering the sinuses.
The comment on the question by wax eagle regarding proper facilities is correct but swim teams typically have little control over their facility and there is competition to contract lane-space in the first place.  Its at a premium.  The best facility in my area has great circulation, is 8 feet deep at its shallowest (large volume of water compared to number of swimmers) has UV, ozone, and bromine treatment, and is much less irritating to the sinuses and lungs.  If only my team trained there.
A couple things for the training bag:

Auro Dri is an alcohol/glycerin ear drop that will disinfect and dry the ear canal.
Simply saline is a sterile saline solution that can be used to irrigate and wash the sinuses.  It should be used sparingly as it can also strip away the protective mucous lining.
Shower with hot water, and inhale the steam to help clean your sinuses.

More tips are appreciated.
Comment: I've heard saltwater pools are effective alternatives to chlorinated pools inland, though of course the added buoyancy may be an issue.
Comment: Would you mind linking to the chlorine information you found? It's not directly related to the answer but it sounds like it might be worth reading into for people having the same problem.
Comment: Edited. I've seen more authoritative sources from athletic journals but can't find them right now.

Swimming and respiratory infections


epimorphisms of Lie groups send unipotent elements to unipotent elements.

Question: Let $f:G\to H$ be a surjective morphism of Lie groups. Suppose $g\in G$ is a unipotent element, namely $Ad_g:Lie(G) \to Lie(G)$ is a unipotent transformation of Lie algebras(the only eigenvalue of is one). Now I wonder how to show that $df(g)\in H$ is also unipotent.
My attempt: Let $w\in Lie(H)$ be a eigenvector of $Ad_{f(g)}$, say $Ad_{f(g)}(w)=rw$. Since $f$ is an epimorphism of Lie groups, I remember that $df$ is surjective as well and assume $df(v)=w$. So we have
$$Ad_{f(g)}(df(v))=r df(v).$$
I wish to somehow conclude from here that
$$Ad_g(v)=rv$$
and since $g$ is unipotnent we have $r=1$. But how? Or are there any other approaches.
Comment: The key ingredient you might want is the Lie-Kolchin theorem. Then just put your element into a unipotent subgroup.
Answer: For any Lie group morphism $f\colon G\to H$ the conjugation map $C_g\colon h\mapsto ghg^{-1}$ satisfies the identity
$$f\circ C_g = C_{f(g)}\circ f.$$
Differentiating this leads to a similar formula for the adjoint map
\begin{equation}\label{1}\tag{*}
df\circ\mathrm{Ad}_{g} = \mathrm{Ad}_{f(g)}\circ df.
\end{equation}
Hence if $X$ is an eigenvector of $\mathrm{Ad}_{g}$ and $df(X)$ is nonzero, then $df(X)$ is an eigenvector of $\mathrm{Ad}_{f(g)}$ with the same eigenvalue.
The same is true also for generalized eigenvectors: Suppose $(\mathrm{Ad}_{g}-\lambda\cdot \operatorname{id})^nX=0$ for some $n\in\mathbb{N}$ and eigenvalue $\lambda$. The binomial expansion of the operator $(\mathrm{Ad}_{g}-\lambda\cdot \operatorname{id})^n$ is
$$(\mathrm{Ad}_{g}-\lambda\cdot \operatorname{id})^n = \sum_{k=0}^n(-\lambda)^k\binom{n}{k}\mathrm{Ad}_g^k.$$
Repeated application of formula \eqref{1} then shows that
$$(\mathrm{Ad}_{f(g)}-\lambda\cdot \operatorname{id})^n(df(X)) = df\Big((\mathrm{Ad}_{g}-\lambda\cdot \operatorname{id})^nX\Big) = df(0) = 0,$$
so if $df(X)$ is nonzero, then it is a generalized eigenvector of $\mathrm{Ad}_{f(g)}$ with the same eigenvalue $\lambda$.
Decomposing the Lie algebra $\mathrm{Lie}(G)$ as a direct sum of the generalized eigenspaces of the map $\mathrm{Ad}_g$ then shows that the spectrum of $\mathrm{Ad}_{f(g)}$ restricted to the image of $df$ is a subset of the spectrum of $\mathrm{Ad}_g$. In particular, if $f$ is surjective and $\mathrm{Ad}_g$ unipotent, then $\mathrm{Ad}_{f(g)}$ is also unipotent.
Comment: Just to make sure I understand what you wrote. the only part you used the subjectivity of f is the subjectivity of $df$? Is that correct?
Comment: In addition, why do you have to go to the generalized eigenvectors? The ordinary eigebvectors not enough?
Comment: Yes, the surjectivity of df is enough. Considering eigenvectors shows that the spectrum of $\mathrm{Ad}_g$ is contained in the spectrum of $\mathrm{Ad}_{f(g)}$.  However eigenvectors don't necessarily span the full Lie algebra $\mathrm{Lie}(G)$, e.g. when the linear map has a matrix of the form $\begin{bmatrix}1&1\\0&1\end{bmatrix}$. So a priori some non-eigenvector could be mapped to an eigenvector with a different eigenvalue. However generalized eigenvectors span the full space, so there is no room for this to happen.
Comment: It is false that $Ad_{f(g)}$ restricted to the image of $df$ has the same spectrum as $Ad_g$. The reason is that the images of some of the eigenvectors under $df$ could be zero.
Comment: @MoisheKohan Good point! I indeed overlooked the fact that $df(X)$ might get mapped to zero. So instead of equality there is only an inclusion, but fortunately the correct one.
Comment: Now it is correct, although you are proving more than the question asks for: It is much easier to check that if $N$ is a nilpotent endomorphism of a vector space $V$, then for each $N$-equivariant epimorphism $V\to W$, $N$ descends to a nilpotent endomorphism of $W$. You do not even need finite dimension for this.


Get "home/index" in Rails project

Question: After running rails generate controller home index in my Rails application, I see this line in routes.rb
get "home/index"

What does this line do? When I removed it, I didn't observe any difference it makes.
Answer: see the Rails Routing page for more info but...
It adds, to the routing table, an entry to direct a GET request of the form
http://localhost:3000/home/index

To the HomeController#index action, which will render a response and display the results to the user.
It is a shorthand notation for
match 'home/index' => 'home#index', :via => :get

To see what other routes your application has available, run the following from a terminal while inside your projects directory
rake routes

Get "home/index" in Rails project


Views to use relative paths for image fields

Question: How can we tell views to use relative paths for dispalying images using image fields. I have created a views slideshow which is displaying images using absolute url which is causing the images to reload on each page load.
facing the same issue in other type of views displays like grid and unformated etc...
Answer: Add your image to the view (mine is called Image2)
Create a theme file for your image field, see screenshot. (mine is called views-view-field--relative-url-example--page--field-image2.tpl.php and it's bolded). Pick the last one for the most granular themeing possible.
 (full size here)
After you have added the theme file to your theme templates (/sites/all/themes/THEME/templates or similar), hit the "Rescan template files" button. Your field template should be bolded now.
Add the following code to your theme file, I removed the comments but you can leave them in if you like:
<code><?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>
<?php

    $url  = file_create_url($row->field_field_image2[0]["raw"]["uri"]);
    $url  = parse_url($url);
    $path = $url['path'];

    print $path;
?>
</code>
I only printed the path to demonstrate it works so you will need to add the image tag, etc.
Here is my output:

You may need to clear the cache and be sure to save your view after you update the theme file.
Comment: I have followed the steps you have defined above but its throwing the following error

Notice: Undefined property: stdClass::$field_image_slider in include() (line 27 of /home/beatabun/public_html/sites/all/themes/mytheme/templates/views-view-field--image-slider--block--field-image-slider.tpl.php).
Comment: is it because I am using multivalue field ??
Comment: It could be, you will need to account for that in your template.
Answer: You can use  image_url_formatter module ,it add url formatter in image field formatter than you can use it in content dispaly or field display in views.
Answer: This did not work for me, but stripping the domain from $output in my view template did:
<code>$output = preg_replace('@http(s)?://www.example.com@', '', $output);
print $output;
</code>


Convert HTML headings and li elements into table

Question: Is it possible to convert a list into a table and use the preceding heading elements as table values? I am open to different solutions, but I feel like this could be done via Python and perhaps BeautifulSoup.
Here's the starting HTML structure:

Category 1

Option 1

A

B

C

Option 2

D

E

F

Category 2

Option 1

G

H

I

Option 3

J

K

L

Here's the desired result:

            Category 1
            Option 1
            A

            Category 1
            Option 1
            B

            Category 1
            Option 1
            C

            Category 1
            Option 2
            D

            Category 1
            Option 2
            E

            Category 1
            Option 2
            F

            Category 2
            Option 1
            G

            Category 2
            Option 1
            H

            Category 2
            Option 1
            I

            Category 2
            Option 3
            J

            Category 2
            Option 3
            K

            Category 2
            Option 3
            L

Again, I am open to any solution. The end goal is to be able to produce a table or csv or something that can be copied into Excel easily, but unfortunately I am not starting with great source content for the format I want.
Answer: You could handle this in a number of ways, I went for parsing the data as a string and some basic regex using the pandas lib.
from io import StringIO
import pandas as pd # pip install pandas.
import numpy as np # pip install numpy

html = """

Category 1

Option 1

A

B

C

 """

df = pd.read_csv(StringIO(html),sep='|',header=None)
print(df.head(3))

            0
0
Category 1

1
Option 1

2

3
A

#if you have lots of uncessary html you need to strip out
# df = df[df[0].str.contains('
|
|
')==True]
#extract category.
df["category"] = df[0].str.extract("
(.*)
")[0].ffill().str.strip()
#extract option.
df["option"] = df[0].str.extract("
(.*)
")[0].ffill().bfill().str.strip()
#remove html tags and replace empty spaces with np.nan so we can drop them.
df[0] = (
    df[0]
    .replace("<[^<]+?>", "", regex=True)
    .str.strip()
    .replace("", np.nan, regex=True)
)

# remove blank rows & rows where the html col is equal to it self.
df = df.loc[ (df[0].ne(df['category']))  & (df[0].ne(df['option'])) ].dropna(how='any')

print(df[['category','option',0]])

      category    option  0
3   Category 1  Option 1  A
4   Category 1  Option 1  B
5   Category 1  Option 1  C
9   Category 1  Option 2  D
10  Category 1  Option 2  E
11  Category 1  Option 2  F
16  Category 2  Option 1  G
17  Category 2  Option 1  H
18  Category 2  Option 1  I
22  Category 2  Option 3  J
23  Category 2  Option 3  K
24  Category 2  Option 3  L

Finally, you can call df.to_excel('file.xlsx',index=False) to export the dataframe.


Python loop counter in a for loop

Question: In my example code below, is the counter = 0 really required, or is there a better, more Python, way to get access to a loop counter? I saw a few PEPs related to loop counters, but they were either deferred or rejected (PEP 212 and PEP 281).
This is a simplified example of my problem. In my real application this is done with graphics and the whole menu has to be repainted each frame. But this demonstrates it in a simple text way that is easy to reproduce.
Maybe I should also add that I'm using Python 2.5, although I'm still interested if there is a way specific to 2.6 or higher.
# Draw all the options, but highlight the selected index
def draw_menu(options, selected_index):
    counter = 0
    for option in options:
        if counter == selected_index:
            print " [*] %s" % option
        else:
            print " [ ] %s" % option
        counter += 1

options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']

draw_menu(option, 2) # Draw menu with "Option2" selected

When run, it outputs:
 [ ] Option 0
 [ ] Option 1
 [*] Option 2
 [ ] Option 3

Comment: can you simply use the array length property instead of the for in loop method, for i < array.length?
Answer: Use enumerate() like so:
def draw_menu(options, selected_index):
    for counter, option in enumerate(options):
        if counter == selected_index:
            print " [*] %s" % option
        else:
            print " [ ] %s" % option

options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)

Note: You can optionally put parenthesis around counter, option, like (counter, option), if you want, but they're extraneous and not normally included.
Answer: I'll sometimes do this:
def draw_menu(options, selected_index):
    for i in range(len(options)):
        if i == selected_index:
            print " [*] %s" % options[i]
        else:
            print " [ ] %s" % options[i]

Though I tend to avoid this if it means I'll be saying options[i] more than a couple of times.
Comment: In such a case you should always use enumerate()
Comment: @gs: yes. That answer was already posted though, so I was posting an alternate solution. As usual, which answer is best depends on the details of your situation.
Comment: @EvanFosmark - There's absolutely no performance difference between the two. I checked both with the following: `python -m timeit "s = 'String used for testing'; ''.join(str(i)+str(c) for i, c in enumerate(s))"` and `python -m timeit "s = 'String used for testing'; ''.join(str(i)+str(s[i]) for i in xrange(len(s)))"`. Each of them averaged on 8.83 usec per loop over 100,000 loops. Other tests (too long for a comment) showed very slight (~2%) speed increases for `xrange(len(s))` if it only needed to access the element on every 16 iterations.
Comment: gs, what if you only need to get the element every once in a while, but you need the index every time? It seems like in those situations this could be beneficial because you aren't creating a new variable each time.
Answer: You could also do:
 for option in options:
      if option == options[selected_index]:
           #print
      else:
           #print

Although you'd run into issues if there are duplicate options.
Comment: Or if options is an iterator.
Answer: enumerate is what you are looking for.
You might also be interested in unpacking:
# The pattern
x, y, z = [1, 2, 3]

# also works in loops:
l = [(28, 'M'), (4, 'a'), (1990, 'r')]
for x, y in l:
    print(x)  # prints the numbers 28, 4, 1990

# and also
for index, (x, y) in enumerate(l):
    print(x)  # prints the numbers 28, 4, 1990

Also, there is itertools.count() so you could do something like
import itertools

for index, el in zip(itertools.count(), [28, 4, 1990]):
    print(el)  # prints the numbers 28, 4, 1990

Python loop counter in a for loop


RoxyFileman blank pop up on server

Question: I'm using Nopcommerce, everything seems to work fine on the local machine. But after publishing and uploading the site to the server when I want to insert an image or video an empty pop-up opens with only RoxyFileman title.
By browsing the pop's source I can see the controls are in the page but not displayed.
How can I solve this issue?
Answer: Provide read/write permission to image folder(yourwebsite\Content\Images) for local IIS user . Also do check & clear System Warning from website ->admin->System->Warning.
Better you provide screen shot of issue if still problem persist.

RoxyFileman blank pop up on server


Expressão regular para trocar o par de variáveis no mysql em arquivo PHP

Question: Qual expressão posso usar para poder trocar os parâmetros da função do MYSQL, exemplo:
mysql_query($query,$db);

mysql_query($db,$query);

Porque procuro por mysql_query e troco por mysqli_query depois que conseguir fazer essa mudança.
Ou seja, trocar de lugar duas strings que estejam dentro de um parenteses.
Answer: Pode inveter os argumentos criando três grupos no final basta formatar a substituição.
A ideia é quebra essa instrução da seguite forma, o primeiro grupo é mysql_query o segundo $query e o terceiro $db. Com os elementos capturados inverta a ordem do segundo com o terceiro e adicione os parenteses.
O primeiro pega a instrução: (mysql_query) o segundo a variável com a query (\$\w+), que é representando por um cifrão seguido de uma ou mais letras, seguido de uma virgula e de mais uma variável.
Buscar por:
(mysql_query)\((\$\w+)\s*,\s*(\$\w+)\)

Substituir por:
\1\(\3,\2\)

Ou ainda:
$1\($3,$2\)

Comment: Muito Obrigado.


DNS Server- subdomains on internal LAN and www on public IP

Question: I have a Windows 2008R2 based domain controller also working as internal DNS server for my domain say "domain1.com".
I also have a working website www.domain2.com hosted elsewhere and accessible globally.
Now I am creating a test environment on my internal network where I am going to add a couple of subdomains, say sub1.domain2.com and sub2.domain2.com
These subdomains/webpages are hosted internally (LAN).
I have created a new zone on my DNS server and added A records so that I can have both these sundomains mapped to respective internal IP addresses.
These subdomain DNS requests are working as expected.
But now the problem is that my live website www.domain2.com is inaccessible from
my internal network. My windows DNS server is unable to handle requests for it, though I have added an A record on my internal DNS server pointing to the public IP of website. Have I missed something here?
Regards,
Vin
Answer: When you create the zone, create the subdomain and not the root domain.
So create 2 zones, sub1.domain2.com.
Delete domain2.com zone so your server stops answering nxdomain for www.domain2.com
I use this method to split-dns my premise exchange servers.
Answer: Cause i have not 50 Reputation i'm not able to add an normal Comment. So had to do a normal comment, really strange the permission system here.
http://blogs.technet.com/b/networking/archive/2015/05/12/split-brain-dns-deployment-using-windows-dns-server-policies.aspx
Split Brain DNS, should be a good hint.


Connect iphone app to mysql data base

Question: I have app i want to connect to iphone app i have done code and also php code problem is that i am always getting Incorrect password alert view . I aam entering correct user name and password but again it displays error alert view
<code>      NSString *post =[NSString stringWithFormat:@"UserName=%@&UserPassword=%@",userNameTextField.text, userPasswordTextFiled.text];

     NSString *hostStr = @"http://www.myurl.com/emrapp/connect.php?";
    hostStr = [hostStr stringByAppendingString:post];
     NSData *dataURL =  [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
     NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
     if([serverOutput isEqualToString:@"Yes"]){
        UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Congrats" message:@"You are authorized "
                                                          delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alertsuccess show];
    [alertsuccess release];

    } else {
        UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Error"  message:@"Username or Password Incorrect"
                                                          delegate:self     cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
         [alertsuccess show];
        [alertsuccess release];

     }
</code>
And my server side code  is
<code>    <?php
     $con = mysql_connect("emriphone.db.6420177.hostedresource.com","emriphone","Light12-");
   if (!$con)
    {
   die('Could not connect: ' . mysql_error());
  }

  mysql_select_db("emriphone", $con);

   $u=$_GET['UserName'];
   $pw=$_GET['UserPassword'];

   $query = sprintf("SELECT UserName,UserPassword from appUsers WHERE UserName='%s' AND  UserPassword='%s'", mysql_real_escape_string($u),mysql_real_escape_string($pw));

  $login=mysql_query($query,$con) or die(mysql_error());

  if(mysql_num_rows($login)==1){

   $row =mysql_fetch_assoc($login);
    echo 'YES'; exit;
   }

  else{
   echo'NO';exit;
  }

  mysql_connect($con);

  ?>
</code>
Comment: this link may help you http://stackoverflow.com/questions/2720288/how-to-connect-with-sqlite-in-iphone
Comment: this is mine link dear but i am having same problem
Comment: the server output in string i am getting is @""; only so that's why i think it gives error can u help me out in thi s
Comment: What response your getting from server in string "serverOutput"?
Comment: @""; this when i nslog but when i direclty give username and password values to php script and match with database it returen YES
Answer: Try Using Following Code
<code>           NSString *data = [[NSString stringWithFormat:@"UserName=%@&UserPassword=%@",userNameTextField.text, userPasswordTextFiled.text];

           NSData *postData = [data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

    // preaparing URL request to send data.
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

NSString *url = [NSString stringWithFormat:@"http://www.myurl.com/emrapp/connect.php?"];

            [request setURL:[NSURL URLWithString:url]];
            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setHTTPBody:postData];
            [request setTimeoutInterval:7.0];

NSURLResponse *response;// = [[NSURLResponse alloc] init];
NSError *error;// = [[NSError alloc] init;

NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];

     NSLog(@"Login response:is %@",str);
</code>
Comment: wait i am giving you result of this
Comment: Just try to ECHO your query and see what does it respondes?
Comment: this same as i told you printing space only because there is @"" in str
Comment: I don't know much about php about i think thier is some problem in php code?
Comment: Means anything you try to ECHO from server is blank?
Comment: SELECT UserName,UserPassword from appUsers WHERE UserName='' AND UserPassword=''NO echo of query
Comment: Echo this ->  $query and then exit.
Comment: i have added in comment the echo of querry
Comment: So query is correct? I cant see any values for UserName & UserPassword?
Comment: i am post the values to username and password from iphone app so may be there may be probelm in psoting
Comment: Try to NSLog .."data" means ur value of username and password and "postlength".
Comment: what is the output of postlength?

Connect iphone app to mysql data base


How to create a Web slice with Search?

Question: Does anyone know how bing's weather webslice search works? I am attempting to create a web slice(only available in IE8) with search built in and I have read that forms are not allowed and neither is javascript.  Any help would be appreciated.
Answer: You can create active content by defining it on another page using the entry-content rel attribute of an  tag.  In this example slice.aspx has JavaScript code on it.

        My Active Slice

Answer: You can achieve a similar effect using some simple javascript in a Chrome extension to create an Arbitrary Web Slice extension but with the advantage of being able to take any slice out of any web page, not just predefined Web Slice areas like Bing weather.  Obviously only works in Chrome but Firefox has a similar extension API in GreaseMonkey.

How to create a Web slice with Search?


Não consigo pegar o número de telefone em uma agenda no telefone

Question: Não estou conseguindo pegar o número do telefone para adicionar na minha lista, alguém sabe?
public void pegarContatos() {

        Uri agenda = ContactsContract.Contacts.CONTENT_URI;
        Cursor cursor = getContentResolver().query(agenda, null, null, null, null);

        while (cursor.moveToNext()) {

            int telefone = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

            if(telefone == 1) {
                int ID = cursor.getColumnIndex(ContactsContract.Contacts._ID);
                String nome = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                Contato contato = new Contato(ID ,nome);

                listaDeContatos.add(contato);
            }
        }

        this.lista();

        cursor.close();
    }

Answer: é preciso fazer loop pois um contato pode ter vários números.
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
    int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
    String nome = cursor.getString(nameFieldColumnIndex);

    String ID = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

    ArrayList numeros = new ArrayList();

    Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + ID, null, null);
    while (phones.moveToNext()) {
        String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        numeros.add(number);
    }
    phones.close();
}
cursor.close();

Comment: Cara, conseguiria me explicar o que faz cada linha? Estou realizando uma pesquisa e não acho.. queria entender a função de cada linha....


[a-z]+, [A-Z]+, [0-9]+ and flag commands in awk

Question: I am trying to understand some commands in awk, which are related to If statement inside awk to change a value question.
The input file is
...
MODE P E
IMP:P 1 19r 0
IMP:E 1 19r 0
...
SDEF POS= 0 0 14.6 AXS= 0 0 1 EXT=d3 RAD= d4 cell=23 ERG=d1 PAR=2
SI1 L  0.020
SP1    1
SI4 0. 3.401
SI3 0.9
...
NPS 20000000

and the code is
#! /bin/bash

vals=(0.02 0.04)

for val in "${vals[@]}"; do
awk -v val="$val" '
  BEGIN { i=1; split (val,v," ") }
  # If it is a string, find the sequence SI1 L and change the value after that, using values that the user inputs
  /SDEF POS.*ERG=[a-zA-Z]+/ { flag="y" ; }
  /SI1 L/ { if (flag=="y") { $3=v[i]; i++; flag="n"; } }
  # If it is a number, change the number using values that the user inputs.
  /SDEF POS.*ERG=[0-9]+ / { sub(/ERG=[0-9]*/, "ERG="v[i],$0);i++; }
  1
' 20small > "${val}"
done

I am trying to ubderstand the following

Why after [a-z], [A-Z] and [0-9] there is the + sign? I can understand that those commands search for any letter and number after the defined sequence, but I don't seem to understand what does the + do.
What exactly does flag do? I can understand that /<expresion>/ flag="y" "replaces" the <expresion> with y. I can't seem to understand the reason to change the flag a few lines bellow. Is it like a dummy flag?
What exactly does /    / do? I know that this declares the search pattern. Why adding SDEF and POS? Just to be sure it's the correct line? I also find confusing the use of .*. Does it mean Find SDEF POS line and on the same line look for ERG no matter what it's between them? What exactly does /SDEF POS.*ERG=[a-zA-z]+/ do?

I am a rookie in awk so I am trying to learn it by example. An help would be more that welcome!
Answer:
+ means one or more repetitions.  For example, a+ will match a aa aaa etc.  a* match same as +, but also none a
flag is used as a temporary information holder.
/  / is regex holder and is used to show that it must match regex inside the two /

I do suggest you look at some awk one liners and try to understand how they work. Also start by reading some awk tutorials.  You can find a lot by using Google.
Comment: Thank you very much for your answer! More questions though. Why add the new flag i.e. `flag="n"`? It's a useless info, isn't it? In addition what does `.` do? For instance what does `/SDEF POS.*ERG=[a-zA-Z]+` do?
Comment: `.` represent any characters.  Flag is changed from `y` (yes) to `n` (no) to tell its done with some operation, to prevent repeating. I like flag with `0` or `1` but anything can do. `/SDEF POS.*ERG=[0-9]+ /` mans a text starting with `SDEF POS` then some or more unknown characters `.*` then `ERG=` then one or more digits `[0-9]+`. Eks it will match this line `DATA SDEF POSME TOERG=3445356`
Comment: I see!!! It means yes or no... Now it make4s perfect sense!!! Thank you very much!!!


Scheme Error, Return Binary Search Tree as Ordered List (R5RS)

Question: I am a noob at Scheme.  I have a binary search tree. The format of a node is a list of three elements, the first being the value at the node, the second being the left child node, and the third being the right child node. The "make" function creates an empty tree that looks like this: ( () () () ). I am able to create the tree, insert values, and find if a certain value exists in the tree.  My problem comes when I try to write a function that returns the tree as an ordered list.  Insert and Make functions:
<code>;Inserts a number into the tree
(define (insert t x)
    (cond ((null? (car t))
          (list x (make) (make)))
          ((< x (car t))
           (list (car t) (insert (cadr t)  x) (caddr t)))
          ((> x (car t))
           (list (car t) (cadr t) (insert (caddr t) x) ))

    )
)

;Makes a new empty tree
(define (make)
    (list (list) (list) (list))
 )
</code>
Those works fine.  Here is my as-list:
<code>;Gives list of all numbers
(define (as-list t)
    (cond
         (
           (null? (car t) )
           (list)
         )
          (
           #t
           (append (as-list (cadr t)) (as-list (car t)) (as-list (caddr t)))
         )
     )
  )
</code>
Running this, I get a contract violation, saying it expected "mpair?".  I do not believe this is a logic error on my part, but it may be.  Is this another parentheses problem?
Thank you for your time!
Answer: Your recursion should be
(append (as-list (cadr t)) (list (car t)) (as-list (caddr t)))
You only want to call as-list on trees, and the car of your t is not a tree.
Comment: You are basically a genius.  Thank you.  Yet again, I have been proven a moron.


Como limitar casa decimais?

Question: printf("%.3f", &resp);

Estou usando a seguinte linha, porém, ao comparar com um número, ele exige que tenha o mesmo número de casa decimais do originais, por exemplo:
2.963258741 !=  2.963

Tem como limitar as casas para que essa comparação seja verdadeira?
Comment: Possível duplicata de [Como limitar casas decimais?](https://pt.stackoverflow.com/questions/94564/como-limitar-casas-decimais)
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: Tem, mas não da forma como espera. Está usando tipos de ponto flutuante binário, e comparações são complicadas. Se depende de exatidão, precisa usar um tipo de ponto fixo ou flutuante decimal. Como C não tem nativo precisa criar uma solução ou arrumar uma biblioteca de terceiros.
Uma possibilidade "mais simples" é transformar isto em inteiro para comparar. Você pode multiplicar por 1000 para obter as 3 casas que deseja e fazer um cast para int. Ainda não é o ideal porque pode ter problemas de arredondamento, para ser exato teria que tratar isto.
Uma possibilidade sem usar um tipo decimal é pedir para entrar com o valor sem a vírgula, aí cabe em um inteiro.
Só note que se for manipular inteiros tem que entender a escala, para soma e subtração é tranquilo, mas para multiplicação e divisão muda o número de casas e aí precisa voltar para o número de casas original. Por isso um tipo decimal pode ser o mais adequado, ele já trata isto (ainda que nem sempre do jeito que precisa, aí volta ser manual).
Tem uma maneira de fazer a comparação de float com aproximação, mas eu não gosto dela. Obviamente precisa cuidar da escala também.
Coloquei no GitHub para referência futura.

Como limitar casa decimais?


any method for udp streaming video to be played in HTML browser page

Question: is there a node js module, method using flash, or anything that can allow a udp streaming video, located at an address like udp://(ipaddress):port to be played in an HTML page?
i mean there has to be SOME way to play a udp video on a web page right?
is this WebRTC API the best way to do it?
thanks
Comment: What is your use case for video streamed over udp? If you have an existing video you want to be streamed, using HTML video elements would be your best bet. If instead, the video is a live broadcast, you'll likely need to use WebRTC which does work over Udp but you'll a server component first.
Comment: it is a constantly streaming rendered video from a UDP address
Comment: most the webRTC examples I am finding are examples of streaming live video / audio from the computers webcam, but I am trying to stream just a video that is constantly playing from a UDP address like udp://(ipaddress).... any idea where i could find an example on this?
Answer: I'm doing something like this as well. A video stream (coming from ffmpeg in my case) and being pushed out over http:// but I think you could use the same principle for udp
I found a project that uses nodejs as a server to pick up the http packets being sent from ffmpeg, put them on a websocket to the browser, and then there's client-side Javascript that decodes each individual frame. In this case it was h.264, and the performance seems tolerable for real-time video.
https://github.com/131/h264-live-player
Answer: Flash supports UDP sockets - but you will run out of browsers supporting Flash.
http://help.adobe.com/en_US/as3/dev/WSb2ba3b1aad8a27b0-181c51321220efd9d1c-8000.html#WSb2ba3b1aad8a27b0-181c51321220efd9d1c-7ffe
So you can use Flash open an UDP socket, decode the video and render it.
WebRTC may use internally UDP but certainly won't enable you to open a bare socket.


Hide Block on Particular Page with Bootstrap

Question: I have a block called 'calendar' that I display on all events pages. events* such as events/today/, events/all/ etc.
A constraint that I have is that the block must be displayed on all events pages but on one particular page. The block must be hidden when the user is using a mobile device.
My thought process was to simply apply the bootstrap 'hidden-xs' class to the block. But the constraint is not satisfied as it would trigger on all the events pages.
What would be the easiest way to implement this?
Thanks in advance.
Comment: I've gone with a pure CSS implementation. By simply using a class in the body element and a media query. I'll add a more detailed answer to explain the solution shortly.
Comment: Just a note. You can use [Browser Class](https://www.drupal.org/project/browserclass) module in Drupal which will add classes to < body > tag based on OS and Browser user is viewing your site in.
Answer: You can use combination of media query  to achieve this.Using media query hide the block under mobile resolutions . For example
<code>@media screen and (min-width: 480px) {
.block-class {
    display: none;
  }
}
</code>
Answer: I used a media query and the node-type-event class generated in the body element to target and hide the views-event-block.
<code>@media only screen and (max-width: $screen-md) {
  .node-type--event{
    .views-event-block{
      display: none;
    }
  }
}
</code>


Having trouble trying to make a board game which ranomly chooses a case and then depending on the case adds that incrimented value until 50

Question: Here is my code, this is for a school project and the rubric stipulates against the use of functions or arrays. I need help with incrementing the different card values and and asking the player to draw each time, and display the current score of the player. Thank you in advanced.
<code>int main(int argc, char** argv) {
    //Initialize Random Seed once here!

    //Declare Variables
    int choose, cColor, rDraw, board, draw;//Choose

    //Initialize variables here
    do{
        //List of Problems which can be run by the program
        cout<<"    ****************************"<<endl;
        cout<<"    *     Welcome to Sorry!    *"<<endl;
        cout<<"    ****************************"<<endl;
        cout<<"Enter 0 to Start Game";
        cout<<"\tEnter 1 for How To Play"<<endl;
        cout<<"       Press Any Key to Exit"<<endl;
        cin>>choose;

        switch(choose){
            case 0:cout<<"******************************"<<endl;
            cout<<"What color would you like to be?"<<endl;
            cout<<"1. Red"<<endl;
            cout<<"2. Blue"<<endl;
            cout<<"3. Yellow"<<endl;
            cout<<"4. Green"<<endl;
            cin>>cColor;
            switch(cColor){
            case 1: cout<<"You have chosen Red."<<endl;
                break;
                case 2: cout<<"You have chosen Blue."<<endl;
                break;
                case 3: cout<<"You have chosen Yellow."<<endl;
                break;
                case 4:cout<<"You have chosen Green."<<endl;
                break;
                default: cout<<"ERROR Please only choose 1-4"<<endl;
            }
            cout<<endl;
            do{
            srand(static_cast<unsigned int>(time(0))); //seed the random number
            rDraw = rand() % 11 + 1;
            if(rDraw== 1){ //this is the trouble and downwards implenting until 50 and displaying it.
                board++;
                cout<<board;
                cout<<endl;
                cin>>draw;
                cout<<endl;
                break;
            }
            else if(rDraw== 2){
                board=board+2;
                     cout<<board;
                    cout<<endl;
                    cin>>draw;
                    cout<<endl;
                 break;
            }
             else if(rDraw== 3){
                 if (board== 0)
                 {
                     cout<<"Still in Start!\nYou need to draw either a 1 or 2."<<endl;
                     break;
                 }
                 else{
                     board=board+3;
                    cout<<board;
                    cout<<endl;
                    cin>>draw;
                    cout<<endl;
                 }
                 break;
            }
             else if(rDraw== 4){
                if (board== 0)
                 {
                    cout<<"Still in Start!\nYou need to draw either a 1 or 2."<<endl;
                    break;
                 }
                 else{
                    board--;
                     cout<<board;
                    cout<<endl;
                    cin>>draw;
                    cout<<endl;
                 }
                 break;
            }
             else if(rDraw== 5){
                 if (board== 0)
                 {
                     cout<<"Still in Start!\nYou need to draw either a 1 or 2."<<endl;
                     break;
                 }
                 else{
                     board=board+5;
                     cout<<board;
                    cout<<endl;
                    cin>>draw;
                    cout<<endl;
                 }
                 break;
            }
             else if(rDraw== 6){
                  if (board== 0)
                 {
                      cout<<"Still in Start!\nYou need to draw either a 1 or 2."<<endl;
                      break;
                 }
                 else{
                      board=board+7;
                cout<<board;
                cout<<endl;
                cin>>draw;
                cout<<endl;
                 }
                 break;
            }
             else if(rDraw== 7){
                 if (board== 0)
                 {
                     cout<<"Still in Start!\nYou need to draw either a 1 or 2."<<endl;
                     break;
                 }
                 else{
                     board=board+8;
                cout<<board;
                cout<<endl;
                cin>>draw;
                cout<<endl;
                 }
                 break;
            }
             else if(rDraw== 8){
                  if (board== 0)
                 {
                      cout<<"Still in Start!\nYou need to draw either a 1 or 2."<<endl;
                      break;
                 }
                 else{
                      board=board+10;
                cout<<board;
                cout<<endl;
                cin>>draw;
                cout<<endl;
                 }
                 break;
            }
             else if(rDraw== 9){
                  if (board== 0)
                 {
                      cout<<"Still in Start!\nYou need to draw either a 1 or 2."<<endl;
                      break;
                 }
                 else{
                      board=board+11;
                cout<<board;
                cout<<endl;
                cin>>draw;
                cout<<endl;
                 }
                 break;
            }
             else if(rDraw== 10){
                  if (board== 0)
                 {
                      cout<<"Still in Start!\nYou need to draw either a 1 or 2."<<endl;
                      break;
                 }
                 else{
                      board=board+12;
                cout<<board;
                cout<<endl;
                cin>>draw;
                cout<<endl;
                 }
                 break;
            }
             else{
                cout<<"11"<<endl; break;
            }
         }while(board !=50 && draw== 1);
            break;
            case 1:cout<<"Place Problem 1 here"<<endl;break;
            default:cout<<"Exiting the Menu"<<endl;
        }
    }while(choose>=0 && choose<=2);
    //Exit the program
    return 0;
}
</code>
Comment: Note : `//Initialize Random Seed once here!` I'd follow this advice. Seeding the RNG with `srand(static_cast(time(0))); //seed the random number` later in the program inside a loop will keep resetting the seed, skewing the RNG. Worse if you hit that `srand` fast enough, less than the resolution of `time` (almost always 1 second), you will always generate the same sequence.
Comment: Recommendation: Stop writing new code. and test what you have so far. You are being forced to write ing spaghetti code by some ing
 lunatics, so you'll have to be extra careful. If you keep adding tho this program without ensuring what you currently have is correct, you will be adding more bugs to an already shaky foundation and the time you will have to spend debugging will increase exponentially, not linearly with each new bug.
Answer: Excessive use of nesting is usually a bad practice.
Try to remove the hierarchy and make it as flat as possible. It will also help you to better visualize your code and catch bugs.
For these show menu-read input type of code, the loop and a half pattern is usually the best coding style.


Windows Server Use Ip address on iPhone

Question: I've a windows server. I need to be able to use its IP address to connect to the internet via my iPhone. I don't know if I've to set up a proxy on the server or if it's possible to use SOCKS and do a SSH Tunneling, as with linux. Do you've any suggestion on how I can achieve this?
Comment: Where is the iPhone? Is it on the same local network as the server, or are you wanting to do this from anywhere in the world?
Comment: The Server is a datacenter somewhere, the iPhone is with me... so I guess it's not on the same network
Answer: Setup an IPSec VPN via Routing and Remote Access on your Windows Server.
Then if you connect to the VPN from your phone, the iPhone's internet traffic will route through the server.

Windows Server Use Ip address on iPhone


On a conjecture and other numbers like $144$.

Question: Yesterday, I noticed that the following numbers were prime: $$67, 167, 467, 967, 1667.$$ I realised that the digits of these primes, apart from $67$, were square numbers: $$0^2, 1^2, 2^2, 3^2, 4^2.$$
I then wanted to find values $a_n$ such that when we concatenate $a_n^{\ \ 2}$ with $67$, it is a prime number. This means, we join $a_n^{\ \ 2}$ with $67$ to form a new number, and we will denote this as $a_n^{\ \ 2}\mid\mid67$. For example, $1$ concatenated with $2$ is denoted as $1\mid\mid 2$ which equals $12$.
Below is a sequence of all the values $a_n$ that range from $0$ to $160$ inclusive:
$0,1,2,3,4,7,9,10,15,16,18,23,24,28,30,31,33,42,43,45,48,53,55,61,65,68,69,72,76,77,87,88,93,94,96,98,105,106,109,110,112,113,116,117,119,122,125,130,132,133,138,140,144,145,147,151,155,159.$
Here, $a_1 = 0$, $a_2 = 1$, $a_3 = 2$, $\ldots$
Conjecture 1.
I made a conjecture that for every number $b_n^{\ \ 2}\mid\mid 67$ that is not prime, it will either have $2$ or $3$ divisors such that $b_n$ does not appear in this sequence. I did find a counter-example, namely $158$. This was the first counter-example thus far such that, $$158^2\mid\mid 67 = 24964\mid\mid 67 = 2496467 = 17\times 19\times 59\times 131.\tag{4 divisors}$$
Conjecture 2.
I also made another conjecture that for $n\geqslant 3$, if $a_n^{\ \ 2}\mid\mid 67$ is prime, and $(a_n + 1)^2\mid\mid 67$ is also prime, then not only will $(a_n + 2)^2\mid\mid 67$ not be prime, but it will be semi-prime, which is a prime composed of strictly two prime numbers. However, I also found another counter-example, namely $144$. This was also the first counter-example to this conjecture, such that $144^2\mid\mid 67$ is prime, $(144^2 + 1)\mid\mid 67$ is also prime, but $$(144^2 + 2)\mid\mid 67 = 19\times 151\times 743.\tag{3 divisors}$$ This number is not semi-prime because it is composed of three prime numbers.
I extended my first conjecture for which every number $b_n^{\ \ 2}\mid\mid 67$ that is not prime will have at most $4$ prime divisors. But my question is, do there exist other counter-examples to the second conjecture? Particularly counter-examples that are square numbers, like $144$? And is there a counter-example to my extended first conjecture?
Thank you in advance.

Edit:
Conjecture 2 has been proven to be false, and lots of the counter-examples of conj$_2$ are square numbers. Here are the first few among the list: $$\begin{align} 1 = 1^2 &\quad 2916 = 54^2 &\quad 5776 = 76^2 &\quad \\ 837225 = 915^2 &\quad 3111696 = 1764^2 &\quad 10259209 = 3203^2\end{align}$$
Comment: I also wonder why the resilience to writing it in the form $100k^2+67$ rather than $k^2\Vert 67$.
Comment: Is what you mean $100a_n^2+67$? That formulation is perhaps more amenable to analysis than your concatenation notation. It is easy to show that this is not divisible by any of $2, 3, 5, 7, 11, 13$. Avoiding low primes is a notorious way of creating conjectures about primes which are falsified for large values.
Comment: @YuriyS I noticed that $67$ is prime, $167$ is prime, $467$ is prime, $967$ is prime, and $1667$ is prime. I found that the first few digits apart from $67$ were squared numbers. Then it came to this.
Comment: @RobertSoupe ok. I will look into that. Thank you :)
Comment: @MarkBennet yeah, but I introduced concatenation for users who wanted to learn something :) Also, thanks for that little tip
Comment: $2916 = 54^2$. If I had to bet I will believe that there will be infinitely many $n'$ such that $100(n'^2)^2 + 67$, $100(n'^2+1)^2 + 67$ and $100(n'^2+2)^2 + 67$ are all primes.
Comment: You should look at the diagram of primes in $\mathcal O_{\mathbb Q(\sqrt{-67})}$. There are a few different programs available from GitHub to do that.
Comment: @HwChu Yes, I thought pretty much the same thing haha.
Answer: There are many $n$ such that $100n^2+67$, $100(n+1)^2+67$ and $100(n+2)^2+67$ are all prime. The sequence of such $n$ begins
$$1,2,204,205,212,228,236,237,337,406,705,706,721,1016,1554,1765,1802,1879,1883,$$
$$1884,1945,1946,1954,1955,2088,2089,2184,2262,2294,2488,2744,2796,2858,2865,2914,$$ $$2915,2916,2940,2998,3076,3077,3408,3409,3434,3435,3664,3681,3707,3708,3810,3985,$$ $$4361,4616,4751,4752,5107,5549,5755,5776,5816,6146,6201,6223,6246,6247,6494,6809,$$ $$6858,7159,7476,7639,7697,7804,7912,8229,8230,8626,8908,8950,9137,9401,9628,\dots$$
Your conjecture 2 is false.
Added: Code to do this calculation in GP:
f(n)=100n^2+67
for(i=1,10^4,if(isprime(f(i))>0 && isprime(f(i+1))>0 && isprime(f(i+2))>0,print1(i,",")))
Added: Here are all the square terms less than 10^8:
$1,2916,5776,837225,3111696,10259209,18438436,24750625,63091249,$
$66879684,
67305616,67815225,71385601.$
Comment: Two lines of GP/PARI code.  I'll add them to the answer.
Comment: Wow!! How did you get all of those results so quickly??
Comment: $2916=54^2$.......
Comment: $837225 =915^2$ and $3111696=1764^2$ are in this list, too.  I'm not sure this is relevant.
Comment: Hahah yes you are right, but I was just curious. Thank you very much :)
Comment: $3203^2=10259209$ is also in the list.
Comment: Please upvote if anything is useful.  I'm trying to get to 10k!
Comment: $4294^2$ and $4975^2$ are in the list, too.
Comment: I cannot upvote. I have to wait $24$ minutes hahah sorry though. Thank you so much though :)
Answer: So you are looking at numbers of the form $a_k := 100k^2 + 67$. Let's see what are the conditions to have $p \ | \ a_k$.
$$
p \ | \ a_k \quad\Leftrightarrow\quad k^2 \equiv -100^{-1}\times 67 \pmod p.
$$
Such $k$ exists if and only if $ \Big(\frac{-67}{p}\Big) = 1$. This happens at half of the primes. As there are infinitely many primes, you should be able to find $k$ using CRT such that $a_k$ has any number of divisors as you wish.


How to set the values of a new incident?

Question: I'm writing a C# code that creates a new Service Manager 2012 Incident and set its values I'm having a problem setting the "Source", "Classification Category", and "Affected User" values for the incident,, any help please?
thanks,,
Comment: i need a function to retrieve the data inside Incident Source list and Incident Classification Category list
Answer: You can find your answer in these pages:
http://scsmnz.net/c-code-snippets-for-service-manager-1/
http://blog.scsmsolutions.com/2011/09/codesnipets-for-scsm-2010-sdk/
There is no difference between SCSM 2010 and 2012 incident creation.


Add a node as a select list in Webforms Drupal 6?

Question: I want to make a Webform in Drupal 6 where I can put a <select> list where the lists are a node. I already created a content type which is events and these events expires. So what I want is when the user submits a form he/she has the ability to select from the <select> list so when the form is submitted, when I go to the submission results, I can see the content type(events) which the user chose upon submitting the webform. Is this possible? Thanks
Answer: If you are using D6 then consider the Webform View Reference Component module. Here is a quote about it (from the module's project page):

... adds a webform component where you could use a View as a datasource for your normal webform select component. Instead of hardcoding all the selectable values in the component values field you just select a reference to a View similar to the CCK nodereference. The selectlist/radiobuttons/checkbox then automatically gets filled with all the nodes from the View.
Comment: how do I exactly use that?I already installed the module but still in my `select` field, my nodes are not available?
Comment: I personally haven't tried the module. But you should see another form element called as "Select View". So you add that component and in the select list you select the view which list all the nodes you want. If you need to learn how to use views then will have to use the advance help module to learn how to create views.
Comment: Thanks a lot. I tried to explore around and found the `select view` list which contains all the nodes I want. Thanks a lot. :)


Is there an easier way of doing this?

Question: So I wrote a python code that converts seconds into hour minutes and secs, but the code doesn't look neat. What would be a better way of doing what my script is doing?
from fractions import Fraction as Frac
from decimal import Decimal as Deci

def Hrs(mins,hr=[],deci=[],hrs=True):
  return(Seperator(mins/60))

def Seperator(Decimal,num=[],deci=[],nums=True):
  del num[:],deci[:]
  for item in str(Decimal):
   if item == '.':
    deci.append(item)
    nums = False
    continue
   num.append(item)if nums else deci.append(item)
  return''.join(num),''.join(deci)

def Mins(secs):
  t = Deci(float(Frac(secs,60)))
  return t

def Secs(deci):
  r = Deci(float(deci*60))
  return r

def Clean(decimal,deci=[],p=True):
  del deci[:]
  for item in str(decimal):
   if item == '.':
    if p:deci.append(item);p=False;continue
    else: break
   deci.append(item)
  return float(''.join(deci))

if __name__ == '__main__':
  Seconds = 6033
  Hours   = Hrs(Mins(Seconds))[0]
  Minutes = int(Secs(Clean(Hrs(Mins(Seconds))[1])))
  Seconds = int(eval(Seperator(Secs(Clean(Hrs(Mins(Seconds))[1])))[1])*60)
  print '{}:{}:{}'.format(Hours,Minutes,Seconds)

Answer: Absolutely. Here you go:
def convert(total):
    secs = total%60
    total /= 60
    minutes = total%60
    total /= 60
    hours = total%24
    days = total/24
    return (days, hours, minutes, secs)

convert(13246345)

Output: (153, 7, 32, 25)
Answer: This should do the trick
import time

localtime   = time.localtime()
timeString  = time.strftime("%Y%m%d%H%M%S", localtime)

timeString  = time.strftime("%H:%M:%S")
print timeString

Is there an easier way of doing this?


Second order D.E. - general solution

Question: If $y=y(x)$, and we have the differential equation
$y''=-k^2y$
for some constant $k>0$, then wolfram alpha gives the general solution as $y=A\cos(kx)+B\sin(kx)$. I've also seen this result used in various other situations. My first question is, aren't the functions
$y=A\cos(kx+x_1)+B\sin(kx+x_2)$ for some constant angles $x_1,x_2$
more general? They clearly satisfy the differential equation. I know this isn't a massive problem but it's irritating me. Thanks for any help!
Answer: It is essentially the same, if you expand the formula for the cosine or sine of a sum. Then $A,B$ would be different, but since without initial values conditions they are arbitrary, then you encompass all solutions anyway.
Comment: Oh I see, alright thanks a lot!

Second order D.E. - general solution


Erro ao retornar formulário dinâmico

Question: Pretendo criar um formulário dinâmico mas recebo o seguinte erro:

javprogram.js:377 Uncaught TypeError: "#retorno3".html is not a
function
at Object.success (javprogram.js:377)
at fire (jquery-latest.js:3119)
at Object.fireWith [as resolveWith] (jquery-latest.js:3231)
at done (jquery-latest.js:9275)
at XMLHttpRequest.callback (jquery-latest.js:9685)

Código para criar o formulário:
HTML:
<form action="#!" id="retper">

</form>

JS:
$(document).on('click', '.view_perfil', function(){
   var perf = $(this).attr("id_perfil");

   $.ajax({
        url:"perfil.php",
        method:"POST",
        cache: false,
        data:{perf:perf},
        dataType:"json",
        success:function(data){
            var linha = ``;
            for (var i = 0; i < data.length; i++) {

                Nome = data[i][0];
                Email = data[i][1];
                Acesso = data[i][2];
                Foto = data[i][3];

                linha += `

                        <input type="text" class="form-control" value="${Nome}">

                        Nome

                        <input type="text" class="form-control" value="${Email}">

                        Email

                        <input type="text" class="form-control" value="${Acesso}">

                        Acesso

                            Add Foto

`;
                }

                ("#retper").html(linha);
        }

    });
});

php:
$perf = $_POST["perf"];
$stmt = $conn->prepare("SELECT dados.Utilizadores.Nome, Email, dados.Niveis_Acessos .Nome AS Acesso, Foto
FROM dados.Utilizadores LEFT OUTER JOIN dados.Niveis_Acessos
ON dados.Niveis_Acessos.Id = dados.Utilizadores.Niveis_acesso_id WHERE dados.Utilizadores.Id = :perf");
$stmt->bindValue(':perf', $perf, PDO::PARAM_INT);
$stmt->execute();
$json = [];
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
    extract($row);
    $json[]= [(string)$Nome, (string)$Email, (string)$Acesso, (string)$Foto];
}
echo json_encode($json);

Já verifiquei e o script php retorna corretamente os dados. O problema está ao construir o HTML.
Comment: $("#retper").html(linha); Faltou o $
Answer:

//apenas um exemplo
let linha='<input type="text" value="vou para o formulario">';
//correto.
//vai  definir o conteúdo do form com id = Outroretper.
$("#Outroretper").html(linha);

//vai dar o erro, está faltando o $
("#retper").html(linha);

<form action="#!" id="Outroretper">

</form>

<form action="#!" id="retper">

</form>

Erro ao retornar formulário dinâmico


Limit of the surface integral

Question: I'm trying to understand the following when I'm reading a text. It states that if $g:\mathbb R^3 \backslash \{0 \} \to \mathbb R$ is smooth and $f: \mathbb R^3 \to \mathbb R$ is $C^1$ (continuously differentiable), and $\int_{\partial B_\epsilon } g(x) \, dS = 0$  for all $\epsilon > 0$. Then $\int _{\partial B_\epsilon} g(x) f(x) \, dS \to 0$ as $\epsilon \to 0$. Where $B_\epsilon$ are balls centered at $0$ with radius $\epsilon$, and the integrations are on the surface of $B_\epsilon$.
I'm having trouble seeing that. The intuition is clear like as $\epsilon \to 0$, $f(x) \to f(0)$ and the variations in the integration cancels out because of $g$. How can I prove it? Any help is appreciated.
Answer: Observe
\begin{align}
\left| \int_{\partial B_\varepsilon} g(x) f(x)\ dS(x) \right| =&\ \left| \int_{\partial B_\varepsilon} g(x) f(x)\ dS(x)- \int_{\partial B_\varepsilon}g(x)f(0)\ dS(x)\right| \\
\leq&\ \int_{\partial B_\varepsilon}|g(x)||f(x)-f(0)|\ dS(x).\\
\end{align}
Fix $\varepsilon'>0$. Since both $f$ and $g$ are continuous at the origin, then there exists $\varepsilon>0$ such that $|f(x) - f(0)|<\varepsilon'$ and $|g(x) - g(0)|<\epsilon'$ whenever $|x|\leq \varepsilon$. In particular, it follows
\begin{align}
\int_{\partial B_\varepsilon}|g(x)||f(x)-f(0)|\ dS(x) \leq  4\pi (\varepsilon')^2(|g(0)|+\varepsilon')\varepsilon'
\end{align}
whenever $|x| \leq \min(\varepsilon, \varepsilon')$. Thus, it follows
\begin{align}
\lim_{\varepsilon\rightarrow 0}\int_{\partial B_\varepsilon} g(x) f(x)\ dS(x)=0.
\end{align}
Comment: Sorry, I forgot to say that $g$ has a singularity at the origin. Otherwise this is trivial.

Limit of the surface integral


Is there a way to find out what is causing 'No Instance Found' on run in Alloy?

Question: I have written in model using Alloy. However for certain conditions running the predicate to find an instance is failing and it says that no instance can be found. I tried increasing the bound to about 16 instances, yet it does not find any instance.
Is there any way I can debug this so that I can see which facts are failing which is causing Alloy not being able to find an instance?
Thanks !
Answer: If you change the default sat solver to minisat with unsat core, then it will be possible to highlight the constraints that can't be satisfied in a same instance.
Another possible solution is to comment your constraints one by one until analysis yield an instance hence pinpointing which constraint might cause trouble.
For a more specific answer, please share your model.
Comment: How do I change the SAT solver? Do I select it from the options tab? However for me, it doesn't show any other option apart from SAT4J.
Comment: Yes, other solvers are present as binaries in the jar file. They might not be compatible with the system you are running. I'd thus suggest to try your luck with the second option and if nothing comes out of it, feel free to share your model


How to apply xss filter on a csv file

Question: I have a CSV file from which I am importing some data. Should I need to apply XSS filter? How do I achieve this?
<code>   while (!feof($handle)) {
    $data = fgetcsv($handle);
    $path[] = $data[0];
    $title[] = $data[1];
    $description[] = $data[2];
    $abstract[] = $data[3];
    $keywords[] = $data[4];
}
</code>
Answer: Well to my knowledge Drupal doesn't mind the input/import data that much, as long as it's rendered in a secure way.

So what we really have to do is make sure that, regardless the data, its content can never be interpreted as SQL. To do this, we use the escaping functions provided by the database API. We do this escaping in the database layer and not directly after receiving input as it may not be the only escaping (or filtering) we have to do. - https://www.drupal.org/node/101495

Just my 2 cents :)
Comment: This answer mixes up handling user input going into the database and user input being rendered.  Two different things.
Comment: well actually i want to check before any operation on data is performed.
Just when we get the data from csv .if the csv contains any unsantize data the while loop should stop and an error msg should be displayed to user

How to apply xss filter on a csv file


Detect empty, new tab openings in Google Chrome

Question: I just published a Google Chrome extension which loads background images into new, empty tabs. The plugin is found here in the Chrome Web Store.
For detecting new and empty tabs, I need to ask for "tab" permissions in the extension's manifest.json. This, however, gives the extension the permission to read the browser's history. Not all users will want this and we don't actually need it. Is there a way to detect empty tabs without this permission requirement? Currently our check looks like this:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
    if (changeInfo.status == "loading" && tab.url == 'chrome://newtab/')
    { /* load background into tab */ }
});

Answer: If you want to customize the new tab page you should add this to your manifest:
"chrome_url_overrides": {
   "newtab": "newtab.html"
}

Then place the script you are currently injecting into new tab pages as a


Adding Hostname as a Custom Varnish Header

Question: I've several varnish cache servers (v2.1), and I'm looking to add the hostname in the headers in the response from varnish -- so I know which server is (or not) serving cached pages. Upon googling, I found this snippet, but it gives errors:
sub vcl_deliver {
  if (obj.hits > 0) {
    set resp.http.X-MH-Cache ="HIT " obj.hits " "*
    server.hostname* " " resp.http.Age;
  } else {
    set resp.http.X-MH-Cache ="MISS " *server.hostname* ""
  }
}

I am not tied to this snippet per se. Ideally, I would like to set hostname in the event of a miss or a hit.
I am fairly new to vcl files, so any guidance and assistance would be much appreciated. Many thanks!
KM
Answer: Stumbled upon this by chance (isn't it always that way?): https://www.varnish-cache.org/trac/wiki/VCLExampleHitMissHeader -- exactly what I was looking for.
Comment: This is not a correct answer (linking to documentation)
Answer: More likely the error was due to the star signs, and missing plus signs when building up the "X-MH-Cache response header:
Unknown token '*' when looking for STRING

The working vcl code snippet looks like this:
vcl 4.1;
import std;
sub vcl_deliver {
  if (obj.hits > 0) {
    set resp.http.X-MH-Cache = "HIT: " + obj.hits + " *" + server.hostname + "* Age: " + resp.http.Age;
  } else {
    set resp.http.X-MH-Cache = "MISS *" + server.hostname + "*";
  }
}

A snapshot (January 2nd, 2012) to the URL from of the answer (January 27th, 2012) can be found on the Internet Archive site here:
https://web.archive.org/web/20120309095329/https://www.varnish-cache.org/trac/wiki/VCLExampleHitMissHeader