MSMQ slow queue reading

Question: I am using an open source .Net library which uses MSMQ underneath.  After about a week or 2, the service slows down (not timed exactly but general guess).  It appears that what is happening is messages from MSMQ are only being read exactly once every 10 seconds.  Normally, they are read instantly.  So they will be read at T+10sec, T+20sec, T+30sec, etc. independent of when the message was sent (i.e. sometimes it takes 3 seconds for the message to be read, other times 9 seconds).
The current way I get it back to normal is simply deleting & recreating the queues.  So the question is, what can build up in MSMQ queues to cause this kind of slow down?  There are no messages in the queues when the slowdown occurs.  Are there any advanced MSMQ analysis tools that give you a deeper look at the queues (as opposed to Computer Management)?
Oh, I forgot to mention, writing the messages to the queue still appears to be instantaneous.  It is just reading the messages which shows this behavior.
EDIT: Follow up question @ here which is a bit more detailed and more focused.
Comment: On what memory-size is the MSMQ process limited?
Comment: I'm not sure what you mean?  Where can I check the memory limitations of MSMQ?
Comment: Are you sure the problem is in MSMQ and not the open source library you're using?  Have you stepped over the code that is actually reading from MSMQ and confirmed that is where the delay is?
Comment: there is a possibility its a problem in C# but it appeared to me to be MSMQ related because of the way it's fixed.  I'd imagine if it was a C# problem that deleting/recreating the queue would not fix it.  Unfortunately I don't know enough about MSMQ or the library to investigate this fully, but nobody else has this problem using the library which would point to MSMQ also (or specifically, my setup).  If I ever manage to sort this out I will post the solution!
Comment: See http://stackoverflow.com/questions/1794307/c-net-msmq-receive-method-timeout-problem for a more detailed & on track version of the question as I believe I have narrowed down where the problem is occuring a fair bit.
Answer: It has been a while since I did MSMQ stuff so bear with me (be tolerant) of my old brain memory.
Some questions come to mind:
Is the journal queue active?  This is tied to a queue and if the queue is removed, I believe (don't quote me) that the journal then starts from empty...
Is there a Purge process on the queue?
Are these transactional queues?
Are all current service packs applied?  I seem to recall a fix on a service pack for this in the distant past. It is probably platform dependent but you do not list your platform.
I believe there were several service packs of this nature.
What is your disk space like?  Are you getting into a disk space issue or a fragmented disk issue? Files (if I remember) are stored in under windows\system32\msmq. If there are not enough blocks of the size needed, it might slow down - usually on store /receipt of the message, not sure about reads.
Are these public or private queues?
What does performance monitor say about paged pool etc?  I believe it is 70-80 bytes per message.
EDIT 1:
from the MSDN document archives:
"Private queues are registered on the local computer, not in the directory service, and their properties cannot be obtained by Message Queuing applications running on remote computers. Message Queuing registers private queues locally by storing a description of each queue in a separate file in the local queue storage (LQS) folder on the local computer."
Thus, if the directory service is down, public queues are not available.  Private queues on the other hand are stored in the local file system.
This machine should have a LOT of memory to avoid disk swap of the queue.  I have never tried to run MSMQ on an Windows XP box frankly due to the issue of performance - have always had it executing on a dedicated server box with a LOT of memory - but then, we were working with a large set of queued items, of large size each. (many thousands, near the limit in size each)
EDIT 2:  File system and empty files:
"Empty message files are deleted once every six hours, by default. This time interval can be controlled in the registry by setting the MessageCleanupInterval REG_DWORD value under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSMQ\Parameters. Applications should not keep cursors opened unnecessarily for a long time. Cursors might point to messages that were already received (and removed from files). These pointers prevent cleanup and deletion of empty files.
NOTE:  You should have a significant amount of free space on the disk this is running on to prevent fragmentation issues.  You COULD TRY reducing this 6 hour time frame to see if that helps - so it does not have to keep track of empty files.
Try to make sure there is not any other activity on the machine which might fragment the drive - such as browsing the Internet.
On a public queue, sometimes this is extended to avoid the expense of Active Directory interaction which can be expensive.
You need to add this registry value on both ends of a Message Queuing session. Otherwise, the computer with the smallest value will stop the session prematurely. A common reason to add this registry value with a large value is to keep sessions alive and avoid the overhead of creating Message Queuing sessions.   In your instance, you might need to shorten the value to aid in file systems management. (This is a hard call to make, and frankly needs to be made with consideration).
As for hot fixes:
 (probably more out there, and not specific to your problem that I can see)
The MSMQ 1.0 hotfix described in http://support.microsoft.com/kb/304212.
The reason for this hotfix is that Windows XP Message Queuing 3.0 independent clients are built as robust RPC clients. Without this hotfix, calls from Windows XP Message Queuing 3.0 independent clients to MQLocateNext fail.
The RPC hotfix is described in http://support.microsoft.com/kb/823980.
This hotfix is required to enable auditing on the client running Windows XP. This hotfix is also required to enable clients running Windows 2000 to complete Setup.
One thought: what does the Performance monitor say about your memory status issues?  Is there a lot of disk swapping going on there?
Comment: Please excuse my lack of knowledge also, as I'm no MSMQ expert and only know/use it via this 3rd party library.

- Journal is disable & there are no journal messages

- If by purge you mean messages are removed?  There are 0 messages in the queue & the slowdown still occurs.  They are transactional queues.

- I'm pretty sure my computer is patched.  Are there specific MSMQ patches to download?  Computers are Win. XP

- Plenty of disk space, fragmentation might be an issue but I doubt it

- Private

- Care to explain?
Comment: Sorry that last comment didn't format well... I've also found a tool called TMQ which seems to do some extra analysis.  When the slowdown occurs again I will try debugging further.
Comment: Yep, here is a link to a MS page detailing a lot of stuff regarding performance, memory, how it is managed etc.
http://msdn.microsoft.com/en-us/library/ms811056.aspx

More details on message size, numbers etc. might be useful, as well as examination of the file system where the stores are maintained.
Comment: Just an FYI, you can spend days on tedious examination and diagnosis with MSMQ observing different patterns and isolating issues.  So many factors here to consider.
Comment: Thanks for the thorough answers.  RE: EDIT 1, I don't think it's a memory issue as the problem occurs when the queues are empty.  RE: EDIT 2, I will check the disk fragmentation.  At the moment I am just waiting for it to occur again so I can try to detect anything unusual.

MSMQ slow queue reading


regular expressions and words in the language

Question: Consider the regular expression ((AB)* (C(A*) |B))*
Give three words (over the alphabet {A,B,C}) that are in the language of this expression, and three that are not (and label them accordingly).
Translate the language into an NFA.
I got ABABCAAB, ABABCAAAAB and ABCABABCABABCAB for words that are in the language and :
ABC, ABCCAB and ABCCABBB for words that are not in the language. Am i correct? also not sure which language is being referred to , to translate into an NFA
thank you all , i see where i went wrong
Comment: Stars indicate any number of occurrences, even zero, as I understand.  As such, `ABC` is actually a word in your language.  So are the rest of your examples for that matter...  For an example of a word that actually is *not* included in your language, consider `BA`.
Comment: @Magma Incorrect.  Look at the parentheses more closely.  The word $B$ is included in the language.  $(~~(AB)^*~~(C(A^*)~|~B)~~)^*$.  It is zero occurrences of $AB$ followed by the second option of the second term.
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Answer: Stars represent any number of occurrences of what precedes, including zero.
In your language, each of your examples of attempts of words which are not included in the language are incorrect.
$(~~(AB)^*~~(C(A^*)~|~B)~~)^*$
Since zero occurrences of something with a star is allowed., here are a few more examples of words that are included in your language.
$\varepsilon,~B,~C,~AB,~CA,~ABB,~ABC,~BAB,~BBB,~BBC,~BCA,~BCB,~BCC,~CAA,~CAB,~CAC,\dots$
And the list continues.
Now... most of these letters can follow most of the other letters... however there are some catches.  If an $A$ appears, it must satisfy one of three conditions, it either immediately precedes a $B$, it immediately follows an $A$, or it immediately follows a $C$.
Examples of words which do not follow this rule:
$A,~AA,~BA,~AAA,~AAB,~AAC,~ABA,~BAA,\dots$
Answer: I'm assuming you understand what the regular expression says.
For "words in the language", start with the simplest (shortest) ones. Clearly, it is a $()^*$, so $\epsilon$ (the empty word) will do.
Next simplest is the outer parenthesis repeated once, then twice, ... In this case, repeated once you can take $\epsilon$ for $(AB)^*$, need to select one of the alternatives for the second part, $C A^*$ (pick $C$ as simplest) or $B$. Can also combine with one or more $AB$, ...
For "words not in the language", you can do the same. I.e., non-empty that do not start $AB$ (like $BA$, just $A$, ...). The expression is several times $A B$ followe by $C$ and $A$s or $B$. It is a bit harder, a way to do it is to come up with some candidate and check it can't be described by the expression.
There are algorithms to translate from a regular expression to a NFA, or you can draw the automaton from your understanding of the expression.


Can't ping static IP from internal network, only from outside

Question: I'm running ubuntu and I have apache running, however, I can't ping internally to my static IP nor browse http://207.40.XXX.XX the web server using my static IP. I can only ping/browse localhost, 127.0.0.1, and 192.168.0.120 OR 207.40.XXX.XX only from the outside world.
# cat /etc/hosts
127.0.0.1       localhost
127.0.1.1       my-server.myhost.com my-server

# hostname
my-server

# netstat -tapn
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      -
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      -
tcp        0      0 127.0.0.1:29754         0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      -
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN

Any ideas why this is not working?
Comment: Your question is poorly asked, but this may have your answer. http://serverfault.com/questions/167601/no-ip-works-for-non-internal-clients-pinging-works-internally/167607#167607 If you feel this is not the answer please tell us what IP addresses are configured directly on the Ubuntu box.
Comment: @Zoredache: As the link mentions, NAT Hairpinning might be the problem.
Answer: Your NAT-gateway is not behaving in such a way as to allow it. This is how it is probably working:
Ping

You send an ICMP Echo request from 192.168.0.5 to 126.96.36.199
This routes by way of your router.
Your NAT gateway inside your router rewrites the request to be from 184.108.40.206 (it's static IP address)
Your router replies to the ICMP Echo request
Since your router does not support ICMP state, it never passes the ECHO Reply back to you.

HTTP

You send a TCP/80 connection request from 192.168.0.5 to 126.96.36.199
This routes by way of your router
Your NAT gateway rewrites the packet as coming from 126.96.36.199:41345 to 126.96.36.199:80
Your NAT gateway notes that there is a port foward in place, so forwards the packet to 192.168.0.120:80
The server at 192.168.0.120 replies to the connection attempt from 18.104.22.168:41345
Your NAT gateway sees the reply and rewrites the To: address on the reply to 192.168.0.5:36311, but leaves the From: untouched (192.168.0.120:80)
Your computer at 192.168.0.5 gets a packet from 192.168.0.120 that it never requested, and drops it on the floor.
Your connection languishes, and never opens.'

Note, it is possible that the reason ping is failing is because of the same reason HTTP is also failing. This is called 'NAT Hairpinning'.
What you need is a NAT gateway smart enough that at step 6 it also rewrites the source address.
Comment: I suspect you will have difficulty finding a modem. A common work-around is to just setup split DNS.  You serve the public address to external clients, and the private address to internal clients.
Comment: Ok, I found out that If I disable NAT in my modem/router, I can ping fine, but my Internet connection is gone. Do I actually need to have NAT enabled?
Comment: NAT is required if you want any kind of internet connectivity. What you need is a better NAT implementation, which probably means a different router, but could be as easy as changing a config setting on your router.
Comment: Thanks! I'll try to see if I can change the settings, if not I hope my ISP can provide a new modem.
Answer: Although 1138's answer is correct, I just wanted to toss in a detailed explanation about what "hairpin NAT" is, how it works, and why it's necessary in this circumstance. If you don't care about the nitty gritty details of IP, NAT and routing, please feel free to ignore the rest of my (rather lengthy) answer.
Without hairpinning, here is what happens during an HTTP connection attempt from a local LAN client (192.168.0.5) to the webserver via the external IP address (22.214.171.124):

192.168.0.5 sends its SYN packet to 18.104.22.168, port 80. Since 22.214.171.124 is not on the local network, this packet is sent to the default gateway (i.e. the router).
The router, which is configured to forward 126.96.36.199:80 to 192.168.0.120:80, rewrites the packet's destination address to 192.168.0.120, and then delivers the packet to the webserver.
The webserver receives the SYN packet, and sends a reply SYN-ACK packet back to the sender's address, which is 192.168.0.5. Since 192.168.0.5 is on the same network, the webserver delivers the packet directly to 192.168.0.5.
The SYN-ACK packet from 192.168.0.120 arrives at 192.168.0.5, but the host there was not expecting a SYN-ACK from 192.168.0.120, and so it is dropped/rejected. The host at 192.168.0.5 continues to wait for a reply SYN-ACK from 18.104.22.168, but of course, that packet will never arrive. The connection attempt will eventually timeout, perhaps after a few retries, and ultimately, the client and the webserver fail to establish a connection.

This problem can be solved by the router at step 2, by applying a "hairpin NAT". In short, the solution is to trick the client and webserver to send their mutual traffic through the router. This is cleverly accomplished by applying a second phase of NAT at step 2, in addition to the one phase normally applied for port forwarding. Here is the sequence again, this time with the added hairpinning NAT:

As before, 192.168.0.5 sends its SYN packet destined for 188.8.131.52, port 80, to the router.
As before, the router receives the SYN packet, and, as per its configured port-forwarding rule, it rewrites the destination address to 192.168.0.120. This time, however, the router notices that it is about to "hairpin" the packet back out onto the same network from which it was received, so it also rewrites the packet's source address to the router's own LAN address (say: 192.168.0.1). The router then delivers the packet to the webserver at 192.168.0.120.
The webserver receives the SYN packet, and sends its reply SYN-ACK packet back to the sender's address, which, this time, is 192.168.0.1. Thus, the reply goes back to the router.
The router receives the SYN-ACK from the webserver, and recognizes that it is a reply to a packet that it recently NAT-ed (twice). So the router dutifully reverses both NATs, and the reply packet now has source address 126.96.36.199 and destination address 192.168.0.5. Hence, the reply is delivered to 192.168.0.5, the TCP connection handshake continues, and the client and webserver are able to successfully communicate.

Thus, with hairpinning support in the router, the host at 192.168.0.5 thinks it's talking to a webserver at 220.127.116.11, while the webserver at 192.168.0.120 thinks it's talking to a client on the router itself (192.168.0.1). When hairpinning, all traffic between the two hosts passes through the router, even though both hosts are actually on the same network. This is obviously a suboptimal use of network resources, and is the main reason why setting up a split DNS is usually preferrable to relying on hairpinning.
Answer: What kind of firewall are you using? It sounds like NAT hairpinning is not turned on.
Comment: I have an `Actiontec PK5000`


Cloud Foundry Java Client Library throws CloudFoundryException: 403 Access token denied

Question: An App (Java Buildpack) using the CF Java Client Library to login to CF and connect to another App a CloudFoundryException: 403 Access token denied is thrown (see stacktrace below).
The same setup runs on Pivotal Web Services.
The App setup was also fine on the former Nova Swisscom App Cloud. Once the current Swisscom App Cloud was going live the App using the CF Java Client Lib on the Nova App Cloud stopped working with the same Exception.
Maybe that's related with the Swisscom App Cloud integration of the Passport login service which is causing the OAuth token problems.
While still wanting to use the CF Java Lib within a Java-App is there a different way to login to CF and connect to another App?
Stacktrace:
2015-10-23T19:26:03.41+0200 [App/0]      OUT org.cloudfoundry.client.lib.CloudFoundryException: 403 Access token denied.
2015-10-23T19:26:03.41+0200 [App/0]      OUT    at org.cloudfoundry.client.lib.oauth2.OauthClient.createToken(OauthClient.java:114) ~[cloudfoundry-client-lib-1.1.3.jar!/:na]
2015-10-23T19:26:03.41+0200 [App/0]      OUT    at org.cloudfoundry.client.lib.oauth2.OauthClient.init(OauthClient.java:70) ~[cloudfoundry-client-lib-1.1.3.jar!/:na]
2015-10-23T19:26:03.41+0200 [App/0]      OUT    at org.cloudfoundry.client.lib.rest.CloudControllerClientImpl.initialize(CloudControllerClientImpl.java:187) ~[cloudfoundry-client-lib-1.1.3.jar!/:na]
2015-10-23T19:26:03.41+0200 [App/0]      OUT    at org.cloudfoundry.client.lib.rest.CloudControllerClientImpl.<init>(CloudControllerClientImpl.java:163) ~[cloudfoundry-client-lib-1.1.3.jar!/:na]
2015-10-23T19:26:03.41+0200 [App/0]      OUT    at org.cloudfoundry.client.lib.rest.CloudControllerClientImpl.<init>(CloudControllerClientImpl.java:172) ~[cloudfoundry-client-lib-1.1.3.jar!/:na]
2015-10-23T19:26:03.41+0200 [App/0]      OUT    at org.cloudfoundry.client.lib.rest.CloudControllerClientFactory.newCloudController(CloudControllerClientFactory.java:78) ~[cloudfoundry-client-lib-1.1.3.jar!/:na]
2015-10-23T19:26:03.41+0200 [App/0]      OUT    at org.cloudfoundry.client.lib.CloudFoundryClient.<init>(CloudFoundryClient.java:164) ~[cloudfoundry-client-lib-1.1.3.jar!/:na]

Answer: swisscom dev here;
We fixed this issue with an update this morning - authentication with your Swisscom Passeport account should now be working from inside the Appcloud.
Comment: Which kind of update did you install to fix this issue?
Comment: @Stefan: It was the issue that access from within the Appcloud hit a different endpoint than from the outside. The fix was to align this.


How can I code the query set in order that the users can see only their own post in profile section

Question: I'm working on a project by using Django 2.06. I have multiple users and they can post and other people can read their post which is very normal. At the user profile page User should see their own post.
this is where I'm stuck, How i can code the queryset then at the profile section user can see only their own post.
code demo
class ProfileView(ListView):

    template_name = "profile.html"
    queryset = QuickWord.objects.filter()
    context_object_name = 'quickword'

    def get_context_data(self, **Kwargs):
        context = super(ProfileView, self).get_context_data(**Kwargs)
        context['addproduct'] = AddProduct.objects.filter()
        context['article_view'] = Article.objects.filter()
        context['edit'] = Profile.objects.all().last()
        return context

I know that I have to use filter value but do not know how to do that.
Thanks
Comment: How does your `Article` model looks like? How do you store what user wrote what post?
Answer: Assuming your have an author field in your Post model, You should do something like this in your views.py
def profile(request):
    user_posts = Post.objects.filter(author=request.user)

    return render(request, 'path/to/profile.html', {'posts': user_posts})

Of course the above view requires the user to be logged in.


como alinhar no centro com css

Question: Galera tenho dois button que estão alinhados no centro usando display: block;. O problema e que um fica encima do outro, para ficar um do lado do outro eu usei display: tale-cell; e o problema e que eles não ficam no centro.
Como faço para colocar um do lado do outro e alinhados no centro da pagina?

button {
    display: table-cell;
    border:0;
    padding:10px;
    width:200px;
    height: 50px;
    margin: 20px auto;
    cursor: pointer;
    border-radius: 3px;
}
<button  type='submit'>bt1</button>

<button  type='submit'>bt2</button>
Answer: Eu resolveria assim:

        <button /> <button />

CSS:
.linha { width:100%; }
.botoes { margin: 0 auto 0 auto; text-align: center;     }

Comment: Com uma única div, você pode atribuir a ela as duas classes (não recomendo), ou você pode mesclar as duas classes CSS em uma única classe.
Comment: funcionou 100%, mas teria alguma forma de resolver sem ter que criar 2 div?
Answer: Outra Forma
HTML

  <button  type='submit'>bt1</button>
  <button  type='submit'>bt2</button>

CSS
.btns{
  text-align: center;
}
button {
    display: inline-block;
    border:0;
    padding:10px;
    width:200px;
    height: 50px;
    margin: 20px 5px;
    cursor: pointer;
    border-radius: 3px;
}

Comment: muito bom, ficou muito simples sua solução
Comment: E se precisar, dependendo do que tiver dentro do button, `vertical-align:middle` nele.

como alinhar no centro com css


Printing big files from Linux causes PostScript errors

Question: I've been trying to make a Dell 5110cn printer to work from Linux, to no avail.
I've tried sharing the printer from both a Linux and a Windows machine, and in either case, Windows clients can always print fine.
When a Linux client sends a print job that's larger than a few hundred KBs, the printer chokes and prints pages with what appear to be PostScript errors, like:
<code>ERROR: ioerror
OFFENDING COMMAND: image
STACK:
  lot's of characters
</code>
I've been struggling with this for weeks now, and nowhere have I found an answer or a pointer.
Comment: How is the printer connected?  USB?  Parallel?  Serial?  If there's no method for the printer to report to the print service that it's full, it needs to stop and digest, then it'll continue on...
Comment: Ethernet. We've tried USB too, with the same results.
Comment: Ah.  What is the printing method?  IPP?  LPR?  Print to port 9100?  Are you using CUPS?  If so, what print driver are you using to print to it?  If not, how are you digesting your print job before it's sent?  The specs page indicates that it supports both PCL and Postscript.  Have you tried switching to PCL vs. Postscript?  I have encountered printers that will not print in one but will print in the other, for no apparent reason - and those were using Windows print drivers.
Comment: Seems like I missed mentioning a lot of details :) I tried CUPS, 9100, and Windows sharing. I didn't know you could choose PCL, and I don't know where to change that, but I'll look into it. The driver we've used is the PPD from Dell. Thanks!
Answer: Ok, well, here's some food for thought:

Ditch the PPD.  Yeah, that seems counter-intuitive, but really, you'll be fine without it.
Use a different printer language.  Select PCL 5e as the print language, if possible.  Sticking with older, matured protocols allows you to avoid incompatibilities and/or bugs with the implementation of newer ones.  You might not get all the features you want, but you'll get something functional.
Turn the Windows box into a print server.  If you have an LPR service available on your windows box, "Attach" the printer to the windows machine, enable LPR services and point the Linux box at the windows machine, turning it into a print server.
Enable Proprietary Driver Support.  If you have a "newer" Linux distro, the CUPS service should be able to "detect" the presence of the printer easily.  If you are running Ubuntu or Debian, be sure to include support for non-free software, as it's (unfortunately) necessary for stubborn hardware that can't be dragged along for the ride.  Ubuntu has a GUI tool in the System menu that allows you to detect hardware that needs non-free drivers, and install the driver.
Switch Print Drivers.  Here's a dirty little secret - you can use the same print driver on several dozen printers from different vendors, and they will cover different models.  I don't know how many times I've had to use "Apple LaserWriter 600" to just get a vanilla postscript driver installed on a Windows box for a non-printing function.

I'm sure there's more, but this is what comes to mind ATM.
Comment: Just wanted to let you know that I appreciate the time you've taken to help me troubleshoot this issue. We're going to try your suggestions (along with other ideas) later in the week, and I'll let you know how it goes.
Comment: Alright, we're making progress. With the PCL 5e driver it works beautifully... but only in b&W. Will keep trying other options, thanks for your response.
Comment: Good to hear you've got some solid progress.  I wondered if it was an issue with the driver setup...hope you hammer out all the other details soon.


How to modify HTML layout inside a View template

Question: I am very new to Drupal and this is my first post in this community. What I am trying to achieve I know may be very simple but just don't know how! So I am looking forward for expert help.
First please see the screenshot:

Below is what I want to achieve:

WHITE boxes are laid out as float: left;
I want A, B and C to shift below their respective titles, i.e. at A1, B1 and C1 spots respectively.
I want to make the TITLE + A1 to be under the same container so the container can float left itself. Same with TITLE  + B1 and TITLE + C1

I copied views-view-unformatted.tpl.php file to my custom theme folder. The code snippet is rendering the data fine:
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row ?>

<?php endforeach; ?>
But I want each of the field in $row to be printed in a way I want, e.g.:
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>

      <?php print $row->title ?>

      <?php print $row->body ?>

<?php endforeach; ?>
I believe there is a way to do it but don't know how. $row->title or $row->body is actually printing (rendering) nothing.
Also, if I modify views-view-unformatted-tpl.php it will affect the entire site. So I want a separate view for this purpose. How to do this?
Comment: For starters, you shouldn't use `views-view-unformatted.tpl.php` because it will affect all unformatted views. What you need to do, is add your view name so it only affects that specific view. **views-view-unformatted--[view-name].tpl.php**
Comment: Yes, that's one of my questions as well. Thanks for your valuable comments. I will override default view with mine. But how should I proceed with the other part of my question - i.e. shifting content to different area, as I have marked in the screenshot. Help would be much appreciated.
Answer: views-view-fields--[view-name]--machine name.tpl.php
Ex: views-view-fields--hello-world--block-1.tpl.php

  <?php print $fields["field_image"]->content; ?>

     <?php print $fields["title"]->content; ?>

     <?php print $fields["body-summary"]->content; // if you r using a body summary ?>
     <?php // if you are using an actual field then use:  print $fields["field_name"]->content; ?>

CSS
.picture { float: left; }


Adicionar elementos a um array no matlab

Question: Basicamente preciso dentro de um for, adicionar elementos a um array ou lista(não sei se tem na linguagem) e depois efetuar a divisão dos valores pela quantidade de interações. Bem simples, se fosse em qualquer outra linguagem, mas como tenho pouco ou quase nenhum conhecimento em MATLAB, está bem complexo.
Até Agora fiz dessa forma:
maxInteracao = 10;
for index = 1 : maxInteracao
//stuff

erroClassifTeste = 100 * (classificacoesErradas/numTeste);
arrayErro := [] : append(erroClassifTeste);
end

Answer: Segue:
maxInteracao = 10;
for index = 1 : maxInteracao
//stuff

erroClassifTeste = 100 * (classificacoesErradas/numTeste);
arrayErro [i] = erroClassifTeste;
end


how to turn vectors to matrix in R with unequal length

Question: I have vector with following structure like this. Vector with name "data_1" are numbers between cells "data_1" and "data_2", etc
row name   cell meaning
1           data_1
2           3.4
3           2.3
...         ...
40          data_2
41          12
...         ...
60          data_3
61          63.2
...         ...

I want to create array of data frames DF like this. So each vector is in separate data frame.
DF[1]
3.4
2.3
...

DF[2]
12
...

DF[3]
63.2
...

What is the fast way to do it? I have 4 million records, so traditional cycles such as for(i in 1:nrow) are too slow. Thanks.
Comment: The structure of your data is not clear. Please edit the question with the output of `dput(df)`. Or, if it is too long with the output of `dput(head(df, 20))`. (`df` is the name of your data.)
Answer: Did you mean to have something like this?
library(zoo)

#split dataframe in list of values
df_list <- split(df, na.locf(sapply(df$cell_meaning, function(x) ifelse(grepl("[0-9]+\\.?[0-9]+",x),
                                                             NA,
                                                             which(df$cell_meaning==x)))))
names(df_list) <- NULL

#remove data_*
final_list <- lapply(df_list, `[`, -1,)

#final output
final_list
final_list[1]

Output is:
> final_list
[[1]]
[1] "3.4" "2.3"

[[2]]
[1] "12"

[[3]]
[1] "63.2"

> final_list[1]
[[1]]
[1] "3.4" "2.3"

Sample data:
df <- structure(list(cell_meaning = c("data_1", "3.4", "2.3", "data_2",
"12", "data_3", "63.2")), .Names = "cell_meaning", class = "data.frame", row.names = c(NA,
-7L))

Comment: The answer was maybe good, but took too long time to run. I did other thing eventually.
Comment: Oh that's great that you found an efficient solution. You may want to post your solution as an answer for the benefit of others :)


How do I compare fields in a database query?

Question: Given the query fragment:
$query = $connection->select('mytable', 't');
$query->addField('t', 'myfield1', 'myfield1');
$query->addField('t', 'myfield2', 'myfield2');

I need to add a condition like this:
$query->condition('t.myfield1', 't.myfield2', '=');

But it doesn't seem to work. For comparison, I can use:
$query->condition('t.myfield1', 'banana', '=');

... and that works. But it seems comparing two fields to see if they match does not work? I can write this out in straight SQL code and properly query the database in a console, but can't duplicate in Drupal's database API.
What am I doing wrong?
Answer: You must use where(), like this:
$query = \Drupal::database()->select('mytable', 't')
  ->addField('t', 'myfield1', 'myfield1')
  ->addField('t', 'myfield2', 'myfield2')
  ->where('t.myfield1 = t.myfield2');

Comment: Thank you! That worked! I could not find that on the documentation - at least not where I looked. :-/


How the send a webform by email

Question: I have a task in hand that requires me to send a form to a client by email as soon as it is submited.
My question is: Having an aspx(in order to reuse my form) how can I get the generated html to send it by mail?
Thanks in advance
EDIT:
I know how to send emails, what I am looking for is how to get the html that is generated in my webform so i can place it in the email.
Answer: You should be able to call Render on it and stream it.
<code>StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
Page.RenderControl(htmlWriter);
string output = stringWriter.ToString();
</code>
Comment: That was my first try... the result of stringWriter.ToString() is "System.Web.UI.HtmlTextWriter"
Comment: Never mind that comment, I guess i am tired... It works ;) Thanks
Answer: Using the SmtpMail class in System.Web?

How the send a webform by email


POST Form to new Tab. Output is PDF

Question: I'm writing a website that generates some PDF documents for users. I need to do two things.
1) When the user clicks submit, the generated PDF, which is returned in the POST response, should be opened in a new tab.
2) For some requests, the original page needs to be refreshed to show that this PDF is in the user's library.
I've come up with this JS. It does submit the form properly, puts the output in a new tab, and reloads the page.
$.ajax({
    type: 'POST',
    url: '/share/pdf/',
    data: $('#pdf_share_form').serialize(),
    async: false,
    success: function (d) {
        var w = window.open();
        w.document.write(d);
        location.replace('/pdf/');
    }
});

The problem is that document.write() is expecting HTML, so a PDF shows up as a jumble of binary characters.
I feel like I need to indicate that the data should be downloaded when writing it, but I'm not sure how to go about that. Note that some generated files are ephemeral and immediately deleted after being returned from the form POST, so I can't do any sort of window.open(url).
Comment: is there a reason you are submitting this with ajax and not a regular form submit in a new tab?
Comment: @Ramy, I needed to be able to specify `async: false` to be able to open the new tab, read data, and then do the page reload. Thanks to your suggestion, I was able to find `$.when()`, and came up with a solution that works great.
Comment: I think http://stackoverflow.com/questions/9840230/how-to-display-a-pdf-stream-in-a-browser-using-javascript might help you out.
Comment: Glad I - indirectly - helped. As a rule of thumb: if you decide to use `async: false` for an ajax call, there is usually a better way of doing things. :)
Answer: Thanks to @Remy I thought a little more about what I needed to do. Before I wrote this question, I actually had a standard jQuery submit() call with the form set as target="_blank". That worked fine, but I was having problems with reloading the page after the submit. That led me to $.ajax(), which was the wrong solution.
The solution was quite simple:
$.when($('#pdf_share_form').submit()).then(function() {
    location.replace('/pdf/');
});

<form id="pdf_share_form" action="/share/pdf/" target="_blank" method="post">
    <input id="pdf_index" name="pdf_index">
    <input id="pdf_name" name="pdf_name">
</form>

POST Form to new Tab. Output is PDF


Popup issue after upgrading jQuery from 1.11.1 to 3.3.1

Question: I was using jQuery 1.11.1 and jQuery Mobile 1.4.5, everything is working fine. Recently I have upgraded jQuery to 3.3.1. I am getting popup issue. I am getting below error when i tried to open the popup in button onlick by calling popupCaptureOptions() function.
Uncaught TypeError: e.preventDefault is not a function
    at w.Event.preventDefault (jquery-3.3.1.min.js:2)
    at w.Event.preventDefault (jquery-3.3.1.min.js:2)
    at jquery.mobile-1.4.5.min.js:7
    at i (jquery-3.3.1.min.js:2)
    at dispatch (jquery-3.3.1.min.js:2)
    at y.handle (jquery-3.3.1.min.js:2)
    at Object.trigger (jquery-3.3.1.min.js:2)
    at jquery-3.3.1.min.js:2
    at Function.each (jquery-3.3.1.min.js:2)
    at jQuery.fn.init.each (jquery-3.3.1.min.js:2)

My html page looks like below.

            Close

Extraction Failed.

            Read more

Capture Options

                    Capture Back

                    Skip

My javascript code is
var popupCaptureOptions = function() {
        var imgFrontElement = document.getElementById("ID_IMAGE_DIV");
        var content_width = $.mobile.activePage.find("div[data-role='content']:visible:visible").outerWidth();
        $('#capture_popupalert').css({'width':content_width*0.8});
        $("#capture_popupalert").popup("open");
        $("#back_capture").click(function() {
            capturedSide = CAPTURESIDE.CAPTURE_BACK;
            doCapture();
        });

        $("#skip").click(function() {
            $("#capture_popupalert").hide();
            imgFrontElement.style.backgroundColor = "white";
            Utils.showLoadingIndicator();
            if (currentModule == Module.MOBILEID) {
                MobileIDModule.extractData(frontCapturedImage, backCapturedImage, isOnBoardingFlow, region);
            } else if (currentModule == Module.CHECK) {
                CheckDepositModule.extractData(frontCapturedImage, backCapturedImage, isOnBoardingFlow, region);
            }
            frontCapturedImage = null;
        });
    };

Please help me how can solve this issue.
Comment: provide your javascript code in the question
Comment: You made **two** major upgrade bumps. Has any of your code changed? jQuery did introduce a lot of breaking changes from 1->2 and I am sure they did the same from 2->3
Answer: It is very simple.
jQuery Mobile 1.4.5 was not made to work with the latest jQuery versions.
These are supported jQuery versions for jQM 1.4.5: jQuery 1.8 - 1.11 / 2.1
More about them can be found here.
So either upgrade to jQM 1.5 or use an older version of jQuery.
Comment: 3 years and jQuery Mobile and 1.5 is still not out and latest still doesn't work with the latest jQuery... It's time to move to Bootstrap...
Comment: This fixed the same problem for me. I was running jQuery 2.2.4. Downgraded for mobile to 2.1.4 and now the problem is gone. Where is jQuery Mobile 1.5?
Answer: jQuery Mobile 1.5.0 release-candidate-1 works fine with the newer versions of jQuery. I'm working with jQuery 3.2.1, and upgrading the JQM version to 1.5.0-rc1 fixed the popup issue I was experiencing using JQM version 1.4.5.
You can find the newer JQM version here, or alternatively use the following links:

jQuery.mobile.1.5.0-rc1.js (uncompressed)
jQuery.mobile.1.5.0-rc1.min.js (minified)
jquery.mobile-1.5.0-rc1.min.css (theme)

According to JQM's upgrade guide,

1.5 maintains full compatibility with the 1.4 API by default. This is accomplished by rebuilding the 1.4 API on top of the 1.5 API.

implying that you'll probably be running into minimal backwards compatibility issues.


JQuery get returning error when using read me later api

Question: I have the following code which hits the text method of the read it later api:
<code>$(document).ready(function() {
    var request = $.get('https://text.readitlaterlist.com/v2/text?apikey=KEY&url=http://readitlaterlist.com/api/docs');
});
</code>
Where KEY is my api key
If I use the same API key with http://web-sniffer.net/ and perform a get it works correctly. Why is my jQuery get returning an error?
Answer: You will not be able to do a GET from the client (with JS) due to XSS browser policies, you will need to access this resource from your server.


When does it make sense to define a base of a set system?

Question: In a topology, a base is defined to be a class of subsets such that
    every open set is the union of some members of it.
In a convexity
    structure, a base is defined to be a class of subsets such that
    every convex set is the union of an up-directed subcollection of it.
For a sigma algebra, an attempt to define a base is dismissed here. But I guess it may still be open for other possibilities to define what a base is.
A filter base generates a (proper) filter by including all sets which contain a set of the filter base.
So I was wondering whether a base can be defined for a general set
    system? When does a set system admit a base, and when doesn't?
Thanks and regards!
Some sources I have just found, although they haven't provided definitions:

base for an algebra of sets: http://ncatlab.org/nlab/show/sigma-algebra#generating_algebras_14
base for a sigma algebra of sets: http://ncatlab.org/nlab/show/base#bases_for_algebras_7
Comment: I feel somewhat uncomfortable with this question, since the notion of a "base" doesn't seem to be well-defined. For example, in algebraic structures, a "base" means something qualitatively different than what is meant in topology. Perhaps you could clarify your question by telling us what properties you would expect from a "base" (maybe you should also add tag for [category theory](http://en.wikipedia.org/wiki/Category_theory))
Comment: @William: (1) I am not sure what properties I will look for. Maybe closed under part of the operations under which the set systems are close? (2) I think a "base" for a set system may be different from a base for an algebraic structure. But who knows if they will merge into the same concept under category theory?
Comment: [Same question in the title](http://math.stackexchange.com/q/270031/8271)
Answer: I second William's comment that the concept of "base" means different things in different areas of math. So let me focus on the concept of "base" thought as "minimal set of elements that generate a structure".
There is a nice and simple categorical approach to this concept. Categorically, to give an algebraic structure, is to give a monad on a category $T \colon \mathcal{C} \rightarrow \mathcal{C}$. An algebra for a monad is an object in the category $\mathit{Alg}(T)$ of the Eilenberg-Moore resolution for the monad. This resolution comes equipped with a pair of adjoint functors: the forgetful functor $U \colon \mathit{Alg}(T) \rightarrow \mathcal{C}$ and its left adjoint "the free functor" $F \colon \mathcal{C} \rightarrow \mathit{Alg}(T)$ such that $T = U \circ F$.
Now, the crucial thing is that we may compose these functors in the other direction  obtaining a comonad $D = F \circ U$ on the category $\mathit{Alg}(T)$. As it is the case with every comonad, $D$ has its own coresolution in the category of the Eilenberg-Moore coalgebras $\mathit{coAlg}(D)$. Therefore, we may consider coalgebras over algebras. It turns out that in many cases such induced coalgebras over algebras correpond to the usual notion of base. For example: coalgebras over vector spaces decompose vectors into coefficients according to a base; coalgebras over algebras for the power-set monad give decomposition of elements of an atomic (complete) lattice into their descending atoms.

It may help to work out a simple example. Let us consider $\mathcal{C} = \mathbf{Set}$ together with a finite sequences monad:
$$T(X) = X^*$$
The Eilenberg-Moore resolution for $T$ gives the category of monoids $\mathbf{Mon}$. The forgetful functor $U \colon \mathbf{Mon} \rightarrow \mathbf{Set}$ assigns to a monoid its carrier:
$$U(\langle M, \bullet, \iota\rangle) = M$$
and the free functor $F \colon \mathbf{Set} \rightarrow \mathbf{Mon}$ gives a monoid action via concatenation:
$$F(X) = \langle X^*, \circ, [\;]\rangle$$
The induced comonad $D = F \circ U$ associates with every monoid the free monoid build upon the same carrier:
$$D(\langle M, \bullet, \iota\rangle) = \langle M^*, \circ, [\;]\rangle$$
There is the counit of the comonad $\epsilon \colon \langle M^*, \circ, [\;]\rangle \rightarrow \langle M, \bullet, \iota\rangle$ defined by folding with monoid's multiplication:
$$\epsilon([a_1, a_2, \dotsc, a_n]) = a_1 \bullet a_2 \bullet \cdots \bullet a_n$$
and the comultiplication of the comonad $\delta \colon \langle M^*, \circ, e\rangle \rightarrow \langle M^{**}, \circ, e\rangle$ which decomposes words on singletons:
$$\delta([a_1, a_2, \dotsc, a_n]) = [[a_1], [a_2], \dotsc, [a_n]]$$
By definition, a coalgebra over a monoid $\langle M, \bullet, \iota\rangle$ is a monoid homomorphism $h \colon \langle M, \bullet, \iota\rangle \rightarrow \langle M^*, \circ, [\;]\rangle$ such that:

$\epsilon \circ h = \mathit{id}$, that is: $h(r)_1 \bullet h(r)_2 \bullet \cdots \bullet h(r)_n = r$, where $h(r)_k$ is the $k$-th element of sequence $h(r)$
$D(h) \circ h = \delta \circ h$, that is: $h(h(r)_k) = [h(r)_k]$

These conditions say that coalgebras over monoids are tantamount to finite decompositions of elements on indecomposable elements.
Comment: Just a note: perhaps it would be better to use $\mathcal{C}$ instead of $\mathbb{C}$ to avoid confusion with the set of complex numbers.
Comment: William, I do not know how to type the font you suggested. Feel free to make any corrections :-)
Comment: Mockup, the latex command for that is \mathcal{C}. It seems that you have managed to edit your post already.
Comment: Thank! I don't have enough knowledge to understand your reply yet. By "let me focus on the concept of base thought as minimal set of elements that generate a structure", did you only talk about basis in algebraic structures? I agree basis in algebraic structures and in set systems mean different, and I am not sure if they can be unified at higher level such as in category theory. But my question is more about base for a set system, such as for a topology, sigma algebra, not about basis for a vector space or another algebraic structure.
Comment: Hi Tim! You are right, the above approach works only for (in some sense) algebraic categories. I should also have said that I learnt this approach from Bart Jacobs. If I recall, the relevant paper is: B. Jacobs "Coalgebras and approximation", though I have never read it --- maybe you will find more information there.


Visualizing data from different csv files in D3

Question: I am brand new to D3 and begin working on a new project. My question is this. I need to load two local CSV files and visualize them to two separate line charts(not multi-line charts),which contain independent x axis and y axis. The final purpose is to compare these two charts with a vertical line penetrating both of them and both charts can be zooming or panning synchronously.
I created two SVGs for both of two separate charts and used two consecutive calls to d3.csv() to load two csv files such as
d3.csv("file1.csv", function(error, data) {
   //functions control the first chart

});

d3.csv("file2.csv", function(error, dataㄉ) {
   //functions control the second chart

});

However, finally I found that contents inside the first d3.csv() cannot be used in the second d3.csv().
Shouldn't I use different svg, or I need to apply new way to load two csv files but not using two independent d3.csv()?
Comment: Does this answer your question? https://stackoverflow.com/questions/21842384/importing-data-from-multiple-csv-files-in-d3
Answer: You can use d3.queue to load the files at the same time. The function in .awaitAll() is only evaluated after both CSV files have been loaded, and the function .await() only waits for one of the CSV files to complete loading.

function delayedHello(callback) {
  setTimeout(function() {
    console.log("Hello!");
    callback(null);
  }, 250);
}

d3.queue()
  .defer(delayedHello)
  .defer(delayedHello)
  .awaitAll(function(error, data) {
    console.log(error ,data);
  });

d3.queue()
  .defer(delayedHello)
  .defer(delayedHello)
  .await(function(error, data) {
    console.log(error ,data);
  });

Comment: That is not fully correct: `.await()` does also wait until **all** tasks have finished. The difference between `.await()` and `.awaitAll()` is the way the results are passed on to the callback


Use an entity reference in URL as Views Contextual Filter

Question: My site allows users to create a "booking request" node related to a "vehicle" node. I use an Entity Reference to connect the two by prepopulating a "Vehicle" field on the "booking request" node via a string in the URL:
http://example.com/vechiclename=&overlay=node/add/booking%3Ffield_vehicle%3D84
I would like to display a views block on this overlaid page with more info from the related vehicle. As you can see, the NID of the vehicle is in the URL (84), but I don't know how to target it.
I'm familiar with grabbing a path component from the URL, but it's the &field_vehicle=84 that is new to me. Any ideas?
Answer: I have never added a views block into the admin overlay (trying to get a parameter from the URL form the views block). But this is how I would approach the problem.
In your view, pick the 'Block' display. Add a contextual filter for the field that is referencing (Vehicle). Expand 'When the filter is not available'. Pick the option PHP Code. User the following code:
<code>return (isset($_GET['field_vehicle'])) ? $_GET['field_vehicle'] : 'all';
</code>
I am using 'all' as fallback assuming that you will show everything if a value isn't available. But I guess you can use FALSE if you want it empty.
Save it. Add the block into your overlay/admin theme. Check if it works...
Best regards.
Comment: Thanks for your reply. I tried your method, but no result. I think this does not work because the node has not yet been saved, and field_vehicle is not yet set (though a value has been prepopulated into the form). Thoughts?
Comment: I will run some tests locally and see if I can get this working.
Comment: Hey, Steven, I have just set this solution locally (sorry for the delay) and it works! Don't forget you must add your Views block (the block we have prepared) into your admin theme. This is very important. Are you using something like SEVEN as admin theme? If you are, you have to go to the blocks administration section, click on the SEVEN tab and add the new Views block to the content region. When setting the block on Views, add a message for no results. That way you can see if your filter is working -- or not. If you don't get the empty message, means the block isn't properly set.
Comment: I have my block properly configured (it displays without a contextual filter). I also got it to show "all" with the filter in place (displayed the first node's info on other nodes) when I changed "field_vehicle" to "field_vehicle[und]". I still cannot seem to pass the correct value. Maybe it's something about the format of the Entity Reference field? When I use the autocomplete widget for that field, I see "Name (NID)" in the field. If I use dropdown, I see "Name", but "NID" is the value set when I inspect the HTML. In what format does this PHP return the reference?
Comment: Steven, the form interface for autocomplete entity reference fields actually displays 'term name (nid)' but don't worry, this won't affect your results. Did you set the filter exactly as suggested (PHP code with the code above)? $_GET['field_vehicle'] should grab 'field_vehicle' from the URL. I am running out of ideas.
Comment: Marcos, thanks again for your help. I have tried to follow your instructions exactly as posted. Here are some screenshots, if you wouldn't mind double-checking me [http://imgur.com/a/4el0Y]. The only element I question is what field to use as the Contextual Filter on the View. I've tried Content: Van (the reference field), Content: Title and Content: NID.
Comment: It works! My problem - selecting the referenced field as the Contextual Filter instead of Content: NID. Thanks so much for your help. Accepted answer.


Simple existence proofs without bounds

Question: Which is/are the most simple proof/s of an existential statement like
$$
\exists x P(x)
$$
or
$$
\forall x \exists y P(x,y)
$$
where the variables rage over the integers, such that the proof doesn't provide any information about how far is the number that is claimed to exist in the first case or how far is $y$ as a function of $x$ in the second case.
Comment: existence of inverse modulo large primes, maybe?
Comment: Which proof are you thinking about?
Comment: For all $x$ and given prime $p$, there exists a $y$ such that $xy \equiv 1($mod $p)$. The proof is using pigeonhole principle: Consider $x,2x,3x,4x,...,px$. These are $p$ different numbers, and none of them leave the same remainder mod $p$. Since there are only $p$ possible remainders, each one corresponds to exactly one remainder, so for some $y$, $yx$ leaves a remainder of $1$. Thus $y$ is the inverse of $x$, but the size  of $y$ could be anything under $p$. If $p$ is something like $97346111$, we would have trouble finding $y$ given $x$.
Comment: @астонвіллаолофмэллбэрг Euclid's algorithm finds $y$ in polynomial time, doesn't it?
Comment: Somebody edited the question. Before I put my comment in there was no mention of time. But you're right. I'll try and come up with a better example.
Comment: @астонвіллаолофмэллбэрг The point is not the time required by some algorithm, the point is whether the proof provide information about how far we must go to find $y$ given $x$. In this case we know that we have a bound $y \leq px$
Comment: I know that. That's why if the prime is large then you have to search for a while, but yes, there is a bound, so my example is somewhat incorrect.
Comment: What makes you think there are proofs of those statements?  $P(x)$ and $P(x, y)$ could just be $x \ne x$.
Answer: A silly example: given any integer $n$ and a Gödel numbering system, let $\{ n \}$ denote the Turing machine with Gödel number $n$. Let $P(n)$ be the proposition "$\{n\}$ halts on input $0$".
The halting problem is unsolvable, which means that if the Gödel numbering system is horrible, we can't determine which the first index is of a halting machine. We just know that one exists.

If you want something on a related question which is not quite the same:
Let $P(x)$ be the statement that $x$ is a prime factor of some large fixed semiprime $n$. (That is, $n = pq$ where $p, q$ are prime.)
Then by the Fundamental Theorem of Arithmetic, there is some $x$ which divides $n$, but factoring is thought to be algorithmically a very hard problem. All we really know is that there is some $x$ with $2 \leq x \leq \sqrt{n}$.
This is an example where we have a bound, but no real idea where $x$ lies within that bound.
Answer: $\forall x \exists y $ s.t. $y > x$ where $x,y \in \mathbb{N}$
If not then $\mathbb{N}$ has a largest element $\implies$ $\mathbb{N}$ is finite. Q.E.D. by contradiction.
Comment: But this provides information about the number $y$; it specifies it exactly, in fact.
Comment: @Patrick Stevens I have edited it :)
Comment: Isn't this statement just equivalent to "$\mathbb N$ doesn't have a largest element"?
Comment: Well you did ask for simple proofs :/
Comment: Ok but this seems almost like "A implies A" :)

Simple existence proofs without bounds


Exercise 9, Section 2.5 of Hungerford's Abstract Algebra

Question:
If $|G| = p^nq$, with $p\gt q$ primes, then $G$ contains a unique normal subgroup of index $q$.

Why does author mention both unique and normal? Subgroup of index $q$ is Sylow $p$-subgroup of $G$. So uniqueness $\iff$ normality. Showing uniqueness is relatively easy compared to normality. Here is proof of above exercise showing uniqueness.
Comment: @citadel what do you mean?
Comment: Sorry! I missed the title!
Answer: It is perhaps more subtle than you think: if a subgroup is unique for a property that is respected by automorphisms (like its order, abelianess, solvability, ...), then it is certainly normal (even characteristic), since conjugation is an automorphism. However, normality in general does not imply uniqueness (cf. for a non-abelian example, the quaternion group of order $8$ that has $3$ normal subgroups of order $4$). Being Sylow is of course a stronger condition and then uniqueness and normality are equivalent.
Answer: Perhaps the author has used both "unique" and "normal" because they considered part of the exercise to acknowledge that a subgroup of index $q$ it's just a $p$-Sylow subgroup. Once this is done, the claim follows from Sylow II, according to which the $p$-Sylow subgroups are conjugate.

Exercise 9, Section 2.5 of Hungerford’s Abstract Algebra


exclude a URL from rewrites

Question: I have a nodejs application running on iis.
I have url rewrite rule which sends all request to a custom server.js page.
I want to add a new rule or modify the existing one so that  a particular url /something reaches the iis and not the rule I have written.
My rule currently:
    <rewrite>
        <rules>
            <rule name="node">
                <match url="/*" />
                <action type="Rewrite" url="server.js" />
            </rule>
        </rules>
    </rewrite>

Please help on this one.
Comment: possible duplicate from this one? https://stackoverflow.com/questions/23574022/exclude-path-in-iis-rewrite-rule
Answer:             <rule name="sendToNode">
                <match url="/*" />
                <conditions>
                    <add input="{URL}" pattern="/something$" negate="true" />
                </conditions>
                <action type="Rewrite" url="server.js" />
            </rule>

exclude a URL from rewrites


How to determine the integral interval? Can they be exchanged?

Question: $\iint_D\frac{\sin y}{y}\mathrm{d}x\mathrm{d}y$, $D$ with $y=\sqrt{x}$ and $y=x$
What I'm most puzzled about is $\iint_D\frac{\sin y}{y}\mathrm{d}x\mathrm{d}y$=$\int_0^1\mathrm{d}y\int_{y^2}^y\frac{\sin y}{y}\mathrm{d}x$
Can $y$ and $y^2$ exchange their position? Can their upper and lower limits be exchanged?
When I saw the picture, the two equations intersect at one point
Comment: When you saw the graph, did you notice that $x=y$ was right of $x = y^2$ for the given domain?
Answer: The equations $y=\sqrt x$ and $y=x$ intersect in two points, $(0,0)$ and $(1,1)$.  Over the range $0-1$ in $x$ we have $y^2 \lt y$ so the limits are correct to give a positive result.  You can interchange the limits of an integral, but it will negate the result.  You seem to be assuming that $y^2 \gt y$, but that is not the case here.
Answer: Using your bounds you get
$$\int_0^1 \frac{\sin y}{y}\left[ \int_{y^2}^{y}dx\right]dy=\int_0^1\sin y dy-\int_0^1y \sin y dy=1-\sin (1)$$


Exception in MediaPlayer.setDataSource() method

Question: In the class I have this field:
private MediaPlayer mp = new MediaPlayer();

And every time some sound needs to be played, the following method is being called:
private synchronized void playSound(int sound) {
      try {
                mp.setDataSource(context, Uri.parse("android.resource://" + context.getPackageName() + "/" + sound));
            } catch (IOException e) {
                e.printStackTrace();
            }
            mp.prepareAsync();
            mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    if (mp != null) {
                        while (mp.isPlaying()) {
                            // waiting while it is already playing
                        }
                        mp.stop();
                        mp.reset();
                    }
                    mp.start();
                }
            });

The problem is this exception:
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.app, PID: 28893
                  java.lang.IllegalStateException
                      at android.media.MediaPlayer._setDataSource(Native Method)
                      at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1128)
                      at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1012)
                      at android.media.MediaPlayer.setDataSource(MediaPlayer.java:968)
                      at com.speechsynthesizer.TextProcessor.playSound(TextProcessor.java:92)

URI source is OK, I have checked it.
Answer: The Javadocs say:

IllegalStateException - if it is called in an invalid state

Looking at the valid/invalid states table any state besides IDLE would cause this exception. My guess is that playSound is being called twice, and because it is already preparing/playing during the second time the state is invalid.


XSLT – creating a numbered attribute based on the value of another attribute

Question: From a document such as the following list:
<list>
    <city ref="Paris">Paris</city>
    <city ref="Rome">Rome</city>
    <city ref="NYC">New York</city>
    <city ref="Lisboa">Lisboa</city>
    <city ref="Lisboa">Lisbon</city>
    <city ref="Lisboa">Lisbonne</city>
    <city ref="NYC">The Big Apple</city>
</list>

I would like to obtain a copy of this list, with an added numeric attribute derived from the @ref attribute (ideally in alphabetical order), for an output like:
<list>
    <city ref="Paris" id="3">Paris</city>
    <city ref="Rome" id="4">Rome</city>
    <city ref="NYC" id="2">New York</city>
    <city ref="Lisboa" id="1">Lisboa</city>
    <city ref="Lisboa" id="1">Lisbon</city>
    <city ref="Lisboa" id="1">Lisbonne</city>
    <city ref="NYC" id="2">The Big Apple</city>
</list>

I suppose there is a way to use <xsl:key> to number a sorted list of my @ref attributes, but am not fluent enough to get there.
Many thanks in advance.
Comment: Can you use XSLT 2.0?
Answer: With XSLT 3.0 (as supported by Saxon 9.7) it is as easy as
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    exclude-result-prefixes="xs math"
    version="3.0">

    <xsl:variable name="cities" select="sort(distinct-values(/list/city/@ref))"/>

    <xsl:mode on-no-match="shallow-copy"/>

    <xsl:template match="city/@ref">
        <xsl:copy/>
        <xsl:attribute name="id" select="index-of($cities, .)"/>
    </xsl:template>

</xsl:stylesheet>

With XSLT 2.0 we can use
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:variable name="cities" as="xs:string*">
        <xsl:perform-sort select="distinct-values(/list/city/@ref)">
            <xsl:sort select="."/>
        </xsl:perform-sort>
    </xsl:variable>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* , node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="city/@ref">
        <xsl:copy/>
        <xsl:attribute name="id" select="index-of($cities, .)"/>
    </xsl:template>

</xsl:stylesheet>

Finally with XSLT 1.0 the above "translates" into
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:exsl="http://exslt.org/common"
    exclude-result-prefixes="exsl"
    version="1.0">

    <xsl:key name="city" match="city" use="@ref"/>

    <xsl:variable name="cities-rtf">
        <xsl:for-each select="/list/city[generate-id() = generate-id(key('city', @ref)[1])]">
            <xsl:sort select="@ref"/>
            <city id="{position()}" ref="{@ref}"/>
        </xsl:for-each>
    </xsl:variable>

    <xsl:variable name="cities" select="exsl:node-set($cities-rtf)/city"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="city/@ref">
        <xsl:copy/>
        <xsl:attribute name="id">
            <xsl:value-of select="$cities[@ref = current()]/@id"/>
        </xsl:attribute>
    </xsl:template>

</xsl:stylesheet>

Comment: Thank you so much!

Out of curiosity, would there be any practicable alternative with XSLT 2.0?
Comment: Thank you so much!


Map function in RXJS 6.5.1 And Angular 8 with Firestore Collection

Question: I am using AngularFire with RxJS 5.4.0 and Firebase. This below code works fine:
 this.questions$ = dbQuestions$.map(snapshots =>
    snapshots.map(data =>
    this.FilterControls(data)
  ));

When I use the code below with RXJS 6.5.1, Angular 8 and Firestore (shown below), I receive the Error:

Property 'map' does not exist on type 'AngularFirestoreCollection<{}>'

 this.questions$ = dbQuestions$.map(snapshots => {
   snapshots.map(data => this.FilterControls(data))
 });

Answer: The error "map does not exist on type AngularFirestoreCollection<{}>" is due to breaking changes made in RXJS version 5.5.
Pipeable Operators

Starting in version 5.5 we have shipped "pipeable operators", which can be accessed in rxjs/operators... These are meant to be a better approach for pulling in just the operators you need than the "patch" operators found in rxjs/add/operator/*.

With the new pipeable operators, your code would look like:
import { Component } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';

import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  dbQuestionCollection: AngularFirestoreCollection<{}>;
  dbQuestions$: Observable<{}[]>;

  constructor(private afs: AngularFirestore) {
    this.dbQuestionCollection = this.afs.collection<{}>('questions');
    this.dbQuestions$ = this.dbQuestions$ = this.dbQuestionCollection.snapshotChanges().pipe(
      map(actions => actions.map(a => {
        const data = a.payload.doc.data(); // DB Questions
        const id = a.payload.doc.id;
        return { id, ...data };
      }))
    )
  }
}

Comment: Above code is not working. Now it says  error  "pipe does not exist on type AngularFirestoreCollection<{}>"
I tried to import import { map,pipe } from 'rxjs/operators'; but the operators doesnt have pipe it seems...
Comment: i tried with valuechanges and snapshotchanges both still is giving error like below
 this.questions$ = dbQuestions$.valueChanges().pipe(map(snapshots => {
      snapshots.pipe(map(data => this.FilterControls(data)))
    }));

Error Message: pipe doesnt exisit on type unknown[]
Comment: @Dev See updated code example.


Alternating sum of numbers of surjective functions

Question: Let $S(n,k)$ denote the number of surjective functions from $\lbrace1,2,...,n\rbrace$ onto $\lbrace1,2,...,k\rbrace$. I am sure that
$$S(n,n) - S(n,n-1) + S(n,n-2) - ... +(-1)^{n-1}S(n,1) = 1$$
Have you seen this identity anywhere? Any nice proof?
Answer: Yes, this is a very well known identity evaluated at $x=-1$.
$$x^n=\sum _{k=0}^nS(n,k)\binom{x}{k}.$$
You can show it easily for $x$ positive integer by choosing the size of the image of a function $f$ from $[n]$ to $[x]$. Notice that a functions is surjective in its image. Furthermore, if two polynomials agree in infinite number of points, then they are the same polynomial.


How to specify priority in makefile

Question: I have a makefile and several targets there. I want to clean directory first, then build directories and then run compilation of tasks1..4. Sometimes building directories starts after compilation and this makes compilation impossible.
Makefile in general looks like:
release: clean
release: build
release: task1 task2
release: task3 task4

Clean and build must be finished before tasks1..4 start running. In other words how to specify priority in makefile tasks. Now seems all 4 lines from the makefile start altogether in one moment.
Answer: I'm assuming you're using -j; without parallel builds enabled make will never start any rules together: it always runs them one at a time in the order the prerequisites are listed.
The only way to specify order is via prerequisites.  So, this would look like:
release: task1 task2 task3 task4
task1 task2 task3 task4: build
build: clean

However, this last step is a very bad idea: you don't want your build target to depend on clean in general, otherwise it will always be run.  You can either ask people to run clean by hand, but probably the most common way to deal with release targets like this is with make recursion:
release:
        $(MAKE) clean
        $(MAKE) build
        $(MAKE) task1 task2 task3 task4

How to specify priority in makefile


PHP compare two objects with same properties but different properties values, get non-matching values

Question: I have these two objects contained in a array:
array (size=2)
 0 =>
object(stdClass)[20]
  public 'name' => string 'John' (length=4)
  public 'surname' => string 'D' (length=1)
  public 'id_number' => string '924' (length=3)
  public 'file' => string '1001' (length=4)
  public 'arrival_date' => string '1368466111' (length=10)
1 =>
object(stdClass)[21]
  public 'name' => string 'John' (length=4)
  public 'surname' => string 'D' (length=1)
  public 'id_number' => string '924' (length=3)
  public 'file' => string '1002' (length=4)
  public 'arrival_date' => string '1368466190' (length=10)

It would be great to come up with 3 arrays or 3 objects like the following:
array('name'=>'John','surname'=>'D','id_number'=>'924') - contains the matching values
array('file'=>'1001','arrival_date'=>'1368466111') - contains the first set of different values
array('file'=>'1002','arrival_date'=>'1368466190') - 2nd set of not matching values

The story behind the code is that upon the arrival of each person, I open a file, and at some point in time, I want each person to list his name and beneath his name and identification (that are identical for each arrival) to list his arrival files, each in a row.
What do you, think? Is there any neat way to accomplish this? What I did so far is a mess - tons of code with poor results.
Comment: No code is poor code until you have untested it and launched it at production time. Let's see what you've got.
Answer: There are built in functions for that. You do need to cast the objects to an array for this to work though (which is an array of all public properties of the object). Assuming your variable is called $var:
$a1 = (array)$var[0];
$a2 = (array)$var[1];
$inBoth       = array_intersect_assoc($a1, $a2);
$onlyInFirst  = array_diff_assoc($a1, $a2);
$onlyInSecond = array_diff_assoc($a2, $a1);

Comment: this won't work for properties that are not castable to string, unfortunatly.
Comment: yeah , the only solution I found is a good old loop and identity comparison, collecting those who differ :/
Comment: For short, `(array) $classA == (array) $classB`
Comment: @Florian indeed it won't, nice catch. In those cases you would have to make the comparison more elaborate, and create a string for those variables that can't be casted manually, or somehow compare the fields manually.


Por que relações no Entity Framework code first são apontadas com ICollection?

Question: Por que relações no Entity Framework code first são apontadas com ICollection? Qual a melhor instanciação(?) para a propriedade em casos comuns? List?
A utilização da palavra-chave virtual é apenas para habilitar lazy loading na propriedade?
Answer: Por que relações no Entity Framework code first são apontadas com ICollection?
Porque a carga preguiçosa do Entity Framework coloca nesta propriedade um proxy dinâmico, que representa um objeto que implementa ICollection mas que na bem da verdade não é bem uma coleção de coisa alguma.
Ao acessar essa propriedade, o proxy dinâmico é substituído aí sim por uma coleção de verdade (normalmente List<>).
Qual a melhor instanciação (?) para a propriedade em casos comuns?
Da seguinte forma:
public virtual ICollection<Objeto> Objetos { get; set; }

A utilização da palavra-chave virtual é apenas para habilitar lazy loading na propriedade?
Não. virtual indica que o objeto pode receber derivados da classe genérica. Por exemplo, você declara um Model chamado Alimento e outro chamado Fruta, e faz Fruta derivar Alimento. Declarando desta forma:
public virtual ICollection<Alimento> Alimentos { get; set; }

Alimentos pode conter também objetos da classe Fruta.
Leia mais sobre o modificador virtual aqui.


How to wait unitl xhr finished?

Question: I'm making a website where I need to get all people who are registered to an event but every time I make the xhr request the code execute and do not wait the xrh response, that's cause a lot of trouble in the following code...
let inscrit = new XMLHttpRequest();
let methode = "GET";
let url = "php/getInscrit.php";
let asynchronous = true;

inscrit.open(methode, url, asynchronous);
inscrit.timeout = 4000;
inscrit.onload = function () {
  let people;

  if (this.readyState == 4 && this.status == 200) {
    people = JSON.parse(this.responseText);
  }
};
inscrit.send(null);
return people;

Sorry for my bad English and ty
Comment: how do u know its not executing on time? did u try console logging it?
Comment: @B''HBi'ezras--BoruchHashem I made an console log when I call this function and "people" is alwais null and In my network console it prove me that's not null
Answer: It seems like the problem is in "onload", which is only called one time, which could be right at the beginning before it's fully loaded, instead you should do everything in the onreadystatechange callback, so for example:
  let inscrit = new XMLHttpRequest();
    let methode = "GET";
    let url = "php/getInscrit.php"
    let asynchronous = true;

    inscrit.open(methode, url, asynchronous);
    inscrit.timeout = 4000;
    inscrit.onreadystatechange = function() {

        let people ;

        if (this.readyState == 4 && this.status == 200) {

            people = JSON.parse(this.responseText);

        }
    }
    inscrit.send(null);
    return people ;

Comment: "which could be right at the beginning before it's fully loaded" — No. The entire point of the load event is that it fires just **after** it is fully loaded.
Comment: This code won't work either (for the same reason that the original code doesn't: It returns before the value is assigned to `people` in the callback).
Comment: @Quentin OP never said this was inside of a function, so "return" could be superfluous
Comment: If it isn't inside a function then the question doesn't make any sense at all. We can safely infer that it is.
Comment: @Quentin y doesnt it make sense? this can all be happening on page load

How to wait unitl xhr finished?


form in a .tpl.php file

Question: This is the code in my template.php file.
function studiga_theme_theme($existing, $type, $theme, $path) {
    $items['add_property_form'] = array(
        'render element' => 'form',
        'template' => 'node--14',
        'path' => drupal_get_path('theme', 'studiga_theme') . '/templates/node',
    );

    return $items;
}

 function custom_add_property_form($form, &$form_state) {
    $form['first_name'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('First name')),
    );
    $form['last_name'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Last name')),
    );
    $form['address'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Address')),
    );
    $form['city'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('City')),
    );
    $form['state'] = array(
        '#type' => 'select',
        '#options' => array(
            'default' => 'State',
            '...' => '...',
        ),
    );
    $form['zip'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Zip')),
    );
    $form['email'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Email')),
    );
    $form['phone'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Phone')),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );

    return $form;
}

This is the code in node--14.tpl.php.

                Contact Information

        <?php print render($form['submit']); ?>

But no fields are appearing - what am I doing wrong? You can't have a straight forward  in a tpl.php file can you?
Comment: All I want is a form in a .tpl.php file and to be able to access the fields when they are posted. You can't use  and no fields show up if I use $items['add_property_form'] = array(
        'render element' => 'form',
        'template' => 'node--14',
        'path' => drupal_get_path('theme', 'studiga_theme') . '/templates/node',
    );
Answer: Given your definition of studiga_theme_theme(), Drupal will never call custom_add_property_form() because there isn't any relation between the theme template you define, and that function. Eventually, you could implement the preprocess function for that theme template, and set there a variable that is passed to the template.
function studiga_theme_preprocess_add_property_form(&$variables) {
  $variables['form'] = /* define here the form */;
}

Now your theme template will get a $form variable.
Keep in mind that, except in a case, themes don't define forms; that is the task for a module. Eventually, themes can alter a form provided by a module, but (generally speaking) you will never see a theme that defines a form that is not for its own settings.
Comment: I was trying to follow http://drupal.stackexchange.com/questions/312/how-to-a-use-a-template-file-to-theme-a-form
Comment: I am confused  - how does function studiga_theme_preprocess_add_property_form know which tpl.php to use?
Comment: It's not the function that knows which template file to use; it's Drupal that calls that preprocess function for a theme / template named add_property_form. See node.tpl.php for which Drupal calls a preprocess function like `mymodule_preprocess_node()` o `mytheme_preprocess_node()`, where mymodule and mytheme are respectively an enabled module and a theme.
Comment: In that case, `hook_theme()` contains an entry for custom_donate_form too. Then, it has not been explicitly said, but that `custom_donate_form()` is an example of module code. A theme can just define its settings form, not any other form.
Answer: I think your theme name(studiga_theme) is wrong. Try making it just "studiga". "_theme" is reserved word in Drupal. I also faced similar issue once.  Hope that will resolve your problem.
Comment: The short name of the theme is not a problem, if the theme doesn't define a `studiga_theme()` function, and there isn't a studiga module. Otherwise, `studiga_theme()` would be understood from Drupal as `hook_theme()` implementation of the studiga module.
Comment: The name of the theme is studiga_theme
Comment: I know. As I said, that would be a problem only in a case. That is not the reason of the issue the OP is having, though.
Comment: function studiga_theme_preprocess_add_property_form(&$variables) {
  $form = $variables['form'];
  $form['first_name'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('First name')),
    );

}                                                                                and    in the tpl.php but no input field shows up

form in a .tpl.php file


Turn a function into an odd function?

Question: I was asked to let:
$$ f(x) = \begin{cases} 1-x, \text{if $0 \le x < 1$} \\ 0, \text{if $ 1 \le x < 2$} \end{cases}$$
Let fodd be the $4$ periodic odd extension of $f(x)$.
Find the expression of fodd when $-1 < x <0$.
The solution was:
$$f_{\operatorname{odd}}(x) = -f(-x) = -(1-(-x)) = -(1+x) = -1-x$$
My question is: How is $f_{\operatorname{odd}}(x)=-f(-x)$ possible? I thought that $f_{\operatorname{odd}}$ is when $f(-x)=-f(x)$, so I thought that changing $1-x$ to $-1+x$ would be the answer.
edit:
that is what i have fodd(x) is when f(−x)=-f(x) but the solution used fodd(x) = −f(−x) i don't know why this was used.
and for source of why f(-x) = -f(x):
http://mathworld.wolfram.com/OddFunction.html
https://en.wikipedia.org/wiki/Even_and_odd_functions
Comment: Not sure I follow, but the definition is:  G(x) is odd if G(-x) = -G(x).
Comment: "I thought that $f_{\operatorname{odd}}$ is when $f(-x)=f(-x)$". Well, it's always the case that $f(-x) = f(-x)$. What did you want to say instead?
Answer: $f(-x) = -f(x)$ can be just written (equivalently) as $f(x) = -f(-x)$. That's what's it about.
Comment: ah, i did not know that and this was the type of answer I was looking for. Thank you very much

Turn a function into an odd function?


Facet blocks are not shown with Facet API Pretty Paths activate

Question: I've enabled Facet API Pretty Paths and the Face blocks are not shown once I select a category.
For example: the Facet Blocks (color and prices) are not shown for the link: /products/field_brand/simple-threads-68
These are:
Drupal 7.44
Facet API Pretty Paths: 7x-1.4
Profile: Commerce Kickstart (commerce_kickstart-7.x-2.38)
Thanks,
Araujo
Answer: Ok... I got the 'error'
The Facet blocks are visible for the URL: products
When you install Face Pretty Paths, the URL is modified including the segment of the search result.
I just added the "products/*" to the visibility of the block.
Show block on specific pages -> Only the listed pages: products/*


Is a regression line the same if it is computed with the mean of samples?

Question: I have 120 samples (Y-values) at the same point, for 45 points (X-values) = 120x45 samples.
Will the regression line be the same if it is computed with the mean of every 120 samples as if I would do it for all 120?
I am asking since MATLABs Curve Fit Tool Box do not accept multiple Y-values for the same X-values.
Comment: Coefficients should be the same, but variances will differ (this assumes that all y values are means based on the exact same number of observations. If $n_i$ differs you would have to use a weighted regression).
Comment: Just repeat the values! instead of having 120 y's for each x, replicate to have 120 x's with the same value. We could make some theoretical formulas, but it isn't worth the effort. Just replicate.
Comment: Okay, the variance is important to know. Do you have any suggestion how to solve my problem with multiple y-values for same x-values?
Answer: When we plot the regression line, it only includes the mean value of all the Y-values or we can say the expected value of Y. So you need to take the mean of 120 Y-values corresponding each X-value and then you should plot the regression line. Plotting a line for each of the 120 Y-values corresponding each X-value won't give a regression line.


Deleting migrate module tables post migration

Question: We did a massive migration a while back, several hundred thousand rows. Needless to say we now have a bunch of migrate tables that we could do without.
I've disabled the migrate modules but before I dropped the tables (or should I truncate?) I wanted to make doubly sure that this will have no affect on anything.
Thanks in advance.
Answer: So, I deleted the tables (actually truncated them) on my dev server and there have been no side effects that I have noticed, so will try deleting the tables in their entirely. The migrate tables made up around 600mb in a dump.
Answer: It seems it's usefull to keep the migrate tables while you are working on migration, in case you need to see the mapping and revert/redoing stuff.
But actually I was having some troubling while using the migrate module for other pursings. This SQL error: SQLSTATE[HY000] [2002] No such file or directory did keeping show up when I did try to use drush migrate:... till delete those tables.
With this query you can delete all table with prefix migrate
SET GROUP_CONCAT_MAX_LEN=10000;
SET @tbls = (SELECT GROUP_CONCAT(TABLE_NAME)
               FROM information_schema.TABLES
              WHERE TABLE_SCHEMA = 'db'
                AND TABLE_NAME LIKE 'migrate\%');
SET @delStmt = CONCAT('DROP TABLE ',  @tbls);
-- SELECT @delStmt;
PREPARE stmt FROM @delStmt;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


Ear training: the basics

Question: What do I do to start ear training? I want to have to end goal of being able to hear a melody and be able to recognize the notes. But how to I get there? I don't even have a clue on where to start at all, interval training? I would also like to learn how to recognize chords as well. Help would greatly be appreciated!
Comment: I'm inclined to vote this question as a duplicate, as there are already many good questions on learning [ear training](http://music.stackexchange.com/questions/tagged/ear-training?sort=votes&pageSize=50) on this site, such as [What are the specific progressive steps to take in basic ear training](http://music.stackexchange.com/questions/27471/what-are-the-specific-progressive-steps-to-take-in-basic-ear-training) and [What are the most effective ear training methods](http://music.stackexchange.com/questions/178/what-are-the-most-effective-ear-training-methods).
Answer: There are lots of techniques, tips, and tricks out there beyond the "How do you get to Carnage Hall?" answer so lets start a list.  This one was super helpful for recognizing intervals (especially when I came up with my own set of mnemonics)

Comment: "Carnage Hall"... I think I've heard some performances for which that would be an appropriate venue...

Ear training: the basics


How to add rest above a note in LilyPond

Question: I'm trying to typeset the following snippet of violin music. My first idea was to use two voices here but then I would not be able to make a slur between them. Is it possible without using manual placement of notes?
Answer: Since the lower voice is eighth notes and the upper voice is sixteenth notes, my recommendation would be to use separate voices. Here is one possible solution:
\version "2.19.63"

music = \relative c'' {
  <<
    {
      f16\rest b, e\rest a,
    }
    \\
    {
      \autoBeamOff
      f8 e
    }
    \\
    {
      \autoBeamOff
      \override NoteColumn.force-hshift = 0
      \hideNotes f16_( b) e,_( a)
    }
  >>
}

\score {
  \new Staff \music
  \layout { }
}

which compiles

Another option would be to put f16 b e, a in a single voice, but change the flags on the lower two pitches to be eighth notes instead of sixteenth notes.
Comment: Minor quibble:  The "hooks" of short rests should go in spaces (not on lines), i.e. that second rest looks better centred on "F" or possibly "D"  (not "E").


An example of abelian ring which is NOT square-free.

Question: Recall that a ring $R$ is abelian if all idempotents are central.
Recall that a right module $M_R$ is called square-free if whenever $A$ and $B$ are submodules of $M$ with $A\cong B$ and $A\cap B=0$ then $A=B=0$. The ring $R$ is square-free if $R_R$ is square-free.
My question is: Is there an example of an abelian ring which is NOT square-free?.
Thanks in advance.
Answer: Let $R=F_2[x,y]/(x,y)^2$ where $F_2$ is the field of two elements.
This ring is local and Artinian, and it has a nonzero socle made up of a direct sum of two copies of the simple module $R/(x,y)$.  This socle witnesses that $R_R$ is not square-free.
Comment: When i saw the question, I immediately knew that a local ring with nonzero nonsimple socle would suffice. So [that's the DaRT query I ran](https://ringtheory.herokuapp.com/search/results/?H=1&H=23&H=100l&L=98l).
Comment: Thanks alot. Excuse me, I have another question if you don't mind. I registered on the site. Now, I need an abelian $CS$-ring which is NOT square-free. The two keywords "abelian" and "$CS$" already exist in the dropdown menu. But what is the alternative for the square-freeness?.
Comment: @HusseinEid As you saw above, squarefreeness is not a direct option: i had to get around this.  [Here's the same query with CS added](https://ringtheory.herokuapp.com/search/results/?H=1&H=110l&H=23&H=100l&L=98l) but none of the hits are positive. Maybe these can be ruled out, maybe not, but it's a place to start.
Comment: I think the main problem will be that many rings may not have the CS property decided on them yet!


How to notate that the hand should be lifted after playing a note?

Question: In piano notation, how can I indicate for the player to lift his/her hand after playing a note that is being held with the pedal? My goal is to include choreographed movements within the score.
I've been advised to use laissez vibrer ties, but they get messy with other markings present in my score.
As of now, I have put the mallet lift sign over those notes (but I suspect it's 'legal' to do so):

Have you come across more common ways of indicating this?
Comment: Do you mean lift the hand away from the keyboard after holding the note for its full duration, or lifting off the key soon after striking the key, possibly even before the normal duration of the note has completed? If the former, why are trying to indicate that? It seems like where one's hands are between playing the notes indicated should be up to the personal preference of the player.
Comment: Like you want the musicians to be doing a sort of dance along with the playing? Interesting idea. Perhaps invent a system for choreography of motions and create an additional staff that would be lined up with the staff containing notes? Inventing notation and providing a guide to it at the beginning of the score has become not uncommon.
Comment: Why would this need to be indicated? The performer would probably do this as part of the performance without prompting.
Comment: @ToddWilcox I'm trying to indicate that the hand lift off the key soon after striking the key (and holding it with the pedal).
Comment: @Tim In my case, the player could choose not to lift the hand, because it's not absolutely necessary. However, I'm also orchestrating the choreography of movements.
Comment: There may be signs from the dance choreography world that will be relevent.
Answer: For something that specific (based on reading your comments) and extra-musical, just write that in plain English right into the score ("lift hands"). It sounds like you're trying to choreograph actual physical movements, which is beyond what is typically done in the score, and there is no sure way to communicate that through traditional musical notation.
Alternatives would be to use staccato, or a sforzando (if accent is required), or a short note value (1/16, 1/8, etc.), all pedaled, but there is no guarantee that the pianist will actually lift his/her hands off of the keyboard as you describe.
Answer: You want the keys pressed for a short time, so write a short note.  You want the pedal to hold the note, so write a pedal line.  If you want staccato impact, add a staccato dot.
Comment: Won't the pedalling obviate the staccato?
Comment: The length, yes.  But there's more to staccato than how long the key's held down.
Comment: @Tim That notation example covers a whole spectrum of different tonal effects, depending on the precise relative timing of the keyboard and pedal movements. Also, mechanical noises are an important constituent part of "piano tone" - a digital piano simulation that doesn't include the noise content doesn't sound very realistic.


How to get all the contents from a word file document and display it in a div using php?

Question: <code>$content = file_get_contents('filepath');
echo $content;
</code>
When a resume is uploaded I need to preview the resume as it is using PHP codeiginter.
Comment: did u implemented the same ?
Comment: Yes i implemented the same, but im getting data with encrypted form.. @ safin chacko
Comment: Why don't you use fopen();
Comment: https://github.com/PHPOffice/PHPWord
Answer: You can use this below function
<code>function read_docx("filePath"){

    $striped_content = '';
    $content = '';

    if(!$filename || !file_exists($filename)) return false;

    $zip = zip_open($filename);
    if (!$zip || is_numeric($zip)) return false;

    while ($zip_entry = zip_read($zip)) {

        if (zip_entry_open($zip, $zip_entry) == FALSE) continue;

        if (zip_entry_name($zip_entry) != "word/document.xml") continue;

        $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

        zip_entry_close($zip_entry);
    }
    zip_close($zip);
    $content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);
    $content = str_replace('</w:r></w:p>', "\r\n", $content);
    $striped_content = strip_tags($content);

    return $striped_content;
}
</code>


What causes my Rules error when trying to send an email if profile field contains some value?

Question: I'm using Rules and Profile2 in a D7 site.
I'm looking for help to check my logic for the following rule. I can't get it to work and don't know where I'm going wrong.
Event: After saving a new profile
Condition: Data Comparison--> Selected data: site:current-user:profile-main:field-become-a-distributor
Action: send e-mail
Condition is what breaks.  Here is what is in my error log:

Unable to get the data value for the variable or parameter data. Error: Unable to get the data property field_become_a_distributor as the parent data structure is not set.
Comment: Are you using profile 2 module and and field-become-a-distributor is your field ?
Comment: Yes.  That is exactly the case.
Comment: Any information on this? I´m lloking for this functionality too. Thanks!
Answer: Use Data selector account:field-YourField
Comment: Can you expand a little bit where setting this should be applied to?
Answer: Your question is a bit cryptic, but here are a few hints of what might possibly be causing your error:

The token site:current-user:... that you're using in your Rules Condition may not be the correct token to be used. E.g. think of some (super) admin (like user/1) who is triggering the Rules Event you're using (but for an account which is different from user/1) ... In this scenario, your Rules Condition refers to a field related to ... user/1 (and not the account that triggered the Rules Event).
You're trying to access that token in your Rules Condition, but are you sure its value is available? To be sure of that, preceed that Rules Condition by an "Entity has field" Rules Condition (for the account for which a new profile is being created, and for the field you're trying to use in your Rules Condition).
If none of the previous hints solve your issue, it may be that you also need to perform a "Fetch entity by ID" (for the account being created), as your first Rules Action. And then combine this with the execution of a Rules Component (with parameter the data returned by the "Fetch entity by ID"), whereas you replace your existing Rules Condition by an equivalent Rules Condition of that Rules Component, and with your existing Rules Action (to send an eMail) also  moved to an equivalent Rules Action in that Rules Component.
Comment: I guess this proves that it's never too late to answer "old" questions.
Comment: @NoSssweat : "***I guess***"??? I'd rather say there is no need for such guessing. Maybe you should rather ask something like "how do you find 'unanswered' questions like these, which are worth (still) posting an answer for?" ... Actually it's even more fun IMO to go after questions with accepted answers which are incoplete or wrong, and then post a correction / addition to those via an extta answer. PS: probably D4 or D5 tagged questions would be a real waste of time/effort ...


Delete from Multiple Tables using db_delete()

Question: How can we delete fields from multiple tables using db_delete() and INNER JOIN in Drupal 7?
Answer: You can't I'm afraid.
db_delete() takes a single string parameter to define which table the query is to be run against. There's no scope to provide more than one table at a time.
You can run any SQL statement you like, though, with db_query(), eg.
// Deletes all nodes and related author users...please don't actually run this!!
$sql = 'DELETE u, n FROM {node} n INNER JOIN {users} u ON u.uid = n.uid';
db_query($sql);

Comment: That `db_delete` takes a single parameter, without allowing an alias, is annoying. Otherwise, it would be possible to use JOINs similar to db_select.
Answer: Yes, db_delete takes a single parameter. You have to call db_delete() multiple times to delete data from multiple tables. Please see the following sample code:
/**
 * Implements hook_menu_delete().
 */
function block_menu_delete($menu) {
  db_delete('block')
    ->condition('module', 'menu')
    ->condition('delta', $menu['menu_name'])
    ->execute();
  db_delete('block_role')
    ->condition('module', 'menu')
    ->condition('delta', $menu['menu_name'])
    ->execute();
}

Source link:
https://github.com/drupal/drupal/blob/7.x/modules/block/block.module
https://api.drupal.org/api/drupal/modules%21block%21block.module/7.x


What is the isomorphism between the fields $(Z_2[x]^{<3},+_{x^3+x^2+1},\times_{x^3+x^2+1})$ and $(Z_2[x]^{<3},+_{x^3+x+1},\times_{x^3+x+1})$?

Question: They are both Galois fields of order 8.
I'm not exactly sure what the question means - how does one determine/describe an isomorphism?
Comment: This is essentially solved [here](http://math.stackexchange.com/q/787299/11619).
Answer: These are terrible notations for the fields $\mathbb{F}_2[x]/(x^3+x^2+1)$ and $\mathbb{F}_2[x]/(x^3+x+1)$. Since we have $(x+1)^3+(x+1)+1=x^3+x^2+1$, the isomorphism $\mathbb{F}_2[x] \to \mathbb{F}_2[x]$, $x \mapsto x+1$ maps $(x^3+x+1)$ onto $(x^3+x^2+1)$, so that it induces an isomorphism $\mathbb{F}_2[x]/(x^3+x+1) \to \mathbb{F}_2[x]/(x^3+x^2+1)$.
Comment: Can you explain why they are bad notations? It's what our professor seems to use.
Comment: Because it is clumsy and impractical to use systems of representatives (here polynomials of degree $< 3$), and to ignore the useful relationship to quotient rings. https://en.wikipedia.org/wiki/Quotient_ring
Comment: I guess it must be because we haven't seen quotient rings yet. Thanks for your time !