tftpd allows connections, but times out transferring a file

Question: I'm runnung Ubuntu 12.04 in a VirtualBox VM. I've installed the tftpd-hpa package. I'm using this to boot an embedded Linux system, and I've noticed that on first boot of my VM, it wouldn't work, but restarting the tftpd-hpa service made it work every time, until next boot.
Today, I ran a shell script from Texas Instruments that may have mucked with my tftpd configuration, and now I cannot get it to work at all. I'm able to connect, but transfers timeout, even to localhost (I also tried 127.0.0.1):
steve@steve-VirtualBox:~$ tftp
tftp> connect localhost
tftp> status
Connected to localhost.
Mode: netascii Verbose: off Tracing: off
Rexmt-interval: 5 seconds, Max-timeout: 25 seconds
tftp> get zImage
Transfer timed out.

tftp>

Note that /var/lib/tftpboot/zImage does exist, however I get the exact same behavior for a file that doesn't exist.
Here are the contents of /etc/default/tftpd-hpa:
# /etc/default/tftpd-hpa

TFTP_USERNAME="tftp"
TFTP_DIRECTORY="/var/lib/tftpboot"
TFTP_ADDRESS="0.0.0.0:69"
TFTP_OPTIONS="--secure"

Here is /etc/xinetd.d/tftp:
service tftp
{
protocol = udp
port = 69
socket_type = dgram
wait = yes
user = nobody
server = /usr/sbin/in.tftpd
server_args = /var/lib/tftpboot
disable = no
}

Answer: Seems you're starting tftpd-hpa from xinetd and as a standalone service at the same time. Please choose one and disable the other.
E.g. set disable = yes in /etc/xinetd.d/tftp and restart xinetd.
Then restart the standalone service service tftpd-hpa restart and try the connection again.
Comment: It seems like this has resolved my new problem, but I still have to restart tftpd-hpa after a reboot before it will work (which wasn't what this question was about). Thank you!
Comment: For the follow on question to hopefully resolve the other part, see http://serverfault.com/questions/599126/tftpd-hpa-service-must-be-restarted-before-working-after-fresh-boot
Answer: Setting TFTP_ADDRESS="0.0.0.0:69" didn't work for me, at least for both interfaces.
Setting TFTP_ADDRESS=":69" did the job
Comment: Can you clarify your OS and its version?
Comment: It's Debian Jessie
Answer: 1) uninstall/re-install tftpd-hpa
2) add to /etc/default/tftpd-hpa
RUN_DAEMON="yes"

Answer: You may need to poke a hole in the firewall. From step 4 of http://www.thelinuxdaily.com/2010/02/guide-on-tftp-server-setup-in-fedora/:

Insert the following line before the "COMMIT" line of
  /etc/sysconfig/iptables and then restart the service with 'service
  iptables restart':
-A INPUT -m state --state NEW -m udp -p udp --dport 69 -j ACCEPT
Answer: See this answer.
I had to edit /etc/default/tftpd-hpa and set the IP address in the TFTP_ADDRESS= variable.
That was on Debian Jessie, but it may be the same on Ubuntu.


mergeSort in python - object NoneType error

Question: I'm trying to implement a simple merge sort in python with the aim to split the function into mergeSort and merge. My code looks like this:
def merge_sort(s):
    if len(s) <= 1:
        return s
    else:
        m = len(s) // 2
        s1 = merge_sort(s[:m])
        s2 = merge_sort(s[m:])
        print(merge(s1, s2))
        return merge(s1, s2)

def merge(s1, s2):
    i=0
    j=0
    k=0
    while i < len(s1) and j< len(s2):
        if s1[i] < s2[j]:
            s[k] = s1[i]
            i += 1
        else:
            s[k] = s2[j]
            j += 1
        k += 1

    while i < len(s1):
        s[k] = s1[i]
        i += 1
        k += 1

    while j < len(s2):
        s[k] = s2[j]
        j += 1
        k += 1

now I do believe that i understood the basic idea of merge sort, but when I test my code
I get the error:
TypeError: object of type 'NoneType' has no len()

After 2hours I gave up and build my code different and it worked, but its still nagging me because I believe the code above is correct and Im just missing some detail.
I would be most thankful if someone could explain it to me.
Thanks!
Comment: `merge_sort` ends with `return merge(s1, s2)`, but `merge` doesn't return anything explicitely, so it returns `None`.
Answer: def merge_sort(s):
    if len(s) <= 1:
        return s
    else:
        m = len(s) // 2
        s1 = merge_sort(s[:m])
        s2 = merge_sort(s[m:])
        print(merge(s1, s2))
        return merge(s1, s2)

def merge(s1, s2):
    s = []
    i=0
    j=0
    while i < len(s1) and j< len(s2):
        if s1[i] < s2[j]:
            s.append(s1[i])
            i += 1
        else:
            s.append(s2[j])
            j += 1

    while i < len(s1):
        s.append(s1[i])
        i += 1

    while j < len(s2):
        s.append(s2[j])
        j += 1
    return s


How to verify DNS change is active

Question: I have DNS service from a third party, which provides an webapp for changing the DNS. I changed the DNS settings to point one of the domains I control to our new IP, but it's been hours and there was no change to the status.
Not being very familiar with how DNS changes work, I'm tring to debug what's happening - or rather not happening. I'm in the understanding that DNS takes a while to get distributed globally as caches expire, but I would like to confirm that the change has happened on my provider's DNS sever and thus that the change is underway.
The previous IP was 188.8.131.52 and the new is 220.127.116.11 (changed for this article)
First I confirmed that the domain is actually using the nameserver that I can make changes to:
ilari@alux:~$ dig mydomain.fi NS

; <<>> DiG 9.7.3 <<>> mydomain.fi NS
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 6569
;; flags: qr rd ra; QUERY: 1, ANSWER: 4, AUTHORITY: 0, ADDITIONAL: 4

;; QUESTION SECTION:
;mydomain.fi.           IN  NS

;; ANSWER SECTION:
mydomain.fi.        77916   IN  NS  dns2.myprovider.com.
mydomain.fi.        77916   IN  NS  dns3.myprovider.com.
mydomain.fi.        77916   IN  NS  dns.myprovider.com.
mydomain.fi.        77916   IN  NS  dns4.myprovider.com.

;; ADDITIONAL SECTION:
dns.myprovider.com. 1582    IN  A   10.11.12.13
dns2.myprovider.com.    1442    IN  A   10.11.12.14
dns3.myprovider.com.    1715    IN  A   10.11.12.15
dns4.myprovider.com.    1457    IN  A   10.11.12.16

(I originally used whois mydomain.fi for this, but I now realize that was not the proper way, since it doesn't actually query the DNS, only what's written about it in the whois record, if anything.)
After that, I tried using host to fetch results directly from the provider's server. I assume it should immediatly result in displaying the new IP, but instead:
ilari@alux:~$ host mydomain.fi dns.myprovider.com
Using domain server:
Name: dns.myprovider.com
Address: 10.11.12.13#53
Aliases:

mydomain.fi has address 184.108.40.206

This was after many hours. I thought it should have changed to 18.104.22.168 immediately since it should query the exact server I'm making changes to from the web interface. What should I expect to see as results?
How do I make sure the web interface at my provider has worked, and the DNS has changed properly at their server?

It turns out this was a problem at their end. The web interface hadn't made the change properly, and the IP wasn't actually changed at their DNS server.
After their problem was solved, there was still a few minutes delay after the change was seen with host mydomain.fi dns.myprovider.com (and of course longer until the change is seen globally).
Comment: Do the lookup directly from your canonical nameservers: http://serverfault.com/questions/372066/dig-force-resolving-without-cache/372071#372071
Comment: Without going off on a tangent, DNS DOES NOT PROPAGATE.
Comment: @joeqwerty I always try to use the correct terminology when I'm aware of it, and I'm also interested in techical subtleties conveyed by language. Please point me to some source where I can read details on *why* DNS information being slowly distributed to an increasing area due to cache aging *should not* be called "propagation", so that I can fix both the terminology used in the question and also any further use in my own language.
Comment: @joeqwerty Edited my question. It [seems](http://chat.stackexchange.com/transcript/message/4027275#4027275) "propagation" means something more specific to the sysadmin people, and using it with DNS changes is misleading in the professional context.
Answer: A DNS change is "active" as soon as you make it and verify that all of the authoritative servers (as listed in the zone's NS records) are serving the new record.  Ladadadada pointed you at a question/answer that explains how to check this.
A DNS change is "propagated" once the caches on all servers around the world have expired and they've retrieved the new information from the authoritative servers.
("propagation" is technically the wrong word - it's actually cache expiration - but it's the commonly used term).
You can control the first of these. You cannot control the second (the TTL (Time To Live) value on the record should theoretically limit how long it takes for caches to expire, however there are ISPs out there that simply don't respect TTL values -- AOL in particular is notorious for this).
Comment: Doesn't running `dig @authorative.dns.com mydomain.fi` produce the same results than `host mydomain.fi authorative.dns.com` which is what I did in the question?
Comment: @IlariKajaste It should, yes.
Comment: So.. in the case of my question, the change can be confirmed as "active"  (= not yet globally available, but can already be trusted to get eventually distributed to the DNS network) by checking with relevant `dig` or `host` command that all the `dnsX.myprovider.com` listed by the `dig mydomain.fi NS` give the new ip `188.8.131.52` instead of the old `22.214.171.124`. Further, this method of determination only works after the TTL values listed in the `dig NS` query have been observed to reach zero (and jump back up) at least once?
Comment: @IlariKajaste Correct, with the exception of waiting for the TTL to expire. If you are querying an *authoritative* name server it should always return the data it has in the zone file - no caching (and thus no decreasing TTL) should be involved. If it doesn't you may have messed something else up (like not incrementing the zone serial number), and if the TTL is decreasing on subsequent queries you're not querying the true primary authoritative NS (you're getting someone's cache data - possibly off a shadow NS).
Answer: What's the time to live (TTL) setting for the mydomain.fi record?  If the TTL is, say, one day, you would not see changes until tomorrow.
Comment: @IlariKajaste, if you do a dig on the authoritative name servers, you'll see the TTL counting down, e.g., `dig google.com ns1.google.com`
Comment: @cjc Note that you will only see the TTL decreasing on **cached** data. Building on your Google example: `dig @ns1.bsd-box.net bsd-box.net` will query my system for its own DNS data - run it a few times and you'll see the TTL stays the same (3600).  `dig @18.104.22.168 bsd-box.net` will query Google's public DNS, and if you run it a few times you'll see the TTL decrease (It may take a number of tries and be slightly inconsistent as 22.214.171.124 is not just a single DNS server/cache)
Comment: cjc is correct. It lot depends on the TTL. However, your ISP can cache. Check the Root Servers ( http://dns.squish.net/ ) or OpenDNS Cache ( http://www.opendns.com/support/cache/ ) to get an overview on how it is getting resovlved currently.
Comment: Is there a way to check the TTL? It's probably 15 min though, since they said it should only take that long to be active.
Comment: using dig command ( eg: dig ycombinator.com ) will show the TTL in Answer Section. The number next to the domain, is the TTL. It is in seconds.
Comment: @voretaq7 The google.com example is a little weird. I see ns1.google.com in the SOA, but that appears to cache www.google.com, as I see a decrementing TTL when I do `dig www.google.com. ns1.google.com.`  It may be how google manages their DNS more than anything else.
Answer: I like to use dig to check this:
dig hostname.to.check @dns.myprovider.com

Make sure to check all of the nameservers to see that they all respond with the same.
Squish.net also has a great tool for DNS traversal and it will tell you how the active nameservers are going to respond to your request.
Comment: Add the `+trace` option to dig to avoid possible DNS caches.

How to verify DNS change is active


Who are the other horses and riders alongside Americah Pharoah?

Question: Both before and after the Belmont Stakes on Saturday, I noticed that the horses and jockeys were accompanied by men wearing red vests over white shirts, who were also on horses. They first led the procession to the track, then stayed in the rear while the horses entered the gate.
After the race, one of the men rode alongside Victor Espinoza as American Pharoah cooled down after the race. At first, as I had thought earlier, it seemed that the men were merely there to ensure that everything went fine and the horses went where they were supposed to go. However, I noticed that Espinoza was talking and laughing with the man after the race, and America Pharoah appeared the be nuzzling the other horse, indicating that the two pairs knew each other. That seemed to cast doubt on my first theory.
Who are the red-vest-wearing men? Are they officials?
A picture can be seen here, later in the article.
Comment: I know nothing about horse races. But I tried to google a bit and it seems that those accompanying horses are called [lead ponies](https://www.google.com/search?q=lead+pony). I also found [this](http://www.chronofhorse.com/forum/showthread.php?419513-Lead-Ponies-at-the-Races). Perhaps this helps you with further search for the answer.
Answer: These are indeed lead ponies or companion ponies. This horse(s) are brought along with a race horse to and on the road to keep them emotionally stable and focused on the race. These ponies help them to stay calm before races. This is a common practice for many race horses.

Famed champion Seabiscuit relied on a whole covey of kindly animals: a horse named Pumpkin, a dog named Pocatell, and a spider monkey named Jo-Jo. The champion Unbridled, who won the 1990 Kentucky Derby, enjoyed companionship from his equine friend Mustard <

http://www.slate.com/articles/news_and_politics/explainer/2004/06/what_is_a_companion_pony.html`


.NET WebSockets and TCP_NODELAY

Question: Is it possible to build a WebSocket Client in C#.NET that allows me to set the TCP_NODELAY property to True on the socket (i.e. disable Nagle)? I have tried a bunch of WebSocket libraries that don't appear to have this option.
Thanks
Comment: _"set the TCP_NODELAY property to False on the socket (i.e. disable Nagle)"_ -- first, you need to figure out what it is you're actually trying to do. The default value for `TCP_NODELAY` is false, so you don't need to set it to false. The false state corresponds to Nagle's algorithm being _enabled_, not disabled. Beyond that, your question is way too broad... _"is it possible?"_ Sure, it's always possible. The only question is how much work you want to put into it. How much work have _you_ put into this?
Comment: See codeproject : https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_server
Comment: Thanks, but this is a server implementation, I'm looking for a client
Comment: Sorry, I meant to say True not False. I'm sending data that needs to stream with no pauses. Was wondering if this was possible to do with Microsoft's WebSockets. I found how to do it on the Server end.
Answer: I ended up finding an open sourced WebSocket library that I was able to add NoDelay support to.
Comment: Please share the library name

.NET WebSockets and TCP_NODELAY


MS Access - alternative to performing a "full join" for columns with same name

Question: I have this problem using access: I am using the RIGHT + LEFT outer joins to overcome the fact that ACCESS does not support the FULL JOIN.
SELECT *
FROM T1 RIGHT OUTER JOIN T2
ON T1.xxx = T2.xxx
UNION
SELECT *
FROM T1 LEFT OUTER JOIN T2
ON T1.xxx = T2.xxx

on these tables:
T1:
ID1 | xxx | fieldA
a     1       X
b     2       Y
c     3       Z

T2:
ID2 | xxx | fieldB
d      2       K
e      3       J
f      4       H

AS a result I obtain a table with this structure
T1.xxx | T2.xxx | fieldA | fieldB | ID1 | ID2
   1                 X               a
   2        2        Y       K       b     d
   3        3        Z       J       c     e
            4                H             f

xxx is not primary key but has the same name and numerical type (integer)
I saw from many other places that this should work by collapsing the two tables! Here it does not (the elements on the same rows, when non blank, are of course the same)
MY EXPECTATION
FINAL TABLE:
    xxx |  ID1 | ID2 |fieldA | fieldB
     1      a            X
     2      b     d      Y       K
     3      c     e      Z       J
     4            f              H

Comment: Could you please rephrase your question to be more clear? What is the problem?
Comment: Search for `[sql] full outer join` in the search box; there are a large number of questions about full outer join for systems that do not support it natively, including: [Full outer join in MySQL](http://stackoverflow.com/questions/4796872/full-outer-join-in-mysql) and [Full outer join with SQLite](http://stackoverflow.com/questions/1923259/full-outer-join-with-sqlite).  The second has an interesting tweak compared to the first.
Comment: It would also be helpful if you showed simple schemas for T1 and T2, with sample data, the result you're getting, and the result you expected.  It may be that you're getting the correct result but your expectation is wrong.
Comment: Thanks for adding the tables and results — it makes the issue clear in a way that I'd not have guessed from your explanation. You are looking for a NATURAL FULL OUTER JOIN, not a FULL OUTER JOIN.  You'd have to `COALESCE(T1.xxx, T2.xxx) AS xxx` and list the other columns explicitly to get the result you want.  (See also [BNF Grammar for ISO/IEC 9075-2:2003](http://savage.net.au/SQL/sql-2003-2.bnf.html#joined%20table).)  It would be nice if your actual result table were fully filled in like your expected result table is.
Comment: Answers to a question should be posted as answers, not as part of the question (even if it is your own question.) The members of the StackOverflow community are building a collection of questions and answers.
Comment: You are encouraged to post an answer in response to your own question, if you found an answer to your question; this can be shared with the community.
Comment: thanks @JonathanLeffler but the coalescence is not recognized in access. anyway I was posting the solution in the answer field but my early account privileges sucks, now it cannot be seen not even on the question, I will try to fix tomorrow. =)
Comment: Does Access have `NVL` or something similar?  What about `CASE`?  If worst comes to worst, then `CASE WHEN T1.xxx IS NOT NULL THEN T1.xxx ELSE T2.xxx END`.  Otherwise, it might be time to abandon Access, or abandon your NATURAL FULL OUTER JOIN.
Comment: Urgh...It appears that NZ is the nearest you get; it appears that NVL and CASE are not supported.  Hmmm...I think you should do the coalescing in your application code, or the VB code, rather than trying to do it in the SQL (SELECT) per se.  'Tis tempting to say "get a real DBMS", but there are undoubtedly reasons why you are using Access.
Comment: @JonathanLeffler I guess you are right, doing in VB should be much faster, these days I'll learn more VB coding and maybe move that big query somewhere. Thanks you all your support anyway
Answer: It seems that there are different set of column values for both of these 2 tables, you could be having t1.xxx and t2.xxx which have the same values, but other columns dont, the union in this case wouldn't combine these 2 records
Try something like
SELECT T1.xxx
FROM T1 RIGHT OUTER JOIN T2
ON T1.xxx = T2.xxx
UNION
SELECT T2.xxx
FROM T1 LEFT OUTER JOIN T2
ON T1.xxx = T2.xxx

Something like this should give you all the xxx values from table 1 and table 2, ignoring duplicate values for xxx.
Comment: Akash your solution provides a column with only the shared xxx between the two tables, so in my examples it gives as output only two rows with the xxx 2 and 3
Comment: I just solved using a similar solution, which I am posting now in the end of the question
Answer: The most likely explanation for the behavior you observe is that the rows being returned that are not identical, they are not exact duplicates.
The UNION operator will remove duplicate rows, but it doesn't do anything to "collapse tables" other than that.

To get the specified result set (in the updated question), here's one SQL pattern that would return the result. (I don't know if Access supports this, but this would work in MySQL, SQL Server, Oracle, etc.)
 SELECT i.xxx
      , v1.ID AS ID1
      , v2.ID AS ID2
      , v1.fieldA AS fieldA
      , v2.fieldB AS fieldB
   FROM (
          SELECT t1.xxx AS xxx
            FROM T1 t1
           UNION
          SELECT t2.xxx
            FROM T2 t2
        ) i
   LEFT
   JOIN T1 v1
     ON v1.xxx = i.xxx
   LEFT
   JOIN T2 v2
     ON v2.xxx = i.xxx

(NOTE: if xxx is not guaranteed to be unique in each table, then this query could generate duplicate rows.)
Answer: MY SOLUTION (absolutely not elegant):
SELECT [QUERY1].XX, ID1, ID2, fieldA, fieldB
FROM (T2 RIGHT JOIN [QUERY1] ON T2.xxx = [QUERY1].XX) LEFT JOIN T1 ON [QUERY1].XX = T1.XX;

where QUERY1 is the following:
(SELECT CInt(NZ(T1.xxx,T2.xxx)) as XX
    FROM T1 RIGHT OUTER JOIN T2
    ON T1.xxx = T2.xxx
    UNION
    SELECT CInt(NZ(T1.xxx,T2.xxx)) as XX
    FROM T1 LEFT OUTER JOIN T2
    ON T1.xxx = T2.xxx)
    UNION (SELECT CInt(NZ(T2.xxx,T1.xxx))  as xx1
    FROM T1 RIGHT OUTER JOIN T2
    ON T1.xxx = T2.xxx
    UNION
    SELECT CInt(NZ(T2.xxx,T1.xxx)) as xx1
    FROM T1 LEFT OUTER JOIN T2
    ON T1.xxx = T2.xxx);

notice that xx1 is not used, and not even shown in the table
Answer: TRY THIS ONE:  I have tried and get both result sets.
DECLARE @T1 TABLE
(
ID1 VARCHAR(2) ,XXX INT, FIELDA VARCHAR(2)
)
DECLARE @T2 TABLE
(
ID2 VARCHAR(2) ,XXX INT, FIELDB VARCHAR(2)
)

INSERT INTO @T1 VALUES
('a',     1,       'X'),
('b',     2,       'Y'),
('c',     3,       'Z')

INSERT INTO @T2 VALUES
('d',     2,       'k'),
('e',     3,       'j'),
('f',     4,       'h')

SELECT
    ISNULL(CONVERT(VARCHAR(1),T1.xxx),' ') AS [T1.xxx] ,
    ISNULL(CONVERT(VARCHAR(1),T2.xxx),'') AS [T2.xxx] ,
    ISNULL(fieldA,'') AS [fieldA],
    ISNULL(fieldB,'') AS [fieldB] ,
    ISNULL(ID1,'') AS [ID1] ,
    ISNULL(ID2,'') AS [ID2]
FROM
(
    SELECT XXX as XXX1 FROM @T1
    UNION
    SELECT XXX as XXX1  FROM @T2
)T LEFT OUTER JOIN
@T1 T1 ON T.XXX1 = T1.XXX
LEFT OUTER JOIN
@T2 T2 ON T.XXX1 = T2.XXX

----------------------RESULT------------------
T1.xxx  T2.xxx  ID1 ID2 fieldA  fieldB
1       a       X
2   2   b   d   Y   k
3   3   c   e   Z   j
    4       f       h

SELECT
    ISNULL(CONVERT(VARCHAR(1),T.xxx1),' ') AS [xxx] ,
    ISNULL(ID1,'') AS [ID1] ,
    ISNULL(ID2,'') AS [ID2],
    ISNULL(fieldA,'') AS [fieldA],
    ISNULL(fieldB,'') AS [fieldB]

FROM
(
    SELECT XXX as XXX1 FROM @T1
    UNION
    SELECT XXX as XXX1  FROM @T2
)T LEFT OUTER JOIN
@T1 T1 ON T.XXX1 = T1.XXX
LEFT OUTER JOIN
@T2 T2 ON T.XXX1 = T2.XXX

----------------------RESULT------------------
xxx ID1 ID2 fieldA  fieldB
1   a       X
2   b   d   Y   k
3   c   e   Z   j
4       f       h


Chi Square Test for one variable

Question: I got a question about the use of Chi Square test. Let's assume I am conducting a survey. And I have a question: "Have you ever heard of the Internet"?
The possible answers are: "Yes", "No", "Not sure" and I have 3 different age groups for my respondents: "<18", "18
When I want to do a Chi Square test to see if the age factor has an effect, can I just conduct this test on the "Yes" part? Or Do I need to include all the variables?
Comment: you have to include all variables "yes" ,"no" ,"not sure".to apply Chi Square test.
Answer: Inorder to use Chi Square test you need to have two variables. In your example these variables are age and use/no use of internet. Hence you have to use 'yes','no,'not sure'.
Comment: Not really true. The $\chi^2$-test measures the divergence from a given distribution. The test for independence is a particular case, where the joint distribution is given by the definition of stochastic independence.
Answer: It depends on what you want to measure.
You could test whether or not the distribution of "Yes"/"No"/"Not sure" is significantly different from what would occur under the null hypothesis - say, an equal distribution of Y/N/DKs. This is the so-called test for homogeneity use of the $\chi^2$-test.
However, in most cases one uses the $\chi^2$-test to test for independence between two variables.
Stochastic independence is defined by $\Pr(A \cap B)=\Pr(A)\Pr(B)$ - this forms our null hypothesis. This directly translates into the expected cell count $E_{xi}$ of the cell xi as the product of the marginal probabilities times the number of observations. The test statistic is then $\sum\frac{(E_{xi}-O_{xi})^2}{E_{xi}}$, which is $\chi^2_k$-distributed with k being the number of rows minus 1 times the number of columns minus 1.
Comment: So what does it mean when I apply the Chi Square test only on the "yes" part?

Chi Square Test for one variable


Show newest nodes for each taxonomy term in Views

Question: A block with taxonomy terms and an overview of the newest nodes for each taxonomy term. Every news sites uses this idea.
Business: Article 1, Article 2
Technology: Article 1, Article 2
Sports: Article 1, Article 2
Only article 1 for every node has a teaser and picture...
Any idea how to do this with just one view? You can make a view for each term, but I don't like that idea...
Answer: I was trying to achieve a similar thing. I've managed to create a view that gets one article for each taxonomy term using 'Taxonomy term: Representative node' under 'Advanced > Relationship'.
There is also 'Content: Taxonomy terms on node' there which might be more what you're looking for.
Once you've got the relationship you can pull out fields and base filter criteria on that relationship. My view only returns 1 content type for instance.
Make sure your view is on Taxonomy not Content.
Comment: Interesting to view Taxonomy, not Content. That just made me understand a huge programming concept, thank you!
Comment: Do you think it would be possible to show the taxonomy terms WITH content (taxonomy fields) and a list of nodes?

So I don't want to show content from the nodes, I just want to show the titles, and instead I want to show the Taxonomy content...
Comment: On the fields I think you can add Taxonomy Fields. I think you can also set up a relationship that shows all nodes for that taxonomy rather than just one.
Comment: The 'Representative node' relationship was just what I needed. Very awesome. Thanks Matt!


Como posso fazer com que uma caixa de log sempre mostrar a ultima linha?

Question: oi, tenho um arquivo log de outros códigos que fica atualizando ai eu fiz um código javascript que mostra esse arquivo e é um código que fica atualizando o texto ao vivo na pagina dentro de uma textarea porem ele fica atualizando e sempre volta para a primeira linha,ai nunca tem como ver a parte final, queria saber se é coisa do css que tem q mexer ou o javascript msm.
Código JS:
var url  = "wget-log";
var textarea_id = "textarea";

setInterval(function(){

$.ajax({
url : "wget-log",
type : "POST",
success : function(data){
$(".textarea").html(data);

}

});
}, 1000);

Formato da log:
     0K .......... .......... .......... .......... ..........  0%  116K 31m1s
    50K .......... .......... .......... .......... ..........  0%  454K 19m27s
   100K .......... .......... .......... .......... ..........  0% 92.1K 25m56s
   150K .......... .......... .......... .......... ..........  0%  184K 24m18s
   200K .......... .......... .......... .......... ..........  0% 44.4K 35m34s
   250K .......... .......... .......... .......... ..........  0%  620K 30m36s
   300K .......... .......... .......... .......... ..........  0% 93.5K 31m41s
   350K .......... .......... .......... .......... ..........  0% 70.0K 34m7s
   400K .......... .......... .......... .......... ..........  0% 57.5K 37m14s
   450K .......... .......... .......... .......... ..........  0% 71.1K 38m32s
   500K .......... .......... .......... .......... ..........  0%  788K 35m26s
   550K .......... .......... .......... .......... ..........  0%  553K 33m1s
   600K .......... .......... .......... .......... ..........  0% 66.5K 34m36s
   650K .......... .......... .......... .......... ..........  0% 1.29M 32m19s
   700K .......... .......... .......... .......... ..........  0%  565K 30m34s
   750K .......... .......... .......... .......... ..........  0%  652K 29m0s
   800K .......... .......... .......... .......... ..........  0% 55.8K 31m3s
   850K .......... .......... .......... .......... ..........  0% 71.7K 32m5s
   900K .......... .......... .......... .......... ..........  0%  103K 32m12s
   950K .......... .......... .......... .......... ..........  0%  101K 32m21s
  1000K .......... .......... .......... .......... ..........  0% 33.5K 35m52s

Por causa desse formato nunca consigo ler oque realmente está acontecendo já que as ultimas atualizações ficam no final
Comment: Olá, o log que é enviado é apenas um item ou ele retorna sempre todas as linhas?
Answer: Vc pode tentar uma expressão regular para capturar a última linha e exibi-la.
Tente esta regex:
\r?\n?[^\r\n]*$


How to add new column(header) to a csv file from command line arguments

Question: The output of the following code:-
import datetime
import csv
file_name='sample.txt'
with open(file_name,'rb') as f:
    reader = csv.reader(f,delimiter=",")
    #headers = reader.next()
    p=[]
    for row in reader:

        row[0] = row[0].zfill(6)
        row[2] = row[2].zfill(6)
        row[3] = row[3].zfill(6)
        row[4] = row[4].zfill(6)
        row[1] = row[1][5:7] + "-" + row[1][8:10] + "-" + row[1][:4]
        p.append(row[:5])
        print p
with open('names.txt', 'wb') as ofile:
    writer = csv.writer(ofile)
    for row in p:
        writer.writerow(row)

is following:-
User_ID,--Date,0Num_1,0Num_2,Com_ID
000101,04-13-2015,000012,000021,001011
000102,04-03-2014,000001,000007,001002
000103,06-05-2013,000003,000004,000034
000104,12-31-2012,000004,000009,001023
000105,09-09-2011,000009,000005,000104

I want to add a new column to the csv file from command line.
e.g. python script_name.py Dept_ID Location  will create columns for Dept_ID and Location next to Comp_ID.
Can any one guide me here please!
Comment: possible duplicate of [Pythonically add header to a csv file](http://stackoverflow.com/questions/20347766/pythonically-add-header-to-a-csv-file)
Comment: how would you fill it?
Comment: For command line options take a look at getopt. https://docs.python.org/2/library/getopt.html
Answer: see this post which suggests something like the following:
header = ['User_ID','--Date','0Num_1','0Num_2','Com_ID']
writer = csv.DictWriter(outcsv, fieldnames = header)
writer.writeheader()
writer.writerows({col: row} for row, col in zip(header, p))

to parse the extra columns from the system arguments use sys.argv
import sys

extra_headers = sys.argv
header.extend(sys.argv)
n = len(sys.argv)

writer = csv.DictWriter(outcsv, fieldnames = header)
writer.writeheader()

col_fill = ''
# extend p with two columns of blank data
writer.writerows({col: row_item} for row in p for row_item,col in zip(row+[col_fill]*n,header))

here I iterate through each row, I then crate a dictionary to allocate data to each column in order. Notice [col_fill]*n this creates a list of identical items equal to col_fill that will be used to fill the additional columns parsed in via command line arguments.
In this example the command line arguments would be parsed as:
$ python script_name.py Dept_ID Location

and would create:
User_ID,--Date,0Num_1,0Num_2,Com_ID,Dept_ID,Location
000101,04-13-2015,000012,000021,001011,,
000102,04-03-2014,000001,000007,001002,,
000103,06-05-2013,000003,000004,000034,,
000104,12-31-2012,000004,000009,001023,,
000105,09-09-2011,000009,000005,000104,,

Answer: you can use sys.argv to get arguments from command line.
import sys

print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

$ python script_name.py Dept_ID Location

Number of arguments: 4 arguments.
Argument List: ['script_name.pyy', 'Dept_ID Locatio']

after you get the argument from command line, you could add it into your file


What is the significance of mod?

Question: I always see posts about modular arithmetic, and "equivalence", "congruence", etc, and I don't understand what part of mathematics this falls under, and what use it could be in the real word?
How can something like 'remainder' have such a big impact on mathematics?
Comment: This falls under the category of number theory and is _extremely_ useful both in mathematics and in practical applications. I suggest you read about RSA encryption, which is used to secure credit card transactions, emails, data transmission, etc. https://en.wikipedia.org/wiki/RSA_(cryptosystem)
Comment: Number theory uses mod as a notation. We can use mod to point out important rules for divisability. As said above, modern encryption is entirely reliant on modulo arithmetic. Plus, modular groups are very important in group theory.
Comment: All part of the mysterious usefulness of interesting mathematics.
Comment: Are you asking what the definition of congruence is? I'm sure you can find plenty of basic introductions through google.
Comment: I know what it means, I just don't understand how its applied in the real world
Comment: I can prove that [Graham's number](https://en.wikipedia.org/wiki/Graham's_number) ends in $...04575627262464195387$?
Comment: "I know what it means, I just don't understand how its applied in the real world"  Use your imagination.  Any system where output or significant measurement is cyclic or periodic will use it.  In particular trig functions, time measurement, encryption, etc.
Comment: "How can something like 'remainder' have such a big impact on mathematics? " because for anything which is periodic rather than cumulative, the remainder is the *entirity* of the result.  Imagine you are as to do a complicated calculation involving angular manipulation.  The important thing is the final position and orientation. That's determined by the remainder.  You actual number of times you spun to the nearest rotation is not important.
Comment: @Joffan The mysterious usefulness of mathematics: I recently discovered that the matrix of x^2-y^2 is used in quantum physics and in the study of the hydrogen atom. - Somehow all mathematics is relevant.
Answer: Maybe you can read about the Diffie-Hellman algorithm. It is used to protect information in cryptography, and this is often used by banks and companies.
Other use you can do is to solve some equations that are not easy to attack in the integers to determine if have solutions or not. Inclusive in the finite field theory is useful. One example is the proof of the Fermat's last theorem in the case of $n=5$.
Obviously there are a lot of utilities, but maybe with this is enough.
EDIT: @kccu posted too the RSA algorithm, that is one very important (and right now more known) as the Diffie Hellman algorithm.

What is the significance of mod?


how to get (3623752876 * 3623752876) % 4294434817 in c

Question: I implemented a fast-power algorithm to perform the operation (x^y) % m.
Since m is very large (4294434817), I used long long to store the result. However, long long still seems not enough during the operation. For example, I got a negative number for (3623752876 * 3623752876) % 4294434817.
Is there anyway to figure it out?
Comment: Use `uint64_t` because although `uint32_t` is large enough to hold the operand, it won't hold the product.
Comment: @KingstonChan will you please clarify *in your question* whether the calculation is `(x * y) % m` or `(x ^ y) % m` or `pow(x, y) % m`?
Comment: What do you mean with "figure out"? If `long long` is too small? use a calculator and check if the result is > `LLONG_MAX`. If you mean if there is a larger standard integer type which has more than 64 bits? No! Use a big-integer (i.e. one with "unlimited" integers) library. Note to ensure all calculations are done as `long long`, resp. `unsigned long long` to double positive range.
Comment: `3623752876ULL * 3623752876 % 4294434817`
Answer: All three of those constants are between 231 and 232.
The type unsigned long long is guaranteed to be able to store values up to at least 264-1, which exceeds the product 3623752876 * 3623752876.
So just use unsigned long long for the calculation. long long is wide enough to hold the individual constants, but not the product.
You could also use uint64_t, defined in <stdint.h>. Unlike unsigned long long, it's guaranteed to be exactly 64 bits wide. Since you don't really need an exact width of 64 bits (128-bit arithmetic would work just as well), uint_least64_t or uint_fast64_t is probably more suitable. But unsigned long long is arguably simpler, and in this case it will work correctly. (uint64_t is not guaranteed to exist, though on any C99 or later implementation it almost certainly will.)
For larger values, including intermediate results, you'll likely need to use something wider than unsigned long long, which is likely to require some kind of multi-precision arithmetic.  The GNU GMP library is one possibility. Another is to use a language that has built-in support for arbitrary-width integer arithmetic (such as Python).
Answer: This answer is based on the calculation (x * x) % y although the question is not entirely clear.
Use uint64_t because although unsigned int is large enough to hold the operands, and the result, it won't hold the product.
#include <stdio.h>
#include <stdint.h>

int main(void)
{
    unsigned x = 3623752876;
    unsigned m = 4294434817;
    uint64_t r;

    r = ((uint64_t)x * x) % m;
    printf("%u\n", (unsigned)r);
    return 0;
}

Program output:
3896043471

Answer: We can use the power of modulus arithmetic to do such calculations. The fundamental property of multiplication in modulus arithmetic for two numbers a and b states:

(a*b)%m = ((a%m)*(b%m))%m

If m fits into the long long int type, then the above calculation will never overflow.
Since you are trying to do modular exponentiation, you can read more about it here.


Erro 503 "No 'Access-Control-Allow-Origin' header"

Question: estou tentando fazer uma conexão no datasnap usando ajax
meu codigo:
                var url = 'http://cloud.nooven.com.br:12345/datasnap/rest/TServerMethods1/CriaSessao/'+cpfCnpj+'|'+usuario+'|'+senha;
                console.log(url);
                $.ajax({
                    type: "GET",
                    url: url,
                    dataType: "json",
                    success: function(data){
                        console.log('sucesso');
                    },
                    error: function(data){
                        console.log('erro');
                    }
                });

a pagina .html que to acessando ta no servidor, por isso esta como localhost na variavel url, o erro que ocorre é esse:
XMLHttpRequest cannot load http://cloud.nooven.com.br:12345/datasnap/rest/TServerMethods1/CriaSessao/68243096000152%7CMOACIR%7C123456. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://cloud.nooven.com.br' is therefore not allowed access. The response had HTTP status code 503.

obrigado.
Comment: aonde eu to usando @GuilhermeNascimento ???
Comment: ah, apenas usei, nada demais, eu troquei o 'jsonp' por 'json' e mudou o erro: ' XMLHttpRequest cannot load http://cloud.nooven.com.br:12345/datasnap/rest/TServerMethods1/CriaSessao/68243096000152%7CMOACIR%7C123456. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://cloud.nooven.com.br' is therefore not allowed access. The response had HTTP status code 503. '
Comment: em php, eu resolvia com o header( "Allow - ......
Comment: sim, uma hospedagem minha
Comment: o codigo está em delphi, é um datasnap
Comment: Costumo resolver assim: https://pt.stackoverflow.com/questions/92269/qual-%C3%A9-o-nome-da-opera%C3%A7%C3%A3o-quando-fazemos-uma-requisi%C3%A7%C3%A3o-ajax-para-o-servidor-int
Answer: Conforme este link CORS on DataSnap REST Server você deve usar assim:
procedure TWebModule1.WebModuleBeforeDispatch(Sender: TObject;
Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
begin
  //Permite requisições de diferentes dominios
  Response.SetCustomHeader('Access-Control-Allow-Origin','*');
  if FServerFunctionInvokerAction <> nil then
    FServerFunctionInvokerAction.Enabled := AllowServerFunctionInvoker;
end;

Comment: coloquei no delphi, mas continua com o mesmo erro :(  'XMLHttpRequest cannot load http://cloud.nooven.com.br:3715/datasnap/rest/TServerMethods1/CriaSessao/68243096000152%7CMOACIR%7C123456. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://cloud.nooven.com.br' is therefore not allowed access.'
Comment: @Furlan não tenho conhecimento com tal tecnologia, mas vou suport duas coisas. Ou você não reiniciou o aplicativo ou você colocou o código aleatoriamente em qualquer lugar. Como eu não tenho o seu código original, não faço ideia da onde indicar o local para adicionar o método. Se puder adicionar detalhes a pergunta


System.Speech.Synthesis.SpeechSynthesizer - how to customize the voice?

Question: SpeechSynthesizer allows peaking different voices by using
SelectVoiceByHints(VoiceGender, VoiceAge)function (as I understood). But no customization happens if I change the gender and voice age.
Can you explain why? And if I'm doing something wrong, what is correct way to do that?
Thank you.
Answer: Here's a small test program that you can use to discover installed voices:
using System;
using System.Speech.Synthesis;  // Add reference to System.Speech

class Program {
    static void Main(string[] args) {
        var synth = new SpeechSynthesizer();
        foreach (var voice in synth.GetInstalledVoices()) {
            Console.WriteLine(voice.VoiceInfo.Description);
        }
        Console.ReadLine();
    }
}

Output on my machine: Microsoft Anna - English (United States)
Which is the one and only default voice that's shipped with Windows afaik.  Which would of course explain why changing gender and age doesn't have an effect on your machine.
Comment: is it possible get more voices (Spanish,...) ?
Answer: According to the name of the function, I'd say this is a selector for installed voices. It does not customize the voice in any way, but rather picks one from the repo according to your specified parameters.
So, if there is only one voice installed, he can only pick that one.
Comment: When you install a voice, the installer places information in the registry about the age, gender, etc. of the voice.  The framework reads the registry to find the data of the voice.  (In C++, the interface you're looking for is ISpObjectToken, and the MS implementation uses the registry.  Other TTS engines would have their own implementation of ISpObjectToken, and might not use the registry.)
Comment: Yep, maybe, but I couldn't really find any explanation how to extend the list of the voices :).
Comment: You can buy third-party voices, some of which are really quite good. I don't have a link off-hand though.
Comment: Maybe, but I don't really understand how is it working in general. How framework gets the info about installed voices?


Why did newly formed Premiership and FA agree on the promotion system?

Question: The Premiership was founded when 22 clubs left from The Football League and formed a new association football club. All clubs left for more television money and threatened for some years before the split that they will create a super league. It seems to me like a bad divorce between the 22 involved clubs and the FA, so my question is:
Why did the FA agree to rename its divisions and that the highest ranked league will become the second tier of English football?
I'm looking, if there is one, for a different answer than the one that involves the number of supporters the 22 involved clubs had.
Comment: The FA didn't rename any divisions on account of the Premier League.  The tier below the Premier League was known as Football League Division One before and after the split.  And to make things worse, today it is known as The Championship.
Comment: Didn't know that they renamed it later to The Championship.
Answer: There are some corrections to your question.

It seems to me like a bad divorce between the 22 involved clubs and
  the FA.

Nope, it was a divorce between the 22 clubs and the Football League. The Football League is different from the FA. In fact the foundation of the Premier League states

The five (big) clubs decided it was a good idea and decided to press
  ahead with it, however the league would have no credibility without
  the backing of The Football Association and so David Dein of Arsenal
  F.C. held talks to see whether the FA were receptive to the idea. The
  FA did not enjoy an amicable relationship with the Football League at
  the time and considered it as a way to weaken the Football League's
  position.

So now to the question:

Why did the FA agree to rename its divisions and that the highest
  ranked league will become the second tier of English football?

As earlier, the FA pushed this idea. The web archive article says

But rumblings of discontent had started in 1991 with the FA's
  unveiling of their 'Blueprint for Football' which put forward the idea
  of a Super League of 18 clubs. The Football League strongly resisted
  the proposals, but on June 14, 1991 16 First Division clubs signed a
  document of intent to join the newly named Premier League. Eventually
  all 22 First Division clubs tendered their resignation from the League
  and, after months of financial wranglings and threats of a players'
  strike, the PL became official on September 23. The FA agreed to
  continue with three up and three down promotion and relegation, vowed
  to reduce the Premier League to 20 and struck a record five-year
  £304 million television deal with Sky and BBC.

So in this case it seems that the FA actually agreed with the Football League to allow promotions for 3 teams from the Championship rather than keep it a closed shop, in order that those teams get part of the earnings. Note in the Premier League, your final standings at the end of the year specify the % of the Sky TV kitty you take home.
So even though positions 18 - 20 are relegated, they will get a proportional share of the TV earnings. There is an incentive to be 18th, rather than 20th.
In each year, there is a chance for 3 teams from the Championship to get into the Premier League TV revenue. and 3 teams fall out of the Premier League too.
Comment: I'm puzzled. This is a very good answer, which basically corrected the wrong assumptions in the question. However if the question is _"why did they agree to have relegations"_, it doesn't really give an answer, it just states they did (as the question itself already stated). (that being said, the answer is obvious: "a league without promotions and relegations just isn't credible, people would likely not take it seriously, so they did just that")


cannot get jQuery slider to work

Question: How does one get a slider working with jQuery.
HTML:

CSS:
.ui-slider-handle {
    border:1px solid silver;
    height:10px;width:10px;
    background-color:black;
}

#example1 {
    width:1050px;
    background-color:white;
   border:1px solid black;
}

jQuery:
$('#example1').slider( { minValue: -100, maxValue: 100 } );

Let me know if you need more code. What am I doing wrong?
Answer: Looks like you just need to add some jQueryUI styles to it.
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/themes/base/jquery-ui.css" type="text/css" media="all" />

Also, you don't need to have

 inside the div, it's handled by jQueryUI.

cannot get jQuery slider to work


Where to start from?

Question: I'm a good jazz pianist that is good in music theory , can figure out harmony of songs alone.
AND I can play chords and scales on the guitar technically and musically well.
and today I was introduced to classical guitar and finger style it is so compelling and I decided to learn it.
this is the video :

my question is :
how to and where to start learning this technique ? and how can I use my good music theorem throughout studying it? should I search for finger style tutorials ? or play some classic guitar music ?
by "learn it" I mean to play freely and instantly any heard song on the guitar like I do on the piano
Comment: The video is disabled. Jeff who?
Comment: sorry for that fixed it. the video should be a clarification for my purpose and question.
Answer: First of all, there is a difference between classical guitar and fingerstyle guitar. Generally fingerstyle refers to steel string acoustic guitars played with the fingers, while classical guitar uses nylon stringed guitars with a very specific playing technique. Technically classical guitar uses a type of fingerstyle technique, but usually fingerstyle is associated with folk, blues, or country music on steel-stringed acoustic guitars. These are all generalizations, but there is a distinction between the two worth noting as you decide which path you want to take. The video you posted is indeed classical guitar played on a nylon stringed guitar. If you want to teach yourself, it would probably be easier to learn fingerstyle without the classical guitar component as it is less dependent on having the exact right technique.
Classical guitar is one instrument where your technique must be very precise so it's a little bit harder to teach yourself. I would recommend getting a good teacher as they can give you proper instruction on how to hold the guitar, how to play, hand positions, etc. If you don't want to take a lot of lessons, you can potentially just get a few lessons to get the techniques down, then transition to teaching yourself once you know the basics. But it is very hard to un-learn bad habits, and with classical guitar especially bad habits can severely limit your playing potential, so finding a quality teacher is going to be the best and most productive route.
There are a lot of good books out there, but it's difficult to know without feedback if you are doing things right so learning from a book by itself isn't easy. If you want to try a book, The Christopher Parkening Guitar Method and/or the Carcassi Classical Guitar Method are both popular choices. It would probably be useful to watch some video lessons as well, because it's much easier to explain proper technique with video examples than it is with text and pictures. There are a lot of good DVDs out there on the subject, and YouTube can be pretty useful as well. If you are going to teach yourself, you have to pay close attention to your posture and hand positions because those are crucial to proper classical guitar technique.
As for the usefulness of your prior theory knowledge, that will help, but not really in the beginning stages. When you first learn guitar the physical aspects of playing are very important, so the theory isn't as useful until you get the techniques down. With piano all you have to do is press the key and you get a note, so it's easy to transition to chords and scales very early in the learning process, but with guitar it takes more practice and effort just to make a single note, so you will have to spend a lot of time learning how to play before your knowledge of theory really becomes useful.
Finally, getting to the point where you can hear a song and instantly play it will take a lot of time and practice. I'm sure it took a while for you to get to that point in your piano playing, so it isn't much different with guitar. You will have a bit of a head start because you probably have a good ear from all your piano playing, but learning guitar technique and how to play by ear is a different skill than playing piano by ear.

Where to start from?


Custom arrangement for fields with multiple values in Drupal 7

Question: In Drupal 6 I used to make every sort of customised markup for CCK fields with multiple values. Usually this happened when I wanted to lay out thumnails for a gallery inside a table: I used to go into the relevant tpl.php file, grab the relevant $field_fieldname variable, loop through it, and print out the 'view' key for it, which contained the styled thumbnail, often linked to the original image and whatever.
Now, I'm a bit confused on how this should be done in Drupal 7. For now, I set up a suboptimal solution that goes like

    <?php foreach($content['field_gallery'] as $k => $v) : ?>
        <?php if(is_numeric($k)) : ?>
            <?php echo render($v) ?>
            <?php if((($k+1) % 4) == 0) : ?>

            <?php endif ?>
        <?php endif ?>
    <?php endforeach ?>

but it's obviously wrong. I can't seem to get my head around this, even after having read lots of docs about the Field API and theming for D7. Ideas?
Answer: You've got an explanation on how field_view_field and rendering api for fields work in this blog.
Here you've got an example (extracted from the link above):
$node = node_load($nid);
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);

You just need to loop over the $delta value for the fields to render them in a multiple valued field.
Comment: Anyway, this seems to be the most flexible approach I've seen so far, so I'm accepting the answer :) Thanks a lot.
Comment: Yes, I've seen that blog post, and it seemed the most likely approach, though I think it's a bit out of context. I mean, in a template you should try not to call API functions, and this, unless done in some preprocess function, requires you to write a bit more code than it's necessary in the template itself. I was hoping in a more D6-ish solution, like at most calling render() on some render array.
Comment: Ok, question: how do I configure it to work with Colorbox (and/or other lightbox plugins)? Using your third line, I get all the original images, not the thumbnails (and I've properly configure display settings in the Content Type settings). Using a display settings array things seem to get better, but I can't find what to use as image_link to make Colorbox pop up. Ideas?


What does this css selector do?

Question: I spotted this (to me) curious css style in the default Site.css file of an ASP.NET MVC project:
.text-box.multi-line
{
    height: 6.5em;
}

Is .text-box.multi-line just the name of a class that happens to have a dot in the middle of it, or is this a nesting of two classes? Or is it something else entirely? Can you explain?
And can you provide a usage example?
Edit
Thanks for all the answers. This seems to be an omission from the w3schools css reference page.
Comment: Regarding the omission.. it's not surprising, see: http://w3fools.com/
Comment: @DanM: Try SitePoint: http://reference.sitepoint.com/css/classselector that page discusses `div.foo.bar`.
Comment: @DanM sitepoint reference does :) @thirtydot great minds think alike.
Comment: thank you @thirtydot, wasnt aware there was so much against w3schools, i was personally, but nice to know there are a lot of others
Comment: @thirydot, thanks for that link. Interestingly, HTML Dog (one of the recommended sites) doesn't have what I was looking for either :(
Answer: it matches an item with both classes, ie.
<textarea class="text-box multi-line"></textarea>

It will not match if the item only has 1 of the classes.
It will match if the item has those two classes plus additional ones.
Answer: It means that the element has both classes.
It will select an element with the class text-box that also has the class multi-line
This would be the same:
.multi-line.text-box {}
.text-box[class~="multi-line"] {}

An example:

Answer: It's selecting an element like this:
<* class="text-box multi-line"></*>

Any element that has both the text-box and multi-line classes.
Answer: It will select this element:
<textarea class="text-box multi-line" />

Or any element with both the text-box and multi-line classes for that matter.
Answer: Here's a quick little fiddle to show the difference:
http://jsfiddle.net/sGn2v/
basically it'll match an element having BOTH classes!

What does this css selector do?


Examples of the case when expectation is infinite or doesn't exist.

Question: In Jacod&Protter's book, Probability Essentials. In page 52, one statement is we can have $E\{X\}=\infty$, even when $X$ is never equal to $+\infty$. Can anybody give an example here?
Also, let $X,Y\in L^1$, $XY$ need not be in $L^1$ in general. I fail to find an example to show this.
Comment: For the first, consider the discrete RV $X$ supported on $\mathbb{N}$ which takes the value $n$ with probability $6/(\pi n )^2.$ For the second, try to think of an $L^1$ function which is not $L^2.$
Comment: Consider a game where you flip a coin repeatedly until it comes up heads for the first time.  Count the number of tails you flipped and call it $k$.  You win $2^k$ dollars.  Try calculating the expected amount of money that you'll win in this game each time you play.
Comment: When it says X is never equal to infinity. Is it X is almost surely finite? That would help you understand and find examples I think
Comment: For the last, do you really mean $X,Y$ as random variables, or do you mean functions $f,g$?
Comment: @ClementC. I mean random variables.
Comment: @YHH https://math.stackexchange.com/questions/116237/the-product-of-integrable-random-variables-need-not-be-integrable
Comment: Note that you will never find a counterexample if $X,Y$ are independent. (Can you see why?)
Comment: @ClementC.I can see that. thanks for bringing it up.
Comment: After you ask a question here, if you get an acceptable answer, you should "accept" the answer by clicking the check mark ✓ next to it. This scores points for you and for the person who answered your question. You can find out more about accepting answers here: [How do I accept an answer?](http://meta.math.stackexchange.com/questions/3286/), [Why should we accept answers?](http://meta.math.stackexchange.com/questions/3399/), [What should I do if someone answers my question?](https://math.stackexchange.com/help/someone-answers).
Answer: Continuous: consider the "one-sided" Cauchy distribution with density function
$$
f(x) = \frac{2}{\pi}\frac{1}{1+x^2}\mathbb{1}_{[0,\infty)}
$$
(i.e., supported on $[0,\infty)$). Then we have
$$
\int_{[0,\infty)} xf(x)dx = \infty\,.
$$
Discrete: Consider the probability distribution over $\mathbb{N}$ with $p(n) = \frac{6}{\pi^2}\frac{1}{(n+1)^2}$ for $n\geq 0$. (This is the discrete equivalent of the above). Note that $$\sum_{n=0}^\infty np(n) = \infty\,.$$

As for the last question, note that you will never find a counterexample if you choose $X,Y$ to be independent. (Can you see why?) Now, using either Cauchy-Schwarz or the AM-GM inequality, one can also see that at least one of $X,Y$ needs to not be in $L^2$ (otherwise $XY$ will be integrable).
Based on these two observations, choose the simplest : $X=Y$ with $\mathbb{E}[|X|] < \infty$ but $\mathbb{E}[X^2]= \infty$. Examples abund, but take e.g. a discrete random variable $X$ on $\mathbb{N}$ with $\mathbb{P}\{ X = n\} = \frac{C}{(n+1)^3}$, for $n\geq 0$ (and the right normalizing constant $C>0$).


Filter .csv data based on user input and refresh d3.js map

Question: I am a d3.js noob and have been able to hack together a map for a project but now I'm stuck. I want to refresh the map based on user input/selection on any combination of five dimensions. Based on the user input, I want my code to filter to only the rows of data that meet the selected criteria, summarize the headcount for that geographic location and refresh the map. Due to various project constraints, I have to use .csv or .json as my data source. I know I can switch data sources and refresh the map based on user input, but due to the number of possible selection combinations that solution isn't feasible for my project. I think I'm close, but I'm not sure how to cross the finish line. I have stored the user selections in variables, created a d3.nest of my data and have been able to create d3.sums on a specified d3.nest key.
I think I've found posts that answer my questions but I'm too much of a noob to understand how to synthesize the relevant information for my project. What I need to do is dynamically create the d3.nest and d3.sum based on user-input, but I don't know how to link my user-selection variables to my function that creates the nest & sum. I'd like to refresh the map and data each time the user makes a selection, but I'd be open to putting a button on the screen that refreshes the data if that's easier. Here is a screenshot of my map map sample.
Here are the relevant sections of my code:
        // ######################################################################
    // BUILD THE MAP, PLOT THE DATA AND SIZE THE BUBBLES
    // ######################################################################

    var projection = d3.geo.mercator()
        .center([0, 0])
        .scale(225)
        .translate([width / 2, height / 2]);

    var path = d3.geo.path()
        .projection(projection);

    // LOAD THE GEOJSON DATA FOR THE MAP
    // ---------------------------------
    d3.json("world-50m.json", function ready(error, world) {

        g.selectAll('path')
            .data(topojson.feature(world, world.objects.countries).features)
            .enter().append('path')
            .attr("id", function(d) {
                return d.properties.abbreviation;
            })
            .attr("d", path)
            .attr("fill", "#ffcc99")
            .attr("stroke", "#ffffff")
            .on("click", clicked);

        // LOAD THE CSV DATA TO POPULATE THE LOCATIONS
        // AND BUBBLE SIZES ON THE MAP
        // -------------------------------------------
        d3.csv("sample_data.csv", function(data) {

            // INCLUDE ONLY THOSE ROWS OF DATA WITH
            // LATITUDE AND LONGITUDE VALUES AND CONVERT
            // CSV DATA INTO NUMERIC VALUES
            // -----------------------------------------
            data = data.filter(function(d, i) {

                if (d.LATITUDE && d.LONGITUDE) {

                    // CONVERT LATITUDE AND LONGITUDE
                    // VALUES FROM CSV FILE TO NUMBERS
                    d.LATITUDE = +d.LATITUDE;
                    d.LONGITUDE = +d.LONGITUDE;

                    // CONVERT HEADCOUNT VALUES FROM
                    // CSV FILE TO NUMBERS
                    d.HEADCOUNT = +Math.round((d.HEADCOUNT) * 1) / 1;

                    // CALCULATE THE POSITION OF THE
                    // HEADCOUNT DATA POINT WITHIN
                    // THE PROJECTION
                    d.position = projection([
                        d.LONGITUDE, d.LATITUDE
                    ]);

                    return true;
                }
            });

            // DRAW THE CIRCLES ON THE MAP AND SIZE THEM
            // BASED ON HEADCOUNT
            // -----------------------------------------
            g.selectAll("circle")
                .data(data)
                .enter().append("circle")
                .attr("cx", function(d) {
                    return d.position[0];
                })
                .attr("cy", function(d) {
                    return d.position[1];
                })
                .attr("r", function(d) {
                    return (bubblescale(d.HEADCOUNT));
                })
                .attr("fill", "#b300b3")
                .attr("fill-opacity", "0.7")
                .on("mouseover", function(d) {
                    div.transition()
                        .duration(200)
                        .style("opacity", .9);
                    div.html(d.HEADCOUNT + " people in " + d.GEOCODE_LOCATION)
                        .style("left", (d3.event.pageX) + "px")
                        .style("top", (d3.event.pageY - 28) + "px");
                })
                .on("mouseout", function(d) {
                    div.transition()
                        .duration(500)
                        .style("opacity", 0);;
                });
        });

    });

    // ######################################################################
    // NESTING, FILTERING AND SUMMARIZING DATA
    // ######################################################################

    d3.csv("sample_data.csv", function(csv) {

        var data_nest = d3.nest()
            .key(function(d) {
                return d.GEOCODE_LOCATION;
            })
    .key(function(d) {
                return d.CATEGORY1;
            })
            .key(function(d) {
                return d.CATEGORY2;
            })
            .key(function(d) {
                return d.CATEGORY3;
            })
            .key(function(d) {
                return d.TYPE1;
            })
            .key(function(d) {
                return d.TYPE2;
            })
            .sortKeys(d3.ascending)
            .entries(csv);
        console.log(data_nest);

        var data_sums = d3.nest()
            .key(function(d) {
                return d.GEOCODE_LOCATION;
            })
    .key(function(d) {
                return d.LONGITUDE;
            })
    .key(function(d) {
                return d.LATITUDE;
            })
            .sortKeys(d3.ascending)
            .rollup(function(d) {
                return {
                    headcount: d3.sum(d, function(g) {
                        return +g.HEADCOUNT;
                    })
                };
            })
            .entries(csv);
        console.log(data_sums);

    });

    // ######################################################################
    // POPULATE THE FIVE MENU LISTS
    // ######################################################################

    function load_menus() {
        d3.csv("category1.csv", function(error, data_c1) {

            var select = d3.select("#c1_div")
                .append("div")
                .append("select")

            select
                .on("change", function(d) {
                    var selected_c1 = d3.select(this).property("value");
                    alert(value);
                });

            select.selectAll("option")
                .data(data_c1)
                .enter()
                .append("option")
                .attr("value", function(d) {
                    return d.x;
                })
                .text(function(d) {
                    return d.x;
                });
        });

        d3.csv("category2.csv", function(error, data_c2) {

            var select = d3.select("#c2_div")
                .append("div")
                .append("select")

            select
                .on("change", function(d) {
                    var selected_c2 = d3.select(this).property("value");
                    alert(value);
                });

            select.selectAll("option")
                .data(data_c2)
                .enter()
                .append("option")
                .attr("value", function(d) {
                    return d.x;
                })
                .text(function(d) {
                    return d.x;
                });
        });

        d3.csv("category3.csv", function(error, data_c3) {

            var select = d3.select("#c3_div")
                .append("div")
                .append("select")

            select
                .on("change", function(d) {
                    var selected_c3 = d3.select(this).property("value");
                    alert(value);
                });

            select.selectAll("option")
                .data(data_c3)
                .enter()
                .append("option")
                .attr("value", function(d) {
                    return d.x;
                })
                .text(function(d) {
                    return d.x;
                });
        });

        d3.csv("type1.csv", function(error, data_t1) {
            var select = d3.select("#t1_div")
                .append("div")
                .append("select")

            select
                .on("change", function(d) {
                    var selected_t1 = d3.select(this).property("value");
                    alert(value);
                });

            select.selectAll("option")
                .data(data_t1)
                .enter()
                .append("option")
                .attr("value", function(d) {
                    return d.x;
                })
                .text(function(d) {
                    return d.x;
                });
        });

        d3.csv("type2.csv", function(error, data_t2) {
            var select = d3.select("#t2_div")
                .append("div")
                .append("select")

            select
                .on("change", function(d) {
                    var selected_t2 = d3.select(this).property("value");
                    alert(value);
                });

            select.selectAll("option")
                .data(data_t2)
                .enter()
                .append("option")
                .attr("value", function(d) {
                    return d.x;
                })
                .text(function(d) {
                    return d.x;
                });
        });
    }

    window.onload = load_menus;

    // ######################################################################
    // FILTER DATA BASED ON USER SELECTION - NOT WORKING
    // ######################################################################

    function filter_data() {
        d3.csv("map_data.csv", function(error, data) {
            var filterCategory1 = selected_c1;
            var filterCategory2 = selected_c2;
            var filterCategory3 = selected_c3;
            var filterType1 = selected_t1;
            var filterType2 = selected_t2;

            var filtered_data = data.filter(function(d) {
                return d.CATEGORY1 == filterCategory1;
            })
        });
    }

Here is a screenshot of my sample data:
sample data
I've been searching online and in books for over a week now and have neither found other D3 examples of what I'm trying to do nor answers to my data binding, filtering and aggregation questions.
Any help is appreciated. I promise I'll pay it forward when I have the skillz to do so. If I can get this working I'll happily post my full solution on github and link to it from this question.
Answer: It seems to me that your problem here is not specifically D3, but JavaScript scope.
When you write something like:
 d3.csv("category1.csv", function(error, data_c1) {

        var select = d3.select("#c1_div")
            .append("div")
            .append("select")

        select
            .on("change", function(d) {
                var selected_c1 = d3.select(this).property("value");
                alert(value);
            });

That variable selected_c1 exists only inside the anonymous function that contains it. A local variable can only be used inside the function where it is defined. It is hidden from other functions and other scripting code (see here: http://www.w3schools.com/js/js_function_closures.asp).
Thus, when you try to use it later, inside filter_data(), it's not available.
A solution here is passing selected_c1 and all the other 4 variables to filter_data as an argument. It could be something like this:
 d3.csv("category1.csv", function(error, data_c1) {

        var select = d3.select("#c1_div")
            .append("div")
            .append("select")

        select
            .on("change", function(d) {
                var selected_c1 = d3.select(this).property("value");
                filter_data(selected_c1);
            });

And then, change your filter_data() parameter:
function filter_data(selection) {
    d3.csv("map_data.csv", function(error, data) {

        var filtered_data = data.filter(function(d) {
            return d.CATEGORY1 == selection;
        })
    });
}

Keep in mind that despite you successfully passed selected_c1 to filter_data(), you now face the same problem again: var filtered_data exists only inside filter_data, and you have 2 options to pass it to your drawing function:

Making it global;
Passing it as an argument.

This is just a partial answer, you still have some hard work ahead putting all this together.
Comment: Thanks again Gerardo for your input.  I still have a lot to do, but your response pointed me in the right direction.  I'm able to store the selected values now and pass them to the necessary function.  My d3.nest and d3.sum functions are being fussy about how I'm passing them the data but once I figure that out I should be well on my way to finishing.  As promised, I will post the final code and sample data on github for anyone else who'd find this type of online functionality helpful.
Comment: Thanks for the response Gerardo!  I will give this a try.  Your time is very much appreciated.
Comment: No worries. I believe you need to do a sketch of all your code, deciding what function does what, and putting some functions inside others, for using their scope.


Custom a shape for the imageView

Question: How can I leave my imageview in this format, without the image "overflowing" the sides and occupy all space
here is the shape
Answer: If you arleady have the shape, you can add it as src in ImageView, and the image set as background of the same ImageView. Because the image is in front of the background.
Answer: Set.. android backgroud the purple image and app:src the middle image in imageview.. Hope it helps

Custom a shape for the imageView


barra de rolagem altera ajuste de conteúdo

Question: Olá, pessoal!
Quero que a barra de rolagem da minha div só apareça quando o hover for ativado e até ai tudo bem. O problema é que quando o a barra de rolagem aparece, o conteúdo da div é jogado pra o lado e eu não queria isso. Aqui está um exemplo do que acontece junto com uma parte do código:
https://jsfiddle.net/gabigbe/9rk2y7ms/27/

div>span {
  color: var(--cor-branca);
  font-family: var(--fonte-light);
  text-align: justify;
  font-size: 100%;
  letter-spacing: 1px;
}

h4>span {
  font-family: var(--fonte-regular);
  color: var(--cor-branca);
}

div>b {
  color: var(--cor-branca);
  font-family: var(--fonte-regular);
}

.grid {
  width: 100%;
  height: 100%;
  border-style: solid;
  border-radius: 2px;
  border-width: 2px;
  border-color: #a8a8a8;
  padding: 10px;
  margin: 15px;
}

.filter {
  display: flex;
  flex-wrap: nowrap;
  margin: 10px;
  align-items: center;
  width: 95%;
}

.selected {
  border-color: var(--cor-amarelo) !important;
  color: var(--cor-amarelo) !important;
}

/*scrollbar*/

::-webkit-scrollbar {
  width: 5px;
}

/*caminho*/

 ::-webkit-scrollbar-track {
  background: #3d3d3d;
}

/*barrinha*/

 ::-webkit-scrollbar-thumb {
  background: #666666;
  border-radius: 50px;
}

.scroll {
  overflow: hidden;
  width: calc(100% - 5px);
}

.scroll:hover {
  overflow-y: scroll;
  width: 100%;
}

NOME DO GRÁFICO

         FILTRAR DE
        <input type="date" class="form-control date" />
            ATÉ
        <input type="date" class="form-control date" />

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam congue orci a
              egestas vestibulum. Aliquam laoreet quis lacus vel pellentesque.

Alguém pode me ajudar a resolver esse problema?
Obs.: estou usando bootstrap também.
Answer: Você pode diminuir o tamanho do containner quando a barra de rolagem não aparecer, e aumentar quando ela aparecer:
.scroll{
    overflow: hidden;
    width: calc(100% - 5px);
}
.scroll:hover{
    overflow-y: scroll;
    width: 100%;
}

O 5px é o tamanho do scroll, se for mudar o tamanho dele, precisa alterar aqui também


Segmentation fault while trying to implement fixed size queue in C++

Question: I wanted to implement a fixed size queue, I could have easily done with a struct having a queue as one of the data members and a member function that takes care of the push part of the queue, but rather wanted to try it out by inheriting queue like this.
template<typename T>
struct f_queue : public queue<T>{
    int n;
    T prev;

    f_queue(int n_):
        n(n_){}

    void push(T data){
        if(this->size() < this->n){
            this->push(data);
        }else{
            prev = this->front();
            this->pop();
            this->push(data);
        }
    }
};

This compiles just fine but for some reason it gives a segmentation fault and the gdb says

Program received signal SIGSEGV, Segmentation fault.
0x0000555555555862 in std::_Deque_iterator<int, int&,
int*>::_S_buffer_size() ()

Not really sure what that is supposed to mean? When tried doing a backtrace the output comes out to be
#9913 0x0000555555554ec6 in f_queue<int>::push(int) ()
#9914 0x0000555555554ec6 in f_queue<int>::push(int) ()
#9915 0x0000555555554ec6 in f_queue<int>::push(int) ()
#9916 0x0000555555554ec6 in f_queue<int>::push(int) ()
#9917 0x0000555555554ec6 in f_queue<int>::push(int) ()
#9918 0x0000555555554ec6 in f_queue<int>::push(int) ()
#9919 0x0000555555554ec6 in f_queue<int>::push(int) ()

doesn't stop goes infinitely. Need help with this.Thanks in advance.
Comment: You introduced a recursion (probably unintended) with `this->push(data);`. I assume, you actually want `queue::push(data);` to refer to `push()` of base class.
Answer: Your push function always recurses into itself:
void push(T data){
        if(this->size() < this->n){
            this->push(data);//HERE f_queue::push is called
        }else{
            prev = this->front();
            this->pop();
            this->push(data);//HERE f_queue::push is called
        }
    }

You probably meant to call the base class's push:
void push(T data){
        if(this->size() < this->n){
            queue<T>::push(data);
        }else{
            prev = this->front();
            this->pop();
            queue<T>::push(data);
        }
    }

Note that STL containers are not  meant to be publicly derived from. They do not have virtual destructors, so make sure you never delete through the base class pointer/reference.
EDIT
Non-virtual destructor means the  following code is dangerous:
std::queue<T>* base = new f_queue<T>();
delete base;//Call std::queue<T>::~queue();

There is no way how to force the call of the correct destructor. Making f_queue's destructor virtual will not help. But, as long as you never delete through a pointer to the base class, there is nothing wrong with deriving from any class.
One way to enforce that is to use private inheritance but I'm guessing you are using inheritance in the first place to retain most of the std::queue's API.
Comment: Thanks @Quimby, just a question about destructor, you mentioned that STL containers don't have virtual destructor, so unless I am overriding the destructor for the base class (here queue) , there is no issues with this implementation right?
Comment: @Bad_Panda Expanded my answer. This has almost nothing with to do with override. And to be pedantic, destructors cannot be overriden, deleting a given class always calls all destructors of the base classes.


Linq error when returning a List inside a List

Question: I have a class defined as follows:
public class SearchResult
{
    public Customer Customer { get; set; }
    public Receipt Receipt { get; set; }
    public IEnumerable<ReceiptDetail> ReceiptDetail { get; set; }
}

In my Linq query i would like to return a single SearchResult record but have problems in returning the List of ReceiptDetail. If i do:
 var list=(from cust in dbContext.Customers
     join rec in dbContext.Receipts on cust.IdCustomer equals rec.IdCustomer
     join recdet in dbContext.ReceiptDetails on rec.IdReceipt equals recdet.IdReceipt
     select new SearchResult
     {
          Customer=cust,
          Receipt=rec,
          ReceiptDetail = (from  r1 in recdet select r1).ToList() // COMPILER ERROR HERE
     }).ToList();

I get the "Could not find an implementation of the query pattern for source type ReceiptDetail   'Select' not found".
What am i doing wrong?
Answer: Well, recdet comes from here:
join recdet in dbContext.ReceiptDetails on rec.IdReceipt equals recdet.IdReceipt

That means it's a single receipt detail. You're then trying to use it as a collection here:
from  r1 in recdet select r1

I suspect you actually want a group join:
join recdet in dbContext.ReceiptDetails on rec.IdReceipt equals recdet.IdReceipt
  into recdets
...
ReceiptDetail = (from  r1 in recdets select r1).ToList()

or more simply for the latter part:
ReceiptDetail = recdets.ToList()


C# Use generic that references itself in concrete class declaration

Question: Coming from Java, I think I should be able to do something like this:
using System.Collections.Generic;

interface ICoord<T> where T : ICoord<T>
{
    ICollection<T> GetNeighbors();
}

class SquareCoord : ICoord<SquareCoord>
{
    public ICollection<SquareCoord> GetNeighbors() {
        throw new System.NotImplementedException();
    }
}

interface IGrid<T> where T : ICoord<T>
{
    List<T> GetGrid();
}

// This works no problem (everything is concretely defined)
class SquareGrid : IGrid<SquareCoord>
{
    public List<SquareCoord> GetGrid() {
        throw new System.NotImplementedException();
    }
}

class Grid : IGrid<ICoord>
{
    public List<ICoord> GetGrid()
    {
        //do stuff
    }
}

where the last class Grid should be able to operate and return a List of any (concrete implementation of) ICoord.
I have a small working example in Java. If I could get the equivalent (if possible) in C#, that would give me enough to go on.
public class Example {
    private interface Index<T extends Index> {
        List<T> GetNeighbors();
    }

    private static class SquareIndex implements Index<SquareIndex> {
        public List<SquareIndex> GetNeighbors(){
            return new ArrayList<>();
        }
    }

    private interface Grid<T extends Index> {
        List<T> GetGrid();
    }

    // Java does not require a type parameter to implement "Grid"
    private static class MyGrid implements Grid {
        // Java allows me to satisfy the requirements for implementing "Grid"
        // without having a concrete type defined in the method declaration.
        public List<? extends Index> GetGrid() {
            final List<SquareIndex> result = new ArrayList<>();
            result.add(new SquareIndex());
            return result;
        }
    }

    public static void main(String[] args) {
        MyGrid g = new MyGrid();
        g.GetGrid();
    }
}

Answer: My excellent girlfriend just figured it out:
class MyGrid<T> : IGrid<T> where T : ICoord<T>
{
    public List<T> GetGrid() {
        throw new System.NotImplementedException();
    }
}


Algebraic characterization of the exterior covariant derivative

Question: The de Rham complex on a smooth manifold $M$ is a complex of sheaves of $\mathbb{R}$-modules, which I will denote by $$\Omega^\bullet \xrightarrow{d} \Omega^{\bullet+1}.$$
A connection (not assumed to be flat!) on a vector bundle $E \to M$ with sheaf of sections $\mathcal{E}$ can be given by a covariant derivative, which is an $\mathbb{R}$-linear sheaf homomorphism:
$$\mathcal{E} \xrightarrow{\nabla} \mathcal{E} \otimes_{\mathcal{C}^\infty} \Omega^1 .$$
Is there an algebraic (in terms of category theory, sheaves and/or homological algebra) way to characterize the construction of the exterior covariant derivative
$$\mathcal{E} \otimes_{\mathcal{C}^\infty} \Omega^\bullet \xrightarrow{d^\nabla} \mathcal{E} \otimes_{\mathcal{C}^\infty}\Omega^{\bullet+1}$$
from this data?
Naively, we might just stick stick zero sheaves on either side of the covariant derivative to get a complex, and then tensor with the de Rham complex (over the constant sheaf $\mathbb{R}$). But this is obviously wrong because we get a complex, and the connection is not assumed to be flat. Even in the flat case it is easy to see by looking at the individual sheaves that this approach gives the wrong complex.
Answer: For aesthetic reasons, I prefer to use $\Omega^{*} \otimes \mathcal{E}$ (you'll see immediately why) so let me do that. Note that $\Omega^{*} \otimes \mathcal{E}$ has the structure of a left graded $\Omega^{*}$ module and denote the corresponding product between a $k$-form an an $E$-valued $l$-form (resulting in an $E$-valued $(k + l)$-form) by $\wedge$. Then $d^{\nabla}$ is the unique operator which satisfies
$$ d^{\nabla}(\omega \otimes \xi) = d\omega \otimes \xi + (-1)^{|\omega|} \omega \wedge \nabla \xi = d \omega \wedge \xi + (-1)^{|\omega|} \omega \wedge \nabla \xi.$$
for all homogeneous $\omega \in \Omega^{*}(U)$ and $\xi \in \mathcal{E}(U)$. In other words, $d^{\nabla}$ extends $\nabla$ to a "degree $1$ graded derivation with respect to $d$".
Comment: Well, the formula above defines $d^{\nabla}$ explicitly for all $E$-valued $k$-forms. I wrote the "degree 1 graded derivation" in quotes because usually one considers graded derivations on some graded algebra (so that $d(ab) = da \cdot b + (-1)^{|a|} a \cdot db$ makes sense). In our case, this is only a graded left-module. I'm not an algebraist so I don't know if there is a proper terminology for this case.
Comment: Thanks! Does the existence of this unique operator follow from some sort of universal property?


What is the difference between samples, interpolations, elements and portions?

Question: When reading album booklets, I often see different terms being used to indicate some sort of sample.
One thing I'm pretty sure about:

A sample is a piece of a recording reused in another recording. It usually gives credit to both the authors of the work and the performers of the original recording.
An interpolation is a replayed piece of a recording meant to sound exactly the same as the recording to avoid copyright clearances. It usually gives credit to the authors of the work but not to the performers of the original recording. In a sense, this could be considered as a (partial) cover version of a work.

But how do elements and portions fit the "sample" definition? Sometimes they only credit the authors of the work, other times they credit the original performers, which is pretty confusing.
Examples from discogs:
http://www.discogs.com/Jennifer-Lopez-This-Is-Me--Then/release/1104590
http://www.discogs.com/Erykah-Badu-New-Amerykah-Part-Two-Return-Of-The-Ankh/release/2205137
Answer: This is how I've always interpreted it: samples and interpolations ARE elements and portions, but not all elements and portions are samples and interpolations. Example: I replay the melody from Lollipop by Lil' Wayne. If I try to make it sound like that version, it's interpolating. If I make it sound different while still playing the same notes, it's just an element. If I add all of the elements playing in that part of the song at once, it's a portion. If I completely use the audio in the original song, that's a sample.
Comment: Although from an ear's and author's perspective the difference between elements an portions is still debatable, I think your answer is the best you can get, thanks!
Answer: You're right on about the sample definition. Interpolation, however, can take on several definitions in different styles:
From Wikipedia

Classical Music-- an abrupt change in elements, followed almost immediately by a continuation of the first idea.
Pop Music-- the addition of new material in a performance or recording of a previously existing piece of music.
Rap Music-- using a melody – or portions of a melody (often with modified lyrics) – from a previously recorded song, but re-recording the melody instead of sampling it.

An element is a part of the song in a way. It is like a drum solo or a chord progression. A song is made of elements. Some are general, such as counterpoint, others are almost musicians' signatures such as certain drum beats. A portion is basically the same as a sample, but it usually tends to mean something longer. A portion of a song might be the second stanza, but a sample might be the third verse.
Comment: In a strict musical sense, I follow your definition of an interpolation. But in a "sample" sense, I tend to follow the Wikipedia definition: _In rap music, interpolation refers to using a melody – or portions of a melody (often with modified lyrics) – from a previously recorded song, but re-recording the melody instead of sampling it._
Your definition of elements and portions don't really differ from a "sample" in general, so why are they indicated as such in the booklets?
Comment: Are you looking for genre specific definitions?
Comment: Not really, because these terms are used in booklets of releases from different genres (not only rap music). I just don't understand how elements and portions differ from samples and interpolations.
Answer: I think sample means to take a part from a song and add it to another song
Interpolation on the other hand is taking a songs melody and adding different lyrics to it
Answer: An interpolation refers to the use of the underlying written material which is re-recorded instead of sampled or modified lyrically or musically. Hints the writers of the work are credited and the title is listed
A sample I s usually the sound recording that is used. It credits the writers and original performers. A portion is usually longer such as no more drama by Mary j blige uses portions of the young and the restless theme. An element is usually a single part


definition of $_Ahom(A\otimes_BA,A)$ and $_Bend(A)$

Question: Let $H$ be a $K$-Hopf Algebra, $A$ a right $H$-comodule algebra and $l:B\rightarrow A^{coH}$ a ring morphism.
Then $_Ahom(A\otimes_BA,A)\cong\ _Bend(A)$
I don't even know what this means.
$_Bend(A)$ is the set of $K$-linear maps from $A$ to itself to which we add $$ +:\ _Bend(A)\times\ _Bend(A)\rightarrow\ _Bend(A) : (\phi,\varphi) \rightarrow (x \rightarrow \phi(x) + \varphi(x)) \\ \cdot:\ _Bend(A) \times B\rightarrow \ _Bend(A): (\phi, b) \rightarrow (x\rightarrow\phi(x)l(b))$$ i.e. $_Bend(A)$ is the (right) $B$-vector space of K-linear maps from $A$ to itself?
For $_Ahom(A\otimes_BA,A)$ I don't really know what it could be. $A$ is a vector space over $K$ so we have to see $A\otimes_BA$ as a vector space over K for linear applications from $A\otimes_BA$ to $A$ to make any sense. But for me $A\otimes_BA$ doesn't make any sense since $A$ is not a vector space over $B$.
1) is my definition of $_Bend(A)$ correct?
2) How can we give any sense to $_Ahom(A\otimes_BA,A)$
Comment: It would be helpful for potential answerers to add some more context. For example what course you are taking and what textbook(s) you are using.
Answer: This is not an answer, but I'm writing it here since it's too long for a comment.
$A$ is an right $H$-comodule algebra. So in particular $A$ is a right $H$-comodule. Hence we can look at the coinvariants, i.e. $A^{\text{co}H}=\left\{a\in A\mid \rho(a)=a\otimes 1\right\}$. Here $\rho$ denotes the coaction on $A$ that makes it a right $H$-comodule. As $A$ is also an algebra is has a product, hence $A^{\text{co}H}$ also has a product. Show that $A^{\text{co}H}$ is an algebra and hence also a ring.
Now consider a ring morphism $l:B\rightarrow A^{\text{co}H}$. Via this map we can view $A$ as a $B$-module. Indeed, $b\cdot a:=l(b)a$ for $b\in B$ and $a\in A$, $l(b)a$ is defined since $A$ is an algebra. Then we can interpret $_B\text{End}(A)$ simply as the endomorphisms of the $B$-module $A$. Likewise $A\otimes_B A$ is the tensor product of the $B$-modules $A$ and $_A\text{Hom}(A\otimes_B A,A)$ are the $A$-linear maps from the $A$-module $A\otimes_B A$ to the $A$-module $A$.
Now I'm not sure whether this is the correct interpretation, some more information or context could be useful. But this seems to make sense. If you can show that $_A\text{Hom}(A\otimes_B A,A)\cong\  _B\text{End}(A)$ holds with this interpretation, it's probably the correct on.
Comment: I'm having a really hard time juggling with all these structures which are equivalent. (I can't remember seing the tensor product of two modules but I suppose it's the same idea as tensor product between two vector spaces)