Android Fragment null object mNextAnim Internal Crash

Question: Users of the app I am working on have a crashing issue. This is the stack trace I get from the console.
java.lang.NullPointerException: Attempt to write to field 'int android.support.v4.app.Fragment.mNextAnim' on a null object reference
at android.support.v4.app.BackStackRecord.popFromBackStack(BackStackRecord.java:924)
at android.support.v4.app.FragmentManagerImpl.popBackStackState(FragmentManager.java:1605)
at android.support.v4.app.FragmentManagerImpl$4.run(FragmentManager.java:532)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

The crash only happens with users that have Galaxy Note3 or Galaxy S4 phones with 5.x or at least those our the only one that have got reported but it has happen a lot. It seems to happen on transition between fragments or sometimes when coming back from the camera. Here are my transition methods.
public void popBackStackToOr(String popBackFragmentName, String secondPopBackFragment)
{
    int backStackId = 0;
    int backStackCount = getSupportFragmentManager().getBackStackEntryCount();

    List<Fragment> fragments = getSupportFragmentManager().getFragments();

    for (int k = (backStackCount - 1); k > 0; k--)
    {
        String aFragmentClass = fragments.get(k).getClass().toString();
        String[] splitList = aFragmentClass.split("\\.");
        aFragmentClass = splitList[splitList.length - 1];

        boolean firstOptionTrue  = aFragmentClass.equalsIgnoreCase(popBackFragmentName);
        boolean secondOptionTrue = aFragmentClass.equalsIgnoreCase(secondPopBackFragment);

        if ( (firstOptionTrue) || (secondOptionTrue) )
        {
            backStackId = getSupportFragmentManager().getBackStackEntryAt(k).getId();
            break;
        }
    }

    getSupportFragmentManager().popBackStack(backStackId, android.support.v4.app.FragmentManager.POP_BACK_STACK_INCLUSIVE); //Immediate
}

public void popBackStackForReview(String popBackFragmentName)
{
    int backStackId = 0;
    int backStackCount = getSupportFragmentManager().getBackStackEntryCount();

    List<Fragment> fragments = getSupportFragmentManager().getFragments();

    for (int k = (backStackCount - 1); k > 0; k--)
    {
        String aFragmentClass = fragments.get(k).getClass().toString();
        String[] splitList = aFragmentClass.split("\\.");
        aFragmentClass = splitList[splitList.length - 1];
        if (aFragmentClass.equalsIgnoreCase(popBackFragmentName))
        {
            backStackId = getSupportFragmentManager().getBackStackEntryAt(k).getId();
            break;
        }
    }

    getSupportFragmentManager().popBackStack(backStackId, android.support.v4.app.FragmentManager.POP_BACK_STACK_INCLUSIVE);
}

public void transitionToLoginPage()
{
    Fragment newFragment = new LoginPage();

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

    transaction.replace(R.id.frame_container, newFragment);
    //transaction.addToBackStack(null);

    transaction.commitAllowingStateLoss();
}

public void transitionToNewScreen(Fragment newFragment, Bundle bundle)
{
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

    if (currentFragment != null)
    {
        transaction.remove(currentFragment);
    }

    currentFragment = newFragment;

    if (bundle != null)
    {
        newFragment.setArguments(bundle);
    }

    transaction.replace(R.id.frame_container, newFragment);
    transaction.addToBackStack("dummy");

    transaction.commitAllowingStateLoss();
}

public void transitionToNewScreenAndEmptyStack(Fragment newFragment)
{
    getSupportFragmentManager().popBackStack(0, android.support.v4.app.FragmentManager.POP_BACK_STACK_INCLUSIVE);

    currentFragment = newFragment;

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.frame_container, newFragment);
    transaction.addToBackStack(null);
    transaction.commitAllowingStateLoss();
}

These are the only methods that do transition in the app. So I am assuming it is coming from one of these. But the stack trace does not go back to any code I wrote so I am not sure. I have found similar problems saying that this is a Android 5.x issue and there was no fix. So any help to remove this issue would be great
Comment: have you tried replacing commitAllowingStateLoss() by commit() ?
Comment: No I have not tried that I can try to replace it, see what happens.
Comment: That fixed it but caused a problems for older devices crashes and other problems
Answer: It's because you are calling remove() add() etc. methods with null value.

 and please keep in mind that replace() = remove()->add() one by one.
Answer: Try to use Fragments extending android.support.v4.app.Fragment instead of android.app.Fragment and use the android.app.FragmentTransaction instead of android.support.v4.app.FragmentTransaction
This bug already solved in this question:

Trying to remove fragment from view gives me NullPointerException on mNextAnim

Try it out.


How to Increase the Size of an XFS File System?

Question: I just created an Amazon AWS EC2 instance running RHEL7:
[root@ip-10-184-161-46 ~]# cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.0 (Maipo)
[root@ip-10-184-161-46 ~]#

And even though I selected 10GB as my storage capacity, for whatever reason I'm only seeing 6GB that's available for me to use right away:
[root@ip-10-184-161-46 ~]# mount | grep xfs | grep -v selinux
/dev/xvda1 on / type xfs (rw,relatime,seclabel,attr2,inode64,noquota)
[root@ip-10-184-161-46 ~]# df -h | grep xvda
/dev/xvda1      6.0G  2.2G  3.9G  37% /
[root@ip-10-184-161-46 ~]# fdisk -l /dev/xvda

Disk /dev/xvda: 10.7 GB, 10737418240 bytes, 20971520 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x0000b85c

    Device Boot      Start         End      Blocks   Id  System
/dev/xvda1   *        2048    12584959     6291456   83  Linux
[root@ip-10-184-161-46 ~]#

this is what I did:
[root@ip-10-164-175-246 ~]# fdisk -l /dev/xvda

Disk /dev/xvda: 10.7 GB, 10737418240 bytes, 20971520 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x0000b85c

    Device Boot      Start         End      Blocks   Id  System
/dev/xvda1   *        2048    12584959     6291456   83  Linux
/dev/xvda2        12584960    20971519     4193280   83  Linux
[root@ip-10-164-175-246 ~]# xfs_growfs /
meta-data=/dev/xvda1             isize=256    agcount=4, agsize=393216 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=0
data     =                       bsize=4096   blocks=1572864, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0 ftype=0
log      =internal               bsize=4096   blocks=2560, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
[root@ip-10-164-175-246 ~]# df -h | grep xvda
/dev/xvda1      6.0G  2.3G  3.8G  38% /
[root@ip-10-164-175-246 ~]#

Where are my other 4GB? I thought running xfs_growfs / will increase the size of my xfs partition.
What am I doing wrong?
Answer: Funny, I just did exactly this the other day after finding my RHEL instance on EC2 only had 6GB or so of the 10GB space allocated to it...
[root@ip-172-31-20-177 ~]# xfs_info /
meta-data=/dev/xvda1             isize=256    agcount=4, agsize=393216 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=0
data     =                       bsize=4096   blocks=1572864, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0 ftype=0
log      =internal               bsize=4096   blocks=2560, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0

The problem here is that you created a second partition.
Instead, you should resize the first partition.
So, you will use fdisk to delete the second partition, then delete and re-create the first partition at the same time. The fdisk default values will cause it to fill the disk (and be correctly aligned).
Start fdisk and delete the partition:
[root@ip-172-31-20-177 ~]# fdisk /dev/xvda
Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Command (m for help): p

Disk /dev/xvda: 10.7 GB, 10737418240 bytes, 20971520 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x0000b85c

    Device Boot      Start         End      Blocks   Id  System
/dev/xvda1   *        2048    12584959     6291456   83  Linux

Command (m for help): d
Selected partition 1
Partition 1 is deleted

Now re-create the partition with all default values, which will maximize its size:
Command (m for help): n
Partition type:
   p   primary (0 primary, 0 extended, 4 free)
   e   extended
Select (default p): p
Partition number (1-4, default 1):
First sector (2048-20971519, default 2048):
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-20971519, default 20971519):
Using default value 20971519
Partition 1 of type Linux and of size 10 GiB is set

Command (m for help): p

Disk /dev/xvda: 10.7 GB, 10737418240 bytes, 20971520 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x0000b85c

    Device Boot      Start         End      Blocks   Id  System
/dev/xvda1            2048    20971519    10484736   83  Linux

Save the new partition table:
Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.

WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table. The new table will be used at
the next reboot or after you run partprobe(8) or kpartx(8)
Syncing disks.

When you reboot, the filesystem should automatically be resized for you by cloud-init. If not, you can use xfs_growfs / to grow the filesystem manually.
[root@ip-172-31-20-177 ~]# xfs_info /
meta-data=/dev/xvda1             isize=256    agcount=7, agsize=393216 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=0
data     =                       bsize=4096   blocks=2621184, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0 ftype=0
log      =internal               bsize=4096   blocks=2560, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
[root@ip-172-31-20-177 ~]# df
Filesystem     1K-blocks   Used Available Use% Mounted on
/dev/xvda1      10474496 818560   9655936   8% /

Comment: @MichaelHampton, there is one thing that you missed and I want to comment on this so whoever will be following this instruction won't fail on that) you have to use `a` after you re-create partition, which marks it bootable otherwise it won't boot.
Comment: Try running `partprobe` on the disk and it avoids the need to reboot.
Comment: @MatthewIfe Not always. When I did this a few days ago, `partprobe` continued to complain and I had to reboot anyway.
Comment: @MikeScott it _IS_ possible to use `fdisk` to delete and then create partition and only then commit changes to disk. I'll try that in a little bit.
Answer: You've divided your 10GB disk, xvda, into two partitions: xvda1 is 6GB and xvda2 is 4GB. So your other 4GB is in xvda2, and you can mount it somewhere if you want to use it.
Comment: right, that part i figured)) i need to increase `/` mount point, so i need to edit partition, increase blocks and then i gotta `xfs_growfs`.
Comment: You're going to have problems. First, you can't edit a mounted partition, so you'll need to use another AWS instance to edit the partition. And second, parted doesn't support xfs. If you're very very careful you might be able to delete both partitions and then create a new one starting at the same sector. If you're not very very careful, you'll lose all your data.
Comment: Here are some instructions for doing what you want. Use them at your own risk. http://www.powelltechconsulting.com/?p=224
Comment: Thanks, I cannot open your site though, so I'll try it again later.


Analytic Functions

Question: I don't know if this is a problem for this site.
I am looking for all possible analytic functions $f:\Bbb{C}\longrightarrow\Bbb{C}$ such that for any $x,y \in \Bbb{R}$, $|f(x+yi)| \leq (1+|y|)e^x$. Any tips would be helpful.
Comment: Find out something about $g(z) = f(z)e^{-z}$.
Comment: @DanielFischer: You mean $f(z)e^{z}$.
Comment: @MhenniBenghorbal No, I meant what I wrote.
Comment: @DanielFischer: I see. I was looking at it the other way around.
Answer: Conveniently, we have
$$e^x = \lvert e^{x+iy}\rvert$$
for all $x,\, y \in \mathbb{R}$, so multiplying $f$ with $e^{-(x+iy)} = \frac{1}{e^{x+iy}}$ gives us an analytic function $g \colon \mathbb{C} \to \mathbb{C}$ with the estimate
$$\lvert g(x+iy)\rvert = \lvert f(x+iy)\rvert\cdot\lvert e^{-(x+iy)}\rvert \leqslant (1 + \lvert y\rvert)e^x\cdot e^{-x} = 1 + \lvert y\rvert.$$
In particular, $\lvert g(z)\rvert \leqslant 1 + \lvert z\rvert$. The Cauchy estimates now tell us that $g$ belongs to a rather small class of functions, and using the smaller bound $1 + \lvert y\rvert$ reduces the possibilities even further.

Analytic Functions


Reordering nested lists (index) according to colMeans of specific column in nested matrices

Question: I'm working with a nested list of lists of matrices with doubles, motherlist.
m1<-matrix(rep(2+0.2*rnorm(3),5),5)
n1<-matrix(rep(5+2*rnorm(3),10),10)
p1<-matrix(rep(10+2*rnorm(3),8),8)
colnames(p1)<-colnames(m1)<-colnames(n1)<-c("a","b","c")
daughterlistl1<-list(m1,p1,n1)
daughterlistl2<-list(p1,n1,m1)
daughterlist3<-list(n1,m1,p1)
motherlist<-list(daughterlistl1, daughterlistl2, daughterlist3)

I want to take mean or colMeans of column "c" in each nested matrix (motherlist[[m]][[n]][,3]) and then reorder those matrices inside the nested list of matrices (motherlist[[m]][[n]]) (reorder n) ascendingly according to the mean value obtained, so that the matrix with smaller mean in the third column appears first, i.e. gets index 1 (motherlist[[m]][[1]]), and so on, for all m lists.
I was able to get the order of indices in one nested list
order(round(sapply(motherlist[[1]], colMeans), 3)[3,])

but not to reorder them in motherlist[[1]], nor do it iteratively for all m in  motherlist.
is it possible to reassign indexes in a nested list? how?
how can I recreate motherlist with ordered nested lists?
Answer: motherlist <- lapply(motherlist,function(y){
  y[order(sapply(y,function(x){mean(x[,3])}))]
})

Should work for your entire motherlist. The lacking function missing, when you have the indexes, is to use normal brackets:
motherlist[[1]][order(round(sapply(motherlist[[1]], colMeans), 3)[3,])]

gives what you want for thefirst list of your mother list. You just need to lapply again to loop over your motherlist
Comment: I hope it helps. if it works and suits you, don't hesitate to accept the answer.


Generate list of word permutations from a set of words

Question: I have 13 different words.
I need to get permutations like all combinations of these words:
word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12 word13

But the combinations only should be 12 words long.
I have already a script to do this in python:
import time
start = time.time()
items = ['word1', 'word2', 'word3', 'word4', 'word5', 'word6', 'word7', 'word8', 'word9', 'word10, 'word11', 'word12', 'word13']
from itertools import permutations
for p in permutations(items, 12):
        print(p)
print 'It took', time.time()-start, 'seconds.'

But it's too slow, and takes 24 seconds when the combinations are only 4 words long.
With a javascript tool it only took 1 second for up to 9 different words; but when trying 10 different words the browser crashed.
Is there a fast efficient way to do this? Maybe with awk?
EDIT:
This is not the same question as Generating permutations using bash because this question has 13 separated words, and the answers in the other thread do not work with words.
Kind Regards.
Comment: There is often confusion about the terminology of permutations and combinations, so let's clarify what you're looking for. Suppose there are just three words: `A`, `B`, and `C`, and you're looking for a list of combinations 2 words long. Which list do you expect? (1) `AB,AC,BA,BC,CA,CB` (2) `AB,AC,BC` (i.e. order is insignificant) (3) `AA,AB,AC,BA,BB,BC,CA,CB,CC` (4) `AA,AB,AC,BB,BC,CC`
Comment: would epxect the list (1) in your example:
Comment: The main problem here is that there will be 6 billion permutations, so even the most efficient program will struggle because it not only has to generate them but it actually has to do something with them. For example in your script the calls to `print` are the slowest part. If you store them in a file they will probably take at least 500 GB. What do you want to do with these permutations?
Comment: Yes i know that it will be around 300GB. I need them in a file. Actually i have to do it because i have a 12 word bitcoin BIP39 mnemonic, and i dont remember the order of the words but only the words. After having the file i want to write a script to check each one of them for valid mnemonic with BIP39 standard. Otherwise my bitcoins are lost :/
Comment: That's pretty cool. Is the second part where you check each permutation easier to write if it reads from a file instead of directly checking under `for p in permutations(items, 12)`?
Comment: Actually i didnt go longer in python as i saw that 4 words permutation already took 24seconds and in javascript i had 9 word permutation in 1second thats why python would take over 90years :D
Comment: I'm not sure why Python was SO slow for you. Maybe you were printing in a slow environment such as an IDE. But I've shown you that it can still do quite a lot. Also note that `permutations(items, 4)` has length `13*12*11*10=17 160` while the website you saw generated `9! = 362 880` permutations so the difference is probably not as bad as you think. Anyway, the best thing to do would be to check the permutations as you generate them in a single program rather than wasting time and space writing to and then reading from disk. Can you do that? How will you check them?
Answer: Repeatedly calling print will make a script slow, as each call has some overhead as it talks to the system it's going to print on. You get a significant improvement if you lump all the permutations into a single string and print that string once. But even then, printing is a lot of work as you're displaying text on a screen. It's much faster to just write to a file or immediately do whatever you plan on doing with these permutations.
There are smaller improvements that can be made as well. A tuple is a pretty messy string representation to put together: you need quotes (which involves checking if the string has its own quotes), commas, and parentheses. Just joining the words with a space is faster.
Going deeper, it's best if you can make looping implicit based on built-in functions since they're written in C, instead of your own loops written in Python. For example map is faster than a for comprehension if the function is also a fast built-in and not a Python function (e.g. a lambda). If you're interested, read this.
Combining all these ideas together we have:
with open('perms.txt', 'w') as out:
    out.write('\n'.join(map(' '.join, permutations(items, 7))))

This took 8 seconds to generate 9 million permutations of length 7.
Comment: `You get a significant improvement if you lump all the permutations into a single string and print that string once.` - are you sure? You wouldn't in awk due to the memory management overhead in dynamic string concatenation, which I assume python has too...
Comment: Yes, `print` has decent overhead. IO and such are generally a problem. The answer above was arrived at by successive improvements, each of which were timed.
Comment: Also I think that `join` figures out how the long the string will be before allocating it so that you don't get a repeatedly doubling array.


Conversion of Riemann Sum to Integral

Question: I was trying to convert a Riemann Sum to an integral however I got the parameters wrong according to the answers from the textbook. Now the Riemann Sum involves a $\ln$ as the function as is as follows:
$$\sum_{i=1}^n {2\over n} \ln ( 1 + {2i\over n})$$
I assumed that the $\operatorname{dx}$ would be equal to $\frac{2}{n}$ so then $\frac{b-a}{n} = \frac{2}{n}$. Then I assumed that $x_i$ would be $1 + 2\frac{i}{n}$ so where $a$ is equal to $1$ and $b$ is equal to $3$ to produce $2$ from the $\frac{2}{n}$. However the answers in my textbooks say that the function is that of $\ln(1+x)$ where the parameters are $b = 2$ and $a = 0$. How do I know which one to use?
Comment: of course he is wrong, it's probably $i=1$
Comment: are you sure about the lower bound of $\infty$?
Comment: @Alex, he is wrong, if the lower bound is $\infty$, how can you increment?
Comment: $a=1, b=3$ are the bounds on the integral
Comment: @alex, you might as well post the answer.
Comment: @alex yeah that's what I mean i=1. I got the same answer as you however the dilemma is that the textbook has the answer as a = 0 and b = 2...
Answer: Ok, what you have is probably
$$
S=\lim_{n \to \infty} \sum_{k=1}^{n}\frac{2}{n} \log \bigg(1+\frac{2k}{n} \bigg)
$$
here clearly $a=1,b=2+1=3$. Hence you get the integral
$$
S=\int_{1}^{3}\log x dx
$$
EDIT: the integrand can also be $\log(1+x)$, and then the bounds are $a=0, b=2$
Comment: Which is of course equivalent to the answer in the textbook. Looks like OP was on the right track but just didn't realise that part.
Comment: The expression in the question is almost certainly wrong. My solution is based on what I thought he meant, which may not be correct either.
Comment: It is supposed to be i=1 or k=1 whichever convention you want to use. Your answer is the answer that I got, however the textbook says otherwise. Is there another reason to this or is the textbook just simply wrong with that question?
Comment: @user127106: it's the same:http://www.wolframalpha.com/input/?i=integral%28log%28x%29%2Cx%3D1..3%29, but the function is different, for the solution in the textbook it should be $\log (1+x)$
Comment: Awesome, thank you very much Alex :) I fixed the original post so there's no confusion for future readers.
Comment: You are welcome
Comment: Ignore this post. Thanks!
Comment: @Alex: is it possible that you help me with another question that I'm stuck on?
Comment: post the question, either me or other users may help
Comment: @Phillip you should accept his answer if it helped

Conversion of Riemann Sum to Integral


linux - centOS 6.2 block IP starts with

Question: Is it possible to block an IP starting with?
For example i want to block ALL IPs that starting with
188.67.
Is there a command or a way for that?
My problem:
I have a game server, and A person keeps accessing into with with a proxy server, all of his IPs are starting with 188.67.
What should I do?
Answer: You can use
sudo iptables -I INPUT -s 188.67/16 -j DROP

which will drop all packets from IP addresses from 184.108.40.206 to 188.8.131.52. If this works and you're happy with it then use
service iptables save

to write the new configuration to /etc/sysconfig/iptables.
Answer: Yes it is possible. But keep in mind that you will be blocking lots of other legitimate users who might visit your server from the 188.67 IP.
/sbin/iptables -I INPUT -s 18.104.22.168/16 -p tcp --dport 80 -j DROP

You can change the -p option depending on which protocol your server uses, and --dport for the port number on which the server is listening.

linux - centOS 6.2 block IP starts with


Spiceworks SQL Monitor cant authenticate

Question: I have SpiceWorks 4.7, installed and added the sql monitor extension to monitor our SQL servers. It does identify our sql servers correctly, but when I put the login information in it can't authenticate, with the following error message.
Authentication failed. Check the login and password, and ensure that the server is configured for remote connections.

I get the same result trying to use windows authentication.
WE do use an alternate port# could this be the problem?
Answer: Try this two things:

Make sure to enable allow remote connections on the target server.

Make sure the firewall is opened to allow connections through your new port.

Try to login using YourServerName,1433 as user name instead of only using YourServerName. (don't forget to change the port number 1433 with your port number.)

Also make sure mixed mode authentication is on and TCP\IP is enabled on the target server.
Good Luck
Comment: Hey Dani, I would gladly do that but I don't know how to do it with the extention that is in spiceworks. It seems that they default it to the standard port. The only thing I can change through the front end is the username and password, not the machine/instance name. unless there is a config file somewhere I don't see how I can do this.


ssh script doesn't work

Question: Hi guys I need some help, I wrote a script to connect to multiple ssh hosts but the script only work with the first IP the other ones didn't change.
Here is my script:
#!/bin/bash
HOSTS="192.168.120.237 192.168.120.238 192.168.120.239"
USER=root

# Conectar a cada una de las IP
for host in $HOSTS; do
  ssh "$USER@$HOSTS" 'bash -s arg' < /home/soulfly/Escritorio/neo1isla1.sh
done

Comment: `$HOSTS` is a string, but you're using it (well, trying to use it) as an array. My Bash knowledge is limited, but I don't think it'll work like that.
Comment: @ceejayoz bash will split a string in a loop like that using the internal field separator ($IFS).  So a string will be broken up.  Try running `var='one two three four' ; for a in $var ; do echo "- $a" ; done`
Answer: Try ssh "$USER@$host" instead of $HOSTS.  The $HOSTS contains the list of all the addresses.

ssh script doesn't work


Is there a such thing as a Homogenous Monomial

Question: Is there a word for a monomial in only one variable?  Let me explain: consider the homogenous polynomial
$x_1^5 + x_1^4 x_2 + \cdots + x_2^5$.
I there a term for the two terms at the ends? $x_1^5$ and $x_2^5$.  I feel like the term should be "the homogenous monomials of the homogenous polynomial" but this sounds kinda funky.
Comment: Every monomial is homogeneous. I don't know a term, although you could just say that these monomials involve one variable only.
Answer: It may have no commonly used name but they are the terms of
the Power sum symmetric polynomials
which are a special case of
Homogeneous polynomials.


Listview in Tablelayout in android

Question: In my application i have 1 tablelayout,and 1 database.Now,i want to display that database content in a table layout.But it should look like a listview  because i have to show the entries one below the other.Is it possible to have listview inside table layout,also give some idea how to set the database entries in the corresponding listview in table layout.
Here is my XML structure:
<code><ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent" >

    <TableLayout
        android:id="@+id/tablelayout"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:paddingRight="2dip" >

        <TableRow>
            <TextView

                android_layout_span="2"
                android:layout_weight="1"
                android:text="Income" />
        </TableRow>

        <TableRow>
            <TextView
                android:layout_weight="1"
                android:text="Price:"/>

            <TextView

                android:layout_weight="1"
                android:text="Price:" />

            <ListView
        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1" >
    </ListView>
        </TableRow>

        <TableRow>
            <TextView

                android:layout_weight="1"
                android:text="Quantity:"/>

            <TextView

                android:id="@+id/et_url"
                android:layout_weight="1"
                android:text="Quantity:" />
        </TableRow>

    </TableLayout>
</ScrollView>
</code>
Answer: If you need to show your data as a list/something like a list, then why you want to use table layout by making this a complex structure ??
Use your main list_view_layout in your activity which contains a list view. create another xml like list_item & use it in the adapter to show the data one by one. you may use table layout or the design as you wish in the list_item's layout.
You will get a better knowledge here at vogella.com
Just prepare your data set, create list & its adapter & then use the data in the adapter... thats it!!
Good Luck :-)
Comment: Thanks Soumyadip Das.But my requirement is i have to show the data in table format,because i have to show two list like structure side by side.

Listview in Tablelayout in android


Copying specific keys and values of a PHP multidimensional array into another array

Question: I have a multidimensional array like this:
Array
(
    [0] => Array
        (
            [id] => 1
            [name] => mail_failures_only
            [value] => 0
        )

    [1] => Array
        (
            [id] => 2
            [name] => default_service_ttl
            [value] => 60
        )

    [2] => Array
        (
            [id] => 3
            [name] => version
            [value] => 220.127.116.11
        )

    [3] => Array
        (
            [id] => 4
            [name] => process_all_jobs
            [value] => 1
        )
)

I want each value of "name" and each value of "value" to be converted to an associative array like this:
process_all_jobs =>1
How do a construct loop for this?
I tried something like this:
$system_config_array = array();
        if (is_array($configList)) {
            $keys = array_keys($configList);
            for($i = 0; $i < count($configList); $i++) {
                foreach($configList[$keys[$i]] as $key => $value) {
                    echo $key . " : " . $value . "
";
                    if($key!='id')
                        $system_config_array[$value] = '';
                }
            }
       }

where $configList is the initial array.
Comment: see this : https://eval.in/1017632
Comment: Thanks a ton!!! It worked :) And I was using 2 for loops and an if and going mad ..
Comment: Please vote up my question too.
Answer: Use array_column.
$result = array_column($arr, "value", "name");

But this only works if the names are unique.
It doesn't answer your question to create a loop for it, but I belive array_column is a better tool for the job
Comment: Your array with value and names
Comment: Looping is not an optimal solution
Answer: Hope this will help you :
$base = 'your array';
foreach ($base as $key => $value) {
    $data[$value['name']] = $value['value'];
}
print_r($data);

https://eval.in/1017632


Windows: copying a file that is in the process of being written?

Question: Here's some easy points for someone:
If I issue a command like copy * /destination in a folder containing a file that is being written to, will the partially written file be copied?  Will it be ignored?  Will copy throw an error?
Basically I have a script that copies files from a folder to a new location on a schedule, and there could be a case in which a new file is being written to the source folder when the script runs.  I'm wondering what precautions I might need to take.
Edit: I should mention that the file will be coming in via SMB to a shared folder.
Comment: Why don't you try it and see what happens? With test files, of course.
Comment: I did, and got different results depending on how the file was being written.  I thought perhaps there was some definitive guideline.
Answer: Either:

The file will be locked and nothing will happen.  It may crash your script if you don't have decent error handling.
A copy of the file will be made in the state it was in at the instant the copy was initiated.  Data written to the file after this instant will not be in the copied file.  Think of it as a snapshot of sorts

As always, test test test, and move from there.
Comment: I tried this two ways.  In one case I started a download of a large file in Firefox, and ran the copy command.  It copied both the 0 byte destination file and the .part file that are created by Firefox.  In another case I started a copy of a large file from a network share and then ran the copy command, and it errored with a "the process cannot access the file because it is being used by another process."  That was using explorer, however.  The real files will come in via smb from a copy machine, and they get written so quickly it's difficult to test...I'll have to scan a few bazillion pages.
Comment: Ok I tested by initiating a copy via shell from one machine to share on another machine.  While the file was being copied, the copy command run on the destination machine failed with the error I mentioned above.  That's what I want.  Can you elaborate in your answer under what circumstances your two possible outcomes would occur?  Why does firefox write its files without locking?  When copying a file via SMB/CIFS will it always be locked, or does the initiating process have some say in the matter?
Comment: FF is just written to work that way.  It touches a file with the correct name, it then dumps all the incoming data to a .part file, and when done it merges this into the touched file.  It all depends on how the handling software has been written.
Answer: Windows won't let you make a regular copy of the file. You need to use Shadow Copy (aka VSS). Quick Google search produced this example.
Comment: Thanks! I don't actually want the file to be copied if it's not complete though.


Apache: graceful kill fail, sending SIGKILL. How much is too much?

Question: On Apache/2.2.15, is it normal to have one or two "[warn] mod_fcgid: process XXXXX graceful kill fail, sending SIGKILL" per day? After all it's a warning, not an error.
Thanks
Answer: Other people have reported a similar issue with FCGID processes hanging and being unkillable in other systems, such as Wordpress and Sympa.
A suggested fix was to add the option
<code>FcgidMaxRequestLen 1000000000
</code>
to the Apache configuration (default for this setting is 131072).  I have not been able to verify this fixes the issue but there is anecdotal evidence to indicate that it does.
Answer: I dealt with the problem by tracking down the cause of SIGKILL and eliminating them. Now I get 0 SIGKILL warnings per day. I will consider this level the normal level. See this question for more details.


Approximate a CDF

Question: Suppose we have $n$ equations with an integral of the form $\int_0^{x_i} F(z)dz = c_i,\ i=1,\ldots,n$ where $F(y)=\mathbb{P}(X \le y)$ is an unknown cumulative distribution function of a non-negative discrete random variable $X$. $x$ is an input and $c_i$ are known. We can assume that $X \in [0,M]$ is a bounded random variable. We want $F$ to be non-decreasing with $F(0)=0$ and $F(M) = 1$.
Given the above setup, I have the following two questions

What are some effective methods to learn $F$?
Is it possible to get guarantees on the number of samples $n$ ?

I would appreciate any pointers.
Answer: Assuming that the constraints are $$\int_0^{x_i} F(z)dz = c_i\qquad i=1,...,n$$there exists one step function with jumps only at $x_1,x_2,...,M$ that satisfies this collection of constraints and converges to $F$ as $n$ grows to infinity.

Approximate a CDF


Correct way to display my query

Question: I have a query in my model that I need to print the data in my view
Model
    function get_bank()
    {
        $query = $this->db->query("SELECT
(
   12* (YEAR('account_add_date') - YEAR('start_date')) +
          (MONTH('account_add_date') - MONTH('start_date'))
) AS differenceInMonth
->FROM ('bank')
WHERE mem_id = '".$this->session->userdata('id')."'");
return $query->result();
    $data['account_age'] =  $query->row_array();

    }

and I am trying to print the output in my model, but its not working and I do not know where I have gone wrong. I am new to MVC and still getting used to it.
View

age of account

<?php
$age = $this->model('profiles_model' , $data );

print "
$age
";

?>

Controller
function index()
    {
        $data = array();
        $this->load->model('user_profile/profiles_model');
        $query = $this->profiles_model->get_bank();

        if(!empty($query))
        {
            $data['records'] = $query;
        }

        $this->load->view('profile_view', $data);
    }

Comment: That get_bank() method doesn't actually return anything. Is that intended?
Comment: so i should call get_bank in my view $this->model('get_bank') ?, one sec ill update my question
Comment: Are you using a MVC framework?
Comment: Hm, no. I think there is a return statement missing within the definition of `get_bank()`. Hence `$data['records']` will be empty in your controller and there is nothing in `$age` for the view to display.
Comment: @SamA yes Codeigniter
Comment: @DaSourcerer update my question to include return
Comment: Seems like the data is being put in  $data['records'] not $data.
Comment: even if i remove ['records'] and just put it in $data it still dose not read the $data in the view
Comment: Your function returns the query, the code afterwards does not get executed.
Answer: Let's first write your code in proper convention.
Model
function get_bank() {
    $mem_id = $this->session->userdata('id');
    $query = $this->db
        ->select("12*(YEAR('account_add_date') - YEAR('start_date')) + (MONTH('account_add_date') - MONTH('start_date')) AS differenceInMonth")
        ->where('mem_id', $mem_id)
        ->get('bank');

    return $query;
    // $data['account_age'] =  $query->row_array(); <-- Statement after return is useless.
}

Controller
function index() {
    $data = array(
        'records' => array()
    );
    $this->load->model('user_profile/profiles_model');
    $bank = $this->profiles_model->get_bank();

    if($bank->num_rows()){
        $data['records'] = $bank->row_array();
    }

    $this->load->view('profile_view', $data);
}

View
Not sure what you are trying to do with the bank data but here's how you print the record

Bank data

<?=isset($records['differenceInMonth'])?$records['differenceInMonth']:"No record found"?>

Comment: @Beep. Updated Controller to use row_array() instead of result_array() since it's a single row.
Comment: @Beep Removed a line from model.
Comment: I'm not sure if the iteration in the view is really required. It seems there is going to be one result at most, if I understood correctly.
Comment: Yea, it's not necessary. Updated.
Comment: Thanks guys am trying now
Comment: thank @komirad, still integrating it all in with my existing code, one ive done that and get it working. il accept your answer
Comment: @komirad & DaSourcerer, thanks for your help, is displaying now even if it is no records found, but that will be down to my query, il adjust accordingly. thank you very much
Answer: You are not far away, do it this way:
Controller:
function index()
    {

        $this->load->model('user_profile/profiles_model');
        $data = $this->profiles_model->get_bank();

        $this->load->view('profile_view', $data);
    }

Model:
function get_bank()
    {
        $query = $this->db->query("SELECT
          (
          12* (YEAR('account_add_date') - YEAR('start_date')) +
              (MONTH('account_add_date') - MONTH('start_date'))
           ) AS differenceInMonth
        ->FROM ('bank')
          WHERE mem_id = '".$this->session->userdata('id')."'");

         return $query->result();
    }

View:
<?php

foreach(differenceInMonth AS $age){

   echo "
" . $age . "
";

}

Comment: Thanks man, just trying out one of the earlier answer but if that dose notwork il try this one +1
Answer: When you load the view you are passing in $data with $data['records'] that has the data you are wanting to display.
Since that is how you pass the data into the view when you load it you will need to call it that way:
<?php
   var_dump($records);
?>

You will also need to loop through the data as well assuming $records is an array of the query results or use var_dump instead of print just to verify the data is there.
Reading through these will help going forward:
https://codeigniter.com/user_guide/general/views.html
https://codeigniter.com/user_guide/general/models.html

Correct way to display my query


User Interface for Javascript and/or php

Question: What are some of the better known well established user interface libraries? For Java I found Vaadin to be very nice. Is there something out there for javascript and php?
A few good ideas and comment to point me in the right direction would be helpful.
Answer: It appears react is new on the scene and building momentum. Probably asked this question too soon.
Would appreciate what you guy can tell me on top of react and what is out there for PHP.


Interpreting probability from the inverse logit function

Question: I'm doing a study using generalized linear models to investigate effect size and direction of species whose presence/absence were found to be affected by the presence of drought (tested by a Fisher's Exact Test). To do the results easy to interpret, I did the following:
1) I produced a binomal GLM.
2) For presence and absence of a particular species, I converted the non-standardized logistic regression coefficients given by the GLM for the intercept-only model (the null model) and the intercept + drought presence and absence model (the alternative model) to the log-odds probability (using the logit function, where β0 represents the intercept and β1x1 represents drought presence/absence). I did this for drought and for non-drought separately.
3) I converted log-odds probability to probability of detection for drought and non-drought (using the inverse of the logit function), and compared these probabilities of detection within each species during drought and non-drought.
The equations used are as follows:
for (2) logit (α) = β0 + β1x1
for (3) logit^-1 (α) = e^α / (1 + e^α)
The issue is that a couple species do not at all represent reality, even if the patterns are correct. For example, a bird that is detected 60% of the time during drought and 25% of the time during non-drought (from the raw data), after running the GLM, and converting to probability, the model said there's a 58% chance of detecting the bird (instead of somewhere near 25%) during non-drought and a 96% chance of detecting the bird (instead of 60%) during drought. The true probability can't be anywhere near 96%, right? This bird is not that common. Should I not be interpreting these values as true probabilities? How should I be interpreting this 96%? Did I do something wrong? Thank you for any and all help!
Comment: [This](https://stats.stackexchange.com/questions/443932/computation-of-the-intercept-in-logistic-regression-model/443964#443964) might help. Could you write down the full model you ran with all of the variables? Right now it's a little ambiguous what models you ran (e.g., why did you run an intercept-only model?).
Comment: Here's an example with data. I think it is consistent with the link you provided.

Here's a bird we will call species 29. I did all of this using the glm(binomial) in R.

Logistic regression coefficients:
Intercept (null model=no drought): 0.3393
Y1 (model with drought): 2.9188

Logit function:
Drought absent: 0.3393
Drought present: 0.3393 +  2.9188(1) = 3.26

Inverse of logit function (probability of detection):
Drought absent: (e^0.3393) / (1 + e^0.3393) = 0.584
Drought present: (e^3.26) / (1 + e^3.26) = 0.963

Any help you can provide is much appreciated!
Answer: You don't need to fit a full model. You only need to fit a single logistic regression model to get the predicted probabilities of detection under each drought scenario.
fit <- glm(detected ~ drought, data = data, family = binomial)
#Probability of detection under no drought
plogis(coef(fit)[1])
#Probability of detection under drought
plogis(sum(coef(fit)))

These should match the empirical probabilities exactly (i.e., plogis(coef(fit)[1]) == with(data, mean(detected[drought == 0])))
The null model is not helpful here. The intercept in the null model gives you the marginal log odds of detection (i.e., which can be transformed into the probability of detection for the whole sample ignoring whether there was a drought).
Comment: Thank you! Is there somewhere I can read up on to get more familiar with the information you provided?
Comment: There are many good introductions to logistic regression. I learned just by taking classes in graduate school but the book by Hosmer and Lemeshow is a nice introduction.
Comment: Thanks. What should I enter as far as the code for these commands? Specifically,
#Probability of detection under no drought
plogis(coef(fit)[1])
#Probability of detection under drought
plogis(sum(coef(fit)))
These should match the empirical probabilities exactly (i.e., plogis(coef(fit)[1]) == with(data, mean(detected[drought == 0])))

My variables are "VER_S" for drought present (1) or absent (0) and "Present" for presence (1) or absence (0).
Comment: `fit <- glm(Present ~ VER_S, data = DATA, family = binomial)` but replace `DATA` with the name of your data set.


Best javascript library for HTML/DOM to Canvas conversion

Question: I need a good js library which able to concatenate 2 canvas, some text strings and some images in one solid image (canvas). There is outbound divs out of each element which can be rotated and zoomed also.
Actually it is t-shirt design constructor, I need to have complete image after user pressed "Save" button.
Thanks.
Answer: You can use libcanvas for easy drawing and object manipulating. It's a fast opensource library. And get image from canvas like this
<code>var canvas = document.getElementById("canvas");
var resultImage = canvas.toDataURL("image/png");
</code>
Answer: I have found a solution: just learn something and write my own utility to merge my specific DOM structure. Works well.
Still waiting for answers, just curious.


Change Page File via registry, WinXP

Question: I'm trying to run a script to move users page files from C: to D: (if they don't have enough space)
I've figured out how to do it by modifying HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management\PagingFiles
It works fine - a new page file is created on D:
But, the old page file isn't removed from C: on reboot (although it works fine if I make the change manually). After reboot I can actually delete it though, so it's no still in use - just hasn't been removed.
Is there a way to make that happen?
Answer: You shouldn't be hacking the registry to do this.  You should be making the changes the correct way, by using the relevant win32 classes.
The classes you are looking for are Win32_PageFile and Win32_PageFileSetting.
Comment: Oh, nice - I hadn't noticed that. The PageFile link, btw, says that particular class is deprecated.
Comment: It'll still work - not sure what it's been superseded by - have had a look and can't find anything.

Change Page File via registry, WinXP


Safari posting blank form to my server

Question: Short question: Why does safari cause errors on my MVC3 web application - Request.Form is blank for some reason?
Detailed question:
My MVC3 website sends me an email every time there is an uncaught exception. I use these to find and fix bugs quickly, the email contains the exception, stack trace, user's IP address, user-agent string, and any form values that may have been posted.
Recently I have been noticing errors that have proven hard to track down, I thought I would post my findings here in the hope they help others.
The original symptom was these errors: System.Web.Mvc.HttpAntiForgeryException: A required anti-forgery token was not supplied or was invalid.
My form's action was throwing the error, and I couldn't figure out how anyone was getting the page into a state where it didn't have the __RequestVerificationToken hidden field, or the other form fields.
So I spent ages looking into cookies, and how the token works, and eventually just removed the [ValidateAntiForgeryToken] attribute on my ActionResult to see how it went - I still got errors though.
Then I noticed that the useragent strings showed it was only Safari 5.1.7 causing the issue.
Answer: For those of you who, like me, are experiencing this issue even with the [HttpPost] attribute, I have found a solution.
http://forums.iis.net/t/1182376.aspx/1
That thread on IIS describes that Negotiate (i.e. Kerberos) authentication is handled improperly in Safari. You have to disable Negotiate as a provider.
In IIS (I am using IIS 7.5), click your site, then Authentication(double click) → Windows Authentication(single click) → Providers(on the right side) → Remove Negotiate and leave NTLM
This fixed all my problems with Safari.
Answer: Short Answer:
Don't forget to add a [HttpPost] attribute!!!
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult PageSubmit() {

Longer Answer:
Safari has a feature where they show the "top sites" you've visited on a wall-style screen. On my site although I had multiple pages, they all submit to the same form action. This made the form action "very popular", and it appears on the top sites.
People can then click the site, which was doing a direct GET to my processing page, with no form variables, and causing the errors.
I added the [HttpPost] attribute and now it 404's if you click it.
Here is some extra info on the preview feature: Safari Top Sites Preview it appears you can check for a server variable:
Request.ServerVariables["HTTP_X_PURPOSE"] == "preview"

and there is a javascript check you can do too:
window.navigator&&window.navigator.loadPurpose==="preview"

I hope this saves someone some time.
Comment: This isn't working for me at all. I've ensured that I am using HttpPost on all my MVC Controller methods, but I still get issues. It works fine if I use PHP, alas, I don't have that option. It's gotta be an IIS thing :(.
Comment: Hi Jeff, are you saying that even when you add the [HttpPost] attribute, you can still call the method directly with a GET? If you can, then I'd be looking at your routing maybe? Definitely put a breakpoint in the method, and make sure it's definitely hitting that one and not something else you didn't expect. HttpPost has been around since MVC2, you aren't using MVC1 are you?
Comment: I am using MVC 4. I am also using the Intranet template. Whenever I post form data via jQuery's `ajax` method, it works 100% in IE7+, Chrome, and FF2+. No problems. No issues. But when I send a form (via `post`) using Safari (v5.7), it's a blank form every time. I think it has to do with IIS's Windows Authentication...but I don't have the expertise to track it down :(

Safari posting blank form to my server


Linux - show screen logs on multiple screens?

Question: I have a problem with screen. Basically I want it to make one log per screen, for example screen #1 will be screenlog.1 & screen #2 will be screenlog.2 - you get the memo.
Anyhow, what happens is that when I launch screen using:
screen -SL screen1

(The -L parameter is because I need to force it to make logs) it only logs the first screen, not the rest 2-5 screens. I've tried using the .screenrc file with the logfile parameter, it works - but just changes the name of screenlog.0, which isn't really what I want.
Any idea how I would go about this?
Additonal information: CentOS 6.3 (64bit).
Screen version 4.00.03 (FAU) 23-Oct-06.
Comment: Or use `tmux` which makes all of these automation projects so much less painful than `screen` ever did.
Answer: Here is how you can log the output of multiple screen sessions in separate log files:

Start a screen session using screen -S <preferred-name-of-session>
Attach the screen using & then set the logfile of the screen using the command:
 Ctrl + a :logfile <name-of-log-file>
Start the screen logging by running Ctrl + a H
Execute the required program & then detach the screen

This might look like a lot of work everytime but once you start using it, it becomes very handy!
Answer: You may be experiencing buffering of the log output.
I locally tested both with and without screen name and received the expected screenlog.0 and .1 and .2 etc. Each log corresponded to the contents of each window. There is a buffer before it gets written to disk
Reference flush secs:
http://www.gnu.org/software/screen/manual/screen.html#Logging
Answer: In addition to what splaer said (which is probably what's going on here), you might want to use script to record your sessions if screen is giving you trouble.
The convenience of screen -L is nice to have, but if it's giving you trouble script is a handy workaround (and if you ever find yourself on a machine without screen -- they do still exist sadly -- it's likely script is still going to be there).


Periodic points of image of Cantor set by ternary dilation

Question: Let $C$ be the Cantor. The set is built up by cutting all intervals into thirds and removing the middle third step one by one and to infinity.
\begin{align*}
 C_0 = &  [0,1]\\
  C_1 =&  [0, \frac 13] \cup [\frac 23, 1]\\
  C_2 =&  [0, \frac 19]\cup [\frac 29, \frac 13]\cup[\frac 23,\frac 79]\cup [\frac 89, 1].\\
\vdots \\
C= & \cap_{i=0}^{\infty} C_i
\end{align*}
The Cantor set corresponds to the resulting "infinite number of times" ( observe that $T(C)=C$ ).
I wonder how to get prove that the periodic points of  $T(C)$ are dense in $C$, where
$T$ is the transformation $T: C \to C$ defined by $x \longmapsto 3x \quad \mathrm{mod}\, \,  1$.
A periodic point is a point $x_0$ such that $f^k(x_0)=x_0$ for some  integer $k \geq 1$.
So
\begin{align*}
T(x)= x \quad \mathrm{mod} \, 1    \\
2x -  \lfloor 2x \rfloor =& 0 \\
2x =  \lfloor 2x \rfloor &.
\end{align*}
How to finish this exercise.
Many thanks for your help.
Answer: Notice that every $x$ in $[0, 1]$  may be expressed as
$$
  x=\sum_{n=1}^\infty  a_n3^{-n},
  $$
with $a_n\in \{0,1,2\}$, and that $x$ lies in the Cantor set iff it has an expression as above with every  $a_n\neq 1$.
It should be stressed that $x$ may have two different such expressions, e.g.
$$
  \frac 13 = 1\times 3^{-1} = 2\times 3^{-2} + 2\times 3^{-3} + 2\times 3^{-4} + \cdots
  $$
and that it is enough for one of these expressions to satisfy   $a_n\neq 1$ in order  to qualify.
This said,  observe that  ternary dilation corresponds to shifting the digits, namely
$$
  T\left(\sum_{n=1}^\infty  a_n3^{-n}\right) =
  \sum_{n=1}^\infty  a_{n+1}3^{-n}.
  $$
This implies that $x$ is periodic for $T$ if its  digits are periodic,  that is,  if there exists $p$ such that
$$
  a_{n+p}=a_n, \quad\forall n\in \mathbb N.
  $$
Given any $x$ in $C$ we may therefore approximate it by a periodoc point $y$ whose digits $a_n$ coincide with those of $x$ up
to a big enough $n$,  and are then repeated periodically.


MySQL function declare 2 variables with one select

Question: I'd like to know how I can create a MySQL function that declares 2 variables by using 1 select statement.
Something like this:
CREATE FUNCTION  `inHashtagCampaign` (campaignId INT,startDateTime DATETIME,endDateTime DATETIME)
RETURNS TEXT
LANGUAGE SQL
DETERMINISTIC
BEGIN
    DECLARE result TEXT;
    DECLARE limit BIGINT(11);
    DECLARE suspended TINYINT(1);
    #
    #I don't know how to do this, but I'd like to use the result of this query:
    #
    result = SELECT `limit`,`suspended` FROM `settings` WHERE `campaignId` = 2;
    limit = result.limit;
    suspended = result.suspended;
END;

I know this function is far from complete, but I'm kinda stuck on this thing already.
Answer: I think what you are trying to do is like this
DECLARE @limit BIGINT(11);
DECLARE @suspended TINYINT(1);

SELECT @limit := `limit`, @suspended := `suspended` FROM `settings`
WHERE `campaignId` = 2;

(OR)
DECLARE limit1 BIGINT(11);
DECLARE suspended1 TINYINT(1);

SELECT `limit`,`suspended` into limit1, suspended1
FROM `settings` WHERE `campaignId` = 2;


Using wildcards in custom module outputting sql query

Question: It has become obvious to me that SQL syntax is a little different within drupal.
After some fiddling around I am getting the hang of it, but I haven't been able to use wildcards succesfully.
$sql = 'SELECT name Nombre, mail Email  FROM users WHERE status = 1 AND mail LIKE ('%@hotmail%') LIMIT 25';

Do you have any suggestion? I haven't been able to find (or I might be looking in the wrong places) for Drupal documentation regarding wildcards within $page_content in a module.
Comment: What happens when you run the above query then?
Comment: I get no results. If I run it directly in PHPMyAdmin, I do get the expected results.
Comment: Yes it's nothing wrong with the query, are you sure that the query are run at all?
Comment: If I remove the "And LIKE... " portion of it, it works, so I guess the error is in that part. So I guess it is running.
Comment: Whoa! In the Drupal error report I found this:
Division by zero in /home/mysite/www2/dev/sites/all/modules/onthisdate/onthisdate.module in line 38.
Comment: I think it's not working because the % character will be treated as a argument placeholder, check http://api.drupal.org/api/drupal/includes--database.pgsql.inc/function/db_query/6
Comment: Thanx for pointing me there, Kirster. I just posted a question in that piece of documentation.
Answer: Your code has the following errors:

The string delimiter for the query is the single quote character, which is the same delimiter you use for the string inside the query.
The table names are always surrounded with { and }, which allows Drupal to prepend the prefix set in settings.php to the table name.
If you need to use the % character as wildcard character, you need to escape it with another %, in a query passed to the database API.
If you need to limit the number of returned rows, in Drupal you use db_query_range() that allows to use a query that is compatible with every database engine for which there is a driver for Drupal.
If you look at the code used from that function for different database engines, you will notice it will use a different syntax for different database engines, such as:
MySQL/MySQLi
$query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
$query .= ' LIMIT ' . (int) $from . ', ' . (int) $count;

PostGreSQL
$query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
$query .= ' LIMIT ' . (int) $count . ' OFFSET ' . (int) $from;

Your code should be written as the following one:
$sql = "SELECT name, mail FROM {users} WHERE status = 1 AND mail LIKE '%%@hotmail%%'";
$result = db_query_range($sql, array(), 0, 25);

while ($row = db_fetch_object($result)) {
  // $row->name contains the username, and $row->main contains the email address.
}

This is code taken from a Drupal module that uses the LIKE operator:
  $query = "SELECT url, COUNT(url) AS hits, MAX(timestamp) AS last FROM {accesslog} WHERE url NOT LIKE '%%%s%%' AND url <> '' GROUP BY url";
  $query_cnt = "SELECT COUNT(DISTINCT(url)) FROM {accesslog} WHERE url <> '' AND url NOT LIKE '%%%s%%'";

The query uses 5 % because the first 2 are for using % as wildcard, the third is for the "%s" placeholder, and the last two are again for using % as wildcard.
This is an example of code used by a module that limits the number of rows the query returns:
        $sql = db_rewrite_sql("SELECT n.nid, n.title, l.comment_count, l.last_comment_timestamp FROM {node} n INNER JOIN {term_node} tn ON tn.vid = n.vid INNER JOIN {term_data} td ON td.tid = tn.tid INNER JOIN {node_comment_statistics} l ON n.nid = l.nid WHERE n.status = 1 AND td.vid = %d ORDER BY l.last_comment_timestamp DESC");
        $result = db_query_range($sql, variable_get('forum_nav_vocabulary', ''), 0, variable_get('forum_block_num_0', '5'));
        $content = node_title_list($result);

The query string is passed to db_rewrite_sql(), but that is irrelevant, here; the code would not change if it didn't need to use db_rewrite_sql().


Possible error in Guillemin and Pollack RE de Rahm cohomology?

Question: The context is Guillemin and Pollack, Chapter 4.6, Cohomology with Forms.
Let $U$ be an open subset of $\mathbf{R}^k$ and let $\omega$ be a $p$-form on $\mathbf{R} \times U$, represented as $$ \omega = \sum_I f_I(t, x) dt \wedge dx_I + \sum_J g_J(t, x) dx_J. $$  Define an operator $P$ sending $p$-forms on $\mathbf{R} \times U$ to $(p-1)$-forms on $\mathbf{R} \times U$ by $$P \omega = \sum_I \left( \int_0^t f_I(s, x) ds \right) dx_I. $$

Lemma.  Let $X$ be a $k$-dimensional manifold, $\pi \colon \mathbf{R} \times X \to X$ the natural projection, and $i_a \colon X \to \mathbf{R} \times X$ the embedding $x \mapsto (a, x)$ for any fixed $a \in \mathbf{R}$.  Then locally, $$ dP\omega + Pd\omega = \omega - \pi^* i_a^* \omega. $$

Question.  As stated, is this formula true only for $a = 0$?
Letting $\omega$ be locally represented as above, the authors note that $$ \pi^* i_a^* \omega = \sum_J g_J(a, x) dx_J $$ and my calculations verify this.  However, I am calculating $$dP \omega = \sum_{i, I} \left( \int_0^t \frac{\partial}{\partial x_i} f_I(s, x)ds \right) dx_i \wedge dx_I + \sum_I f_I(t, x) dt \wedge dx_I $$ and $$ Pd\omega = -\sum_{i, I} \left( \int_0^t \frac{\partial}{\partial x_i} f_I(s, x)ds \right) dx_i \wedge dx_I + \sum_J \left( g_J(t, x) - g_J(0, x) \right) dx_j$$ hence $$dP \omega + P d\omega = \omega - \sum_J g_J(0, x) dx_J = \omega - \pi^* i_0^* \omega. $$
Assuming this calculation is correct, if I am not mistaking the lemma can be remedied by letting the operator $P$ vary with $a$ as well, i.e. $$P_a \omega = \sum_I \left( \int_a^t f_I(t, x) \right) dx_I$$ so that

$$dP_a \omega + P_a d\omega = \omega - \pi^* i_a^* \omega. $$

Do my calculations check out?  Is this what Guillemin and Pollack probably intended?
Many thanks.
Comment: It is at least suspect in the original formula that the right side depends on $a$, whereas the left side does not.
Answer: I believe I am correct.  It doesn't matter all that much that $P$ is actually parametrized by $a$.  The point is that for each $a$ this provides a homotopy of chain maps between $\text{id}^\#$ and $\pi^\# i_a^\#$, which is the essential lemma in this context.


Problema na inserção de elementos em uma fila

Question: Fiz uma função utilizando o conceito de fila estática para inserir um elemento, porém, não está executando quando chamo ela no main.
Não sei se o problema está nela, na função main ou nas duas rs... segue função de inserção:
<code>#include<stdio.h>
#include<stdlib.h>
#define tamanho_fila 5

int menu(){
   int opc;
   printf("[1]QUEUE\t");
   printf("[2]DEQUEUE\t");
   printf("[3]FREE QUEUE\t");
   printf("[4]SHOW FIRST ELEMENT\t");
   printf("[5]SHOW ALL ELEMENTS\t\n");
   printf("\nPLEASE, CHOOSE ANY OPTION:  ");
   scanf("%i", &opc);
   return opc;
}

struct queue{
   int inicio;
   int qtd;
   int elemento[tamanho_fila];
};

int fila_vazia(struct queue *q){
   if(q->qtd==0)
          return 1;
   return 0;
}

void inserir_fim_fila(struct queue *q, int vlr){
   int fim;
   if(q->qtd==tamanho_fila){
          printf("CAPACIDADE MAXIMA DA FILA ESTOUROU\n");
          exit(0);
   }else{
          fim=(q->inicio+q->qtd)%tamanho_fila;
          q->elemento[fim]=vlr;
          q->qtd++;
   }
}

int remover_inicio_fila(struct queue *q){
   int aux;
   if(fila_vazia(q)){
          printf("IMPOSSIVEL REMOVER, FILA VAZIA");
          return 0;
   }else{
          aux=q->elemento[q->inicio];
          q->inicio=(q->inicio+1)%tamanho_fila;
          q->qtd--;
          return 1;
   }
}

void mostrar_fila(struct queue *q){
   int i;
   for(i=0;i<q->qtd;i++){
          printf("%i", q->elemento);
   }
}

void free_queue(struct queue* q){
   free(q);
}

int main(){
   int opc, vlr;
   struct queue *q;
  while(opc==menu()){
          switch(opc){
                 case 1:
                        printf("INSERT ELEMENT: ");
                        scanf("%i", &vlr);
                        inserir_fim_fila(&q, vlr);
                        break;
                 case 3:
                        free_queue(&q);
                        break;
          };
   system("pause");
   }
    return 0;
}
</code>
Espero que possam ajudar!
Comment: @Blogueira, sim claro.. editei minha pergunta..
Comment: Olá Camilla! Você pode postar seu código completo, ou algo próximo do explicado [aqui](https://pt.stackoverflow.com/help/mcve), por favor? =]
Comment: Camilla - alguém vai ter que responder melhor isso aqui (alguém que entenda!), mas para você continuar trabalhando, acho que tem um igual a mais: `while(opc==menu()){}`. Provavelmente deveria ser `while(opc=menu()){}`.
Answer: Bom reescrevi seu código com algumas alterações por que do jeito que estava ele a lógica estava um pouco confusa. Desculpe a minha resposta editada.
O seu código a princípio no main estava apenas com a struct declarada com ponteiro, mas na verdade com fila estática você trabalha através de referência.
Eu criei uma função para inicializar a Fila, o que é essencial, pois você precisa de sua fila inicie com valores.
Na função de inserção você sempre vai adicionar sempre o elemento no final da fila já que o objetivo de Fila é o "primeiro a entrar o primeiro a sair" então a variável qtd vai marcar o final da Fila então toda vez que você adicionar um elemento você vai incrementar ela.
Na remoção você sempre vai remover do início da fila então você terá a variável inicio marcando qual o primeiro elemento para sair da fila.
Continue a sua implementação a partir desse código que eu acho que vai dar certo. Desculpe entrei na comunidade agora e não tenho muita prática de ensinar através de postagens.
<code>#include<stdio.h>
#include<stdlib.h>
#define tamanho_fila 5

struct queue{
   int inicio;
   int qtd;
   int elemento[tamanho_fila];
};

int menu(){
   int opc;
   printf("[1]QUEUE\t");
   printf("[2]DEQUEUE\t");
   printf("[3]FREE QUEUE\t");
   printf("[4]SHOW FIRST ELEMENT\t");
   printf("[5]SHOW ALL ELEMENTS\t\n");
   printf("\nPLEASE, CHOOSE ANY OPTION:  ");
   scanf("%i", &opc);
   return opc;
}

void inicFila(struct queue *q){
    q->qtd=-1;
    q->inicio = 0;
}

int fila_vazia(struct queue *q){
   if(q->qtd<q->inicio)
          return 1;
   return 0;
}

int inserir_fim_fila(struct queue *q, int vlr){
   int fim;
   if(q->qtd == tamanho_fila-1){
          printf("CAPACIDADE MAXIMA DA FILA ESTOUROU\n");
          return 1;
   }else
        return q->elemento[++(q->qtd)] = vlr;
}

int remover_inicio_fila(struct queue *q){
   int aux;
   if(fila_vazia(q)){
          printf("IMPOSSIVEL REMOVER, FILA VAZIA");
          return 0;
   }else{
          aux=q->elemento[q->inicio];
          q->inicio++;
          return aux;
   }
}

void mostrar_fila(struct queue *q){
   int i;
   if(!fila_vazia(&q)){
       for(i=0;i<q->qtd;i++){
              printf("%i", q->elemento[i]);
       }
   }
   else printf("A fila não tem nenhum elemento.");
}

void free_queue(struct queue* q){
   free(q);
}

int main(){
    int opc, vlr;
    struct queue q;
    inicFila(&q);
    while(opc=menu()){
            switch(opc){
                    case 1:
                        printf("INSERT ELEMENT: ");
                        scanf("%i", &vlr);
                        inserir_fim_fila(&q, vlr);
                        break;
                    case 3:
                        free_queue(&q);
                        break;
            };
    system("pause");
    }
    return 0;
}
</code>
Comment: Olá Luiz, bem vindo ao Stack Overflow! Normalmente as respostas dadas aqui "solucionam" o problema - para tirar dúvidas, usa-se o campo de comentários (que você poderá usar em breve, quando tiver mais reputação). Por enquanto, sugiro que você responda apenas perguntas claras que dê para dar uma solução certeira.
Comment: Olá! O %tamanho_fila é para indicar onde o fim da fila está localizado no vetor, para isso eu preciso somar a quantidade de itens + índice do início % tamanho_fila.. exemplo: 2+4/5 = significa que o fim da fila está no índice 1.. Enfim, eu executo o sistema e ele chega a rodar, mas nem pergunta espera eu inserir o elemento e ele já fecha... talvez o problema esteja na main
Comment: Olá pessoal, Obrigado pelas boas vindas @Blogueira entendo suas dicas, acabei de entrar na comunidade espero que eu possa ajudar outras pessoas com os códigos. Editei minha resposta você pode conferir agora. Obrigado pela compreensão. Até mais.
Comment: Boa! Você pode utilizar sites com o [repl.it](https://repl.it/languages/c) para demonstrar o código em funcionamento (além, é claro, de colocá-lo no texto) - costuma agregar valor à resposta! ;)
Comment: @LuizEduardoC. muito obrigada pela ajuda!!


David Eisenbud, Hilbert theorem

Question: I just started reading D. Eisenbud Commutative algebra with a view towards algebraic geometry and I wonder about a theorem on page 42:
If $M$ is a finitely generated graded module over $k[x_1,...,x_r]$ then $H_M(s)$ agrees, for large $s$, with a polynomial of degree $\leq r-1$, where $H_M(s):=\dim_k(M_s)$.
I don't understand what "then $H_M(s)$ agrees, for large $s$, with a polynomial of degree $\leq r-1$" means. Can someone explain this?
Answer: It means that there is a polynomial $p(n)=a_{r-1}n^r+...+a_0$, and a number $N$ such that $H_M(s)=p(s)$ for $s>N$.
Maybe more important to understand than that statement is the following equivalent one.
Define $\Delta f(n):=f(n+1)-f(n)$ and $\Delta^{m}f(n)=\Delta\Delta^{m-1}f(n)$.
Then the statement above is the same as $\Delta^{r}H_M(s)=0$ for all $s$ large.
Comment: $H_M(s)$ denotes the dimension of $M_s$ over the field $k$, which is, as I understand a natural number. How can evaluation at a polynomial $p(n)$ with coefficients in $k$ be a natural number? What am I missing?
Comment: @MIT Oh! They mean a polynomial with rational coefficients (that returns integers on the integers. Like $n(n+1)/2$ and things like that). Was that what was causing trouble for understanding the statement?
Comment: Yes! I didnt understand it was a polynomial with rational coefficients, they never mentioned it. Thanks though.
Answer: It means that $H_M(s) = p(s)$ for some polynomial $p$ of degree $\leq r-1$ for $s$ sufficiently large.

David Eisenbud, Hilbert theorem


The idea's clear; the proof isn't

Question: I'm working through Enderton's book on set theory. In chapter 3, there are a series of exercises regarding functions. For instance

Prove that if $F$ and $G$ are functions, $dom(F) = dom(G)$, and $F(x) = G(x)$ for all $x$ in the common domain, then $F = G$.
Assume that $F$ and $G$ are functions. Show that $F \subseteq G$ if and only if $dom(F) \subseteq dom(G)$ and $F(x) = G(x)$ for all $x \in dom(F)$.

If I think about the statements, I come up with the following "sketches:"

Suppose $(x,F(x)) \in F$. Then $x \in dom(F)$. Since $dom(F) = dom(G)$, $x \in dom(G)$ and $(x,G(x)) \in G$. Since $G(x) = F(x)$ for all $x$ in the common domain, $(x,F(x)) \in G$. The other direction is similar.
Assume $F$ and $G$ are functions. Then $F \subseteq G$ iff $(x,y) \in F$ implies $(x,y) \in G$. Hence, $x \in dom(F)$ implies $x \in dom(G)$ and $dom(F) \subseteq dom(G)$. Similarly, $(x,y) \in F$ implies $(x,y) \in G$ iff $F(x) = G(x)$ for all $x \in dom(F)$ since $F$ and $G$ are functions and $y$ is uniquely determined by $x$.

But these are not formal proofs. I am having trouble in these exercises with formalizing the idea that I want to express. Hence, the question (request) is for an example of a formalization, so that I can see the appropriate style and level of detail involved.
Comment: Dear danportin, These seem like formal proofs to me. Regards,
Comment: Hi danportin, I too am working through Enderton's set theory. If you ever want to discuss the problems or contribute to this [manual](https://docs.google.com/viewer?a=v&pid=explorer&chrome=true&srcid=0B-baZt4ODPD3ZjgwM2M4NWQtOTNmMC00MmIzLTgxNWMtYTI1YWFkNWM0ZWEx&hl=en&authkey=COntjZAK) I'm working on, please don't hesitate to send me an email.
Comment: Yunone, I'm not sure I could contribute anything that you haven't, or anything better than what you could. But I've been working through all the exercises, so if I get "ahead," I'll shoot you an email.
Answer: You essentially have it. In fact, the first one is pretty much done (unless you want to go down to the nitty gritty of the formal definition of function as a set of ordered pairs). The second one is a bit more confused because you have "iffs" and "implies", which tends to make reading it more difficult. It might be best to separate the two implications you are trying to establish. So let me write those out. You'll see your first is essentially done, the second just needs a bit of clarification.

To prove tht $F=G$, you need to prove that $F\subseteq G$ and $G\subseteq F$. So let $(x,y)\in F$ ($F$ is a function, so all its elements are ordered pairs). In particular, $x\in\mathrm{dom}(F)=\mathrm{dom}(G)$, so there exists $z$ such that $(x,z)\in G$. Note that $(x,y)\in F$ means $F(x)=y$, and $(x,z)\in G$ means $G(x)=z$. Thus, $y = F(x) = G(x) = z$, so $(x,z)=(x,y)\in G$. Thus, $F\subseteq G$. The converse follows by symmetry (or you can try to write it out yourself).
You have an "if and only if" statement, so you may want to do it in two parts. Start by proving the "if" statement: if $\mathrm{dom}(F)=\mathrm{dom}(G)$ and $F(x)=G(x)$ for all $x\in\mathrm{dom}(F)$, then $F\subseteq G$. The proof should be similar to the one above.
Once you're done with the "if", prove the "only if": If $F\subseteq G$, then $\mathrm{dom}(F)\subseteq \mathrm{dom}(G)$ and $F(x)=G(x)$ for all $x\in\mathrm{dom}(F)$.
How do you prove this? Well, $\mathrm{dom}(F) = \{x\mid \text{there exists }y\text{ such that }(x,y)\in F\}$; similarly for $\mathrm{dom}(G)$. So let $x\in\mathrm{dom}(F)$. Then there exists $y$ such that $(x,y)\in F$. Since $F\subseteq G$, then $(x,y)\in F$ implies $(x,y)\in G$. But $(x,y)\in G$ implies $x\in\mathrm{dom}(G)$, which is what we needed to prove. So $\mathrm{dom}(F)\subseteq \mathrm{dom}(G)$. Then you want to prove that for each $x\in\mathrm{dom}(F)$, $F(x)=G(x)$. So take $x\in\mathrm{dom}(F)$; this means there exists $y$ with $(x,y)\in F$; and since $\mathrm{dom}(F)\subseteq \mathrm{dom}(G)$, you have $x\in\mathrm{dom}(G)$ so there exists $z$ such that $(x,z)\in G$. Since $F\subseteq G$, then $(x,y),(x,z)\in G$. Since $G$ is a function, $y=z$. So $(x,y)\in G$, hence $y = G(x) = F(x)$.
Comment: Thank you, Arturo. These are very clear, and are precisely the kind of examples I was looking for.

The idea's clear; the proof isn't


Matrix problem with natural numbers

Question: There are numbers from 3 to 11 and a square 3x3:
<code>  0  1  2
0 __|__|__
1 __|__|__
2   |  |
</code>
Fill this square with aforementioned numbers so that the result of multiplication of numbers in rows and columns with the same index be equal. If it is not possible explain why?
answer:
<code>7 6 5
3 9 8
10 4 11
</code>
but how to solve it?
Comment: Welcome to Math.SE.  Your chances of getting a positive response to a question are improved by giving context to the problem.  What makes this question interesting?  How would you attack it?  Can you give the results of an attempt that was partially successful?
Answer: First we decide what goes on the diagonal. The prime numbers 7 and 11 must be on the diagonal. As there are no other numbers from 3 to 11 that has 7 or 11 as factors, if say 7 is on off diagonal position, then we need another number with 7 as a factor and place it on the mirror position across the diagonal, which is impossible.
Now 9 must be also on the diagonal. If not, then say 9 is in an off diagonal position of row i, then column i must have the two off diagonal entries 3 and 6, since 9 has two factors of 3. But this makes column i having product 3*6*d and row i having product 9*?*d, where d is the corresponding diagonal. This requires ? to be 2. Since we do not have 2 in our list, we must have 9 also on the diagonal.
So far, the diagonal entries must be 7,9,11, to which you can place them any order you want.
Now for the remaining numbers 3,4,5,6,8,10, say start with 3 and put it in any remaining off diagonal position you want. The mirror position of 3 across the diagonal must be a 6, since we need a factor of 3 in those row/column. Now in the row or column that contains 3 we cannot put 4 or 5 as the third off diagonal entry, since we have the mirror position of 3 filled with 6.
So put either 8 or 10 in the row/column that contains 3. You will find that there will be able to fill the remaining squares with 4 and 5.
Example of a construction:

first put 7,9,11 goes on diagonal:
   11 ? ?
    ? 7 ?
    ? ? 9
next place 3 anywhere remaining spot you want:
   11 ? ?
    ? 7 3
    ? ? 9
we must have 6 to be in mirror position (across diagonal) from 3:
   11 ? ?
    ? 7 3
    ? 6 9
now in the row and column that contains 3, place 10 and 8 however you want:
   11 ? 8
   10 7 3
    ? 6 9
we will be left with one way to finish filling 4 and 5:
   11 5 8
   10 7 3
    4 6 9

(there should be 3!*6*2 = 72 possible solutions.)

Matrix problem with natural numbers


Correlation between two matrices with the same features but different samples

Question: I've been reading about mantel tests and Procrustes but I can't quite figure out if they require the samples to the same in matrix 1 and matrix 2?
Basically it's the same features measured in multiple groups of samples and I want to examine if some groups are more highly correlated with each other than the other groups.
Answer: Hopefully this quote from wikipedia helps (emphasis is mine):

The [Mantel] test is commonly used in ecology, where the data are usually estimates of the "distance" between objects such as species of organisms. For example, one matrix might contain estimates of the genetic distances (i.e., the amount of difference between two different genomes) between all possible pairs of species in the study, obtained by the methods of molecular systematics; while the other might contain estimates of the geographical distance between the ranges of each species to every other species.

So the rows and columns refer to the species but the entries are different samples, in the sense that they are measures of genetic difference (measured as a fixation index, say) and geographical distance (measured in kilometers, say).


How to optimize D7 Views?

Question: I would like to optimize Views as they cause most of my performance bottlenecks.
The MySQL slowlog shows not only Views related query times > 5s but, what is more scary, selects with over 10 LEFT JOINs. I have already manually removed some columns from views. It was over 14 LEFT JOINs before...
Are there any solutions (without writing custom module queries) to eliminate or limit LEFT JOINs in Views select queries ?
I found there is the Shadow contrib module available. Is it ready for production website?
Comment: related to http://drupal.stackexchange.com/q/31444/2916
Answer: I would use that contrib module. Beta releases are generally darn tight and seeing that it is beta3 would lend to the idea that it will soon be out of beta. (Of course it may never come out so that doesn't say much.) Also, the maintainer group seems to be high quality which gives me even more confidence.
To answer your other question I do not thing there is anything else you can do besides write something yourself. I was looking around and saw some initial phases of work being done on this but nothing as far along as that project you linked. I imagine this is something they will work on for D8. Your find is surprising. The only other place I might check if I were is IRC just to make sure that there isn't some other optimization technique or module out there that isn't Views specific but that will help. (Probably not, but worth a try.)

How to optimize D7 Views?


without using nested loop how to merge two list of dictionaries by same key in python

Question: I have two list of dicts:
first_list = [{
                "symbol": "BTC",
                "price": 22809
               },
              {
                "symbol": "ETH",
                "price": 1626
              }
             ]

second_list = [{
                "symbol": "BTC",
                "volume": 22809333
               },
              {
                "symbol": "ETH",
                "volume": 19809333
              }
             ]

What is the best solution (without for or another bad time complexibility solutions) to merge two lists like:
final_list = [{
                "symbol": "BTC",
                "price": 22809,
                "volume": 22809333
               },
              {
                "symbol": "ETH",
                "price": 1626,
                "volume": 19809333
              }
             ]

Answer: from itertools import zip_longest

out = [{**u, **v} for u, v in zip_longest(first_list, second_list, fillvalue={})]

#print(out)
[{'symbol': 'BTC', 'price': 22809, 'volume': 22809333},
 {'symbol': 'ETH', 'price': 1626, 'volume': 19809333}]

Comment: The important thing about using the zip_longest method is that the items in the lists must be sorted and similar items must be compressed together.
Unless your data is wrong and you are not aware of it.
Comment: The best thing to do is to sort both lists based on a specific element and check when combining
Comment: first_list = sorted(first_list, key=lambda x: x.get('symbol'))
second_list = sorted(second_list, key=lambda x: x.get('symbol'))

final_list = [u | v for u, v in zip_longest(first_list, second_list, fillvalue={})
                    if u.get('symbol') == v.get('symbol')]
Comment: Thank you for your answer! The community would appreciate if in addition to code you can provide a description / extensive comments to improve it. For example, I think it is a great opportunity to explain (or point to relevant documentation) how `zip_longest` works or what `{**u, **v}` does.


Practicing drums with metronome and not hearing its tick

Question: Often times when I'm doing simple strokes (as from Stick Control) to the tick of a metronome, I get into streaks of not hearing the metronome, just my strokes. I suppose that's a good thing, right? Meaning it's well coordinated enough as to suppress the metronome's tick.
But since it's just my guess, I wanted to know if it's something to aim for. Maybe consistently hearing the tick just after the stroke could be more desirable, I don't know. And I often wonder if I don't subconsciously do louder strokes as to suppress the tick, masking my actual timing precision.
Comment: Yes, I think that's exactly what you want to aim for.
Comment: Well, what happens when you just turn the metronome so loud that you can _always_ hear it? (ie. with closed headphones)
Comment: Ignore the answers suggesting to change something. It's a good thing! As soon as you can't hear the metronome anymore, you're perfectly on the spot. Consistently hearing the tick just after or before the stroke doesn't work, it's too difficult to decide if it was really precise (consistent enough). As long as you are able to hear the metronome when you're off the beat, there's no need to increase the volume. Anyway, closed headphones or another way of protecting your ear is never a bad idea.
Comment: I don't use closed headphones for the metronome, is it preferrable? I'll have to try! But would I have a good sense of when stroke and tick matched this way?
Comment: Interesting that answers and others' comments have upvotes but not my question, wonder what it means. Just wishing I could upvote myself but oh well.
Answer: If you can't hear the click because it falls right underneath your strokes, that's called "burying the click", and it's generally a good thing.  If your stroke is consistently just before the click, that's referred to as playing "ahead of the beat"; If your stroke is just after the click, it's called playing "behind the beat".  Both are valid techniques to achieve a certain feel, but you don't generally want to use them all the time.
Comment: If you're trying to achieve a certain feel you might not want to be straight on the click beat every time - listen to something like The Roots "Dilla Joints"; Questlove is a master at playing around with the feel and getting ahead/behind deliberately. I can see not wanting to be dead on the click if you're playing with other musicians doing something like jazz, where the music should be as organic and flexible as possible.
Comment: Hi Vic, I just meant it's a good thing, unless you're specifically going for an "ahead of the beat" or "behind the beat" feel.
Comment: When you say "generally a good thing", do you mean there are disadvantages to it? If so what would those be?
Answer: I cannot speak specifically to percussion, but when I have worked with both wind players and pianists, when the student "loses" the metronome click, that is typically a bad thing.  This is because they are so caught up in what they are playing that they are not concentrating on their time, and they are actually ignoring the metronome so much that they do not perceive the metronome sound anymore, no matter how audible it is.  I would be surprised if a similar phenomenon was not in play here to some degree.
I have three suggestions for such students:

Slow down, possibly ridiculously, until it is possible to play the passage easily without losing the metronome.  Then, and only then, work on speeding up.
The metronome is not usually the first thing to use when practicing.  If the student does not have reasonable control of the technique of a passage, the metronome will not help anything.  If stability of tempo or evenness is in question but the student can basically play everything, that is when the metronome is the best.
If possible, get a metronome with a different timbre.  "Dr. Beat" is one such metronome, though I typically recommend avoiding the voice counting "one, two, ..." because it does not adequately indicate the takt (plus, it's annoying).  In your case, if the metronome sounds too much like the instrument, this suggestion could be particularly helpful.
Comment: That's an interesting point, but I usually always pay attention to the metronome's visual cue even when I'm not hearing the tick because my stroke suppresses it. So I'm talking about situations where I'm seeing the metronome's visual indication but not hearing it.
Comment: If you are seeing the cue and are sure you are with it, then the only suggestion I have would be the timbre change (and possibly headphones, as others have suggested).
Answer: You could watch the "visual" beat on the metronome instead of trying to hear the tick. That would not be masked by the sharp sound of the drum.
Edit:
Some metronome apps for Android has vibrator. Maybe this could help if having it in your pocket, and you will feel the beat.
Edit2:
To help with the timing on a visual cue, you could look to a classical old style mechanic metronome, where you have the pending stick that gives you a clue when each beat approaches, and not just a sudden blink as you have on the digital ones.
Comment: Yes, I often try to take that as a visual cue as well, but I find that I just can't make as good an assessment for when the visual cue and my stroke match perfectly. Can you? I'd be interested in more tips on practicing like this.
Answer: I can't work with a visual cue either.  I would suggest using headphones like leftaroundabout said.  Others have made a fair point that the sound may be obscured due to perfect timing, but it also may be obscured by other things including psychology (as Andrew said) :P.
If your timing is perfect, hearing the metronome via headphones and confirming it won't hurt anything.  Of course, you'll also want to practice without the metronome to see if you can manage without it, and playing with it there but inaudible unless you go off-time may be a good intermediate step between off and always-audible.


There are red and blue balls in the urn, only put red ball back. What is the expected value?

Question: There are b blue balls and r red balls in the urn. All balls currently in the urn have an equal probability of being selected each.
When drawing a red ball, put it back in the urn, but a blue ball doesn't. Ask the expected value of times to draw the red ball after n times drawn.
I'm really confused since if put both red and blue balls back in the urn, it will be binomial, if put neither of them back, it will be hypergeometric.
But only put back red ball but not blue is very hard to figure out.
Comment: It looks like you are looking for a formula only. I'd suggest to try to understand what is going on. Decompose it into different events that can happen and calculate their probabilities.
Answer: I cannot see a simple closed form, but there will be a recurrence.
Suppose the expectation is $f(r,b,n)$.  Then  $$f(r,b,n)= \frac{r}{r+b}(1+f(r,b,n-1))
+ \frac{b}{r+b}f(r,b-1,n-1)$$ starting with $f(r,b,0)=0$.
For example, if $r=10,b=5,n=3$ then you get $f(10,5,3)=\frac{35216}{17199} \approx 2.0475609$ as your expected number of red balls drawn, slightly more that the expectation of $2$ red balls you would get with the binomial or hypergeometric approach.


C++| OOP | How to declare the variable "a" in class inheritance in main function with switch case

Question: I am making an exercise to choose and entry a kind of quadrangle with class inheritance then check it's methods. However, my main function runs into errors (Error C2065 'a': undeclared identifier. Error C2371 'a': redefinition; different basic types. E0020 identifier "a" is undefined). Please help me correct
#pragma once
#include <iostream>
#include "Point.h"
#include "Quadrangle.h"
#include "Trapezoid.h"
#include "Parallelogram.h"
#include "Rectangle.h"
#include "Square.h"

using namespace std;

int main() {
    int choice = 0;

    do {
        cout << "\n----------MENU----------" << endl;
        cout << "1. Trapezoid" << endl;
        cout << "2. Parallelogram" << endl;
        cout << "3. Rectangle" << endl;
        cout << "4. Square" << endl;
        cout << "----------" << endl;
        cout << "Please choose: ";
        cin >> choice;

        switch (choice) {
        case 1:
            Trapezoid a;
            break;
        case 2:
            Parallelogram a;
            break;
        case 3:
            Rectangle a;
            break;
        case 4:
            Square a;
            break;
        default:
            cout << "Please entry again" << endl;
        }

    } while (choice < 1 || choice > 4);

    a.Set();
    a.CheckCondition();

    cout << "Perimeter = " << a.Perimeter() << endl;
    cout << "Area = " << a.Area() << endl;

    system("pause");
    return 0;
}

Please help me declare variable "a" to avoid errors.
Comment: There is no way to declare a variable in automatic storage to have different types depending on some condition at runtime. You'll need to use some form of indirection, like making `a` a `std::unique_ptr` to some common parent class.
Comment: Can you type the sample code for my case?
Answer: You are declaring the variable a inside of the switch statement, so it won't be known outside of this statement(The variable is local to the switch statement). In order to be able to use the variable after the statement you would have to declare it before entering the switch statement and even the while loop.
In order for overriding to work, a must be allocated dynamically using new and later delete because even if you asign a Trapezoid() to a, a would still be a Quadrangle!
Quadrangle* a;
do {
    ...
    switch(choice) {
    case 1:
         a = new Trapezoid();
    ...
    }

} while...

//A now accessible
cout << "Perimeter = " << a.Perimeter() << endl;

delete a;


Import LoginToboggan settings

Question: Is it possible to import the LoginToboggan settings to a feature ? Logintoboggan doesn't seem to have an api either
Answer: You'll want to use the strongarm module. That will expose the variables that logintoboggan stores it's settings in to features. When building your feature it will add an option for "strongarm: variables" to the edit components section.
You will need to know the actual internal variable name. You can get that by either looking at logintoboggan's code or from the field names in the settings page's html source.

Import LoginToboggan settings


How to convert different formats of date timestamp to the format of timestamp in hive table

Question: I have a list of different formats of timestamp. How to change its for to the format accepted in hive tables.
For eg.
20210811:12:55:56.563 to 2021-08-11 12:55:56.563
25/05/1999 02:35:05.532 to 1999-05-25 02:35:05.532 .
How to do it in python. I have around 7-8 different formats.
Does anyone have any ideas or approach around it.
Your ideas are most welcome.
Answer: You can use below py function to check the format. If below functions returns not none values, then its in expected format else no. Return value will be a date time in yyyy-MM-dd HH:MI:SS.SSSSS format. You can easily insert this into hive date time field.
import datetime

#formats to be checked
fmts=['%d/%m/%Y %H:%M:%S.%f','%Y%m%d %H:%M:%S.%f','%d-%m-%Y %H:%M:%S.%f']

#func to check the formats and return proper date time if its in correct format.
def try_strptime(s, fmts=fmts):
    for fmt in fmts:
        try:
            return datetime.strptime(s, fmt)
        except:
            continue

    return None

Comment: Thanks Kaushik for your help. problem solved!!


Find $\lim_a \frac{Tr^n \left( ({\bf x}-a\cdot{\bf y}) \cdot ({\bf x}-a \cdot{\bf y})^T \right)-Tr^n \left( {\bf x} \cdot {\bf x}^T \right)}{a}$

Question: Let ${\bf x}, {\bf y} \in \mathbb{R}^{ m \times 1}$ and $a \in \mathbb{R}$. How to find the following limit
\begin{align}
\lim_{a \to 0 } \frac{Tr^n \left( ({\bf x}-a\cdot{\bf y}) \cdot ({\bf x}-a \cdot{\bf y})^T \right)-Tr^n \left( {\bf x} \cdot {\bf x}^T \right)}{a}
\end{align}
form some $n>0$.
For the case $m=1$ we have that
\begin{align}
\lim_{a \to 0 } \frac{  (x-a\cdot y)^{2n} - x^{2n}}{a}=-2n\cdot  y \cdot x^{2n-1}
\end{align}
But how to do the general case?
Thank you
Answer: Define the function $T(a) = {\rm tr}\Big((x-ay)(x-ay)^T\Big)$
First, use L'Hopital's rule to reduce the problem to the evaluation of
the function $(\frac{dT^n}{da})$ at the point $a=0$.
Second, find the derivative
$$\eqalign{
 w &= (ay-x) \cr
 T &= {\rm tr}(ww^T) = w^Tw \cr
dT &= 2w^Tdw \cr
dT^n &= nT^{n-1}dT \cr
  &= 2nT^{n-1}\,w^Tdw \cr
  &= 2nT^{n-1}\,w^Ty\,da \cr
  &= 2nT^{n-1}\,(ay-x)^Ty\,da \cr
\frac{dT^n}{da} &= 2nT^{n-1}\,(ay-x)^Ty \cr\cr
}$$
Finally, evaluate this derivative at $a=0$
$$\eqalign{
  \frac{dT^n}{da} &= -2nT^{n-1}\,x^Ty \cr
  &= -2n(x^Tx)^{n-1}\,x^Ty \cr
}$$
Comment: thank you. Do you have any good references on matrix calculus.
Comment: Could you show me how you would  compute a second derivative?  I can't seem to figure it out