file server hard disks for 20 concurrent users and 2 TB of data. Do i need SAS or SATA disks?

Question: I plan a new fileserver with 20 concurrent users and 2 TB of online storage. I plan to divide this data volume over 3-4 separate disks. I plan to buy 10k rpm disks. Implementing RAID-1, this would mean that i need 6-8 diks.
Should i go for sas disks or would sata disks be sufficient?
Comment: How is "should I use A or B" not a product recommendation?
Comment: I do not seek product, service or learning material recommendations. I am only inquiring about whether i should use sas or sata disks to solve my problem. I must say that, for being a newbie, you guys are giving me a very hard time to get my information. Perhaps you should read my question better instead of shutting me down like that
Comment: In my view SAS and SATA are technologies, not products like HP or DEll . How can You discuss technology if It is not allowed  namING the technologeis
Comment: I agree to that. This is a discussion over the merits of two technologies, not about specific products.
Comment: I hear you, but his question isn't "what are the pros and cons of SAS vs. SATA"; instead, he's asking for something tailored to his server requirements.  For my money, that's off-topic; if not as "product recommendation", then as a duplicate of http://serverfault.com/questions/384686/can-you-help-me-with-my-capacity-planning .
Answer: SAS drives are your best approach. Use enterprise SAS disks for speed and nearline SAS disks for capacity.
There's no reason to buy SATA drives these days if you have a choice (unless they're SSDs). Can you elaborate on the server hardware make/model, RAID controller, etc.
Comment: I am thinking about a HP Proliant ML 350p Gen8. I do not know about available RAID levels, though.Is it a goodpractice to split the 2 Tb over p.ex. 4 Sas 10k rpm drives in order to make access and transfer times better?
Comment: @user1985245 An HP Gen8 is a safe bet. Be sure that the onboard RAID controller has at least 512MB of cache. SAS disks are available in 300GB, 450GB, 600GB, 900GB and 1.2TB sizes for 2.5" drives. FOUR or SIX drives in a RAID 1+0 is a good configuration on that particular server.
Comment: Thank you for this info. You have been a great help in sorting this out for me.
Comment: Man, "no reason to buy SATA" for a small setup - ever heard of that funny thing called "Money"? Hint - any SAS setup costs a TON more than a SATA setup. I run a SAS backplane setup and I still buy SATA discs because the price of most SAS discs is crazy high.
Answer: SATA - no need to go SAS. Heck, if you have a decent Raid controller you do not even need 10k RPM discs - 5400 RPM discs are fine, with some SSD as caches.
This smells like you could use one of the SUperMicro storage cases - 24 x 2.5" front loaded SAS slots (+2 back loaded for the IS), a Adaptec 71605Q and 2 smaller SSD as cache - this is what I run now. Slow? Weeeellll..... Raid 6 over 8 discs and I am copying files around with 100+ mb/s - sometimes more than 500. THe SSD cache make a world of difference.
SATA generally is enough for that - remember, this is STILL low usage.
How do you arrive at the need to separate the volumes? Seriously? 2tb is small.
Comment: I thought of using multiple volumes to increase access times. I do not want the drives to become the bottleneck of the system. Is my reasoning valid?
Comment: I agree that for a 20 user fileserver SATA would be fine. I would use 7200RPM to get the sweet spot between price/performance. Four 1TB drives in RAID 10 would give you 2TB and good performance/redundancy... more platters would give you more IOPs of course.
Comment: @user1985245 no, it is not - the IO budget is the same, regardless how you slice it. And smaller parts are more likely to overload.


"Your site was unable to contact the Apache Solr server"

Question: We have been using Drupal 6 for 2 years and we wanted to use SOLR to have a better search and index more documents.
I have did everything right with Apache Solr as per the documentation, my Solr was working fine but I am able to access it on http://localhost/solr/admin.
I have different Solr in different servers, and none work with this Drupal. So I think there is an inherent problem within Drupal, which makes drupal not to find the solr properly.
Previously, I had encountered this issue several times configuring different servers, I am used to reinstall Drupal which made solr work fine but I cant do it to this one because its been running for long with lot of content.
Can anyone help me?
Answer: There a  lot of apache solr variables set. Can you uninstall the solr module, remove the variables if left over and re-install. Sometimes, when you do a wrong config and it can't connect, it presists this in variable. Un-installing and re-installing should help.
Answer: I follow this article https://www.lullabot.com/blog/article/installing-solr-use-drupal ,some day comes this errors after I reconfig of my site& apache.
but I sloved like this
Comment: I don't want install apache tomcat, do you have a solution without install tomcat?
Answer: If your site runs on Pantheon and you restored a database export from Pantheon in a local development environment, you have to disable the Pantheon Apache Solr module. It will not use the configured Solr URL if this module is running.
Answer: Belated answer:
check whether your Solr-serving process is running, and whether you are serving up Solr on the correct port.
The default Solr install seems always to come with Jetty (a Java based server) which runs on port 8983.
Solr can also be installed over Tomcat (another Java based server) which runs on port 8080.
Check if the process (whichever you chose - Jetty or Tomcat) is running, e.g.:
  ps -ef | grep tomcat
Your web logs may offer a clue.
Answer: You just need to add your collection in solr by following the step given in this url ( Apache Solr 4.6.0 installation and compatibility with Drupal7... ) and then select your collection from your solr which is running on localhost or live site (http://localhost:8983/solr/) and go to schema tab. Click schema tab and then you can see you schema file attach in apachesolr module.
You now just need to your schema url which just look like this http://localhost:8983/solr/your_core_name/. Now add this url in apachesolr module.
Then it will show that your site has contacted apache solr server in your drupal site.


How Applications manage DNS records with 2 or more IP address?

Question: I have a couple of DNS records with 2 or more IP addresses, for example, the A records for our email server is "mail.example.com" and have 2 IPaddress:
<code>mail.example.com  188.8.131.52
mail.example.com  22.214.171.124
</code>
Each IP address belong to a different ISP. Sometimes, when one of those IP's are  unavailable, some applications on users's computers (like Outlook) get stocked with only the first IP address on the A record they received from the DNS Server, even though it receives 2 IP's, Outlook does not try with the other IP. I've seen this with other applications as well. When I run "ipconfig /displaydns" I see that the DNS have delivered the 2 IP's for the A record, but the app is only using the first one.
We use Amazon Route 53 to manage DNS, and to workaround this I'm using "Health Checks" and then the DNS response based on the availavility of the IP's.
My question is, is it normal that applications use only the first IP address they find on the DNS record? Is there any other way to make the applications alternate between the IPs on a given DNS record or this behave depends on the app?
Comment: For mail systems, you should use two MX records instead of two A records. That will make all standards-compliant mailservers try the second server if the first is down.
Comment: Hi, and thanks for your reply, but the MX records are used by SMTP servers, I'm refering to clients like Outlook, they look for A record, not MX.
Comment: Ah, that was a misunderstanding on my part. In that case, you've already been answered below.
Answer:
My question is, is it normal that applications use only the first IP
  address they find on the DNS record?

Yes. Many applications are designed in a way to return a single address when resolving a hostname to numerical address.  Some applications such as web browsers will pull a full list of records and try them sequentially on failure.

Is there any other way to make the applications alternate between the
  IPs on a given DNS record or this behave depends on the app?

No, this needs to be handled by the name server.  Even with round robin, there are cases when the first IP Address returned by the resolver is not the first returned to the application from the method used for the lookup.
Comment: I believe the AWS DNS Server, Route 53, returns records in a random order. That way if the clients use the first record in the list they're effectively using a random record.
Comment: Agreed. Multiple A records should be treated with the same priority.  The order of multiple records cannot be a reliable way to determine weight of a specific record, nor be used for health or geolocation checks, that logic should stay within the resolver.
Answer: Of course, the purpose of DNS is to get an IP address. The only reason that would make me as an app developer to use a second A or AAAA record would be if I couldn't connect to the endpoint with the first one.
If you wanted to do load balancing you would have to take that "ordinary" behaviour into consideration and make your DNS server prioritize A or AAAA records accordingly.
Comment: That doesn't really answer the question.
Comment: I beg to differ. The implication is clear: it is app dependent.


Near identical code producing different results. TIME modual

Question: I am using TIME for the first time and wanted to make a basic timer. I ran this code completely on its own:
import time
start = int(time.time())
answered = "No"
while int(time.time()) - 2 < start:
  if input("What's 1 + 1?") == 2:
    print("Correct")
  else:
    print("Incorrect")

This code's execution gives you 2 seconds to answer as many times as you want, once 2s is up you can no longer answer, this was made just so I could practice using the TIME module and has no greater purpose.
However, when I tried to implement the TIME module into a game I am working on:
start = int(time.time())
hits = 0
while int(time.time()) - start != time:
 #COMBAT MECHANICS#

I have only included a tiny snippet of code as this is the only times time is mentioned in the code so the only relevant part for this error.
When this code is ran I receive the message: "UnboundLovalError: local variable 'time' referenced before assignment"
Time is imported at the beginning of the code as it was in the practice. The only difference is this is within a function, but I don't see how that should influence the behaviour of the code.
Please can someone help me fix this.
Comment: You seem to be using the name `time` for both the imported module and a local variable.  It can't be both things at the same time...
Comment: _The only difference is this is within a function, but I don't see how that should influence the behaviour of the code._ this COULD have HUGE difference, due to scope. Please, post [mre], incl. full traceback
Answer: As pointed out by @jasonharper you changed your logic in the second example and in the process misused time in your while statement.  Keeping your second example's logic in line with your first example's logic (assuming that is your goal) you would want to do something like this:
start = int(time.time())
hits = 0
while int(time.time()) - 2 < start:
 #COMBAT MECHANICS#


Counting how many times a word is in a file

Question: I'm trying to write a program that gets a string, and counts how many times that string is found in a specific file.
The file is currently: hello my name hello is oria
I like hello to program
And the word I'm counting is hello.
this is my code
int num_of_words(FILE* stream,char* str)
{
    int count=0,i=0,length;
    char c;
    rewind(stream);
    length=strlen(str);
    do
    {
        c=fgetc(stream);
        while(c==*(str+i))
        {
            c=fgetc(stream);
            i++;
            if(i==length)
            {
                count++;
                i=0;
            }
        }
        i=0;
    }while(c!=EOF);
    return count;
}

The idea is that there is a certain index called i, and it advances only if there is a match between letters. if i reached the length of the string, then it means we found all the letters in succession, and i raise count by one.
For some reason, it always returns zero.
Comment: `fgetc()` returns `int`, `EOF` is not a character value.
Comment: search string include newline.
Comment: Do you need to know how many times a word is in a file, or how many time a string is in a file?  For example, searching for the string "word" would get a hit in "Sword", is that what you want?  If not then you might need regular expressions using the word boundary markers.  C might not be the ideal language.
Answer: I. while (!eof) is wrong.
II. Don't reinvent the wheel - there's the strstr() function in the C standard library which helps you find a substring in another string.
I'd rather read the file into a buffer then use the following function. If the file is not too large, this should not be a problem.
int count(const char *haystack, const char *needle)
{
    int n = 0;
    const char *p = haystack;
    size_t len = strlen(needle);
    while (p = strstr(p, needle)) {
        n++;
        p += len;
    }

    return n;
}

Comment: Would changing the !=eof to !feof(stream) correct the problem?
Answer: char c; should probably be int c; to accommodate for the type of data that fgetc returns. Otherwise, when char is an unsigned type c can never equal EOF and your loop will never end.
Before your code increments i once, it reads two characters from the file. That seems problematic to me. I'd move the c=fgetc(stream); in the inner loop to the end of that loop, eg:
    while(c==*(str+i))
    {
        i++;
        if(i==length)
        {
            count++;
            i=0;
            break;
        }
        c=fgetc(stream);
    }


How to display views titles by categories

Question: I have a content type which has category field.
I added few nodes. Each node has a value from category.
I would like to display a views block which should display titles grouped by category. That means:
Category 1
title
title
title
Category 2
title
title
title
I created a views block:
Format: Unformatted list
Fields: Title
Now, I have list of titles. I am not sure how I can add category(non linked) before the relevant titles?
Comment: I suppose similar questions have been asked before here (so a comment instead of an answer). Add your category as a field, and suppress it from showing. Then in the format settings (left top) choose a grouping field. That will give what you need.
Comment: Please refer https://drupal.stackexchange.com/questions/237954/how-do-i-add-a-subheading-to-a-view
Answer: You can group content based on the field. Click the format settings in View,

select the field here and group the content
NOTE: Grouping field should be added in the field area and then field will be shown in the grouping select list.


How are key signatures for quarter tones denoted?

Question: For example, in 31-TET, all tones are accessible via (double) sharps or (double) flats on CDEFGAB. So there exists key signatures, for example, D double-flat major. (That's same as C half-sharp major.) Wikipedia has a comprehensive list of the keys.
But what for 24-TET? The in-between tones are not accessible via sharps nor flats on CDEFGAB. I can't think of the key signature, for example, C half-sharp major. How should they be denoted?
Comment: @user45266 That applies to 24-TET, but not in 31-TET. In 31-TET, D double flat is C half-sharp, and D three-halves flat is C sharp.
Comment: Most musicians interpret "D Double Flat" tro be enharmonically equivalent to C, whereas you seem to be using the term to describe what others call "D three-halves flat", sometimes represented by a backwards flat next to a regular flat.
Answer: A quartertone key signature sounds extremely complicated and painful to read.
If for some reason you need to notate a piece in a quartertone key I'd say add staff text at the beginning of the piece telling the performer to re-tune their instrument a quartertone up or down and use the nearest normal key signature.
Alternatively, use no key signature and go wild with the half-accidentals.
Answer: A quick DuckDuckGo search for '24-TET notation' leads to the wikipedia article on quarter tones which shows one possible notation system ,and to Introduction to quarter tones which details another.
As a player who only ever produces quarter tones accidentally or as part of a slide, I cannot advise on which is 'better' ...


Update a table based on values from a other table

Question: It's rather simple, I want to update a table but only if a condition in a other table is met.
The query i currently have:
UPDATE Table1
SET Table1.value='1234'
WHERE   ID IN
(
  (A sub query returning all the id's needed)
)

This sort of works, but it updates to many values.
Problem is that there is a second condition, namely:
AND Table2.value = 'Pudding'

But seeing it's a different table it doesn't work. And i don't know how to join it in Oracle. Seen some other posts but they don't seem to relate to my specific problem. Tried adding the From clause with joins that i also use in the sub-query but i can't find here to put it in an update statement in oracle.
Edit: Example database
Table1
ID    Key1     Key2     Value
1    A1       B1       345
2    A1       B2       75
3    A2       B1       45

Table2
Key1     Key2     Value
A1       B1       'Pudding'
A1       B2       'Pudding'
A2       B1       'Something else'

And yes the Table2 is also part of the sub-query, but so are about 6 other tables. I believe that listing the entire structure of the sub-query would only be more confusing seeing all it does it bring back a series of Id's which already works fine.
But as result the first two rows in the example need to be updated.
Comment: Sample data and desired results would really help.  I don't see what `Table2` has to do with your query.
Comment: Is the subquery accessing `table2` to get the IDs, or something else? Are the two tables related some how? And yes, sample data would help explain.
Comment: @AlexPoole and Gordon
I updated the question with a sample of the data and an explanation on why i'm not doing the entire sub query.
Answer: You can try to use exists with subquery like this, becuase there are two columns need to compare in the tables.
UPDATE Table1 t1
SET t1.Value = '1234'
WHERE t1.ID IN
    (
      --(A sub query returning all the id's needed)
    )
and
    exists (
     select 1
     from Table2 t2
     where t1.Key2 =t2.Key2 and t1.Key1 =t2.Key1 and t2.Value = 'Pudding'
    )

Here is a sample
CREATE TABLE Table1(
  ID INT,
  Key1 VARCHAR(50),
  Key2 VARCHAR(50),
  Value VARCHAR(50)
);

INSERT INTO Table1 VALUES (1,'A1','B1','345');
INSERT INTO Table1 VALUES (2,'A1','B2','75');
INSERT INTO Table1 VALUES (3,'A2','B1','45');

CREATE TABLE Table2(
  Key1 VARCHAR(50),
  Key2 VARCHAR(50),
  Value VARCHAR(50)
);

INSERT INTO Table2 VALUES ('A1','B1','Pudding');
INSERT INTO Table2 VALUES ('A1','B2','Pudding');
INSERT INTO Table2 VALUES ('A2','B1','Something else');

UPDATE Table1 t1
SET t1.Value = '1234'
WHERE  exists (
 select 1
 from Table2 t2
 where t1.Key2 =t2.Key2 and t1.Key1 =t2.Key1 and t2.Value = 'Pudding'
)

Query 1:
select * from Table1

Results:
| ID | KEY1 | KEY2 | VALUE |
|----|------|------|-------|
|  1 |   A1 |   B1 |  1234 |
|  2 |   A1 |   B2 |  1234 |
|  3 |   A2 |   B1 |    45 |

Comment: `TRUE if a subquery returns at least one row`.  `select 1`
 mean the condition match  in the subquery.https://docs.oracle.com/cd/B19306_01/server.102/b14200/conditions012.htm`
Comment: This works, but i have a little question. I've never used Exists before and wonder why the "Select 1"? what function does that have?


Different note head uses in MuseScore?

Question: The photo here is from "MuseScore", the free notation software. A note head replaces a note head, shown in this photo.

Since I have never seen these note heads before, what are these used for (if ever used) and where? I see some common ones, like the first and 13th one, but the ladder and the other I do not know. Thank you~
Answer: Some of it appears to be a variation of shape notes (5,8,9,10,11,12), others seem based on larger note values that are quite rare in modern music and clef like (6,14). Some (mainly the Xs and triangles) seem based on percussion notation (2,7,8) and some just seem to be decorations (1,3,4,13).
As these notes heads come from different places and are used in different situations it's best not to use them until you learn more about them.
Comment: +1 because even though our lists are similar, you match specific symbols to specific uses.
Answer: Here are some of example of where alternate note heads are useful. There are probably more that I can't think of, or am unaware of.

The "ladder" shape is one form of the double-whole note (aka breve). As you might expect, it has twice the duration of a regular whole note.
Notation for percussion instruments oftens use various shapes to indicate different drums (such as an 'x' for high-hat), or different types of drum strikes.
Similarly, spoken parts that are unpitched, but require being notated in the score (usually for rhythmic reasons) will also use an 'x'-shaped note head.
There is a notational tradition among some singers to use shaped notes to indicate scale degree (basically a notated version of solfege), which, in theory, is meant to make music more easily transposable to other keys.
Comment: Good answer. I would also add to the third point that stringed instruments can be played while muted with the fretting hand and that is normally notated with an x shaped head also. Pitchless as well so means the same thing but another common example of the use of this shape.

Different note head uses in MuseScore?


LEFT JOIN gives no results

Question: So basically I have two tables:

u_contracts
+--------+---------+------------------------------+
| id     | user_id | reschedule_wait_confirm_till |
+--------+---------+------------------------------+
| 107742 |   19982 | 2012-08-08 17:10:41          |
|  38548 |    4622 | 2012-08-08 10:24:42          |
|  98483 |   36707 | 2012-08-08 21:39:08          |
|  45165 |   17632 | 2012-08-08 23:13:57          |
| 131285 |   47527 | 2012-08-08 08:33:58          |
| 131686 |   40194 | 2012-08-08 12:18:09          |
|  91749 |   11021 | 2012-08-08 12:22:05          |
+--------+---------+------------------------------+

restruct_mail_history
+----+---------+---------------------+
| id | user_id | _date               |
+----+---------+---------------------+
|  1 |   47527 | 2012-08-07 12:16:51 |
+----+---------+---------------------+

Now I need to select all user_id's from u_contracts that have date reschedule_wait_confirm_till for tomorrow and that have no todays entires in restruct_mail_history.
So far I have a working query like this:
SELECT
  uc.user_id
FROM
  u_contracts uc
WHERE
  uc._status = 6
  AND DATE( uc.reschedule_wait_confirm_till ) = DATE( ADDDATE( now(), 1 ) )
  AND uc.user_id NOT IN ( SELECT rmh.user_id FROM restruct_mail_history rmh WHERE DATE( rmh._date ) = DATE( now() ));

Output:
19982
4622
36707
17632
40194
11021

Now I don't like the SELECT statement in WHERE, so I was planing to make LEFT JOIN like this:
SELECT
  uc.user_id
FROM
  u_contracts uc
LEFT JOIN
  restruct_mail_history rmh
ON
  uc.user_id = rmh.user_id
WHERE
  uc._status = 6
  AND DATE( uc.reschedule_wait_confirm_till ) = DATE( ADDDATE( now(), 1 ) );

Output:
19982
4622
36707
17632
47527
40194
11021

Now this gives me all u_contracts result, but when I add the necessary parameter AND DATE( rmh._date ) != DATE( now() ) it gives me absolutelu no results.
Any idea what I'm doing wrong?
EDIT If iI change the last line to AND DATE( rmh._date ) = DATE( now() ), it gives me only the results that should not be in the list, witch id correct. Why doesn't it work the opposite way?
Thank you already.
Comment: is there any nulls in the time date columns?
Answer: try this:
SELECT uc.user_id
FROM u_contracts uc
     LEFT JOIN restruct_mail_history rmh
        ON uc.user_id = rmh.user_id
WHERE uc._status = 6 AND
      DATE( uc.reschedule_wait_confirm_till ) = DATE( ADDDATE( now(), 1) ) AND
      (rmh.user_id IS NULL OR DATE( rmh._date ) != DATE( now() ));

see here: Visual Explanation Of Joins.
Comment: EDIT: you need to add `rmh.user_id IS NULL` in where clause.
Comment: This still gives me back all the results;
Comment: Nope, it still hase the extra line. I updated the question with output examples and data from *both* tables.
Answer: TRy this
SELECT
  uc.user_id
FROM
  u_contracts uc
LEFT JOIN
  restruct_mail_history rmh
ON
  uc.user_id = rmh.user_id and   uc._status = 6
  AND DATE( uc.reschedule_wait_confirm_till ) = DATE( ADDDATE( now(), -147 ) );

Comment: My mistake, It was there in the original question ;)

LEFT JOIN gives no results


get parent's siblings of term in views

Question: I want to create a views that termId passed from url to it  and then show parent and parent's siblings(uncle aunt) of that term,,I can handle that show parent term id ,but I don't any idea that how can I get parent's siblings,I can handle it finally with php_views but first ask here maybe somebody has better solution.
tnx for your attetions
Answer: I did some a quick search and stumbled onto this comment in this thread, which led to the Views arg parent term module. From what I read on the module page
..this module provides another default plugin argument, to get
associated parent terms.
I think it can be helpful in your case.

get parent's siblings of term in views


Substituição e exibição de parâmetro em PHP

Question: Estou criando um codificador, um projeto pessoal para aplicar conhecimentos e aprender mais.
A parte de codificar está funcionando, mas a parte de decodificar não.
Eu executo e não aparece nada.
Alguém poderia me ajudar a encontrar o problema?

    <form method="POST" action="resultado.php">
        <fieldset>
 Escolha uma opção:

            <input type="radio" name="condiçao" id="codificar" value="codificar"> Codificar
            <input type="radio" name="condiçao" id="decodificar" value="decodificar"> Decodificar
        </fieldset>

Digite o texto:

        <textarea name= "txt" class="cod" cols="100%" rows="20" > </textarea>

        <button> ENVIAR </button>
    </form>

    <?php
    echo "
 Resultado:
";
    $condiçao = isset($_POST["condiçao"])?$_POST["condiçao"]:" ";
    $txt = isset($_POST["txt"])? trim($_POST["txt"]):" ";
    //conta
    $cont = str_word_count($txt);
    //divide
    $v= explode(" ", $txt);
    //junta
    //inicio contador
    $i = 0;
    while ($i>$cont) {
        if($v[$i] == "21UO4UTYEP"){
            echo "A";
        }
        elseif ($v[$i] == "IPDQXS1QGL") {
            echo "B";
        }
        $i++;
    }
    ?>

Comment: No seu while está errado o ` while ($i>$cont) {`   precisa ser ` while ($i<$cont) {`
Comment: Nem acredito que não percebi. Obrigado cara
Comment: Tranquilo, isso acontece. Quando travar em alguma coisa, a dica é parar e ir fazer outra coisa, depois quando você voltar precisar ler o código palavra por palavra que você encontra essas coisas. já passei por isso também algumas vezes nesse 20 anos de programação.
Answer: Você atribui o valor de $cont igual ao número de palavras e o valor $i igual a 0, depois você diz enquanto $i for maior que $cont.
Seu código nunca entra no laço, $i nunca será maior que o contador.
Inverte.
while($i < $cont){}

Comment: Nem acredito que não percebi isso. OBRIGADO


iDRAC: Does racadm have some kind of "echo" command?

Question: I'm writing some scripts to automate the interaction with racadm sessions. Sometimes I need to show some info messages to the users, like Will retry in 30 seconds. For now I just use an unknown command like this:
$ ssh admin@idrac-ip-addr
racadm> ECHO "Will retry in 30 seconds."
ERROR: Invalid command specified.
racadm>

This works though it's a bit ugly. So I want to know if there's anything like an echo command or does it support comments (like the # char in shells).
Answer: No, it doesn't.
If you are running a script this is functionality you would build into the sending side. For example, if you are on Linux on a remote device connecting to the iDRAC, you would use iDRAC Tools for Linux and as part of your bash script you would have the echos. For example:
sysinfo=$(racadm -r SERVERIP -u root -p YOURPASS getsysinfo)
echo $sysinfo


how to find image style url from themed image

Question: I've a code which theme & print the original image to specific image style.
print theme('image_style', array(
  'path' => $node->field_theme_image[$node->language][0]['uri'],
  'style_name' => 'home_theme',
));

I don't figure out how to get url of this new theme. I don't need to print the image but I need just url. Please suggest.
Answer: You need to use the image_style_url function instead of theme.
$path = image_style_url('home_theme', $node->field_theme_image[$node->language][0]['uri']);

Comment: This is not the correct way to do this.  See this article:  https://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way  also I have a way to do this without writing a single line of code.  See my answer below.


How a Boolean Algebra is a $\bf F_2-$ Vector Space?

Question: In a answer of this question it's said that "A ($\sigma$-)algebra is a boolean algebra. In particular, it is an $\Bbb F_2$ vector space."

Unfortunately i have never seen this term Boolean Algebra.Could someone please explain me what is a Boolean Algebra and how is this a $\Bbb F_2$ vector space?

Thanks for your help!
Answer: A Boolean algebra of subsets of $X$ is a collection of subsets of $X$ that is closed under finite union, finite intersection and taking complements, and contains $\emptyset$ and $X$ itself.
(Of course, there is also an abstract definition of Boolean algebras as well.)
Any Boolean algebra becomes an $\mathbb{F}_2$-vector space: the "addition" is symmetric difference $$A + B = (A \backslash B) \cup (B \backslash A),$$ and the zero element is $\emptyset.$
The answer you linked to does not seem to be valid, though: infinite-dimensional $\mathbb{F}_2$-vector spaces do not need to be uncountable sets, and there do exist countably infinite Boolean algebras.
Comment: I dont think i understand it completely.What is the scalar multiplication here? and Could you give example of countably infinite Boolean Algebra?
Comment: The scalar multiplication is $0 \cdot x = 0$ and $1 \cdot x = x$. For a countably infinite Boolean algebra, you can take the finite subsets of $\mathbb{N}$ and their complements.


Aceder a um site de um servidor que está na mesma LAN (XAMPP)

Question: Olá a todos!
Tenho dois computadores:

Windows 7;
Windows Server 2012.

O meu site está no xampp do windows server 2012, e eu quero aceder a ele através do windows 7.
Já tentei pesquisar no browser pelo IP, pelo nome do Windows Server 2012, e também tentei pesquisar pelo NomeDoWindowsServer.NomeDaEmpresa.com mas o erro é sempre o mesmo:

ERR_CONNECTION_TIMED_OUT

Gostava de saber o que preciso de configurar no Xampp, ou até mesmo no Windows Server 2012 para conseguir resolver este erro.
Obrigado desde já!
Comment: O servidor tem de estar configurado para aceitar conexões externas dentro rede, na porta 80, que por default é a que o XAMPP usa, mas pode ser diferente, tens de confirmar no XAMPP.
Comment: Procura o `httpd.conf` do xampp, tem de haver uma linha que diga algo `Listen 80`, acho que o xampp já deve estar configurado para aceitar os pedidos, mas podes confirmar. O servidor pode ter firewall? Control Panel > Firewall, se tiver e estiver activa, tens de configurar ai excepções para a porta 80.
Comment: Deve ter algo tipo `ServerName localhost:80` no **httpd.conf**, que valor tens? Se for `localhost`, muda para ser o IP do servidor, e.g. `ServerName 192.168.10.10:80`
Comment: @Leite Como é que eu configuro o xampp para aceitar conexões externas?
Comment: @Leite Sim aparece Listen 80, e em relação à firewall, eu pus turn off, do que achas que poderá ser?
Comment: OBRIGADO!!!! CONSEGUI RESOLVER!! Andei a tentar resolver isto à umas 2 semans, funcionou muito obrigado mesmo!
Answer: @Leite

Deve ter algo tipo ServerName localhost:80 no httpd.conf, que valor tens? Se for localhost, muda para ser o IP do servidor, e.g. ServerName 192.168.10.10:80


curl to tar to zip with pipes

Question: I am wanting to download a tar.gz archive, extract it and compress it into a zip file in one command with a bash script. Reason for this is to be independent from temporary files.
The code I use:
curl -L "someURL" | tar xOz --strip-components=1 | zip -@ test.zip

gives a lot of output to STDOUT so I guess zip is not accepting the pipe.
Maybe I am missing something out here, but the man page of zip doesn't give me more information than using -@ or - nor does the internet.
Comment: May be [this thread][1] can help you.

  [1]: http://stackoverflow.com/questions/2019603/how-do-you-specify-filenames-within-a-zip-when-creating-it-on-the-command-line-fr
Answer: The manpage for zip says (at least on my system):

If  a  file  list  is specified as -@ [Not on MacOS], zip takes the list of input files from standard input instead of from the command line.  For example,
      zip -@ foo
  will store the files listed one per line on stdin in foo.zip.

The manpage for tar

-O, --to-stdout
               extract files to standard output.

So, in short:
tar -O can output the files (but not their names) in one long stream to stdout. But zip expects a list of filenames on stdin. So that's not going to work. And it's hard to see how to make it work, because bash pipes are just unstructured strings, but to transmit the information from tar to zip you need to add some structure, even if it is minimal:
[filename][filedata][filename][filedata]...

And the sender (tar) and receiver (zip) would have to agree on the format of that structure. Which is not going to happen.
However, you can use interfaces to tar and zip other than the command-line utilities. For example, if you have python installed, the following should work:
#!/usr/bin/python
import sys
import tarfile
import zipfile
tarf = tarfile.open(sys.argv[1], "r:*")
zipf = zipfile.ZipFile(sys.argv[2], "w", zipfile.ZIP_DEFLATED)
for m in tarf:
  if m.isreg():
    zipf.writestr(m.path, tarf.extractfile(m).read())

(Needs lots of error checking. As written, it just crashes on any error.)
You can make that into a shell "one-very-long-liner" although personally I'd just use the python script above.
 python -c "$(printf %s \
   'import sys;import tarfile;import zipfile;' \
   'T=tarfile.open(sys.argv[1],"r:*")' \
   'Z=zipfile.ZipFile(sys.argv[2],"w",zipfile.ZIP_DEFLATED);' \
   '[Z.writestr(m.path,T.extractfile(m).read()) for m in T if m.isreg()]')" \
   input.tar output.zip

(If you want to pipe from curl into that, use /dev/stdin as the input file. I think that will avoid Python trying to interpret stdin as a UTF-8 stream.)
Comment: `tar` can output *either* the contents or their names to `stdout` but not both. Nor would it being able to do that be all that useful unless something else understood its output format for that.
Comment: @EtanReisner: Yeah, the point (which you also make) is that bash pipes are unformatted strings and unformatted strings suck as a mechanism for serializing structured data. So you need to use something a bit more sophisticated. I did it in python, but other bindings are possible.
Comment: Add "allowZip64 = True" parameter to "ZipFile" to support files greater than 4 GB.
Answer: tar is going to send all the file data to stdout (but no file names).
zip can't possibly do much of anything sane with that (barring creating a giant zip blob of doom of all the file contents in a single zip file and I can't imagine you want that).
You need to extract the files to disk if you want to create a zip archive of them.
I was going to say that you might be able to loop over the entries in the tarball (by name) and extract each one to the pipe (though that would be very costly in terms of number of times needed to scan through the tarball) but I don't actually see, in the man page for zip I have here at least, a way to get zip to compress data given to it via standard input. It only seems to take file names that way.
Comment: Thank you for this explanation. So what you are about to say is, that there is no way today to zip from stdout without a file list. So this leaves me at the beginning again, trying to find a workaround.
Comment: @Flatron From what the `zip` manpage says (as quoted by @rici in his answer) no. It cannot take file contents as input only a list of filenames. Recall that `zip` doesn't come from the same sort of universe as `tar` and friends do.

curl to tar to zip with pipes


How to use Drupal unixtime instead of timestamp

Question: What is the proper Drupal way to deal with timestamp fields?
I wanted to create two timestamp fields in a MySQL table, but ran into some problems that I can't solve (see this question). So now I want to try it with the INT fields and Unix timestamps that Drupal uses.
The two columns in question are for "created" and "updated" purposes. What is the Drupal way to store a record with the current (UTC) time and how can I retrieve those timestamps in the user's own timezone? My server is on UTC time and I'm using Drupal 7.
Comment: A Unix timestamp is always UTC, no matter what timezone the server is in.
Comment: Doh! You are absolutely right.
Answer: Use REQUEST_TIME.
I think that as long as you use Drupal to display/calculate the time, you shouldn't be worrying about time differences between the users or the site.
Comment: That works, for those who found this question, you can covert the timestamp back to a readable format with date_format.


Plane tiling by pentagons : are the given data sufficient to find certain lengths?

Question: I have the given network which is a combination of irregular pentagons with the two edge length $a$ and $b$. I embed the black square with the edge length $c=b\sqrt{6}$ in this network (as in the picture).

My question is: are the given data sufficient to find the length of $d1,\;d2$ (marked by red) and  $f1,\;f2$ (marked by green)? I guess (as the plot shows) that they should be equal as  $d1=d2$ and  $f1=f2$ and $d1+f1=b$.

I appreciate any hints or comments.
Answer: The answer to your question is "yes" : knowing the length of line segment AB is enough. Why that ?
Consider the following picture I have made with Matlab, with a certain choice of coordinates I am going to explain.

The origin $O$ is the center of the elongated hexagon. The $x$ and $y$ axes are given by $OV$ and $OA$. The axis graduation is going to be a consequence of the following choice : I have considered that the "arms" of "red cross" with center $D$ have unit length, i.e., $DA=DF=b=\cdots=1$. The same for the 3 other crosses, of course.
From there, we are going to show that
$$a:=AB=\sqrt{3}-1\tag{1}$$
Explanation : Triangles $STW$ and $UVW$ are equilateral with resp. sidelengths $a$ and $a+2$. Therefore, $UV=a+2 \implies OV=1+\frac{a}{2}$. But $OV$ can be computed in another way, as the sum of the projections of unit length segments $AD$ and $DV$ onto the horizontal axis, giving ;
$$OV=\cos(\frac{\pi}{6})+\cos(\frac{\pi}{3})=\frac{\sqrt{3}}{2}+\frac{1}{2}$$
Equating the two expressions for $OV$, we get (1).
The polar angles (angles wrt horizontal axis) of straight lines $AD, FD, CE$ are resp. $\frac{\pi}{6}, -\frac{\pi}{3}, \frac{\pi}{4}$.
Let $p=\cos\frac{\pi}{6}=\frac{\sqrt{3}}{2} \ ; \ k=p-\frac{1}{2}$.
It is not difficult from there to obtain the following coordinates :
$$A(0,k), B(0,-k), C(-p,0), D(p,p)$$
$$E(p,2p), F(k,2p), I(-p,2p), J(3p,0) \tag{2}$$
(in particular, from (2), we obtain : $c=DE=\sqrt{6}$ confirming your relationship $c=\sqrt{6}b$).
(1) allows different calculations, in particular coordinates of $G$ and $H$ (for example, for $G$, by considering it as the intersection of lines $DF$ and $CE$). Knowing these coordinates, one is able to compute the lengths you denote by $d_1$ and $d_2$.
The computation of lengths $f_1$ and $f_2$ follows the same logic.

Edit (2023/01/22)
I just realized that this paving of the plane is plainly a Voronoi diagram ! Here is how (I can give more details if you are interested); setting $r=\sqrt{3}$, we have for example the Voronoi cells'centers :
$$P,P'=(\pm \frac12(3-r), 0), \ \ Q,Q'=(0,\pm \frac32(r-1))$$

Here is the corresponding Matlab program :
<code> clear all;close all;hold on;
 axis equal;
 r=sqrt(3);
 d=(3-r)/2; %  attempt other values
 a=2;
 axis([-a,a,-a,a]);
 X=[];Y=[];S=[-1,1];
 for x=-a:a
    for y=-a:a
       m=mod(x+y,2);
       X=[X,x*r+m*d*S];
       Y=[Y,y*r+(m-1)*d*S];
    end;
 end;
 scatter(X,Y,30,'filled');
 g=voronoi(X,Y);
 set(g,'color','k','linewidth",2);
</code>
Comment: If you have time, see the splendid Wikipedia article on pentagons [here](https://en.wikipedia.org/wiki/Pentagonal_tiling) where this type of tilings is mentionned twice.
Comment: $AB$ "has to have this value" because we have chosen to take $AD=DV=1$ ; if $AD=DV=m$ ($m$ a constant) length $AB$ would be $(\sqrt{3}-1) \times m$.
Comment: No problem : these are natural questions. 1) Up to a $\pi/2$ rotation Am is the same as FG 2) About the length of DH, I have computed by hand the coordinates of $H$ : $(x=\frac14(5\sqrt{3}-3) ; y=\frac14(\sqrt{3}+3)\approx (x=1.41, y=1.18)$ giving indeed for DH the same value as DG.
Comment: A general afterthought about this issue. The unique square which is superimposed on the paving by (irregular) pentagons can be considered as a representative of another paving of the plane by squares obtained by translating this square into the horizontal and vertical directions.  I am almost sure that this **double** paving of the plane can receive an easier treatment. By the way, as I have a big interest for paving, can I ask you why you are interested in this specific paving ?
Comment: Sorry for the late response. It is a type of crystal studied in graphene-related material in solid-state physics; that is why I was interested in this structure.
Comment: I have computed the coordinates of $G$, which are $(x=(3 \sqrt{3}-3)/4 ; y=(5 \sqrt{3}-3)/4)$ ; from them, we find that length $DG=\frac12 \sqrt{6(2-\sqrt{3})}\approx 0.634$


Creating a Risset glissando with Chuck - How do I get rid of the "click"

Question: I'm trying to create a Risset glissando (https://en.wikipedia.org/wiki/Shepard_tone) with chuck (http://chuck.cs.princeton.edu/). The problem is, I keep hearing a very annoying click when the sounds start a new cycle. I tried to get rid of it by not using the extremes of the gain range but it doesn't seem to help. Does anybody have an idea how I get rid of the click? Here's my code:

//low sinsus wave
SinOsc s1 => Gain g1 => dac;

//high sinus wave
SinOsc s2 => Gain g2 => dac;

//a C at 110hz
110.0 => float c;

//octave (2 times our C)
(2 * c) => float o;

//f is our glissando frequency
c => float f;

//g is the gain factor (volume).
f / c => float g;

//gain is from 0..1, gSpace is how much we'll use to vary the gain.
0.8 => float gSpace => float gSpace1 => float gSpace2;

//the amount of gain that define our extremes.
(1-gSpace)/2 => float gMargin;

while (true) {

  //increment the frequency (glissando)
  f * 1.01 => f;

  //if frequency reaches the octave, reset to intial C
  if (f >= o) {
  <<<"reset" >>>;
    c => f;
  }

  //calculate gain factor. g now varies from 0 to gSpace
  ((f / c) - 1) * gSpace => g;

  //gain for the low sinus wave. Gets louder as frequency increases
  gMargin + g => gSpace1;
  gSpace1 => g1.gain;

  //gain for the hi sinus wave. Gets quieter as frequency increases
  gMargin + gSpace - g => gSpace2;
  gSpace2 => g2.gain;

  //change frequency of low sinus
  f => s1.sfreq;

  //hi sinus is one octave above low sinus
  f*2 => s2.sfreq;

  //debug info
  <<<"1: ", f, " - ", gSpace1, "; 2: ", 2*f, " - ", gSpace2 >>>;

  //make sound
  0.1::second => now;
}
Comment: @WheatWilliams sorry - I should've added a reference. It's a programming language for sound synthesis. Added link in question.
Comment: Have you tried asking this on StackOverflow? There's a `chuck` tag there with 20 followers, perhaps you'll have more luck!
Comment: This is just a guess since I don't know anything about chuck, but it could be that the "click" you are hearing is actually an artifact of the physical speakers being unable to keep up with sudden changes. Is there a way you can incorporate some kind of really short crossfade when the frequency is supposed to reset?
Comment: I think I fixed it. Double check it and make sure none of the '<' or '>' are missing. For future reference: http://meta.music.stackexchange.com/questions/240/guitar-tab-plugin-jtab-should-be-active-only-in-questions-tagged-guitar
Comment: @Dom, thanks! I just hit the pre button on the toolbar, I wasn't aware of this syntax. Thanks for the link :)
Comment: What is a chuck?
Comment: Have you tried this with gSpace=1?
Answer: The issue with the click is at the beginning of a cycle your speakers are making a large amplitude jump. The easiest way to alleviate this sort of issue is to write some sort of central mixing code that keeps track of the volume of the whole system. You will also want to write your keep in such a way that volume never jumps values, but always makes a smooth assent. Most like


Android studio File writing is not working

Question: I have a small problem. I'm trying to write file and then read it, but it is not working. This is the code
 public void SaveData(String data){
    try {
        FileOutputStream fieloutputsteam = openFileOutput("basketball.txt",MODE_PRIVATE);
        fieloutputsteam.write(data.getBytes());
        fieloutputsteam.close();
        Log.d("debug1","Save completed");
        Log.d("debug1","Data: "+ data+"");
    }
    catch(Exception e)
    {
        Log.d("debug1","Error on saving");
    }
}
public void ReadFile() {
    String data2 = null;
    try {
        FileInputStream fileinputsteam = openFileInput("basketball.txt");
        InputStreamReader isr = new InputStreamReader(fileinputsteam);
        BufferedReader br = new BufferedReader(isr);
        StringBuffer sb = new StringBuffer();
        while ((data2 = br.readLine()) != null) {
            sb.append(data2 + "\n");
        }
        Log.d("debug1","Reading complete");
        Log.d("debug1","data: "+data2+"");

    } catch (Exception e) {
        Log.d("debug1","Error on read");
    }
}

Log output is:
03-25 10:11:53.814 12149-12149/com.example.remix3030303.myapplication D/debug1: Save completed
03-25 10:11:53.814 12149-12149/com.example.remix3030303.myapplication D/debug1: Data: 1,1,0,0,0,0
03-25 10:11:53.819 12149-12149/com.example.remix3030303.myapplication D/debug1: Reading complete
03-25 10:11:53.820 12149-12149/com.example.remix3030303.myapplication D/debug1: data: null

I dont know why data after reading is null.
I'm on Android Studio 3.0.1
I also added this to my manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_USER_DICTIONARY"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Answer: Notice the loop condition:
while ((data2 = br.readLine()) != null) {
     sb.append(data2 + "\n");
}

When it stops, data2 must be null, you should log StringBuffer sb instead :
 Log.d("debug1","data: "+ sb.toString());

Comment: How i didn't saw it :D Thanks.


How remove equal rows having n columns in Linux

Question: I have a file (df.txt) with 3045 rows and 900.000 columns, but 145 repeated rows, thus:
 1234  1111122233330000000000003333311122222............................
    1235678 00000000000000000000000111111122222............................
    4567  1122222222222222222222223333333333333............................
    3456  111111111111111122222222222222222222............................
    1234 1111122233330000000000003333311122222............................
    1235678 00000000000000000000000111111122222............................
    3423 33333333300000000011111112222222222222............................
    2211 11111111111111111111111111111111111111............................

Thus, the new file (dffinal.txt)should not have repeating information in column 1, as:
 1234  1111122233330000000000003333311122222............................
    1235678 00000000000000000000000111111122222............................
    4567  1122222222222222222222223333333333333............................
    3456  111111111111111122222222222222222222............................
    3423 33333333300000000011111112222222222222............................
    2211 11111111111111111111111111111111111111............................

I try with
cat df.txt | sort |uniq > dffinal.txt

but it keeps the same number of rows
Comment: `uniq` compares the whole line, not just the first column. Try using `sort -u` and specifying the first column as the key.
Comment: Is the order of lines important?
Comment: Do you need to maintain the different indentations?
Comment: @choroba, No absolutely no
Comment: @Barmar, No absolutely no
Comment: Is that `900` or `900000` columns? (presume the `'.'` separator is just a LOCALE difference from `','`)?
Answer: You can use awk to check for duplicates in column 1.
awk '!a[$1] { a[$1]++; print }' df.txt > dffinal.txt

This remembers the first column in the a array. If the column isn't already in there, it saves it and prints the line. So it prints the first instance of any repeated key.


Save variable to RAM for other script use?

Question: Is there anyway i can save the value of <code>$x</code> into the RAM or any other place
(rather than HDD , database , cookie , session)
so it can be re-used after a while
(read again from another script/read again from the same script/modified) ?
Comment: What's wrong with writing it to disk or a database?
Comment: database is overused by simple function of increasing the views for a post by one for example , you can save the views count of a post into the memory , then save them to the database every 10 minutes for example if you're gettng like 100000 views/hour ! . saving resources is a must in large websites ;)
Comment: If you so desperately need to save your resources to this extent, you should already be using APC or memcache, together with database query caching, etc
Answer: What is RAM?
random-access memory
The closer you can use is memcache
Comment: or APC, or shmem (if you're feeling adventurous)
Comment: is true ... memcache is work better in distributed environment or multiple servers


Virtually $\mathbb{Z}$ implies $\mathbb{Z}$ is central

Question: Let $G$ be a (EDIT: torsion-free) virtually $\mathbb{Z}$-group, i.e., there is a subgroup $H \leq G$ of finite index isomorphic to $\mathbb{Z}$. WLOG, we can suppose $H$ is normal in $G$ - otherwise exchange $H$ with the kernel of the action of $G$ on the permutation set $S(G/H)$ - which must also be isomorphic to $\mathbb{Z}$ as it is contained in $H$.

Is $H$ is central in $G$?

I guess so. Because $|\text{Aut}(H)| = 2$ and the kernel of the conjugation map $G \to \text{Aut}(H)$ is the centralizer $Z_G(H)$, it means that the centralizer has index 1 or 2 in $G$. If it's $1$, then it is done - I'm failing to show why it must be so, unfortunately.
PS: I'm trying to prove that if $G$ is torsion-free, then $G \simeq \mathbb{Z}$. If I manage to prove that $H$ is central, then the transfer map $G \mapsto H$ is essentially multiplication by $[G\colon H]$, from which follows it must be injective and then we have it: any subgroup of $\mathbb{Z}$ is isomorphic to $\mathbb{Z}$.

I found an unsatisfactory way around using group cohomology (I believe that there is an elementary way of doing this though, so I'm leaving the question open). We can suppose, WLOG, that $[G\colon H] = 2$, simply by exchanging $H$ with $Z_G(H)$ and applying the proof for central subgroups. Then, we have an exact sequence:
$$\{1\} \to \mathbb{Z} \to G \to \mathbb{Z}/2\mathbb{Z} \to \{1\}$$
If $G/H$ acts trivially on $H$, we have that $Z_G(H) = G$ and we're done. Otherwise, $G/H$ must act by inverting the elements in $H$, and in particular $H^{G/H} = \{1\}$: there are no non-trivial fixed points. Such extensions $G$ are parametrized by $H^2(\mathbb{Z}/2\mathbb{Z}, \mathbb{Z})$, and by the free periodic resolution over $\mathbb{Z}/2\mathbb{Z}$, we have:
$$H^2(\mathbb{Z}/2\mathbb{Z}, \mathbb{Z}) \simeq \mathbb{Z}^{\mathbb{Z}/2\mathbb{Z}}/N\mathbb{Z} = \{1\}$$
where $N$ is the norm element. Thus, the only such extension is $\mathbb{Z} \rtimes \mathbb{Z}/2\mathbb{Z}$. This contradicts the hypothesis that $G$ is torsion-free.
Comment: Perhaps I'm missing something, but wouldn't $G=\mathbb{Z}\rtimes\mathbb{Z}_2$ with nontrivial action of $\mathbb{Z}_2$ on $\mathbb{Z}$ give a counterexample?
Comment: Suppose you've already reduced to the case when $|G:H|=2$. Here is how to finish in an elementary way. Take $g\in G\setminus H$. Now, as you noted, either $g$ centralises $H$, and you are done, or it inverts every element in $H$. Assume the latter. Note that $g^2$ is in $H$ and centralised by $g$ so we must have $g^2=1$, and thus $G=H\rtimes \langle g\rangle$.
Comment: More generally, if $H$ is normal but not centralised by $G$ with $|G:H|=n<\infty$, take $g\in G\setminus Z_G(H)$, then $g^n$ is in $H$ and centralised by $g$, so $g^n=1$, and you have torsion.
Comment: Actually, if $G$ is a virtually $\mathbf{Z}$ group, it has a (unique) maximal finite normal subgroup $F$ and $G/F$ is isomorphic to either $\mathbf{Z}$ or the infinite dihedral group $D_\infty$.
Comment: @user281392 yes it is. I guess I need the extra assumption of $G$ being torsion-free then.
Comment: @verret thanks! That's exactly the type of argument I was looking for. Would you make it an answer, so I can mark it as solved?
Answer: By replacing $H$ with its core in $G$, we may assume that $H$ is normal in $G$ with $|G:H|=n< \infty$. Suppose there exists an element $g$  of $G$ that does not centralise $H$. Now, $g$ must act on $H$ by inversion, as this is the only non-identity automorphism of $\mathbb{Z}$. Note that $g^n$ is in $H$ so it is inverted by $g$. Since it is also centralised by $g$ and since the identity is the only involution in $H$, we have $g^n=1$. Note that $g\neq 1$, hence $G$ has torsion.


Setting a target or multiplefile for a grunt task with sass and autoprefixer?

Question: I'm setting a grunt file for a task. My goal is to create a css file from a sass file (scss) and add an autoprefix to all the proprieties which require so. Initially I used the propriety multifiles but it didn't work, so now I'm using the target propriety that works fine, but my problem is, even if I target the very same file, it will create another file in my folder where I put all my sass files.
So far my file is the following:
module.exports = function (grunt) {

    grunt.initConfig({

        pkg: grunt.file.readJSON('package.json'),

        sass: {
            dev: {
                options: {
                    style: 'expanded',
                    sourcemap: 'none',
                },
                files: {
                    '../style.css': 'scss/style.scss'
                }
            },
            dist: {
                options: {
                    style: 'compressed',
                    sourcemap: 'none',
                },
                files: {
                    '../style-min.css': 'scss/style.scss'
                }
            }
        },
        autoprefixer: {
            options: {
                browsers: ['last 6 versions']
            },
            target: {
                expand: true,
                flatten: true,
                src: '../style.css',
                dest: ''
            }
        },
        watch: {
            css: {
                files: '**/*.scss',
                tasks: ['sass', 'autoprefixer']
            }
        },
    });

    grunt.loadNpmTasks('grunt-contrib-sass');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-autoprefixer');
    grunt.registerTask('default', ['watch']);
}

My goal is to set up a global task for all my css files, like so:
target: {
    expand: true,
    flatten: true,
    src: '*.css',
    dest: ''
}

but it is not working even if I try something like:
target: {
        expand: true,
        flatten: true,
        src: '../*.css',
        dest: ''
    }

Does anyone know why?
Answer: Use cwd (stands for current working directory) which is the path where grunt looks for the files matching the pattern in src. Also define the dest so that it would create the destination file in the same folder.
target: {
    expand: true,
    flatten: true,
    cwd: '../',
    src: [ '**/*.css' ],
    dest: '../'
}

Comment: See this https://gruntjs.com/configuring-tasks. Everything has been clearly explained here.
Comment: It works! Do you know where I can find this kind of documentation? The version that I found is totally different and it uses the pipe function


Which properties determine the uniqueness of the local Artin map?

Question: Any abelian extension of local fields can be realized as the completion of a global abelian extension.  So let $L/K$ be abelian, $w/v$ an extension of places.  From the global Artin map on ideles we can define the local Artin map as the composition $$K_v^{\ast} \rightarrow \mathbb{I}_K \rightarrow \text{Gal}(L/K)$$ as well as show this composition maps onto the decomposition group $\text{Gal}(L/K)_v = \text{Gal}(L_w/K_v)$ with kernel $N_{w/v}(K_w^{\ast})$.  But the definition of the local Artin map depends on (somewhat arbitrary) global parameters.  What is it about the local Artin map that ensures its uniqueness (so that it doesn't depend on the choice of $L/K$ inducing it)?
Answer: This is the local reciprocity law. It says for any non-archimedian local field $K$, there exists a unique group homomorphism $\phi_K : K^\times \rightarrow \mathrm{Gal}(K^{ab}/K)$ with the property that:
i) If $\pi$ is a uniformizer for $K$, and $L/K$ is a finite unramified extension, then $\phi_K(\pi)|_L$ acts as the Frobenius on $L$.
ii) If $L/K$ is a finite abelian extension, then $\mathrm{Nm}_{L/K}(L^\times)$ is in the kernel of $\phi_K|_L$, and there's an induced isomorphism
$$ \overline{\phi}_K|_L : K^\times/\mathrm{Nm}_{L/K}(L^\times)\rightarrow \mathrm{Gal}(L/K).$$
See for example Milne's notes on class field theory.
One remark is that historically the global theorem was proved first analytically, and the local theorem was deduced from it. The idèlic notation you are using was introduced by Chevalley to give a local algebraic proof and to reverse the order of implications.
Comment: @Alex this may be overkill, but it follows from the Chebotarev's density theorem.
Comment: The proof that this map is onto in Milne's notes seems incomplete.  It claims (without justification) that if every prime of $K$ unramified in $L$ splits completely, then $K=L$.  Is there a reason that's true?


Where is the result of fetch backbone?

Question: I've fetched a collection in backbone by a apirest on parse.com but in the console.log i can read this result:
child {collection: child, attributes: Object, _escapedAttributes: Object, cid:   "c2",              changed: Object…}.
So where is the result??In my collection there are user with name,username ecc..
            var HomeView = Backbone.View.extend({

template: Handlebars.compile(template),

 events: {

  },

  initialize: function() {

      console.log("inhomeview");

      var amici = new Usercollection();
    amici.fetch({
  success: function(collection) {
   amici.each(function(object) {
  console.warn(object);
  console.log(object);
  });
  },
   error: function(amici, error) {
  // The collection could not be retrieved.
   }
   });

Collection:
     var Usercollection = Backbone.Collection.extend({

     model:Person,
     url:'https://api.parse.com/1/classes/User',

Model:
       var Person = Backbone.Model.extend({

  defaults:{

      },

  initialize:function(){
          console.log("inperson");

      },

  validate:function(){
          console.log("validate");
      },

      send:function(){
           var user = new Parse.User();
           user.set("username", this.get("username"));
           user.set("password", this.get("password"));
           user.set("email", this.get("email"));

          // other fields can be set just like with Parse.Object
           //user.set("phone", "415-392-0202");

           user.signUp(null, {
           success: function(user) {
      // Hooray! Let them use the app now.
            },
           error: function(user, error) {
     // Show the error message somewhere and let the user try again.
           alert("Error: " + error.code + " " + error.message);
           }
         });

      }

         });

          return Person;
          });

Comment: Try `console.log(object.toJSON())`
Answer: amici.models contains the objects you are pulling
each model is a Person
initialize: function() {
  var amici = new Usercollection();
  amici.fetch({
    success: function(collection) {
      amici.models.each(function(person) {
        console.log(person);
        console.log(person.attributes);
      });
    },
    error: function(amici, error) {
    }
  });
}

Answer: The objects you are printing to the console are instances of the Person model. That is what happens when you ask a collection to fetch data. It fetches data from the server, converts that data into model instances, and stores a list of those model instances as the collection contents. Perhaps you can further clarify your question.
Comment: Don't use JSON.stringify. That is only needed when sending requests over the wire and backbone does that for you automatically. When you have a backbone collection and you want to convert it to plain data  objects (not a JSON string!) for rendering (not parsing) via handlebars, use `myCollection.toJSON()`, which will return an array of plain objects, which you can render via handlebars.
Comment: I need to parse the result of collection with hanldebars.Now i've used Jsonstringify(object) and it returns a json array.It's right?
Comment: Now there is another problem,if i fetch by this url:https://api.parse.com/1/users return nothing,if i try to json stringify it make an empty array.Why?On parse.com user exists and contain some fields.

Where is the result of fetch backbone?


How do I use unicode_escape correctly?

Question: I need to add an additional \ to escape some characters. For instance, BC \ BS needs to become BC \\ BS. The following line solves the issue:
txt.encode('unicode_escape').replace("'", "\\'")

However, it messes up other characters. For example, ^@? becomes \x00?. in such a situation, I will need to remove \x00 as a subsequent step but other characters might show up.
What is the most Pythonic way to add the escape character to set of characters such as \,\t,\n etc. without causing other characters to break? I have tried using translate but ran into issues as the character size of \\t is unequal to \t.
Comment: Is this source text that is going to go to a language parser ?
Comment: Are you planning to use this in a regular expression? If so the `escape` function in the `re` module may do what you need.
Comment: Find: `(?<!\\)((?:\\\\)*)([tnrb]|\\(?!\\))` replace `$1\\$2` Because, it could already be escaped. It's imperative to know the difference.
Comment: @TripleD `re.escape` doesn't do it. It escapes a bunch of chars but the output can't be read by the reader I'm using. A number of  `\`s cause issue.
Answer: Are you attempting to escape certain characters in text strings, raw text strings, or byte strings? What is the full set of characters you need to escape? If it's text, then there is no need to encode it first...Some things you can try:
test = "Please escape this: ' and this \n"
for char in ["'","\n"]:
     test = test.replace(char, f"\{char}")

complicated_test = "This \tstring \n is \ full of ' things to \t escape"
re.escape(complicated_test)

How do I use unicode_escape correctly?


Tirar printscreen no Android pela API

Question: Tenho um app e uma das funções seria tirar printscreen da tela.
Como fazer isso?
Answer: Achei este código nessa resposta no SO:
<code>//nome e local onde será gravado
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + ACCUWX.IMAGE_APPEND;

//cria a imagem
Bitmap bitmap;
View v1 = mCurrentUrlMask.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);

OutputStream fout = null;
imageFile = new File(mPath);

try {
    fout = new FileOutputStream(imageFile);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
    fout.flush();
    fout.close();

} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
</code>
Alternativa usando canvas conforme outra resposta no SO:
<code>public Bitmap screenShot(View view) {
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);
    return bitmap;
}
</code>
Coloquei no GitHub para referência futura.
Comment: Sim, ele pode fazer com o resultado o que ele quiser, não necessariamente gravar no SD.
Comment: No caso esse código tira um print e salva no SD Card, acho que só a parte do `bitmap` é suficiente. (:
Comment: testei e vi o link que você enviou. Retirei o ACCUWX.IMAGE_APPEND, não faço ideia o que é isso mas substitui pelo nome+extensão da img (é uma boa por o nome do arquivo como data-hora para não substituir caso tire mais de uma screenshot!!). Tb tive que substituir mCurrentUrlMask.getRootView(); por getWindow().getDecorView().getRootView(); Pois não estava tirando print e nem mostrando erro. Só que tem um porem, ele tira print somente da activity, não tira da tela do Android por completo
Comment: @FelipeAvelar como faz para deixar uma palavra do comment marcada, tal como vc fez com bitmap?
Comment: @felipe.rce verei se acho mais alguma coisa, para destacar qualquer texto nos posts você usa ele entre crases ` `
Comment: @bigown, consegui tirar printscreen da tela inteira, seguindo o link que você me enviou, só que precisa de root... Então creio que não tem como sem root
Answer: Somente para complementar a resposta do Maniero.
Tem uma solução para tirar print screen da tela do Android, você pode usar isso em um service, mas necessita de root:
<code>    try {
         Process sh = Runtime.getRuntime().exec("su", null,null);
         OutputStream os = sh.getOutputStream();
         os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
         os.flush();
         os.close();
         sh.waitFor();
   } catch (IOException e) {
         e.printStackTrace();
   } catch (InterruptedException e) {
         e.printStackTrace();
   }
</code>
Comment: Quando você colocou o comentário, eu ia trazer pra cá esta que era o que eu achei que você tinha utilizado.

Tirar printscreen no Android pela API


Deriving the expression for the posterior predictive distribution.

Question: We have $Y \mid \Theta=\theta \sim \operatorname{Po}(\theta)$ and $\Theta \sim \operatorname{Gamma}\left(\alpha_0, \lambda_0\right)$, the expression for the posterior predictive distribution is acquired by the following,
$\begin{aligned} f_{Y \mid \boldsymbol{X}}(y \mid \boldsymbol{x}) & =\int_0^{+\infty} f_{Y \mid \Theta}(y \mid \theta) f_{\Theta \mid \boldsymbol{X}}(\theta \mid \boldsymbol{x}) d \theta \\ & =\int_0^{+\infty} \frac{\theta^y}{y !} e^{-\theta} \cdot \frac{\lambda_n^{\alpha_n}}{\Gamma\left(\alpha_n\right)} \theta^{\alpha_n-1} e^{-\lambda_n \theta} d \theta \\ & =\frac{\lambda_n^{\alpha_n}}{\Gamma\left(\alpha_n\right)} \frac{1}{y !} \int_0^{+\infty} \theta^{\alpha_n+y-1} e^{-\left(\lambda_n+1\right) \theta} d \theta \\ & \propto \frac{1}{y !} \int_0^{+\infty} \theta^{\alpha_n+y-1} e^{-\left(\lambda_n+1\right) \theta} d \theta \\ & =\frac{1}{y !} \frac{\Gamma\left(\alpha_n+y\right)}{\left(\lambda_n+1\right)^{\alpha_n+y}} \\ & \propto \frac{\Gamma\left(\alpha_n+y\right)}{y !}\left(\lambda_n+1\right)^y\end{aligned}$
$\begin{aligned} f_{Y \mid \boldsymbol{X}}(y \mid \boldsymbol{x}) & \propto \frac{\left(\alpha_n+y-1\right) !}{y !}\left(\frac{1}{\lambda_n+1}\right)^{\alpha_n+y} \\ & \propto \frac{\left(\alpha_n+y-1\right) !}{\left(\alpha_n-1\right) ! y !}\left(\frac{\lambda_n}{\lambda_n+1}\right)^{\alpha_n}\left(\frac{1}{\lambda_n+1}\right)^y .\end{aligned}$
I understand the first couple of steps where we use the fact that the posterior distribution ($\Theta \sim \operatorname{Gamma}\left(\alpha_0, \lambda_0\right)$) integrates to $1$ and we just have to determine the integral up to a constant. The confusing step is where $\frac{1}{y !} \frac{\Gamma\left(\alpha_n+y\right)}{\left(\lambda_n+1\right)^{\alpha_n+y}}$ becomes $\frac{\left(\alpha_n+y-1\right) !}{\left(\alpha_n-1\right) ! y !}\left(\frac{\lambda_n}{\lambda_n+1}\right)^{\alpha_n}\left(\frac{1}{\lambda_n+1}\right)^y$. Isn't sufficient to have $\frac{1}{y !} \frac{\Gamma\left(\alpha_n+y\right)}{\left(\lambda_n+1\right)^{\alpha_n+y}}$, why is the latter preferred over the other?
Comment: At first you write $\Theta\sim\mathrm{Gamma}(\alpha_0,\lambda_0)$ but in the computations there is $\alpha_n$, $\lambda_n$, which is confusing.
Answer: The computation can be done directly:
\begin{align}
\int_0^\infty \frac{\theta^y}{y!}e^{-\theta} \frac{\lambda^\alpha}{\Gamma(\alpha)}\theta^{\alpha-1}e^{-\lambda\theta}\ \mathsf d\theta &= \frac{\lambda^\alpha}{\Gamma(\alpha)y!}\int_0^\infty \theta^{\alpha+y-1}e^{-\lambda\theta}\ \mathsf d\theta\\
&= \frac{\lambda^\alpha \Gamma(y+\alpha)}{(1+\lambda)^{y+\alpha}\Gamma(\alpha)y!}\\
&= \frac{\Gamma(y+\alpha)}{y!\Gamma(\alpha)}\left(\frac{\lambda}{1+\lambda}\right)^\alpha\left(\frac{1}{1+\lambda}\right)^y,
\end{align}
and hence the posterior predictive distribution is negative binomial with parameters $r=\alpha$ and $p=\frac\lambda{1-\lambda}$.
Comment: Thanks for the answer, the approach seem to be  to evaluate the integral and use the fact that  PDF's/PMF  integrate/sum to one and use the terms left to identify what distribution they look like.
Comment: @adam Indeed, sometimes it may be easier to evaluate up to a proportional constant. Here that seemed to make matters more confusing.


Behaviour of the spectrum of a compact operator w.r.t. perturbations.

Question: Suppose $A$ and $B$ are linear compact operators on a Hilbert space with $\sigma(A)$ and $\sigma(B)$ as their spectrum.
Is it possible to obtain some continuity result of $\sigma(A+\epsilon B)$ as $\epsilon\downarrow 0$ towards $\sigma(A)$? Is the limiting behavior of the form "$\sigma(A)+\epsilon \sigma(B)$''?
Thanks in advance!
Answer: A partial answer. I think it is true if $\sigma(A)=\{0\}$. For $\lambda\neq 0$, $A-\lambda I$ is invertible. However, the set of isomorphisms is open in $\mathcal{B}(H)$, so there exist $\varepsilon>0$ such that $A-\lambda I+\varepsilon B$ is also invertible. This means that $\lambda\notin\sigma(A+\varepsilon B)$, for $\varepsilon$ small enough. This should imply that $\sigma(A+\varepsilon B)\to 0$.
Answer: The first question has an answer and is "yes", see Dunford-Schwartz, Linear operators, part II, XI-9, Lemma 5; it reads:
"Let $A_n, A$ be compact operators and $A_n\rightarrow A$ in the uniform operator topology. Let $\lambda_m(A)$ be an enumeration of the non-zero eigenvalues of $A$, each repeated according to its multiplicity. Then, there exist enumerations $\lambda_m(A_n)$ of the non-zero eigenvalues of $A_n$, with repetitions according to multiplicity, such that $$\lim_{n\rightarrow\infty} \lambda_m(A_n)=\lambda_m(A), \quad m\geq 1,$$ the limit being uniform in $m$."
So, under compact perturbations $\epsilon B$ of a compact operator $A$, the perturbed spectrum moves continuously. I don't know about your second question, the order of convergence might be a little bit tricky to obtain, some Rellich result might be useful. Consider checking Kato's book "Perturbation Theory for Linear Operators".


child recyclerview not scrolling when i put horizontal recyclerview inside another horizontal recyclerview

Question: I have a nested recyclerview and both have a horizontal linear layout but the child one is not scrolling
All consequences
1) I'm using a snap helper in the parent recyclerview
2) also using recycler view pool in child recyclerview
Answer: It is bad practice to use a Nested RecyclerView with the same LayoutManager.
If horizontal scrolling is important to use for you then try RecyclerView inside ViewPager.
This will behave like this:
When scrolling RecyclerView, Fragment will stick to port until RecyclerView last item is shown. After that the next fragment switchs.


Drupal Commerce Free Shipping For Some Products

Question: Drupal 7, Commerce
The Setup: A store with two products. They are a shippable item and a gift certificate.
The shippable item has a number of shipping options available.
Gift certificates have free shipping, and always go via first class mail.
I added a 'free shipping' shipping method. Unfortunately this always shows up in all checkouts, so someone could order a hundred shippable items and then select free shipping.
When I 'configure component' for the free shipping method, it lets me define a rule as to how this method is applied.
In this rule, I need to make a loop that goes through all line items, and if there are only products marked with a field called 'field_free_shipping', then show this method.
However.... Rules sucks. :-) I can make a loop, but then I can't ask it about the product node or the field.
What am I doing wrong? Any assistance appreciated.
I'll be adding a bounty to this question when it becomes eligible.
Answer: In such a simple scenario, where you only have two products, I would just use the condition Order contains a particular product to look for the shippable product to enable the paid shipping service. I'd then use the same condition negated to enable the free shipping service.
Comment: Came back to answer my own question to see an authoritative answer. We have like 5 shipping methods (intl, expedited, etc), so I had to conditionalize all of them against the free shipping product. A bit of tedium, and will have to change in 5 places with each new product. Commerce could do this better but I don't know how. Thanks.
Comment: Ahh, if you have more shipping methods, then you can either manage them all individually like you have or else use a Rules component to define the condition set and just call the component from your various other Rules. That would let you maintain updates to the logic in a single place if, for example, you needed to add another free shipping product to the site.
Comment: not understanding a module doesn't mean it sucks. Yes, it's opaque, but once you wrap your hear around it (like drupal itself, there are almost no limits)
Comment: Of course, for a very limited number of products, you could just filter by the *particular product*. But how would you do this, when there are plenty of products, only some of which are shipped for free?


Forming a Commitee of Senators

Question: From Blitzstein & Hwang "Introduction to Probability":

The US senate consists of 100 senators, with 2 from each of the 50 states. There are $d$ Democrats in the Senate. A committee of size $c$ is formed, by picking a random set of senators such that all sets of size $c$ are equally likely. Find the expected number of Democrats on the committee.

Attempts at solving:
i) Assumed that there were ${100}\choose{c}$ total combinations and then tried $X\sim Binom(100,\cfrac{d}{100})$, where $X$ is the number of Democrats in the commitee however then realised that if we have two independent variables ($c$ and $d$), then there will be some cases that will be nonsensical; if we fix $c=10$ and $d=5$, then we cannot fill up the committee with Democrats so we will have overcounted.
ii) Attempted the problem in a similar fashion to (i), however tried fitting $X$ to: $X \sim HGeom(d,100-d,100)$ however ended up at the same issue of overcounting as a result of two independent variables again.

After this I concluded that $X$ would not be distributed as a named distribution but I am not having any luck in dealing with the issue of two independent variables (some pointers would be much appreciated).
Answer: The fraction of democrats in the senate is $\frac{d}{100}$. The expectation for a random committee of size $c$ would be the same fraction.  So the expected number of democrats on the committee would be $\frac{d}{100}\cdot c=\frac{cd}{100}$.
This problem can also be approached by choosing senators sequentially for the committee.  Let $X_i$ be $1$ if the $i$-th senator is a democrat, and $0$ if not.  The number of democrats is $X_1 +\cdots +X_c$.  Then the expected number of democrats is $E[X_1+\cdots+X_c]=E[X_1]+\cdots+E[X_c]$ (by linearity of expectation, which does not require independence).  Each $E[X_i]$ is $\frac{d}{100}$, from which the same result follows.
Comment: Same method does not work variance of hypergeometric because sampling without replacement causes $X_i$'s to be correlated. Method works for both mean and variance of binomial because of indep trials.
Answer: [The binomial distribution has the effect of sampling with replacement, so you don't want that part.]
The number of equally likely ways in which to choose a committee of size $c$
is ${100 \choose c}$ as you say.
The number of ways to choose such a committee with $D$ Democrats and
$c - D\,$ non-Democrats is ${d \choose D}{100 - d \choose c-D}.$ In order
to make sense of this, we must have $c \ge D.$
This means that the random variable $D$ that counts the Democrats on
a randomly selected committee of size $c$ is hypergeometric. The hypergeometric
mean is $E(D) = c(d/100).$
Notice that it is necessary to distinguish between the number $d$ of
Democrats in the senate, and the random number $D$ of Democrats on the
committee.
Given the text you are using (thanks for telling us), you will probably
be used to the idea of verifying analytic results via simulation.
Here are a million simulated committees of size $c=14$ in a (hypothetical) Senate with 42 Democrats.
<code> m = 10^6 # iterations
 D = numeric(m)
 c = 14   # committee members
 d = 42   # Democrats in Senate
 sen = c(rep(1,d), rep(0, 100-d)) # 1 = Dem, 0 = non-Dem
 for(i in 1:m) {
   com = sample(sen, c)  # randomly select committee
   D[i] = sum(com) }
 mean(D)  # aprx E(D)
 ## 5.880656
 c*(d/100) # exact E(D)
 ## 5.88
 sd(D)    # aprx SD(D)
 ## 1.720396
 2*sd(D)/sqrt(m)
 ## 0.003440792
</code>
With a million iterations $m$, the simulation
estimates $E(D) \approx 5.881 \pm 0.003,$ compared with the exact
result $E(D) = 5.88.$  According to the Central Limit Theorem, the 95% margin
of simulation error is $1.96\,SD(D)/\sqrt{m}.$ Your text should have
a formula for $Var(D)$ of a hypergeometric random variable $D,$ so you can check the accuracy of the simulated standard
deviation for yourself.
Below is a histogram of the simulated distribution of $D$, where red dots
atop histogram bars show exact hypergeometric probabilities. The vertical
resolution of the graph is about 0.002, so the fit looks almost perfect.
<code> hist(D, prob=T, br=(0:15)-.5, col="skyblue")
   i = 0:15;  pdf = dhyper(i, d, 100-d, c)
   points(i, pdf, pch=19, col="red")
</code>

Forming a Commitee of Senators


Prove alternating sum of binomial coefficients squared by induction

Question: I am trying to find the sum
$${100\choose 0}^2-{100\choose 1}^2+{100\choose 2}^2- \dots+ {100\choose 100}^2$$
After the first few examples for small numbers this appears to be
$$\sum_{k=0}^{n}{(-1)^k {n\choose k}^2}=(-1)^\frac{n}{2}{n\choose \frac{n}{2}}$$
for all even $n$s. (For odd $n$ this is obviously $0$ because of the symmetry ${n\choose k}={n\choose{n-k}}$).
I tried to prove it by induction, but it is too messy and I am not sure that's the right direction. What I did is write it in terms of $m=\frac{n}{2}$ so then the induction step will be just $+1$, although that didn't help very much.
Thanks in advance for any help.
Answer: Consider two binomial series $(1+x)^{n}$ and $(1-x)^{n}$. Note that the terms in the sum are the product of the coefficients of the terms in these expansions.
$$\begin{aligned}\sum_{k=0}^{n}(-1)^{k}\left[{n\choose k}\right]^{2}&=\text{constant term in }(1+x)^{n}\left(1-\frac{1}{x}\right)^{n}\\&=\text{coeff. of } x^{n} \text{ in }(x^2-1)^{n}=(-1)^{\frac{n}{2}}{n\choose \frac{n}{2}}\ \square\end{aligned}$$
Comment: Do you mean $(1+x)^n (1-x)^n$?
Comment: @aradarbel10 No. $(1+x)^n\left(1-\frac{1}{x}\right)^n$ has to be taken to get the series sum as the constant term in the expression.


How to get information about process in C#?

Question: How to get information about process (cpu, memory, disk & network usage) in C# application?
P.S. System.Diagnostics.Process and System.Diagnostics.PerformanceCounter doesn't provide information about disk and network usage. I don't use it.
Comment: Can you be more specific about "disk & network usage." Do you want the equivalent of "I/O Read Bytes" and "I/O Bytes Other" shown in task manager or something more?
Comment: Disk usage is a percentage that application using of the maximum possible activity of disk. Network usage is a percentage that application using of the maximum possible network speed.
Answer: System.Text.StringBuilder sb = new System.Text.StringBuilder();

var currentProcess = System.Diagnostics.Process.GetCurrentProcess();
sb.AppendLine("Process information");
sb.AppendLine("-------------------");
sb.AppendLine("CPU time");
sb.AppendLine(string.Format("\tTotal       {0}",
    currentProcess.TotalProcessorTime));
sb.AppendLine(string.Format("\tUser        {0}",
    currentProcess.UserProcessorTime));
sb.AppendLine(string.Format("\tPrivileged  {0}",
    currentProcess.PrivilegedProcessorTime));
sb.AppendLine("Memory usage");
sb.AppendLine(string.Format("\tCurrent     {0:N0} B", currentProcess.WorkingSet64));
sb.AppendLine(string.Format("\tPeak        {0:N0} B", currentProcess.PeakWorkingSet64));
sb.AppendLine(string.Format("Active threads      {0:N0}", currentProcess.Threads.Count));

etc.
Answer: As a starter this get a  list of all processes and loop over it:
    using System.Diagnostics;

    //...

    Process[] all = Process.GetProcesses();
    foreach (Process thisProc in all) {
      string Name = thisProc.ProcessName;
      //...
    }

Answer: Add this line to your using list:
using System.Diagnostics;

Now you can get a list of the processes with the Process.GetProcesses() method, as seen in this example:
Process[] processlist = Process.GetProcesses();

foreach(Process theprocess in processlist)
{
    Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id);
}

Comment: I know about it. But System.Diagnostic.Process doesn't provide information about disk network usage
Answer: In System.Diagnostics there is a class called Process which allows you to statically get Processess by name, ID,etc.  So you can do something like
Process p = Process.GetCurrentProcess();
int pageMemSize = p.PagedMemorySize;

There are a lot of different properties of the class. Look at the Process class here


Convergence/divergence of the operator norm for random sign matrices

Question: For each ${n}$, let ${A_n = (a_{ij,n})_{1 \leq i,j \leq n}}$ be a random ${n \times n}$ matrix (i.e. a random variable taking values in the space ${{\bf R}^{n \times n}}$ or ${{\bf C}^{n \times n}}$ of ${n \times n}$ matrices) such that the entries ${a_{ij,n}}$ of ${A_n}$ are jointly independent in ${i,j}$ and take values in ${\{-1,+1\}}$ with a probability of ${1/2}$ each. If ${\|A_n\|_{op}}$ denotes the operator norm of ${A_n}$, and ${\varepsilon > 0}$, show that ${\|A_n\|_{op} / n^{1/2+\varepsilon}}$ converges almost surely to zero, and that ${\|A_n\|_{op} / n^{1/2-\varepsilon}}$ diverges almost surely to infinity. (Hint: use the spectral theorem to relate ${\|A_n\|_{op}}$ with the quantities ${\hbox{tr} (A_n A_n^*)^k}$.)
Attempt: As $A_nA_n^*$ is symmetric, its' operator norm ${\|A_nA_n^*\|_{op}}$ is equal to the ${\ell^\infty}$ norm
$\displaystyle \|A_nA_n^*\|_{op} = \max_{1 \leq i \leq n} \lambda_i$
of the eigenvalues ${\lambda_1,\ldots,\lambda_n\in {\bf R}}$ of $A_nA_n^*$ (note the eigenvalues are non-negative here). On the other hand, we have the standard linear algebra identity
$\displaystyle \hbox{tr}(A_nA_n^*)^k = \sum_{i=1}^n \lambda_i^k$. In particular, for any natural number $k$, we get the inequalities
$\displaystyle \|A_n\|^{2k}_{op} = \| A_nA_n^* \|_{op}^k \leq \hbox{tr}(A_nA_n^*)^k \leq n \|A_nA_n^*\|_{op}^k = n\|A_n\|^{2k}_{op}$.
From this, we see that for any even $k$,
$\displaystyle {\|A_n\|_{op} / n^{1/2+\varepsilon}} \leq [\hbox{tr}(A_nA_n^*)^k]^{\frac{1}{2k}} / n^{1/2+\varepsilon}$
and $\displaystyle {\|A_n\|_{op} / n^{1/2-\varepsilon}} \geq [\hbox{tr}(A_nA_n^*)^k]^{\frac{1}{2k}} / n^{\frac{1}{2k} + \frac{1}{2} - \varepsilon}$.
I was unable to proceed using law of large numbers with these bounds, since the entries of $A_nA_n^*$ are not iid. Any direct or indirect help will be appreciated.
Answer: Edit: After some further consideration, I managed to obtain a solution which I paste below. Critiques, verifications, and suggestion for different methods are welcomed.
Fix some $\varepsilon, \varepsilon' > 0$. As $A_nA_n^*$ is symmetric, the operator norm ${\|A_nA_n^*\|_{op}}$ is equal to the ${\ell^\infty}$ norm $\displaystyle \|A_nA_n^*\|_{op} = \max_{1 \leq i \leq n} \lambda_i$ of the eigenvalues ${\lambda_1,\ldots,\lambda_n\in {\bf R}}$ of $A_nA_n^*$ (note that these values are non-negative). Also, we have the standard linear algebra identity $\displaystyle \hbox{tr}(A_nA_n^*)^k = \sum_{i=1}^n \lambda_i^k$. Consequently, for any natural number $k$, we have the inequalities
$\displaystyle \|A_n\|^{2k}_{op} = \| A_nA_n^* \|_{op}^k \leq \hbox{tr}(A_nA_n^*)^k \leq n \|A_nA_n^*\|_{op}^k = n\|A_n\|^{2k}_{op}$
It follows that for any natural number $k$,
$\displaystyle {\|A_n\|_{op} / n^{1/2+\varepsilon}} \leq [\hbox{tr}(A_nA_n^*)^k]^{\frac{1}{2k}} / n^{1/2+\varepsilon}$
and
$\displaystyle {\|A_n\|_{op} / n^{1/2-\varepsilon}} \geq [\hbox{tr}(A_nA_n^*)^k]^{\frac{1}{2k}} / n^{\frac{1}{2k} + \frac{1}{2} - \varepsilon}$.
Let $E_n$ be the event $[\hbox{tr}(A_nA_n^*)^k]^{\frac{1}{2k}} / n^{1/2+\varepsilon} > \varepsilon'$, which is equivalent to the event
$\displaystyle \hbox{tr}(A_nA_n^*)^k / n^{k(1+2\varepsilon)} > \varepsilon'$, where we re-scale $\varepsilon' := (\varepsilon')^{2k}$. It can be shown by induction that ${\bf E}\hbox{tr}(A_nA_n^*)^k = 2n^{k+1} - n^k$ for all $n$ and all $k \geq 2$. From this and the Markov inequality, we obtain the bound
$\displaystyle {\bf P}(E_n) \leq \frac{2n - 1}{\varepsilon' n^{2 \varepsilon k}}$.
Valid for any $k \geq 2$. Choose some sufficiently large $k$ (greater than $2$) depending on $\varepsilon$ such that the denominator $\displaystyle \varepsilon' n^{2 \varepsilon k} \geq O(n^3)$ (say), we see in particular that the ${\bf P}(E_n)$ are summable, and ${\bf P}(\bigvee_{n \geq N} E_n) \to 0$ as $N \to \infty$ by subadditivity. Combined with the first inequality, this implies that ${\|A_n\|_{op} / n^{1/2+\varepsilon}}$ converges almost surely to zero.
Finally, setting $k=1$ in the second inequality gives the bound
$\displaystyle {\|A_n\|_{op} / n^{1/2-\varepsilon}} \geq n^{\varepsilon}$,
which implies that ${\|A_n\|_{op} / n^{1/2-\varepsilon}}$ diverges almost surely to infinity.


Unable to run backup script shipped with Neo4j Enterprise 1.8.2

Question: Operating System: Windows 2012
Neo4j Version: 1.8.2 Enterprise
I am having trouble using the Neo4jBackup.bat script to backup the Neo4j server. I am running the following command from an Administrator command prompt:
.\Neo4jBackup.bat -full -from single://127.0.0.1 -to E:\Neo4j-Backup

When I run this command, I receive the following output and stack trace:
Performing full backup from 'single://127.0.0.1'
Exception in thread "main" java.lang.RuntimeException: java.io.IOException: The filename, directory name, or volume label syntax is incorrect
    at org.neo4j.index.impl.lucene.LuceneDataSource.newIndexWriter(LuceneDataSource.java:685)
    at org.neo4j.index.impl.lucene.LuceneDataSource.syncGetIndexSearcher(LuceneDataSource.java:574)
    at org.neo4j.index.impl.lucene.LuceneDataSource.getIndexSearcher(LuceneDataSource.java:540)
    at org.neo4j.index.impl.lucene.LuceneDataSource.makeSureAllIndexesAreInstantiated(LuceneDataSource.java:893)
    at org.neo4j.index.impl.lucene.LuceneDataSource.listStoreFiles(LuceneDataSource.java:833)
    at org.neo4j.com.ServerUtil.rotateLogsAndStreamStoreFiles(ServerUtil.java:129)
    at org.neo4j.backup.BackupImpl.fullBackup(BackupImpl.java:41)
    at org.neo4j.backup.BackupClient$BackupRequestType$1.call(BackupClient.java:73)
    at org.neo4j.backup.BackupClient$BackupRequestType$1.call(BackupClient.java:69)
    at org.neo4j.com.Server$4.run(Server.java:427)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.io.IOException: The filename, directory name, or volume label syntax is incorrect
    at java.io.WinNTFileSystem.canonicalize0(Native Method)
    at java.io.Win32FileSystem.canonicalize(Unknown Source)
    at java.io.File.getCanonicalPath(Unknown Source)
    at org.apache.lucene.store.FSDirectory.getCanonicalPath(FSDirectory.java:129)
    at org.apache.lucene.store.FSDirectory.<init>(FSDirectory.java:143)
    at org.apache.lucene.store.MMapDirectory.<init>(MMapDirectory.java:93)
    at org.apache.lucene.store.FSDirectory.open(FSDirectory.java:180)
    at org.apache.lucene.store.FSDirectory.open(FSDirectory.java:172)
    at org.neo4j.index.impl.lucene.LuceneDataSource$DirectoryGetter$1.getDirectory(LuceneDataSource.java:914)
    at org.neo4j.index.impl.lucene.LuceneDataSource.newIndexWriter(LuceneDataSource.java:664)
    ... 15 more

What am I doing wrong? The Neo4j settings related to backup are set to:
online_backup_enabled=true
online_backup_port=6362

Your assistance is appreciated. Thank you.
Amir.
Comment: I have not received any solutions to this question. Is there anyone running Neo4j on Windows? If so, have you tried backing up your data using the backup script that ships with Neo4j?
Comment: Did you try something like  `Neo4jBackup.bat -full -from single://127.0.0.1 -to E:\\Neo4j-Backup`
Comment: Yes, I have tried it with E:\\Neo4j-Backup. I have tried also the variation E://Neo4j-Backup. No luck there either.
Comment: I tried running the backup from Mac OSX machine using the command
`./neo4j-backup -full -from single://[machine IP] -to ~/backup-neo4j` and the result is the stacktrace posted originally. I am beginning to believe that the backup script and tool in Neo4j are just broken. Any thoughts?
Comment: What is the name of the directory where you keep the server data? The problem seems to be on the server-side, not the backup-client.
Comment: @RickardÖberg the data files live in a folder with the path E:\NEO4JHOME. I don't see how this path will be an issue. Thoughts?
Comment: Agreed, that should be an ok path. It's a local drive right?
Comment: Yes, it is a local path. Anyway, we implemented a backup system using shadow copies. This is not ideal and it works, for now.
Answer: Could you try using valid URI syntax for the backup location, like
.\Neo4jBackup.bat -full -from single://127.0.0.1 -to /E:/Neo4j-Backup

Does that work?
Comment: No, it does not work. I receive the exact same error message. I ran the command you provided precisely. Any other ideas?
Comment: I tried running the backup from Mac OSX machine using the command
`./neo4j-backup -full -from single://[machine IP] -to ~/backup-neo4j` and the result is the stacktrace posted originally. I am beginning to believe that the backup script and tool in Neo4j are just broken. Any thoughts?
Answer: Try running the command like this
Neo4jBackup.bat -full -from single://127.0.0.1 -to E:/Neo4j-Backup

Comment: I ran the command as you have typed it. The result is the same error message as described originally. Any other ideas?
Comment: Check if you have write access on that folder? and have you tried changing the backup folder location?
Comment: I tried the following from the Administrator command prompt:

- Use the copy command to write data to the backup folder (Success)
- Run the backup command for Neo4j to the backup folder (Fail)
- Create a new directory on another local drive on the server and run the Neo4j backup command (Fail)
- Run the Neo4j backup command on another local drive without first creating the directory (Fail)
Comment: I tried running the backup from Mac OSX machine using the command
`./neo4j-backup -full -from single://[machine IP] -to ~/backup-neo4j` and the result is the stacktrace posted originally. I am beginning to believe that the backup script and tool in Neo4j are just broken. Any thoughts?


Ler 9 números inteiros, ordenar de forma decrescente e inserir numa matriz 3x3

Question: Tentativa de código:
function getRandom(max) {
    return Math.floor(Math.random() * max + 1)
}

function criarMatrizAlt(n){
    const mat = Array(n).fill(undefined).map(x => Array(n).fill(getRandom(10)));
    mat.sort(function(a,b){
        if(a > b) return 1;
        if(a < b) return -1;
        return 0;
    });
    return mat;
}

console.log(criarMatrizAlt(3));

Saída:
[ [ 9, 9, 9 ], [ 3, 3, 3 ], [ 2, 2, 2 ] ]
OBS.: preciso de ajuda em como ler os valores pelo navegador (com prompt ou algo do tipo) e então armazenar os valores na matriz.
Comment: Opa Bruno, veja se seria isto por favor: https://jsfiddle.net/xy9z36oc/
Comment: @MarceloVismari muito obrigado, Marcelo!
Answer: Resolução pessoal:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title> Ordenando uma matriz </title>

Saída esperada:


Proving convergence in distribution of quotient of two random variables

Question: Question. Let $X_{1}, X_{2}, \ldots$ be positive i.i.d. random variables with $\mathbf{E} X_{1}=a$ and $\operatorname{Var}\left(X_{1}\right)=\sigma^{2}$. Let $S_{n}=X_{1}+\cdots+X_{n}$. Show that $Y_n = \frac{\sqrt{n}(S_n - an)}{S_n}$ converges in distribution as $n \rightarrow \infty$.

My attempt:
Let $Z_n = \frac{S_n - an}{n^{1/2}}$ and $U_n = \frac{S_n}{n}$ so that $Y_n = \frac{Z_n}{U_n}$. Let $g(x,y) = x/y$ so that $Y_n = g(Z_n,U_n)$. If $(Z_n,U_n) \to_d (Z,a)$ then $g(Z_n,U_n) \to_d g(Z,a)$. But convergence in probability implies convergence in distribution and so it suffices to show that $(Z_n,U_n) \to_P (Z,a)$. Now, $Z_n \to N(0,1)$ by CLT and $U_n \to a$ by weak LLN, therefore
$$
\begin{aligned}
P(|Y_n - Y| > \varepsilon) &= P(|(Z_n - Z, U_n - a)| > \varepsilon) \\
&= P(\sqrt{|Z_n - Z|^2 + |U_n - A|^2} > \varepsilon) \\
\end{aligned}
$$
Let $A_{n,\varepsilon} := \{\sqrt{|Z_n - Z|^2 + |U_n - A|^2} > \varepsilon\}$, let $B_{n,\varepsilon} := \{|Z_n - Z| > \varepsilon\}$ and $C_{n,\varepsilon} := \{|U_n - a| > \varepsilon\}$. Then $A_{n,\varepsilon} \subseteq B_{n,\varepsilon} \cup C_{n,\varepsilon}$ and so
$$
P(A_{n,\varepsilon}) \leq P(B_{n,\varepsilon}) + P(C_{n,\varepsilon}) \to 0
$$
Therefore $P(A_{n,\varepsilon}) \to 0$ and so $g(Z_n, U_n) \to_P g(Z,a) = Z/a \sim N(0,\sigma^2/a^2)$.

Does this proof work? I tried to prove it directly but is it more appropriate to show that $Z_n + U_n \to_d Z + a$ by Slutsky's Theorem, so since the linear combination of the components of $(Z_n, U_n)$ converges in distribution, then the random vector itself must convergence in distribution?
Answer: I think your proof does not work because you need $P(|Z_n-Z|>\varepsilon)\to 0$, which means $Z_n\to_P Z$ and it's stronger than CLT. Maybe it's easier to compute the characteristic functions directly.
Comment: Ah yes of course, thank you!
Answer: You should be able to apply Slutsky's theorem directly.
Notice that if $X_n \to X$ in distribution and $Y_n \to c$ in probability, where $c \neq 0$ is a constant, then Slutsky's theorem tells us that $\frac{X_n}{Y_n} \to \frac{X}{c}$ in distribution.
In your case, you have shown that $Z_n \to_d Z \sim N(0,\sigma^2)$ by the central limit theorem and that $U_n \to_P a$ by the weak law of large numbers. Slutsky's theorem allows you to conclude that:
$$\frac{Z_n}{U_n} \to_d \frac{Z}{a} \sim N(0, \sigma^2 a^{-2})$$
Comment: Makes sense thank you!


How to handle dynamic schema and dynamic data in php mysql?

Question: I am going build a medium scale application, where the requirement is to create web forms dynamically, those forms will be available through a permalink then data entry operator will be entering data in those forms. That data will be used to apply statistical operations on it.
Couple of questions are here.

How I can manage the dynamic schema to enter the data, should I be generating a separate table for each form (there can be thousands of forms)?
Is there any open source framework in php/codeigniter?
Should I think about schema less /Nosql databases?
Answer: You may like my presentation Extensible Data Modeling with MySQL. I talk about requirements and several solutions for dynamic schemas.

Extra Columns
Entity-Attribute-Value
Class Table Inheritance
Serialized LOB & Inverted Indexes
Online Schema Changes
Non-relational databases

Each solution has its own strengths and weaknesses. Knowing about them all gives you more tools to use in a given application.
For storing form data, I'd suggest either the Serialized LOB & Inverted Indexes, or else use a non-relational database that can index fields within a document.
Comment: Thank you for such a great presentation. After reading it I am going to adopt Serialized LOB & Inverted Indexes, but I am worrying about schema updation. If a form is altered, what will happen with the data? And what about the search?
Comment: Additionally, is it possible to create pivot table queries with Serialized LOB & Inverted Indexes technique?
Comment: With Serialized LOB, you can INSERT anything form data you want. Existing data inserted previously is not changed. You must keep the inverted indexes updated manually. Pivot queries would have to be done with the inverted index fields.