How to set non Drupal 404 and 403 pages for Drupal?

Question: Under Site Information we can provide custom 404 and 403 pages to Drupal, but these need to be created inside Drupal, and non Drupal pages are rejected. (such as myerror/404.html).
Contrib modules like custom error and static 404 also work inside Drupal. Any ideas on how to set an external page as 404 or 403?
Comment: Any particular reason for using HTML ? Cant you put the contents of that HTML in a node and use that node for 404 ?
Comment: The design of the html is somewhat complex and different to the site. Also, this is a multilingual site, so we would need to do this for every language. Also, Drupal is just a small part of the site at the moment :)
Answer: If you want to catch errors not handled by Drupal, you can do this using .htaccess:
ErrorDocument 403 /error403.html
ErrorDocument 404 /error404.html
ErrorDocument 500 /error500.html

However, if you want to intercept the errors handled by Drupal, and redirect that to an standalone error page, you should be able to do this with Redirect 404.
Comment: Note that Redirect 404 does NOT send actual 404 HTTP header. For SEO purposes it will not be a 404, but a massive case of duplicated content, if you will use it to redirect to static page. It may kill your site's position in search results.
Answer: When sending 404 or 403 header, Drupal cannot use redirect, as redirects are simply 3xx headers and you want 4xx. So, if it cannot redirect, it needs to pass the body of a file itself. But for security reasons it cannot access files outside it's own installation directory.
There are 3 solutions:

Use iframe, JavaScript, or other client-side technique to provide content from outside Drupal directory
Use webserwer's built in capabilities to substitute Drupal-generated response body with a content of outside file
Provide a filesystem links to files you need


android - geocoder.getfromlocationname returns Service Not Available

Question: I have this wierd bug on my phone (Not Emulator).
I wrote a code a button with edittext of navigating to the first result entered.
It worked for a few days and as I continued devlopibg it suddenly stopped working.
What is wierd is that I installed an earlier version and it didnt work.
The specific code part didnt change since!
Also, I installed the most updated version on a different phone and suddenly it didnt work on it either.
I dont know how to solve it and I dont understand why I get this error.
Why does it suddenly say Service Not Available if it worked before ?
This is the code:
<code>configure Search button//Button btn_search = (Button)findViewById(R.id.map_ ;(search_button if(!came_from.matches(" (("FollowLocation } ;(btn_search.setEnabled(false { btn_search.setOnClickListener( } ()new OnClickListener } (public void onClick(View v final AlertDialog.Builder ;(alert = new AlertDialog.Builder(context final EditText input = new ;(EditText(context input.setHint("Enter ;("Address input.setImeOptions( ;(EditorInfo.IME_ACTION_DONE ;(alert.setView(input alert.setPositiveButton("OK", } ()new DialogInterface.OnClickListener public void onClick(DialogInterface dialog, int } (whichButton String value = ;()input.getText().toString().trim } try Geocoder geocoder =

Geocoder(getApplicationContext(), ;(Locale.ENGLISH List<Address> results

;(geocoder.getFromLocationName(value, 1

} (if (results.size() == 0

AlertDialog.Builder builder2 = new ;(AlertDialog.Builder(context

builder2.setMessage("No Address Found, ("Please Try Again

(setCancelable(true.

setNegativeButton("OK", new. } ()DialogInterface.OnClickListener public } (void onClick(DialogInterface dialog, int id

;()dialog.cancel { ({ ;()show. { else } Address ;(address = results.get(0 GeoPoint p = (new GeoPoint((int address.getLatitude() * 1E6), (int)) ;(((address.getLongitude() * 1E6 gMapView = ;((MapView) findViewById(R.id.myGMap mc = ;()gMapView.getController

;(mc.setZoom(18

;(mc.animateTo(p

remove//previous overlays and put this location as circle

;()gMapView.getOverlays().clear Add a //

MyLocationOverlay circleOverlay = new ;()MyLocationOverlay

;circleOverlay.circle=true list = ;()gMapView.getOverlays

;(list.add(circleOverlay {

} (catch (Exception e {

AlertDialog.Builder builder2 = new ;(AlertDialog.Builder(context

builder2.setMessage("Error. Please check

(".internet connection

(setCancelable(true.

setNegativeButton("OK", new. } ()DialogInterface.OnClickListener public } (void onClick(DialogInterface dialog, int id

;()dialog.cancel { ({ ;()show. {

{ ;({ alert.setNegativeButton(" Cancel", new } ()DialogInterface.OnClickListener public void onClick(DialogInterface dialog, int } (whichButton ;()dialog.cancel { ;({ ;()alert.show { ;({
</code>
Comment: please paste your code in proper way.
Answer: The answer to my problem was restarting my phone.
Comment: as much as the answer seems lame, it is the answer none the less. I have ICS ph and JB xoom both throwing exception and restarting them both as answered works.
Comment: That's the eleventh commandment: Thou shalt not know what really happened.


Play 2.3.x libraryDependencies predefined Keys

Question: I am exploring Play framework and SBT and I have noticed tutorials often include a set static keys such as libraryDependencies ++= Seq(javaJdbc, javaEbean, cache, javaWs).
I understand they are connected to SBT-managed dependencies and I understand how can one add such a dependency by providing maven/ivy coordinates for a given dependency but these are something different.
I would like to know more about them and my guess/understanding is they represent modules of Play framework and also specify transitive dependencies needed for correct functioning of module. However, even though I have tried to find an exhaustive list of these modules with explanations and dependencies they include, so far I haven't been able to find anything conclusive in either Play/SBT documentation.
Is there such a list? How are these static keys referred to in Play lingo? What is this concept called in SBT?
EDIT: I have found they correspond to modules in com.typesafe.play however I haven't been able to find where is the list of libraryDependencies literals from above defined.
Comment: possible duplicate of [Where do the dependencies javaWs, javaJpa, etc. come from in Play/Java application?](http://stackoverflow.com/questions/25055469/where-do-the-dependencies-javaws-javajpa-etc-come-from-in-play-java-applicati)
Comment: Probably, but I believe the comments on the answer are valuable as well as they indicate precisely how the whole thing is working plus it points out the exact source class which holds these values. If we could somehow aggregate the two questions/answers?
Comment: See http://stackoverflow.com/a/25063872/1305344 where the exact source class is presented. What else is missing in the other answer (mine actually) that this has? I see no additional value.
Comment: Fair enough - I was referring to `Dependencies.scala`. In addition, I find my comment gives a short and concise overview how the whole thing is working, without delving into too much details. That is my personal opinion, though.
Answer: Play is actually an sbt auto-plugin. Auto-plugins allow you to define auto imports, which in turn is an object whose contents are put into scope (of your build.sbt) automatically. Play auto-imports its sub-modules and some other useful stuff.
You can find the full list in sbt-plugin/src/main/scala/PlayImport.scala.
Comment: Yes, exactly. You can check the file `Dependencies.scala` to see what deps each Play module has.
Comment: Thank you sir, again easy points for you but very valuable info for me :) Correct me if I am wrong(being relatively new to Scala), so we're referencing the exposed vals as elements in `libraryDependencies` which are just shorthands for defining the play module dependencies ourselves (through exact maven coordinates). The dependencies I see on the classpath of the project (e.g. Spring framework beans) are merely transitive dependencies of a particular Play module that has been added to the `libraryDependencies` sequence?


Google Cloud Messaging: Send UTF-8 data via JavaScript request

Question: I want to send a text with umlauts (äüöß) with GCM, but I always get the following exception when sending the request:
{"to":"/topics/mytopic","data":{"message":"ö;ä;1471125600000;1471211999999"}}

undefined:1
JSON_PARSING_ERROR: Unexpected token END OF FILE at position 106.
^
SyntaxError: Unexpected token J
  at Object.parse (native)
  at IncomingMessage.<anonymous> (c:\project\path\gcm.js:43:30)
  at IncomingMessage.emit (events.js:129:20)
  at _stream_readable.js:908:16
  at process._tickCallback (node.js:355:11)

When I send a text without umlauts, everxthing works fine and I get a result.
Here my JavaScript function:
exports.sendMessage = function (req, res) {

var topic = req.body.topic;
var message = req.body.message;

var data = JSON.stringify({
    "to": "/topics/" + topic,
    "data": {
        "message": message
    }
});

var options = {
    host: 'gcm-http.googleapis.com',
    path: '/gcm/send',
    method: 'POST',
    headers: {
        'Authorization': 'key=xxx',
        'Content-Type': 'application/json; charset=utf-8',
        'Content-Length': data.length
    }
};

var req2 = http.request(options, function(resp) {
    var msg = '';
    resp.setEncoding('utf-8');
    resp.on('data', function(chunk) {
        msg += chunk;
    });
    resp.on('end', function() {
        console.log(JSON.parse(msg));

        if(JSON.parse(msg).message_id) {
            res.send(200, {msg: "Message sent successfully! Message: " + JSON.parse(msg).message_id});
        } else {
            res.send(400, {msg: "Message sending failed! Message: " + JSON.stringify(msg)});
        }
    });
});

req2.write(data);
req2.end();

};
What am I doing wrong? Do I need to re-encode the message string before sending?
Answer: I finally got it after hours of searching - removing the Content-Length did the trick for me. So my request options now look the following:
var options = {
    host: 'gcm-http.googleapis.com',
    path: '/gcm/send',
    method: 'POST',
    headers: {
        'Authorization': 'key=xxx',
        'Content-Type': 'application/json; charset=utf-8'
        // NO CONTENT-LENGTH PARAMETER ANYMORE!!!
    }
};

Comment: Could someone give an explanation, why the request WITH "Content-Length" parameter works for non-umlaut containing texts, but doesn't for text with umlauts?


Routing error using Inerita and Laravel on Heroku

Question: My app works on local environment, but after I deployed it on Heroku I get the following error
Uncaught (in promise) TypeError: Cannot read properties of null (reading 'dataset')

and this is what is printed on the screen

when I open the site
I've tried moving the script tag from app.blade.php after the @inertia tag and to add defer to the script, however none of these methods worked.

    @inertia

    @env ('local')

    @endenv

Also I've tried following this article, but this didn't fixed it either.
I fell like I am missing something, any advice would be appreciated!
Comment: Hey Alex, the script should be loaded in the head. The @ tags should be replaced by php/blade/inertia and is not a javascript issue. Are all the composer dependencies installed on heroku?
Answer: stps to deoply laravel project on heroku server

download cli
https://devcenter.heroku.com/articles/heroku-cli#download-and-install

Prepare your Heroku CLI
Download and install Heroku installer base on your operating system.
heroku login

 Create Procfile inside your main Laravel project directory and push your project into Heroku and past the below code
 web: vendor/bin/heroku-php-apache2 public/

run the following git commands
git init
heroku create appname
git add .
git commit -m "Initial Commit"
git push heroku master
now try to open your laravel project you will find 500 error

Step 4 — Adding some configuration in Heroku base on .env file
read complete about them here
https://devcenter.heroku.com/articles/config-vars
you can check the image as well
https://miro.medium.com/max/700/1*1uv-JEb3CNByEwC68vWGtg.png

Step 5 — Database configuration
First, click "Resources" menu, then in the "Add-ons" side, click "Find more add-ons". You'll redirect into Heroku Add-ons page.In the Heroku Add-ons page, we click Heroku Postgres. and install it its complete free .

then  set database properties
check the link below
https://miro.medium.com/max/700/1*9jLE08DL6gHyYTP89MuZtg.png
https://miro.medium.com/max/700/1*eMqch3Bz2J6BLGhZ6Himmw.png
https://miro.medium.com/max/700/1*u7gxP2fMnm3yScq1D0qlNQ.png

to update your project
Ok, now we need to commit and push our config/database.php update into Heroku repository. Back into terminal and running this

git add .
git commit -m "Update database connection"
git push heroku master

Successful, now you are ready to running your Laravel App with Heroku. Hopefully this tutorial is useful and help you all guys :)

Thanks


Cross-validation of multiple subjects with multiple instances

Question: I have a training set of 50 subjects with about 550-600 measurements each. One measurement consists of 24 features and one class label (1 or 0). So my data looks like this (simplified):
<code>Subject  F1  F2  F3  ...  Class
1        1   3   2   ...  1
1        1   4   7   ...  0
...
2        2   3   2   ...  1
2        1   1   1   ...  1
...
</code>
I want to train my classification model (artificial neural network) with all measurements of all 50 subjects. Now I want to know if I can just use leave-one-out-cross-validation on the subject level (training with all measurements of all but one subject and then testing on the measurements of the remaining subject) or is validation on measurement level also needed (k-fold cross-validation within the measurements of each single subject)?
Answer: To answer this question, you should ask what you want your classifier to be able to do.
If I understand correctly, when you train your classifier on the 'measurement level' you would 'teach' the classifier to distinguish (classify) a set of features of a single subject. This is different from training it to classify any set of features independent of what subject it came from.
Assuming you want your classifier to be able to classify any set of features, independent of what subject those features came from, you should not do any cross-validation on the 'measurement level'.
In this same setting. I do not exactly understand why you would consider all the measurements of a single subject as 'one' (In the context of the leave-one-out cross-validation). Did you consider a single set of features (a single measurement), independent of what subject it came from, as being 'one' thing?
[EDIT]: I just discussed this problem with a colleague. Doing cross-validation on the entire dataset (independent of subject) will leak information.
If part of the measurements of a subject are included in the training set and if the other measurements of that same subject are in the testing set, this will overestimate the performance! Although, if you do not get any measurements from new subjects, this is not a problem.
In the case you do get measurements from new subjects (more likely, I think), then it is a good idea to include all the measurements of a subject in the testing set, if that subject was selected to be in that set.
Comment: I want a general classifier to classify any set of features, independent of it's subject. I considered all measurements of one subject as 'one', because the measurements are some what biased by their subject. When considering a single measurement as being 'one' thing, you mean that I should put all measurements together (not considering their subject at all)? So this way a simple k-fold cross-validation would do the job?
Comment: Cross-validation is a simulation in which you want to simulate a real world situation. So if you are interested in classifying a single measurement (independent of the subject) at the end, then the answer is yes.
Comment: [cont'd] yes, you can do a 'simple' k-fold cross-validation on the entire dataset (put all measurements together).

If you want the Neural Network to classify a single measurement of a distinct subject, then you can consider it as 50 separate (one for every subject) datasets, maybe, depending on what you want.
Comment: The classifier will almost exclusively classify measurements of new subjects. So following your EDIT, after all, you would suggest validation on subject level. Therefore leave-one-out cross-validation (on subject level) would be a good choice again, right? In fact the class distribution of my training measurements is almost equal among all 50 subjects. So this way I would get a leave-one-out cross-validation that is somewhat stratified.
Comment: Yes, then doing it on the subject level would be a better representation of the real world application. If you would not do it on subject level you will have a biased model and overestimate the generalisability.
Comment: Just a comment: I have similar situations regularly with repeated measurements of the same patient. When describing our cross validation setup I always emphasize , e.g.: because of the hierarchical data structure with multiple measurements per patient, cross validation is performed with patient-wise splitting. Other fields call these structures "clustered data".


Establish location-affinity between two users from their geotags?

Question: The Idea.
I would like to build a function like:
location_affinity(user_a, user_b)

which establish a location affinity between two users. In particular, this function will return a float number between 0 (no affinity) and 1 (max affinity) indicating how much places user_a has been correspond to places user_b has been. e.g.: If user_a ALWAYS stays with user_b and follows him to every places he go, I'm expecting a "1" as result. If user_a lives far away from user_b and they never got even close to each other, I'm expecting a "0" as result.
The Data.
Each user has a list of points(latitude, longitude) where he has been, and those points were already extracted from user's Facebook geotags.
To visualize this: IMAGE

Red "X"s are points(lat, lng) user_a has been.
Green "X"s are points(lat, lng) user_b has been.
Blue area represent the overlap.

The Question.
Are there any known algorithms which, based on two users' map points list, can establish the affinity (which I gather it depends on the overlap area)?
If not, which keywords should I search for?
Additional.
I'm trying to build Python functions with Spark. Are there any integrations?
Thank you.
Comment: How many points are there in each users point list?
Answer: How about something like this:
First we use scipy.spatial.distance.cdist to determine the distances between each point from user_a to each point from user_b to find the closest point for each. We then use the exponential function to exponentially suppress higher distances. The constant c determines how large this suppression is, smaller means large distances have a higher suppression (you will need to scale it to make sense in your actual units). Then we just look at the mean of that metric.
import numpy as np
from scipy.spatial.distance import cdist

def affinity(user_a, user_b, c=0.1):
    dists = cdist(user_a, user_b)
    return (np.exp(-dists.min(axis=0)/c)).mean()

This has the nice property that if the two sets of points are exactly equal, it returns 1.
user_a = np.random.rand(1000, 2)
user_b1 = np.random.rand(1000, 2)
user_b2 = user_a.copy()

print(affinity(user_a, user_b1))
# 0.85169834916
print(affinity(user_b1, user_a))
# 0.856871315902
print(affinity(user_a, user_b2))
# 1.0

It has a small problem, though, as you can see above. This function is not symmetric. However, we can make it symmetric by considering both equally:
def affinity(user_a, user_b, c=0.1):
    dists = cdist(user_a, user_b)
    min_dists = dists.min(axis=0), dists.min(axis=1)
    return np.concatenate([np.exp(-x/c) for x in min_dists]).mean()

print(affinity(user_a, user_b1, 0.01))
# 0.271448093071
print(affinity(user_b1, user_a, 0.01))
# 0.271448093071
print(affinity(user_a, user_b2, 0.01))
# 1.0

Of course you can use many different metrics to determine the fall-off of larger distances. Here I chose exp(-x), but you could also use 1 - tanh(x) or tanh(1/(x+epsilon)) (the epsilon is needed to avoid a divison by zero in case two points are exactly identical). This results in different behaviour:

Actually, you could use 1 - any function defined in this post.


Find a shortest distance from point to $\operatorname{span} U$

Question: Let U = $\operatorname{span}\{(1,0,0,-1),(0,1,-1,0)\}$. Find the shortest distance from $(2,0,2,0)$ to $U$.
This problem is in my textbook, and seem very easy, but I cannot imagine how can we find the distance from the point to the $span U$. Because $span U$ is not like a plane, a line... in geometry (in my thinking).
Thanks :)
Answer: The elements of U are in the form $(a,b,-b,-a)$. The distance from $(a,b,-b,-a)$ to $(2,0,2,0)$ is $(a-2)^2+b^2+(-b-2)^2+a^2$ Now minimize the last expression by minimizing $(a-2)^2+a^2$ and minimizing $(-b-2)^2+b^2$


Load disabled items in a menu

Question: I load my main menu programmatically with the following code :
    $menuTree = \Drupal::menuTree();
    $menuTreeParameters = $menuTree->getCurrentRouteMenuTreeParameters($name);
    $menuTreeParameters
        ->setMinDepth($minLevel)
        ->setMaxDepth($maxLevel);

    $tree = $menuTree->load($name, $menuTreeParameters);
    $tree = $menuTree->transform($tree, $this->getDefaultManipulators());

    return render($menuTree->build($tree));

I would like to get all my menu items, included thoses which are disabled. When I inspect $tree variable, I have all my menu items.
I don't know why but after the call to the build method, I get only my enabled items.
Answer: Check this line in buildItems() which is called by $menuTree->build($tree), in \Drupal\Core\Menu\MenuLinkTree.php:
  // Generally we only deal with visible links, but just in case.
  if (!$link->isEnabled()) {
    continue;
  }

It's designed to exclude links that are not enabled. I played around with something like this to get them all showing:
foreach ($tree as $id => $treeItem) {
    // Get the link definition.
    $definition = $tree[$id]->link->getPluginDefinition();

    // Skip links that are already enabled.
    if ($definition['enabled'] == 1) {
        continue;
    }

    // Change definition and enable link.
    $definition['enabled'] = 1;

    // Recreate the link.
    // I'm not 100% sure about the correctness of this part.
    // This is my first time playing with this stuff. Hopefully someone can fill in this blank.
    $pluginContainer = \Drupal::getContainer();
    $conf = [];
    $newLink = \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent::create($pluginContainer, $conf, $id, $definition);
    $tree[$id]->link = $newLink;
}

Load disabled items in a menu


Como posso saber quais os objetos do ArrayList estão sendo modificados ou excluídos?

Question: Possuo um ArrayList que esta pré-carregado com alguns objetos do tipo da minha classe Pessoa, veja:
ArrayList<Pessoa> listaDePessoas = new ArrayList<>();
listaDePessoas.add(new Pessoa("Joao", 29));
listaDePessoas.add(new Pessoa("Ana", 21));
listaDePessoas.add(new Pessoa("Maria", 25));

Vamos supor que em um dado momento eu altero um desses objetos contido no ArrayList listaDePessoas veja:
listaDePessoas.get(0).setNome("Jao carlos");

E depois em um outro momento eu removo um desses objetos contido no ArrayList listaDePessoas veja abaixo:
listaDePessoas.remove(listaDePessoas.get(2));

Removi o objeto que esta na terceira posição da lista.
Estrutura da classe Pessoa:
public class Pessoa {
    private String nome;
    public String getNome() { return nome; }
    public void setNome(String nome) { this.nome = nome; }
    private int idade;
    public int getIdade() { return idade; }
    public void setIdade(int idade) { this.idade = idade; }

    public Pessoa(String nome, int idade) {
        this.nome = nome;
        this.idade = idade;
    }

    public Pessoa() { }
}

Pergunta
Sendo assim, eu gostaria de saber como eu poderia saber quais objetos estão sendo modificados e quais estão sendo removidos da lista? Para que futuramente as modificações aplicadas nesses objetos (alteração e exclusão) sejam aplicadas em outro lugar.
Comment: Não seria um caso de implementação do padrão observer, pra monitorar alterações?
Comment: Não sei se entendi que informação deseja obter da API.
Comment: Checar os modificados eu não faço ideia, mas os excluidos, me parece que o proprio ArrayList reordena o indice quando um item é removido. Veja a descrição do método [`remove()`](http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#remove%28int%29): *Shifts any subsequent elements to the left (**subtracts one from their indices**).*
Comment: @diegofm não sabia que o método `remove(int index)` me retorna o elemento removido porem o método `remove(Object o)` retorna true se o elemento removido que foi especificado existir na lista.
Comment: @bigown preciso obter (uma copia dos objetos) os objetos que estão sendo removidos e alterados na lista.
Comment: Assim de repente a única possibilidade que eu encontro é ter uma classe que manipule o array e a criação/alteração dos objectos Pessoa. Tanto o array como os objectos serão privados dessa classe.
Comment: @DenerCarvalho dá para postar a classe `Pessoa`? Posso estar enganado na sua necessidade, mas não parece ser o caso do `Observer`, pelo menos não com o que está na pergunta. Você precisa que outro objeto precise ser notificado que algo foi alterado nesse?
Comment: `Para que futuramente as modificações aplicadas nesses objetos (alteração e exclusão) sejam aplicadas em outro lugar.` Qual lugar? Pode dar detalhes?
Comment: @bigown vou editar aqui e colocar a classe `Pessoa`
Comment: @BrunoCosta as modificações serão aplicadas em um arquivo XML que contem vários objetos do tipo Pessoa.
Comment: @bigown sim preciso ser notificado, para aplicar as modificações em outro lugar.
Comment: @DenerCarvalho a pergunta ficou um bocadinho ampla :) Não que eu ache que precisa ser fechada. Você pode mudar essa classe `Pessoa`? Poderia implementar a interface `Clonable`?
Comment: @bigown se as mudanças ñ afetar muito a estrutura da classe ela ser mudada sim. A interface `Clonable` solucionaria? Eu até pensei em adicionar os objetos que estão sendo excluidos e alterados em outra lista `listaPessoasExcluidas` e `listaPessoasAlteradas` mas não sei se isso seria ideal :P
Comment: A `Clonable` é um dos passos, dá para fazer sem, mas complica bastante o uso. Como precisa ser observável, terá que por outras coisas de qualquer jeito, vai ficar "complicado", não tem jeito. Mas aí é que tá, sem saber o que precisa qualquer solução é errada, se vai criar uma lista, se vai notificar outra classe, se vai só retornar o objeto, tudo isso pede soluções diferentes. Um [mcve] em algo tão amplo e até não claro ajudaria muito. Está faltando requisitos certos para responder. Não fecho porque sei que você vai arrumar :)
Comment: @bigown eu poderia adicionar todo o contexto, porem isso ia fazer com que a pergunta ficasse ampla de mais e também muito difícil de testar o exemplo. Vou dar uma pesquisada na interface `Clonable` e ver o q eu encontro. Não tem problema nenhum a pergunta ser fechada, se a comunidade achar q ela deve ser fechada eu também votarei para fecha-la ;)
Answer: Resposta simplista
Não dá para fazer isto em Java.
Resposta impraticável
Você poderia instrumentalizar as classes do Java de modo a interceptar os acessos e alterações realizadas nos objetos.
Resposta razoável
Implemente um padrão de acesso aos objetos que permita reproduzir as ações realizadas.
Isso me lembra o padrão arquitetural Event Sourcing, onde as operações realizadas sobre os dados são armazenados como eventos, sendo possível então reproduzir, desfazer e navegar pelo histórico de eventos do sistema.
Toda alteração nos dados deve ser feita por uma classe que gerencia os dados e será representada por um objeto que contém os dados do evento.
Exemplo
Fiz uma implementação simples baseado no código da pergunta:
Classe Pessoa
Alterei para ser imutável, pois é uma boa prática.
public class Pessoa {
    private final String nome;
    private final int idade;

    public Pessoa(String nome, int idade) {
        this.nome = nome;
        this.idade = idade;
    }

    public String getNome() { return nome; }
    public int getIdade() { return idade; }

    @Override
    public String toString() { return nome + " / " + idade; }
}

Interface dos eventos
interface Event {
    void apply(List<Pessoa> lista);
}

Evento para adicionar uma pessoa
public class AddPessoaEvent implements Event {
    private final Pessoa p;

    public AddPessoaEvent(Pessoa p) {
        this.p = p;
    }

    @Override
    public void apply(List<Pessoa> lista) {
        System.out.println("* Adicionando " + p);
        lista.add(p);
    }

    @Override
    public String toString() { return "Add " + p.getNome(); }
}

Evento apra remover uma pessoa
public class RemovePessoaEvent implements Event {
    private final int index;

    public RemovePessoaEvent(int index) {
        this.index = index;
    }

    @Override
    public void apply(List<Pessoa> lista) {
        System.out.println("* Removendo " + index);
        lista.remove(index);
    }

    @Override
    public String toString() { return "Remove " + index; }
}

Evento para atualizar o nome de uma pessoa
public class AtualizaNomePessoaEvent implements Event {
    private final int index;
    private final String nome;

    AtualizaNomePessoaEvent(int index, String nome) {
        this.index = index;
        this.nome = nome;
    }

    @Override
    public void apply(List<Pessoa> lista) {
        System.out.println("* Atualizando " + index + " com nome " + nome);
        lista.set(index, new Pessoa(nome, lista.get(index).idade));
    }

    @Override
    public String toString() {
        return "Atualiza " + index + " com nome " + nome;
    }
}

Classe gerenciadora da lista de pessoas
public class PessoasManager {
    private final List<Pessoa> listaDePessoas = new ArrayList<>();
    private final List<Event> eventos = new ArrayList<>();

    public void add(Pessoa p) {
        AddPessoaEvent e = new AddPessoaEvent(p);
        eventos.add(e);
        e.apply(listaDePessoas);
    }

    public void remove(int index) {
        RemovePessoaEvent e = new RemovePessoaEvent(index);
        eventos.add(e);
        e.apply(listaDePessoas);
    }

    public void atualizaNome(int index, String nome) {
        AtualizaNomePessoaEvent e = new AtualizaNomePessoaEvent(index, nome);
        eventos.add(e);
        e.apply(listaDePessoas);
    }

    public List<Pessoa> getListaDePessoas() { return listaDePessoas; }
    public List<Event> getEventos() { return eventos; }

    public void replay(List<Event> eventos) {
        for (Event e : eventos) {
            this.eventos.add(e);
            e.apply(listaDePessoas);
        }
    }
}

Usando as classes
O código principal para realizar as operações mencionadas na pergunta seria o seguinte:
PessoasManager pm = new PessoasManager();
pm.add(new Pessoa("Joao", 29));
pm.add(new Pessoa("Ana", 21));
pm.add(new Pessoa("Maria", 25));
pm.atualizaNome(0, "Jao Carlos");
pm.remove(2);

Cada método do gerenciador de pessoas cria o respectivo evento e o aplica na lista de pessoas. Como cada método apply tem um println, isto iria imprimir no console:

Adicionando Joao / 29

Adicionando Ana / 21

Adicionando Maria / 25

Atualizando 0 com nome Jao Carlos

Removendo 2

Imprimindo as listas de pessoas e eventos:
System.out.println("Pessoas " + pm.getListaDePessoas());
System.out.println("Eventos " + pm.getEventos());

Temos o resultado:

Pessoas [Jao Carlos / 29, Ana / 21]
Eventos [Add Joao, Add Ana, Add Maria, Atualiza 0 com nome Jao Carlos, Remove 2]

Então, como temos os eventos, podemos aplicá-los novamente em outra lista, criando outro gerenciador de pessoas e usando o método replay:
PessoasManager pm2 = new PessoasManager();
pm2.replay(pm.getEventos());

A segunda linha acima irá produzir a mesma exata saída no console referente, já que os mesmos eventos serão aplicados novamente. E se imprimir a nova lista de pessoas ela também vai ser a mesma que a anterior.
Algo interessante neste padrão, é que você poderia replicar os eventos em outra estrutura de dados criando outro método análogo ao apply. Ao invés de uma lista, poderia ser uma conexão com o banco, por exemplo.
Desvantagens
O padrão, tal qual aplicado acima, pode gerar eventos desnecessários. Imagine um nome de uma pessoa atualizado diversas vezes.
Portanto, se o histórico não é importante para você, outra alternativa seria armazenar a lista inicial, criar uma cópia dela, aplicar as alterações e no final gerar um diff, ou seja, uma lista de diferenças entre o estado inicial e o final, de modo a executar o número mínimo de operações possível quando for aplicá-las em sua outra fonte de dados.
Outra alternativa mais simples, quando a lista é pequena e não há  dependências, é simplesmente não tentar replicar o processo, mas substituir os dados de destino pelos novos dados. Por exemplo, eu trabalhei num sistema, há alguns anos, onde o usuário podia editar uma tabela. Atualizar cada campo e registro no banco de acordo com a linha e coluna da tela era complicado, principalmente porque o usuário poderia incluir e excluir linhas e colunas arbitrariamente. Nesta situação específica, decidimos que a solução mais viável no momento era simplesmente apagar os registros existentes e recriá-los todos a partir dos novos valores.
Answer: Já que você sabe qual é o objeto que deseja basta fazer uma cópia dele antes de fazer alguma operação. É uma técnica básica, não existe "mágica".
Alteração
Pessoa pessoaAlterada = listaDePessoas.get(0).clone();
listaDePessoas.get(0).setNome("Jao carlos");

Não fiz uma cópia simples. Como o tipo é por referência a cópia seria da referência, portanto pessoaAlterada apontaria para o mesmo local da memória onde está objeto apontando o elemento na lista, então a alteração seria vista nessa cópia. A solução foi clonar o objeto. Por isso tive que implementar a interface Cloneable na classe. Até tem como fazer na mão, mas não é o ideal.
Com a clonagem a cópia apontará para um novo objeto com os mesmos dados do que será alterado em seguida. Por ser um objeto independente a alteração do objeto referenciado na lista não afetará o objeto clonado.
Só é importante entender que essa é uma clonagem rasa, então todos os bits do objeto serão copiados, inclusive as referências contidas nesses objeto. Concluímos que o objeto novo apontará para os mesmos objetos que o compõe que o objeto original está apontando. Se o objeto original mudar esses objetos de composição, o objeto clonado verá as alterações. Para evitar isso precisaria de uma clonagem profunda que clona toda a árvore de objetos, tornando tudo independente. Precisa ver se é o que deseja.
Se quer a clonagem profunda, ou o tipo de dado (Pessoa) deve ter um método  clone() que faça isso por você, ou terá que criar um algoritmo no código para fazer toda clonagem de toda a árvore na mão. Não fiz até porque não parece ser necessário nesse caso, mas poderia ser se colocar atributos novos. Mesmo a String que é um tipo por referência tem semântica de tipo por valor e é imutável, então não tem esse problema, uma alteração criaria um novo objeto.
Isso tipo de cópia é perigosa se não souber o que está fazendo.
Falo sobre cópia rasa e cópia profunda em Cópia de classe em C#. É muito parecido com o Java.
Remoção
Pessoa pessoaRemovida = listaDePessoas.remove(2);

Perceba que não precisa pegar o objeto se já sabe o índice. E essa sobrecarga do método retorna o próprio objeto (a referência), então nem precisa fazer uma cópia anterior.
Para remover não precisa fazer cópia alguma do objeto em si, afinal você removeu ele da lista, então ele não será mais acessível na lista, então pode usar ele mesmo. Claro que se tiver algum outro motivo para clonar o objeto pode fazer também, igual ao exemplo anterior.
Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Notificação
Não está claro ainda se precisa ou não da notificação, é possível fazer isso na classe, mas precisaria ver como será consumido isso. Tem algumas perguntas sobre o assunto:

Como funciona e como implementar o Design Pattern Observer?
Design pattern Observer aplicado em eventos
Listeners são uma implementação de Observer?
Observer pode ser considerado quebra de encapsulamento?

A ideia básica é colocar em Pessoa um array:
private List<Observer> observers = new ArrayList<Observer>();

Uma forma de assinar:
public void subscribe(Observer observer) {
    observers.add(observer);
}

Os notificador:
public void notifyAllObservers() {
    for (Observer observer : observers) {
        observer.update(this);
    }
}

Quando a propriedade for modificada precisa disparar a notificação:
public void setNome(String nome) {
    this.nome = nome;
    notifyAllObservers();
}

A interface Observer seria algo assim:
public interface ObserverPessoa {
    public void update(Pessoa pessoa);
}

E os consumidores seria algo assim:
public class Consumidor extends Observer {
    @Override
    public void update(Pessoa pessoa) {
        //faz o que quiser aqui
    }
}

Coloquei no GitHub para referência futura.
É uma ideia, tem várias outras de fazer. Essa eu fiz sem pensar muito, sem conhecer o caso real. Ela tem vantagens e desvantagens. Só postei para dar uma ideia, não quer dizer que eu faria isso.
Se precisa da notificação na lista precisa ver onde está a lista e montar algo semelhante ao acima nessa classe. Pode ter notificações gerais ou especializadas.


Timezone handling of python datetime objects

Question: I don't understand why the code below subtracts an hour of a UNIX epoch timestamp (in timezone UTC+1):
import datetime
import pytz
start_dt = datetime.datetime.fromtimestamp( 1362268800 , pytz.utc )
print start_dt
# prints datetime.datetime(2013, 3, 3, 0, 0, tzinfo=<UTC>)
print int( start_dt.strftime("%s") )
# prints: 1362265200 (which is 2013-03-02T23:00Z ) <--- I expected 1362268800
print start_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
# prints: 2013-03-03T00:00:00Z

I've since hacked around my problem by using calendar.timegm( start_ts.timetuple() ), but I fundamentally wonder what's wrong with the code above, and how to create datetime objects that are in UTC and where strftime would print the epoch timestamp.
Using "%s" is not specifically allowed according to the python docs. Should it be explicitly be not allowed (ie. raise an exception?) if it results in confusing results?
Using python 2.7.3
Comment: [various ways to convert date, datetime objects to POSIX timestamp](http://stackoverflow.com/a/8778548/4279)
Answer:
Using "%s" is not specifically allowed according to the python docs.
  Should it be explicitly be not allowed (ie. raise an exception?) if it
  results in confusing results?

From the docs:

The full set of format codes supported varies across platforms,
  because Python calls the platform C library's strftime() function, and
  platform variations are common.

There is an open issue in the Python bug tracker "datetime.strftime('%s') should respect tzinfo" to add explicit support for "%s":

> it would appear the problem lies with strftime()
Yes, strftime('%s') ignores tzinfo at the moment.  This is not a bug.
  Support for '%s' format code is incidental and not documented in
  Python.


How I can do a loop in a xml file that I get a Attributte value?

Question: Hi I have a xml file and a string from active directory...I want to check the string with the value from the xml file.
here is xml: Permissiongroups.xml
<Permissiongroup>
  <Permission canonicalname="OU=dbg,OU=de,OU=zzz,DC=company_test,DC=com" display="group" />
  <Permission canonicalname="OU=brv,OU=de,OU=zzz,DC=company_test,DC=com" display="group" />
  <Permission canonicalname="OU=EK,OU=brv,OU=de,OU=zzz,DC=company_test,DC=com" display="group" />
</Permissiongroup>

My C# Code:
string canonicalname = user.canoncialName; //here I get the canonicalname of the search user

//for example is here "CN=Tarasov\, W,OU=PRG,OU=IT,OU=dbg,OU=de,OU=zzz,DC=company,DC=com"
string path = Server.MapPath("~/App_Data/Permissiongroups.xml"); // Get XML Path
string group = GetGroup(path, canonicalname); // Get User that match with canonicalname

here my method:
private string GetGroup(string xml, string canonicalname)
{
   XDocument document;
   XElement element;

   try
   {
     document = XDocument.Load(xml);

     //check every attribute canonicalname in the xml with the string canonicalname

     //return display value from the element with attributte canonicalname = canonicalname

   }
   catch (Exception)
   {
    return null;
   }
   finally
   {
    document = null;
    element = null;
   }

 }

Now is My Question how I can make a loop in a xml that give me the attribute canoicalname value. That I need for check it with the other string.
Answer: You can try this:
var permissions = document.Descendants("Permission");

foreach (var p in permissions)
{
    Console.WriteLine(p.Attribute("canonicalname").Value);
}

This is just an example how to print those values but I think that you will do the rest because I don't know what this check requirements are.
If you want to find a Permission that match your canonicalname you can try this code:
var searchedPermission = permissions.FirstOrDefault(p => p.Attribute("canonicalname").Value == canonicalname);

Answer: You can use LINQ to XML approach. First find all attributes canonicalname in the xml with the string canonicalname:
var q = (from c in doc.Descendants("Permission")
        where string.Equals(c.Attribute("canonicalname").Value, canonicalname)
        select c).ToList();

Then display values:
foreach (var item in q)
{
    Console.WriteLine(item.Attribute("canonicalname").Value);
}


Graphics and Animation in C#

Question: I created a Game in C# (Multi-player Tanks Game) using Windows Forms Tools (Panels, shapes, buttons, etc...) but the Animation and Graphics are just so poor, so is there any Type of simple Graphics or Animation to use in C# to make this game a little better, can I use flash in C#, anything?!!!
Comment: You might also be interested in our sister site [GameDev.SE].
Answer: XNA is great, its a completely different technology to Windows Forms as its based on DirectX.
Another idea is to check out silverlight or WPF depending on how complex your game is. For simple 2D games with not too busy screens it might be a lot easier than XNA.
I found a great example of building a multiplayer game in WPF.
Answer: I would recommend having a look at Microsoft XNA.
Answer: I'm pretty sure if you want to improve the graphics of your game you're going to have to use design software or hire someone to do it for you. A simple look up on Google will direct you to model development software.
A good place to start is the microsoft XNA framework.
I also recommend using Blender: http://www.blender.org/
It's a completely free open source 3D model creation program.
Answer: There are many librarys and ways for game development in C#.
I prefer to use XNA, which is based on DirectX and developed by Microsoft itself.
But there are also many other wrapper like OpenGL wrapper SharpGL, a custom DirectX wrapper SlimDX or using the plain DirectX SDK.
Answer: Some time ago I was looking for libraries or frameworks to improve winforms experience with nice animations. My best options were XNA or OpenTK (OpenGL) and SDL.Net.

Graphics and Animation in C#


How do we check if mock request is actually the correct one?

Question: Since we return mock objects from the requests made by the code, this means that no matter the input to the code under test, as long as the response from the request is handled correctly, the test would always pass. However we don't know if the code made the right request(s) to my site in the first place. For example, if makeRequest() for some reason made a request to www.my-site.com/foobar or www.google.com we would get a false positive because the tests would still pass since the mock response is still what we expect, but they should really fail.
Probably a silly question, but is there a way in unittest.mock to check and make sure the request made is what we expect as well?
def makeRequest(session):
    resp = session.get(www.my-site.com/foobar)
    return resp

@patch.object(requests.Session, 'get')
def test_makeRequest(self, mock_get):
    def mockResp(self):
        r = requests.Response()
        req.status_code = 200
        return r

    mock_get.return_value = mockResp()
    mock_get_response = makeRequest()

Comment: The package requests-mock allows exactly this.
Answer: You can check the request parameters by using assertions on the mock.
# setting up the canned response on the mock
mock_get.return_value = mockResp()

# actually calls the real code under test, i.e. calls makeRequest
mock_get_response = makeRequest()

# make an assertion about what the code *within* makeRequest did
mock_get.assert_called_once_with("www.my-site.com/foobar")

# maybe make an assertion about the `mock_get_response` here, too

Note that, as written, this test will fail. You need to pass a session into makeRequest, since it takes one required argument. Rather than setup your mock on requests.Session, it will be easier to just pass in your mock as the session argument during the test.


Rugby penalty kick into touch-in-goal

Question: In Rugby Union, when a penalty is taken as a kick into touch, imagine the following two situations:
Penalties http://www.die-sinlosen.de/fred/rugbykick.png

The kick goes over the try line (I think this is called in-goal?), but then into the touch area (over the field's side line) before touching the ground.
The kick goes over the try line and over the end of the field.

What happens in these cases? Which team will have possession?
Answer: In both cases the defending team would be offered the option of a 22m drop out or a scrum back at the point the kick was taken from.  This is the same as for any kick.  This would only apply for kicks not at goal.
If it had been signaled as a kick at goal both would result in a 22m drop out for the defending team.
These scenarios are covered by law 22.8.

Rugby penalty kick into touch-in-goal


Epsilon-Delta proof of multivariable function

Question: I have the following multivariable function: $f(x,y) = xy^2$, and I must prove it is continuous at (1,1). I have come to: $|((x-1)^2+(y-1)^2)^\frac{3}{2}-1| \le ((x-1)^2+(y-1)^2)^\frac{3}{2}+1$ (Triangle inequality) $<\delta^3+1=\epsilon$.
What can I do with this 1? Any tips are welcome and thank you in advance!
Comment: Your attempt isn't clear. You need to show that, for any $\epsilon > 0$ there exists $\delta > 0$ with the property that $$((x-1)^2 + (y-1)^2 )^{1/2} < \delta \implies |xy^2 - 1| < \epsilon.$$
Comment: Pragmatically, one is pushed to consider $$|f(x,y)-f(1,1)|=\varepsilon,$$ to find $\delta$ from $$\|(x,y)-(1,1)\|\le\delta.$$ But, also the clever choice $x=y$ because $f(x,x)=x^3$ increases faster.
Comment: But how can I put a bound on $(x-1)^2$ and $(y-1)^2$?
Comment: Under the simplification I suggested, your problem can be posed as to find $\delta$ such that $f(1+\delta,1+\delta)=1+\varepsilon$. This implies $(1+\delta)^3=1+\varepsilon$ and then $\delta=-1+^3\!\!\sqrt{1+\varepsilon}$
Answer: I think you're a bit confused about what you're asked to do. You have to prove that given any $\epsilon > 0$, there is a $\delta > 0$ such that $d((x,y),(1,1)) < \delta \implies |xy^2 - 1| < \epsilon$. The distance function I have in mind on $\mathbb{R}^2$ is different from the one you've written down, namely $ d((x,y),(1,1)) = \sqrt{(x-1)^2 + (y-1)^2}$.
Now in general, if I write down some ugly formula and ask you to prove it's continuous, it's going to be incredibly tedious if not outright impossible to do this by divine inspiration. This is why we have theorems such as "the product and sum of continuous functions are continuous." So one way to prove this is to observe that $f_1(x,y) = x$ and $f_2(x,y) = y$ are both separately continuous functions, which is really just the same statement twice, and then write $f(x,y) = x \cdot y \cdot y$, and use this theorem.
You can find a discussion of this theorem here.
If your instruction is to use the definition and only the definition, my advice is to look long and hard at the proof of this fact, and then just plug in all the values you have in this special case. It shouldn't be that hard since all three of the factors are just projection functions.
Comment: This clears things up for me, thank you for your answer!
Comment: So how can I "rewrite" $|xy^2-1|$ such that I have something with (x-1) and (y-1) in there so that I can substitute delta.
Comment: You usually can't do this kind of thing in general. This is why I suggested breaking it up into the three pieces.
Answer: One can pose this problem by considering the graph of the function as follow.
From the definition of continuity the $\varepsilon$-neighbourhood of the image $f(1,1)=1$ determines a couple of planes $z=1+\varepsilon$ and $z=1-\varepsilon$
(those planes in light yellow in the picture bellow).
The intersections of the planes $1\pm\varepsilon$ with the graph of $f$ determine two hyperbolas
$$
\left(\begin{array}{c}x\\y\\1\pm\varepsilon\end{array}\right),$$
with $xy^2=1\pm\varepsilon$.
Also a little circle of radius $\delta$, which is the border of a
$\delta$-neighbourhood centered at the preimage $(1,1)^{\top}$, when is transformed gives a closed curve $C$ viewed in the graph of $f$.
Then there is a point in the curve $C$ (the red fat point in the picture) which is the farest away from $p=(1,1,1)^{\top}$, which will be determined by considering that for the curve
$C$ can be parametrized as
$C(y)=\left(\dfrac{1+\varepsilon}{y^2}, y,1+\varepsilon\right)^{\top}$ and
the distance function
$$d(p,C(y))=\sqrt{\left(\dfrac{1+\varepsilon}{y^2}-1\right)^2+(y-1)^2+\varepsilon^2}.$$
Once you have the coordinates of this red point you can determine the coordinates of the little red point bellow in the $\delta$-circle centered a $(1,1)^{\top}$, which allows you see which is this $\delta$ conditioned by $\varepsilon$.


How would i send a value from one jsp to another using the link

Question: I have a jsp page where I have a link to "Creation.jsp" for which I have to pass the id.
I have used the following inside the anchor tag
href=/home/Creation.jsp?rad=<%=id%>
When i use like this, the actual id value is being displayed in the URL of the browser.
My question is : i dont want to display the value in the URL but want to send a value through the link from one jsp to another.
How can I do this.
Answer: Create a link button of type submit and submit it via a form. In the form action give the name of the Creation.jsp page there you will be able to access the value if you have stored it in a invisible textbox.
<form action="Creation.jsp" method="post">

<input type= "hidden" value="<%=id%>" name="hdnId"/>

<input type="submit">

</form>

now on the Creation.jsp page get the value by request.GetParameter("hdnId");
Addition:
Put this in the servlet
RequestDispatcher rd = request.getRequestDispatcher("Creation.jsp");
rd.forward(request, response);

refer http://docs.oracle.com/javaee/5/api/javax/servlet/RequestDispatcher.html
Comment: I have more than 6 links in my homepage, each link I have to send a different value to another jsp....
Comment: Those links wont be directing to the same page then you have to give each different values in different input type
Comment: Could you please elaborate on this.
Comment: For your situation as you dont want to show data in the url create a servlet where first the request will go there you can check which button was pressed then you can pass to different page using requestdispatcher.
Comment: So you only need only 1 hidden field holding your value which you can access from the required page


Solving a set of ODE with conditional statement

Question: I am trying to solve a set of differential equations with Python. Basically, I want to plot the figure below:

This is a graph that shows how the concentration of nutrients (Am) and phytoplankton (Phy) changes with time.
The Python code that I have to plot both variables as function of time:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp

# parameters
dil = 0.2
har_f = 20
har_pc = 0.95
ext_Am = 100
umax_Phy = 0.693
kAm_Phy = 14
t0 = 0
tf = 100
ns = 200
dt = (tf-t0)/(ns-1)

params = [dil, har_f, har_pc, ext_Am, umax_Phy, kAm_Phy, t0, tf, ns, dt]

def odes(t,x):
    dx = [0,0]
    har_dil = 0

    if t > 0 and t % har_f == 0:
        har_dil = har_pc/dt
    else:
        har_dil = 0

    time_dil = params[0] + har_dil
    in_Am = params[3] * time_dil
    u_Phy = params[4]*x[0]/(x[0]+params[5])
    gro_Phy = u_Phy * x[1]
    out_Am = x[0] * time_dil
    out_Phy = x[1] * time_dil
    dx[0] = in_Am - out_Am - gro_Phy
    dx[1] = gro_Phy - out_Phy

    return dx

# initial conditions:
x0 = [99,1]

# declare a time vector(time window)
tspan = (0,100)

# solving the set of ODEs
sol = solve_ivp(odes,tspan,x0)

fig1,axs_lst = plt.subplots(nrows=1,ncols=1,squeeze=False)

axs_lst[0,0].plot(sol.t,sol.y[0, :],'-',color='red',label='Am')
axs_lst[0,0].plot(sol.t,sol.y[1, :],color='green',label='Phy')
axs_lst[0,0].legend(loc='best',frameon=True,edgecolor='black',fancybox=False)
axs_lst[0,0].set_xlabel('Time [day]',size='12')
axs_lst[0,0].set_ylabel('Concentration [$g\:biomass\:m^{-3}$]',size='12')
axs_lst[0,0].tick_params(axis='both', which='both', direction='in')
axs_lst[0,0].grid(True)

However the graph that is generated is shown below:

As you can see, the concentration of nutrients does not decrease as it should because the value of the variable har_dil accounted is only the final value of the conditional statement. I would appreciate if someone could please help me with a strategy to solve this issue.
Answer: You wrote:
    if t == 0:
        har_dil = 0
    elif t > 0 and t % har_f == 0:
        har_dil = har_pc/dt
    else:
        har_dil = 0

    har_dil = 0

Ok, couple of things going on there.
(1.) You went to some trouble to compute har_dil,
and then you unconditionally zero it.
That can't possibly be what you intended.
Recommend you break out the if as a helper function,
and unconditionally assign the result of that function.
(2.) The t % har_f == 0 expression is apparently
trying to inject some periodicity, as seen in your first figure.
Good.
But, fair warning, asking if a
FP
quantity is exactly equal to zero is rather hit-or-miss.
Recommend that you either put int(t) into that expression,
or else ask if the modulo result is "close to" zero.
That is, pick a small epsilon and ask if abs(t % har_f) < epsilon.
Comment: Yeah, indeed, that was not intended. Actually the line har_dil = 0 should be written before the if-statement, because this is the usual value, except when time is a multiple of 20 (har_f = 20). I tried to use abs(t % har_f) < epsilon, as you suggested, but the graph generated was still the same. I have also updated the code, so that the line har_dil = 0 is before the conditional statement.
Comment: Changes of the ODE in one point do not change the exact solution, the numerical solver might be driven to small step sizes, but might miss the point or the small interval around it completely. It is better to just stop the integration at such points, make the intended changes to the parameters or state vector  and resume integration until the next interesting time.


Rails Jcrop Syntax Error

Question: I'm adding cropping functionality to my Rails app and am using the Railscast as my guide:
http://railscasts.com/episodes/182-cropping-images-revised
I've double checked things and am still getting a strange error when I try to load any page. Here is the message I'm getting:
SyntaxError in PeopleController#show
/app/uploaders/photo_uploader.rb:40: syntax error, unexpected '(', expecting keyword_end process :resize_to_limit(600, 600) ^
/app/uploaders/photo_uploader.rb:80: syntax error, unexpected end-of-input, expecting keyword_end

Extracted source (around line #4):

validates_presence_of :fname, :lname, :company, :department, :title, :work_phone, :mobile, :office, :address, :city, :state, :zipcode, :country, :suite, :column

mount_uploader :photo, PhotoUploader

after_update :crop_photo

Here is my person model code:
class Person < ActiveRecord::Base
validates_presence_of :fname, :lname, :company, :department, :title, :work_phone, :mobile, :office, :address, :city, :state, :zipcode, :country, :suite, :column

mount_uploader :photo, PhotoUploader

after_update :crop_photo

  def crop_photo
    photo.recreate_versions! if crop_x.present?
  end
end

Here is my photo uploader code:
# encoding: utf-8

class PhotoUploader < CarrierWave::Uploader::Base

# Include RMagick or MiniMagick support:
include CarrierWave::RMagick
# include CarrierWave::MiniMagick

# Choose what kind of storage to use for this uploader:
# storage :file
 storage :fog

 include CarrierWave::MimeTypes
 process :set_content_type

# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
  "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end

# Provide a default URL as a default if there hasn't been a file uploaded:
def default_url
# For Rails 3.1+ asset pipeline compatibility:
ActionController::Base.helpers.asset_path("fallback/" + [version_name,     "default.png"].compact.join('_'))

# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
end

# Process files as they are uploaded:
# process :scale => [200, 300]
#
# def scale(width, height)
#   # do something
# end

# Create different versions of your uploaded files:

version :large do
  process :resize_to_limit => [600, 600]
end

version :thumb do
  process :crop
  process :resize_to_limit => [200, 200]
end

def crop
  if model.crop_x.present?
    resize_to_limit(600, 600)
    manipulate! do |img|
      x = model.crop_x.to_i
      y = model.crop_y.to_i
      w = model.crop_w.to_i
      h = model.crop_h.to_i
      img.crop!(x, y, w, h)
    end
  end

after :store, :remove_original_file

def remove_original_file(p)
  if self.version_name.nil?
    self.file.delete if self.file.exists?
  end
end

# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
# def extension_white_list
#   %w(jpg jpeg gif png)
# end

# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
#   "something.jpg" if original_filename
# end

end

Here is what I have added for my Create section of my controller:
if @person.save
  if params[:person][:photo].present?
    render :crop
  else
    redirect_to @user, notice: "Successfully created user."
  end
end

I have similar code in my New action in my controller.
I'm completely stumped. The number of "End"s seem to match up from what I've seen.
I'm on Rails 4, Ruby 2 and am using Bootstrap 2.
All help is greatly appreciated.
Comment: One thing I'm doing different from the Railscast since I'm on Rails 4 is instead of attr_accessor I'm using strong parameters. So I've added  :crop_x, :crop_y, :crop_w, :crop_h to my params I've defined in my controller.
Answer: version :large do
  process :resize_to_limit(600, 600)
end

should be:
version :large do
  process :resize_to_limit => [600, 600]
end

Comment: Yep, I just saw that and made the change. I'm now getting a new error: /app/uploaders/photo_uploader.rb:80: syntax error, unexpected end-of-input, expecting keyword_end. It doesn't like something in my model. It doesn't like this line "mount_uploader :photo, PhotoUploader"
Comment: It's also saying there is a problem with my people controller in Line 7 which is: "def index
    @people = Person.page(params[:page]).per_page(5).order('lname')
  end" I'm wondering if there is a problem with will_paginate which I'm using
Comment: You're missing an end for def crop

Rails Jcrop Syntax Error


Gravação de voz com MediaRecorder Android Studio

Question: Estou trabalhando em um projeto com gravação de voz, estou com meio caminho andado, já estou com o gravador funcionando e salvando a gravação conforme o código a baixo, porem estou com alguns problemas:  1º não consigo criar uma pasta para salvar os áudios para depois exibir, fica todos os audios no diretório raiz, 2º não consigo listar os áudios na listView, 3º não faço a menor ideia de como deletar os áudios depois de criados e exibidos na ListView. segue o código do  gravador .java e XML. OBS: não vou colocar o codigo do exibir da listView porque não tem nada implementado.
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.util.Random;

import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

public class Gravador extends AppCompatActivity {

Button buttonStart, buttonStop, buttonPlayLastRecordAudio, buttonStopPlayingRecording ;
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder ;
Random random ;
String RandomAudioFileName = "ABCDEFGHIJKLMNOP";
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer ;

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

    buttonStart = (Button) findViewById(R.id.button);
    buttonStop = (Button) findViewById(R.id.button2);
    buttonPlayLastRecordAudio = (Button) findViewById(R.id.button3);
    buttonStopPlayingRecording = (Button)findViewById(R.id.button4);

    buttonStop.setEnabled(false);
    buttonPlayLastRecordAudio.setEnabled(false);
    buttonStopPlayingRecording.setEnabled(false);

    random = new Random();

    buttonStart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if(checkPermission()) {

                AudioSavePathInDevice = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + CreateRandomAudioFileName(5) + "AudioRecording.3gp";

                MediaRecorderReady();

                try {
                    mediaRecorder.prepare();
                    mediaRecorder.start();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                buttonStart.setEnabled(false);
                buttonStop.setEnabled(true);

                Toast.makeText(Gravador.this, "Recording started", Toast.LENGTH_LONG).show();
            }
            else {

                requestPermission();

            }

        }
    });

    buttonStop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            mediaRecorder.stop();

            buttonStop.setEnabled(false);
            buttonPlayLastRecordAudio.setEnabled(true);
            buttonStart.setEnabled(true);
            buttonStopPlayingRecording.setEnabled(false);

            Toast.makeText(Gravador.this, "Recording Completed", Toast.LENGTH_LONG).show();

        }
    });

    buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) throws IllegalArgumentException, SecurityException, IllegalStateException {

            buttonStop.setEnabled(false);
            buttonStart.setEnabled(false);
            buttonStopPlayingRecording.setEnabled(true);

            mediaPlayer = new MediaPlayer();

            try {
                mediaPlayer.setDataSource(AudioSavePathInDevice);
                mediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }

            mediaPlayer.start();

            Toast.makeText(Gravador.this, "Recording Playing", Toast.LENGTH_LONG).show();

        }
    });

    buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            buttonStop.setEnabled(false);
            buttonStart.setEnabled(true);
            buttonStopPlayingRecording.setEnabled(false);
            buttonPlayLastRecordAudio.setEnabled(true);

            if(mediaPlayer != null){

                mediaPlayer.stop();
                mediaPlayer.release();

                MediaRecorderReady();

            }

        }
    });
}

public void MediaRecorderReady(){

    mediaRecorder=new MediaRecorder();

    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

    mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);

    mediaRecorder.setOutputFile(AudioSavePathInDevice);

}

public String CreateRandomAudioFileName(int string){

    StringBuilder stringBuilder = new StringBuilder( string );

    int i = 0 ;
    while(i < string ) {

        stringBuilder.append(RandomAudioFileName.charAt(random.nextInt(RandomAudioFileName.length())));

        i++ ;
    }
    return stringBuilder.toString();

}

private void requestPermission() {

    ActivityCompat.requestPermissions(Gravador.this, new String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);

}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case RequestPermissionCode:
            if (grantResults.length > 0) {

                boolean StoragePermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                boolean RecordPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;

                if (StoragePermission && RecordPermission) {

                    Toast.makeText(Gravador.this, "Permission Granted", Toast.LENGTH_LONG).show();
                }
                else {
                    Toast.makeText(Gravador.this,"Permission Denied",Toast.LENGTH_LONG).show();

                }
            }

            break;
    }
}

public boolean checkPermission() {

    int result = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
    int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO);

    return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
}

}
XML do Gravador

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:src="@drawable/mic_pic"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Record"
    android:id="@+id/button"
    android:layout_below="@+id/imageView"
    android:layout_alignParentLeft="true"
    android:layout_marginTop="37dp"
    />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="STOP"
    android:id="@+id/button2"
    android:layout_alignTop="@+id/button"
    android:layout_centerHorizontal="true"
    />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Play"
    android:id="@+id/button3"
    android:layout_alignTop="@+id/button2"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="STOP PLAYING RECORDING "
    android:id="@+id/button4"
    android:layout_below="@+id/button2"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="10dp"

        />
</RelativeLayout>

Answer: Bom voce tem mais de uma duvida entao vou tentar te ajudar em passos:

Salvar o audio em uma pasta especifica:

Segundo essa resposta do SO gringo:
File f = new File(Environment.getExternalStorageDirectory() + "/suapasta");

if (f.isDirectory()) {
        //Seu codigo caso o "suapasta" seja um diretorio

} else {

        // cria um objeto File pro diretorio pai
        File wallpaperDirectory = new File("/sdcard/Wallpaper/");
        // cria a pasta caso seja necessario
        wallpaperDirectory.mkdirs();
       // cria o objeto File pro output
       File outputFile = new File(wallpaperDirectory, filename);
       // agora adiciona o OutputStream no seu arquivo
       FileOutputStream fos = new FileOutputStream(outputFile);

}

Esse codigo checa se o local onde voce quer salvar eh uma pasta (nao vai ser na primeira vez que salvar, ou caso apague os dados do dispositivo) e caso seja, voce ja salva direto como faria na pasta raiz, senao ele cria a pasta pra voce e ai vc salva o arquivo (recomendo um metodo auxiliar pra salvar pra evitar a duplicidade de codigo)

Mostrar no listview

Essa parece mais ser uma pergunta de desconhecimento de como funciona o ListView do que ter a ver com audio, entao te recomendo fortemente dar uma lida na documentacao do ListView (a nao ser que seja um requerimento usar o ListView, tambem recomendo fortemente, mas fortemente  mesmo, dar uma olhada no RecyclerView ao inves do ListView)
Segue a documentacao:
ListView
Como Criar listas e Cards
Mas a ideia basica por cima de forma resumida, eh que voce precisa criar um layout pra cada item da sua lista, ter uma lista de objetos de audio (ou de uma classe container com mais informacoes sobre o audio) que vai ser passada pro adapter, criar um adapter que relaciona o seu layout com cada item da lista (procure por ListView/RecyclerView adapter que encontra muita coisa no Google) e acredito que voce tambem quer relacionar cada audio com um elemento da lista, isso eh facinho de fazer no adapter quando voce entende o conceito.

Deletar os audios

Bom, nao entendi muito bem essa duvida, pois se voce deletar eles nao vai conseguir usa-los no ListView pra tocar, entao se puder deixe um comentario explicando melhor o que vc quis dizer com isso que eu edito.
Desculpa se nao respondi todas as duvidas mas era uma pergunta bem extensa, espero ter ajudado
Comment: Opa muito obrigado pela dica, sou novo na área de desenvolvimento Mobile, questao de deletar seria depois de já estar listando os áudios, ou seja, aparecendo todos na lista, quero deletar determinado áudio que gravei e que não quero mais usar ou nao quero mais que que apareça na lista. Outra questão é como eu poderia colocar um nome antes de salvar o Áudio?


How to delete all data in one field of a particular content type?

Question: We have a content type basic page that has a Date field (field_bp_date). We want to use the hook_update to delete all data in this field. We are having trouble figuring out what is the best way to simply delete all data in the field_bp_date field on the basic page content type?
Ideally we would like to do the following:
function mymodule_update_7001(...) {
    $content_type = 'page';
    $fieldDataToDel = 'field_bp_date';

    //some function/hook to delete all the data
    ....
}

Answer: If you only need to do this once you could use Views Bulk Operations https://www.drupal.org/project/views_bulk_operations
/admin/structure/views

Click "Add new view" link
Show "Content" of type "YOUR_CONTENT_TYPE"
Click "Continue & Edit" button

Under the FORMAT section change Show: click 'Content' change to 'Fields'

Click 'Apply' button
Click 'Apply' button again

Under FIELDS section click the 'Add' button

Checkmark 'Bulk operations: Content'
Under SELECTED BULK OPERATIONS choose 'Modify entity values' checkbox
Scroll down a little, you will see OPERATION SETTINGS choose that date Field you want to edit.
Click 'Apply' button
Click 'Save' to save that View

Go to the View Page you just created.

Under Operations choose 'Modify entity values'
Select one or all of them (I suggest you do one as a test).
Click the 'Execute' button.
This page will allow you to set the Date to anything you want, even nothing. TIP! for Date if you want no date you need to change all values to blank. You can't delete just the hours, you need to set all of them to blank, which gives you the result you requested.
Click the 'Next' button.
Click the 'Confirm' Button.

Congrats. Go back and run it on all of them, if it went as expected on the one test node.
Comment: How to do so ??
Comment: It is a GUI interface.      Create a View.
    Add a "Bulk operations" field if available (see technical details below).
    Configure the field. There's a "Views Bulk Operations" fieldset where the actions visible to the user are selected.
    Go to the View page. VBO functionality should be present. https://www.drupal.org/node/1591352
Comment: Please transform your comment in an updated version of your answer (which is where it really belongs). Just trying to get you going on this site, ok?
Comment: You should also explain how via VBO those data to be deleted can actually be deleted. EG which VBO "action" to use for doing so ...
Comment: There.  I wrote a whole tutorial.
Comment: Much better !!!
Answer: You can just run a mysql delete command.  As this is a date field, there aren't any dependencies on other tables.
function mymodule_update_7001() {
  db_query("DELETE FROM field_data_field_bp_date WHERE entity_type = 'node' and bundle = 'page'");
  db_query("DELETE FROM field_revision_field_bp_date WHERE entity_type = 'node' and bundle = 'page'");
}

Note: You would only want to use this approach if you felt certain that there weren't any other modules that needed to react to that data.
Comment: True, you "can", but I'd not recommend doing so. Any idea what the problem with such approach really is?
Comment: No, what are you hinting at?
Comment: Using this approach, do you allow Drupal core and/or other modules to detect that change (and trigger whatever related actions)? That's why I rather prefer an approach similar to http://drupal.stackexchange.com/questions/189450/should-i-change-multiple-text-fields-values-via-mysql-or-is-there-any-other-pref/192659#192659
Comment: Yes, you would only want to use this approach if you felt certain that there weren't any other modules that needed to react to that data.


Action button not working within UITable

Question: I have been through few of these tutorial and I cant seem to call my function via button click. I have followed this guy's tutorial but nothing works.
My tableView currently working just great, all Im doing now is adding a button so I could pass data to another view but my button click is not calling its function.
//class IncomeFeedCell: UITableViewCell:

@IBOutlet var weak button: UIButton!

View Contoller:
// class IncomeFeedVC: UIViewController, UITableViewDelegate, UITableViewDataSource:

// viewDidLoad:
tableView.delegate = self
tableView.dataSource = self

// cellForRowAt indexPath
let cell = self.tableView.dequeueReusableCell(withIdentifier: "IncomeFeedCell") as! IncomeFeedCell
cell.button.tag = indexPath.row
cell.button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
cell.configureCell(income: income)
return cell

Now the function to call when tapped:
func buttonPressed(){
  print("Tapped")
}

Simulator:

Have I missed something simple?
Edit:
Apologies for all who and tried to help and got downvoted because I left out more vital information. All this is inside my viewDidLoad in IncomeFeedVC:
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self

DataService.ds.REF_INCOMES.queryOrdered(byChild: "date").observe(.value, with: { (snapshot) in

    /**
     * Sorting the object before looping over
     * Info here: http://stackoverflow.com/questions/41416359/sort-firebase-data-with-queryordered-by-date
     */
    guard let incomeSnap = snapshot.value as? [String:AnyObject] else{

        return
    }

    let sorted = incomeSnap.sorted{($0.0.value["date"] as! Double) > ($0.1.value["date"] as! Double)}

    for snap in sorted {
        if let incomeDict = snap.value as? [String: AnyObject] {
            let key = snap.key
            let income = Income(incomeId: key, incomeData: incomeDict)
            self.incomes.append(income)
        }

    }
    self.tableView.reloadData()
})

Comment: @Hrishikesh If `cell.button` was `nil` there would be crashes trying to use the `nil` reference.
Comment: @HimanshuMoradiya What is and where, please?
Comment: cell.button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside) this line and func buttonPressed(){
  print("Tapped")
} funcation
Comment: Your question isn't clear. What is the exact problem? What happens when you tap the button?
Comment: @rmaddy When tapped, nothing prints to console.
Comment: check if cell.button is nil ??? before adding any action to button
Comment: Im confident that this should work. Many tutorials has the same as mine. Im using Swift 3, xcode 8.
Comment: cell.button is not nil
Comment: Could you please share your cell.configureCell(income: income) function.
Comment: Move the configureCell line before setting the tag / addTarget code (yes, @DheerajD might be right, you might overwrite the event handler there)
Comment: And to be sure, put a breakpoint inside the `buttonPressed` method. Is the breakpoint reached when a button is tapped?
Comment: Why are you not connecting `IBAction` in `IncomeFeedCell` like `IBOutlet` you have connected! And make sure that your button is not covered by any other view !
Comment: cell.button.tag = indexPath.row problem is here . all time you got new tag of your button cell so remove it .
Comment: @rmaddy Did but the issue is that it's not even attempting to call the function.
Comment: @HimanshuMoradiya. There is always a new tag because it is always a new button... There's no reason to delete that if he references the tag later on.
Comment: but its batter to use outlet instead of tag .
Comment: Set the button's tag to row: this is the easiest way to refer to the index of the data array to access the related object for further use. If you don't want to use tag, you can also get the cell by looping sender's superviews, then use `tableView.indexPathForCell` method to get the indexPath.
Comment: I may have a clue here, would `self.tableView.reloadData()` cause an issue elsewhere in my `class`?
Comment: @Sylar would you like to update your question and show us your code of the IncomeFeedVC class and IncomeFeedCell class?
Comment: Post updated. Nothing else to add.
Answer: My ViewController:
class ViewController: UIViewController , UITableViewDelegate,UITableViewDataSource{
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as! TestTableViewCell

    cell.bttn.addTarget(self, action: #selector(clickme(sender:)), for: .touchUpInside)
    return cell
}
func clickme(sender: UIButton) {
    print("cliked")
}

}

My UITableViewCell
import UIKit

class TestTableViewCell: UITableViewCell {

@IBOutlet weak var bttn: UIButton!
override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

}

Its working fine in my case.
Can you remove the "self" in your
let cell = self.tableView.dequeueReusableCell(withIdentifier: "IncomeFeedCell") as! IncomeFeedCell line.
Comment: How does this explain the problem in the question? Why isn't the `buttonPressed` method being called in the OP's code?
Comment: @maddy I just added a working reference.And OP's code is not working probably of cellForRow function I also suggested what could be wrong in his code.
Comment: Pretty much all the code in your answer is irrelevant to this question apart from one func.
Comment: `self` is removed but still the same. Also, I am reloading the `tableView` in `viewDidLoad`. Would that be an issue?
Comment: @Sylar no, there is no problem you call tableView.reloadData() in viewDidLoad.
Answer: your button tapped function should be like this:
  func buttonPressed(sender: UIButton)
  {

  let buttonTag = sender.tag// you can check tag like this

  }

Comment: The `sender` parameter is not needed. Adding this doesn't answer the question.
Comment: Someone said the `sender` parameter is not needed, yes, you don't need to provide any parameter to an event handler, but it's a bad programming behaviour. You should always pass in `sender` to any event handler for UIControl even you don't use it.
Comment: @sagar his  func buttonPressed(sender: UIButton) method is not calling.
Comment: agreed with  @bubuxu sender should be present is good programming but not mandatory
Comment: That's great, but that doesn't necessarily solve OP's problems.
Answer: Can you please try
cell.button.addTarget(self, action: #selector(IncomeFeedVC.buttonPressed(_:)), for: .touchUpInside)

Also below function should be implemented in IncomeFeedVC class
func buttonPressed(_ sender: AnyObject){
  print("Tapped")
}

Comment: Same. Nothing is printing. I have the function in `IncomeFeedVC`. Weird one
Comment: @sylar Did you implemented func buttonPressed(sender: UIButton) in IncomeFeedVC class?
Comment: @Manoj Having it in this format should not matter if his function is in the IncomeFeedVC as he has said it is. Almost think I should DV this.
Comment: Also, why `AnyObject`? it is a method called by a button, so the sender would always be a button.
Comment: @Benjamin it is good practice which I followed.   https://github.com/apple/swift-evolution/blob/master/proposals/0022-objc-selectors.md
Comment: @Manoj Yes I did.


Heartbeat removes default gateway

Question: I'm setting up 2 mailservers (Postfix) with heartbeat failover & drbd shared maildirs. For some reason, when starting the heartbeat, the default gateway is lost. Any idea how / why this happens and what the solution is?
/etc/network/interfaces:
# The loopback network interface
auto lo
iface lo inet loopback

# eth0: ip of this node
auto eth0
allow-hotplug eth0
iface eth0 inet static
        address 192.168.2.3
        gateaway 192.168.2.46
        netmask 255.255.255.0
# eth0:0: ip address which heartbeat is supposed to take over
iface eth0:0 inet static
        address 192.168.2.5
        netmask 255.255.255.0

/etc/ha.d/haresources:
mx1 IPaddr::192.168.2.5
mx1 drbddisk::r0 Filesystem::/dev/drbd0::/syncdata::ext3 nfs-kernel-server

Failover works fine, but a the default gateway is lost as soon as heartbeat starts it seems (so, also after booting / not yet taking anything over). So far, the only thing I can think of is adding a route add default gw 192.168.2.46 in post-up & post-down of eth0:0, but that seems rather ugly....
Answer: Is this an actual typo in your config?
    gateaway 192.168.2.46

Should be
    gateway 192.168.2.46

Comment: OMFG... Pfft.... I probably moved things around to much with getting it to work I totally missed this... Fixing now, and if this was the problem all along, you have the right to call me an idiot for a full year...
Comment: Don't worry, mistakes like that do happen all the time. That's why it's good to have an extra eye pair looking at the config files :)
Comment: Even after knowing there was an error here, I had to read it twice to find it :)
Comment: @Chris N: I spotted that because the vertical alignment of text was wrong. The words `address`, `network`, `netmask` and `gateway` in `/etc/network/interfaces` all contain seven characters, so the `gateaway` line being unaligned immediately got my attention. :-) Yes I know, I probably have seen that file too many times in my life.
Comment: Yup, extra eyes help a lot ;). Confirmed this was the one & only problem, thanks!
Comment: @Wrikken: Solved? YOU IDIOT! :P
Comment: Hehe ;) A whole year.... ouch.
Comment: @Wrikken: I'm tempted to reserve `iswrikkenstillanidiot.com` and make it return `YES` until 26th of October, 2012.
Comment: Change "gateway" to "stargate" and you get some really neat traffic from a sniffer.

Heartbeat removes default gateway


Define the image of the projection matrix $Q:=X(X^{T}X)^{-1}X^{T}$

Question: I recently came across the following claim:

Let $X \in \mathbb{R}^{n \times p}$ ($p\leq n$) be a matrix with linearly independent columns. Then $Q:=X(X^{T}X)^{-1}X^{T}$ is a projection matrix onto $span\{x_{1},\ldots,x_{p}\}$ ($x_{i}$ is the i-th column of $X$).

The projection properties are easy to verify:

$Q$ is symmetric: $Q^{T}=(X(X^{T}X)^{-1}X^{T})^{T}=X(X^{T}X)^{-1}X^{T}=Q$
$Q$ is idempotent: $QQ=X(X^{T}X)^{-1}X^{T}X(X^{T}X)^{-1}X^{T}=X(X^{T}X)^{-1}X^{T}=Q$

Hence $P:\mathbb{R}^{n}\rightarrow \mathbb{R}^{n}, x \mapsto Qx$ is a projection.
However I do not see why the range of $Q$ is given by $span\{x_{1},\ldots,x_{p}\}$. Any suggestions?
Answer: Set $y:=X e_i$ and compute $Qy$ to obtain $x_i$ ($i$-th column of X) as an image vector.
Comment: Ah, yes. $QX=X(X^{T}X)^{-1}X^{T}X=X$ and hence $image(Q)=span\{x_{1},\ldots,x_{p}\}$.


how to load a json from parent directory

Question: I have to load a configuration file from parent directory. Here is the folder structure :
.
├── cleanup
├── _conf.json
├── data
│   ├── all_combine_200k.csv
│   ├── cyclegear.csv
│   ├── make_dataset.py
│   └── R_Result_Temp.csv
├── features
│   ├── add_template_python.py
│   ├── build_features.py
│   ├── create_templates.py
│   ├── read_template_python.py
│   └── template_features_req.proto
├── __init__.py
├── models
│   ├── hmm
│   ├── __init__.py
│   ├── predict_model.py
│   └── train_model.py
├── remotedb
│   └── cyclegeardb.py
├── utils
│   ├── c_print.py
│   └── __init__.py
└── visualization
    ├── __init__.py
    └── visualize.py

I am in add_template_python.py and need to load _conf.json from the src directory.
In order to import stuff from other directories I just use sys.path.append('..') but that won't work here. What code can load json file from parent directory?
Comment: Load `"../_conf.json"`.
Comment: @erip "_conf.json" is not in "cleanup", it is in the root of the project.
Comment: I will, it just says to wait a minute :)
Comment: @DYZ You're missing if `add_template_python` isn't executed in CWD.
Comment: Please respond to us instead of editing your post. It makes it very confusing for answers.
Comment: Sorry, my bad. The last solution worked out. Thanks a lot.
Comment: @JohnM. If it solved your problem, you can select it as the answer by clicking the checkmark.
Answer: You can get the path to the the file with:
path_to_json = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '_conf.py')

This will not normalize the path. If that's important, you can normalize it with os.path.normpath.
Answer: Normalized Path:
file_path = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '_conf.json'))


error with jsp parameter

Question: basically my query was,
SELECT SEC_ORGANIZATION.description as sec_desc, FIN_COA.name as coa_name, FIN_COST_CENTRE.name as cctr_name, FIN_ANALYSIS.name as analysis_name, FIN_SUBANALYSIS.name as sub_analysis_name, FIN_COA.description as coa_desc, SEC_USER_UPDATE.login_name as update_name, CURRENCY.description as currency_desc, SEC_USER_CREATE.login_name create_name, DOCUMENT_TYPE.description as doc_desc, DOCUMENT_TYPE.name as doc_name, FIN_TRADER.description as trader_desc, AP_REC_POSTED_HDR.trans_no, AP_REC_POSTED_DTL.trans_mode, AP_REC_POSTED_DTL.document_amt as dtl_doc_amt, AP_REC_POSTED_HDR.post_frequency, AP_REC_POSTED_HDR.trans_date as hdr_trans_date, AP_REC_POSTED_HDR.rec_start_date, AP_REC_POSTED_HDR.rec_end_date, AP_REC_POSTED_HDR.document_no hdr_doc_no, AP_REC_POSTED_HDR.rec_lastgen_date, AP_REC_POSTED_HDR.rec_nextgen_date, AP_REC_POSTED_HDR.exchange_rate, AP_REC_POSTED_HDR.document_amt hdr_doc_amt, AP_REC_POSTED_HDR.base_amt hdr_base_amt, AP_REC_POSTED_DTL.base_amt as dtl_base_amt, AP_REC_POSTED_DTL.line_no, AP_REC_POSTED_HDR.organization_id, FIN_YEAR_PERIOD.fin_year, FIN_YEAR_PERIOD.acct_period, AP_REC_POSTED_HDR.remarks hdr_remarks, AP_REC_POSTED_DTL.remarks as dtl_remarks
 FROM   (((((((((((AP_REC_POSTED_HDR AP_REC_POSTED_HDR LEFT OUTER JOIN SEC_ORGANIZATION SEC_ORGANIZATION ON AP_REC_POSTED_HDR.ORGANIZATION_ID=SEC_ORGANIZATION.OBJECT_ID)
 LEFT OUTER JOIN DOCUMENT_TYPE DOCUMENT_TYPE ON AP_REC_POSTED_HDR.DOC_TYPE_ID=DOCUMENT_TYPE.OBJECT_ID)
 LEFT OUTER JOIN FIN_YEAR_PERIOD FIN_YEAR_PERIOD ON AP_REC_POSTED_HDR.YEAR_PERIOD_ID=FIN_YEAR_PERIOD.OBJECT_ID)
 LEFT OUTER JOIN CURRENCY CURRENCY ON AP_REC_POSTED_HDR.CURRENCY_ID=CURRENCY.OBJECT_ID)
 LEFT OUTER JOIN FIN_TRADER FIN_TRADER ON AP_REC_POSTED_HDR.TRADER_ID=FIN_TRADER.OBJECT_ID)
 LEFT OUTER JOIN SEC_USER SEC_USER_CREATE ON AP_REC_POSTED_HDR.CREATED_BY=SEC_USER_CREATE.OBJECT_ID)
 LEFT OUTER JOIN SEC_USER SEC_USER_UPDATE ON AP_REC_POSTED_HDR.UPDATED_BY=SEC_USER_UPDATE.OBJECT_ID)
 LEFT OUTER JOIN AP_REC_POSTED_DTL AP_REC_POSTED_DTL ON AP_REC_POSTED_HDR.OBJECT_ID=AP_REC_POSTED_DTL.AP_REC_POSTED_HDR_ID)
 LEFT OUTER JOIN FIN_COA FIN_COA ON AP_REC_POSTED_DTL.ACCT_ID=FIN_COA.OBJECT_ID)
 LEFT OUTER JOIN FIN_COST_CENTRE FIN_COST_CENTRE ON AP_REC_POSTED_DTL.COST_CTR_ID=FIN_COST_CENTRE.OBJECT_ID)
 LEFT OUTER JOIN FIN_ANALYSIS FIN_ANALYSIS ON AP_REC_POSTED_DTL.ANALYSIS_ID=FIN_ANALYSIS.OBJECT_ID)
 LEFT OUTER JOIN FIN_SUBANALYSIS FIN_SUBANALYSIS ON AP_REC_POSTED_DTL.SUBANALYSIS_ID=FIN_SUBANALYSIS.OBJECT_ID
 WHERE  DOCUMENT_TYPE.NAME='PE'

Everything goes right, but when i put,
and ap_rec_posted_hdr.trans_no >= $P{tnoFrom}
and ap_rec_posted_hdr.trans_no <= $P{tnoTo}
and ap_rec_posted_hdr.trans_date >= to_date($P{dtTFrom},'dd-mm-yyyy')
and ap_rec_posted_hdr.trans_date <= to_date($P{dtTTo},'dd-mm-yyyy')
and ap_rec_posted_hdr.posting_date >= to_date($P{finFrom},'dd-mm-yyyy')
and ap_rec_posted_hdr.posting_date <= to_date($P{finTo},'dd-mm-yyyy')
and fin_trader.name >=$P{venFrom}
and fin_trader.name <=$P{venTo}
and sec_user_create.login_name >= $P{cFrom}
and sec_user_create.login_name <= $P{cTo}
  ORDER BY AP_REC_POSTED_HDR.TRANS_NO

It returns the null value when displayed on the web page.
Comment: ... now that's a query... basically? :)
Answer: Chi: Run the same query directly against the database. Use the same values you used in the report.
If you get null, then the query is correct.

error with jsp parameter


No fixed point problem for iterations

Question: Let $f(z)$ be an entire function that is not a polynomial of degree 1 or degree 0 , where $z$ is a complex number.
Let $f(z,1) = f(z)$ and let $f(z,n) = f(f(z,n-1))$.
Let $g(f,1)$ be the amount of distinct complex fixpoints of $f(z,1)$.
More general let $g(f,n)$ be the amount of distinct complex fixpoints of $f(z,n)$.
Let $G(f,n)$ = $g(f,1)$ + $g(f,2)$ $+ ... +$ $g(f,n)$
What is an example $f(z)$ such that $G(f,30)$ = 0 ?
Comment: By "nonlinear" do you mean in the sense of linear maps, or linear polynomials?
Comment: Briefly: a linear map is a function $f$ such that $f(\lambda x + \mu y) = \lambda f(x) + \mu f(y)$, whereas a linear polynomial is just a polynomial of degree 1. I assume you mean the latter (the only linear maps that are also entire functions are multiplication by a constant), but you ought to be clear.
Comment: @ Ben : Thanks you are correct.
Answer: There are none.
Suppose $f$ is an entire function and both $f$ and $f(\cdot,2)$ lack fixed points.  Consider
$$q(z) = \frac{f(z) - f(z,2)}{f(z) - z}$$
Since the denominator is never $0$, this is an entire function.  It never takes the values $0$ (because $f(z) - f(z,2) = 0$ would mean $f(z)$ is a fixed point of $f$) or $1$
(because $f(z) - f(z,2) = f(z) - z$ would mean $z$ is a fixed point of $f(\cdot,2)$).  By
Little Picard it is constant: $q(z) \equiv c$ where $c \notin \{0,1\}$. But then $z = c^{-1} (f(f(z)) + (c-1) f(z))$ implies that $f$ is one-to-one, and the only one-to-one entire functions are polynomials of degree $1$.
Comment: Thanks for the reply. I see that $q(z)=c$.
Could you explain why f is one-to-one ?
Comment: If $f(z_1) = f(z_2)$, then
$$z_1 = c^{-1} (f(f(z_1)) + (c-1) f(z_1)) = c^{-1} (f(f(z_2)) + (c-1) f(z_2)) = z_2$$
Comment: Ah yes ! Thank you.
Comment: I was wondering about non-entire functions ... I think it applies to all taylor series. And others. Im dreaming about fractals now.
Comment: You have to worry about domains.  For example, a branch of $\sqrt{z}$ with branch cut on $[0,\infty)$ maps ${\mathbb C} \backslash [0,\infty)$ into itself and has no fixed or periodic points.

No fixed point problem for iterations


Can I Make Password Change Reminders More Obvious

Question: In Windows 7 and Windows 2008 is appears that Microsoft changed how users would be reminded about upcoming password expirations.
In Windows XP the password expiration was very obvious. There was a password change request screen that was displayed after the user logged in asking if they wanted to change their password because it will expire in X number of days.
However in Windows 7/2008 this was changed. Now the user is logged in normally with a small notification bubble that appears for a few seconds in the lower right hand corner of the users screen suggesting that they change their password.
I am looking for a way to go back to the Windows XP type of method, or at least something that is more obvious to the user that they need to change their password. Is there an AD setting, or something else that I can do, to enable the functionality on my users systems?
Answer: I would recommend providing users notifications via email.
You can do this with software:
http://www.netwrix.com/password_expiration_notifier_freeware.html
Or you can write a script to do it as well.
http://www.sheenaustin.com/2009/06/19/active-directory-password-expiry-reminder-email/
I find a lot of users that are traveling or away from their computer won't realize their password is expiring but with this method they are always notified via email.