What is the mistake with my Android animation of my ImageView?

Question: This code works only for the first animation. Though the final position of the ImageView is not exactly the point of the MotionEvent and the animation looks not smooth. The result of all other MotionEvents is actually no animation. The ImageView just appears at the point i touch the screen.
Here is the code.
ImageView image;
MyAnimationListener am;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    image = (ImageView)findViewById(R.id.imageView1);
    am = new MyAnimationListener(image);
}

@Override
public boolean onTouchEvent(MotionEvent mEvent){

    if(mEvent.getAction()==MotionEvent.ACTION_DOWN){
        TranslateAnimation tAnimation = new TranslateAnimation(image.getX(),mEvent.getX(),image.getY(),mEvent.getY());
        tAnimation.setDuration(500);
        am.setCoordinates(mEvent.getX(), mEvent.getY());
        tAnimation.setAnimationListener(am);

        AnimationSet aSet = new AnimationSet(true);
        aSet.addAnimation(tAnimation);
        image.startAnimation(aSet);
    }

    return true;
}

And the interesting methods of MyAnimationListener.
ImageView i;
float x,y;

public MyAnimationListener(ImageView i){
    this.i = i;
}

public void setCoordinates(float x, float y){
    this.x = x;
    this.y = y;
}

@Override
public void onAnimationEnd(Animation animation) {
    i.setX(x);
    i.setY(y);
}

Thanks in advance.
Comment: use mEvent.getAction()==MotionEvent.ACTION_MOVE case also.. as it continuosly track as we move finger...while action down traces the point where we tap on first cordiante before move
Comment: Okay. But that does not solve the proble. The code works for the first tap. All following taps produce no animation. And i cant figure out why.
Answer: may be you need to do call a fillAfter so that the postion is not reset at the end of the animation. see link


rails 5 - could could not generate rspec:install

Question: I am trying to build restful  api using rails
I am following the blog link tutorial to work out
https://scotch.io/tutorials/build-a-restful-json-api-with-rails-5-part-one
but when i run this following command
rails generate rspec:install
It generates the following error
identical  .rspec
       exist  spec
      create  spec/C:/Users/Shad Munir/AppData/Local/Temp/d20170503-6768-l4n0e9/spec/spec_helper.rb
C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:253:in `mkdir': Invalid argument @ dir_s_mkdir - E:/todos-api/spec/C: (Errno::EINVAL)
        from C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:253:in `fu_mkdir'
        from C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:227:in `block (2 levels) in mkdir_p'
        from C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:225:in `reverse_each'
        from C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:225:in `block in mkdir_p'
        from C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:211:in `each'
        from C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:211:in `mkdir_p'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/actions/create_file.rb:61:in `block in invoke!'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/actions/empty_directory.rb:116:in `invoke_with_conflict_check'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/actions/create_file.rb:60:in `invoke!'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/actions.rb:95:in `action'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/actions/create_file.rb:25:in `create_file'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/actions/file_manipulation.rb:27:in `copy_file'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/actions/directory.rb:94:in `block in execute!'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/actions/directory.rb:80:in `each'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/actions/directory.rb:80:in `execute!'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/actions/directory.rb:66:in `invoke!'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/actions.rb:95:in `action'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/actions/directory.rb:52:in `directory'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rspec-rails-3.5.2/lib/generators/rspec/install/install_generator.rb:23:in `block in copy_spec_files'
        from C:/Ruby23-x64/lib/ruby/2.3.0/tmpdir.rb:89:in `mktmpdir'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rspec-rails-3.5.2/lib/generators/rspec/install/install_generator.rb:20:in `copy_spec_files'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/command.rb:27:in `run'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/invocation.rb:126:in `invoke_command'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/invocation.rb:133:in `block in invoke_all'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/invocation.rb:133:in `each'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/invocation.rb:133:in `map'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/invocation.rb:133:in `invoke_all'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/group.rb:232:in `dispatch'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.19.4/lib/thor/base.rb:444:in `start'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.2/lib/rails/generators.rb:180:in `invoke'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.2/lib/rails/commands/generate.rb:13:in `<top (required)>'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/activesupport-5.0.2/lib/active_support/dependencies.rb:293:in `require'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/activesupport-5.0.2/lib/active_support/dependencies.rb:293:in `block in require'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/activesupport-5.0.2/lib/active_support/dependencies.rb:259:in `load_dependency'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/activesupport-5.0.2/lib/active_support/dependencies.rb:293:in `require'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:138:in `require_command!'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:145:in `generate_or_destroy'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:60:in `generate'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:49:in `run_command!'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.0.2/lib/rails/commands.rb:18:in `<top (required)>'
        from bin/rails:4:in `require'
        from bin/rails:4:in `'

I tried some related solution from stack overflow but none of them is working .
Comment: Can you try to create the project on you C: drive instead?
Comment: Could you please add link to the SO questions that you tried but didn't work?
Answer: I had this same problem a couple of days ago. What I had to do was delete all versions of RSpec from my machine and then run bundle install. This installed the latest version of RSpec and everything was good afterwards.


Estrutura de Dados, Alocação Dinâmica de Memória em C++ e leitura de dados

Question: Eu tenho um código com encapsulamento e composição com 3 classes em C++. No meu código eu tenho de ciar os objetos de forma estática mas quero criá-los de forma dinâmica. Eu tenho uma classe chamada trabalhador que tem 2 objetos de outras 2 classes (info e familia) como seus membros, de forma que trabalhador tem info e familia. Toda vez que eu quero criar um objeto trabalhador (que tem info e familia) eu tenho de fazê-lo de forma manual (estática) mas quero fazê-lo dinamicamente. Eu quero que o usuário escolha quantos trabalhadores ele quer criar dinamicamente. Eu acho que eu deveria usar estruturas de dados como uma lista e alocação dinâmica de memória mas eu não sei como fazê-lo. Meu código também cria um arquivo chamado "cadastro.dat" e eu quero ler esse arquivo mas também não sei como fazê-lo. Alguém poderia me ajudar? Estou mostrando o código que já fiz.
//MAIN
#include <iostream>
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::ios;

#include <fstream>
using std::ofstream;

#include <cstdlib>
using std::exit;

#include "trabalhador.h"

int main()
{
    ofstream saidaArquivoCadastro( "cadastro.dat", ios::out );

    if ( !saidaArquivoCadastro ) // operador ! sobrecarregado
 {
 cerr << "Arquivo nao pode ser aberto" << endl;
 exit( 1 );
 }

    cout << "INFORME OS DADOS SOLICITADOS: \n\n";
    cout << "Nome do funcionario: ";
    info i1;
    cout << "\nCPF: ";
    info i2;
    cout << "\nNome da mae: ";
    familia f1;
    cout << "\nNome do pai: ";
    familia f2;
    trabalhador t(i1, i2, f1, f2);

    return 0;
}

//trabalhador.h
#ifndef TRABALHADOR_H
#define TRABALHADOR_H

#include "info.h"
#include "familia.h"

class trabalhador
{
    public:
        trabalhador (const info &, const info &, const familia &, const familia &);
        void print () const;
    private:
        const info funcionarioNome;
        const info funcionarioCPF;
        const familia mae;
        const familia pai;
};

#endif

//trabalhador.cpp
#include <iostream>
using std::cout;

#include "trabalhador.h"
#include "info.h"

trabalhador::trabalhador (const info &infoNome, const info &infoCPF,
const familia &famiMae, const familia &famiPai)
:funcionarioNome (infoNome),
funcionarioCPF (infoCPF),
mae (famiMae),
pai (famiPai)
{
    cout << "\nDados do funcionario: \n";
    print();
}

void trabalhador::print() const
{
    funcionarioNome.print();
    funcionarioCPF.print();
    mae.print();
    pai.print();
}

//info.h
#include <string>
using std::string;

#ifndef INFO_H
#define INFO_H

class info
{
    public:
        info (string = "");
        void setInfoDado (string);
        void setInfo ();
        void print () const;
    private:
        string infoDado;
};

#endif

//info.cpp
#include <iostream>
using std::cout;
using std::cin;

#include <string>
using std::string;
using std::getline;

#include "info.h"

info::info (string info)
{
    setInfoDado (info);
}

void info::setInfoDado (string info)
{
    infoDado = info;
    setInfo();
}

void info::setInfo ()
{
    string nome;
    getline (cin, nome);
    infoDado = nome;
}

void info::print () const
{
    cout << infoDado << "\n";
}

//familia.h
#include <string>
using std::string;

#ifndef FAMILIA_H
#define FAMILIA_H

class familia
{
    public:
        familia (string = "");
        void setFamiDado (string);
        void setFami ();
        void print () const;
    private:
        string famiDado;
};

#endif

//familia.cpp
#include <iostream>
using std::cout;
using std::cin;

#include <string>
using std::string;
using std::getline;

#include "familia.h"

familia::familia (string info)
{
    setFamiDado (info);
}

void familia::setFamiDado (string info)
{
    famiDado = info;
    setFami();
}

void familia::setFami ()
{
    string nome;
    getline (cin, nome);
    famiDado = nome;
}

void familia::print () const
{
    cout << famiDado << "\n";
}

Answer:
No meu código eu tenho de ciar os objetos de forma estática mas quero
criá-los de forma dinâmica. Eu tenho uma classe chamada trabalhador
que tem 2 objetos de outras 2 classes (info e familia) como seus
membros, de forma que trabalhador tem info e familia. Toda vez que eu
quero criar um objeto trabalhador (que tem info e familia) eu tenho de
fazê-lo de forma manual (estática) mas quero fazê-lo dinamicamente

O problema maior com seu código é que errou nos construtores para info e família e acabou ficando sem a implementação do construtor padrão dessas classes. E no caso da classe trabalhador não só não escreveu um construtor padrão mas ainda escreveu um único construtor que cria 2 instâncias de familia e duas de info, só que sem o construtor que você imaginava que iria ler os valores do teclado para o único campo dessas classes.
Veja:
class trabalhador
{
    public:
        trabalhador (const info &, const info &, const familia &, const familia &);
        void print () const;
    private:
        const info funcionarioNome;
        const info funcionarioCPF;
        const familia mae;
        const familia pai;
};

Poderia ter escrito do modo normal
class trabalhador
{
public:
    trabalhador() :
        funcionarioNome(info()),
        funcionarioCPF(info()),
        mae(familia()),
        pai(familia())
    {};

    trabalhador(
        const info&,
        const info&,
        const familia&,
        const familia&
    );
    void print() const;

private:
    const info funcionarioNome;
    const info funcionarioCPF;
    const familia mae;
    const familia pai;
};

E aí teria os dois construtores. E para criar alguns trabalhadores poderia escrever o normal:
    trabalhador* WorkForce = new trabalhador[20];
    WorkForce[19].print();
    delete[] WorkForce;

Note que do modo como escreveu as 3 classes não pode fazer nada com isso exceto chamar print() para o trabalhador.


How can I save a file in specific folder?

Question: I want to upload files to specific folders. How can I achieve this programatically. How can I modify below code such that upload_location should be dynamic.
<code>    $form['document'] = array(
    '#type' => 'managed_file',
    '#upload_validators' => array('file_validate_extensions' => array('xml')),
    '#upload_location' => 'public://',
    '#submit' => array('custom_document_submit'),
    );
</code>
Comment: How you wants to pass folder name? do you want to pass the folder name as a form element.
Comment: I have some folders in public://, so I am thinking to display all folder names in dropdown, then user can select the folder name and next upload option is there. When user selects folder and uploads files, it should go to that perticular folder. So how you will suggest me to do?
Answer: In form submit action you can give the destination path.
<code>function formname_form_submit($form, &$form_state) {
    $destination = $form_state['values']['foldername_name'];
    $validators = array();
    $file = file_save_upload('file', $validators, 'public://'.$destination);
}
</code>
More about file_save_upload get https://api.drupal.org/api/drupal/includes!file.inc/function/file_save_upload/7.x.
more related links
https://stackoverflow.com/questions/1253094/howto-drupal-file-upload-form
Comment: Thank you for this. Is there any way to pass dynamic folder name in the form element only.?
Comment: i think you want a input box for folder name right?
Comment: I have input box and i have one button, when I enter name and click a button, it will create a folder in public//:. But now i want to upload the files to the newly created folders.
Comment: are you creating folder on form submit button or another button present folder create.
Comment: for that form submit I am calling seperate submit function, not default form submit.


! Error: docker push exited with Error: 1

Question: I'm trying to push my docker image to Heroku but I get this error:
EOF
 !    Error: docker push exited with Error: 1
I tried to retry the push command many times: Heroku container: push web – app calm-bayou-96507
But after one minute (more or less) of pushing the docker image I get the same error.
Here is the logs of my docker command:
The push refers to repository [registry.heroku.com/calm-bayou-96507/web]
7686842e236d: Pushing  191.1MB/191.1MB    8db154b68457: Layer already exists    cd4b2eb3c039: Layer already exists    6e73d8f201cb: Pushing  2.603GB/2.603GB    f75f1e7a96e5: Pushing  22.76MB/22.76MB    72d0068e8a69: Pushing   7.69MB/7.69MB    748a464db597: Layer already exists    ebb30ce58669: Pushing  71.38MB/71.38MB    1bd26e8168dc: Waiting    ffc9b21953f4: Waiting
EOF
 !    Error: docker push exited with Error: 1

I'm verifying my connection by speedtest and here is the result:
Speedtest Result:

How to solve this problem?
Answer: It seems like you got to give it some times and try again, because Heroku needs to save it or something like that.
Answer: I've seen this, and it has to do with being consistent with the use of sudo. As a good last resort:
sudo heroku login
sudo heroku container:login
sudo heroku container:push web

Not that I logged in with sudo and pushed with sudo.
When successful, the response will be
Your image has been successfully pushed. You can now release it with the 'container:release' command.


Angular Material Dialog & JSON.stringify

Question: I am unable to show the string provided by JSON.stringify including the spaces for indentation inside a material dialog of my Angular project. It always appears as a raw data string, without any spacing for the indentation, even if I use the spaces parameter.
The funny thing is that the same code provides a good indentation if I console.log it.
component.ts :
[...]
onClickJSON() {
    let dialogConfig = new MatDialogConfig()
    dialogConfig.data = {
        json: this.item
    }
this.jsonDialog.open(JsonDialogComponent, dialogConfig)
[...]

dialog.ts :
[...]
export class JsonDialogComponent implements OnInit {

    json: string;

    constructor(private dialogRef: MatDialogRef<JsonDialogComponent>,
                @Inject(MAT_DIALOG_DATA) public data: any) {
    console.log(JSON.stringify(this.data['json'], null, 4)) //Good appearance
    this.json = JSON.stringify(this.data['json'], null, 4) //Bad appearance, like raw data
[...]

dialog.html :

    {{json}}

Answer: That's because you didn't use the correct tag.
Instead of using
, use either

{{ json }}

or

{{ json }}

More in depth, this is due to CSS styling, you can check the native styling of the pre tag and apply it to your p if you want. But semantically speaking, it's better to use
 than
 in that case.
Comment: No problem, if it resolved your issue be sure to mark it as such !
Comment: yeah... just in 5 min it will let me do so, you were so fast :D
BR
Comment: Thanks it works, I was not aware about the  tag


ReferenceError: jsPDF is not defined (with access to the package)

Question: I made a userscript for Google where I click "Do something", it prints out the webpage, in a PDF.
However, when I click on it, it gives an error: ReferenceError: jsPDF is not defined.
I have the jspdf file located with:
// Create the element
var script = document.createElement("script");

// Add script content
script.src = `https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js`;

// Append
document.head.appendChild(script);

Can you explain why it is raising this error?
Code:
// ==UserScript==
// @name         PDF Google
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.google.com/*
// @grant        none
// ==/UserScript==

window.addEventListener('load', function () {
    console.log('Running jsPDF')

    // Create the element
    var script = document.createElement("script");

    // Add script content
    script.src = `https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js`;

    // Append
    document.head.appendChild(script);

    var button = document.createElement("button");
    button.innerHTML = "Do Something";
    button.onclick = function () {

        var doc = new jsPDF();
        var specialElementHandlers = {
            '#editor': function (element, renderer) {
                return true;
            }
        };

        doc.fromHTML($('#content').html(), 15, 15, {
            'width': 170,
            'elementHandlers': specialElementHandlers
        });
        doc.save('sample-file.pdf');
    }

    var newLine = document.createElement("div");
    newLine.innerHTML = "
";

    var body = document.getElementsByClassName("FPdoLc tfB0Bf")[0];
    body.append(newLine);
    body.appendChild(button);

})

Answer: When you wrote:
script.src = `https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js`;

you are using the grave accent instead of proper quotes:
https://en.wikipedia.org/wiki/Grave_accent
Once you fixed that, see if there is still an error.


mocha testing nodejs mssql - connection is closed

Question: Trying to setup my tests for NodeJS with MsSql using Mocha. But every time I run my tests I get a "Connection is closed".

The weird thing is that it does work when I run the app in itself, then, I do get the data back from the database and the connection isn't closed too soon.
My code for the test:
var express = require('express');
var expect = require('chai').expect;
var calendar = require('./../Server/calendarDatabase');

describe("Calendar", function () {
    describe("Database", function () {
        it("should get stuff from the database", function (done) {
            calendar.getAll().then(function (returnValue) {
                console.dir(returnValue);
                expect(returnValue.count).to.equal(5);
                done();
            });
        });
    });
});

What my calendarDatabase code looks like
var express = require('express');
var sql = require('mssql');

var config = require('./../config');

var calendarDbConnection = {};

sql.connect(config.mssql, function (err) {
    console.log(err);
});

calendarDbConnection.getAll = function () {
    return new sql.Request()
        .query('select * from Human')
        .then(function (recordsets) {
        return recordsets;
    })
        .catch(function (err) {
        console.log(err.message);
    });
}

module.exports = calendarDbConnection;

And finally, this is what I use when running the app:
var express = require('express');
var router = express.Router();

var calendarDb = require('./../Server/calendarDatabase');

router.get("/", function (request, response) {
    response.render('calendar', { title: 'Calendar app title' });
});

router.get('/getYear/:year', function (request, response) {
    calendarDb.getAll().then(function(returnValue) {
        console.dir(returnValue);
    });
    response.send();
});

module.exports = router;

So my question, why does this not work while testing with Mocha but it does when running the app in itself? What am I missing here?
Answer: My connection seemed to be closed because of the framework not keeping it open.
Making my connection a promise worked.
describe("Calendar", function () {
    describe("Database", function () {
        it("should get stuff from the database", function (done) {
            calendar.Connect().then(function () {
                calendar.getAll().then(function (returnValue) {
                    console.dir(returnValue);
                    expect(returnValue.count).to.equal(5);
                }).done();
            });
        });
    });
});

Calendar db:
calendarDbConnection.Connect = function() {
    return sql.connect(config.mssql);
}

Answer: I fought with this for awhile, and was either breaking mocha testing, breaking my api functionality, or breaking pooling. Ended up using the following code using callbacks with successful pooling.
First I made a file in root called sql.js
var config = require('./config.js');
var sql = require('mssql');
var cp = new sql.ConnectionPool(config.sql);

const connect = function(callback) {

    if(cp.connected) {
        callback(cp);

        return true;

    }

    cp = new sql.ConnectionPool(config.sql, function() {
        callback(cp);

    });

}

module.exports = {
    connect

}

Then within any controller, I simply include the module sql and reference it like so
var sql = require('../../sql.js');

const someFunction = (callback) => {

    sql.connect(function(cp) {
        cp.request()
        .input('jti', jti)
        .input('reference', reference)
        .execute('insertToken', function (err, recordset) {
            callback(err, recordset);

        });

    })

}


React header component with slots

Question: I am working on a React app which has some nested react router switches and non trivial logic involving changing header content based on the currently displayed page.
I have previously seen two solutions for this problem:

A  that knows absolutely everything about every single possible route and the state of the app
Flat page layout: every page renders its own instance of

Both solutions suck donkey balls in my opinion. I think that the header must be fed shit and kept in the dark. All it has to do is to stay at the top of the page. Inspired by React Helmet I want to make a declarative solution to this problem.
Let's suppose that we have a header with three sections: left, right and center. At the root of our application we render something like
return (
    <HeaderLeft>
        <Logo />
    </HeaderLeft>
    ...
)

Which as expected display a logo.
Somewhere deeper in the hierarchy of the component tree we have a NestedPage that needs to change what is displayed in the left section of the header. So we simple do
return (
    <HeaderLeft>
        <SomethingElse />
    </HeaderLeft>
    ...
)

The trick is when we navigate away from the NestedPage we need to put back in the <HeaderLeft/> that which was there before we came to the NestedPage.
I came up with a somewhat +/- working solution involving react context and stack:
https://codesandbox.io/s/great-mendeleev-0b5y4?file=/src/MainPage.js
But this things relies heavily on the useEffects execution order.
The Question
Does anyone have an idiomatic solution/idea of a pattern/link to how to achieve the desired result.
Comment: will [this](https://codesandbox.io/s/runtime-water-nf8j9?fontsize=14&hidenavigation=1&theme=dark) work for you?
Comment: @Yousaf without going into details, no. Your solution is the contrary of what I am trying to achieve.
Answer: Having gone through React Helmet source code I ended up using this little jewel
It does exactly what I need: collects synchronously props from all instances in the render order.
Thus we can get the last children rendered:
function reducePropsToState(props) {
  return props[props.length - 1];
}

The tricky part was to let the Header component know what to render. Fortunately we are all software engineers and React runs on javascript.
I created a simple observable singleton:
class Observable {
  constructor() {
    this.value = null;
    this.subscribers = [];
    this.raf = null;
    this.notify = this.notify.bind(this);
  }

  subscribe(s) {
    this.subscribers.push(s);
    s(this.value);
  }

  setValue(c) {
    this.value = c || null;
    cancelAnimationFrame(this.raf);
    this.raf = requestAnimationFrame(this.notify);
  }

  notify() {
    this.subscribers.forEach((subscriber) => {
      subscriber(this.value);
    });
  }
}

In the header component we subscribe to this observable and update local state:
useLayoutEffect(() => {
    contentObservable.subscribe((v) => {
      setContent(v);
    });
  }, []);

Demo in codesandbox

React header component with slots


Find a 5-dimensional vector space over $\Bbb Z_5$ and determine its basis.

Question: Find a 5-dimensional vector space $V$ over $\Bbb Z_5$ and determine its basis.
Attempt:
I pick $V = P_4(\Bbb R)$, the set of all polynomials of degree less or equal than $4$ with the coefficients are in $\Bbb R$.
The basis is $B:=\{1,x,x^2,x^3,x^4\}$. Here's why $B$ be the basis.
Spanning: Since each polynomials $p \in P_4$ can be written as
$p = a_0+a_1x+a_2x^2+a_3x^3+a_4x^4$, which is a linear combination of $1,x,x^2,x^3,x^4$, then
$\text{span}(B) = V$.
Linearly independent: Denote $p_0=1,p_1=x,p_2=x^2,p_3=x^3, p_4 = x^4$. To show that the only coefficient satisfying the vector equation $a_0p_0+a_1p_1+a_2p_2+a_3p_3+a_4p_4 = 0 ... (0)$ are $a_i = 0$ for all $i\in \{0,1,2,3,4\}$. But, the equation (0) is equivalent to the statement that
$a_0+a_1x+a_2x^2+a_3x^3+a_4x^4 = 0 ... (1)$ for all $x \in (-\infty, \infty)$. So, we must show that this is true iff each coefficient in $(1)$ is zero. But, each coefficient in $(1)$ must be zero. Otherwise, the left side of the equation would be a nonzero polynomial with infinitely many roots. On the other hand, a nonzero polynomial of degree $n$ has at most $n$ distinct roots. Thus, the equation $(0)$ has only trivial solution.
Therefore, $B$ is a basis of $V$. In particular, $\dim(V) = 5$.
Am the above true ? What if I pick $V = P_4(\Bbb Z_5)$ ? Firstly, I pick it and know that the standard basis (as above) not form a basis, since $0=5=10$, etc, and hence it's not linearly independent.
Comment: The problem with the example you chose is that it's not clear what the vector space structure is. How are you proposing to use an element of $\mathbb{Z}_{5}$ to scale elements of $P_{4}(\mathbb{R})$? If you are proposing to just consider the elements of $\mathbb{Z}_{5}$ as the integers $0,...,4$ (which are not the same thing!), then are you sure that's a linear operation? For example, if you sum 5 copies of the same non-zero polynomial then you are multiplying by 5, which means the result is 0, which is not 5 times the polynomial - this does not satisfy the definition of "vector space".
Comment: What do you mean by "Find" a vector space? We can just declare a vector space. For example let $\{a,b,c,d,e\}$ be a basis and put $V = \{a\alpha_{1}+b\alpha_{2}+c\alpha_{3}+d\alpha_{4}+e\alpha_{5} \mid \alpha_{i} \in \mathbb{Z}_{5} \}$.
Comment: I pick a wrong V, and now I pick z5^5 as V, so closed for me
Answer: Any such will be isomorphic to $\Bbb F_{5^5}$.  You could take the quotient $\Bbb F_5[x]/p(x)$ where $p(x)$ is an irreducible fifth degree polynomial. Again a basis would be $\{1,x,x^2,x^3,x^4\}$.
Comment: This is confusing. We certainly **could** do this, but there is no need to consider quotienting out the ring of polynomials just to get a vector space, and certainly no reason to do so by an irreducible polynomial. I am also confused why we would consider a vector space as being isomorphic to a field; this field certainly **can** be considered as an $\mathbb{F}_{5}$-vector space, but I would never say that an arbitrary vector space was isomorphic to a field.
Comment: For example, $\mathbb{F}_{5}[x]/(x^5-1)$ is also a 5-dimensional vector space over $\mathbb{F}_{5}$, and is certainly not isomorphic to $\mathbb{F}_{5^{5}}$.
Comment: @MorganRodgers As a vector space over $\Bbb Z_5$, yes, it is isomorphic. As an algebra over $\Bbb Z_5$, it is not isomorphic.
Comment: Thanks @MorganRodgers  I was thinking vector space isomorphic, but am always at risk of overstepping my bounds.
Comment: @MorganRodgers But we don't care about the algebra structure. Vector space is all that matters here. So it turns out that they are all isomorphic to $\Bbb F_{25}$.
Comment: @Arthur It can be ambiguous to say they are isomorphic without qualification, especially if both structures **do** have a multiplicative operation, and while $\mathbb{F}_{p^n}$ can naturally be considered a vector space over any subfield, this notation **emphasizes** that it has more algebraic structure than a simple vector space; so my point is, it is strange to say such a vector space is isomorphic to $\mathbb{F}_{5^5}$ (and to emphasize a quotient ring construction) if we do not need to introduce a multiplication operation for any reason.


Overriden function getting hiden even after a dynamic cast (upcast)

Question: I started to learn about dynamic cast and how it uses the RTTI to determine the type of the object for a downcast.
In this example, I did an upcast, from a derived class to the base class.
<code>#include <iostream>

using namespace std;

class Base
{
public:
    virtual void foo()
    {
        cout<<"Base"<<endl;
    }
};

class Derived : public Base
{
public:
    void foo()
    {
        cout<<"Derived"<<endl;
    }
};

int main()
{
    Derived* d = new Derived();

    Base* b = dynamic_cast<Base*>(d);        //(1)

    cout<<typeid(b).name()<<endl;
    b->foo();

    return 0;

}
</code>
The program prints:
<code>PBase
Derived
</code>
For me:

In the compilation, the compiler creates a vTable for the base class, where we have a pointer to the RTTI "table", and a pointer to the Base::foo function.
In the execution time, when the program arrives to the line (1), He creates a _vptrBase pointer who points to this vTable.

My question is: how is comes that the program print "Derived" while we are calling the foo function? Why It doesn't call the Base::foo function?
Comment: `Base* b = dynamic_cast(d);` is equivalent to just `Base* b = d;`. This line doesn't touch vtable pointer inside of the class. It was pointing to the vtable for `Derived` when the object was created (because it's its type), and it continues to point to that vtable after the cast.
Comment: if you do want virtual, but need call `Base::foo`, then call it explicitly `b->Base::foo();`. see [live](http://coliru.stacked-crooked.com/a/f477ec9f5511fec3)
Comment: if you don't want that, then don't make `foo` virtual. see [live](http://coliru.stacked-crooked.com/a/5667cab411dfccc5)
Comment: This is what polymorphism is for. You can have pointer to base class and call methods defined for derived versions. Better example would have an array of Base pointers and multiple versions of  Derived classes.
Answer: Quoting cppreference (bold is mine):

Virtual functions are member functions whose behavior can be
overridden in derived classes. As opposed to non-virtual functions,
the overriding behavior is preserved even if there is no compile-time
information about the actual type of the class. That is to say, if a
derived class is handled using pointer or reference to the base class,
a call to an overridden virtual function would invoke the behavior
defined in the derived class. Such a function call is known as virtual
function call or virtual call.


Recurrence Relation with Alternating Variable

Question: I am trying to turn the recurrence relation into a linear equation in order to sum some probabilities. I've done this with some recursive stuff similar to the Fibonacci sequence, but I was told by a friend that this is much harder because I have an alternating variable.
$x_n=(1-x_{n-1})*(\frac{1}{36+12(-1)^{n}}),$
$x_1=\frac{1}{24}, x_2=\frac{23}{1152}, x_3$ should equal $\frac{1129}{27648}$
The recursive sequence works as intended, and I could definitely program it to approach the eventual number I want, but I'd rather get the proper linear one. I tried to apply the method some people on here explained to me for fibonacci-esque sequences, but I couldn't get it to work. Honestly I don't think I completely get what exactly is happening when I translate from one to the other, so that might be even more important than this specific equation. If I did not explain anything right please ask me, thank you.
Comment: Are you sure it is linear? I may be misunderstanding the question but the points $(1, \frac{1}{24})$, $(2, \frac{23}{1152})$, and $(3, \frac{1129}{27648})$ do not lie on the same line. $y-\frac{1}{24}=\frac{-25}{1152}(x-1)$ is the equation of the line that goes through the first two points, but not the third. I don't completely understand the situation, but maybe have an equation for odd values of $n$, and another for even values of $n$.
Comment: It is an inhomogeneous first-order linear recurrence relation with non-constant coefficients. You may solve it explicitly by following this answer of mine : https://math.stackexchange.com/questions/4610074/recurrence-relation-in-reduction-formula-for-integral-sinnx/4610252#4610252 (from the line "$c_n = \ldots$").
Comment: Yes this one I don't think is linear, I am trying to translate it from recursive to linear. So really another way I wrote it down is that the first part of the equation is $(1-x_1) * (1/24) or (1/48)$ and it alternates. The way I made it alternate is to have it be (36+-12). I see what you mean in terms of 2 separate equations, and I will definitely consider that.
Answer: Alternate terms of your sequence satisfy linear recurrences with constant coefficients:
\begin{align}
x_{2n+1}&=\frac{1}{24}\big(1-x_{2n}\big)\\
  &=\frac{1}{24}-\frac{1}{24\cdot48}\big(1-x_{2n-1}\big)\\
&=\frac{47}{1152}+\frac{x_{2(n-1)+1}}{1152}\ .
\end{align}
The solution of this recurrence is
\begin{align}
x_{2n+1}&=\frac{x_1}{1152^n}+47\left(\frac{1152^n-1}{1152^{n+1}-1152^n}\right)\\
&=\frac{1}{24\cdot1152^n}+\frac{47\big(1152^n-1\big)}{1151\cdot1152^n}\\
&=\frac{1128\cdot1152^n+23}{27624\cdot1152^n}\ ,
\end{align}
and the evenly indexed terms of the sequence are then given by
\begin{align}
x_{2n}&=1-24x_{2n+1}\\
&=\frac{23\big(1152^n-1\big)}{1151\cdot1152^n}\ .
\end{align}


Indices, Combining Sum and Product Notation

Question: I have a function
$$ f(x) = (x-a_1)(x-a_2) \cdot \cdot \cdot (x-a_n) $$
I want to express $f'$ with sigma notation. It is clear that $f'$ is the sum of $n$ terms, where each term is missing one $(x-a_i)$. So I want to sum over n terms, and for each term I want to multiply all but one $(x-a)$ in the original polynomial.
I think it is:
$$ f'(x) = \sum_{\substack{i = 1}}^n  \prod_{\substack{j \neq i}}^n  \;(x-a_j) $$
An alternative is
$$ f'(x) = \sum_{i = 1}^n \prod_{\substack{i = 1 \\j \neq i}}^n  \;(x-a_j) $$

Does this say what I want it to say?

Edit:
The correct notation is
$$ f'(x) = \sum_{\substack{i = 1}}^n  \prod_{\substack{j = 1 \\ j \neq i}}^n  \;(x-a_j) $$
Comment: Those aren't sigmas. Those are pis. Compare: $\Sigma$ vs. $\Pi$. That being said, the first is appropriate. Multiply over all $j \neq i$.
Answer: An elegant alternative is to index over a set. For $j \in \{1,\dots,n\}$, let $I_j := \{1,\dots,n\} \backslash\{j\}$.
Now, if
$$f(x) = \prod_{j=1}^n (x-a_j),$$
then
$$f'(x) = \sum_{j=1}^n \prod_{k \in I_j}(x-a_k).$$
Answer: Yes it says what you want it to say. For every $i,$ you're only multiplying the $(x-a_j)$'s that are not equal to $(x-a_i).$
Comment: Actually, I think it makes sense to have the product go from $j=1, j \neq i$ to $j=n$. ?
Comment: The first one is correct and very intuitive, but the second is incorrect. You're not adding anything in the second one; just multiplying.
Comment: Is one of the two options I have in my post better than the other?
Comment: No problem, I'll accept your answer as soon as it lets me. A small question, in the first notation, should it be a product only over $i \neq j$, or should I give it an upper limit of $n$? (I have the upper limit in the post, I'm not sure it makes sense though).


How to store different select value to the same variable

Question: Is it possible to store different select value to the same variable?
DECLARE @cout int

SELECT @cout= count(*) FROM Master1 WHERE (...)

SET @cout = SELECT count(*) FROM Master2 WHERE (...)

SET @cout = SELECT count(*) FROM Master3 WHERE (...)

IF(@cout = 0)
 BEGIN
 END

Answer: No, what you've got there will replace the value. You can append them as strings though, or add up the numbers. But it's bad practice; better to return a resultset, i.e:
SELECT
    (select count(*) FROM Master1 WHERE (...)) as 'Foo1',
    (SELECT count(*) FROM Master2 WHERE (...)) as 'Foo2',
    (select count(*) FROM Master3 WHERE (...)) as 'Foo3'

Comment: If any one of these statement returns 1 i have to stop the process
Pls. i want to know the better way
Comment: Then declare individual variables and check the result after each assignment, *then* return the bunch as a result set, as per above. Is that clear?
Comment: No, the only other way would be to append the items with some delimiter like ",", but this would be really bad practice. The best idea is to return the resultset.
Answer: How about:
IF EXISTS
(
SELECT 1 FROM Master1 WHERE (...)
UNION ALL
SELECT 1 FROM Master2 WHERE (...)
UNION ALL
SELECT 1 FROM Master3 WHERE (...)
)
BEGIN
...
END

It should do the trick, and pull out quickly enough...
Answer: You want to only run if none of these exist.
You could use the EXISTS keyword.
Something like this.
IF NOT EXISTS SELECT ID FROM Master1 WHERE (...)
  IF NOT EXISTS SELECT ID FROM Master2 WHERE (...)
    IF NOT EXISTS SELECT ID FROM Master3 WHERE (...)
    BEGIN
      ..do stuff...
    END

Note that I don't use count, if count is zero NOT EXISTS is true.  Select any column to get the query to run.
Can't test right now, the syntax might look like this:
IF NOT EXISTS (SELECT ID FROM Master1 WHERE (...))
  IF NOT EXISTS (SELECT ID FROM Master2 WHERE (...))
    IF NOT EXISTS (SELECT ID FROM Master3 WHERE (...))
    BEGIN
      ..do stuff...
    END


Como iniciar Accordion fechado

Question: Olá,
Tenho na minha página um accordion, está funcionando perfeitamente, porém, quando inicia a página ele ja vem aberto.
O que quero é que ele venha fechado, tem como?
HTML:

                TITULO 1

TEXTO 1

Texto 2

Leia mais

                Titulo 2

Texto 1

Texto 2

Leia mais

CSS:
/* ACCORDION */

.panel-group .panel {
    border-radius: 0;
    box-shadow: none;
    border-color: #EEEEEE;
}

.panel-default > .panel-heading {
    padding: 0;
    border-radius: 0;
    color: #212121;
    background-color: #FAFAFA;
    border-color: #EEEEEE;
}

.panel-title {
    font-size: 14px;
}

.panel-title > a {
    display: block;
    padding: 15px;
    text-decoration: none;
}

.more-less {
    float: right;
    color: #212121;
}

.panel-default > .panel-heading + .panel-collapse > .panel-body {
    border-top-color: #EEEEEE;
}

JS:
function toggleIcon(e) {
    $(e.target)
        .prev('.panel-heading')
        .find(".more-less")
        .toggleClass('glyphicon-plus glyphicon-minus');
}
$('.panel-group').on('hidden.bs.collapse', toggleIcon);
$('.panel-group').on('shown.bs.collapse', toggleIcon);

Desde ja agradeço!
Answer: Retira a classe in do HTML.
Vendo a documentação é claro que a classe in é usada para abrir a secção:

.collapse esconde o conteúdo
.collapsing aplicado durante a transição aberto/fechado
.collapse.in mostra o conteúdo

Exemplo:

function toggleIcon(e) {
  $(e.target)
    .prev('.panel-heading')
    .find(".more-less")
    .toggleClass('glyphicon-plus glyphicon-minus');
}
$('.panel-group').on('hidden.bs.collapse', toggleIcon);
$('.panel-group').on('shown.bs.collapse', toggleIcon);
.panel-group .panel {
  border-radius: 0;
  box-shadow: none;
  border-color: #EEEEEE;
}

.panel-default>.panel-heading {
  padding: 0;
  border-radius: 0;
  color: #212121;
  background-color: #FAFAFA;
  border-color: #EEEEEE;
}

.panel-title {
  font-size: 14px;
}

.panel-title>a {
  display: block;
  padding: 15px;
  text-decoration: none;
}

.more-less {
  float: right;
  color: #212121;
}

.panel-default>.panel-heading+.panel-collapse>.panel-body {
  border-top-color: #EEEEEE;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

          TITULO 1

TEXTO 1

Texto 2

Leia mais

          Titulo 2

Texto 1

Texto 2

Leia mais

Comment: Verdade... Era isso mesmo. Muito obrigado ^^
Answer: Tente remover a classe in do seguinte elemento

Comment: Era isso mesmo. Muito obrigado!

Como iniciar Accordion fechado


Querydsl - Sum with type Duration

Question: I have a Entity that have a Duration type field and I would like to sum this field with QueryDsl.
Is it possible? I was search on querydsl.com and dont find a solution.
The sum accepts only number, but my field is Duration type.
public static <E extends Number> AbstractGroupExpression<E,E> sum(Expression<E> expression)

Any sugestions, please?
Comment: Hi Diego! Please try to add a little more information into the question. What have you tried so far? Is there any elastic article you can refer to that might have a similar problem?
Answer: Even I was facing the same issue. I resolved it by using Expressions.numberPath() as below.
final NumberPath<Long> durationPathAsLongPath = Expressions.numberPath(Long.class, durationPath.getMetadata());

Then you can use sum() on the resulting NumberPath.

Querydsl - Sum with type Duration


Automating Alchemy pad segments in Logic Pro X

Question: How can one automate the movement of the performance pads in Logic Pro X's new Alchemy Synth?
Is there a way to record the movements and map that to automation for further tweaking?
I see the mappings there, but its not really logical in terms of defining a path.
Is it possible to add multiple layers of automation in Logic? E.g. One for the X direction, one for the Y.
Comment: just select 'touch' for your automation option in the channel strip and it records your real time manipulations of all that
Answer: In Alchemy 'Perform' section has 2 pads,

Transform Pads

XY Pads

Change the 'Automation Mode' from 'Read'(default) to 'Touch'

From 'Automation Parameter' dropdown, choose 'Alchemy > Perform > Transform Pad X'

Note that this will set 'Automation Parameter' to both Transform Pad X and Transform Pad Y

Now press 'R' and then click-hold the rectangular 'focus' on the Transform Pad and move it as you wish, the corresponding X-Y coordinates will be plotted as automation.

P.S : LPX 10.3.2


Error: ENOENT: no such file or directory, scandir '/Documents/android-sdk-linux/build-tools' at Error (native)

Question: I am new to Appium and I am running a selenium script with device connected and while running in terminal i am getting this error:
<code>"Error: ENOENT: no such file or directory, scandir '/Documents/android-sdk-linux/build-tools' at Error (native)"
</code>
I am running in Linux. Can you please help me out ?
Comment: Likely there is no build-tools folder at that location. Does it exist or not?
Answer: You need to paste this two lines in .bashrc file
export ANDROID_HOME=/home/rijomon/Documents/android-sdk-linux/sdk
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
then you will not get that error
Answer: This error is caused when Appium can not find a valid path to the Android SDK in the ANDROID_HOME environment variable
...or when the SDK installation is corrupt.
Rijo Mon's answer is correct for his system but the ANDROID_HOME path will need to be changed to point to the actual location of your installed SDK.

Install Android Studio if you aren't already using it.
Make sure only one version of Android SDK is installed in Android studio, and make sure Android Studio does not display any errors or warnings about the SDK installation.

Go to Android Studio Preferences  → Appearance and Behavior → System Settings → Android SDK
Uninstall all installed Android SDK versions here by unchecking
their boxes and clicking Apply
Uninstall any other copies of the Android SDK on your system
In Android Stduio, check only one SDK version and install it by clicking Apply.
Close and re-open Android Studio (you may want to reboot your machine)
Go back into the Android SDK window in Preferences → Appearance and Behavior → System Settings → Android SDK
Confirm that Android Studio does not display any warnings about the installed Android SDK.

Make sure the ANDROID_HOME environment variable is in your bash_profile and that it points to the location of your installed SDK.  For an SDK installation managed by Android Studio on OSX, this should be ~/Library/Android/sdk

The output of "ls -l ~/Library/Android/sdk" or the ls for your correct path to your SDK should now show a directory listing with the installed SDK files and folders including "build-tools" and "emulator"
Add the following line to ~/.bash_profile (OSX) or ~/.bashrc (Linux)

export ANDROID_HOME="${HOME}/Library/Android/sdk" (replace the path with your actual SDK path)

Restart your terminal or source the modified bash profile with "source ~/.bash_profile" or "source ~/.bashrc"


How to stop user from accessing the previous pages once he/she logs out

Question: the code here is using ASP.NET with C#. The issue  is that when user click logout button a user  can return back to previous page.
Logoin code
  protected void Page_Load(object sender, EventArgs e)
    {
        Session["email"] = txtemail.Text;
    }

    protected void btlogin_Click(object sender, EventArgs e)
    {

    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = "SELECT [email], [password] FROM [customer] WHERE [email]=@email AND [password]=@password";
    cmd.Parameters.Add("@email", SqlDbType.VarChar).Value = txtemail.Text;
    cmd.Parameters.Add("@password", SqlDbType.VarChar).Value = txtpassword.Text;

    conn.Open();
    SqlDataReader reader = cmd.ExecuteReader();

    if (reader.Read())
    {

        Response.Redirect("~/Booking.aspx");

        reader.Close();
        conn.Close();

    }
    else
    {

        lb.Text="Email or Password incorrect";

    }

}

}

logout code
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["email"] == null)
        {

            Response.Redirect("Default.aspx");

        }
    }

    protected void btlogout_Click(object sender, EventArgs e)
    {
        Session["email"] = null;

        Response.Redirect("Default.aspx");
    }

How to stop user from accessing the previous pages once he/she logs out
Answer: There are several ways
Clear Your Session using Session.Abandon and use Response.Redirect("~/LoginPage.aspx");
Then you can use Following Methods to Clear Cache or clear history
Using Codebehind
// Code disables caching by browser.
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();

Using JavaScript

with asp.net
without update panel
Page.ClientScript.RegisterStartupScript(this.GetType(),
Guid.NewGuid().ToString(),"ClearHistory();",true);

with update panel
ScriptManager.RegisterStartupScript(this,this.GetType(),
Guid.NewGuid().ToString(),"ClearHistory();",true);

Comment: where to locate code behind .. is it in page-load or in logout button  ?
Comment: @NewStar Yes on page Load


Prove: If $a^5|b^3$, then $a|b$ for integers $a, b$.

Question: I know that if $a^5|b^3$, then there exists some integer t such that $ta^5=b^3$. I also know that if I can show there exists some integer s such that $sa=b$, then $a|b$. I believe I should use prime factorization in some way. I can write $a^5 = (p_1^{r_1}p_2^{r_2}...p_n^{r_n})^5$ and $b^3=(p_1^{s_1}p_2^{s_2}...p_m^{s_m})^3$ if I allow some of the exponents to possibly b zero. Logically, I would think that some of the $p_i$ in the factorization of $a$ would be in the list of prime factors of b. However, I am not sure which direction I should go with this.
Comment: Click this... This seems similar. Didn't know how to use the link code. :( http://math.stackexchange.com/questions/1236862/prove-or-disprove-a3-mid-b2-rightarrow-a-mid-b?rq=1
Comment: @randomgirl `[text you want link to appear as](http://  ~~linkurl~~)`
Comment: The only thing I don't understand is why once I know that $p^r|b$ then why does a|b
Answer: Hint: If $a^5|b^3$, $a^3|b^3$.


exponential generating function - Fibonacci recurrence relation

Question: I am learning about exponential generating functions from some free tutorials and I recently learned how to use ordinary generating functions to solve the Fibonacci recurrence. I was wondering how can one solve the Fibonacci recurrence using exponential generating functions. I have not seen many examples of recurrences being solved using exponential generating functions so this will be very helpful to me.
Thank you.
Comment: see https://math.stackexchange.com/questions/1133712/what-is-the-need-of-exponential-generating-functions-on-combinatorial-problems?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
Comment: See Example 1 in Section 2.3 of generatingfunctionology: https://www.math.upenn.edu/~wilf/gfology2.pdf
Comment: I have not studied differential equations before so there is part in the example that I am not following. So the author just solves the diff eq and says to apply the operator $[x^n/n!]$. Is there an example w/o diferentialf equations @awkward
Comment: As far as I know, solving the Fibonacci recurrence with an exponential generating function inevitably involves a differential equation.
Answer: $F_n=\dfrac{1}{\sqrt{5}}\left[\phi^n+\left(1-\phi\right)^n\right]$, where $\phi=\dfrac{\sqrt{5}+1}{2}$ (golden ratio)
$\quad\sum_{n\ge0} F_n\dfrac{z^n}{n!} \\ =\dfrac{1}{\sqrt{5}}\sum_{n\ge0} \left[\phi^n+\left(1-\phi\right)^n\right]\dfrac{z^n}{n!}\\=\dfrac{1}{\sqrt{5}}\sum_{n\ge0}\left[\dfrac{\left(\phi z\right)^n}{n!}+\dfrac{\left(z-\phi z\right)^n}{n!}\right]\\=\dfrac{1}{\sqrt{5}}\left[e^{z\phi}+e^{z\left(1-\phi\right)}\right] $
Answer: Your recurrence is $F_{n + 2} = F_{n + 1} + F_n$ and $F_0 = 0, F_1 = 1$. Start by defining $f(z) = \sum_{n \ge 1} F_n \frac{z^n}{n!}$, multiply your recurrence by $z^n/n!$ and sum over $n \ge 0$, recognize some sums:
$\begin{align*}
\sum_{n \ge 0} F_{n + 2} \frac{z^n}{n!}
  &= \sum_{n \ge 0} F_{n + 1} \frac{z^n}{n!} + \sum_{n \ge 0} F_n \frac{z^n}{n!} \\
\frac{d^2}{d z^2} f(z)
  &= \frac{d}{d z} f(z) + f(z)
\end{align*}$
You get a differential equation, from the initial values you get that $f(0) = 0$, $f'(0) = 1$.


How to find the coefficient without a calculator?

Question: I wanted to solve this question without using a calculator.
Question: The number of non-negative integer solutions to
$$3x+y+z=24$$
By creating generating functions you have to find the coefficient of $x^{24}$ in the expression: $$\left(\frac{1}{1-x}\right)^{2}\left(\frac{1}{1-x^3}\right)$$
Using the theory I know about now, I would just split the problem into smaller parts adding all the combinations together while using the extended binomial theorem. But this takes a lot of time and I was wondering if there is a faster/easier way to find coefficients in terms of multiple generating functions by hand? If so, what are some recommended places to read about it?
Comment: Are you supposed to specifically use generating functions? There are other much more elementary ways of solving this problem.
Answer: Here's an alternative approach that uses stars and bars instead of generating functions.  Condition on the number of solutions with $x=k$, which reduces to the number of nonnegative integer solutions to $y+z=24-3k$:
\begin{align}
\sum_{k=0}^8 \binom{24-3k+2-1}{2-1}
&= \sum_{k=0}^8 (25-3k) \\
&= 9\cdot 25 - 3\sum_{k=0}^8 k \\
&= 9\cdot 25 - 3\cdot 9 \cdot \frac{0+8}{2} \\
&= 9(25 - 12) \\
&= 117
\end{align}
Answer: Pen, paper, and effort is what is required outside of a computer to calculate higher terms in expansions. In this case
\begin{align}
\frac{1}{(1-x)^2} &= \sum_{n=0}^{\infty} (n+1) \, x^n \\
\frac{1}{1-x^3} &= \sum_{n=0}^{\infty} x^{3 n}
\end{align}
for which the product of these series gives
$$ P = \frac{1}{(1-x)^2 (1-x^3)} = \sum_{r=0}^{\infty} (r+1) \, x^r \times \sum_{m=0}^{\infty} x^{3 m}. $$
Expanding to powers of $x^{24}$ gives
\begin{align}
P &= (1 + 2 x + 3 \, x^2 + \cdots + 25 \, x^{24})(1 + x^3 + \cdots + x^{24}) \\
&= \cdots + (1 + 4 + 7 + 10 + 13 + 16 + 19 + 22 + 25 ) \ x^{24} + \cdots \\
&= \cdots + 108 \, x^{23} + 117 \, x^{24} + 126 \, x^{25} +  \cdots.
\end{align}
The resulting value is then $[x^{24}] P = 117$.
Answer: As the number 24 is reasonably small a direct approach (also called brute force method) would work and be transparent.
As $3x$ is a multiple of 3, it can take any value from $\{0,3,6,9,\dots,24\}$. For each such value count how many (ordered) pairs of non-negative integers  $y,z$  give that sum.
The number of pairs of non-negative integers $y,z$ giving a  prescribed positive integer $n$ as sum is easily found to be $n+1$.
So the final answer is $(0+1) +(3+1) + (6+1)+(9+1) +\cdots (24+1)$ .
And this reduces to the well-known problem of  summing an arithmetic progression. Actually this shows one can find the answer even for big RHS value like 9630, not just small 24.


Cache Size Decorators in Python

Question: I am building my own decorator function, but I can't seem to be able to update the func.cache_length method of the function.
The code below simply uses an OrderedDict to store the items from all the dataframes loaded in pandas, with 5 dataframes maximum stored in cache.
I want the user to also find out how many items currently the function has loaded using cache_length but every time I run it I get 0.
from functools import wraps
from collections import OrderedDict

def cache(func, max_length=5):

    func.cache_dict = OrderedDict()
    func.cache_length = 0
    @wraps(func)

    def wrapper(*args, **kwargs):
        if kwargs['df_name'] in func.cache_dict:
            return func.cache_dict[kwargs['df_name']]
        elif len(func.cache_dict) < max_length:
            print('Running function...')
            df = func(*args, **kwargs)
            func.cache_dict[kwargs['df_name']] = df
            func.cache_length += 1
            return df
        else:
            func.cache_dict.popitem(last=True)
            df = func(*args, **kwargs)
            func.cache_dict[kwargs['df_name']] = df
            return df

    func.cache_reset = lambda: func.cache_dict.clear()

    return wrapper

import pandas as pd

@cache
def data_reader(*, df_name: pd.DataFrame, file: str):
    df = pd.read_csv(file)
    return df

This is the output vs. expected (I should get 1),

data_reader(df_name='test_dataframe', file="parsed_data.csv")

>>

Running function...
....

>>

data_reader.cache_length

>>

0

Comment: Not sure, maybe `functool.wraps` is adding it, I wouldn't expect it, but I'm any case, the reason you aren't seeing `1` is because **nowhere** do you update `wrapper.cach_length`, you could check `data_reader.__wrapped__.cache_length`  though
Comment: This doesn't make any sense to me, `data_reader.cache_length` should raise an attribute error since `data_reader` is the wrapper function you returned from your decorator.
Comment: there is no attribute error, check it.
Comment: Yes, as @juanpa.arrivillaga stated, you are checking the `cache_length` attribute of the `wrapper` object, not of the wrapped `func`. Regardless, this decorator seems relatively pointless, since it seems tailored to that specific function `data_reader` (the wrapper assumes a specific keyword argument). I would suggest either generalizing the decorator (if you want it to be reusable) or creating a class for your `data_reader` that has a `__call__` method and internally manages the cache on an instance level.
Comment: how would you generalize the decorator?
Answer: Based on what you described, here is a more general implementation: (details below)
from collections import OrderedDict
from functools import wraps

def cache(function=None, *, max_length=5):
    def decorator(func):
        cache_dict = OrderedDict()
        @wraps(func)
        def wrapper(*args, **kwargs):
            call_repr = f"args={args}, kwargs={kwargs}"
            try:
                return cache_dict[call_repr]
            except KeyError:
                pass
            if len(cache_dict) >= max_length:
                cache_dict.popitem(last=False)
            print(f"Running function {func.__name__}...")
            cache_dict[call_repr] = output = func(*args, **kwargs)
            return output
        wrapper.cache = cache_dict
        return wrapper
    return decorator if function is None else decorator(function)

@cache(max_length=3)
def add(x, y):
    return x + y

def main():
    print(f"{add(1, 1)=}")
    print(f"{add(2, 1)=}")
    print(f"{add(1, 1)=}")
    print(f"{add(3, 1)=}")
    print(f"{add(4, 1)=}")
    print(f"{add(1, 1)=}")
    print(f"{add.cache=}")
    add.cache.clear()
    print(f"{len(add.cache)=}")
    print(f"{add.cache=}")

if __name__ == "__main__":
    main()

Output:
Running function add...
add(1, 1)=2
Running function add...
add(2, 1)=3
add(1, 1)=2
Running function add...
add(3, 1)=4
Running function add...
add(4, 1)=5
Running function add...
add(1, 1)=2
add.cache=OrderedDict([('args=(3, 1), kwargs={}', 4), ('args=(4, 1), kwargs={}', 5), ('args=(1, 1), kwargs={}', 2)])
len(add.cache)=0
add.cache=OrderedDict()

Notice the cache was used for the second add(1, 1) call, but not the third.
Details

Uses the pattern allowing the decorator to be used with or without parantheses
Resulting wrapper function has the cache attribute to allow direct access to the underlying OrderedDict
Caching based on the string representation of all function arguments (positional and keyword)

Caveats

Not completely general by any stretch
Works as expected only with argument types that have a deterministic __repr__ without side effects (which is what one would expect, to be fair)
Cannot differentiate between arguments with identical string representations
Clean type annotations may be a bit more involved

Hope this helps.
Comment: can you explain why do we need the outer function "cache"? Can we just keep decorator and wrapper?
Comment: @matt.aurelio The outer function is needed, if you want the ability to use the decorator _with_ and _without_ parantheses (and arguments), i.e. you can decorate functions like this `@cache` and also like this `@cache(max_length=10)`. This is a relatively common pattern for decorators with additional parameters, when all of them are optional. Just a little extra syntax-sugar.

Cache Size Decorators in Python


Unable to display/hide label while a function executes

Question: My code is as :
main()
{
    label1.Visible=true;

    /* code that takes about 1-2 minutes to respond */

    label1.Visible=false;
}

Now i am unable to display & hide that label.
How do I display and hide the label?
Comment: If you want to change a labels state while code is executing then you should consider multithreading.
Comment: The underlying cause is explained [here](http://stackoverflow.com/a/952964/60761). The `await` answer below is a better solution.
Comment: I think you need to call `Invalidate` and then `Update`. See [Control.Invalidate Method](http://msdn.microsoft.com/en-us/library/598t492a%28v=vs.110%29.aspx).
Comment: Just put `this.Refresh();` after hide/shod instuction
Answer: It's because all work is done in one thread which is your UI thread. Try performing the hard work in another thread asynchronously:
async void YourMethod()
{
    label1.Visible=true;
    await Task.Run(() => /* do the work */);
    label1.Visible=false;
}

See Asynchronous Programming with Async and Await for more details.
Comment: Note that YourMethod should be an eventhandler (`async void YourMethod(object sender, SomeEventArgs e)`) or you'll only have shifted the problem elsewhere.


Modifing metadata from existing phAsset seems not working

Question: In my App I want to make it possible, that the user sets an StarRating from 0 to 5 for any Image he has in his PhotoLibrary. My research shows, that there are a couple of ways to get this done:
Save the exif metadata using the new PHPhotoLibrary
Swift: Custom camera save modified metadata with image
Writing a Photo with Metadata using Photokit
Most of these Answers were creating a new Photo. My snippet now looks like this:
let options = PHContentEditingInputRequestOptions()
options.isNetworkAccessAllowed = true

self.requestContentEditingInput(with: options, completionHandler: {
            (contentEditingInput, _) -> Void in

    if contentEditingInput != nil {

        if let url = contentEditingInput!.fullSizeImageURL {
            if let nsurl = url as? NSURL {
                if let imageSource = CGImageSourceCreateWithURL(nsurl, nil) {
                    var imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary?
                    if imageProperties != nil {
                        imageProperties![kCGImagePropertyIPTCStarRating] = rating as AnyObject

                        let imageData = NSMutableData(contentsOf: url)
                        let image = UIImage(contentsOfFile: url.path)

                        let destination = CGImageDestinationCreateWithData(imageData!, CGImageSourceGetType(imageSource)!, 1, nil)

                        CGImageDestinationAddImage(destination!, image!.cgImage!, imageProperties! as CFDictionary)

                        var contentEditingOutput : PHContentEditingOutput? = nil

                        if CGImageDestinationFinalize(destination!) {
                            let archievedData = NSKeyedArchiver.archivedData(withRootObject: rating)
                            let identifier = "com.example.starrating"
                            let adjustmentData = PHAdjustmentData(formatIdentifier: identifier, formatVersion: "1.0", data: archievedData)

                            contentEditingOutput = PHContentEditingOutput(contentEditingInput: contentEditingInput!)
                            contentEditingOutput!.adjustmentData = adjustmentData
                            if imageData!.write(to: contentEditingOutput!.renderedContentURL, atomically: true) {
                                PHPhotoLibrary.shared().performChanges({
                                    let request = PHAssetChangeRequest(for: self)
                                    request.contentEditingOutput = contentEditingOutput
                                }, completionHandler: {
                                    success, error in
                                    if success && error == nil {
                                        completion(true)
                                    } else {
                                        completion(false)
                                    }
                                })
                            }
                        } else {
                            completion(false)
                        }

                    }
                }
            }
        }
    }
})

Now when I want to read the metadata from the PHAsset I request the ContentEditingInput again and do the following:
if let url = contentEditingInput!.fullSizeImageURL {
    if let nsurl = url as? NSURL {
        if let imageSource = CGImageSourceCreateWithURL(nsurl, nil) {
            if let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary? {

                if let starRating = imageProperties[kCGImagePropertyIPTCStarRating] as? Int {
                    rating = starRating
                }
            }
        }
    }
}

But I never get my rating because it says that the value of imageProperties[kCGImagePropertyIPTCStarRating] is nil.
I also tried the examples from the Answers I posted above, but I always get the same result.
I hope anybody knows, what I can do to change the Metadata.
Also, how can I change the Metadata from an PHAsset with the MediaType .video? I tried to achieve that through the AVAssetWriter and AVExportSession Objects, but in both cases it does not work. Here what I tried for Videos:
var exportSession = AVAssetExportSession(asset: asset!, presetName: AVAssetExportPresetPassthrough)
exportSession!.outputURL = outputURL
exportSession!.outputFileType = AVFileTypeQuickTimeMovie
exportSession!.timeRange = CMTimeRange(start: start, duration: duration)

var modifiedMetadata = asset!.metadata

let metadataItem = AVMutableMetadataItem()
metadataItem.keySpace = AVMetadataKeySpaceQuickTimeMetadata
metadataItem.key = AVMetadataQuickTimeMetadataKeyRatingUser as NSCopying & NSObjectProtocol
metadataItem.value = rating as NSCopying & NSObjectProtocol

modifiedMetadata.append(metadataItem)

exportSession!.metadata = modifiedMetadata

exportSession!.exportAsynchronously(completionHandler: {
    let status = exportSession?.status
    let success = status == AVAssetExportSessionStatus.completed
    if success {
        do {
            let sourceURL = urlAsset.url
            let manager = FileManager.default
            _ = try manager.removeItem(at: sourceURL)
            _ = try manager.moveItem(at: outputURL, to: sourceURL)
        } catch {
            LogError("\(error)")
            completion(false)
        }
    } else {
        LogError("\(exportSession!.error!)")
        completion(false)
    }
})

Comment: for anyone else interested in that, I have an open TSI Ticket for that so probably Apple knows how to achieve that.
Comment: I opened a new question for the [Video Metadata](https://stackoverflow.com/questions/44824936/modifying-metadata-from-phasset-with-mediatype-video-fails)
Answer: Sorry this isn't a full answer but it covers one part of your question. I noticed you are placing the StarRating in the wrong place. You need to place it in a IPTC dictionary. Also the properties data is stored as strings. Given you have the imageProperties you can add the star rating as follows and read it back using the following two functions
func setIPTCStarRating(imageProperties : NSMutableDictionary, rating : Int) {
    if let iptc = imageProperties[kCGImagePropertyIPTCDictionary] as? NSMutableDictionary {
        iptc[kCGImagePropertyIPTCStarRating] = String(rating)
    } else {
        let iptc = NSMutableDictionary()
        iptc[kCGImagePropertyIPTCStarRating] = String(rating)
        imageProperties[kCGImagePropertyIPTCDictionary] = iptc
    }
}

func getIPTCStarRating(imageProperties : NSMutableDictionary) -> Int? {
    if let iptc = imageProperties[kCGImagePropertyIPTCDictionary] as? NSDictionary {
        if let starRating = iptc[kCGImagePropertyIPTCStarRating] as? String {
            return Int(starRating)
        }
    }
    return nil
}

As the imageProperties you get from the image are not mutable you need to create a mutable copy of these properties first before you can call the functions above. When you create your image to save use the mutable properties in your call to CGImageDestinationAddImage()
if let mutableProperties = imageProperties.mutableCopy() as? NSMutableDictionary {
    setIPTCStarRating(imageProperties:mutableProperties, rating:rating)
}

One other point you are creating an unnecessary UIImage. If you use CGImageDestinationAddImageFromSource() instead of CGImageDestinationAddImage() you can use the imageSource you created earlier instead of loading the image data into a UIImage.
Comment: I get  `*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'` at the line `imageProperties[kCGImagePropertyIPTCDictionary] = iptc`
Comment: Are you checking you can cast the imageProperties dictionary as a NSMutableDictionary?
Comment: yes, i get a NSMutableDictionary for the ImageProperties
Comment: I changed setIPTCStarRating() for the situation where there is already an IPTC dictionary. Do you want to try now?
Comment: i'm not quite sure, but it seems, that the `imageProperties[kCGImagePropertyIPTCDictionary]` is immutable. cause I still get the error.
Comment: Edited to include a mutable copy of properties before setting IPTC data
Comment: It worked now! I just did some small adjustments to your answer, as I am passing now an `NSNumber` to the Dictionary. So I can convert it directly to an Int when I want to get it from the Image. So thank you very much for that, You don't know what I need to change, to change the Metadata of a Video?
Comment: Sorry don't know anything about video metadata. I think you should break that out into another question.


How can I use the MySQL FIELD() function within a SelectQuery object in Views?

Question: I want to use the MySQL FIELD() function to alter a query so that it orders a particular field on a particular order of keys.
The keys for this 'select' field are: active, under_contract, sold
I want to sort the View so that all of my results are sorted first by node.created DESC (this is simple, of course) and then push all sold nodes to the very bottom of the result.
I tried doing this first in hook_views_post_execute():
function mymodule_views_post_execute(&$view) {
  if ($view->name == 'my_view') {
    usort($view->result, function($a, $b) {
      return ($a->field_field_status[0]['raw']['value'] == 'sold') ? 1 : -1;
    });
  }
}

but quickly discovered that, since my view only shows 25 results per page, this only pushes sold nodes to the bottom of each page.
Next, I tried to use hook_views_query_alter() to add the awesome MySQL FIELD() function that I just discovered – which works to achieve my goal perfectly in MySQL - but can't be added (at least as I'm discovering) to a SelectQuery object, which Views uses to run the query:
function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'my_view') {
    $query->orderby[0] = array(
      'field' => " FIELD(field_data_field_status.field_status_value, 'sold') ",
      'direction' => 'DESC',
  );
  }
}

How can I add a FIELD() orderby function to this query? Is there another method to push a particular filter value to the bottom of the result queue?
Comment: Thats not how you add an orderby to a SelectQuery built with db_select(). you use the `orderBy()` function I believe. See http://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db_select/7#comment-13489

Install the Devel module and dpm($query); in your hook_views_query_alter(), which should be MYMODULE_views_query_alter() ....
Comment: `$query->orderby` consists of arrays of `[field],[direction]`. See: http://api.drupal.org/api/drupal/includes%21database%21select.inc/function/SelectQuery%3A%3AorderBy/7. When Views formalizes the `$query` array it runs the `->orderBy()` method. Since `$query` in `hook_views_query_alter()` is simply an array and not yet an instantiation of a SelectQuery object, throwing ->orderBy() at it throws a fatal error, `Call to undefined method`.
Comment: For further explanation, see http://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7. At this stage, we don't treat this as a true SelectQuery object but an array that describes the query and contains all of the arguments that these methods need (such as `orderBy($field, $direction)`).
Answer: I got this working! I couldn't find any way to get the orderBy working in hook_views_query_alter(), so I tried to do this in the raw hook_query_alter(). In my particular situation, I couldn't get any result when I filtered against the table that Views had already joined with (I can't explain why) and so I added my own join. Voila, it works.
function mymodule_query_alter($query) {
  if ($query->hasTag('my_view_id')) {
    // Remove the current sort order.
    $order =& $query->getOrderBy();
    $order = array();

    // Join with the table that we need, giving it a custom alias.
    $query->join('field_data_field_listing_status', 'custom_status', 'custom_status.entity_id = node.nid');

    // Add our cool FIELD() function to push all 'sold' nodes to the very back of the list.
    $query->orderBy("FIELD(custom_status.field_listing_status_value, 'sold')", 'ASC');

    // Add any other ordering that we need...
    $query->orderBy('node_created', 'DESC');
  }
}

Answer: Building on the previous answer (thanks). I found a way to do it within the views API.
"5,2,1,4" is just a random order of ids, so you can replace this by whatever field and keys you wish.
function HOOK_views_post_build ($view) {
  if ($view->name == 'my_view' && $view->current_display == 'my_display') {
      $view->build_info['query']->orderBy("FIELD(id,5,2,1,4)", 'ASC');
    }
  }
}


mod_vhost_alias VirtualDocumentRoot many domains

Question: I'm sure I'm not the first person to encounter this problem, but I cannot, for the life of me, find an answer - although that could be down to not knowing what to search.
I have the need to host many client websites on an Ubuntu server. All is working well, but I want to set up dynamic virtual hosts, so that I can automate the process of creating a wordpress site on the server. I've got mod_vhost_alias module working, and am pleased with that, however, I have ran into an issue with .com domains vs .co.uk or .com.au domains and the VirtualDocumentRoot
For a domain such as example.com I want all requests to www.exapmple.com and example.com to point to a directory called something like /var/webroot/example.com and for domains such as example.co.uk, I would like all requests to www.example.co.uk and example.co.uk to point to a directory called /var/webroot/example.co.uk
The VDR I have at the moment looks like this...
VirtualDocumentRoot /var/webroot/%-2.0.%-1.0
Which grabs the second to last and last parts. This works great for example.com but for example.co.uk it is looking for a directory at /var/webroot/co.uk - which is not ideal!
Is there a way around this? Do I need to use mod_rewrite and if so, how?
Answer: This is a case where I'd just break out the symlinks instead of using a very specific (and potentially fragile) RewriteRule:
Use VirtualDocumentRoot /var/webroot/%0, then within /var/webroot/ create a symlink for www.example.com pointing to the real directory of example.com.  This will work with domains however deep you need, in addition to being a little more flexible if you have a site where www should have different content for some reason, or you want to point aaa.example.com to the same content as example.com.
If that's not to your liking, then you could indeed use mod_rewrite:
DocumentRoot /var/webroot
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$
RewriteRule ^/(.*)$ /%2/$1

That'll just always look for the domain name in /var/webroot, ripping the www off the front if it's there before looking.
Alternately, you could also redirect to remove (or add) the www to all requests instead of serving the same content for both domains.
Comment: I've gone with the rewrite option as this will work best for my requirements. Thanks for your help! :-)


Grafo caminhos possíveis python

Question: Eu tenho um dicionário, em que a chave é um vértice e o valor é uma lista de vértices adjacentes ao vértice (chave).
dic = {'A':['B,'C'],'B':['A','C','D'],'C':['A','B','D'],'D':['B','C']}

O que eu quero é uma matriz de todos os caminhos possíveis (de um vértice a outro, por exemplo de 'A' a 'D').
Já tentei tanta coisa, que não sei já mais o que tentar.
Eu pensei em percorrer cada lista de vértices adjacentes, começando pela chave 'A' (por causa do exemplo) e depois para cada vértice adjacente percorrer a sua lista de vértices adjacentes.
Tentei fazer isso, mas deu-me um erro, pelo que percebi não parava de percorrer.
def percorrer(v,vAux,dic):
  for e in dic.get(v):
    while e!=vAux:
        percorrer(e,vAux,dic)

def todosCaminhos(g,v1,v2):
   dicVertices = g.getVertices()
   for v in dicVertices:
       if v != v1:
           if v1 in dicVertices.get(v):
               dicVertices.get(v).remove(v1)
    matriz=[]
    lista=[]
    for v in dicVertices.get(v1):
        while v != v2:
            percorrer(v,v2,dicVertices)
            lista.append(v)
        matriz.append(lista)
    return matriz

Comment: Suponho que você quer gerar caminhos sem vértices repetidos (e.g. ['A', 'B', 'C', 'D'] seria legal mas ['A', 'B', 'C', 'B', 'D'] seria proibido)? Qual o número máximo de vértices desse grafo?
Comment: @ctgPi Sim, não é suposto haver vértices repetidos. Estou a criar esta função para ajudar noutra, e não faz sentido haver vértices repetidos. Este grafo pode ter n vértices, mas no exemplo que dei tem somente 4.
Comment: Tem como editar a pergunta e postar o código que você fez até agora (mesmo com esse problema de percorrer o grafo infinitamente)?
Comment: @ctgPi Editei, já pôs o código!
Answer: O problema da sua solução é que a função percorrer não tem acesso a lista, que é onde você guarda a informação sobre quais vértices você já visitou. Você tem que passar essa informação de alguma forma para a função que vai fazer a recursão. Eu juntei as funções, coloquei uns comentários e fiz um código mais idiomático:
# encoding: utf-8
# A linha anterior permite usar acentos no nosso programa.

def gerar_caminhos(grafo, caminho, final):
    """Enumera todos os caminhos no grafo `grafo` iniciados por `caminho` e que terminam no vértice `final`."""

    # Se o caminho de fato atingiu o vértice final, não há o que fazer.
    if caminho[-1] == final:
        yield caminho
        return

    # Procuramos todos os vértices para os quais podemos avançar…
    for vizinho in G[caminho[-1]]:
        # …mas não podemos visitar um vértice que já está no caminho.
        if vizinho in caminho:
            continue
        # Se você estiver usando python3, você pode substituir o for
        # pela linha "yield from gerar_caminhos(grafo, caminho + [vizinho], final)"
        for caminho_maior in gerar_caminhos(grafo, caminho + [vizinho], final):
            yield caminho_maior

# Exemplo de uso
G = {'A': ['B', 'C'], 'B': ['A', 'C', 'D'], 'C': ['A', 'B', 'D'], 'D': ['B', 'C']}
for caminho in gerar_caminhos(G, ['A'], 'D'):
    # "print(caminho)" em python3
    print caminho

(IDEOne)
Pra evitar a repetição, eu uso o operador in do Python, que verifica se um objeto pertence a uma lista (ou um conjunto, ou às chaves de um dicionário) — isso quer dizer que eu ignoro os vizinhos do vértice atual pelos quais eu já passei.
A outra coisa que eu faço é usar o yield na minha função — é mais fácil ilustrar o que ele faz com um exemplo mais simples:
def LOST():
    yield 4
    yield 8
    yield 15
    yield 16
    yield 23
    yield 42

for n in LOST():
    print n

O yield funciona como se fosse um return, mas pensado para ser usado em um for. O yield, ao contrário do return, não interrompe a execução da função: ele devolve o valor para o for, deixa o for fazer o serviço dele, e depois volta a executar a função de onde ele parou.
A ideia da chamada recursiva a gerar_caminhos(grafo, caminho + [vizinho], final) é que é permitido ir a vizinho partindo de caminho[-1] (o último elemento de caminho); eu procuro todos os caminhos que fazem isso, devolvo eles para a função-mãe (i.e. a função que me chamou), e repito isso para todos os vizinhos que já não estão no caminho (assim evitando a repetição).
Comment: Acho que percebi, por acaso já conhecia o yield, não costumo é usar, por não o conhecer bem.no python 3. Muito obrigada, deu-me uma grande ajuda!
Comment: uma curiosidade, basta fazermos: **#encoding utf-8** no início do código e podemos utilizar acentos no código todo?
Comment: Dado que essa pergunta ainda não está no pt.StackOverflow (que quase não tem Python), eu preferia que você a fizesse como uma pergunta top-level, pra ela não ficar perdida aqui nos comentários.
Comment: Não sei bem o que pergunta top-level significa, mas perguntei no "Faça uma pergunta", lá em cima.
Comment: Era isso mesmo. :)
Answer: Use o algorítmo de busca Depth Dirst Search:
dic = {'A':['B','C'],'B':['A','C','D'],'C':['A','B','D'],'D':['B','C']}

def dfs_caminhos(grafo, inicio, fim):
    pilha = [(inicio, [inicio])]
    while pilha:
        vertice, caminho = pilha.pop()
        for proximo in set(grafo[vertice]) - set(caminho):
            if proximo == fim:
                yield caminho + [proximo]
            else:
                pilha.append((proximo, caminho + [proximo]))

caminhos = list(dfs_caminhos(dic, 'A', 'D'))
print(caminhos)
>>> [['A', 'B', 'D'], ['A', 'B', 'C', 'D'], ['A', 'C', 'D'], ['A', 'C', 'B', 'D']]

Primeiro caminho mais curto:
min(caminhos, key = len)
>>> ['A', 'B', 'D']

Você também poderia utlizar Breadth-first search.

Grafo caminhos possíveis python


Can't mass-assign protected attributes: works_attributes, educations_attributes in rails nested model

Question: I am trying to save the model called applicant with nesting to work and education model. When saving the model, I am getting:

Can't mass-assign protected attributes: works_attributes, educations_attributes error.

I am also getting an error for an undefined method `klass' for nil:NilClass. I am using Rails 3.2.
My model code:
applicant.rb

class Applicant < ActiveRecord::Base
  attr_accessible :first_name, :last_name, :location, :email, :mob_no, :alternative_no, :linkedin, :facebook, :twitter, :message, :resume, :job_id
  has_many :works, :dependent => :destroy
  has_many :educations, :dependent => :destroy
  accepts_nested_attributes_for :works, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true

  accepts_nested_attributes_for :educations, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true

end

work.rb

class Work < ActiveRecord::Base
  attr_accessible :applicant_id, :company_name, :description, :end_month, :end_year, :start_month, :start_year, :title
  belongs_to :applicant
end

education.rb

class Education < ActiveRecord::Base
  attr_accessible :applicant_id, :end_month, :end_year, :institution_name, :major, :start_month, :start_year, :title
  belongs_to :applicant
end

Answer: Try including work and education attributes like this ..
class Applicant < ActiveRecord::Base
  attr_accessible :works_attributes, educations_attributes

Comment: its working, but the work model data is not saved to the data base
Comment: To save the work model data you have to pass the values in your applicant controllers create method
Comment: how i have to pass them...can you help me for that
Comment: i have also tried nested_form gem of rails, i am trying the same code as given on github page for nested_form gem. But in views , where i am using fields_for task, its giving me error :wrong number of arguments (4 for 3)
Extracted source (around line #56):

53:
54:
55:
56:             <%= f.fields_for :works do |task_form| %>
57:             <%= task_form.text_field :title %>
58:             <%= task_form.link_to_remove "Remove this task" %>
59:             <% end %>
Comment: my controller code : def newFillProfile
    if Job.find_by_id(params[:id]).nil?
      render_404
    else
     job = Job.find_by_job_url(params[:id])
    applicant = Applicant.new
     2.times { applicant.works.build }
     2.times { applicant.educations.build }
    end
  end

  def createProfile
     applicant = Applicant.new(params[:applicant])
    applicant.save
  end .............. i have removed @ from the instance vairables as this editor not allowing me to write it here


How to handle the dependent array in useEffect

Question: I am new to react and just learned how to use useEffect and useState/useReducer. Now I am facing a problem.
Assume I have a useEffect like below and states A,B,C,D:
React.useEffect(() => {
   D = fetchReq(A, B, C);
}, [A, B, C])

React.useEffect(() => {
   B = fetchReq(A)
}, [A])

React.useEffect(() => {
   C = fetchReq(B)
}, [B])

The problem is B also depends on A, so everytime A gets update, B needs to update by an async req accordingly i.e B = fetchReq(A). And C depends on B, C = fetchReq(B).
So once if A change, it may trigger incorrect behavior like fetchReq(A,B_old,C_old) or fetchReq(A,B,C_old), which is unwanted.
How should I fix this problem?
Comment: Do some validations before running the function, you can get previous values, check this post: https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state
Answer: I don't know why you would want to chain it like this as this is causing multiple re-renders for no real gain. You do not mention that B,C,D are being managed using useState. If this is purely a chain of requests that need to be performed on A updating, I would do something like this:
useEffect(() => {
    async (() => {
        const B = await fetchReq(A);
        const C = await fetchReq(B);
        const D = await fetchReq(A, B, C);
    })();
}, [A])

Comment: useEffect should be aware of all the values involved
Comment: Please elaborate on this
Comment: I think Simon means is that according to [link](https://reactjs.org/docs/hooks-reference.html#useeffect). **If you use this optimization, make sure the array includes all values from the component scope (such as props and state) that change over time and that are used by the effect.**
Comment: I recommend this [article](https://overreacted.io/a-complete-guide-to-useeffect/)
Answer: Is ABCD an object? If so, look for a more specific property value on that object to use inside of useEffect's trigger condition[]. By doing so, if the value does not change, even if useEffect runs through an dependent structure, there will be no circularity.
I am sure that the value of the variable required for fetch, does not keep changing every time when it is fetched again.
If that is the case, please write a more specific code example.
Answer: I would remove the dependency on A and B in your first effect.  C will only update if A is updated (and subsequently B).  So, you will not need to listen for changes to A and B, because their change will be a given.
Try that:
React.useEffect(() => {
   D = fetchReq(A, B, C);
}, [C])

React.useEffect(() => {
   B = fetchReq(A)
}, [A])

React.useEffect(() => {
   C = fetchReq(B)
}, [B])

Comment: useEffect should be aware of all the values involved


App Store publish app for iPad and update for iPhone later

Question: So i want to publish my app on the App Store but the app is only working on iPad's now. Can i upload the version 1.0 with the "Devices" option set on iPad and when i want to update the new version 1.1 with "Devices" set to Universal. Is that possible?
Comment: Yes that is perfectly fine.
Answer: Yes, it's possible. I see no reason why not.
Comment: Thanks sir , that was all i had to know.
Comment: You're welcome. The opposite situation when you reduce the list of available device types is dangerous: the app may be easily rejected by review team.


Quotient of group schemes and its rational points.

Question: At the moment I have some difficulties in understanding the quotient of group schemes and so exact sequences. I am aware that precise answers would be difficult to be given without speaking of sheaves over categories, that is why I am just looking for the idea behind. In particular I have the following questions.
If $k$ is a field, $F$ a field extending $k$, and
$$1\longrightarrow H\longrightarrow G\longrightarrow K\longrightarrow 1$$
is an exact sequence of group schemes over $k$. Is it true that then
$$1\longrightarrow H(F)\longrightarrow G(F)\longrightarrow K(F)\longrightarrow 1$$
is an exact sequence of groups?
What is the relation between $G/H$ and $K$?
And what can we say about $(G/H)(F)$, $G(F)$ and $H(F)$? I mean, is there something like $(G/H)(F)=G(F)/H(F)$ or $(G/H)(F)\simeq G(F)/H(F)$ holding?
Thank you.
Answer: The exactness of $1\to H\to G\to K$ means $H\to G$ induces an isomorphism from $H$ to the kernel of $G\to K$ which is the fibere product $G\times_K \{1_K\}$. The exactness of $G\to K\to 1$ means $G\to K$ is faithfully flat. This is equivalent to $G\to K$ is surjective when $G, K$ are smooth over $k$.
For any field extension $F/k$,
$$ 1\to H(F)\to G(F) \to K(F)$$
is exact because $(G\times_K \{1_K\})(F)=G(F)\times_{K(F)} \{ 1_K\}$ by the universal product of fiber product. This exactness can also be seen directly.
If moreover $F$ is algebraically closed, $G(F) \to K(F)\to 1$ is also exact at least if your group schemes are of finite type over $k$. This is because $G\to K$ is a surjective morphism.
However, for a general extension $F/k$, $G(F) \to K(F)\to 1$ is not exact in general. If $F$ is perfect, we can use Galois cohomology to bound the cokernel:
$$ 1\to H(F)\to G(F) \to K(F) \to H^1(F, H(F^{alg})). $$
To give an example example of non-exactness at right, fix an odd integer $n\ge 3$ and consider the Kummer exact sequence for the multiplicative group $\mathbb G_m$ over $k=\mathbb Q$:
$$ 1\to \mu_n \to \mathbb G_m \xrightarrow{()^n} \mathbb G_m \to 1 $$
where $\mu_n$ is the group of the $n$-th roots of unit and the second map is the power $n$ map. When you take rational points over $\mathbb Q$, you get
$$ 1\to 1 \to \mathbb Q^* \xrightarrow{()^n}  \mathbb Q^*$$
where the last map the power $n$ map. It is of course not surjective.
Finally, $G/H=K$ by definition, and $G(F)/H(F)$ is a subgroup of $K(F)$, not equal to $K(F)$ in general by the above example.


How to use if directive in apache2.4 to deny all excepts some routes

Question: I'm working in a configuration for an API rest, and I want to deny all the routes except the use by the API.
I'm trying to make this
Allow all the query_string with match with /rest or /rest/* in it.
Deny the rest of the routes.
<code><If "%{QUERY_STRING} =~ /rest/">
  Require all granted
</If>
<Else>
  Require all denied
</Else>
</code>
I only get denied for all the routes.
Comment: Your configuration looks correct. I suggest that you try turning on debug logging to figure out why your regexp doesn't match the query string. (You do this by changing the usual `LogLevel warn` to `LogLevel debug` in your main config file.)
Answer: You can to deny all in your main Directory, and allow all in the rest location.
Something like this:
<code> <Directory /path/to/your/docroot>
   Require all denied
   ...
 </Directory>
 ...
 <LocationMatch "^/rest">
   Require all granted
 </LocationMatch>
</code>
Comment: That would work if the question was about locations - but it's about the query string, i.e. the part that comes after a `?` in the URI.
Comment: The questions says "deny all excepts some routes". The sample code is trying to do this checking the query_param but IMHO is a wrong approach (probably because of a clean URL functionality). So, the proposed answer denies all routes but not the ones beginning with "/rest".