Upgrading simply from php 5.6.x to 7.x on CentOS 7 with Nginx and php-fpm

Question: I am trying to upgrade the PHP version on a Digital Ocean server from 5.6.19 to the latest PHP 7.2. A lot of instructions found online point to "php72", which makes me wonder if 5.6.19 will be seamlessly replaced with a yum update php. I doubt it.
Which means I may have to first 5.6.19, in which case I run the risk of totally deleting old settings. This is scary in case th enew setup does not go well, there's not much to flip back to.
I find there are important settings in these places:

/etc/php-fpm.d/www.conf
/etc/php.ini
/etc/php-fpm.conf
/etc/nginx/common.conf
/etc/nginx/fastcgi.conf

And of course the Nginx.conf (the main Ngnix config file) has calls to PHP-FPM accordingly. They include the #4 file above, common.conf, which in turn includes the fastcgi.conf.
Instructions on external websites, such as this one--
https://www.cyberciti.biz/faq/how-to-install-php-7-2-on-centos-7-rhel-7/
--do not take into account Nginx and PHP-FPM specifics especially in terms of old PHP 5.6.19 already existing.
All these instructions anyway speak of "php72", which I am afraid will change all the paths, and I'll have to update all paths to new php links everywhere.
Could you please advise how best to do this so I seamless upgrade the old PHP with the latest, with all the usual paths as above working? Otherwise we need to:

Remove 5.6.19
Install 7.2, and all additional modules (which will introduce the "php72" in the paths)
Make sure all paths everywhere are new everywhere..

Any way to make this simpler in a OS-default way, without additional repos like "Remi" etc?
Comment: It doesn't make sense. CentOS 7 came with PHP 5.4, not 5.6. So there must have been something else done to the system first, i.e. installing a third party repo for PHP. Where did it come from?
Comment: Where did you get PHP 5.6 from?
Comment: Through the usual `yum install php` in CentOS 7. And doing yum update does not change this to a new major version like 7. It just updates it to 5.6.latest.
Comment: Probably epel then. One of the usual instructions though, where the php-fpm etc are not in highly customized directories like `/etc/opt/remi/php72/php-fpm.d/www.conf`.
Comment: Using "remi" repository, following the wizard instructions, a simple "yum update" shlould do it. https://rpms.remirepo.net/wizard/  (using "single version", /opt is only use for SCL, "multiple versions")
Comment: Solved, see https://forum.remirepo.net/viewtopic.php?id=3798
Answer: Remi Collet answered in comments, so there's no answer to accept. I'm adding it here for easier visibility for anyone who needs the same help:
Steps for posterity, to save on Stack Exchange here:

Remove php56w-mcrypt module with YUM before the update (it's not a
much used module anyway these days)
Then run the steps listed in the wizard on Remi's website
Run yum update --noplugins (the dash dash noplugins options is safe)
Check if any nginx conf files have old style comments starting with #. If so, replace them with the new strict comments that have to begin with ;
Restart nginx (I had to manually kill any running nginx processes)

Hope this helps someone. The discussion is on Remi's forum.
Thank you.


Como somar vários números que foram digitados no output?

Question: O que tenho até agora:
for c in range(3):
    n = int(input())
    n += n #tenho quase certeza que essa parte não está certa
print(n)

Como somar vários números que foram digitados no output?
Comment: Não está somando corretamente.
Comment: A variável que recebe o total deve ser criada fora do loop
Answer: Estás a fazer overwrite ao valor de n quando fazes n = int(input()), faz antes:
total = 0
for _ in range(3):
    n = int(input())
    total += n
print(total)

DEMONSTRAÇÃO
Ou com menos linhas/variáveis:
total = 0
for _ in range(3):
    total += int(input())
print(total)

Python style:
total = sum(int(input()) for _ in range(3))

Comment: Pode explicar melhor o que fez?
Comment: Tu estavas a anular o valor anterior de n quando fazias `n = int(input())`, depois só estavas a somar-lo com ele próprio (equivalente a `n*2`) na linha seguinte
Comment: No trecho `n = int(input())` dentro do loop você declarava a variável novamente e ela perdia o valor da soma anterior `n += n`
Answer: Você pode utilizar o seguinte código...
valores = list(map(int, input('Digite todos os valores: ').split()))
print(f'\033[32mA soma dos valores digitados é: {sum(valores)}')

Veja o funcionamento deste código no repl.it.
Quando executamos este código, recebemos a seguinte mensagem...
Digite todos os valores:

Neste momento devemos digitar todos os valores que desejamos, na mesma linha, separados por um espaço e, em seguida, pressionar a tecla enter.
Se, por exemplo, quisermos digitar os valores 3, 4, 5, 6, quando o programa solicitar a digitação dos valores, devemos digitar da seguinte forma:
3 4 5 6

...e posteriormente pressionar enter.
A partir desse momento o programa irá calcular a soma de todos os valores que foram digitados e armazenados na lista valores.
Observe também, que este código soma uma quantidade de valores indefinidos e, para encerrar a digitação, basta pressionar enter.
Em outras palavras, se você digita 3 valores e pressionar enter será somado os 3 valores.
Agora, se você digitar 100 valores e pressionar enter, será somado os 100 valores.


Composers making translation errors in their Italian directions

Question: Virtually all composers in the Classical, and most composers in the Romantic period followed the convention of notating tempo markings and other directions in Italian.
However, clearly not all of these composers were Italian, and I assume some of them only had a limited understanding of Italian beyond the directions commonly notated in sheet music.
I have a vague recollection that Beethoven, not knowing the corresponding Italian word for the tempo marking he intended, made up an Italian word out of whole cloth.
What examples are there of works whose sheet music includes Italian directions which are unidiomatic, ungrammatical or otherwise erroneous?
Answer: There is a difference between "conventional musical terms that were originally Italian" and "the Italian language".
A common example is "con sordino" with a mute or "sordini" (plural) - the "correct" Italian is sordina/sordine, but most musicians either don't know or don't care whether their mutes are grammatically masculine or feminine.
Another is "D.S. al coda/fine" which I have never seen written "correctly" as "D.S. alla coda/fine".
This also works in reverse. A non-Italian speaker who knows a bit of music terminology may think that "Largo e Allegro" is a nonsensical tempo marking, but it is perfectly good Italian, and has been used by composers who actually knew Italian - Handel, for example. "Largo" doesn't mean "slow" in Italian, but it does mean "slow" as a conventional musical term.


Testing csv file stored in memory using unittest django

Question: I'm getting an error when trying to write to a csv file. Here's my two scripts:
Tasks.py
def get_data():

          customer = Customer.objects.all()
          csvfile = StringIO.StringIO()
          csvwriter = csv.writer(csvfile)

          for i in customers:
              csvwriter.writerow([str(i.phone_number)])

          return csvfile

In tests.py:
    with open(get_data().getvalue(), 'rb') as myfile:
        data = [row for row in csv.reader(myfile.read().splitlines())]
        print data

This is the error:
IOError: [Errno 2] No such file or directory: '999999999\r\n'

Where '999999999' is what should be written in the file.
How can I fix this?
Comment: Why are you trying to open it at all? It's not a file. `get_data` is a StringIO object which you can read directly.
Comment: Okay makes sense. Thanks!
Answer: Your get_data() function doesn't return a file but a StringIO object. You don't need to open() it, you can just read it like this:
myfile = get_data().getvalue()
data = [row for row in csv.reader(myfile.splitlines())]
print data


Exchange 2007 storage configuration for 50 users

Question: What kind of storage configuration would you recommend for a small Exchange server deployment supporting about 50 users? Probably won't grow past 75 users in 3 years. Majority will be "medium" users, with a few "heavy" users and BlackBerry clients.
So far, everything that I've read suggests keeping the Exchange database and the transaction logs on separate physical drives, and keeping both of those off of the system drive. It also says to put the transaction logs on something fast, like a Raid 1+0 array. Considering that all the data needs to be protected, it looks like this would be an optimal setup:
System drive - 2 small drives in RAID 1
Exchange database - 2 big drives in RAID 1
Transaction logs - 4 fast drives in RAID 1+0
However, using 8 drives for a tiny Exchange server seems like incredible overkill. Where would it be safe to cut back?
Answer: Even with heavy users and a lot of headroom you are not going to see much more than 2 IOPS per user and you will probably never even break 1 IOPS per user if it's a small environment like this [See this Technet article. Even taking a fairly conservative number of 80 IOPS per drive (assuming you opt for large 7200rpm SATA drives for the data) and factoring in the double IOPS overhead for write IO, you should still be fine with lumping all the Exchange data and logs onto a two drive RAID1 pack. If you have the option and want to isolate the logs, then by all means go ahead but you are never going to stress a half decent 2-drive RAID-1 set up with the sort of IO that your Exchange environment is going to generate even at 75 users.
Comment: +1 - I agree. I'd probably put the transaction logs on the RAID-1 set with the operating system, and the database onto another RAID-1 (since the OP mentioned he might want to get down to 4 disks). That'll offer some redundancy in case of losing either spindle (since you'll still have either the database or transaction logs intact). Realistically, you could do it on 2 drives and be just fine, but I'd sleep better w/ the separate spindles for the database and transaction logs, personally.
Comment: Good point Evan - it's always a good idea to get as much use out of the available redundancy as possible.
Comment: This is exactly the kind of answer I was looking for. We tend to be more limited by capacity than performance, so I think two RAID 1 sets of SATA drives will be perfect.
Answer: I'd say the first place to cut back would be not using striping for the t-logs.  On such a small server you really don't need striping-backed performance there.
You could also consider not putting the logs on a separate storage, but the first thing I'd cut would be the two extra drives for striping and just run two drives in RAID 1 for the t-logs.
Comment: That sounds like a great start. If I wanted to get down to 4 drives, should I put the database or transaction logs on the system drive?
Answer: How much traffic will each user generate? This is quite an important factor to take into account. How much storage per user? How much growth a day?
Whatever you do, don't cut down on RAID. Use at least RAID 1 for each volume. A crashed server because of a single disk failure is definitely something you don't want.
Also, there's a really good reason to physically separate databases from transaction logs: disaster recovery. It's really, really bad to have them on the same volume, because you risk losing both at the same time. If you by chance lose your database, you want to have you transaction logs ready, otherwise the most you can do is restore your last full backup (which may be from some days before the crash).
Summary: RAID 1 for the O.S., RAID 1 for transaction logs, RAID 1, 5 or 10 (depending on your storage needs) for database(s).
Comment: That's a great point about the reasoning for separation of transaction logs and database. Do people normally also back up transaction logs at all?
Comment: That would be pointless, because they're automatically truncated when you do a full database backup. The only time you need them is when you're restoring (but you WILL need them, then).
Answer: With the small number of users you have, I don't think you should be going too far down the route of optimizing storage.  Bottom line is, unless you do something completely daft, the storage subsystem is not going to be a bottleneck.  So take some basic common sense recommendations and don't worry overly much about it.


Apache in linux-vserver won't start, can't create socket

Question: During extensive research and testing to write a proper question worthy of stackexchange I found a solution: rebuild the libapr1 package inside the guest.I thought I'd nevertheless post this information as it could be useful to others.
Problem
When I install libapache2-mod-php5 inside the Wheezy guest and it tries to start up, I get the following:
root@test01:~# /usr/sbin/apache2ctl start
[crit] (22)Invalid argument: alloc_listener: failed to get a socket for (null)
Syntax error on line 9 of /etc/apache2/ports.conf:
Listen setup failed
Action 'start' failed.
The Apache error log may have more information.
root@test01:~# tail /var/log/apache2/error.log
root@test01:~#
root@test01:~# head -n 9 /etc/apache2/ports.conf|tail -n 1
Listen 80

This is the unchanged pristine package installation which by default doesn't manage to start up.
My testing
According to the official documentation, Listen 80 is actually fine. Turning it into Listen 127.0.0.1:80 gives me:
[crit] (22)Invalid argument: alloc_listener: failed to get a socket for 127.0.0.1
Syntax error on line 9 of /etc/apache2/ports.conf:
Listen setup failed
Action 'start' failed.

So why would Apache fail to get a socket? I've other deamons running (i.e. nginx on other Wheezy installation; exim4 listening on port 25 on the same installation) without problems.
Environment
Host
Debian Lenny on 2.6.26-2-vserver-amd64
# vserver-info
Versions:
                   Kernel: 2.6.26-2-vserver-amd64
                   VS-API: 0x00020303
             util-vserver: 0.30.216-pre2772; Dec 13 2008, 04:56:19

Features:
                       CC: gcc, gcc (Debian 4.3.2-1) 4.3.2
                      CXX: g++, g++ (Debian 4.3.2-1) 4.3.2
                 CPPFLAGS: ''
                   CFLAGS: '-Wall -g  -O2 -std=c99 -Wall -pedantic -W -funit-at-a-time'
                 CXXFLAGS: '-g -O2 -ansi -Wall -pedantic -W -fmessage-length=0 -funit-at-a-time'
               build/host: x86_64-pc-linux-gnu/x86_64-pc-linux-gnu
             Use dietlibc: yes
       Build C++ programs: yes
       Build C99 programs: yes
           Available APIs: v13,net,v21,v22,v23,netv2
            ext2fs Source: e2fsprogs
    syscall(2) invocation: alternative
      vserver(2) syscall#: 236/glibc
               crypto api: beecrypt
   use library versioning: yes

Paths:
                   prefix: /usr
        sysconf-Directory: /etc
            cfg-Directory: /etc/vservers
         initrd-Directory: $(sysconfdir)/init.d
       pkgstate-Directory: /var/run/vservers
          vserver-Rootdir: /var/lib/vservers

Assumed 'SYSINFO' as no other option given; try '--help' for more information.

Guest
Debian Wheezy, built with vserver $VSERVER build -m debootstrap --hostname $VSERVER --netdev eth0 --context $CONTEXT --interface v$CONTEXT=x.y.z.$CONTEXT/zz -- -d wheezy -m http://apt-proxy:9999/debian/
Research so far
The internets provied me with the following things so far:

Problem on fedorra fixed by upgrading APR
Problem fixed by upgrading package
Kernel incompatibility
Another solution required a kernel upgrade

My greatest fear, and this is my current conclusion, is that apache inside the virtual server depends on some newer kernel feature which my host doesn't provide. After all, the Wheezy default kernel certainly isn't as old as my 2.6.26.
I want to avoid upgrading the host kernel at all costs.
Why?

Lack of time and knowledge (hardware is HP server, no idea what to watch out)
Wheezy does not support vserver anymore (out of the box; for self-installation see 1) ...)
Already running vservers which are required to be available 24/7 (the whole system is company internal and not exposed to the internet)
No second same hardware to perform testing

I'm willing to patch Apache
If it's possible to figure out what the problem is, I'm wiling to build a custom deb package for my Wheezy quests.
Answer: Solution
As I said in the first sentence, I already found the solution: I rebuilt the libapr1 package inside the guest.
I found the solution by googling for "Invalid argument: alloc_listener: failed to get a socket for (null)", the 5th hit was Invalid argument crap which mentions the kernel upgrade and refers to another blogger talking about Fedora 11 httpd problems:

The issue is related to three kernel calls that are used in apr-1.3.8-1: accept4(), dup3() and epoll_create1(). Without these calls, apache is unable to start.

He mentions the Fedora team fixed so I checked out the bug report: https://bugzilla.redhat.com/show_bug.cgi?id=516331, specifically the second comment:

.. if you build your own APR on that Xen instance, it will correctly pick up the older functions and work ..

That ringed a bell. All I had to do was to rebuilt the libapr1 package because the configure script will automatically figure out that accept4 is not available and will revert to accept. That's how I did it:

apt-get source libapr1
tar -xf apr_1.4.6.orig.tar.gz
cd apr-1.4.6
tar -xf ../apr_1.4.6-3.debian.tar.gz
dpkg-buildpackageThis failed at first because of missing dependencies: apt-get install debhelper autoconf autotools-dev uuid-dev doxygen libtool
After some time this produced a debian package outside the directory which I installed:dpkg -i libapr1_1.4.6-3_amd64.deb
Then I just started apache and it worked!/etc/init.d/apache2 start

On a disk-starved systems, you may want to remove doxygen after compilation: on my system it needed over 600MB together with its dependencies.
Comment: +1 Thanks, very helpful and it fixed my problem as well in http://serverfault.com/questions/506238/after-upgrade-to-wheezy-apache-fails-to-start You should mark your own answer as the accepted one.
Comment: no such a package


Regression model with missing data in dependant variable

Question: modelo <- lm( P3J_IOP~ PräOP_IOP +OPTyp + P3J_Med, data = na.omit(df))
summary(modelo)

Error:

Fehler in step(modelo, direction = "backward") :
Number of lines used has changed: remove missing values?

I have a lot of missing values in my dependent variable P3J_IOP.
Has anyone any idea how to create the model?
Comment: Welcome to Stack Overflow. Can you post an example of your data?
Answer: tl;dr unfortunately, this is going to be hard.
It is fairly difficult to make linear regression work smoothly with missing values in the predictors/dependent variables (this is true of most statistical modeling approaches,  with the exception of random forests). In case it's not clear, the problem with stepwise approaches with missing data in the predictor is:

incomplete cases (i.e., observations with missing data for any of the current set of predictors) must be dropped in order to fit a  linear model;
models with different predictor sets will typically have different sets of incomplete cases, leading to the models being fitted on different subsets of the data;
models fitted to different data sets aren't easily comparable.

You basically have the following choices:

drop any predictors with large numbers of missing values, then drop all cases that have missing values in any of the remaining predictors;
use some form of imputation, e.g. with the mice package, to fill in your missing data (in order to do proper statistical inference, you need to do multiple imputation, which may be hard to combine with stepwise regression).

There are some advanced statistical techniques that will allow you to simultaneously do the imputation and the modeling, such as the brms package (here is some documentation on imputation with brms), but it's a pretty big hammer/jump in statistical sophistication if all you want to do is fit a linear model to your data ...


Transformation to fit gamma distribution for glm

Question: The data simulated below has a maximum value of 4 and is interestingly skewed. The maximum of 4 is a limitation imposed by the instrument used and the data is semi-discrete, i.e., there are a reasonably large number of numbers it could be between -4 and 4. Because of the shape of the data, I thought about transforming it so it would approximate a gamma distribution:
Edit to update for comments:
It is limited to this range in this instance because it is a signal detection measure (d prime http://en.wikipedia.org/wiki/D%27) and the accuracy we have for this particular measure limits us to +-4. It is skewed like this because one population does not very often get false positives and will generally get more hits while the other populations often do get false positives and less hits.
set.seed(69)
g1<-rnorm(700,0,1); g2<-rnorm(100,-0.5,1.5); g3<-rnorm(100,-1,2.5)
gt<-data.frame(score=c(g1, g2, g3), fac1=factor(rep(c("a", "b", "c"), c(700, 100, 100))), fac2=ordered(rep(c(0,1,2), c(3,13,4))))
gt$score<-with(gt, ifelse(fac2 == 0, score, score-rnorm(1, 0.5, 2)))
gt$score<-with(gt, ifelse(fac2 == 2, score-rnorm(1, 0.5, 2), score))
gt$score<-round(with(gt, ifelse(score>0, score*-1, score)), 1)+4
gt$score<-with(gt, ifelse(score < -4, -4, score))
gt$cov1<-with(gt, score + rnorm(900, sd=40))/40
hist(gt$score)
gt$score2<-with(gt, 4-score+0.0000001) #Gamma distribution can't have 0s (and is positive skewed???)
hist(gt$score2)

glm1<-glm(score2~cov1+fac1*fac2, family="Gamma", data=gt)

This is quite new territory for me.
1. Is this a reasonable thing to do?
2. Are there other distributions I might try and compare (exponential perhaps)?
Update:
After some comments below, I investigated beta regression using the betareg package in R. It gave me skewed residuals:
gt$scorer<-with(gt, (score--4)/(4--4))
gt$scorer<-with(gt, (scorer*(length(scorer)-1)+0.5)/length(scorer))
b1 <- betareg(scorer ~ cov1 + fac1 * fac2, data=gt)
plot(density(resid(b1))) #Strange residuals, even straight lm looks better

So I had a look at a quasibinomial regression and it gave me smaller and better looking residuals:
glm2 <- glm(scorer~cov1 + fac1 * fac2, data=gt, family="quasibinomial")
plot(density(resid(g1))) #Better residuals

Are the residuals good enough to go on in this case?
Or is the fact that d', while based upon T/F, is not a binary variable, a serious issue?
Edit 3: d' clarification
The below is an example of my d' scores, with the rough distributional qualities and similar raw scores for hits and false positives.
hitrate<-sample(0:16, 100, replace=T, prob=c(rep(0.02,11), 0.025, 0.05, 0.1, 0.2, 0.3, 0.2))/16
hitrate<-ifelse(hitrate==1, 31/32,hitrate); hitrate<-ifelse(hitrate==0, 1/32,hitrate)
farate<-sample(0:32,100, replace=T, prob=c(0.7,0.1,0.05,0.05,0.05,0.02,rep(0.001, 27)))/32
farate<-ifelse(farate==0, 1/64,farate); farate<-ifelse(farate==1, 63/64,farate)

dprime<-round(qnorm(hitrate) - qnorm(farate),1)
plot(density(dprime))

Comment: Why would you think your data should follow the gamma distribution, which has an infinite support (all $x>0$)? To find the right distribution, tell us about the data generating process: what makes it restricted to the $(-4,4)$ range, and why is it skewed?
Comment: Updated question to include more info on the data. It appears the gamma distribution is certainly not correct for this instance.
Comment: This is a very interesting problem, but I need further clarification. The following is based on the signal detection link you included. Is this correct? You send $n_T$ true signals, and get $k_T$ detections for a hit rate of $h=k_T/n_T$; then you send false signals for a false alarm rate of $f=k_F/n_F$, and finally you get $d'=\Phi^{-1}(h) - \Phi^{-1}(f)$, which is the score you are analyzing. If this is correct, would you have any of the intermediate values available?
Comment: Yes, its the same signal detection calculation. I've updated the question to show the rough process; from raw scores to final d' scores. Is this what you were after?
Answer: A gamma distribution definitely doesn't make sense for you data.  Gamma takes support on the entire real line and is always skewed right.  The example data you provide in your code would be horrible data to try to fit a gamma to.
It would definitely be nicer to know more about the data generation process.  But one thing that comes to mind is you could scale and shift the data to be constrained between 0 and 1 and then attempt to use a Beta distribution to model that.  Once again it would be better to know more about your data but a Beta is one of the few well known parametric distributions that is bounded below and above.
However, it seems you want to do some sort of a regression.  Have you tried to fit the regression assuming a normal error term and examining the residuals?  A lot of people assume that the data itself needs to be normally distributed for a linear regression to work but typically we place the assumption on the error term and depending on the values your covariates take this can lead to a skewed distribution for your response variable.
Comment: I wouldn't rely heavily on using considerations of support to select a probability model.  After all, normal distributions--which, like Gammas, have infinite support--are frequently used, with great success, to model distributions that *must* have finite support (such as the sampling distribution of binary responses in a survey question).
Comment: Thanks. So gamma distributions are really only for situations where the possibility could be any number, I made a similar error previously with respect to negative binomials. A beta binomial type distribution as you suggest sounds good. The residuals show a slightly skewed distribution in this case. However, sometimes the measures I'm interested in are not so well behaved for the normal regression. I have updated the question to give more info about the data.
Comment: Oops, realised you meant the beta distribution not the beta-binomial.
Comment: Very true.  Which is why I wondered what happened with the residuals for a normal linear regression.  Using their example data it didn't seem like a gamma was very appropriate.
Answer: I was going to suggest using binomial regression with a probit link on the original hit/false alarm counts, but before writing out the details I googled for this idea. Apparently, someone else thought of it already (there goes a publication :)
Here is the reference (in case the link is restricted), there is also an R package sensR to go with it:
PB Brockhoff, RH Bojesen Christensen (2010) Thurstonian models for sensory discrimination tests as generalized linear models, Food Quality and Preference, 21(3), 330-338.
Comment: Thanks, will probably be back with a question later after reading the ref. Would give an extra +1 for the reference if I could.


How to solve error "Big integer literals are not available in the configured target environment" on vite?

Question: I am using vite, react and typescript then i got this error, anyone knows how to solve it ?
Here is my package.json:
{
  "name": "",
  "private": true,
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "@apollo/client": "^3.7.9",
    "@composedb/cli": "^0.3.1",
    "@composedb/client": "^0.3.1",
    "@didtools/pkh-ethereum": "^0.0.3",
    "@emotion/react": "^11.9.0",
    "@emotion/styled": "^11.8.1",
    "@mui/icons-material": "^5.8.4",
    "@mui/material": "^5.8.2",
    "@mui/x-date-pickers": "^5.0.0-alpha.5",
    "cytoscape": "^3.22.1",
    "date-fns": "^2.28.0",
    "did-session": "^1.0.0",
    "graphql": "^16.6.0",
    "graphql-tag": "^2.12.6",
    "moment": "^2.29.4",
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "react-router-dom": "^6.3.0",
    "web3": "^1.8.2"
  },
  "devDependencies": {
    "@types/cytoscape": "^3.19.6",
    "@types/react": "^18.0.0",
    "@types/react-dom": "^18.0.0",
    "@vitejs/plugin-react": "^1.3.0",
    "axios": "^0.27.2",
    "typescript": "^4.6.3",
    "vite": "^2.9.9"
  }
}

Logs:

✘ [ERROR] Big integer literals are not available in the configured target environment ("chrome87", "edge88", "es2019", "firefox78", "safari13.1")

node_modules/bigint-mod-arith/dist/esm/index.browser.js:231:16:
  231 │         e = e / 2n;
      ╵                 ~~

✘ [ERROR] Big integer literals are not available in the configured target environment ("chrome87", "edge88", "es2019", "firefox78", "safari13.1")

node_modules/bigint-mod-arith/dist/esm/index.browser.js:232:17:
  232 │         b = b ** 2n % n;
      ╵                  ~~

7:04:56 AM [vite] error while updating dependencies: Error: Build failed with 68 errors:
node_modules/bigint-mod-arith/dist/esm/index.browser.js:21:14: ERROR:
Big integer literals are not available in the configured target environment ("chrome87", "edge88", "es2019", "firefox78", "safari13.1")
node_modules/bigint-mod-arith/dist/esm/index.browser.js:27:20:
ERROR:
Big integer literals are not available in the configured target environment ("chrome87", "edge88", "es2019", "firefox78", "safari13.1")
node_modules/bigint-mod-arith/dist/esm/index.browser.js:27:26: ERROR:
Big integer literals are not available in the configured target environment ("chrome87", "edge88", "es2019", "firefox78", "safari13.1")
node_modules/bigint-mod-arith/dist/esm/index.browser.js:47:13: ERROR:
Big integer literals are not available in the configured target environment ("chrome87", "edge88", "es2019", "firefox78", "safari13.1")
node_modules/bigint-mod-arith/dist/esm/index.browser.js:47:24: ERROR:
Big integer literals are not available in the configured target environment ("chrome87", "edge88", "es2019", "firefox78", "safari13.1") ...
at failureErrorWithLog
[...]

I tried, deleting node_modules and pnpm-lock-yaml and reinstalling them but the problem is still there.
Comment: Please [edit] your question to include your `tsconfig.json` file and any other compilation configuration. Why are you targeting such old browser versions? Safari is the problem as it only got [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt#browser_compatibility) support in v14
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: I solved it on vite 3.2.x and 4.1.x (with Svelte instead of React, but it should work) by defining the following vite config's options:

optimizeDeps.esbuildOptions.target
optimizeDeps.global
optimizeDeps.esbuildOptions.supported.bigint
build.target

import { defineConfig } from "vite";
// import react, svelte and other needs...

// https://vitejs.dev/config/
export default ({ mode }) => {

  return defineConfig({

    optimizeDeps: { //  optimizedeps
      esbuildOptions: {
        target: "esnext",
        // Node.js global to browser globalThis
        define: {
          global: 'globalThis'
        },
        supported: {
          bigint: true
        },
      }
    },

    build: {
      target: ["esnext"], //  build.target
    },
  })
}

Comment: Used this Vite config in a NuxtJS project and solved my static build deployment.
Although i had to set my target to 'es2020'
Comment: @flydev may I ask how you were able to figure this out?I want to get better at debugging issues like these.
Comment: @nxmohamad create a [chat room](https://chat.stackoverflow.com/), invite me and let's have a discussion.
Comment: @flydev created - https://chat.stackoverflow.com/rooms/info/255046/vite-config-deep-dive?tab=general
Answer: Simplified the @flydev answer a bit:
vite.config.ts
export default defineConfig({
  // ...
  build: {
    target: 'esnext', // you can also use 'es2020' here
  },
  optimizeDeps: {
    esbuildOptions: {
      target: 'esnext', // you can also use 'es2020' here
    },
  },
})

Also, make sure your Typescript target is high enough:
tsconfig.json
"compilerOptions": {
  "target": "ES2020", // you can also use higher value
  // ...
}


Multi-scale fretboard: angle of bridge and nut

Question: I'd like to understand how to draw a multi-scale fretboard. I'm aware of tools like FretFind2D, but I'd like to do the maths on my own. I thought of having the center of the bridge at point (0, 0) in the coordinate system. But at what angle will I have to draw the bridge? And what about the nut?
The given parameters are:

upper scale length
lower scale length
total string spacing at the bridge
total string spacing at the nut
perpendicular fret
Comment: What in particular are you having trouble with? It's a pretty straight forward trig problem.
Comment: Indeed, in the end it's all basic trigo, but I just don't know where to start. The first thing I want to do is calculate the bridge angle. Since the bridge width (total string spacing at the bridge) is already given, I just need the actual "bridge width" as seen horizontally to calculate the bridge's angle. But this is based on the perpendicular fret, and I'm unable to calculate this value.
Comment: The perpendicular fret is the one that is perpendicular to the fretboard centerline, right?
Comment: @waitan you may need to clarify your question, I assumed you knew and understood your given parameters. Whereas the other answer assumed you needed to know what a perpendicular fret is.
Comment: @Fergus: I do know and I do understand the parameters, that's correct. And I do not need to know what a perpendicular fret is, your answer pretty much sums up what I needed to know :)
Answer: Firstly, I assume the strings spacings at the bridge are measured across from the high E nut/saddle perpendicular to the fret board centreline (FBC). This seems the only logical way as it not affected by the level of fanning, i.e. it reflects what string spacing measures traditionally; 'neck width feel' is consistent with non-fanned guitars. If you're using string spacing parallel to the line of the string end points, this method will need adjustment as two knowns and unknowns swap.
Draw a large diagram, not proportional. Exaggerate some dimensions (e.g. make bridge string spacing (BSS) double or so nut string spacing (NSS)) to make angles etc easier to see.
Calculate string spread angle (SSA, angle between high or low E and FBC). LSL is the lower scale length (for high E).
SSA = inverse sin(((BSS-NSS)/2) / LSL)

To calculate distance to perpendicular fret:
d = fret distance from nut
s = scale length
n = perpendicular fret number

d = s-s/(2^(n/12))

Do this for both E strings.
Position the perpendicular fret (PF) on the high E.
Calculate the distances from the PF to the low E and high E nut and bridge points parallel to the FBC.
A few more steps will give the bridge and nut angle; I can add them if it's not obvious.
There are a few very small triangles near the low E bridge and nut that could easily be missed. That's why skewing the diagram is important — it makes them more visible.
Comment: I think my main problem was that I wanted to use the string spacing across the bridge/nut, not as you described. It worked with your method, having a string spacing perpendicular to the fret board centreline. Thanks a lot!
Answer: On every multi-scale instrument that I have seen, there is one fret position where the fret is the closest to completely perpendicular to the strings. Different builders have each chosen a different point. It seems to me that this fret position has a lot to do with the ease of playing of the instrument, ergonomically speaking, and this has to do with the overall scale length of the instrument.
The calculation of the angle of the nut and the bridge would be dependent upon which fret position you choose to be the perpendicular fret, in addition to the scale length you choose for the lowest string and the scale length you choose for the highest string.
I have taken some images off the web to illustrate this. You can see which fret is chosen as the perpendicular fret, and you can see the relative angle of the bridge and nut of each instrument, which depend on the difference in scale lengths chosen by the designer, between the longest and shortest string. There is a great deal of variability in these designs.


Nonlinear Pendulum

Question: The question I have is mostly on stability analysis but the problem is:
Consider a nonlinear pendulum. Using a linearized stability analysis, show that the inverted position is unstable. What is the exponential behavior of the angle in the neighborhood of this unstable equilibrium position.
I don't understand what inverted position means, what position was it in to begin with? I found this thing on linearized stability analysis but I'm not totally sure if that applies to this problem.
Answer: The phrase "inverted position" means that the pendulum is pointing straight up.
Intuitively, we know that this is unstable since any perturbation away from perfectly vertical will cause the pendulum to swing downwards. To show this, you'll compute the linearization of the system when the pendulum is pointing straight up and you'll find that it's unstable (and probably that the distance from vertical grows exponentially).
Answer: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\down}{\downarrow}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\half}{{1 \over 2}}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\ol}[1]{\overline{#1}}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
The pendulum equation of motion is given by
$$
mL^{2}\ddot{\theta} = mgL\sin\pars{\theta}\quad\imp\quad
\ddot{\theta} - {g \over L}\,\sin\pars{\theta} = 0
$$
where $m$: mass, $L$: length, $g$: gravity acceleration
$\ds{\approx 9.8\ {{\rm m} \over {\rm sec}^{2}}}$. $\theta$ is the angle from the vertical line where $\theta = 0$ $\pars{~\it\mbox{inverted pendulum}~}$ is the highest point and $\theta = \pi$ is the lowest point.
When $\theta \approx 0$, the equation of motion becomes
        $$
        \ddot{\theta} - {g \over L}\,\theta \approx 0$$
    which has solutions $\theta\pars{t} \sim \exp\pars{\pm\root{g \over l}t}$
    which renders the motion unstable.
When $\theta \approx \pi$, the equation of motion becomes
        $$
        \ddot{\theta} + {g \over L}\,\pars{\theta - \pi}\approx 0$$
    which has solutions
    $\theta\pars{t} - \pi \sim \exp\pars{\pm\ic\root{g \over l}t}$
    which oscillates around the lowest point $\ds{\pars{~\mbox{with angular frequency}\ \root{g \over L}~}}$ and it means the motion is stable..
Answer: "Inverted Pendulum" - this means that the pendulum (system) is in it's upright position. The pendulum in its natural pendent state is stable because that position of the system falls in to a stable attractor. As it swings, up on reaching its upright position the attractor  remains no longer stable. The system parameters does receive a small control signal up on reaching the  up right position due to the presence of an attractor(weak). Lyapunov second method works perfectly fine for analyzing stability of this system.The behavior of the angle in the vicinity of the unstable equilibrium position is chaotic, since topological mismatch & Cantor set appears in this position.

Nonlinear Pendulum


IntelliJ, remove scrollbar

Question: Especially when using split screen in JetBrains products, the scrollbar often gets in the way and takes up important screen real estate. Is there a way to disable it? I cannot find an option in IntelliJ/JetBrains-IDE settings.
Comment: Note also that scrollbar behaviour (e.g. you can set it to hide when not scrolling) can be customized in OS settings, see e.g. it in General settings for mac.
Comment: @Andrey yes, but that OS setting doesn't seem to be propagated to IntelliJ.
Answer: There is no actual way to disable the scrollbar. However, one can go into
Color Scheme > General > Vertical Scrollbar > *

and turn Background property to Opacity: 0

I cannot find an option for the horizontal scrollbar.

IntelliJ, remove scrollbar


Check if terminal output matches my string

Question: I'm trying to find if i have the right leptonica version installed. I run tesseract -v and the output is this one:
tesseract 3.04.01

 leptonica-1.73

  libgif 5.1.2 : libjpeg 8d (libjpeg-turbo 1.4.2) : libpng 1.2.54 : libtiff 4.0.6 : zlib 1.2.8 : libwebp 0.4.4 : libopenjp2 2.1.0

The output it's written on stderr, so my script looks like this:
if tesseract -v 2> >(head -n2 | tail -n1) | grep -q 'leptonica-1-73' ; then
    echo "matched"
else
    echo "not found"
fi

When I run the script, it shows:
Syntax error: redirection unexpected.

Any idea why?
Comment: @Igor Chubin thanks for editing my question!
Comment: You can most likely avoid the entire middle of that pipeline: `if tesseract -v 2 | grep -q 'leptonica-1-73'`
Comment: Do you start your script with `#!/bin/sh` or `#!/bin/bash` ? Process substitution is a bash feature. Also exists in ksh and probably zsh
Answer: Yes.
Use
tesseract -v 2>&1 | head -n2 | tail -n1

instead of
tesseract -v 2> >(head -n2 | tail -n1)

Comment: Worked just fine. Thanks a lot!
Comment: @GEazy, please accept the answer if it solved your problem.
Comment: http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235


How do I migrate a custom field from WordPress?

Question: I'm working on migrating a fairly large blog type site from WordPress into Druapl 7. The WordPress Migrate module has imported the basic blog content very well (title, body, tags, etc), however there were custom fields set up in WP that do not import.
Looking at the xml file, there's really just one extra piece of info I need. A line for a video file (which is a code for a youtube video).
Here's how the code for this looks in the XML file:
<code>    <wp:postmeta>
        <wp:meta_key>Video_File</wp:meta_key>
        <wp:meta_value><![CDATA[8ENbMuVQCYE]]></wp:meta_value>
    </wp:postmeta>
</code>
I have decent PHP experience, but the only customizing I've done in Drupal are relating to themes. Can I write a little addition to the WordPress Migrate module to insert this extra piece of info? Since the module migrates everything else nicely can I create a new little module that would go through the same xml file, find the matching node (by post date/time, title, some distinguishing piece of info from the xml file) and then add in the video info (assuming I would first create another row in the DB table)?
I'm at a bit of a loss, and since I need to bring in close to 1000 posts (most of which have the video code), I really need to fine a solution that doesn't involve me editing every single node by hand to add in the dang code.
I should also mention I currently don't have a CCK field in Drupal for the video code... that just dawned on me, so I'm off to create one and then re-migrate a portion of the blog (I downloaded it in multiple xml files for testing).
Update: Created that CCK field, re-imported the blog, and sadly it didn't work :) Not that I thought it would to begin with (nothing is ever that easy).

Update: I've been attempting to modify the WordPress Import module with little success thus far. This meta field is just some text, so I'm hoping to figure out where to add in the info I need to have it process correctly. I'm sure I need to tell it which cck field to insert the new data, just have to find it!

Another Update:
Working on adding a WP plugin to export all the content as a CSV, then going to use the Feeds module to attempt to import everything.
My backup is going to be to use the wordpress_migration module to import the basic stuff (title, body, tags, etc), then write a custom php page to add the video links... I'm basically thinking to find the title in the node table, grab the nid, then create the entry in the video_field in the db table. At least that's how it's currently laid out in my head, whether or not that works in real life remains to be seen.
Course hopefully Feeds works just fine and I won't have to try the backup!
Answer: Neat. It looks like wordpress is storing a small fragment of the youtube url in the DB. I'm not sure how the the cck video field stores content -- probably in its own field, and it probably has to be set for "Youtube" before you attempt a migration.
Once you figure out where the youtube ID will be stored in a drupal field. See the documentation on how to extend worpress migrate:

Extend the appropriate class, such as the WordPressBlogEntry class with your custom behavior - add field mappings in __construct(),
  manipulate the body ($row->content) in prepareRow(), etc.
Extend the WordPressBlog class, and override migrationClasses to point to your custom classes:

<code><?php class MyCustomBlog extends WordPressBlog {
public function migrationClasses() {
    $classes = parent::migrationClasses();
    $classes['WordPressBlogEntry'] = 'MyCustomBlogEntry';
    $classes['WordPressPage'] = 'MyCustomPage';
    return $classes;
} }
</code>
In your custom migration class you would then define the migration of a field using a Mapping as something like:
<code> // dest (a field in the node) <- source
 $this->addFieldMapping('youtube_url', 'source_yt_value');
</code>
In your custom migration class you will of course have access to the typical helper methods used in migrations to "prep" the data (retrieve the youtube url from that CDATA crud), and translate it into a valid video blurb for drupal.
Comment: The youtube info is quite literally just plain text. Whoever set up the blog created a custom simple text field (looks like the WP plugin is called "Custom Field Template") that will accept text (the youtube id), and then later on parse it into a player. I'm fine with doing something similar, I just need to get the text to import with the rest of the content.

I'll try what you wrote, however I'm not a Drupal developer by any means, so I'm not optimistic :) Thanks for the suggestion!
Comment: No such luck thus far - I'm going to install another wp plugin to export the site as a CSV and try using the Feeds module. Adding code to the Wordpress_Migrate module will be a last resort (since I have no idea what to add or where to add it).


Doctrine is trying to allocate 4GB?

Question: I mapped a Post object with Doctrine to the wp_posts table used by Wordpress. A column called post_content in this table is a LONGTEXT that can contains 4GB.
When I try to load the objects from these table, I receive the following message:

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried
  to allocate 4294967296 bytes) in
  /home/rdinhani/renato/php-lib/DoctrineORM-2.2.2/Doctrine/DBAL/Driver/Mysqli/MysqliStatement.php on line 165

This occurs when executing a query to load the objects (at the moment, only ONE row will be returned).
So, Doctrine is trying to allocate 4GB to load the value inside this column, but this overflow the memory. I don't have large values inside this column, only a few texts.
There is some configuration in Doctrine or PHP that can avoid it to try to allocate the 4GB to the column, or maybe, set the maximum limit in MySQL column to a smaller value like 2MB, 10MB, etc?
Comment: PHP usually reports the location of the error. I doubt anybody will be able to help you knowing only that at some unidentified location (possibly in Doctrine) you're running out of memory.
Comment: @lanzz You're right, I updated the message, but the only message I have is in Doctrine when I try to execute a query in the database.
Comment: Doctrine wont be padding out columns to meet the max size in your DB tables. What hydrator are you using for your query? also, can you show us the "Post" entity.
Answer: Mysqli driver has a bug.
When try to select mediumtext or longtext field it tries to allocate the whole field size 2^32 bytes = 4294967296.
Solution: Change to PDO_Mysql or change the medium/longtext field to text field.

Doctrine is trying to allocate 4GB?


Diferença entre "" ou " " no #include

Question: Estou aprendendo a programar em c++, e gostaria de saber qual a diferença de em programar com a biblioteca
#include <iostream>

ou as bibliotecas
#include <stdlib.h>
#include <stdio.h>

Uma eu usaria coisas como std::cout e std::cin e outra eu usaria printf e scanf.
Preciso saber programar com as duas ou posso seguir em uma somente, que no caso eu tava aprendendo com o  std::cout? Elas tem diferença em performace ou algo assim?
Comment: Duplicadas e/ou relacionadas [diferença-de-cout-para-printf-em-c](https://pt.stackoverflow.com/questions/204071/diferen%C3%A7a-de-cout-para-printf-em-c), [posso-substituir-o-cout-e-printf](https://pt.stackoverflow.com/questions/263407/posso-substituir-o-cout-e-printf/263411#263411), [cin-vs-scanf-qual-é-mais-rápido](https://pt.stackoverflow.com/questions/126240/cin-vs-scanf-qual-%C3%A9-mais-r%C3%A1pido)
Answer: Uma é o I/O da biblioteca padrão C, outra é o I/O da Standard Template Library (STL) para C++. Não deve haver diferença substancial de performance entre elas.
Como profissional da área é bom conhecer as duas, porque V. encontrará ambas em código de terceiros.
Em C++ você tem a escolha de uma OU outra, sugiro não misturar porque o I/O é bufferizado (armazenado temporariamente em memória), aí a gravação em arquivo ou exibição no console (stdout/cout) pode acontecer numa ordem diferente da qual você esperava.
Pessoalmente prefiro a biblioteca C por conta das máscaras do printf() que conheço melhor e são empregadas em muitas linguagens diferentes de C, mas não entenda isto como uma recomendação. Use uma e outra e veja qual agrada mais. Muita gente diria que se você programa em C++ deveria evitar a biblioteca C padrão, preferindo o STL.
Comment: Eu gosto muito desta resposta. Tentou evitar a guerra de opiniões entre estilo 'c' e estilo 'c++'. Os dois estilos têm pontos bons e ruins.
Comment: Obrigado pela resposta, vou pegar um conhecimento pra entender a biblioteca padrão de C e irei continuar a usar a (STL), pois aprendi inicialmente ela e me sinto mais confortavel com ela.
Comment: @KyleA valeu :)

Diferença entre "" ou " " no #include


Android good architecture

Question: I am interested in exploring good architectural patterns for Android applications.
I made several experiments with VIPER and generally Clean Architecture approaches but I would like to get some good material/ideas to investigate from you dear SO fellows.
Here are some important points that should be reflected:

It should help handle routing/navigation in a typical single activity/multiple fragments app
It should clearly separate which components/layers will run on background threads and which on the main thread and to communicate between layers (observer pattern, eventbus or whatever)
It uses limited amount of third party libraries and if it does please indicate the pros and cons (like Dagger for Dependency Injection for example)
It helps mantaining orthogonality on the long run while adapting/extending the app. A change in one module should affect the minimum amount of components without having cascading effects because components are thigh coupled.
It would be great to have a look to real examples/prototypes on github or wherever to keep it real and practical without being too much on the academic side ;-)

Thanks in advance for any cool ideas/patterns
Comment: This is not an appropriate question for SO. From the [help center](http://stackoverflow.com/help/dont-ask): _"You should only ask practical, answerable questions based on actual problems that you face. Chatty, open-ended questions diminish the usefulness of our site and push other questions off the front page.... Your questions should be reasonably scoped. If you can imagine an entire book that answers your question, you're asking too much._"
Comment: A vast topic, check some [links](http://mgolokhov.github.io/architecture/)
Answer: You can use MVP + Repository pattern, I am using it in my project and the code is more cleaner,  loosely couple, there are well separated layers. You can add Dagger to dependency injections and RxAndroid to asynchronous task.
This are the best links that I found and helped me to learn this architecture:
http://fernandocejas.com/2014/09/03/architecting-android-the-clean-way/
https://medium.com/android-news/android-architecture-2f12e1c7d4db#.bupsk0o2n
https://medium.com/@artem_zin/m-model-from-mvc-mvp-in-android-flow-and-mortar-bd1e50c45395#.uyij0tjgs
http://fahimk.github.io/2015/04/21/using-rxjava-with-mvp-to-handle-configuration-changes/
https://kmangutov.wordpress.com/2015/03/28/android-mvp-consuming-restful-apis/
https://github.com/sam33rdhakal/MVPandroid/tree/master/app/src/main/java/com/enepalichords/nepalichords
http://magenic.com/Blog/Post/6/An-MVP-Pattern-for-Android
You can find code in the above links and this is one of my projects used to learning purposes :
https://bitbucket.org/emaleavil/cheapshark/
There are many things to improve but I think that can you help to start, this project is unfinished, I'm so sorry.
Comment: Yes I understand, this answer will do it. I was not aware of this SO rule to not allow open discussion, thanks
Comment: I'm sorry. I didn't know that but it's impossible explain all the architecture pattern in a comment.

Android good architecture


Como colocar um botão numa textarea em asp.net, c#?

Question: Boas. Tenho o seguinte esboço de um formulário de contacto feito no wix.com mas queria colocá-lo também no meu projeto asp.net.
Até agora, está assim :

O meu código é o seguinte:

    <form id="form1" runat="server">

                        <asp:TextBox ID="txtName" runat="server" ValidationGroup="contact" placeholder="Nome*"></asp:TextBox>

                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*Campo obrigatório"
                            ControlToValidate="txtName"></asp:RequiredFieldValidator>

                        <asp:TextBox ID="TextBox1" runat="server" placeholder="Assunto*"></asp:TextBox>

                        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="*Campo obrigatório"
                            ControlToValidate="TextBox1"></asp:RequiredFieldValidator>

                        <asp:TextBox ID="txtEmail" runat="server" placeholder="Email*"></asp:TextBox>

                        <asp:RegularExpressionValidator ID="valRegEx" runat="server"
                            ControlToValidate="txtEmail"
                            ValidationExpression=".*@.*\..*"
                            ErrorMessage="*Endereço de email inválido."
                            Display="dynamic">

                        </asp:RegularExpressionValidator>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="*Campo obrigatório"
                            ControlToValidate="txtEmail"></asp:RequiredFieldValidator>

                        <asp:TextBox ID="TextBox2" runat="server" TextMode="MultiLine" placeholder="Mensagem*"></asp:TextBox>

                        <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="*Campo obrigatório"
                            ControlToValidate="TextBox2"></asp:RequiredFieldValidator>

                    <%--	--%>

                        <asp:Button ID="btnSend"  runat="server" Text="Enviar"  OnClick="btnSend_Click" />

                    <%--	--%>

                        <asp:Label ID="lblMessage" runat="server" Text="" ForeColor="Green"></asp:Label>

    </form>

Alguém tem como ajudar por favor? Obrigado desde já!
Answer: Nesse caso, é só "brincar" com o CSS e não colocar o seu botão em uma nova
. Veja o exemplo abaixo:

textarea,
input,
button {
  border: 2px solid rgba(7, 143, 27, 1);
  padding: 5px 10px;
  background-color: white;
  font-family: Arial;
  width: 400px;
  height: 33px;
}

textarea {
  height: 150px;
}

button {
  width: 200px;
  height: 60px;
  display: block;
  margin: 80px auto;
  position: absolute;
}

td {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-align: center;
  -moz-box-align: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;
  justify-content: center;
  -webkit-justify-content: center;
  -webkit-box-pack: center;
  -moz-box-pack: center;
  -ms-flex-pack: center;
}

  <form id="form1" runat="server">

            <input type="text" ID="txtName" ValidationGroup="contact" placeholder="Nome*" />

            <input type="text" ID="TextBox1" placeholder="Assunto*" />

            <input type="text" ID="txtEmail" placeholder="Email*">

            <button ID="btnSend">Enviar</button>
            <textarea ID="TextBox2" TextMode="MultiLine" placeholder="Mensagem*"></textarea>

  </form>

Comment: Boa jovem pensei a mesma coisa, só que com position apenas, pra não ter que mudar de table-cell para flex. Espero que não se importe de ter usado parte de seu código ;)
Comment: @hugocsl, É todo seu, css eu só dou pitaco pra não deixar o AP na mão e espero alguém vir com a resposta mais completa.
Comment: Para mim serviu! Obrigado :)
Comment: Tem horas que o simples é o mais difícil de pensar rss e falando em CSS quase sempre tem mais de um jeito de fazer... []´s
Answer: Minha ressalva com relação ao código do Leandro é o cuidado em não mudar o display do elemento que é uma table-cell por flex. Acredito que com position apenas seja mais adequado para essa situação.
Usado parde do código do @LeandroAngelo fiz esse modelo.

textarea,
input,
button {
  border: 2px solid rgba(7, 143, 27, 1);
  padding: 5px 10px;
  background-color: white;
  font-family: Arial;
  width: 400px;
  height: 33px;
}

textarea {
  height: 150px;
}

button {
  width: 200px;
    height: 60px;
    position: absolute;
    bottom: -22px;
    margin: 0 auto;
    left: 0;
    right: 0;
}
.rel {
  position: relative;
}
<form id="form1" runat="server">

          <input type="text" ID="txtName" ValidationGroup="contact" placeholder="Nome*" />

          <input type="text" ID="TextBox1" placeholder="Assunto*" />

          <input type="text" ID="txtEmail" placeholder="Email*">

          <button ID="btnSend">Enviar</button>
          <textarea ID="TextBox2" TextMode="MultiLine" placeholder="Mensagem*"></textarea>

</form>


Updating the probability distribution when removing links from a Bayesian network

Question: I have spent a fair amount of time trying to solve this problem but I can't find the solution. More specifically, I have the following matrix:
<code>P(D|E&F) = [ 0.5 0.3 0.5 0.2 ;
             0.5 0.7 0.5 0.8 ]
</code>
All the variables are binary (two states)
D, E and F are nodes of a Bayesian network. E and F are the parents of D and they are independent.
Now, new evidence comes in and we know that D and E are independent as well (the link between D and F remains but the arc from E to D is removed). How do I go about finding P(D|F) from P(D|E&F) ?
Answer: You should add the Bayesian network to your question since that implies a further independence assumption: E and F are independent give D.
There might still be something missing.  Do you know P(E)?  In that case, you could simply marginalize over E: $P(D|F) = \sum_i P(E=i)P(D|E=i \cap F)$.
Comment: Ok - strange notations. More rigorously this is $\Pr(D=i \mid E=j \cap F=k)$. Therefore your notation $\Pr(F)$ is not clear because $F$ is a r.v. and not an event.
Comment: Hm..I think @NeilG is right because E and F are also independent (they're the parents of D). Therefore, if I'm not mistaken P(E=i∣F) will become P(E=i)
Comment: @Neil this does not help to answer the question.
Comment: @StéphaneLaurent: Please have a look at the whole question including the probability table given.  Your answer misses half the question.
Comment: $\Pr(D \mid E\cap F)$ is a number, so what is this matrix ?
Comment: It's P(D|EF).  Did you notice that they're binary variables?
Comment: @Neil G: The comments cannot be understood if you replace your answer by another one... And your last formula $P(D|F) = \sum_i P(E=i)P(D|E=i \cap F)$ is not correct.
Comment: I thought about marginalization but I couldn't understand how to do it exactly! What's wrong with the formula @StéphaneLaurent?
Comment: The correct formula is $P(D|F) = \sum_i P(E=i \mid F)P(D|E=i \cap F)$
Comment: You really shoud edit your question and add all the assumptions !
Comment: Yes, you're right. I changed the details. I apologise for the confusion. I guess the issue is settled! Thanks both of you for the help!
Answer: You cannot conclude anything. For example, consider two independent r.v.\ $X$ and $Y$ taking positive integer values. Take $D=\{X=1\}$, $E=\{Y=2\}$, and $F=\{X+Y=3\}$. Then the equality $\Pr(D \mid F)=\Pr(D \cap E\cap F)$ is equivalent to $\Pr(X+Y=3)=\Pr(X=1 \cap Y=2)$, which can be true in some cases, and false in other cases.
By the way, I do not understand why $\Pr(D \mid E\cap F)$ is a matrix in your question ?
EDIT: my interpretation of the question was not the right one - see the answer by Neil G
EDIT2: Neil G has now completely deleted the above mentioned answer...
Comment: Ok. So this question's taken from a past exam paper for Bayesian Networks. I was given that matrix because there is a child node D with two parents E and F. However, at some point the question specifies that the link between E and D must be removed since E and D are independent. And the question asks to deduce P(D|F) from P(D|E&F). Therefore, I assume that the question must have an answer but you said that we cannot conclude anything. Thanks for answering tho!
Comment: My question doesn't have any Pr(D∩E∩F) matrix!!!
Comment: Sorry: $\Pr(D \mid E\cap F)$, I will edit my post. And my answer does not satisfy you ?
Comment: Sorry I don't know about the notion of "child node". You could remove $E$ if $D$ and $E$ are conditionally independent given $F$, for instance.
Comment: You're right George, you can remove the link between D and E.  Stephane's answer assumes that F can render D and E dependent, but that's inconsistent with your graphical model.


What key is a piece in if an augmented chord is used as a dominant?

Question: I personally think that augmented chords can be just as consonant as major if used in a certain way. For example, in the first octave of a piano, if I play an augmented chord, yes it will want to resolve but not as much as say if I played that same chord an octave lower in the small octave. But in a way, augmented is ambiguous. You don't have 1 single root, you have 3 roots, 3 mediants, and 3 dominants. But at the same time these can be viewed as inversions of a single chord.
Here are the resolutions I get for C augmented in order of most natural to least:
C aug -> A minor 1st inversion(Harmonic minor scale has this augmented chord in it)
C aug -> C major
C aug 1st inversion -> E major
C aug 1st inversion -> A minor 2nd inversion
C aug 1st inversion -> C major 1st inversion
C aug 1st inversion -> C# minor 1st inversion
C aug 2nd inversion -> Ab major
C aug 2nd inversion -> A minor
C aug 2nd inversion -> C major 2nd inversion
C aug 2nd inversion -> F minor 1st inversion
That's all from 1 chord but that is 3 separate major/minor key pairs. At the same time E major can be viewed as the resolution of E aug and same for the Ab major and Ab aug. In turn C major can be viewed from any of those 3 keys as a resolution so what key are you playing something in if you are using the augmented chord as a dominant function chord? The major with the same lower note as the chord? The relative minor of that? Something else entirely? It sounds like it is not sure where it wants to resolve, just where it naturally would land out of 6 chords(namely the relative minor of the lower note). But all 6 chords are resolutions that sound equally as good.
With diminished you have a similar thing going on but only between 2 chords which are not equidistant on the circle of 5ths(for example B major and C minor both from C diminished). I mean to go from B major to C minor would take 8 or 4 steps through the majors and then 1 more step to relative minor depending on whether you go in the flat direction or in the sharp direction. With augmented, it is 4 steps in either direction through the majors that both resolve so what key are you in? C major? E major? Ab major?
So how can you tell the key a piece is in just from an augmented chord in the harmony? Is that even possible?
Comment: Just like with diminished 7th chords, I suspect that the tonic is whatever the root of the chord straight after the (augmented/diminished) dominant-function chord is. (I've used augmented chords as dominant-function chords before, and I've also found such chords in the Prism Plains theme from Kirby Squeak Squad.)
Comment: Since there are  only really four augmented chords in equal temperament tuning (C C# D and D#) if you have four resolutions for the "first and second inversions" there are also four for the "root position" (I use the quote marks  because there is no real difference between the "inversions" and "root" augmented chords - Caug first inversion and Eaug root position are identical). One of the missing resolutions is Caug -> F which was quite common in the classical period.
Comment: Actually there are (at least) SIX resolutions of an augmented chord that all work the same way: just move one of the notes either up a semitone or down a semitone. But maybe the OP didn't consider "Caug -> C#minor" to be "in the key of C major" (though  I would consider it that way - C#minor is just the minor form of the "Neapolitan" chord, more usually spelled as D flat not C sharp).
Answer: Starting in the 19th century, augmented triads started to be used as dominant sonorities. Or, put another way, augmented triads became acceptable dominant sonorities in the 19th century.
In other words, augmented triads can be the dominant of the tonality. C augmented (C E G♯), therefore, would be the dominant of F (major or minor), and thus you might be in the key of F.
If this C augmented is spelled enharmonically as E augmented (the chord thus being E G♯ B♯), you would resolve to A. If the C augmented is spelled as A♭ C E/G♯ B♯ D, it would resolve to a tonic of D♭ or C♯, respectively.
And for what it's worth, the III+ augmented chord (the augmented triad in the harmonic scale) is very rarely used in tonal music. In my experience, a III+ chord is usually a V chord with scale-degree 3 functioning as a non-chord tone.
Comment: Would C augmented be spelled with Ab, as then there would be no augmented 5th, only a minor 6th? Or maybe you meant 'the chord containing these notes'.
Comment: @Tim No, I meant the correct tertian spellings of those augmented triads. I'll edit to try and make it more clear.
Comment: "the III+ augmented chord (the augmented triad in the harmonic scale) is very rarely used in tonal music" - you're right.  However, they are still more common in classical music than modern popular music.  I've seen Chopin using an III+ in his Ballade No. 1 in g-minor.
Answer: Rather like the diminished chords, of which there are essentially three, after which, going up a semitone each time, we get back to the same notes as the first one; there are four augmented chords.
Their names may be different, and the names of their notes certainly will be, but essentially their make-up results in only four.
For example, C E G# =C+, But E G# B# = E+, and G# B# Dx = G#+. The last could also be spelled Ab C E. So there's 3 different keys to head to after hearing those three notes, which constitute a kind of dominant chord. Their inversions may feel the need to head in a particular direction, but that's subjective.
It stands to reason that there's C#+, D+, and Eb+, going up in semitones, before we hit the same notes again as the first example, C+.
Answer: Same key as it would if the dominant was a plain major triad.
You're over-thinking this.   C7 is the dominant of F.  C7(#5) is still the dominant of F.  Maybe even stronger because as well as the E - Bb tritone pushibg towards F - A, we also have the G# pushing towards A.  (They might not both actually resolve to A, but that's another matter.)
And a chromatic note doesn't have to imply a change of key.  (Otherwise there wouldn't BE any chromatic notes, just loads of modulations, sometimes to several keys at once!)
Answer: It would still be the same key as if the dominant was a major triad or a dominant-seventh (major-minor seventh) chord.

An augmented dominant chord is an altered chord that is derived from the V chord of a key.  The 5th note of the chord is raised, causing it to become an augmented triad.  We need to remember that an augmented chord is considered dissonant, therefore it requires a specific way of resolution.  The 3rd and the 5th of the chord need to move a half-step (minor 2nd) up, and the resolved chord must always be a major triad.
We have a set of a dominant and secondary dominants in all 30 keys.  In C-major, for instance, we would have:

G - C (C: V - I)
A - Dm (C: V/ii - ii)
B - Em (C: V/iii - iii)
C - F (C: V/IV - IV) (same as C: I - IV)
D - G (C: V/V - V)
E - Am (C: V/vi - vi)
F♯ - Bdim (C: V/viio - viio)

We can turn all of them to augmented chords.  We get:

Gaug - C (C: V+ - I)
Aaug - D (C: V+/ii - V/V)
Baug - E (C: V+/iii - V/vi)
Caug - F (C: V+/IV - IV)
Daug - G (C: V+/V - V)
Eaug - A (C: V+/vi - V/ii)
F♯aug - B (C: V+/viio - V/iii)

Please note that the secondary V+ chords over ii, iii, vi, and viio are being resolved to another secondary dominant because we need to resolve the 3rd and the 5th altogether.


java read from file. the last row overwrites the values of the previous lines in list

Question: I have a file name 1.txt
Coupe 1 2
Coupe 3 4

and I have a code
br = new BufferedReader(new FileReader("1.txt"));
String tmp = "";
while ((tmp = br.readLine()) != null) {
String[] s = tmp.split("\\s");
comfortName = s[0];
tickets = Integer.parseInt(br.readLine());
baggage = Integer.parseInt(br.readLine());
// next code send to constructor of class from value of comfort name a parametrs.
Class[] e = new Class[]{Integer.TYPE,Integer.TYPE};
comfortName = "second.objects.carriages.type." + comfortName;
Class carriageClass = Class.forName(comfortName); Constructor constructor = carriageClass.getDeclaredConstructor(e);
passenger = (Passenger) constructor.newInstance((tickets),(baggage));
// the next line add to list a value from constructor
carriage.addPassenger(passenger);

add passenger code:
 public boolean addPassenger(Passenger passenger) {
        totalPassenger +=Passenger.getTickets();
        totalBaggage+=Passenger.getBaggage();
        return Carriage.getPassengerList() .add(passenger);
    }

So the result when I send it to list have something like that:
Coupe 3 4
Coupe 3 4

But from debugger I see that values reading good. but always the last row
overwrites the values of the previous lines in list .
So when I send only one row it's working
Comment: thanks ! now i understanding why
Comment: int tickets = Integer.parseInt(br.readLine());
  int baggage = Integer.parseInt(br.readLine()); should throw a NumberFormatException
Comment: yeah, i make a try catch , but for this question to smallest code i have deleted it
Comment: The java.lang.Class.newInstance() creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.
Comment: so the problem is solved. My mistake was in static variables tickets and baggage.
Answer: You have a typo in your code
I believe you should get tickets and baggage from the splitted array
tickets = Integer.parseInt(s[1]);
baggage = Integer.parseInt(s[2]);

instead of reading next lines, below will throw exception
tickets = Integer.parseInt(br.readLine());
baggage = Integer.parseInt(br.readLine());

Comment: Yes, it will throw exception
Answer: The java.lang.Class.newInstance() creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.
This sample code is working fine for me.
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new FileReader(System.getProperty("user.dir") + "/src/1.txt"));
String tmp = "";
while ((tmp = br.readLine()) != null) {
    String[] s = tmp.split("\\s+");
    String comfortName = s[0];
    int tickets = Integer.parseInt(s[1]);
    int baggage = Integer.parseInt(s[2]);
    System.out.println(comfortName + tickets + baggage);

}
br.close();

}
on console :
Coupe12
Coupe34

Comment: it's trows ArrayIndexOutOfBoundsException. the example that i send working when i send to console values from this class. but when i'm send it to list the last row overwrites the values of the previous lines in list
Comment: did you try it without creating a new instance of the class constructor?
Comment: check the data in your file, line should be able to split into three substrings, proper spaces are given in between for ArrayIndexOutOfBoundsException
Answer: Check your Passenger constructor that you create instance.
passenger = (Passenger) constructor.newInstance((tickets),(baggage));

The problem is at you constructor. If you constructor create new instance of Passenger object it will be ok. You constructor should be like that:
private Passenger(int tickets, int baggage){
   this.tickets = tickets;
   this.baggage = baggage;
}

Comment: My constructor looking like that ;) but when I'm send one passenger , all is good. So when I'm send more than one - the last passenger overrides the previous passenger


Regenerate Graphite dashboard

Question: I have a bunch of machines pushing data into a dashboard in Graphite and the number of machines is constantly growing so I am wondering whether is a way to automatically regenerate a dashboard based on the machines that are providing various stats.
Like, I don't want to manually add machines to the dashboard each time I add new ones - I want to have a background task running for this.
Answer: You should be able to do this by reporting metric names in a task oriented format and wild cards.
Example: <site>.<purpose>.<hostname>.<platform>.<stats>
You can also just use a wildcard anywhere (<site>.*.*.*.<stat>) and as long as that metric exists at that level it will be included in the graph.

Regenerate Graphite dashboard


Grouping fields together

Question: Is it possible to generate fields which are "grouped" together when marked as Unlimited? For example, a select field with label "What time do you wake up?" lets the user select the day of the week (Mon-Sun) then beside it an empty textfield to type in the time they get up. These 2 fields are "grouped" together. Then if they want to add another day of the week (Unlimited), the new field generates a dropdown menu and a textfield together all over again.
NOTE: No CCK please. I'm using Drupal 7 and it's already in the core.
Answer: Try the Field Collection module. It's not stable yet (beta 1) but it looks promising.
Comment: I'll check it out.
Comment: Stupid question but how do I use Field Collection? I just installed it.
Comment: You can download the recruiter distribution to see how it's implemented. Other wise the field collections or like nodes (entities) that you can add to the actual node as a field for each collection. So, make a bunch of collections like they are their own node, then make a node and add the collections which are individual fields.
Answer: I know the Drupal way to build a module that solves everybody's problems but I needed something a little more specific. Here is my business hours module. I made it with the Field API which is actually very easy to use.
Comment: IMO there is nothing wrong with a well written custom module that uses the API as intended. Thanks for sharing.
Answer: This is actuall a feature in CCK 3, which is in alpha for D6 but not yet available (as an "extras" module) for D7...
Shame, they should've had this by default.
Here is a discussion about modules that have similar functionality:
http://drupal.org/node/939836
But Field collection seems to be the smartest choice for now.
Comment: While OP has specified no CCK solutions, it is nice to have them.

Grouping fields together


What to change in .htaccess?

Question: I am installing Drupal 7 on a subdomain example.com/exampledev2 and I am running into problems with .htaccess. Meaning when I put the files in the root for the first time I get a 500 Internal Server Error, but if I rename it to .htaccess_off or something I can begin installation. Then when I get to the last step, after filling in the site info and creating a user, I click the continue button and I get a Error 500 Internal Server error. I am assuming this has something to do with having .htaccess no longer working, but I can't turn it on, or I get the error before installation. Any advice on how to change the file so I can use it?
EDIT: This is the .htaccess file that finally worked for me:
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$">
  Order allow,deny
</FilesMatch>

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess, because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\." - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  RewriteBase /mysite
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

  # Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
  # Serve gzip compressed CSS files if they exist and the client accepts gzip.
  RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

EDIT: I think the problem was not totally the htaccess file. The file did "direct" me to a WSOD page if it wasn't fixed, but I don't think it was the reason that when I got to the end of the install process I got an Error 500 screen. I think this was cause by having incorrect access to the database? During the process of install I may have changed the password, and then not updated it in the install.php process. Anyways I got the site up and working and will give some credit to MPD because it is a good answer.
Answer: It sounds like you aren't actually running in a subdomain, but rather a subdirectory.  If you really are in a subdirectory, you you need to have .htaccess read (line 98ish, without the leading #)
RewriteBase /exampledev2

A 500 error typically means that something went wrong with Apache and/or PHP.  In general, it isn't a syntax error or anything else in code, but usually something configuration related.
The WSOD page should be some help.  You really need to see the Apache error_log to see exactly what went wrong.
If I had to guess, your setup is disallowing one or more directives in the .htaccess file.  If you are on shared hosting, this is a real possibility.
Nearly everything in .htaccess is feature detected via <IfModule> directives, but there are a few things that may be disallowed.  I have worked on systems where the Options can't be overridden.  Try commenting out those lines.  Drupal should still work, though there may be some security implications by not having the Options -Indexes.
If you comment out those lines, and everything works, then you need to talk to your sysadmin about how to fix this long term.  Ideally, you shouldn't need (or want) to do that.
Comment: Congratulations! Welcome in the 10K user arena. `:)`
Comment: Yes Part of the problem is that this site is set up on a university system, which has its own servers, and its own section of sysadmins, who I am not sure would love to share the apache error log. I did get it installed, with the .htaccess named something else. I will post the contents of the file that we have working on the site now.

What to change in .htaccess?


PSQL outer join keep joined columns unique

Question: Say I have two tables that look like the following:
Student
age|name|gender
---+----+------
 3 |jon | M
 4 |mike| M
 2 |Sue | F

Teacher:
experience|name|college
----------+----+-------
10 years  |Sue | UVA
23 years  |Tom | Yale
9 years   |Bob | Harvard

When performing an outer join, how would I combine this table while being able to identify the difference between Sue Teacher and Sue Student?
Comment: By adding a unique id.
Comment: Could you post an example in an answer format?
Comment: And also, show us your current select, and describe whats wrong with it!
Comment: If you are doing an outer join, there should be column(s) common to both tables. I don't see any. As @jarth says, give us more details and perhaps we can help.
Answer: Do you mean a UNION instead of an outer join?
SELECT 'student' as type, name
  FROM student
 UNION SELECT 'teacher' as type, name
  FROM teacher


Are Pianos and Electric Guitar Keys the same?

Question: So I know that Pianos Keys are pretty simple to understand, yea? Like C1 is just the first time C comes up, but how does that relate to guitar? More specifically, F#5 on keyboard is easy to find, but where is that on a guitar?
I've done some google searches and found differing answers. Some saying you can play guitar in the same key, some saying pianos are in C while Guitars are in E, or in G. So I thought that maybe I could play a couple keys up like f#5(G, 11th Fret) was really the same key three whole steps upward. (B,16th fret)
I'm really just confused at this point and would really like if someone can explain where F#5 would be on guitar, and how I can find other keys. I figured they might be the same and I might just be overthinking it, but when I played the notes, it sounded outright wrong.
I've been using trying to use this image here to try and figure it all out.
[1]: https://i.stack.imgur.com/9XPd6.jpg
Comment: I'm having a hard time understanding what you're asking. Pianos and guitars a very different in terms of how the notes are arranged. They can both play essentially any combination of notes, but the way you play those combinations is very different. And the lowest note the piano can play lower than the guitars lowest note, and the highest note the piano can play is higher than the guitar. So what are you trying to understand about them?
Comment: The diagram looks correct to me, indeed, as @ToddWilcox wrote it covers only the notes in the (typical) guitar range. The note on 11th fret on G string is F#4, not F#5, OP read the diagram incorrectly (note guitar transposes by an octave down). I also don't understand what is the question. For starters, is the guitar in tune?
Comment: I think that diagram is confusing you because it's not very well made. That diagram doesn't show the whole piano keyboard.
Comment: The diagram tells you: The 5th octave is pink. There are three pink F# on the guitar: E/14th fret, B 19th fret and G 23rd fret (which not all guitars have).
Answer: I'm going to go out on a limb and guess that your confusing the idea of a musical "key", a set of notes and a tonic, with a physical "key" on a keyboard. Correct me if wrong, please.
Each key on a piano corresponds to a note. Every fret + string (ex 1st string 5th fret) combination on a guitar corresponds to a note. Every note on a guitar can be played on a piano. Not every note on a piano can be played on a guitar, because a piano might have a larger range (lower and maybe higher than the guitar can play).
Your image is correct for a guitar in standard tuning. Guitars are not "in a key", they are "in a tuning". Guitars can play in any key, provided the musician knows how to. Notes also occur in multiple locations on a guitar. You can see from the image that F#5 appears on three different strings. This is just the nature of the instrument. These locations of the note F# (in standard tuning) are string 1 fret 14, string 3 fret 19, and string 3 fret 23 (which guitar may not have).
Edit: If your guitar sounds "Wrong" I would make sure it is in tune and maybe even correctly intonated. Worry about tuning first
Answer: Guitars are an octave-transposing instrument.  This means they play in C*, the same key as a piano, but one octave lower than written.  (Why?)
The lowest note on a standard-tuning guitar sounds an E2, and this would be called "concert E2". On a written score, however, it will be written an octave up, as an E3.  From there, you can count up just like a piano.  Personally, I prefer to talk about the guitar in concert pitch, especially since I play genres that don't typically use written music anyway.
So, where is (concert) F#5 on a guitar?  Well, the lowest F# you can play on a guitar is F#2, since that's the first F# that's not lower than E2.  Then the next highest F# is F#3, then the next is F#4, then finally F#5.

Original guitar image from Wikipedia
*An instrument in C means that a C played on the instrument is the same pitch as a C on a piano.  Music can be played on a guitar in any key, just as with a piano.
Answer: "keys", on a piano, are the things you press to make notes sound. they are not the notes themself -- D is a note, you sound it on a piano by depressing a key, you sound it on a guitar by plucking (and perhaps also fretting) a string.
"key", in the sense of instrument tuning, is difficult to explain but relates to non-octave transposing instruments. you do not need to worry about this, the guitar is an octave-transposing instrument; your low E string is the same as an E on a piano, but if you're reading sheet music, it's an octave down from where it would be on a piano. a guitar is, in this sense, "in C".
in my experience, many guitarists do not use transposing terminology, and "in C" to a guitarist might instead mean that the guitar is drop-tuned to C-G-C-F-A-D. this is incorrect terminology if you are hoping to communicate with musicians who play transposing instruments (e.g., in a jazz or ska band), but it's common, and is probably why you have heard the statement that guitars are "in E" (meaning, that the lowest string in standard tuning is tuned to E). to be explicit, despite using the phraseology of key ("in E"), guitarists are not taking about key when they use this language in this way, they are talking about tuning. i would strongly recommend never using this terminology in this way.
there is also "key" in the sense of tonality. this is more abstract again, it broadly describes the chord you might expect to end a song on (oversimplifying because you don't seem ready).
for some reason, musicians insist on giving every theory-specific word three distinct meanings. this is extremely frustrating for beginners.
Comment: i suppose if you are reading tab that assumes an alternate tuning, then in a very weird sense, you are playing a transposing instrument. i think this is pushing the original context for the terminology so far that it's not really accurate -- in some contexts, trombones will read treble clef in B-flat, but i dont think anyone would say that "trombone is sometimes in B-flat", we all know it predominantly sounds what it reads in C.
Answer: Pianos and guitars have no 'key' as they offer multiple octaves of notes. Woodwind instruments have a fixed number of notes and can be purchased in different keys.
However, to make sheet music easier, some instruments have music in one key and make sounds in another key. For example a clarinet's C natural sounds exactly like the piano's B flat ... to make the sheet music for clarinet simpler, no accidentals in the key of C.
It's a transposing instrument.
https://www.soundslice.com/blog/2/transposing-instruments/
Don't confuse the name of the tuning of a guitar with the key. A guitar tuned in "Open G tuning" means the open strings are the notes of a G major chord.
Guitar strings are tuned:
E2–A2–D3–G3–B3–E4
A2 is 110.00 Hz.
Bass strings are one octave lower and are tuned:
E1–A1–D2–G2
A1 has half the frequency of A2 i.e. 55 Hz.
https://newt.phys.unsw.edu.au/jw/notes.html
https://en.wikipedia.org/wiki/Guitar_tunings#Standard
The diagram you noted seems clear. The F♯5 is between pink-5 and pink-6 ... B string 19th fret ... or E string 14th fret ... or G string 23rd fret.
That's a really good diagram!
Comment: There are some confusing statements in this answer. A couple - clarinet music (with a Bb clarinet- others are available) isn't written in key C to make it easier (though it may be), it's to make it in tune. And 6 string bass guitars? Mine isn't tuned EADGBE, it's the standard BEADGC. And most have only 4 or 5 strings.
Comment: @ojs The reason transposing instruments exist is a completely different question which has been explained both on this site and elsewhere.
Comment: Orchestral woodwind instruments are not built 'in a key'. They can play in any key even if they are transposing instruments. There is no such thing as a 'transpositional' instrument.
Comment: @PiedPiper: But aren't most of the transposing instruments derived from earlier instruments that clearly were built in a key (e.g. the [natural horn](https://en.wikipedia.org/wiki/Natural_horn) as the predecessor to the [French horn](https://en.wikipedia.org/wiki/French_horn))?
Comment: It's interesting that the existence of transposing instruments is just a fact and doesn't need any explanation.
Comment: @PiedPiper Oh that's right!@ ... it's not a key, it's a range.


Is there a way to obtain, by name, a function at current process in Windows?

Question: Is there an equivalent of the following on Windows?
#include <dlfcn.h>
#include <stdio.h>

void main_greeting(void)
{
    printf("%s\n", "hello world");
}

void lib_func(void)
{
    void (*greeting)(void) = dlsym(RTLD_MAIN_ONLY, "main_greeting");

    greeting ? greeting() : printf("%s\n", dlerror());
}

int main(void)
{
    lib_func();

    return 0;
}

This is a short snippet, the real purpose is to call a function know to exist at a main process (main_greeting), from inside a function (lib_func) from a dynamic loaded library. The main process is not modifiable, and so cannot be rewritten to pass callbacks.
Comment: I don't understand, there are lots of C compilers for Windows.
Comment: @Hogan, this is not much about compilers, it's more about platform process/library tooling.
Comment: I doubt it. If there's no debugging information either in the executable itself or in the symbol file (e.g. .pdb), you can't locate a function by its name in the .exe because they are not supposed to export functions. You most likely would need to find the function relative to the base of the .exe, find the base at run time, add the offset and only then call.
Comment: "call a function know to exist at a main process from inside a function" is difficult to understand, please clarify
Comment: @chico - See Anton Kovalenko's answer below -- clearly this is simple via gcc (for example).  Thus the real question was not as above as pointed out by Alexy Frunze.  The real question was "I can't get this to work with MS's compiler.  (Maybe the phrasing of my comment failed to get this across :)
Comment: @Hogan, sorry, I'm being generalist here. The question is really toward platform/library tooling. I want to know whether the Windows OS allows this for `.exe's`. Knowing MinGW provides exporting from executables through a simple option is nice to know. I'm not asking specific for msvc, I want to know about its options too.
Comment: @AlexeyFrunze, Thanks, I know about the hacking way when the PE don't have exports, but I'm not really toward using this option. I wanted to know two things, "Is it possible to have executable exports?" and "How to call them?" AntonKovalenko had figured it out.
Answer: On Windows, executables and DLLs are of the same format (PE nowadays), so an executable can export functions too. GetProcAddress(GetModuleHandle(NULL),TEXT("main_greeting")) will do what you want if the function is exported from the executable. It's done by -Wl,-export-all-symbols for mingw GCC.
I believe there is no equivalent option for Microsoft's linker, so if you use their toolchain, you have to:

export every function with __declspec(dllexport) in source files,
or write a module definition file listing every exported function, passing it to linker,
or generate module definition file automatically.
Comment: @chico Then add that to the question and retag it.
Comment: Thanks, I'd like to know whether msvc has such a option tough.
Comment: @chico see http://stackoverflow.com/questions/225432/export-all-symbols-when-creating-a-dll for a two-stage solution (involving autogenerated .def file)
Comment: @AntonKovalenko Looking at http://msdn.microsoft.com/en-us/library/28d6s79h.aspx I see, for msvc, it boils down to using Module-Definition Files for defining the exports of .exe's.
Comment: @chico There's no problem if you don't mind writing .def file manually, listing all exported functions. The link above was for *automatic* generation of a .def file to export *everything*.
Comment: @AntonKovalenko could you replace "(don't know of msvc equivalent)" by mentioning it boils down to that? (`/DEF` and Module-Definition Files)
Comment: @AntonKovalenko and also stating that, as such, Windows `.exe's` can have exports too as dynamic libraries have. (I guess I'm building an answer of my own :P)