Using "keys()" in python3.4 in win7

Question: I'm reading Natural Language Processing with Python by Steven Bird, Ewan Klein, Edward Loper.
And in this book, they use python2.4 or 2.5, but I could get python3.4.1 and python3.3 and python2.7.1. So I can1t use keys().
Please tell me how to use python2.4 or 2.5, or how to make "keys()" on myself.
I know the concept of function so I will make keys() with some hints, please help me!
Comment: Python 3 has `dict.keys()`. What makes you think it doesn't?
Comment: And you can use Python 2.7, instead of 2.4 or 2.5. Just about everything that works in 2.4 and 2.5 will work just fine in 2.7.
Answer: If you are trying to use a book designed for Python 2.4 or 2.5, you can use Python 2.7 and not have any problems.
Python 3 dict.keys() exists and works just fine. It returns a dictionary view object rather than a list like in Python 2, so all you have to do to get the same result is call list(somedict.keys()).
However, you'll have other problems translating the Python 2 code to Python 3, and I strongly advice you to stick with a Python 2.x interpreter.
Comment: Thank you very much for your answer and advice!I'm going to master Natural Language Processing, not python3.4.1.So I will recieve your advice to use python2.7.Some other functions has another work from the book, if I can do as on the book, it's very happy.Very nice advice, Regard
Comment: dict.keys() had worked!Thank you! But .keys() had worked too! What a amaging! I am noob!

Using "keys()" in python3.4 in win7


nginx rewrite all wildcard subdomains to www.site.com

Question: I want to redirect all subdomains of http://abc.example.com to https://abc.example.com.
Answer: This could work for example.com to www.example.com:
server {
    listen 80;
    listen [::]:80;
    server_name *.example.com;
    return 301 https://www.example.com$request_uri;
}

From http to https for all subdomains:
server {
    listen 80;
    listen [::]:80;
    server_name *.example.com;
    return 301 https://$host$request_uri;
}

Notice the server_name *.example.com
You could also use $server_name

$host – The hostname provided by the client for the current request.
$server_name – The first hostname from the hostname declaration in your config for the server block that responds to the request.

Canonical hostname
If the hostname doesn't match the first name in the server_name list. Makes sure your content is only available at the canonical hostname, e.g. to avoid duplicate content issues (SEO). Excellent for redirecting non-www to www or redirecting www to non-www in Nginx as long as your server block is only for a single website.
server_name example.com www.example.com example.net www.example.net _;
if ( $host != $server_name ) {
  return 301 $scheme://$server_name$request_uri;
}

Check this site nginx-redirect for extended version
Comment: I replaced  return 301 https://$host$request_uri;  instead of  return 301 https://$server_name$request_uri;  ...  now working good
Comment: I updated the answer to give more context hope it can helps
Answer: Try this code,
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    listen  443 ssl default_server;
    listen [::]:443 ssl default_server;
    server_name *.example.com;

    if ($scheme = http) {
        return 301 https://$host$request_uri;
    }


Apache does not start on EC2

Question: I have a t2.medium ec2 instance which runs apache. Everything was fine till today morning but suddenly apache stopped working and does not restart again.
<code>[ec2-user@ip-172-31-3-46 ~]$ sudo service httpd start
Starting httpd:                                            [FAILED]
[ec2-user@ip-172-31-3-46 ~]$ service httpd start
Starting httpd: (13)Permission denied: AH00072: make_sock: could not bind to address [::]:80
(13)Permission denied: AH00072: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
AH00015: Unable to open logs
                                                           [FAILED]
</code>
Then we checked where port 80 is already listening.
<code>[ec2-user@ip-172-31-3-46 ~]$ sudo netstat -tupln
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name
tcp        0      0 0.0.0.0:111                 0.0.0.0:*                   LISTEN      2204/rpcbind
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      2392/sshd
tcp        0      0 0.0.0.0:38935               0.0.0.0:*                   LISTEN      2225/rpc.statd
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      2714/sendmail
tcp        0      0 0.0.0.0:3306                0.0.0.0:*                   LISTEN      2664/mysqld
tcp        0      0 :::111                      :::*                        LISTEN      2204/rpcbind
tcp        0      0 :::22                       :::*                        LISTEN      2392/sshd
tcp        0      0 :::46232                    :::*                        LISTEN      2225/rpc.statd
udp        0      0 0.0.0.0:68                  0.0.0.0:*                               2090/dhclient
udp        0      0 0.0.0.0:111                 0.0.0.0:*                               2204/rpcbind
udp        0      0 172.31.3.46:123             0.0.0.0:*                               2416/ntpd
udp        0      0 127.0.0.1:123               0.0.0.0:*                               2416/ntpd
udp        0      0 0.0.0.0:123                 0.0.0.0:*                               2416/ntpd
udp        0      0 0.0.0.0:51407               0.0.0.0:*                               2225/rpc.statd
udp        0      0 0.0.0.0:683                 0.0.0.0:*                               2204/rpcbind
udp        0      0 127.0.0.1:708               0.0.0.0:*                               2225/rpc.statd
udp        0      0 :::111                      :::*                                    2204/rpcbind
udp        0      0 :::683                      :::*                                    2204/rpcbind
udp        0      0 :::40147                    :::*                                    2225/rpc.statd
</code>
But there is no sign of port 80 in this.
We need to go live today but this has posed a major problem? Can someone please suggest what to do?
Comment: First, it's not StackOverflow question. Second, use `sudo` Finally, if this requires you to ask for help - you are not ready to go live today
Comment: I have tried both with and without sudo.
Comment: (a) Check error log during httpd restart (`/var/log/httpd/error*`); (b) try `apache2ctl configtest`; (c) If nothing works, you might want to shutdown this instance & spin up a new one; (d) I would agree with @Felix, if you need to ask help on this, its bad idea to go live today!
Comment: Can you paste content of "/etc/apache2/ports.conf"
Answer: Try this: pidof httpd or pidof apache2 (depending on the distro running on that t2micro aws instance). If it returns any pid then kill that pid or those pids manually issuing a kill -9 pid then try restarting apache. If that doesn't work you should investigate the apache logs. That should give you more info about what is preventing apache to start and a possible way to fix the issue so you can start apache. Deploying a new instance is not going to help you to start the apache on your current instance and/or figure out the current issue.

Apache does not start on EC2


Universal $C^\ast$-algebra generated by the unilateral shift.

Question: Consider the Hilbert space $L^2(\mathbb{S}^1)$ and the Hardy subspace $\mathcal{H}(\mathbb{S}^1)$, along with the projection $\pi:L^2(\mathbb{S}^1)\to\mathcal{H}(\mathbb{S}^1)$. For each $f\in C(\mathbb{S}^1)$, let $T_f\in B(\mathcal{H}(\mathbb{S}^1))$ be the associated Toeplitz operator.
Let now $\mathcal{T}$ be the $C^\ast$-algebra generated by $\{T_f:f\in C(\mathbb{S}^1)\}$ and the compact operators $K$ on $\mathcal{H}(\mathbb{S}^1)$, called the Toeplitz algebra, which fits into the short exact sequence  $0\to K\to\mathcal{T}\overset{\sigma}{\to} C(\mathbb{S}^1)\to0$.
There is a couple of things I don't understand here (this is from the notes from my teacher):
How is this map $\sigma$ defined, and why is this sequence in fact short exact?
More importantly, the teacher mentions that $\mathcal{T}$ is in fact the universal $C^\ast$-algebra generated by $s$ and $s^\ast$ satisfying $s^\ast s=1$, and he hints at $S$ being the unilateral shift on $\ell^2(\mathbb{Z}_{\ge0})\cong\mathcal{H}(\mathbb{S}^1)$. How can one see/prove this?
Answer: The map $\sigma$ is the quotient map by the compacts. It is not hard to see that
$$
\mathcal T=\{T_f+K:\ f\in C(\mathbb S^1),\ K\ \text{ compact }\}=C^*(\{T_z\}).
$$
For this, one can show that $T_f$ is never compact, and that $T_fT_g-T_{fg}$ is always compact. Thus $\sigma $ is defined by $\sigma(T_f+K)=f$. From $T_f-T_g=T_{f-g}$, one can see that $\sigma$ is well-defined, and the other aforementioned properties, that it is a $*$-homomorphism.
Here is a sketch of the proof that $\mathcal T=C^*(\{T_z\})$. Write $\{e_n\}$ for the canonical orthonormal basis of $L^2(\mathbb S^1)$.

Show that $C^*(T_z)$ is irreducible. If a projection $P$ commutes with $T_z$, it commutes with $I-T_zT_z^*$, which is the projection onto the span of the constant function $e_0=1$. So $Pe_0=\lambda\,e_0$, with $\lambda=0$ or $\lambda=1$. In any case, $$Pe_n=PT_z^ne_0=T_z^nPe_0=\lambda T_z^ne_0=\lambda e_n.$$ Thus either $P=0$ of $P=I$.
Show that $C^*(T_z)$ contains the compact operators. Since $C^*(T_z)$ contains a compact operator ($I-T_zT_z^*$, for instance), and it is irreducible, we get that $C^*(T_z) $ contains the compact operators (this is definitely not a trivial result, it requires some work).
Show that $C^*(T_z)$ contains $\{T_f:\ f\in C(\mathbb S^1)\}$. These are limits of linear combinations of powers of $T_z$.
The steps above show that $\mathcal T\subset C^*(T_z)$. The reverse inclusion follows from the fact that $T_fT_g-T_{fg}$ is compact.

As for your second question, the Wold Decomposition lets you write any isometry as $$U\oplus \bigoplus_j S,$$ where $U$ is a unitary and $S$ the unilateral shift on $\ell^2(\mathbb N)$. We can then replace $S$ with $T_z$ (they are unitarily equivalent). As the universal C$^*$-algebra generated by a unitary is also $C(\mathbb S^1)$, we get that the C$^*$-algebra generated by any isometry is a quotient of $\mathcal T$.


SQL Error: ORA-00907: missing right parenthesis

Question: I am using Oracle SQL developer to create a basic table with the following command:
CREATE TABLE chartered_flight(
   flight_no NUMBER(4) PRIMARY KEY
   , customer_id FOREIGN KEY
   , aircraft_no FOREIGN KEY
   , flight_type VARCHAR2 (12)
   , flight_date DATE NOT NULL
   , flight_time TO_DATE 'HH:MI' NOT NULL
   , takeoff_at CHAR (3) NOT NULL
   , destination CHAR (3) NOT NULL
)

Where is the missing right parenthesis? Or is the syntax that I have used incorrect.
I have made the following changes:
CREATE TABLE chartered flight(
   flight_no NUMBER(4) PRIMARY KEY
   , customer_id NUMBER(6) REFERENCES [customer]([customer_id])
   , aircraft_no NUMBER(4) REFERENCES [aircraft]([aircraft_no])
   , flight_type VARCHAR2 (12)
   , flight_date DATE NOT NULL
   , flight_time INTERVAL DAY TO SECOND NOT NULL
   , takeoff_at CHAR (3) NOT NULL
   , destination CHAR (3) NOT NULL)

Now I get this error:
Error at Command Line:1 Column:23
Error report:
SQL Error: ORA-00922: missing or invalid option
00922. 00000 -  "missing or invalid option"
*Cause:
*Action:

I have a feeling it is something to do with TO_DATE or is it because I have not created my aircraft table yet so aircraft_no is missing? Can some one please help, thanks.
Comment: Don't surround table/column names with [ ].
Answer: There is no type called TO_DATE. To_DATE is used to convert a string to a date.
So the create statement should be something like
CREATE TABLE chartered_flight(
    flight_no NUMBER(4) PRIMARY KEY,
    customer_id FOREIGN KEY,
    aircraft_no FOREIGN KEY,
    flight_type VARCHAR2 (12),
    flight_date DATE NOT NULL,
    flight_time VARCHAR(4) NOT NULL,
    takeoff_at CHAR (3) NOT NULL,
    destination CHAR (3) NOT NULL)

You can use to_date when selecting data from the table. For example
Select to_date(flight_date, 'yyyy/mm/dd') from chartered_flight;

Comment: Wouldn't it be better to have a flight_time as a number in minutes, if that is the lowest unit of measurement you want to use, and then you can convert it into hours / days in code. I definitely wouldn't have a number stored as a varchar if at all possible. Bound to cause trouble.
Comment: but what if I want the time to be specific to just HH:MM please how do I set this? I see default oracle data type for date is just DD/MM/YY
Comment: You can possibly declare flight_time as varchar2 and then use a check constraint to validate the data.
Comment: where would I implement the check constraint? I think this is OTT maybe I should just leave it date as this is only for coursework.
Comment: @Ben yes i agree but he wants to include the ':'. I agree that number format can easily be formatted.
Answer: To specify foreign key constraint, you should either use inline  customer_id [type] REFERENCES [master_table_name]([master_column_name]) or out of line syntax : , CONSTRAINT [constraint_name] FOREIGN KEY(customer_id) REFERENCES [master_table_name]([master_column_name]) See more example here. Also, it usually makes sense to add indexes on foreign key columns.
For flight_time you probably need to use INTERVAL DAY TO SECOND type
Comment: I have made changes that you have suggested but now I get a new error please can you have a look thanks.
Comment: You don't need square brackets in the `CREATE TABLE`. In my answer I use them to specify that you have to put actual values, so you need `customer_id NUMBER(6) REFERENCES customer(customer_id)`
Comment: I have made that change but I am still getting the exact same error?! @a1ex07
Answer:
ALTER TABLE EMPLOYEE_DETAILS ADD (
  EMPLOYEE_ID NUMBER(10),
  EMPLOYEE NAME VARCHAR2(100),
  );

Above ALTER statement caused the below error.
Error report:
SQL Error: ORA-00907: missing right parenthesis
00907. 00000 -  "missing right parenthesis"
*Cause:
*Action:
How ever I have rectified my self and here is the correct one.

ALTER TABLE EMPLOYEE_DETAILS ADD (
  EMPLOYEE_ID NUMBER(10),
  EMPLOYEE_NAME VARCHAR2(100),
  );

Solution: There is a space in the name of second column which caused this error.
Thanks,
Manne


numpy.diagonal retornando cópia read-only mesmo na versão 1.10

Question: Estou fazendo um programa em Python onde preciso alterar os valores na diagonal de uma matriz. O seguinte trecho de código deve ser suficiente pra entender a ideia geral (ele altera para 2 o valor na primeira posição da diagonal principal da matriz):
import numpy as np
x = np.eye(2)
d = x.diagonal()
d[0] = 2

Segundo a documentação, na versão 1.9 o retorno dessa função havia passado a ser somente leitura, mas isso foi desfeito na versão 1.10 (que supostamente devolve uma referência para a matriz original):

In versions of NumPy prior to 1.7, this function always returned a
  new, independent array containing a copy of the values in the
  diagonal.
In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal,
  but depending on this fact is deprecated. Writing to the resulting
  array continues to work as it used to, but a FutureWarning is issued.
In NumPy 1.9 it returns a read-only view on the original array.
  Attempting to write to the resulting array will produce an error.
In NumPy 1.10, it will return a read/write view and writing to the
  returned array will alter your original array. The returned array will
  have the same type as the input array.

Bom, eu tinha a versão 1.9 instalada aqui (Windows 8) mas acabei de atualizá-la (usando pip install -upgrade numpy). Garantidamente a versão atual é a correta:
>>> np.version.version
'1.10.1'

Porém, mesmo assim, o código de exemplo acima gera o seguinte erro:
>>> import numpy as np
>>> x = np.eye(2)
>>> d = x.diagonal()
>>> d[0] = 2
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    d[0] = 2
ValueError: assignment destination is read-only

Há toda uma discussão a respeito das mudanças nas versões nesta thread - justamente de onde eu peguei o exemplo mínimo anteriormente apresentado - mas eu não encontrei nenhuma informação que contradiga a documentação.
Alguém pode oferecer alguma ajuda?
Answer: Então, o que acontece é que, como você viu, existe uma discussão muito grande sobre o que essa função deve retornar, havendo várias opiniões divergentes.
Se você acompanhar a issue referente a isso verá que ela foi marcada como tarefa para a versão 1.11.
Mas, para esclarecer esse comportamento, basta olhar o código: na versão 1.10.1 ela ainda continua fazendo a mesma coisa que na versão 1.9.3, isso é, a flag writeable continua sendo removida do array no fim da função.
Na documentação do método, diz que ele passará a ter o novo (ou velho) comportamento ainda na 1.10, dando a entender que isso ainda possa acontecer em minor releases. Mas, como ela foi marcada como tarefa para a 1.11, acredito que terá que esperar um pouco mais (mas isso é só minha especulação).


How to get ASAN to ignore child process?

Question: I'm trying to run my application with ASAN enabled to search for leaks and other errors but, since I'm using popen inside the application, sanitizer reports child process errors as well it seems (which I really do not care about and are confusing).
Is there a way to make it ignore child processes ?
My environment is: Fedora 26, gcc 7.3.1, libasan 7.3.1-6
Comment: ASAN cannot possibly do what you say it does. `popen` immediately replaces the forked process with another executable, and unless that executable was built with ASAN, ASAN cannot report anything about it. Can you provide a [mcve]?
Comment: Are you using `LD_PRELOAD`?
Comment: @yugr yes, is that the reason it affects child processes ?
Comment: Even if you preload libasan it should not affect the child process built without -fsanitize=address.
Comment: @n.m. Preloading would still affect them because Asan will detect errors in heap-allocated memory accessed via standard libc APIs. This is due to libc interceptors inside `libasan.so`.
Comment: @yugr this is not what my experience shows. Perhaps it will catch certain class of errors but it didn't catch buffer overflows in malloc'd memory for me.
Comment: @n.m. It will catch buffer overflow done by `memcpy` or `strcpy` (but beware that gcc sometimes "optimizes" them into inline loops and in such cases they will of course not be instrumented).
Comment: @yugr indeed. I wonder why it doesn't catch the problem at `free` time.
Answer: I suspect that you are using LD_PRELOAD=libasan.so which will cause Asan runtime to be preloaded to child processes. This will cause some limited form of sanitization because runtime will intercept and sanitize calls to standard libc functions like malloc or memcpy.
There is no builtin way to disable this inside Asan so your best bet would be to reset LD_PRELOAD at program start:
int main() {
# ifdef __SANITIZE_ADDRESS__
  // Do not sanitize child processes
  // TODO: strip only libasan.so, keep everything else
  unsetenv("LD_PRELOAD");
# endif

Comment: I ran into a problem with this approach: I *think* that dynamically loaded libraries that are loaded *after* `unsetenv` do not work and even make ASan stop working properly. I found that [ld](http://man7.org/linux/man-pages/man8/ld.so.8.html) provides the option to run programs via `--preload` (as of glibc version 2.30), which does not affect child processes, but I haven't tested that.
Comment: @ingomueller.net It's hard to comment without a reprocase but I would be very surprised if `unsetenv` of `LD_PRELOAD` influenced behavior of Asan or any other shlib in the same process.


Como impedir que uma aplicação React Native retorne ao clicar no BackButton usando React Navigation

Question: Olá, estou criando uma aplicação em React Native, e para as navegações eu tenho trabalhado com o plugin React Navigation. A estrutura do meu projeto está assim:
import React from 'react';
import { View, Text, Button } from 'react-native';
import { FluidNavigator } from 'react-navigation-fluid-transitions';

// tela de splash
export default SplashScreen extends React.Component {
  componentDidMount = () =>
    setTimeout(() => this.props.navigation.navigate('Login'), 500);

  render = () =>
    <View>
    <Text>SplashScreen</Text>
  </View>;
}

// tela de login de usuario
export default LoginScreen extends React.Component {
  goToDashboard = () => this.props.navigation.navigate('Dashboard');
  goToRegister = () => this.props.navigation.navigate('Register');
  render = () =>
    <View>
      <Text>LoginScreen</Text>
      <Button onPress={goToDashboard} title="Sign in" />
      <Button onPress={goToRegister} title="Sign up" />
    </View>
  }
}

// tela de registro de usuario
export default RegisterScreen extends React.Component {
  render = () => <View><Text>RegisterScreen</Text></View>;
}

// tela de dashboard (após o usuário estar logado)
export default DashboardScreen extends React.Component {
  render = () => <View><Text>DashboardScreen</Text></View>;
}

// navigator contendo as telas
const Navigator = FluidNavigator({
  Splash: { screen: SplashScreen },
  Login: { screen: LoginScreen },
  Register: { screen: RegisterScreen },
  Dashboard: { screen: DashboardScreen }
})

export default App extends React.Component {
  render(){
    return <View><Navigator/></View>
  }
}

Meu problema está nas navegações. Quando o usuário clica no botão voltar, ele vai para a tela anterior e isso me complica... eu preciso que a navegação seja na seguinte relação:

SplashScreen => LoginScreen
LoginScreen <=> RegisterScreen
LoginScreen  => DashboardScreen
RegisterScreen => DashboardScreen

Eu até tentei resetar o index usando o NavigationActions mas isso atrapalha as animações que estão na tela (por causa do react-navigation-fluid-transitions).
Também tentei bloquear o evento do BackButton assim como em alguns tutoriais, só que se eu bloqueio ele na tela de Screen, ele passa a dar pau em todas as telas, impedindo que eu consiga voltar para a tela de Login na tela de Register e consequentemente para as outras telas que virão na aplicação.
O que eu preciso fazer para que eu impeça (dentro da tela que eu quero impedir) para que ela não possa voltar até 'X' tela?
Comment: Você já tentou setar em cada página o retorno que cada uma deve ter?
Comment: Então eu costumo determinar de maneira direta a rota que deve seguir ao clicar no botão de retorno. Você pode fazer adicionando no construtor da sua página o seguinte código: `BackHandler.addEventListener('hardwareBackPress', function() {
      Actions.rota_que_deseja();
      return true;
    }); `
Comment: Funcionou utilizando  o `navigatePrev()`?
Comment: não entendi... poderia me dar um exemplo? sou novo com react-native e realmente não consegui ver o que me falou...
Comment: eu tentei fazer algo assim, mas se eu faço 1 vez, a função padrão de voltar buga e não funciona normalmente. Sibem que eu poderia forçar a navegação a voltar com um `this.props.navigation.navigatePrev()`
Answer: Com base no que o @sant0will disse nas respostas, eu consegui "resolver" o problema ao adicionar em todas as telas um tratamento específico para o BackHandler, assim:
export default SplashScreen extends React.Component {
  //...
  componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', () => { return true; });
  }
}

// tela de login de usuario
export default LoginScreen extends React.Component {
  //...
  componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', () => { return true; });
  }
}

// tela de registro de usuario
export default RegisterScreen extends React.Component {
  //...
  componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', () => {
      this.props.navigation.navigate('Login');
      return true;
    });
  }
}

// tela de dashboard (após o usuário estar logado)
export default DashboardScreen extends React.Component {
  //...
  componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', () => { return true; });
  }
}

Sinceramente não gostei de resolver assim porque me cheira a "recurso técnico" mas como funcionou e é como vai ficar...
Comment: Boaaa, que bom que funcionou.
Comment: valei parceiro! =D
Answer: Pelo que sei no react navigation existe uma função própria que se chama goBack que volta a tela anterior, simplesmente você irá importar o react-navigation/native, e usar o useNavigation do mesmo, e assim usar o onPress dentro do seu "botão"
Exemplo:
<TouchableOpacity
                onPress={() => navigation.goBack()}
            >
                <Text>
                    Voltar
                </Text>
            </TouchableOpacity>

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Is it a good practice to save "dependent value" in the database?

Question: We are developing a game that has heroes and soldiers. All of them can level up. However, as they leveled up, different algorithms are used to get their attributes for their next level.

For heroes, their attributes are fixed values configured by designers. That is, for every level 3 mage, their attributes are totally identical.
For other soldiers, their attributes are generated using a formula in the script, with some random noise. That is, two rabbit of the same level are not the same.

As we develop, we first implement the soldier part, then the hero part. For soldiers, as their attribute values are generated, we store each soldier attributes into the database. As the development goes on, we did the same for heroes. But is it a good practice? I mean actually we can get all the attributes from designers XML file as long as level and class are provided, save all attributes to the database seems a kind of repeat. We are taught to avoid repeat, aren't we?
For more, we have some bag grids unlocked for every 5 levels as the hero levels up, is it good to save those unlock information to the database?
Answer: A good rule of the thumb coming from experience, if you store value in database, it should have priority over any default values. If it is the case, the design is correct. If no, it's a redundance, which should be avoided. How would future developers react if they notice that the values in the game are other from those stored in database? The first expected reaction would be - oh, there's an error, we need to fix it.
Comment: I got what you mean, but the problem here is, we stored information exactly the same as in XML files. Is it good that we do not store that and just read it from XML files?
Comment: If in case of difference between database and XML you would take the value from XML, than better not store that value in database.


Member functions with react hooks

Question: I've recently started working with hooks and have a relatively simple question about "member functions". Previously, member functions worked like this in a react class:
class App extends React.Component {
  constructor(props) {
    this.state = { toggle: false };
    this.toggle = this.toggle.bind(this);
  }

  // Member function
  toggle() {
    this.setState(toggle: !this.state.toggle);
  }

  render() {
    <button onClick={this.toggle}>Toggle Me!</button>
  }
}

However, now with React Hooks, I'm not using class components, but still need a function to do stuff like this. Is it poor practice to do something like this? If so, what is the best practice here?
const App = () => {
  const [toggle, setToggle] = useState(false);

  // Kind of like a "member" function
  const toggleState = () => setToggle(!toggle);

  return <button onClick={toggleState}>Toggle Me!</button>;
}

Answer: Your code looks good. It works for the absolute majority of cases, but if you want to create a function that gets memoized between renders you can use the useCallback hook so that e.g. the props sent to a PureComponent will be the same and doesn't cause unnecessary renders.

const { useState, useCallback, PureComponent } = React;

const App = () => {
  const [toggle, setToggle] = useState(false);
  const toggleState = useCallback(() => setToggle(toggle => !toggle), []);

  return (

{toggle ? 'On' : 'Off'}

      <VeryExpensiveComponent onClick={toggleState} />

  );
};

class VeryExpensiveComponent extends PureComponent {
  render() {
    console.log("Rendered expensive component");
    return <button onClick={this.props.onClick}>Toggle Me!</button>;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

Comment: you could use useMemo instead of PureComponent.
Comment: @ArberSylejmani Sure, hence the "e.g." in my answer. There are more than one case when it's appropriate.
Comment: there are also case when re-rendering doesn't create performance issues, such in the question, so the use of useCallback's optimization costs more than not having the optimization

Member functions with react hooks


How Do I adjust My Blog Post To Reach The Left and Right Sides?

Question: Here is the link to the post I am trying to adjust its widths to reach the edges of my screen (On Mobile Devices). https://mybloggertestpage.blogspot.com/p/admin-demo.html
The output on computer is okay but there are too many vacant spaces on the left and right side of the post on mobile view.
Click here for the screenshot of how my post shows on my phone. I am not allowed to embed images to my posts yet
I have tried to adjust the widths from my blogger code.
I changed the value of my (outer-wrapper to 100%;)
#outer-wrapper{max-width:100%;box-shadow:none}
.row{width:100%}

Then,
I changed main-wrapper widths to auto
#main-wrapper{width:auto}

I also changed my article widths size to auto.
article.my-wrapz {
    width: auto;
    margin: 0 auto;padding-left: 0!important;    float: none!important;
}

After making these changes to the code, I noticed the widths were adjusted a little bit but there were still much bigger spaces on the right and left side of my post (On Mobile Device).
I will be so happy if I can get help on this issue. I just want my post  to reach the edges of the screen on mobile devices.
Here is the full CSS code of my blogger website (Mobile View).

Comment: Which mobile device are you using? I just looked at your blog on my phone and it doesn't have any issue.
Comment: I use a Tecno KA70, I just edited my post, I have attached a screenshot of how my blog post shows on my mobile device. Please check the image to understand me better.
Answer: Possibly try this?
#main-wrapper {
  width: 100%;
}

Or even adding that code at the appropriate media if its just a mobile issue.  Like this:
@media (max-width: 1200px){
  #main-wrapper {
    width: 100%;
}
  }

Edit, I think I found it. Add this to your CSS:
.profile-body {
 margin: 0;
}

Comment: I have tried that, please check the result on your mobile.
Comment: I think I found the issue, I just updated the answer.
Comment: @BABOSAMMONG Try adding this to your CSS: `.profile-body {margin: 0;}`
Comment: John, Thank you so much for your time, I really appreciate you. I have updated the code but I am not still getting the result I want. My aim is to make the profile card to extend to the edges of the screen of my mobile device.
Comment: @BABOSAMMONG Please revert back to what you had when you first asked this question and then only add the `.profile-body {margin: 0;}` Ignore the first 2 parts of code in my answer.
Comment: John!!! thank you so so so so much! It worked! check it now! I can't believe my eyes!
Comment: @BABOSAMMONG Looks good.  It seems to be working.


Diffuse lighting artifacts (OpenGL 4)

Question: I'm trying to implement simplest possible diffuse lighting after reading a few tutorials, but fail miserably.
I load 3d mesh from Wavefront obj file and if I don't apply lighting, it looks just fine. But, when I do apply lighting, the animal looks like a chessboard and the cube is messed up even more:
animal comparison (with normals)
cube comparison (with normals)
Here is the vertex shader:
#version 400

layout (location = 0) in vec4 a_position;
layout (location = 1) in vec3 a_texCoords;
layout (location = 2) in vec3 a_normal;

uniform mat4 u_viewProjection;
uniform mat4 u_model;

out vec3 v_fragPos;
out vec3 v_fragNormal;

void main() {
    v_fragPos = a_position.xyz;
    v_fragNormal = a_normal;
    gl_Position = u_viewProjection * a_position;
}

I pass fragment position and normals to the fragment shader as-is because I'm not applying any model transformations, I simply assume that a model already has world coordinates after loading it from file (forget about u_model uniform, it's not used for now).
Then, the fragment shader:
#version 400

uniform vec3 u_lightPos;
uniform vec3 u_lightColor;

uniform vec3 u_diffuseColor;
uniform vec3 u_specularColor;
uniform vec3 u_ambientColor;

in vec3 v_fragPos;
in vec3 v_fragNormal;

out vec4 o_fragColor;

void main() {
    vec3 lightDir = u_lightPos - v_fragPos;
    float cosTheta = max(dot(normalize(v_fragNormal), normalize(lightDir)), 0.0);
    vec3 diffuseContribution = cosTheta * u_lightColor;

    o_fragColor = vec4(u_diffuseColor * diffuseContribution, 1.0);
}

No model or normal matrices used, because no rotations (or scale) are applied to model for now.
I thought about incorrect normals, but at least a simple cube should have correct ones, right?
Also, maybe I should mention that I'm using NSOpenGLView under MacOS.
Any help will be appreciated.
Thank you!
UPDATE:
Adding VBO setup.
This is how single vertex looks like:
struct Vertex1P1N1UV {
        glm::vec4 mPosition;
        glm::vec3 mTextureCoords;
        glm::vec3 mNormal;

        Vertex1P1N1UV();
        Vertex1P1N1UV(glm::vec4 position, glm::vec3 texcoords, glm::vec3 normal);
};

I initialize my VAO like this
auto* VAO = new GLVertexArray<Vertex1P1N1UV>();
VAO->initialize(subMesh.vertices(), GLVertexArrayLayoutDescription({
                static_cast<int>(glm::vec4::length() * sizeof(GLfloat)),
                static_cast<int>(glm::vec3::length() * sizeof(GLfloat)),
                static_cast<int>(glm::vec3::length() * sizeof(GLfloat)) }));

VAO initialize method
void initialize(const std::vector<Vertex>& vertices, const GLVertexArrayLayoutDescription& layoutDescription) {
    bind();

    mVertexBuffer.initialize(vertices);

    GLuint offset = 0;
    for (GLuint location = 0; location < layoutDescription.getAttributeSizes().size(); location++) {
         glEnableVertexAttribArray(location);
         GLsizei attributeSize = layoutDescription.getAttributeSizes()[location];
         glVertexAttribPointer(location, attributeSize / sizeof(GLfloat), GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void *>(offset));
         offset += attributeSize;
     }
 }

And buffer initialize method
void initialize(const std::vector<Vertex>& data) override {
     bind();
     glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(Vertex), data.data(), GL_STATIC_DRAW);
}

Vertex will become Vertex1P1N1UV in this case
UPDATE:
Implemented normal visualization (reuploaded screenshots, scroll to top).
What bothers me is that I can see normals through the mesh, like it's transparent despite opaque color. Is this a depth testing problem?
Comment: @Vallentin: Linear interpolation denormalizes normal vectors, so renormalizing them is not optional.
Comment: @NicolBolas Ohh right. Guess I shouldn't go on Stack Overflow first thing when I wake up.
Comment: @Vallentin updated the question, please tell me if I forgot some relevant information
Comment: Could you update the questions with a display of your normals please ?
Comment: @Zouch working on normal visualization right now, will update as soon as I can
Answer: After 2 days of struggling I found the problem.
I did not enable depth buffer on NSOpenGLView. That is one line of code.
If someone stumbles upon this, he can look here OpenGL GL_DEPTH_TEST not working
for a solution.

Diffuse lighting artifacts (OpenGL 4)


Views 3.0 virtual numeric field handler

Question: I've created a custom handler for a counter virtual field for my module but it seems that I am doing something wrong since I can't sort it nor filter on it as a numeric field.
Any one can tell what I need to add to the query method in order to actually place the values in the tables for views to use it?
class mymodule_handler_field_count_for_interval extends views_handler_field_numeric {

    function query() {
        $this->ensure_my_table();
        $this->add_additional_fields();
    }

    function pre_render(&$values){
        foreach ($values as $key=>$value){
            $values[$key]->count=$this->my_module_count($value->nid);
        }
    }

    function render($values) {
        $count = $values->count;
        return $count;
    }

    function mymodule_count($nid){
        $count=0;
        if (isset($this->view->filter['timestamp'])) {
            $filter_operator=strtoupper($this->view->filter['timestamp']->operator);
            $filter=$this->view->filter['timestamp'];
            $query=db_select('my_module_table','s');

                switch ($filter_operator){
                    case '<':
                    case '<=':
                    case '>':
                    case '>=':
                        //building the query
                        $query->condition('timestamp',strtotime($filter->value['value']),$filter_operator)
                        ->condition('nid',$nid,'=')
                        ->fields('s',array('sid'))
                        ->addExpression('COUNT(sid)','sid_count');
                        $result=$query->execute();
                        foreach ($result as $count_row){
                            //counting
                            $count+=$count_row->sid_count;
                        }
                        break;
                    case 'between':
                    case 'not between':
                        //building the query

                        $query->condition('timestamp',array(strtotime($filter->value['min']),strtotime($filter->value['max'])),$filter_operator)
                        ->condition('nid',$nid,'=')
                        ->fields('s',array('sid'))
                        ->addExpression('COUNT(sid)','sid_count');
                        $result=$query->execute();
                        foreach ($result as $count_row){
                            //counting
                            $count+=$count_row->sid_count;
                        }
                        break;
                }
        }
        return $count;
    }
}

To clarify a bit the question here is my custom module table in the install file(hook_schema).
function my_module_schema(){
$schema['my_module_table']=array(
        'description'=>t('the base table for our statistics'),
        'fields'=>array(
            'sid'=>array(
                'description'=>t('The index field'),
                'type'=>'serial',
                'unsigned'=>TRUE,
                'not null'=>TRUE,
            ),
            'uid'=>array(
                'description'=>t('The user UID'),
                'type'=>'int',
                'unsigned'=>TRUE,
                'not null'=>TRUE,
            ),
            'nid'=>array(
                'description'=>t('The node NID'),
                'type'=>'int',
                'unsigned'=>TRUE,
                'not null'=>TRUE
            ),
            'tid'=>array(
                'description'=>t('The node TID for the category taxonomy.'),
                'type'=>'int',
                'unsigned'=>TRUE,
                'not null'=>FALSE
            ),
            'access_type'=>array(
                'description'=>t('The access type: 0=>web, 1 =>mobile, 2=>barcodescan'),
                'type'=>'int',
                'size'=>'tiny',
                'unsigned'=>TRUE,
                'not null'=>TRUE,
            ),
            'timestamp'=>array(
                'description'=>t('The time of viewing'),
                'type'=>'int',
                'unsigned'=>TRUE,
                'not null'=>TRUE
            ),
        ),
        'unique keys' => array(
            'sid' => array('sid'),
        ),
    );
    return $schema;
}

As you can see it would be very difficult to keep another table with counters because the data is modified per second/minute and users accessing the nodes are different. so what I'd like to understand is how to make views see that I am building a numeric virtual field and where to put it in the views tables so it does the query from its internal tables. Is that possible?
Answer: If you want to be able to sort by values which aren't in the database you definitive need to write the data into the database.
Once you have this you can write a views integration for this field in the database and you are fine.
Comment: since is a matter of avoiding a few more queries for each access replacing it with 1 query at presentation (views) I would prefer to use some kind of virtual table inside the view object. is that possible?
Comment: No it's not, you can _only_ use tables in sql, because that's what views uses for filtering.
Comment: just to be sure. I hope you understand that I cannot vote for both answers even if both are correct. I will go for the first option here.
Answer: Fields, filtering and sorting are implemented by separate handlers. In your case, since your data is virtual, you will need to write your own handlers. You should probably look at extending views_handler_filter_numeric and views_handler_sort. Then in your mymodule.views.inc file you would have something like:
$data['mytable']['count_for_interval'] = array(
 'title' => t('Count for interval'),
 'help' => t('Number of counts in interval.'),
 'field' => array(
   'handler' => 'mymodule_handler_field_count_for_interval',
   'click sortable' => TRUE,
 ),
 'filter' => array(
   'handler' => 'mymodule_handler_filter_count_for_interval',
 ),
 'sort' => array(
   'handler' => 'mymodule_handler_sort_count_for_interval',
 ),
 'argument' => array(
   'handler' => 'views_handler_argument_numeric',
 ),

);
Comment: I agree with you, but since I know for sure that I am creating a **numeric field** I would like to avoid creating my own filter, sort, argument handler for it. Is that possbile?
Comment: Possible? Perhaps, but above you are already rewriting code that is in the existing handlers I mentioned. You will write less and be able to take advantage of built-in features by extending what's built into Views already.

Views 3.0 virtual numeric field handler


Why does area of triangle calculated geometrically and by integration do not match in my calculation?

Question: I'm working on a probability problem where I need to calculate the area of a triangle between the square $ \left[ (1,1),\,(1, -1),\,(-1, 1),\,(-1,-1) \right] $ and the inequality $ x + y \leqslant z $. To keep things simple, let's focus just on the bottom part of the square, between $x = -1$, $y = -1$, and $y \leqslant =-x$.
The geometric approach boils down to this: Given the boundary $ x + y = z $ calculate the distance from the intersections with the sides of the square $x = -1$ and $y = -1$ as a function of $z$ calculating the distance those two points to the point $(-1,-1)$.
The first of those is $P = (z+1, -1)$ and the second $Q=(-1, z+1)$. Calculating the euclidian distance $d_{PO} = \sqrt{ (z+2)^2} = d_{QO}$ where $O = (-1, -1)$.
With these distances, we have that the area of the triangle is $ \frac{(z+2)^2}{2}$.
Here is a picture to help with this argument:

And now here is the integration argument, which should match the above calculation, but doesn't, and I can't figure out where my mistake is.
Using the following picture to guide the creation of the independent intervals to apply Fubini's theorem:

Integrating first with respect to $y$
$$
\begin{align}
\int_{-1}^{1}\int_{-1}^{z - x} \,dy\,dx &= \\
 \int_{-1}^{1} \left( z - x + 1 \right) \, dx &= \\
 zx - x^2 + x \biggr\rvert^{1}_{x = -1} &= \\ &2z + 2
\end{align}
$$
Which is clearly wrong. What am I getting wrong?
Comment: If you want $x, y \ge -1$ and $x + y \le z$, $x$ might not be able to go all the way to $1$.
Comment: I don't think you want to integrate all the way to $x=1$
Answer: For $\bf z\leq 0$, the line $x+y=z$ intercepts the boundary for the square at points $(-1, z+1)$ and $(z+1, -1)$ .
You already used this fact to measure the sides of the triangle, so likewise use it to identify the bounds for the integration domain.
$$\lVert\triangle(-1,-1)(-1,z+1)(z+1,-1)\rVert =\int_{-1}^{z+1}\int_{-1}^{z-x}\mathrm d y\,\mathrm d x $$


How do I theme the user profile page?

Question: What is the best / easiest way to theme the user profile page? I'm building a talk radio website and registered members will provide news articles publically avail. eventually there will be thousands of registered users.
I'm worried that I will figure out an answer that works but isn't correct and will force me to go back and rewrite later on.
I don't know if I should use views or just straight code the page-user.tpl - if I straight code,  what function gets the uid from the /user/xx url? if I use views how do I assign the view to the pages in /user/xx
For some reason I cannot find any complete info on this; either it's a great secret or I'm missing something really simple. thank you!
Comment: I just want a basic user profile page that a registered user can customize with a avatar, bio, etc, displays a summary of their recent activity like any articles they've written and where unregistered visitors can search for and look at.

I just don't know how I should take my first step and I'm worried that I'll find a way to make it work but it won't be the right way and I'll have to do a total rewrite once the user database gets bigger.
Comment: Though you have written many things here but still its not clear what you want to achieve, design or functionality. At one place you are asking about theming the profile page of user & ending with giving functionality such as user activity, info etc. Please clarify
Comment: possible duplicate of [How to theme the PAGE template for user account?](http://drupal.stackexchange.com/questions/65553/how-to-theme-the-page-template-for-user-account)
Answer: I would suggest you to use Panels and Views modules and optionally Profile2.
You will add some fields to user account or to the user profile if you installed Profile2. Then enable the 'User profile template' page under admin/structure/pages and add a panel variant, select a layout and place the content or fields. If you have Profile2, then you need to add it as a relationship 'Profile2 from user' under the 'Contexts' menu of the panel page. I'm not going into details about how to use panels.
To display the summary of user's recent activity, you should setup a view with a contextual filter of user id, preferably a 'Content pane' display, then you need to place this content pane into you user panel.
It is not a great secret how to build a user profile page, but it's completely dependent of what you want to have. If you have any difficulties implementing the steps I wrote, you can update your question or post another more specific question.
Comment: I've heard panels slows down the site which is why I didn't give it much thought. Is there any truth to that?
Comment: If you use caching it is much better than core blocks.
Answer: I decided to use a combination of VIEWS and template overrides, hooks, css and custom PHP.
Comment: Could you summarize this a little bit?  This answer won't really help anyone else who reads it in the future.
Comment: in the end, Drupal 7 was so designer unfriendly I gave up on it. so while I figured some solutions to problems I ran into, drupal 7 turned out to be too complex for me to understand well enough to design the way I wanted. (I'm not a backend guy) however drupal 8 beta is stable enough and is very designer friendly so I'm working with it instead.

How do I theme the user profile page?


Criar usuário e banco de dados MySQL via PHP

Question: 1 - É possível criar novo usuário e banco de dados MySQL via script PHP?
2 - No caso afirmativo, implicaria em algum risco de segurança tal ação?
Objetivo: Tenho um sistema rodando (CMS próprio) onde o usuário faz praticamente tudo para se ativar no servidor, sendo que, este será alocado em um subdomínio em nosso servidor, portanto, a criação de um banco de dados para este novo usuário para este novo subdomínio precisaria ser de forma automatizada no momento do cadastro, o que hoje não ocorre e toda vez temos que criar novo usuário e banco de dados para um novo cadastro. Aceito sugestões se tiverem outros caminhos.
Detalhes: VPS rodando Linux / WHM(11.52.0) / cPanel(184.108.40.206) / MySQL(5.6.23) / PHP(5.5)
Answer: 1 - Sim se o usuário que o script php roda tiver "GRANT OPTION", ele poderá criar outros usuários e dar permissões, de nada até a sua permissão equivalente.
2 - Como se diz, a corrente é forte tanto quanto o elo mais fraco, depende da forma como seu php for montado. Fora isso tudo é perfeitamente possível da forma como você pretende.
Comment: Marcelo, sua resposta sanou parte da dúvida, porém em sua resposta não mencionou sobre criar banco de dados, e sim apenas criar usuários, sabe se com GRANT OPTION isso também é possível? Estou usando a própria classe do cPanel.
Answer: Eu fiz assim:
<!DOCTYPE html>

        <meta charset="UTF-8" content="viewport">
        <meta name="viewport" content="width=device-width">
        <title>Criando Banco de Dados...</title>
        <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" media="screen">

    <form action="" method="post">
        <fieldset form="formcreatedb">
            <legend>Criando Database</legend>
                <input name="nome" class="fcampo" required maxlength="50">
                <input type="submit" class="button" value="Criar Banco..." >

        </fieldset>

    </form>

<?php

$nome = $_POST['nome'];

// Create database
$sql = "CREATE DATABASE IF NOT EXISTS $nome;";
if (mysqli_query($conn, $sql)) {
    echo "Banco";
} else {
    echo "Error creating database: " . mysqli_error($conn);
}

mysqli_close($conn);

?>


View page displays "Page not found" error but previously worked

Question: I am working on a site at the moment with a View of "properties".  The view used to function perfectly but for some reason now displays a "Page not found" error when trying to access the page and during the Views AJAX preview, displays a 404 error when it tries to render. This has only started to happen in the last couple of days.
I've tried clearing all caches (inc Views cache), rebuilding permissions and deleting the View and importing it again but nothing seems to work.  It only happens with this particular View, all others on the site function correctly.
The exported View is shown below.  The version of views is 2.1.2.
Edit for new information:

There is no menu entry assigned in the View but there is a menu item in the Primary Links. There are no particular access rules for the it either, everyone is allowed to access every View
Menu has been rebuilt and all caches flushed and rebuilt
I had it briefly working by disabling the Boost module.  I had a warning that Boost's .htaccess file was not properly configured, so I reconfigured the .htaccess file and I then enabled the module again that didn't work.  I then disabled Boost again, but it still didn't work, even after restoring Drupal's default .htaccess file.

-
$view = new view;
$view->name = 'properties_listing_2';
$view->description = 'Properties Listing 2';
$view->tag = '';
$view->view_php = '';
$view->base_table = 'node';
$view->is_cacheable = FALSE;
$view->api_version = 2;
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->override_option('fields', array(
  'field_property_image_fid' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '

No image available',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 1,
    'label_type' => 'none',
    'format' => 'property-page-image_linked',
    'multiple' => array(
      'group' => 1,
      'multiple_number' => '1',
      'multiple_from' => '0',
      'multiple_reversed' => 0,
    ),
    'exclude' => 0,
    'id' => 'field_property_image_fid',
    'table' => 'node_data_field_property_image',
    'field' => 'field_property_image_fid',
    'override' => array(
      'button' => 'Override',
    ),
    'relationship' => 'none',
  ),
  'title' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 1,
    'exclude' => 0,
    'id' => 'title',
    'table' => 'node',
    'field' => 'title',
    'override' => array(
      'button' => 'Override',
    ),
    'relationship' => 'none',
  ),
  'field_price_value' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 1,
      'text' => '[field_price_value] pm',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 0,
    'label_type' => 'none',
    'format' => 'default',
    'multiple' => array(
      'group' => TRUE,
      'multiple_number' => '',
      'multiple_from' => '',
      'multiple_reversed' => FALSE,
    ),
    'exclude' => 0,
    'id' => 'field_price_value',
    'table' => 'node_data_field_price',
    'field' => 'field_price_value',
    'relationship' => 'none',
  ),
  'body' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 1,
      'max_length' => '190',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 1,
    ),
    'empty' => '',
    'hide_empty' => 1,
    'empty_zero' => 0,
    'exclude' => 0,
    'id' => 'body',
    'table' => 'node_revisions',
    'field' => 'body',
    'relationship' => 'none',
  ),
  'field_number_bedrooms_value' => array(
    'label' => 'Beds',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 0,
    'label_type' => 'custom',
    'format' => 'default',
    'multiple' => array(
      'group' => TRUE,
      'multiple_number' => '',
      'multiple_from' => '',
      'multiple_reversed' => FALSE,
    ),
    'exclude' => 0,
    'id' => 'field_number_bedrooms_value',
    'table' => 'node_data_field_number_bedrooms',
    'field' => 'field_number_bedrooms_value',
    'relationship' => 'none',
  ),
  'field_available_date_value' => array(
    'label' => 'Available',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 0,
    'label_type' => 'custom',
    'format' => 'short',
    'multiple' => array(
      'multiple_number' => '',
      'multiple_from' => '',
      'multiple_to' => '',
      'group' => '',
    ),
    'repeat' => array(
      'show_repeat_rule' => '',
    ),
    'fromto' => array(
      'fromto' => 'both',
    ),
    'exclude' => 1,
    'id' => 'field_available_date_value',
    'table' => 'node_data_field_available_date',
    'field' => 'field_available_date_value',
    'override' => array(
      'button' => 'Override',
    ),
    'relationship' => 'none',
  ),
  'phpcode' => array(
    'label' => 'Available',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'value' => '<?php

print(date(\'jS M Y\', strtotime($data->node_data_field_price_field_available_date_value)));

?>',
    'exclude' => 0,
    'id' => 'phpcode',
    'table' => 'customfield',
    'field' => 'phpcode',
    'relationship' => 'none',
  ),
  'field_furnishing_value' => array(
    'label' => 'Furnished',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 0,
    'label_type' => 'custom',
    'format' => 'default',
    'multiple' => array(
      'group' => TRUE,
      'multiple_number' => '',
      'multiple_from' => '',
      'multiple_reversed' => FALSE,
    ),
    'exclude' => 0,
    'id' => 'field_furnishing_value',
    'table' => 'node_data_field_furnishing',
    'field' => 'field_furnishing_value',
    'override' => array(
      'button' => 'Override',
    ),
    'relationship' => 'none',
  ),
  'field_property_type_value' => array(
    'label' => 'Property Type',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 0,
    'label_type' => 'widget',
    'format' => 'default',
    'multiple' => array(
      'group' => TRUE,
      'multiple_number' => '',
      'multiple_from' => '',
      'multiple_reversed' => FALSE,
    ),
    'exclude' => 0,
    'id' => 'field_property_type_value',
    'table' => 'node_data_field_property_type',
    'field' => 'field_property_type_value',
    'relationship' => 'none',
  ),
  'field_location_nid' => array(
    'label' => 'Locale',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 0,
    'label_type' => 'custom',
    'format' => 'plain',
    'multiple' => array(
      'group' => TRUE,
      'multiple_number' => '',
      'multiple_from' => '',
      'multiple_reversed' => FALSE,
    ),
    'exclude' => 0,
    'id' => 'field_location_nid',
    'table' => 'node_data_field_location',
    'field' => 'field_location_nid',
    'relationship' => 'none',
  ),
  'view_node' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'text' => 'More details',
    'exclude' => 1,
    'id' => 'view_node',
    'table' => 'node',
    'field' => 'view_node',
    'relationship' => 'none',
  ),
  'nid' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 0,
    'exclude' => 1,
    'id' => 'nid',
    'table' => 'node',
    'field' => 'nid',
    'relationship' => 'none',
  ),
  'nothing' => array(
    'label' => '',
    'alter' => array(
      'text' => '[view_node]     Email to friend',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'exclude' => 0,
    'id' => 'nothing',
    'table' => 'views',
    'field' => 'nothing',
    'relationship' => 'none',
  ),
));
$handler->override_option('filters', array(
  'type' => array(
    'operator' => 'in',
    'value' => array(
      'property' => 'property',
    ),
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'type',
    'table' => 'node',
    'field' => 'type',
    'override' => array(
      'button' => 'Override',
    ),
    'relationship' => 'none',
  ),
  'status' => array(
    'operator' => '=',
    'value' => '1',
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'status',
    'table' => 'node',
    'field' => 'status',
    'override' => array(
      'button' => 'Override',
    ),
    'relationship' => 'none',
  ),
  'field_general_location_value_many_to_one' => array(
    'operator' => 'or',
    'value' => array(),
    'group' => '0',
    'exposed' => TRUE,
    'expose' => array(
      'use_operator' => 0,
      'operator' => 'field_general_location_value_many_to_one_op',
      'identifier' => 'general_location',
      'label' => 'Location',
      'optional' => 1,
      'single' => 1,
      'remember' => 0,
      'reduce' => 0,
    ),
    'id' => 'field_general_location_value_many_to_one',
    'table' => 'node_data_field_general_location',
    'field' => 'field_general_location_value_many_to_one',
    'override' => array(
      'button' => 'Override',
    ),
    'relationship' => 'none',
    'reduce_duplicates' => 0,
  ),
  'distance' => array(
    'operator' => 'dist',
    'value' => array(
      'latitude' => '',
      'longitude' => '',
      'postal_code' => '',
      'country' => 'uk',
      'php_code' => '',
      'nid_arg' => '',
      'nid_loc_field' => 'field_postcode_location',
      'uid_arg' => '',
      'search_distance' => '',
      'search_units' => 'mile',
    ),
    'group' => '0',
    'exposed' => TRUE,
    'expose' => array(
      'use_operator' => 0,
      'operator' => 'distance_op',
      'identifier' => 'distance',
      'label' => '',
      'user_location_choose' => 0,
      'optional' => 1,
      'remember' => 0,
    ),
    'identifier' => 'dist',
    'origin' => 'postal_default',
    'id' => 'distance',
    'table' => 'location',
    'field' => 'distance',
    'relationship' => 'none',
    'gmap_macro' => '',
  ),
  'field_property_type_value_many_to_one' => array(
    'operator' => 'or',
    'value' => array(),
    'group' => '0',
    'exposed' => TRUE,
    'expose' => array(
      'use_operator' => 0,
      'operator' => 'field_property_type_value_many_to_one_op',
      'identifier' => 'property_type',
      'label' => 'Property Type',
      'optional' => 1,
      'single' => 1,
      'remember' => 0,
      'reduce' => 0,
    ),
    'id' => 'field_property_type_value_many_to_one',
    'table' => 'node_data_field_property_type',
    'field' => 'field_property_type_value_many_to_one',
    'override' => array(
      'button' => 'Override',
    ),
    'relationship' => 'none',
    'reduce_duplicates' => 0,
  ),
  'field_furnishing_value_many_to_one' => array(
    'operator' => 'or',
    'value' => array(),
    'group' => '0',
    'exposed' => TRUE,
    'expose' => array(
      'use_operator' => 0,
      'operator' => 'field_furnishing_value_many_to_one_op',
      'identifier' => 'furnishing',
      'label' => 'Furnishing',
      'optional' => 1,
      'single' => 1,
      'remember' => 0,
      'reduce' => 0,
    ),
    'id' => 'field_furnishing_value_many_to_one',
    'table' => 'node_data_field_furnishing',
    'field' => 'field_furnishing_value_many_to_one',
    'override' => array(
      'button' => 'Override',
    ),
    'relationship' => 'none',
    'reduce_duplicates' => 0,
  ),
  'field_number_bedrooms_value' => array(
    'operator' => '>=',
    'value' => array(
      'value' => '',
      'min' => '',
      'max' => '',
    ),
    'group' => '0',
    'exposed' => TRUE,
    'expose' => array(
      'use_operator' => 0,
      'operator' => 'field_number_bedrooms_value_op',
      'identifier' => 'min_bedrooms',
      'label' => 'Min. Bedrooms',
      'optional' => 1,
      'remember' => 0,
    ),
    'id' => 'field_number_bedrooms_value',
    'table' => 'node_data_field_number_bedrooms',
    'field' => 'field_number_bedrooms_value',
    'relationship' => 'none',
  ),
  'field_price_value' => array(
    'operator' => '>=',
    'value' => array(
      'value' => '',
      'min' => '',
      'max' => '',
    ),
    'group' => '0',
    'exposed' => TRUE,
    'expose' => array(
      'use_operator' => 0,
      'operator' => 'field_price_value_op',
      'identifier' => 'min_price',
      'label' => 'Min. Price',
      'optional' => 1,
      'remember' => 0,
    ),
    'id' => 'field_price_value',
    'table' => 'node_data_field_price',
    'field' => 'field_price_value',
    'relationship' => 'none',
  ),
  'field_price_value_1' => array(
    'operator' => '<=',
    'value' => array(
      'value' => '',
      'min' => '',
      'max' => '',
    ),
    'group' => '0',
    'exposed' => TRUE,
    'expose' => array(
      'use_operator' => 0,
      'operator' => 'field_price_value_1_op',
      'identifier' => 'max_price',
      'label' => 'Max. Price (£ Monthly)',
      'optional' => 1,
      'remember' => 0,
    ),
    'id' => 'field_price_value_1',
    'table' => 'node_data_field_price',
    'field' => 'field_price_value',
    'relationship' => 'none',
  ),
));
$handler->override_option('access', array(
  'type' => 'none',
));
$handler->override_option('cache', array(
  'type' => 'none',
));
$handler->override_option('title', 'Property Search');
$handler->override_option('empty', 'No results available.  Please refine your search.');
$handler->override_option('empty_format', '1');
$handler->override_option('use_pager', '1');
$handler->override_option('exposed_block', TRUE);
$handler = $view->new_display('page', 'Property Search Original', 'page_1');
$handler->override_option('path', 'properties');
$handler->override_option('menu', array(
  'type' => 'none',
  'title' => '',
  'description' => '',
  'weight' => 0,
  'name' => 'navigation',
));
$handler->override_option('tab_options', array(
  'type' => 'none',
  'title' => '',
  'description' => '',
  'weight' => 0,
  'name' => 'navigation',
));
$handler = $view->new_display('page', 'Property Search Table', 'page_2');
$handler->override_option('path', 'properties2');
$handler->override_option('menu', array(
  'type' => 'none',
  'title' => '',
  'description' => '',
  'weight' => 0,
  'name' => 'navigation',
));
$handler->override_option('tab_options', array(
  'type' => 'none',
  'title' => '',
  'description' => '',
  'weight' => 0,
  'name' => 'navigation',
));

Comment: Does the path exist in the menu_router table in the database?
Comment: I'm having exactly the same problem, but I don't have boost enabled on this site. Cleared all caches, there's an entry in the menu_router table, tried cloning the view to a new path, still doesn't work. The fact that it was working fine and then suddenly stopped without warning is worrying, the fact that I had this happen on another site is just scary...
Comment: Can you please add a screenshot or description of 1) the menu-settings of the view (page) and 2) any insights on how you have the access of the view configured?
Comment: There is no menu entry assigned in the View but there is a menu item in the Primary Links.  There are no particular access rules for the it either, everyone is allowed to access every View.
Comment: have you tried to rebuild the menu?
Comment: Yeah, I tried that and emptied all caches, but nothing.
Comment: I would suggest you start by removing and disabling (entirely!) as many modules as possible. Starting with Boost. Reading through your comments it seems the problem is not in views, but in some module misbehaving with your views(settings) or a views-addon.
Comment: And start with removing Calendar module if you're using it - I remember seeing some issues with Views 2.x + Calendar, don't recall the details though.

Also, do a quick health check of your view, for example make sure you're not using any non-existent fields anywhere (does anything has changed recently?)

You could try to create a new view exactly like this one and monitor on each step whether it still works or not.
Comment: Did you try cloning the page view display, creating a different URL, then typing that URL directly into your browser?
Comment: Go to devel/php, and do a dpm(menu_get_item('properties')); and see what comes up. You should be able to see the page callback to give you an idea of what is handling the URL.
Answer: Have you tried to change the view path to something else ?
Did you try "To clear Boosts cache set "Ignore cache flushing:" to 'Disabled' in the boost advanced settings & try again." ?
Does your hosting support gzip compression ?
As far as I know there is Boost option "Aggressive Gzip: Deliver gzipped content independent of the request header". What happens if you uncheck the "Aggressive Gzip" option under the Boost Configuration ?
Answer: Hmm, long shot, maybe you are using Pathauto and somehow the URL you used got nuked?  That's happened to me a couple of times.
Answer: you seem to have the same issue as me. The problem for me was caused by using the imagecache preset linked to the node and by ticking the views "link this field to its node".
The view was working perfectly up until a few hours ago and also worked perfectly when I created a dump of the database and imported the site work on it locally. This suggests to me that there's something super obscure going on with the server (shared hosting) setup.
In your case, for your field "field_property_image_fid" you can't have link_to_node = 1 at the same time as using the property-page-image_linked format.
If this fixes the problem for you, and my solution wasn't something just specific to my setup, could you please open an issue in the queue on the Views' project page?
Comment: nm, issue is here - http://drupal.org/node/1422634
Answer: In my case disabling the /taxonomy/term/ view fixed this problem.
Answer: Just had this, think it must be php version related maybe.it turned out to be the "field_property_image_fid" in the view for me as it was for David. Was the image from a ubercart product.
Deleted (it wasn't even needed in the view!) it and all was ok again.
Thanks.


"date(): It is not safe to rely on the system's timezone settings…"

Question: Peguei um sistema para dar manutenção, e ao migrar para outro servidor, começou a dar erro em um input com a data atual, ex:.
<input type='text' value='<?php echo date("d/m/Y"); ?>'>

Mas está dando o seguinte erro:

WARNING:  DATE(): IT IS NOT SAFE TO RELY ON THE SYSTEM'S TIMEZONE
  SETTINGS. YOU ARE REQUIRED TO USE THE DATE.TIMEZONE SETTING OR THE
  DATE_DEFAULT_TIMEZONE_SET() FUNCTION. IN CASE YOU USED ANY OF THOSE
  METHODS AND YOU ARE STILL GETTING THIS WARNING, YOU MOST LIKELY
  MISSPELLED THE TIMEZONE IDENTIFIER. WE SELECTED THE TIMEZONE 'UTC' FOR
  NOW, BUT PLEASE SET DATE.TIMEZONE TO SELECT YOUR TIMEZONE. IN
  /XXX/XXXXXX/XXXXXXXXXXX/PAINEL-MASTER.PHP ON
  LINE 458WARNING:  DATE(): IT IS NOT SAFE TO
  RELY ON THE SYSTEM'S TIMEZONE SETTINGS. YOU ARE REQUIRED TO USE THE
  DATE.TIMEZONE SETTING OR THE DATE_DEFAULT_TIMEZONE_SET() FUNCTION. IN
  CASE YOU USED ANY OF THOSE METHODS AND YOU ARE STILL GETTING THIS
  WARNING, YOU MOST LIKELY MISSPELLED THE TIMEZONE IDENTIFIER. WE
  SELECTED THE TIMEZONE 'UTC' FOR NOW, BUT PLEASE SET DATE.TIMEZONE TO
  SELECT YOUR TIMEZONE. IN
  /XXX/XXXXXX/XXXXXXXXXXX/PAINEL-MASTER.PHP ON
  LINE 45811/01/2018

Setei no início do PHP:
date_default_timezone_set('America/America/Sao_Paulo');

Mas a partir daí não sei como setar a data (Dia/Mes/Ano) dentro do input, li sobre o que é sugerido no WARNING porém não resolvi.
Answer: Essa timezone não existe. O Correto é:
date_default_timezone_set('America/Sao_Paulo');

Você também pode obter a lista de timezones com a função DateTimeZone::listIdentifiers
Comment: Mas e setando isso, como exibo no input a data ?
Comment: resolvido, ok...
Answer: Você provavelmente precisa colocar o fuso horário em uma linha de configuração em seu php.ini. Você deve ter algo como isto em seu arquivo php.ini:
[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = America/Sao_Paulo

Comment: Mas e setando isso, como exibo no input a data ?
Comment: resolvido, ok, graças...
Comment: Acredito ser uma boa solução a nível global do servidor.
Caso tenha programas que necessite mudar o fuso por rodar em alguma região específica, você pode setar no PHP via `date_default_timezone_set()`
Answer: date_default_timezone_set('America/Sao_Paulo');
Isso mesmo, deu certo para mim, vlw pessoal!

“date(): It is not safe to rely on the system's timezone settings…”


What effects aging might have on a guitar?

Question: I'm planning to buy a second-handed guitar from my friend, and I really don't know how many years has it being played by how many players, etc. etc.
The only thing I know is that it's a Yamaha F310 TBS, made in Indonesia, and nothing more.
So, I went on searching in Google trying to find some advises on what notes should I bear in mind to buy a second-handed guitar.
But to my surprise, I didn't find quality knowledge on it. I mean, I thought it should have been discussed much more than that.
Are there any criteria to consider while buying a second-handed guitar? I'm trying to find things like:

No bending in the body wood
Lesser fingerprints on the fingerboard
Sound volume test using a tool (I don't know)
...

Do we have such a list?
Answer:
Check that the neck is straight, or nearly straight. Look down it and see if the fingerboard follows the straight strings, and is parallel to them. If it's banana shaped, there may be the facility to put it right with  adjustment of the truss rod.At the same time, push and pull the neck against the body, seeing if it's still the tight fit it would have been when new. If not, probably forget it.

2.On an acoustic, tap the body all over. If there's a 'ring' rather than a clunk, it's not split. Sometimes, you can see a split.In fact, any split, anywhere - Not good.

Look at the fretwires, they should be unworn- not have grooves.If they have - often on 2nd fret, they can be replaced, but it's hardly a DIY job.

4.Check the machine heads - are they smooth,when turned, bent,etc?. It's a DIY job to replace, but you'll end up buying a set probably.
5.Intonation (check elsewhere on this site) needs to be good - often on acoustics there is no adjustment, so if it's out, leave the guitar, unless you're a complete beginner and it's only a temporary till you get better.
6.The strings are probably going to need a change, anyway, so factor a new set into the price.
7.Varnish ,or lack of it in places, is not a big deal,it's patina, and even cracks in that varnish are not necessarily going to be a problem, providing they are in the varnish, not the wood.
8.The strap knobs loose or missing shouldn't put you off.
The number system is rubbish, and it's not my doing !!
Answer: Things to check

That there is no lateral twisting of the neck. The neck should be ever so slightly bowed upwards (a few mm at most), without any lateral twisting.
That the truss rod actually works. Never turn more than a quarter of a rotation at once. Ensure that it is possible to tighten and loosen the truss rod. It should be secure and not freely rotating/rattling.
Visually check the frets to ensure there are no grooves or excessive wear. Frets should be consistently shaped. With acoustics, pay attention to the first few frets especially.
Run your fingers along the neck touching the edge of the frets, none of the frets should feel sharp to the touch.
Fret each note on each string to see if any notes do not ring out. This indicates that either the setup is incorrect, or there is a high fret.
Tune the guitar with a tuner, then play the 12th fret, and its harmonic. Check both those notes with a tuner. Acoustic guitars are tricky to intonate, so be careful of excessively bad intonation. Also visually inspect the bridge to ensure that it is not lifting away from the top of the guitar as this can considerably effect intonation. Pay attention to the tuners while tuning as well.
Visually inspect the nut, ensure that the grooves are not excessively worn.
Turn the guitar over and inspect the neck, particularly the area near the nut. Check for any repair work which may have happened if the head stock was knocked off, or any cracks caused by dropping the guitar.
Inspect the neck join carefully. There should be no surrounding cracks, or gaps between the neck and the body of the guitar.
Inspect the area where the fretboard joins the top of the guitar, there should be no gaps or cracks between the top and the fretboard.
Inspect the rear of the guitar where the strap pin is, ensure that the wood is not splitting along the join between the two pieces of wood which make up the sides of the guitar.
Inspect the join between the sides and the top/bottom. There should be no splitting, lifting, or gaps.
Finally, strum the guitar. there should be no rattling or wood noise.

If the guitar is nicely setup, dont forget to ask what gauge strings the current owner is using, so you can get the same gauge! changing the gauge will change the tension and may require setup tweaking.


React get value from select dropdown populated from API

Question: I have a select component:
<Select}>
    {data &&
        data.map((survey) => (
            <Option key={survey.id} value={survey.id}>
                {survey.name}
            </Option>
        ))
     }
</Select>

The data array is coming from an API fetch using axios, which is then saved in the state data:
const [data, setData] = useState([]);

How do I grab the selected value and display it?
I tried adding an onChange handler to the  component and save the e.target.value in a separate piece of state:
onChange={e => setInput(e?.target?.value)}

However, I'm getting an error that value is undefined. I suspect it's because the data hasn't loaded yet.
How do you get the selected value from the options when the options are coming from an API? (i.e., dynamic dropdown)
Answer: Try like this :
  const [data, setData] = useState([]);
  const handleChange = (e) => {
    console.log(e.target.value);
    setData(e.target.value);
  };

   <select onChange={handleChange}>
      {dataArr &&
        dataArr.map((survey) => (
          <option key={survey.id} value={survey.id}>
            {survey.name}
          </option>
        ))}
    </select>

Example : Example
Comment: Thank you. I tried this but it still says cannot read value of undefined. Just a reminder that the options themselves are coming from an API. Not sure if that makes a difference.
Comment: The error only appears when I select an option from the list. The list itself is being populated without a problem
Comment: Did you try the example I shared ?
Answer: You need to define a new state and set it in onChange handler to show the selected data at somewhere else.
Define it as:
const [selectedValue,setSelectedValue] = useState()

Then, set it:
const handleChange = (e) => {
    setSelectedValue(e.target.value)
}

it is now available to use anywhere in this component.
Here is an example:
import React, { useState, useEffect } from 'react';

export default function App() {
  const [data, setData] = useState([]);
  const [selectedValue,setSelectedValue] = useState()

// this useEffect is just a simulator for api response, you do not need this useEffect,
// instead just call your api and set the data with your awaited response
  useEffect(()=>{
    setTimeout(()=> {
      setData([
        { name: 'first Option', id: 'ID of first option'},
        { name: 'Second Option', id: 'ID of second option' }
      ])
    },[2000])
  },[])

  const handleChange = (e) => {
    console.log(e.target.value); // maybe print the value to check
    setSelectedValue(e.target.value)
  }

  return (

    <select onChange={handleChange}>
      {data &&
        data.map((survey) => (
          <option key={survey.id} value={survey.id}>
            {survey.name}
          </option>
        ))}
    </select>
    {selectedValue ?
Selected value:  {selectedValue}
 : ''}

  );
}


(mongoose/promises) How do you check if document was created using findOneAndUpdate with upsert

Question: Consider this code, where I need to either create or update a particular document.
Inbox.model.findOneAndUpdate({ number: req.phone.number }, {
    number: req.phone.number,
    country: req.phone.country,
    token: hat(),
    appInstalled: true
}, { new: true, upsert: true }).then(function(inbox){
    /*
       do something here with inbox, but only if the inbox was created (not updated)
    */
});

Does mongoose have a facility to be able to make the distinction between whether or not the documented was created or updated? I require new: true because I need to call functions on the inbox.
Answer: In the case of .findOneAndUpdate() or any of the .findAndModify() core driver variants for mongoose, the actual callback signature has "three" arguments:
 function(err,result,raw)

With the first being any error response, then the modified or original document depending on options and the third which is a write result of the issued statement.
That third argument should return data much like this:
{ lastErrorObject:
   { updatedExisting: false,
     n: 1,
     upserted: 55e12c65f6044f57c8e09a46 },
  value: { _id: 55e12c65f6044f57c8e09a46,
           number: 55555555,
           country: 'US',
           token: "XXX",
           appInstalled: true,
           __v: 0 },
  ok: 1 }

With the consistent field in there as lastErrorObject.updatedExisting being either true/false depending on the result of whether an upsert occured. Note that there is also a "upserted" value containing the _id response for the new document when this property is false, but not when it is true.
As such you would then modify your handling to consider the third condition, but this only works with a callback and not a promise:
Inbox.model.findOneAndUpdate(
    { "number": req.phone.number },
    {
      "$set": {
          "country": req.phone.country,
          "token": hat(),
          "appInstalled": true
      }
    },
    { "new": true, "upsert": true },
    function(err,doc,raw) {

      if ( !raw.lastErrorObject.updatedExitsing ) {
         // do things with the new document created
      }
    }
);

Where I would also strongly suggest you use update operators rather than raw objects here, as a raw object will always overwrite the entire document, yet operators like $set just affect the listed fields.
Also noting that any matching "query arguments" to the statement are automatically assigned in the new document as long as their value is an exact match that was not found.
Given that using a promise does not seem to return the additional information for some reason, then do not see how this is possible with a promise other than setting { new: false} and basically when no document is returned then it's a new one.
You have all the document data expected to be inserted anyway, so it is not like you really need that data returned anyway. It is in fact how the native driver methods handle this at the core, and only respond with the "upserted" _id value when an upsert occurs.
This really comes down to another issue discussed on this site, under:
Can promises have multiple arguments to onFulfilled?
Where this really comes down to the resolution of multiple objects in a promise response, which is something not directly supported in the native speicification but there are approaches listed there.
So if you implement Bluebird promises and use the .spread() method there, then everything is fine:
var async = require('async'),
    Promise = require('bluebird'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/test');

var testSchema = new Schema({
  name: String
});

var Test = mongoose.model('Test',testSchema,'test');
Promise.promisifyAll(Test);
Promise.promisifyAll(Test.prototype);

async.series(
  [
    function(callback) {
      Test.remove({},callback);
    },
    function(callback) {
      var promise = Test.findOneAndUpdateAsync(
        { "name": "Bill" },
        { "$set": { "name": "Bill" } },
        { "new": true, "upsert": true }
      );

      promise.spread(function(doc,raw) {
        console.log(doc);
        console.log(raw);
        if ( !raw.lastErrorObject.updatedExisting ) {
          console.log( "new document" );
        }
        callback();
      });
    }
  ],
  function(err) {
    if (err) throw err;
    mongoose.disconnect();
  }
);

Which of course returns both objects and you can access then consistently:
{ _id: 55e14b7af6044f57c8e09a4e, name: 'Bill', __v: 0 }
{ lastErrorObject:
   { updatedExisting: false,
     n: 1,
     upserted: 55e14b7af6044f57c8e09a4e },
  value: { _id: 55e14b7af6044f57c8e09a4e, name: 'Bill', __v: 0 },
  ok: 1 }

Here is a full listing demonstrating the normal behaviour:
var async = require('async'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/test');

var testSchema = new Schema({
  name: String
});

var Test = mongoose.model('Test',testSchema,'test');

async.series(
  [
    function(callback) {
      Test.remove({},callback);
    },
    function(callback) {
      Test.findOneAndUpdate(
        { "name": "Bill" },
        { "$set": { "name": "Bill" } },
        { "new": true, "upsert": true }
      ).then(function(doc,raw) {
        console.log(doc);
        console.log(raw);
        if ( !raw.lastErrorObject.updatedExisting ) {
          console.log( "new document" );
        }
        callback();
      });
    }
  ],
  function(err) {
    if (err) throw err;
    mongoose.disconnect();
  }
);

For the record, the native driver itself does not have this issue as the response object is in fact it's only object returned aside from any error:
var async = require('async'),
    mongodb = require('mongodb'),
    MongoClient = mongodb.MongoClient;

MongoClient.connect('mongodb://localhost/test',function(err,db) {

  var collection = db.collection('test');

  collection.findOneAndUpdate(
    { "name": "Bill" },
    { "$set": { "name": "Bill" } },
    { "upsert": true, "returnOriginal": false }
  ).then(function(response) {
    console.log(response);
  });
});

So it is always something like this:
{ lastErrorObject:
   { updatedExisting: false,
     n: 1,
     upserted: 55e13bcbf6044f57c8e09a4b },
  value: { _id: 55e13bcbf6044f57c8e09a4b, name: 'Bill' },
  ok: 1 }

Comment: I have tried looking at `raw` and it seems in the latest version to no longer exist (always is undefined). I am also using promises, which only provide a single argument to the `then(function(item)...`
Comment: I ended up solving the problem by creating my own `createOrUpdate` static.
Comment: @MattWay This is a bit suspect. Works fine with a plain callback, seems to be something about how things are being passed as a promise. Think I'll spend a few minutes looking at what is going wrong here.
Comment: According to this https://github.com/Automattic/mongoose/issues/2931 findAndModify only provides the doc (not raw).
Comment: @MattWay  That statement on the issue is not entrely true. I've added some information about what the native driver methods actually do, and also cleared this up with a working example. The issue here is the promise and not the functionality of the driver methods.
Comment: Any ideas why when I try with a callback instead of a promise, `raw` is always `undefined`?
Comment: @MattWay Trying to do some digging, but the clear thing right now seems to be that the promise is only ever getting the document response returned and no other arguments. If I find something concrete I'll add it.
Comment: @MattWay Something concrete with a bit more information.
Comment: If I understand correctly ... `promisifyAll()` is very expensive if you just want bluebird's `.spread()` method. After all `.spread()` does nothing that you can't do with `.then()`.
Comment: @Roamer-1888 The point is the the "callback signature" that is required returns "two" useful arguments other than the "error" reponse. So the "success" is not a single object in the desired response where the detail required comes from the "second" object response. This is not supported by `.then()`. Hence you need to in "some way" define it so that `.spread()` is available to accept both responses. Ideally this would be ES6 and you would just cast the return value. So incorrect. In this case `.spread()` does something you cannot do with `.then()`
Comment: Ah OK, it's a bit confusing because the code in the question indicates that `.findOneAndUpdate()` is already thenable. If that's so then it would appear that it's own `.then()` callback is inadequate (exposes just doc), while it's direct callback is fully featured (exposes both doc and raw)?
Comment: @Roamer-1888 Of course you "can" call then, but that is not the point. The point is the core method `.findOneAndUpdate()` can possibly return `(err,doc,raw)` but when you call with `.then()` you only get `doc` which is why you call `.spread()` so you can get `(doc,raw)` which you cannot get with `.then()` as there are "two" arguments. `.then()` is a "higlander". I already have links in here that explain this as well as the examples.
Comment: @Roamer-1888 Thats ["highlander"](https://www.google.com.au/search?q=highlander+there+can+be+only+one)
Answer: For people using this with Promises, According to this link from Mongoosejs.com we can pass rawResult: true along with other options.
const filter = { name: 'Will Riker' };
const update = { age: 29 };

await Character.countDocuments(filter); // 0

let res = await Character.findOneAndUpdate(filter, update, {
  new: true,
  upsert: true,
  rawResult: true // Return the raw result from the MongoDB driver
});

res.value instanceof Character; // true
// The below property will be `false` if MongoDB upserted a new
// document, and `true` if MongoDB updated an existing object.
res.lastErrorObject.updatedExisting; /

and the result from this query will be of the format
{ lastErrorObject:
   { n: 1,
     updatedExisting: false,
     upserted: 5e6a9e5ec6e44398ae2ac16a },
  value:
   { _id: 5e6a9e5ec6e44398ae2ac16a,
     name: 'Will Riker',
     __v: 0,
     age: 29 },
  ok: 1 }

so the document can be accessed at data.value


Python - Rpy2 - Can't import a bunch of packages

Question: I've just started using rpy2 with Python.  I've installed it and am able to do basic things, like call R's plot function from inside Python.  For everything I've done, I've used import calls like:
import rpy2
import rpy2.robjects

From robjects I can do most things I want to do.  However, if I want to use things like ggplot2, I am unable to get the relevant imports to work.  Following the steps here, I try:
from rpy2.robjects.packages import importr

But I get an error message telling me that there is no module called "packages."  I'm not really sure why this is happening, as I am able to import other things from robjects, like rpy2.robjects.numpy2ri.  I'm hoping this is some obvious problem other people have dealt with!  I did some googling and tried messing around with the env variable $PYTHONPATH but I don't think that is the issue.
Answer: packages is new in 2.1. You're probably still using 2.0.x.
Answer: You can use the normal library() command from robjects.r to load a library in rpy2 2.0.x:
from rpy2.robjects import r
r.library("lattice")
r.library("ggplot2")

Or you can upgrade to the 2.1 alpha and see if the new way works for you.