Unexpected behaviour in Lex

Question: I have written this code in my bas.l file
digit [0-9]

%%
{digit}{1,5} {printf("Small Number");}
^{digit}+$ {printf("Big Number");}
%%

int main(void){
    yylex();
    return 0;
}

Now I used lex and cc commands to build my lexical analyser and output an executable file.
Exact commands:
lex bas.l
cc lex.yy.c -ll

When I enter any 1-5 sized number, the lex analyser doesn't match with the first reg expression. It is always matching with the second one and prints Big Number.
Input:43
Output : Big Number

Input:4341
Output : Big Number

Input:434111
Output : Big Number

I expect my analyser to print out Big Number when I input a group of digits larger than 5 and Small Number when less than 5.
I tried removing the ^ and $ in the second reg expression and it works. The analyser matches numbers greater than 5 digits with the second reg expression and prints Big Number. It matches numbers with less digits than 5 with 1st reg expression and prints Small Number.
I want to know why it didn't work in the first case. How those ^, $ in second expression had to do anything with matching the first expression when the input is simply some three digit number like 324. Thanks in advance.
P.s: I do know that ^ matches occurrences at start of the line and $ at the end. Yet I don't see why 1st expression is not being matched.
Answer: I think the reason the anchored pattern (^...$) always matches is that it also includes the newline, so it is always the "longer" match, as per the Flex manual which says:

When the generated scanner is run, it analyzes its input looking for strings which match any of its patterns.  If it finds more than one match, it takes the one matching the most text (for trailing context rules, this includes the length of the trailing part, even though it will then be returned to the input).

In (f)lex, the $ is a "trailing context operator" which matches zero characters followed by a newline character, so the newline is included in the length of the match.  The other trailing context operator is \, so foo$ is the same as foo/\n.
Comment: Thanks. I didn't know that `$` had such a behaviour. Since`$` includes `\n`, length of match would be more and the second expression matches.

Unexpected behaviour in Lex


Understanding for loop in Python

Question: I am just learning Python and in the documentation the below example is mentioned and they have not mentioned the reason for this behavior.
words = ['cat', 'window', 'defenestrate']
for w in words[:]:
    if(len(w) > 6):
       words.insert(0,w)

From what I understand the above would iterate over the elements by first creating a copy of the original array and the syntax [:] means from the start position to the end position of the copy.
The documentation mentions that if instead of the above syntax we used the syntax
for w in words:
  if(len(w) > 6):
     words.insert(0,w)

It would create an infinite list with the word 'defenestrate' being inserted over and over again.
Can someone please explain such behavior and also if I could find the answer to my question by referring some other documentation.
Comment: Because if you're iterating over a list while constantly adding items to the end of it, how do you ever reach the end?
Comment: This is adding an element to starting position `words.insert(0,w)`
Comment: That's true, sorry. You're still extending the length of the list, though.
Answer: I think what you are looking for is mentioned at https://docs.python.org/3/reference/compound_stmts.html#for

Note There is a subtlety when the sequence is being modified by the
  loop (this can only occur for mutable sequences, e.g. lists). An
  internal counter is used to keep track of which item is used next, and
  this is incremented on each iteration. When this counter has reached
  the length of the sequence the loop terminates. This means that if the
  suite deletes the current (or a previous) item from the sequence, the
  next item will be skipped (since it gets the index of the current item
  which has already been treated). Likewise, if the suite inserts an
  item in the sequence before the current item, the current item will be
  treated again the next time through the loop. This can lead to nasty
  bugs that can be avoided by making a temporary copy using a slice of
  the whole sequence, e.g.,
for x in a[:]:
    if x < 0: a.remove(x)

Comment: Thanks for the answer... this makes sense as once an element is added before the current position the max length internal variable increases by one and each time the current element is treated again and again and the loop never finishes .. right?
Answer: for w in words: # means every element in list
    if(len(w) > 6): # this means will run only 'defenestrate' as only its len is greater than 6
        words.insert(0, w) # this will add 'defenestrate' back again before ending

Answer: Using the second way, the loop will go over each word or element in words, since only 'defenestrate''s length is greater than 6, the loop will add a duplication of defenestrate to the beginning of the list. This means the loop will run again over defenestrate as that word is now in the next position of the list. Since the loop now grows by one word per loop, the loop with never reach the end of the list.
In the first way, this bug is fixed as the list iterated over is a copy, so when defenestrate is duplicated in the list, the list the loop is looking at remains unmodified and the loop ends

Understanding for loop in Python


R code check for bootsrapping ChiSq Median Estimation

Question: I have a homework problem to write a function that bootstraps its way to finding the 95% CI of a df = 2 Chisq distribution median. My function seems to work, but from wiki I get the formula for the median as k(1 - 2/9k)^3 which yields .343 for k = 2. My function's CI is estimated at (1.28, 1.51) with a plenty large distribution, sample size, and number of simulations (100000). So the theoretical answer isn't anywhere in that interval. Can someone tell me where my code is failing please?
ChisqMedian_CI <- function(chiN, nsim, sampleN){
y <- rchisq(n=chiN, df=2)
medy_resample <- NULL
for (i in 1:nsim) {
  y_resample <- sample(y, replace=TRUE, size=sampleN)
  medy_resample[i] <- median(y_resample)
}
  LB <- quantile(medy_resample, probs=c(0.025))
  UB <- quantile(medy_resample, probs=c(0.975))
  return(c(LB, UB))
}

Comment: Maybe the answers to this question help somehow: https://stackoverflow.com/q/53533829/6574038
Answer: There are two issues here:

The median of a chi-squared distributed random variable is approximately
k * (1 - 2 / (9k))^3. For k = 2, this is about 1.4. This is in line with your results.
For (standard) bootstrap, the bootstrap samples are always as large as the original sample. So chiN is not necessary and would be set to sampleN.
Comment: Thank you. Very helpful. I guess I missed a necessary parenthesis or something when calculating that median manually in R. I did not realize 2 either. That was never made explicit to me before but makes perfect sense.


Angular Protractor - maxInstances option no longer works with chromedriver 90.0.4430.72

Question: Chrome has recently updated to 90.0.4430.72 on my machine (Mac OS) and when my protractor test suites run, they fail to run my tests correctly - I do have chromedriver updated as well to match the browser version.
I have tracked this down to the maxInstances protractor config option (in multiCapabilities section) which I have set to 4 instances currently.
The behaviour I observe is that I do see multiple chrome instances launched, 2 in my case as I have two test suite (spec files setup).
The initial step is to perform a login, and I notice that in one of the chrome instances the sending of keys to my login form inputs is being done twice, so a user name and password gets entered twice in the respective inputs, which fails login of course. But in the second chrome instance it just never connects to the target application.
In my console output, I see the following in relation to the first browser instance where i see the double entry of login details:

This seems like an issue with the tracking\connection of these instances thats crept in as part of the chrome\chromedriver v90 updates.
Setting the maxInstances option to 1 allows my tests to run as they did before, albeit without the benefit of parallel test executions.
Has anyone come across this with the recent update to Chrome, and if so have you got more than 1 instance running successfully in your test runs?
I am using protractor 5.4.4 and have tried the latest 7.0.0 version too.
Thanks
Answer:
I can see your browser (v90) doesn't match your chromedriver version (89). See here  https://stackoverflow.com/a/67100403/15614102 how to make them match

I think chrome v90 is not officially released. v89 is still recommended (not 100%)

If #1 doesn't resolve your problem, let the chromedriver team know you're seeing issues by filing a ticket. This might as well be a bug, and sometimes it's so much easier to just ask developer to fix it, since it's in both side's interests https://bugs.chromium.org/p/chromedriver/issues/list


Installing IIS from c# code on 64bit machine with 32bit application

Question: I'm trying to install IIS on a 64bit machine.
The installation is a 32bit c# application.
The code is as follows (taken from here):
<code>Process proc = new Process();
string cmd = @"C:\Windows\System32\pkgmgr.exe";
string cmdargument =
            @" start /w pkgmgr /iu:IIS-WebServerRole;IIS-WebServer;IIS-CommonHttpFeatures;
            IIS-StaticContent;IIS-DefaultDocument;IIS-DirectoryBrowsing;IIS-HttpErrors;IIS-HttpRedirect;IIS-ApplicationDevelopment;
            IIS-ASPNET;IIS-NetFxExtensibility;IIS-ASP;IIS-ISAPIExtensions;IIS-ISAPIFilter;IIS-HealthAndDiagnostics;IIS-HttpLogging;
            IIS-LoggingLibraries;IIS-RequestMonitor;IIS-HttpTracing;IIS-CustomLogging;IIS-Security;IIS-WindowsAuthentication;
            IIS-RequestFiltering;IIS-IPSecurity;IIS-Performance;IIS-HttpCompressionStatic;IIS-WebServerManagementTools;
            IIS-ManagementConsole;IIS-ManagementScriptingTools;IIS-ManagementService;WAS-WindowsActivationService;
            WAS-ProcessModel;WAS-NetFxEnvironment;WAS-ConfigurationAPI;NetFx3";

proc = Process.Start(cmd, cmdargument);
proc.WaitForExit();
proc.Close();
</code>
When the application is compiled to "AnyCPU" everything works fine.
But it is compiled with "x86" the PkgMgr window shows an error: "An attempt was made to load a program with an incorrect format".
I also tried to run the PkgMgr from the wow32 folder but it didn't work as well.
Any idea? Thanks.
Comment: Very hard to come up with a reason to not use AnyCPU.
Comment: The installer application is running some code that must be compiled with x86. Otherwise, it would be the best solution.
Answer: I think I found a solution, it is not optimal but it works.
I'm wrapping the PkgMgr execution with an AnyCPU compilation and does the work.
I still would like to find a more "right" solution.


Entity Data Model - Adding a keyless table

Question: Visual studio is giving me a trail of errors that I have hit a dead end on. I am trying to add an existing table in a database to my data model. I understand that the table should have a key, but it doesn't and I can't fix that; it isn't my database to re-design.
When I first try to add the table, I get this error:

The table/view
  'BT8_GC.dbo.SAVED_QUERY_CATEGORY' does
  not have a primary key defined and no
  valid primary key could be inferred.
  This table/view has been excluded. To
  use the entity, you will need to
  review your schema, add the correct
  keys, and uncomment it.

Ok, fine, I'll define the keys for it and uncomment. Here is the block I uncomment, after manually defining the keys (I also had to add the nullable=false part):
<code>      <EntityType Name="SAVED_QUERY_CATEGORY">
    <Key>
      <PropertyRef Name="SQC_CAT_ID"/>
      <PropertyRef Name="SQC_USER_ID"/>
    </Key>
    <Property Name="SQC_CAT_ID" Type="int" Nullable="false" />
    <Property Name="SQC_USER_ID" Type="int" Nullable="false" />
    <Property Name="SQC_CAT_DSCR" Type="varchar" MaxLength="50" />
    <Property Name="SQC_SEQ_NO" Type="int" />
  </EntityType>
</code>
Nope, now the designer won't open. Go back into the file, and Intellisense shows this error:

Error 11002: Entity Type 'SAVED_QUERY_CATEGORY' has no entity set.

Ok... Uncommenting created a new error. After adding an entity set:
<code><EntitySet Name="SAVED_QUERY_CATEGORY" EntityType="IssueModel.Store.SAVED_QUERY_CATEGORY" store:Type="Tables" Schema="dbo" />
</code>
Yay! The designer opens! Still not there yet, because while it shows up under the store's Tables/Views folder, it has not Entity Type in the model. Can't call it from my code. I don't have any errors to work off though, so I tried creating an entity set mapping, but that results in the error "does not exist in MetadataWorkspace".
So that's what I have tried. How do I get this poorly designed table into my data model?
Comment: For posterity, you must add a child XML element `EntitySet` to a `EntityContainer` in the `Schema` element.  In my case, the `EntityContainer` was autogenerated in collapsed form, so I had to poke around to figure it out.
Answer: By modifying XML you have only added information about database table. Now you have to open toolbox and add entity to your model in the designer. Configure the entity to have properties as you need. Then open mapping details and map the new entity to your table.
Btw. once you modify the XML describing database manually you cannot use update from database anymore - VS designer will always delete your changes and you will have to do them again.
Comment: Unfortunately no. You can either modify database to contain primary key (you mention you can't), write some script to automate EDMX modification and run it after each update, try some [commercial designer extension](http://www.huagati.com/dbmltools/) or abandon EDMX and use code first (entity framework 4.1).
Comment: Is there another way to add a table then, one that will not be deleted when I later update the model?


Domain Controller DNS alias

Question: I recently updated an old Win2008R2-based domain to a new Win2019-based one (with the common promote / demote / decommission dance). This was for a very small office (3 peoples), so this is a single-DC setup where both the old and the new DCs doubled down as fileserver.
For this reason, I created a DNS alias to point the old name (ie: olddc.example.com) to the new one (ie: newdc.example.com). So far, so good: all client could reach the new DC/fileserver both with the old and the new names. However, I forget to formally add to the new DC the old DC's name (as an alias). In other words, I did not issue something similar to:
netdom computername newdc.example.com /add:olddc.example.com

Today I was on the new DC and, out of muscle memory, I tried to reach its own shares via the old names (opening Explorer and writing \\olddc.example.com). Explorer immediately complained about "wrong credendials" and, indeed, a Wireshark dump shown STATUS_LOGON_FAILURE. I issued the netdom command above (adding olddc.example.com as an alias) and the problem went away: the server is now able to see its own shares via the old name.
I know and understand why the alternate/alias name should be added via netdom (or through a separate setspn command). However, what surprises me is that all the Win10 clients shown no complains at all even when such alternate name was not provided.
So, why do the Win10 clients worked with not issues at all while the server immediately walked back from accessing its own shares with a "unknown" DNS alias? Is it due to some different settings between Server and Client OSes? Or is it related to accessing a loopback share?
Answer: Loopback SMB connections are indeed treated differently from external ones: https://docs.microsoft.com/en-us/troubleshoot/windows-server/networking/accessing-server-locally-with-fqdn-cname-alias-denied.
(The article references Windows Server 2003, but it still applies.)
Comment: I did not know about the loopback check! Thank you so much.
Answer:
The Problem
On Windows machines, file sharing can work via the computer name, with or without full qualification, or by the IP Address. By default, however, filesharing will not work with arbitrary DNS aliases. To enable filesharing and other Windows services to work with DNS aliases, you must make registry changes as detailed below and reboot the machine.

The Solution
Allowing other machines to use filesharing via the DNS Alias (DisableStrictNameChecking)
This change alone will allow other machines on the network to connect to the machine using any arbitrary hostname. (However this change will not allow a machine to connect to itself via a hostname, see BackConnectionHostNames below).

•   Edit the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\lanmanserver\parameters and add a value DisableStrictNameChecking of type DWORD set to 1.

Domain Controller DNS alias


Fetching DLLs from NuGet if Deleted

Question: I've done a fair bit of reading on NuGet, and I can't seem to find what I want. Essentially, I'm hoping that it will work like Apache Ivy, where you can just check in your config file (without any binaries) and tell NuGet to fetch all the DLLs -- thus saving you from versioning tons of DLLs.
Hence: is there a command in NuGet to fetch and configure all dependencies mentioned in packages.config?
Again, the case for this is that I only checked packages.config into source control, not the actual DLLs, and I need to re-fetch everything. (Preferably without fetching packages one by one by name).
Answer: This has been covered recently in blog posts:

Inbuilt functionality for this is coming in a future version of NuGet: http://feeds.haacked.com/~r/haacked/~3/x8g_kFzD4eA/feedback-request-for-using-nuget-without-committing-packages.aspx
(Linked from above) How to do this today using command line NuGet.exe (available from the NuGet pages on CodePlex): http://blog.davidebbo.com/2011/03/using-nuget-without-committing-packages.html

EDIT: Now also covered on NuGet's Documentation Pages

Fetching DLLs from NuGet if Deleted


the following function : $(t,x)\mapsto tx$ from $[0,1]\times A$ to $X$ is continous

Question: Let $X$ be a Banach space and $A$ be a nonempty closed subsets of $X$.
Consider the following function: $(t,x)\mapsto tx$ from $[0,1]\times A$ to $X$.
Show that it is continous function:
My effort:
Let $(a,x) $ and $(b,y)$ in $[0,1]\times A$, we have:
$$
\|ax-by\|\leq \|ax-ay\|+\|ay-by\|=|a|\|x-y\|+|a-b|\|y\|
$$
then, if  $(a,x) $ tends towards $(b,y) $ we have:
$$
\|ax-by\|\to 0
$$
Then this function is continous.
This is true.?
Comment: Looks correct, but it's better and more clear to take actual sequences and show sequential continuity.
Comment: Yes this is fine, as the above commenter said use sequences. Also, this does not require the space to be Bamach, all normas spaces are topological vector spaces.
Answer: Let $(X,||\cdot||)$ a normed vector space (not necessarily a Banach space) and the map
\begin{equation*}
\begin{split}
f : [0,1] \times A & \to X \\
(\alpha, x) & \mapsto \alpha x
\end{split}
\end{equation*}
where $A\subset X$ is a non-empty closed subset of $X$. Then,
\begin{equation*}
\begin{split}
||f(\alpha,x)-f(\beta, y)|| & =||\alpha x-\beta y|| \\
& =||\alpha x-\alpha y+ \alpha y-\beta y|| \\
& \leq ||\alpha x-\alpha y||+|| \alpha y-\beta y|| \\
& = |\alpha|\cdot ||x-y||+||y||\cdot|\alpha-\beta|
\end{split}
\end{equation*}
Since $A$ is closed, then for every $x\in A$ there exists a sequence $\{x_n\}\subset A$ that converges to $x$. Analogously, since $[0,1]$ is closed, then for every $\alpha \in A$ there exists a sequence $\{\alpha_n\}\subset [0,1]$ that converges to $\alpha$.
Hence, for every $\varepsilon>0$ we can pick $y\in A\backslash \{0\}$ and $\beta\in [0,1]$ such than
$$||x-y||\leq \frac{\varepsilon}{2|\alpha|}, \quad |\alpha-\beta|\leq \frac{\varepsilon}{2||y||}$$
and the previous inequality is written as
$$ ||f(\alpha,x)-f(\beta, y)|| \leq |\alpha|\cdot ||x-y||+||y||\cdot|\alpha-\beta|\leq |\alpha|\frac{\varepsilon}{2|\alpha|}+||y||\frac{\varepsilon}{2||y||} = \frac{\varepsilon}{2}+\frac{\varepsilon}{2}=\varepsilon$$
Observe that this argument does not hold when $\alpha=0$. However, we can write for this case
\begin{equation*}
\begin{split}
||f(\alpha,x)-f(\beta, y)|| & =||\alpha x-\beta y|| \\
& =||\alpha x-\beta x+ \beta x-\beta y|| \\
& = |\beta|\cdot ||x-y||+||x||\cdot|\alpha-\beta|
\end{split}
\end{equation*}
and use an analogous argumentation.


Ubuntu 16.04 - Login not working in external SSH Clients

Question: I've got a DigitalOcean droplet which is running on Ubuntu 16.04 which I am trying to access via PuTTY (the SSH client).
Whenever I connect to the droplet, I am prompted with the user login as expected, however after putting in the password for a user account, it asks for it again as though the password was incorrect. I can clarify 110% that the password is correct. See below:
I can access the console through the droplet's control panel on the DigitalOcean website, and the login details I am using are identical to that of PuTTY.
Using the console that I can use through the DigitalOcean control panel, I have checked my UFW settings and OpenSSH is allowed in its entirety.
How can I solve this issue? I need SSH access from PuTTY and other external terminals.
Comment: Consider the possibility that your server is compromised and collecting passwords.
Answer: Using user/password for cloud instances is not recommended as passwords can be hacked.
Instead, use ssh keys.
While you are logged into the instance through the web console, type:
ssh-keygen -t rsa

and keep pressing 'Enter' until you get a new prompt line.
That will generate a private and public keys for your instance.
Next, type:
cat ~/.ssh/id_rsa

Copy the content and paste it to a file in your windows machine (Notepad++ is recommended for this as notepad may add extra invisible characters), example:
my_private_key.pem
Next, download PuttyGen, open it and load the key file you created, then click save private key and overwrite the key file (my_private_key.pem).
Then configure Putty like:

In the left pane, expand Connection -> SSH -> AUTH and in the right
pane click "Browse" and choose the key.
In the left pane again, click "Data" and insert the username you use to login to the instance.

Go back to "Session" fill in the public ip of the instance, give the connection a name and click "Save".
Then double-click the name you gave the session and it should connect automatically using the private key and without the need to enter a password.


Calculating height of a binary tree

Question: I tried to implement a method to calculate height of a binary tree by creating a method internal to the binary tree class. It is showing the error None Type object doesn't have attribute height.
here is the code:
def height(self):
    if self==None:
        return 0
    else :

            lheight=self.leftChild.height()

            rheight=self.rightChild.height()

            if lheight>rheight:
                return lheight+1
            else:
                return rheight+1

Comment: @idos actually checked that also, but then it is showing that the rheight is referenced before assignment.
Answer: Problem is that you dont check if right or left are None...
For every node before you set lheight and rheight check first that they are not None
if self.right is not None:
    rheight = self.right.height()

They don't check it theirselves because they just don't call height() - None Type has no height() function, the error stands there
Comment: i did this but now it is showing the error- variable lheight referenced before assignment.
Comment: Create it before condition and assign 0 to it (if there is no right, its "height" is 0)
Comment: thanks..but I have one question..in the successive function calls how are the values of lheight and rhight being retained. Shouldn't they be initialized to 0 when the function gets called ?
Comment: Sorry but I can't understand your question... Explain it to me plz
Comment: yeah...actually what I am asking is that I have initialized both of them to 0 and It is working but since for each left and right child  the function is being called the variables lheight and rheight will be again and agin initialized to 0 right ?
Comment: OK. If I understood right your'e asking about different calls of the function - the function is called a lot of times in one height calculation - why lheight and rheight don't override themselves?
Is that the question?
Comment: OK very good question:)
For every new call of a function the interpreter leaves the caller aside for a moment, preforms the called function and then returns to the caller, and continues its code.
This caller list ( a function in a function in a function) is called the `stack`.
Anyway, when a function calls itself, the interpreter treats the caller and called as completely separate functions, stored in separate memory and everything. The lheight of one call is not the same variable as the lheight of the other.

Calculating height of a binary tree


Varnish sending bad "Host" header to Apache

Question: I'm in the early stages of testing Varnish 3.0.4 as a new front end for a web service. I have varnish configured to listen on port 88. For its backend it's using an existing apache server running on the same host on port 80.
The trouble I'm having is that when varnish makes a request to apache, it's including ":88" in the Host http header (even though it's definitely connecting to apache on port 80.
For example:

I request http://www.myservice.com:88/images/foo.gif. It makes a request to the backend.
The apache backend logs the HOST header to the Apache access log - using %{Host} in the log file format
The access log shows this host header as www.myservice.com:88, not www.myservice.com.

If I connect to this apache server with telnet and make identical HEAD requests but altering the value of the Host header, I see the same behavior that I witness through varnish - i.e. if I include the :88 in the host header, the request returns 404.
I've tried:

altering req.http.header.port and beresp.http.header.port to 80
altering req.http.header.host and beresp.http.header.host to www.myservice.com.

Seems like I'm missing something obvious.
How do I get varnish to send a proper Host header to apache?
Comment: Please post the relevant portions of your vcl file. Also, what version of varnish?
Answer: Varnish leaves the Host header completely unmolested by default - it's sending to Apache what was sent to it.  This is intended behavior - Varnish tends not to fiddle with anything unless you tell it to.
To manipulate it, put something like this in your vcl_recv, in addition to any conditional logic you need to add:
set req.http.Host = "www.myservice.com";

Comment: Had this exact problem with Varnish 3.0.5 and this answer didn't work for me unless I did `set req.http.host` in lower-case. Not sure if this is a bug introduced in 3.0.5 or what.


Django CMS - check if placeholder is empty

Question: I use:

DjangoCMS 2.4
Django 1.5.1
Python 2.7.3

I would like to check if my placeholder is empty.

    {% placeholder "my_placeholder" or %}
    {% endplaceholder %}

I don't want the html between the placeholder to be created if the placeholder is empty.
{% if placeholder "my_placeholder" %}

    {% placeholder "my_placeholder" or %}
    {% endplaceholder %}

{% endif %}

Answer: There is no built-in way to do this at the moment in django-cms, so you have to write a custom template tag. There are some old discussions about this on the django-cms Google Group:

https://groups.google.com/forum/#!topic/django-cms/WDUjIpSc23c/discussion
https://groups.google.com/forum/#!msg/django-cms/iAuZmft5JNw/yPl8NwOtQW4J
https://groups.google.com/forum/?fromgroups=#!topic/django-cms/QeTlmxQnn3E
https://groups.google.com/forum/#!topic/django-cms/2mWvEpTH0ns/discussion

Based on the code in the first discussion, I've put together the following Gist:

https://gist.github.com/timmyomahony/5796677

I use it like so:
{% load extra_cms_tags %}
{% get_placeholder "My Placeholder" as my_placeholder %}

{% if my_placeholder %}

    {{ my_placeholder }}

{% endif %}

Comment: It's a template tag so you have to create a folder called `templatetags` in one of your applications, create a file (`extra_cms_tags.py` for example) then in your template call `{% load extra_cms_tags %}` to import it
Comment: Don't forget to add `__init__.py` to your `templatetags` folder ;). See [custom template-tags documentation](https://docs.djangoproject.com/en/1.7/howto/custom-template-tags/) for more details.
Comment: I'm a beginner. Where should have put the file ?
Comment: If you keep scrolling there's a better answer: https://stackoverflow.com/a/36098323/1605873
Answer: If you want additional content to be displayed in case the placeholder is empty, use the or argument and an additional {% endplaceholder %} closing tag. Everything between {% placeholder "..." or %} and {% endplaceholder %} is rendered in the event that the placeholder has no plugins or the plugins do not generate any output.
Example:
{% placeholder "content" or %}

There is no content.

{% endplaceholder %}

Comment: This is great, but it doesn't let you output HTML content only if the placeholder is not empty.
Comment: This should be the correct answer. Super simple and does not require template tags.
Comment: @Flimm I'm not sure in which version did you try and it didn't do that, but on `django-cms==3.4.6` it works like a charm: the content between the tags appears ONLY if the placeholder is empty.
Answer: Here's a very compact solution.
Template filter:
@register.filter('placeholder_is_empty')
def placeholder_is_empty(request, slot):
    page = request.current_page
    placeholder = page.placeholders.get(slot=slot)
    return placeholder.cmsplugin_set.exists()

Usage in template:
{% if request|placeholder_is_empty:'myplaceholder' %}

Here comes some content...

{% endif %}

Comment: Why not return placeholder.cmsplugin_set.exists()?
Comment: Is this still needed in 2019, or are there better tools nowadays? it still works, but wonder if there is a "builtin" way?
Comment: Yes, @jabez, exists() is better. I've edited my answer.
Comment: Trying to implement this feature myself, where would I put the Template filter file?
Comment: @jmona789, this is explained very well here: https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/
Answer: Depending on what you are trying to achieve, you can simply use CSS to hide the element if doesn't have content using the :empty selector. And if you are worried about white spaces you can use Django's in-build {% spaceless %} template tag to remove them.
So you'd get this template:
{% spaceless %}

    {% placeholder "my_placeholder" %}

{% endspaceless %}

And this CSS:
hide_if_empty:empty {
    display: none;
}

Not exactly what was asked for as it doesn't remove the HTML - but this will solve the most common case where one wants to check if a place holder is empty, and doesn't require the introduction of a new template tag.
Answer: 2023 update
Accepted answer https://stackoverflow.com/a/17148137/5322302 has issues with latest DjangoCMS.
Updated solution (credits for F.B. from DjangoCMS community).
Tested with Django CMS 4.
{% load get_placeholder %}
...
{% get_placeholder "content" as placeholder_content %}
{% if placeholder_content %}

{{ placeholder_content }}

{% endif %}

code of the templatetag .../templatetags/get_placeholder.py
from classytags.arguments import Argument, MultiValueArgument
from classytags.values import StringValue
from django import template
from django.utils.safestring import mark_safe

from cms.models.placeholdermodel import Placeholder as PlaceholderModel
from cms.templatetags.cms_tags import (
    DeclaredPlaceholder,
    Placeholder,
    PlaceholderOptions,
)

register = template.Library()

class RenderGetPlaceholder(Placeholder):
    """
    Render the content of a placeholder to a variable. Can be provided
    with the name of the placholder (i.e. "Header" in the case of a normal
    CMS page) or a template variable containing a placeholder (i.e. myentry.content in the
    case of an external app using a placeholder)

    {% get_placeholder ["string"|placeholder_var] as variable_name %}

    e.g.
    {% load extra_cms_tags %}
    {% get_placeholder "My Placeholder" as my_placeholder %}

    {% if my_placeholder %}

        {{ my_placeholder }}

    {% endif %}
    """

    name = "get_placeholder"

    options = PlaceholderOptions(
        Argument("name", resolve=True),
        MultiValueArgument("extra_bits", required=False, resolve=False),
        "as",
        Argument("varname", resolve=False, required=True),
        blocks=[
            ("endplaceholder", "nodelist"),
        ],
    )

    def render_tag(self, context, name, extra_bits, varname, nodelist=None):
        if isinstance(name, PlaceholderModel):
            content = name.render(context, None)
        else:
            content = super(RenderGetPlaceholder, self).render_tag(context, name, extra_bits, nodelist)
        context[varname] = mark_safe(content)
        return ""

    def get_declaration(self):
        # Fix some template voodoo causing errors
        slot = self.kwargs["name"].var.var.__str__().strip('"').strip("'")

        return DeclaredPlaceholder(slot=slot, inherit=False)

register.tag(RenderGetPlaceholder)

Answer: Based on the great answer form @Philip Zedler, a solution that works for both placeholder on django-cms pages, but also on placeholders "outside of the cms".
@register.filter()
def placeholder_empty(page_placeholder, slot=None):
    """
    for page/slot, pass a page object, and a slot name:
    {% if request.current_page|djangocms_misc_placeholder_empty:"content" %}

    for a outside page placeholder, just the placeholder object:
    {% if object.placeholderfield|djangocms_misc_placeholder_empty %}

    also, with:
    {% with ph_empty=object.placeholderfield|djangocms_misc_placeholder_empty %}
    """
    placeholder = None
    if isinstance(page_placeholder, Placeholder):
        placeholder = page_placeholder
    elif isinstance(page_placeholder, Page):
        page = page_placeholder
        try:
            placeholder = page.placeholders.get(slot=slot)
        except Placeholder.DoesNotExist:
            pass
    if placeholder:
        # // return not placeholder.cmsplugin_set.filter(language=get_language()).exists()
        return not placeholder.cmsplugin_set.exists()
    return False

usage in template
{% if request.current_page|placeholder_empty:'content' %}

Fallback!

{% endif %}

It's in my djangocms-misc package
Answer: I took the extra compact solution here and created a templatetag that checks if a static placeholder is not empty:
from cms.toolbar.utils import get_toolbar_from_request

@register.filter("static_placeholder_is_not_empty")
def static_placeholder_is_not_empty(request, slot):

    placeholder = StaticPlaceholder.objects.get(code=slot)

    if get_toolbar_from_request(request).edit_mode_active:
        placeholder = placeholder.draft
    else:
        placeholder = placeholder.public

    is_not_empty = len(placeholder.get_plugins(request.LANGUAGE_CODE)) > 0
    return is_not_empty

It's used like this:
{% load my_new_shiny_templatetag %}

{% if request|static_placeholder_is_not_empty:'my_static_placeholder' %}

{% endif %}

{% static_placeholder "my_static_placeholder" %}

{% if request|static_placeholder_is_not_empty:'my_static_placeholder' %}

{% endif %}


Where can I get a opinon / review about my music? I'm self-taught, so music college is not an option

Question: When I got enough time I learn and try to compose at least a simple piece of music but I don't know a place where it's sure that I would get criticism and opinion about it and if I make something good than it won't be copied.
I tried to create some dungeon synth and synth song weeks ago.
I frist tried soundcloud with the synth songs...well...I didn't have much practice back than but still because I don't have big and successfull statistics I can't even find myself on the page which is pretty ironic.
I tried bandcamp with my dungeon synth music as a "totally free album". I even send the link to one of the D.Synth youtube channels but my I'm not professional so I'm exactly where I'm with soundcloud.
Now the more classical like ones I don't have much idea. I'm pretty beginner so I don't wanna make it complicated with own web sites and all sort of things.
About the classical part...I've been composing more "orchestral-like" music recently. I cannot say it's pure classical because I still have much to learn about music theory so there's at least as much intuition and improvisation as much theory (if not more) but still it's not professional so I don't wanna go to paid web pages or anything like that.
Also I'm afraid I'm a little paranoid about "What if my song got copied?" thing. I understand that I have to create something good enough but I don't know if there is a way to make it a little bit more safe.
Comment: please add something about the style of your music, that could matter when looking for an audience.
Comment: You could ask for opinions on Gearslutz or the SOS forum. Both have 'post your music' sections. Better gird your loins though, not everyone is encouraging and polite.
Answer: Posting online to random unqualified sources will earn you random, unqualified feedback. Yes, college might not be an option for you, but there's nothing wrong with reaching out to the graduate students of a college and asking for lessons.
I suggest emailing a professor at a local college and ask if there are any graduate composition students interested in giving private lessons. You might get a bite. Remember that when you ask for feedback, you're asking to make your music better not be petted like a cat. Don't ask family members or friends.
Last, and this is a cold truth: no one will steal your music because no one cares enough about you or your music to steal it. I have no use for some beginner's music. That said, don't post your tracks Willy-nilly online because robots can and do steal recordings and post them on other sites. Control your content as much as you can. Tough words but hopefully they release you from feeling paranoid. Focus on your passion, not your fear.
Comment: Unfortunately, I've actually had one of my original compositions stolen and used without credit. Because I publish on Musescore, which reveals sheet music by default, I've figured that copying is inevitable, so I publish all my compositions with the Creative Commons Attribution license. ...Which means that all I did (and really felt like I could do) was make the user provide the proper credit. ...I'm actually more sore about the transcription of another Musescore user's work that I released with his/her permission that got stolen in a similar fashion, complete with crediting neither of us.
Answer: You have a lot to 'unpack' in your question: beginner, self-taught, opinion, review, criticism, copyright.
I'll skip the copyright part. That's law. Read up on that and handle your music accordingly.
Some personal observations:
Music professors will offer technical advise on the craft of writing. From an emotional perspective they will encourage you to keep writing. You are more likely to hear something like 'you did this here, but you could also have done option 2 or option 3.' You probably won't hear 'you did this here and it moved me deeply.'
Students will offer all kinds of emotional reactions. But, it typically goes two ways: the praise for you that they really want to hear about themselves, or the harsh payback critique from someone you have criticized.
Friends and family will usually say something like: 'that's nice.' Occasionally, you might get 'I could never write music.'
All the above are generalizations, but based on real experiences.
Once my wife voluntarily said she like a 'Gay 90's' style waltz I wrote.
The only real emotional comment I ever heard was from a co-worker/friend who listened to an 8 bar, minor key, exercise I wrote. He said: 'damn, why you gotta be making me cry!' From the perspective of craft I have no idea why I got that reaction. It was an electronic playback with strings and oboe, slow tempo, and some non-chord tones.
Those were nice compliments, but in terms of development it didn't help me much.
So, having shared all that I think you should ask yourself this: as a beginner what exactly do you want? Do you want the kind of feedback a professional would give? Do you want emotional feedback with no insight to the craft or worst is not genuine?
Of course that question is rhetorical. My advice is to get the advice of professionals or at least those with a serious approach to learning the craft.
Try to distinguish between: opinion, criticism, review, etc. Mere opinion is not objective, an audience of one. Formal criticism should be de-personalized and based on some objective understanding, the realm of the professionals. A review is written to inform the public, it could be good or bad, but 'there's no such thing as bad publicity.' Online followers, likes, etc. I would put in the review category, because in the end those are about publicity.
Wanting feedback from lots of people is a natural desire, but I really think it is more important to develop a good sense of self criticism. Good teachers should advise you at a level appropriate for your level. The more you push yourself, the deeper the advice you can then receive. Seek out quality relationships not the greatest number of commentators.
Two final anecdotes.
After college I kept studying. Eventually I mailed a collection of short pieces to that composition professor form college. I think I attached a short letter, but I can't remember exactly. I didn't know if I would get a reply. To my surprise he telephoned me and then wrote back a short letter. He gave me a few tips and words of encouragement.
More recently I send some 'cold' emails to two professors who wrote theory books I really like. I explained how I was trying to apply ideas presented in the books to my studies. In one case I attached a score for a sonata exposition. I received replies from both professors including a copy of my score with revisions from the professor.
I took me a long time to build up the nerve to approach those professors as I was not one of their students. I made sure to be brief and specific and appreciative. No vague questions. No nagging follow up emails.
You could try reaching out to people this way, but make sure you start with critiquing yourself.
Comment: My family actually generally aren't supportive of my compositions. My mom thinks it's a waste of time. My brother (and actually some other listeners) thinks I'm too chord-heavy. (Granted, he prefers the arpeggio-heavy Touhou music more.) My cousin is supportive, though, but we've been estranged for years.


Composer is not recognizing PHP 7

Question: I created a travis profile to test my project from PHP 5.6 to PHP 7.
I am getting the following error when composer is run:
Your requirements could not be resolved to an installable set of packages.
  Problem 1
    - This package requires php ~5.4 but your PHP version (7.0.1-dev) does not satisfy that requirement.

the command that I am running is:
composer update -n

with travis set to environment PHP 5.6 I do not run into this issue
Comment: Can you please provide the require-block of your composer.json?
Answer: If the platform requirement is in your root package, you can solve it by amending composer.json as such
{
    "require": {
        "php": "~5.4 | ^7.0"
    }
}

You could also try to ignore platform requirements, but depends on whether you actually want to see that happen:
$ composer install --ignore-platform-reqs

For reference, see https://getcomposer.org/doc/03-cli.md#install.
Comment: I dont like using --ignore-platform-reqs as I'm using travis to do continuous tests.
Comment: How about adjusting your platform requirements as suggested, @azngunit81?
Answer: A package that you use, or your own software itself, explicitly requires a PHP 5.x version (~5.4), with x being at least 4, or higher (i.e. it would run with PHP 5.5, 5.6, or even 5.10 if it would exist).
This package does not allow PHP 7. That's why you cannot run composer update successfully.
Comment: had a php block in the required `"php": "~5.4",`. tks
Answer: check your composer.json file,
delete this code:
 "config": {
    "bin-dir": "bin",
    "platform": {
        "php": "5.x.1"  // Or change 5.x.1 to your php version
    }
},

Comment: Resolved my issue. I was running PHP7, but it kept saying I was on 5.5.9. This was why. Thanks!
Answer: change php default V
sudo update-alternatives --config php

Composer is not recognizing PHP 7


Equivelant of node_type_load() for entity bundles

Question: If I know the entity type and bundle, I want to load the bundle object with its settings. Drupal core has this for nodes, but is there any way to do it for entities?
See node_type_load() in core:
https://api.drupal.org/api/drupal/modules!node!node.module/function/node_type_load/7
EDIT: So to elaborate, I'm asking about a way to load up the data about the entity bundle, not a specific entity.
E.g.
var_dump(node_type_load('page'));

object(stdClass)[628]
  public 'type' => string 'page' (length=4)
  public 'name' => string 'Page' (length=4)
  public 'base' => string 'node_content' (length=12)
  public 'module' => string 'node' (length=4)
  public 'description' => string 'Use pages for your static content.' (length=43)
  public 'help' => string '' (length=0)
  public 'has_title' => string '1' (length=1)
  public 'title_label' => string 'Title' (length=5)
  public 'custom' => string '1' (length=1)
  public 'modified' => string '1' (length=1)
  public 'locked' => string '0' (length=1)
  public 'disabled' => string '0' (length=1)
  public 'orig_type' => string 'page' (length=4)
  public 'disabled_changed' => boolean false

Comment: have you tried entity_get_property_info() like i suggested below ?
Answer: You can use entity_get_property_info() for example
var_dump(entity_get_property_info('node'));

Bundles are a keyed array within the result and they contain a keyed array of the fields and their settings.
Other information about the bundles other than field properties, such as menu callback etc, can be obtained using entity_get_info() where the bundles as keyed array within the result contains other non-field info.
Answer: I guess I am not 100% sure what you need here. However, as nodes are entities there will be a way to load other entities. You have entity_load for example. If this is not what you need could you elaborate?
Comment: For example: `$wrapper = entity_metadata_wrapper('node', NULL, array('bundle' => 'page'));` has a lot of information, possibly way too much for your needs.
Comment: Have updated question with example output of `node_type_load()`.
Comment: Ok, are there particular settings from the node_type_load var_dump that you need. You can load up a lot of information with [EntityMetadataWrappers](https://www.drupal.org/documentation/entity-metadata-wrappers). Depending on what you are trying to do with the information [EntityFieldQuery](https://www.drupal.org/node/1343708) might help as well. Let us know which properties, settings etc. you are looking for and we can help you narrow it down.


Code with isdigit and isalpha . C programming language

Question: I've tried to use %c but  then the printf afther while , prints 2 times. With %s I solved the problem but I get warnings. Also i tried a different version of the code with but after the printf the program stopped:
enter code here

char k;

while(isalpha(k))

printf("put number not a letter");

scanf("%d", &k);

********************************Code I have problem with is  The one down there*******************
**
#include <stdio.h>
#include <ctype.h>

int main(){

   unsigned char a;

    printf("Put a number");
    scanf("%c", &a);

    //that checks if the input contains letters
    while(!(isdigit(a))){
        printf("you have put a letter not a number,put a number again:\n");
        scanf("%c", &a);

    }
    if(isdigit(a)){
        printf("you have put a number %c", a);
    }

Comment: The trouble is that when you type `a` and hit return, you enter two characters, neither of which is a digit. So, after reading and rejecting the `a`, it also reads and rejects the newline. You could help yourself (and your user too) by modifying the error message to something like: `printf("You entered %c, which is not a digit; please enter a digit: ");` (the newline is optional for a prompt). Use the [suggestion](https://stackoverflow.com/a/61152093/15168) by [@Breakpoint](https://stackoverflow.com/users/9345287/breakpoint) — use a leading blank in the format (but never a trailing blank).
Answer: while(!(isdigit(a))) {
...
scanf(" %c", &a);
       ^ This is a white space

This will solve the problem of printing two times and warnings (if any)


About a definition of skew field and field, with example $\{0\}$

Question: I use following definitions from Corso di geometria-Stoka Marius-CEDAM-1995:

let be $(C,+)$ a commutative group and $(C,\cdot)$ a semigroup $$(C,+,\cdot) \text{ is ring iff }\begin{cases}
 \forall x\in C, \forall y\in C, \forall z\in C: (x+y)\cdot z=(x\cdot z)+(x\cdot y)\\
 \forall x\in C, \forall y\in C, \forall z\in C:  x\cdot (y+ z)=(x\cdot y)+(x\cdot z)
\end{cases}$$
let be $(C,+,\cdot)$ a ring $$(C,+,\cdot) \text{ is commutative ring iff }
 \forall x \in C, \forall y\in C: (x\cdot y)=(y\cdot x)
$$
let be $(C,+,\cdot)$ a ring $$(C,+,\cdot) \text{ is ring with 1 iff }
 \exists x=:1 \in C,\forall y \in C: (x \cdot y)=y=(y\cdot x)
$$

I thinked,  are the following definitions of skew field and field possible?

let be $(C,+,\cdot)$ a ring with 1 $$(C,+,\cdot) \text{ is skew field iff } \forall x \in C\setminus{0},\exists y \in C: (x \cdot y)=1=(y \cdot x)$$
let be $(C,+,\cdot)$ a skew field $$(C,+,\cdot) \text{ is field iff } \forall x \in C,\forall y \in C: (x \cdot y)=(y\cdot x)$$

If yes, is $(\{0\}, +, \cdot)$ a field?
Comment: No, $\{0\}$ is a ring with identity, but it is not a (skew-)field.
Comment: Usually, in a (skew-)field, it is assumed that $0\ne1$.
Comment: BTW, given that you tagged the question [tag:finite-fields] you may want to know that all finite skewfields are commutative, and hence fields. This is a theorem of Wedderburn.
Comment: it means that a skew field is a ring with 1 but $\{0\}$ ist not ring with 1?
Comment: ok, if I use my definitions I have that the set $\{0,1\}$, with $1 \neq 0 $ naturally, is another (skew-)field, is true? If yes, my def works.. is true?
Comment: I don´t understand, why is "usually"?
Comment: If $\{0\}$ is considered a field, then the theorem "an ideal $I$ of a commutative ring $R$ is maximal if and only if $R/I$ is a field" would be false. I don't think there are textbooks where $\{0\}$ is considered to be a field, but I can't exclude it.
Comment: The usual definition of a (skew)field reads that $(C,+,\cdot)$ should be a ring, and $(C\setminus\{0\},\cdot)$ should be a group. In particular $C\setminus\{0\}$ should be non-empty.
Answer: A skew-field (or skew field) is a ring in which the equations ax=b and ya=b with a≠0 are uniquely solvable. In the case of an associative ring (cf. Associative rings and algebras) it is sufficient to require the existence of a unit 1 and the unique solvability of the equations ax=1 and ya=1 for any a≠0. A commutative associative skew-field is called a field. An example of a non-commutative associative skew-field is the skew-field of quaternions, defined as the set of matrices of the form
(a−bb¯a¯)
over the field of complex numbers with the usual operations (see Quaternion). An example of a non-associative skew-field is the Cayley–Dickson algebra, consisting of all matrices of the same form as above over the skew-field of quaternions. This skew-field is alternative (see Alternative rings and algebras). Any skew-field is a division algebra either over the field of rational numbers or over a field of residues Fp=Z/(p). The skew-field of quaternions is a 4-dimensional algebra over the field of real numbers, while the Cayley–Dickson algebra is 8-dimensional. The dimension of any algebra with division over the field of real numbers is equal to 1, 2, 4, or 8 (see [Ad], and also Topological ring). The fields of real or complex numbers and the skew-field of quaternions are the only connected locally compact associative skew-fields (see [Po]). Any finite-dimensional algebra without zero divisors is a skew-field. Any finite associative skew-field is commutative (see [Sk], [He]). An associative skew-field is characterized by the property that any non-zero module over it is free. Any non-associative skew-field is finite-dimensional [ZhSlShSh]. A similar result applies to Mal'tsev skew-fields [Fi] (see Mal'tsev algebra) and to Jordan skew-fields [Ze] (see Jordan algebra). In contrast to the commutative case, not every associative ring without zero divisors can be imbedded in a skew-field (see Imbedding of rings).
Associative skew-fields are also known as division rings, in particular if they are finite dimensional over their centre
Comment: This answer fails to address the main question, namely whether the $0$-ring is considered a skew field.


Convert casual language to date

Question: I'm looking for a library for .NET which will take a date string like "two hours ago" or "3", meaning today at 3PM, and convert it to an actual date. Humanizer seems to do the opposite, taking a date and converting it to a more human-readable date, but I can't find anything that does it this way round. Any suggestions?
Comment: Rob, Both are very old questions. Quite some time back, but after those questions were posted, what was [considered on-topic](http://stackoverflow.com/help/on-topic) (see #4) changed. Questions asking for off-site resources are no longer on-topic. Closing old questions is something that happens slowly. Someone willing and able has to see the question, and vote/flag them for closure. The Q goes into a review queue which is *always* full of several thousand questions. Five people have to vote to close each one, and votes eventually expire. Each person who can vote, gets only 50 such votes/day.
Comment: For some reason people are voting to close this question, even though there are very similar questions elsewhere on the site: http://stackoverflow.com/questions/1495487/is-there-any-python-library-for-parsing-dates-and-times-from-a-natural-language http://stackoverflow.com/questions/23689/natural-language-date-time-parser-for-net
Comment: I would have loved to have found the answer I now have to this question when I first asked this a few weeks back. It seems strange that something of value to me, along with the two questions I reference above with a large number of upvotes, should be considered not fit for this site. Will they be deleted too?
Comment: This question, and those, will not be [automatically deleted](http://stackoverflow.com/help/roomba). They may be deleted, if (at least) 3 users with enough reputation vote to delete them, but it's unusual for that to happen due to A) the reputation score required to be able to do so is *much* higher, and B) the number of available delete votes is *much* lower. Basically, such votes are usually held in reserve for questions which are much more deserving of being deleted.
Comment: If you are looking for software recommendations (including libraries, etc), such questions are, generally, [on-topic](https://softwarerecs.stackexchange.com/help/on-topic) for [softwarerecs.se].
Answer: nChronic seems to do the job: https://github.com/robertwilczynski/nChronic

Convert casual language to date


Django QuerySet Annotations - More efficient way?

Question: In a class Based ListView I want to annotate each Post with the number of comments (this method works)
def get_context_data(self, *args, **kwargs):
    context = super().get_context_data(*args, **kwargs)

    context['approved_comments'] = Comment.objects.values('post_id').annotate(c_count=Count('post_id')).filter(approved=True)
    return context

in my Template I do the following (which feels really inefficient)
{% for comment in approved_comments %}
    {% if post.id == comment.post_id %}
        {{comment.c_count}}

    {% endif %}
{% endfor %}

This gets me the result I want but I'm struggling to find a better way to deliver this since this seems really redundant.
I was trying to find a SO question that already deals with this but haven't found one so if you could point me to the link that would be helpful.
Thanks in advance :)
Answer: This is a quadratic JOIN, you should not do that. You can simply annotate the Posts with the number of approved comments in the view:
from django.db.models import Count, Q
from django.views.generic import ListView

class MyListView(ListView):
    model = Post
    queryset = Post.objects.annotate(
        napproved_comments=Count('comment', filter=Q(comment__approved=True))
    )
and then render this in the template with:
{{ post.napproved_comments }}
Comment: Thanks!  This is exactly what I was looking for :)


Implementing an iterator over binary (or arbitrary) tree using C++ 11

Question: I would like to create an iterator over the binary tree so as to be able to use range-based for loop. I understand I ought to implement the begin() and end() function first.
Begin should probably point to the root.  According to the specification, however, the end() functions returns "the element following the last valid element". Which element (node) is that? Would it not be illegal to point to some "invalid" place?
The other thing is the operator++. What is the best way to return "next" element in tree? I just need some advice to begin with this programming.

I would like to expand/augment my question*. What if I wanted to iterate over a tree with an arbitrary arity? Let each node have a vector of children and let begin() point to the "real" root. I would probably have to implement a queue (for breadth-first) inside the iterator class to store the unique_ptr's to nodes, right? Then, when the queue is empty I would know that I have passed all nodes and thus should return TreeIterator(nullptr) when oprator++() is called. Does it make sense? I want it as simple as possible and only forward iteration.
*Or should I create a new thread?
Comment: Your `end()` iterator will probably end up being some sentinel value that's not an actual node in the tree.
Answer: Where your begin() should point to pretty much depends on the order in which you want to traverse your tree. Using the root may be sensible, e.g., for a breadth first walk of the tree. The end() doesn't really sit on a tree node: this position is accessed and indicates that the end of the sequence is reached. Whether it indicates anything related to the tree somewhat depends on what sort of iteration you want to support: when supporting only forward iteration it can just indicate the end. When also supporting bidirectional iteration, it needs to know how to find the node right before the end.
In any case, the place pointed to isn't really accessed and you need a suitable indicator. For a forward iteration only iterator end() could just return an iterator pointing to null and when you move on from the last node you just set the iterator's pointer to null as well: equality comparing the two pointers would yield true, indicating that you have reached the end. When wanting to support bidirectional iteration you'll need some sort of link record which can be used to navigate to the previous node but which doesn't need to store a value.
The ordered associated containers (std::map<K, V>, std:set<V>, etc.) are internally implemented as some sort of tree (e.g., a Red/Black-tree). The begin() iterator starts with the left-most node and the end() iterator refers to the position after the right-most node. The operator++() just finds the next node to the right of the current:

if the iterator sits on a node without a right child node, it walks along the chain of parents until it finds a parent reaching its child via the left branch of the tree
if it sits on a node with a right child node it walks to the child and then down the sequence of left children of this child (if any) to find the left-most child in the right subtree.

Obviously, if you don't walk your tree from left to right but rather, e.g., from top to bottom, you'll need a different algorithm. The easiest approach for me is to draw a tree on a piece of paper and see how to get to the next node.
If you haven't implemented a data structure using your own iterators I'd recommend trying things out on a simple sequential data structure, e.g., a list: There it is pretty obvious how to reach the next node and when the end is reached. Once the general iteration principle is clear, creating a tree is just a matter of getting the navigation right.
Answer: Look at SGI implementation of RBTree (this is the base for std::set/std::map... containers).
http://www.sgi.com/tech/stl/stl_tree.h
You will see that begin() is the leftmost node.
You will see that end() is a special "empty" node header which is the super root - I mean a real root (preset only if the tree is not empty) is its child node.
operator ++ is to go to right child and then find this child leftmost node.
If such child does not exist - we go to left parent of the rightmost parent node. As in this example (red lines are skip move, blue ones ends are the given steps of iteration):

The code copied from SGI:
  void _M_increment()
  {
    if (_M_node->_M_right != 0) {
      _M_node = _M_node->_M_right;
      while (_M_node->_M_left != 0)
        _M_node = _M_node->_M_left;
    }
    else {
      _Base_ptr __y = _M_node->_M_parent;
      while (_M_node == __y->_M_right) {
        _M_node = __y;
        __y = __y->_M_parent;
      }
      if (_M_node->_M_right != __y)
        _M_node = __y;
    }
  }

When a tree is empty - begin() is leftmost of header - so it is header itself - end() is also header - so begin() == end(). Remember - your iteration scheme must match this condition begin() == end() for empty trees.
This seems to be very smart iteration scheme.
Of course you can define you own scheme - but the lesson learned is to have special node for end() purpose.
Comment: `if (_M_node->_M_right != __y)  _M_node = __y;`
How can this return false ? `__y` is `_M_node`'s parent so how could `_M_node->_M_right` be equal to `__y`?
Comment: Why it must always hold that begin()==end()? In [this](http://www.cprogramming.com/c++11/c++11-ranged-for-loop.html) tutorial the author implements an iterator over an array and this condition does not hold.
Comment: I meant this condition only for empty tree ;)
Answer: An iterator for a tree is going to be more than just a pointer, although it will likely contain a pointer:
struct TreeIterator {
  TreeIterator(TreeNode *node_ptr) : node_ptr(node_ptr) { }
  TreeIterator &operator++();
  TreeIterator operator++(int);
  bool operator==(const TreeIterator &) const;

  private:
    TreeNode *node_ptr;
};

TreeIterator begin(const Tree &tree) { ... }
TreeIterator end(const Tree &tree) { ... }

You can make your end() function return something special, like TreeIterator(nullptr)
What your begin iterator points to will depend on the type of traversal that you want.  If you are doing breadth-first traversal, then starting at the root makes sense.


Finding the CDF of a a sequence of independent random variables

Question: Let $Z_t$, where $t$ is even, be a sequence of independent random variables defined as,
$$Z_t = \left\{\begin{array}{ccc} +1 & , & p = \frac{1}{2} \\ -1 & , & p = \frac{1}{2}\end{array}\right.$$
and $Z_t = Z_{t - 1}$ if $t$ is odd.
I need to show that the process $Z_t$ is first-order stationary in distribution, which seems straight forward from the definition, however I am confused on how to find the CDF based on the PMF $Z_t$.
Comment: Have you tried computing $P(Z_t\leq x)$ for any given $x$? There's not that many cases to consider.
Comment: Though even that is hardly necessary: when $t$ is even all $Z_t$ are identically distributed, and this identical distribution extends to when $t$ is odd.  Though the process is clearly not second-order stationary
Comment: The joint PMF can take one of four values: $(-1, -1)$, $(-1, 1)$, $(1, -1)$, $(1, 1)$, each with a probability of $\frac{1}{4}$. Since the joint PMF is the same in any case, wouldn't this make $Z_t$ second-order stationary?
Answer: The CDF of a single value is pretty straightforward here:
$$F_{Z_t}(z) = \mathbb{P}(Z_t \leqslant z) = \frac{1}{2} \bigg[ \mathbb{I}(z \geqslant -1) + \mathbb{I}(z \geqslant 1) \bigg].$$
Since this does not depend on $t$, the process is first-order stationary.  As pointed out in the comments, the process is first-order stationary but not second-order stationary.


Monotone Union of subgroups being subgroup

Question: I saw this exercise in a book:
Suppose $G$ is a group. Suppose $T$ is an index set and for each $t \in T$, $H_t$ is a subgroup of $G$. Furthermore, if $\{H_t\}$ is a monotonic collection, show that $\bigcup_{t \in T} H_t$ is a subgroup of $G$.
My question is if $T$ is not $\mathbb N$, how to define "monotonic"?
If it is defined by what Jyrki Lahtonen suggested:
For arbitrary $k$, $l \in T$, either $H_k \subseteq H_l$ or $H_l \subseteq H_k$ (or both).
Then here is my proof:
Suppose $a$, $b \in \bigcup_{t \in T}H_t$, then $a \in H_k$ for some $k$ and $b \in H_l$ for some $l$. So either $a$, $b \in H_k$ or $a$, $b \in H_l$ (or both). Then either $a \cdot b \in H_k$ or $a \cdot b \in H_l$ (or both). Hence $a \cdot b \in \bigcup_{t \in T}H_t$. Therefore $\bigcup_{t \in T}H_t$ is a subgroup.
My question is:

Is the above proof correct?
I think it looks too trivial. In my opinion, if you have a monotonic collection of sets, all satisfying certain criterion, then "obviously" the union also satisfies that criterion. Can someone give a counter-example?
Comment: This doesn't make sense. If $T$ is just a set, then there is no possibility of defining monotonicity. If $T$ is a partial order, then monotonic probably means $s \leq t \Rightarrow H_s \subseteq H_t$. But then the claim is not true. For example, if $T$ is discrete (i.e. $s \leq t$ iff $s=t$), then every collection of subgroups is monotonic, but it is well-known that the union of distinct subgroups is almost never a subgroup. What we really need is that $T$ is a *directed* partial order. And in that case the proof is a two-liner.
Comment: I guess that monotonic simply means that if $\ell$ and $k$ are two arbitrary elements of $T$, then you have either $H_\ell\subseteq H_k$ or $H_k\subseteq H_\ell$ (or possibly both). The usual subgroup criterion then gives the claim relatively quickly.
Comment: Sensible people call such a thing *a chain of subgroups*.
Comment: BY the way, it is **never** a good idea to mention a book saying «a book»: what book is it? Adding more or less complete bibliographic information always helps everybody: you, the OP,because it makes it easier for others to answer your question by giving context, and others because, well, because it does.
Comment: You definition of "monotonic collection" is quite often called chain, see [Wikipedia](http://en.wikipedia.org/wiki/Total_order#Chains), [ProofWiki](http://proofwiki.org/wiki/Definition:Chain_%28Set_Theory%29).
Comment: Your suggestion in 2. is too naive: Consider the case where you have a chain $N_0\subset N_1\subset N_2\subset\dots$ with each $N_i$ order isomorphic to $\mathbb N$, say $N_0=\{a_0<a_1<\dots\}$ and $N_1=\{a_{-1}<a_0<a_1<\dots\}$ and $N_2=\{a_{-2}<a_{-1}<a_0<\dots\}$, etc. Now, you could object that this is not a good example, in that I am changing the first element, but the criterion all models satisfy is simply that there is a least element, not which element it is.
Comment: Naturally, this suggests that there may be a version of 2. that works, but special attention has to be paid to either the *language* or the *theory* we want to preserve. The right framework to study this question is *model theory*, and there are indeed theorems giving positive versions of 2.
Comment: @AndresCaicedo I gave as my suggestion as a counterexample (in the other question, which is almost the same) the property of *being finite*. I also mentioned Tukey's lemma, which says that this works for properties of finite character.
Comment: You definition of "monotonic collection" is quite often called chain, see [Wikipedia](http://en.wikipedia.org/wiki/Total_order#Chains), [ProofWiki](http://proofwiki.org/wiki/Definition:Chain_%28Set_Theory%29).
Comment: See also this older question: http://math.stackexchange.com/questions/72184/union-of-an-infinite-number-of-subgroups
Comment: @MartinSleziak Ah, I did not read the comments or the link to the previous question before answering.
Answer: The definition of monotonic is indeed the one suggested in Jyrki's comment
In the book Elements of Abstract and Linear Algebra by Edwin H. Connell1 we can find the following definition:

Definition A collection of sets is said to be monotonic if, given any two sets of
  the collection, one is contained in the other.

I would also mention that such system of sets is quite often called chain, see Wikipedia, ProofWiki. (Or we could simply call it totally ordered subset, or linearly ordered subset.)
The above definition is mentioned in the book when discussion Hausdorff maximality principle. The formulation given in the book is that "every monotonic collection is contained in a maximal monotonic collection".
1The OP mentioned in another post that this is the book where the problem comes from.

You also asked this:

I think it looks too trivial. In my opinion, if you have a monotonic collection of sets, all satisfying certain criterion, then "obviously" the union also satisfies that criterion. Can someone give a counter-example?

Well a trivial example would be considering the property "a set is finite". You can easily find a monotonic collection (chain) of finite subsets, such that the union is finite.
But Teichmüller–Tukey lemma say that your conjecture is true for properties of finite character.

A comment to your proof: To show that the union is indeed a subgroup, you should also show that: 1) it is non-empty, 2) it is closed under taking inverses (i.e., $a\in\bigcup H_t$ $\Rightarrow$ $a^{-1}\in\bigcup H_t$).
These parts are rather easy, but you should mention both of them for the proof to be complete.
Answer: Does the book define "index set"? I'm guessing that by index set they actually mean what would normally be called a directed set, which is a set with a preorder in which every pair of elements has an upper bound. So, in this case monotonic would mean that if $s \le t$, then $H_s \subseteq H_t$. I don't see how the claim can be true without assuming $T$ is directed.
Answer: Your proof is not enough, since not every subset of a group that is closed under products is a subgroup. Consider the positive integers as a subset of the positive rationals, with multiplication.
However, the idea of the proof is there, just recall that to be a subgroup, a set needs to be not just closed under products, but also under inverses, and that can be verified in this setting just as easily.
However, your suggestion in 2. is too naive, and does not work without some care: Consider the case where you have a chain $N_0\subset N_1\subset N_2\subset\dots$ with each $N_i$ order isomorphic to $\mathbb N$, say $N_0=\{a_0<a_1<\dots\}$ and $N_1=\{a_{-1}<a_0<a_1<\dots\}$ and $N_2=\{a_{-2}<a_{-1}<a_0<\dots\}$, etc. Now, you could object that this is not a good example, in that I am changing the first element, but the criterion all models satisfy is simply that there is a least element, not which element it is.
Naturally, this suggests that there may be a version of 2. that works, but special attention has to be paid to either the language or the theory we want to preserve. The right framework to study this question is model theory, and there are indeed theorems giving positive versions of 2.

Theorem. A $\Pi_2$ formula $\varphi$ is preserved by unions.

To understand what this means, assume you have a family of structures in a common language -- in the sense of model theory, but this is very general: These could be sets with a binary relation, or sets $S$ with a unary function $f:S\to S$ and some distinguished "constant" $a\in S$, or ...
A first order formula $\phi$ is $\Pi_2$, or universal-existential, iff it has the form $$\forall x_1\dots\forall x_n\exists y_1\dots\exists y_m \psi(x_1,\dots,x_n,y_1,\dots,y_m,a_1,\dots,a_k)$$ where $\psi$ has no quantifiers. for instance, the field axioms have this form.
The theorem says that if we are given a chain of such structures, and the statement $\phi$ is true in all of them, then it is also true in their union. All that matters is that $\phi$ is "not too complicated" syntactically, in the specific form described above.
In fact, the same holds not just for chains but for direct limits of directed systems, so the result really covers many natural examples.
The topic of what statements or theories are preserved under unions is a classical problem well studied in model theory. Remarkably, we have:

Theorem. A theory $T$ is preserved under unions of chains iff each axiom of $T$ is universal-existential.

This is Theorem 3.2.3 in the classical Chang-Keisler Model theory, but it is treated in detail in many other sources as well.
For instance, partial orders are preserved under unions. For a more interesting example, the theory of Boolean algebras is also preserved under unions: Given a chain of Boolean algebras, their union is again a Boolean algebra. Here we need to be careful on how the language is specified. Boolean algebras are completely described by their natural partial order, but perhaps you find more natural to describe them in terms of a least and largest elements, with conjunction, disjunction and negation, and to say that an algebra $A$ is a substructure of an algebra $B$ means that, as sets, $A\subset B$, and the operations of $A$ are the restrictions of the operations of $B$, plus the requirement that the $0$ of $A$ is the $0$ of $B$, and also the $1$ of $A$ is the $1$ of $B$.
On the other hand, the theory of atomic Boolean algebras is not preserved under unions. Table 3.2.1in Chang-Keisler provides many other examples.


How does one go about converting a class to an abstract generic base class from which it derives?

Question: I am currently working in Visual Studio 2013 with VB on .NET 4.5. I have an abstract base class which holds a collection of another abstract base class, like this:
Generic Base Class:
Public MustInherit Class CustomCollection(Of collectionItemType As CollectionItemBase)
    Inherits Collections.ObjectModel.KeyedCollection(Of String, CollectionItemBase)
    '...
End Class

Base Class Referened by Generic Base Class:
Public MustInherit Class CollectionItemBase
    '...
End Class

I have a group of classes that inherit the generic base class "CustomCollection":
Public Class Collection1
    Inherits CustomCollection(Of ClassThatDerivesFromCollectionItemBase1)
    '...
End Class

Public Class Collection2
    Inherits CustomCollection(Of ClassThatDerivesFromCollectionItemBase2)
    '...
End Class

'etc...

This is the code I am using to try and convert an instance of Collection1 to a CustomCollection(Of CollectionItemBase):
'...
someProperty = instanceOfCollection1.Cast(Of CustomCollection(Of CollectionItemBase))
'...

This generates the following error at runtime, which to me seems to be nonsense:

"Unable to cast object of type
  'd__b1`1[ApplicationName.CustomCollection`1[ApplicationName.CollectionItemBase]]'
  to type
  'ApplicationName.CustomCollection`1[ApplicationName.CollectionItemBase]'."

It appears to be claiming that it is unable to cast the object to its own type. Any thoughts?
Comment: There is a problem with this code. Shouldn't `Inherits CustomCollection(Of ClassThatDerivesFromCustomCollection1)` be  `Inherits CustomCollection(Of ClassThatDerivesFromCollectionItemBase1)` ?
Comment: Oh no. I wanted to clarify that, and then post my answer. I have the answer ready :)
Comment: @Alireza Awesome, can't wait to read it! It's been a nightmare trying to figure this out.
Comment: @Alireza Yes, you are right! My apologies, I made a mistake while translating the code over, I will fix that immediately. However, this was not an issue in the original code. Please let me know if you have any idea what might be causing the underlying problem! :-)
Answer: When you use Cast(Of T) on an IEnumerable(Of U) it will cast every individual element to the destination type, so you should not pass the type of IEnumerable(Of T), but T itself.
In your case write your cast as
someProperty = instanceOfCollection1.Cast(Of CollectionItemBase)

This cast returns an IEnumerable(Of CollectionItemBase) that you can use.
But I don't think that was your question. Let's put that single line of code aside and talk about your question. The fact is generics don't work that way. Generic types Of Base/Derived types are totally different types.
In the simplest example, an instance of A(Of T) can't be cast to A(of U) even if T Inherits From U, because A(Of U) is a different type than `A(Of U)..
To replace class names with your real classes: an instance of
    Collection1
or say
CustomCollection(Of ClassThatDerivesFromCollectionItemBase1)

can't be cast to
CustomCollection(Of CollectionItemBase)

despite of the fact that
ClassThatDerivesFromCollectionItemBase1
    Inherits CollectionItemBase

because
CustomCollection(Of ClassThatDerivesFromCollectionItemBase1)

is a different type than
CustomCollection(Of CollectionItemBase).

This has nothing to do with covariance because (from MSDN):

In the .NET Framework 4, variant type parameters are restricted to
  generic interface and generic delegate types.

So it won't work foe classes but works for interfaces. Let me make some changes to your code:
Public Class CollectionItemBase
End Class

Public Class ClassThatDerivesFromCollectionItemBase1
    Inherits CollectionItemBase
End Class

Public Class ClassThatDerivesFromCollectionItemBase2
    Inherits CollectionItemBase
End Class

Public Interface ICustomCollection(Of Out collectionItemType As CollectionItemBase)
End Interface

Public Class Collection1
    Implements ICustomCollection(Of ClassThatDerivesFromCollectionItemBase1)
End Class

The Out modifier in this line
Public Interface ICustomCollection(Of Out collectionItemType As CollectionItemBase)

makes the type parameter covariant, meaning that if you have
Dim instanceOfCollection1 As New Collection1

these two lines will work:
Dim x As ICustomCollection(Of CollectionItemBase) = instanceOfCollection1
Dim y As ICustomCollection(Of Item1) = instanceOfCollection1

Hope that was helpful
Comment: Thanks so much! Because there are a fair number of classes in my application that will be need to be updated based on a conversion of CustomCollection from an abstract class to an interface, I will get back to you with the outcome a bit later! Again, I very sincerely appreciate your efforts and am optimistic after having read your response that I might finally be able to patch a solution together :-)
Comment: So I'm in the middle of converting CustomCollection to an interface now, but I'm having a tough time finding an effective way to guarantee that any class that implements ICustomCollection will also function as a KeyedCollection of items of the same type as ICustomCollection's specified CollecitonItemBase type. Any ideas?


How to get list of commands used in a shell script?

Question: I have a shell script of more than 1000 lines, i would like to check if all the commands used in the script are installed in my Linux operating system.
Is there any tool to get the list of Linux commands used in the shell script?
Or how can i write a small script which can do this for me?
The script runs successfully on the Ubuntu machine, it is invoked as a part of C++ application. we need to run the same on a device where a Linux with limited capability runs. I have identified manually,  few commands which the script runs and not present on Device OS. before we try installing these commands i would like to check all other commands and install all at once.
Thanks in advance
Comment: Take a look at: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html
Comment: Or this: http://unix.stackexchange.com/questions/20979/how-do-i-list-all-installed-programs
Comment: Arek Thanks, it helps little bit but not exactly what i was looking for. I need to know what all commands the script uses. i can not run the entire script at one shot as it runs part by part based on the arguments. as of now we do not have all the information about arguments.
Comment: 1000 lines isn't that long, and most of it is probably either shell-specific (like `if`, `while`, etc) or repetitive (the same command being called repeatedly with different arguments.) You'll probably spend less time scanning it manually than you will looking for a way to do it automatically.
Comment: Your best bet: update your script to wrap command execution with your own function, then in this function log the command and just pass through to the command itself. `run() { echo "$1" > /tmp/commands; $@; }` or such.
Comment: If you wanted a *truly guaranteed-complete* answer, this is at worst a NP-complete issue, equivalent to the halting problem (which is to say, not even theoretically possible to answer via an algorithm guaranteed to complete): You would need to simulate all possible execution paths, since commands can be dynamic.
Answer: I already tried this in the past and got to the conclusion that is very difficult to provide a solution which would work for all scripts. The reason is that each script with complex commands has a different approach in using the shells features.
In case of a simple linear script, it might be as easy as using debug mode.
For example: bash -x script.sh 2>&1 | grep ^+ | awk '{print $2}' | sort -u
In case the script has some decisions, then you might use the same approach an consider that for the "else" cases the commands would still be the same just with different arguments or would be something trivial (echo + exit).
In case of a complex script, I attempted to write a script that would just look for commands in the same place I would do it myself. The challenge is to create expressions that would help identify all used possibilities, I would say this is doable for about 80-90% of the script and the output should only be used as reference since it will contain invalid data (~20%).
Here is an example script that would parse itself using a very simple approach (separate commands on different lines, 1st word will be the command):
# 1. Eliminate all quoted text
# 2. Eliminate all comments
# 3. Replace all delimiters between commands with new lines ( ; | && || )
# 4. extract the command from 1st column and print it once
cat $0 \
    | sed -e 's/\"/./g' -e "s/'[^']*'//g" -e 's/"[^"]*"//g' \
    | sed -e "s/^[[:space:]]*#.*$//" -e "s/\([^\\]\)#[^\"']*$/\1/" \
    | sed -e "s/&&/;/g" -e "s/||/;/g" | tr ";|" "\n\n" \
    | awk '{print $1}' | sort -u

the output is:
.
/
/g.
awk
cat
sed
sort
tr

There are many more cases to consider (command substitutions, aliases etc.), 1, 2 and 3 are just beginning, but they would still cover 80% of most complex scripts.
The regular expressions used would need to be adjusted or extended to increase precision and special cases.
In conclusion if you really need something like this, then you can write a script as above, but don't trust the output until you verify it yourself.
Answer:
Add export PATH='' to the second line of your script.
Execute your_script.sh 2>&1 > /dev/null | grep 'No such file or directory' | awk '{print $4;}' | grep -v '/' | sort | uniq |  sed 's/.$//'.
Comment: This might find a few, but probably not all: likely the script errors out as soon as it hits the first missing command.
Comment: Hello and welcome to Stack Overflow :) Which script are you talking about? Please put it in context.
Comment: You are right, this is only valid for simple scripts, I think it is too simple.
Answer: If you have a fedora/redhat based system, bash has been patched with the --rpm-requires flag

--rpm-requires: Produce the list of files that are required for the shell script to run.   This  implies -n  and  is  subject  to the same limitations as compile time error checking checking;  Command substitutions, Conditional expressions and eval builtin are not parsed  so  some  dependencies may be missed.

So when you run the following:
$ bash --rpm-requires script.sh
executable(command1)
function(function1)
function(function2)
executable(command2)
function(function3)

There are some limitations here:

command and process substitutions and conditional expressions are not picked up. So the following are ignored:
$(command)
<(command)
>(command)
command1 && command2 || command3

commands as strings are not picked up. So the following line will be ignored
"/path/to/my/command"

commands that contain shell variables are not listed. This generally makes sense since
some might be the result of some script logic, but even the following is ignored
$HOME/bin/command

This point can however be bypassed by using envsubst and running it as
$ bash --rpm-requires <(


Disappears after passing a certain time

Question: Just a p of CSS I want to disappear after a while I looked here and found this, but the opposite instead of hiding appears https://stackoverflow.com/a/31751324/10634372
Comment: Just change `.show()` to `.hide()`.
Comment: What is your actual question? Please include any code relevant to the question, in the question itself. What is "just a p of CSS"?
Comment: as Jon P says, it really is quite unclear what you are asking. Linking to other questions or external code will put a lot of people off investigating your problem. Please describe clearly what you would like to do and show what you have already tried.
Comment: I just wanted the opposite way of this code - .show to hide https://stackoverflow.com/a/31751324/10634372
Answer: You may dispense with JavaScript's setTimeout() as follows:

$(document).ready(function() {
$("#proceed").show();
  });

$("button").click(function(){
  $("#wait").hide("slow");
  $(this).fadeOut("slow");

  $("#welcome")
.delay(500)
  .queue(function (next) {
$(this).fadeIn();
$(this).animate({"font-size":"56pt","letter-spacing":".3em"},"fast");
next();
  });

});

#proceed {
      display: none;
}

#wait {
font: 1em Arial,Helvetica;
padding:0;
margin:0;
}

 #welcome {
 display:none;
 color:red;
 font-family: Arial,Helvetica;
 text-shadow: 3px 4px #999;
 }

 span {
 margin:0;
 }

 button {
 margin-left:45%;
 }

 p {
   background-color:beige;
   text-align:center;
 }

You need to wait 0 before you can proceed.
Welcome

<button type="button" id="proceed">proceed</button>

jQuery provides HTML elements different methods governing their display, such as .hide(), .show(), .fadeIn() and .fadeOut() and each of these can take a string parameter such as "slow" or "fast" or else a number to specify the duraction of the effect.
When it comes to how fast a CSS property is set, there is also something else available, namely a queue function whose execution you may delay. That portion of this example's code derives from an answer given here. However, note the following:

"The .delay() method is best for delaying between queued jQuery
  effects. —.delay() is not a replacement for JavaScript's native
  setTimeout function, which may be more appropriate for certain use
  cases."

Source: here
The animate() method can also affect how slow or fast an element displays.
Answer: In the code on the other stack overflow answer where the code says $("#proceed").show();
remove the .show(); and replace it with .hide();
the full code would be:

You have 5 seconds to proceed

<button type="button" id="proceed">proceed</button>

var i = 4;
var time = $("#time")
var timer = setInterval(function() {
  time.html(i);
  if (i == 0) {
    $("#proceed").hide();
    clearInterval(timer);

  }
  i--;
}, 1000)

#proceed {
  display: none;
}

Comment: Did not succeed, they disappear immediately, must disappear after 5 seconds

Disappears after passing a certain time


Is there a technical name and rules for a double-touch in badminton?

Question: Double-touch (at least that's what people call at my court) is when the shuttle touches the racket more than once in an instance.
So, what are the rules regarding this?  Does the point count?
If not, then is the point awarded to the opponent or is the rally abandoned?
Is there a technical/official term for "double touch" in Badminton?
Comment: The common phrase is [double hit](http://www.worldbadminton.com/glossary.htm#Double_Hit) but it's not in the official rules AFAIK
Answer: Rules of Badminton state:

FAULTS:  It shall be a 'fault':

...
13.3 if in play, the shuttle:
...
13.3.6 is caught and held on the racket and then slung during the execution of a stroke;
13.3.7 is hit twice in succession by the same player. However, a shuttle hitting the head and the stringed area of the racket in one stroke shall not be a 'fault';
13.3.8 is hit by a player and the player's partner successively;

Source: http://www.bwfbadminton.org/file.aspx?id=680849&dl=1
So to answer your questions:

So, what are the rules regarding this? Does the point count?

The point counts. But it is a fault. Hence, the point is awarded to your opponent. See 13.3.8. However, be award that if the shuttle first hits the head and then the stringed area, it is NOT a fault and therefore a legal shot.

If not, then is the point awarded to the opponent or is the rally abandoned?

See above.

Is there a technical/official term for "double touch" in Badminton?

When looking at the official rules, it seems, there is no official term.


How to debug rules that are not being run?

Question: I have few rules bound to the Event: Completing the checkout process
After completing the checkout process these rules should run - but they do not work...
I am using Devel module to debug the Rules and in the dblog there is nothing about these rules - There are only rules that are actually being run upon other events.
How can I debug this ?
Answer: /config/workflow/rules/settings
Enable all debugging and it should show in the log if the event is correct. It will go through each condition and say which passed and which failed.


Proof that if $m^2+m+1 \equiv 0 \mod p$ for some prime $p$ not equal to 3 and some integer $m$, then $p$ is congruent to 1 modulo 3.

Question: I'm trying to prove this as part of a step by step proof that there are infinitely many primes congruent to $1$ modulo $3$. It is clear that $p$ is incongruent to $0$ modulo $3$ but I am having trouble proving that $p$ must be incongruent to $2$ modulo $3$.
Any hints would be much appreciated.
Comment: Hint:  use the quadratic formula and evoke reciprocity.
Answer: $f(X)=X^2+X+1$ is the third cyclotomic polynomial.
Let $p\ne3$ and $f(m)\equiv0\pmod 3$. Then $m^3\equiv1\pmod p$
but $m\not\equiv1\pmod p$. Thus $m$ has order $3$ in the multiplicative
group modulo $p$. By Lagrange's theorem $3\mid p-1$.
Essentially the same argument shows that if $\Phi_n(m)\equiv0\pmod p$
where $p$ is a prime not dividing $n$, and $\Phi_n$ is the
$n$-th cyclotomic polynomial, then $n\mid p-1$.
Answer: Continuing on from my question and using the hint from lulu.
As $m^2+m+1 \equiv 0 \mod p $, we have that $m \equiv \frac{-1 \pm \sqrt{-3}}{2} \mod p $ and so $-3$ must be a quadratic residue modulo $p$. So $\left(\frac{-3}{p}\right)=+1$. Using the multiplicity of the Legendre symbol, $\left(\frac{3}{p}\right)\left(\frac{-1}{p}\right)=+1$, so either both Legendre symbols are $+1$ or both are $-1$. Suppose they are both $-1$. then $p\equiv3 \mod 4$, and so $\left(\frac{3}{p}\right)=-\left(\frac{p}{3}\right)=-1$. So $\left(\frac{p}{3}\right)=+1$, so $p$ is a quadratic residue modulo $3$, so $p$ is congruent to $1$ modulo $3$. Similarly, if both Legendre symbols are $+1$ we again find that $p$ must be a quadratic residue modulo $3$ and so is congruent to $1$ modulo $3$.


$ X_1,...,X_n $ independent and identically distributed. Show inequalities.

Question: Let $ X_1,...,X_n$ be independent and identically distributed random variables with values in $\mathbb{N} $ and probability function $p(k) = \frac{1}{k(k+1)}$.
Calculate:
a) $P(X_1 \ge k) $
b)$P(max(X_1,...,X_n) \ge k) $
c) the probability function of the  random variable $ M_n$ := max{$X_1,...,X_n$}
d) Show that $P( M_n > \lambda \cdot n ) $ convergences for every $\lambda$ $ > 0$. What's the limit?
Attempt:
a)$ P(X_1 \ge k) = \sum_{x=k} P(X_1=x) = \sum_{x=k} \frac{1}{k(k+1)} = \sum_{x=k} \frac{1}{k} -\frac{1}{k+1} = 1 - (1- \frac{1}{k})= \frac{1}{k}$ .
b) I'm not sure if I understand b), because I could say that$ X_j := max(X_1,...,X_n)$, couldn't I? Then it is analogous to a). Where is my mistake here? Edit : b) is clear now. found my mistake.
c) I know that I have to use b).
d) $P( M_n > \lambda \cdot n ) $ = $\sum_{m > \lambda \cdot n} P(M_n = m)$ = $\sum_{m > \lambda \cdot n} \frac{1}{m(m+1)}$ = ? . Now this a telescoping series,right? I'm stucked, here. Edit2 I know that this isn't right. Have to use b) again.
Do I have mistakes?
Answer: Although the maximum $M_n$ will have the same value one of the $X_j$ by definition, it will not have the same distribution as a particular $X_j$. As a thought experiment, imagine drawing $n=1000$ or $n=10000$ i.i.d. samples, computing the maximum $M_n$, and think about the probability $P(M_n=1)$. Do you see why it does not intuitively make sense for $P(M_n=1)=P(X_1=1)$?
b) Try rewriting the event $\{\max(X_1,\ldots,X_n) < k\}$ as $\{X_1 < k\} \cap \cdots \cap \{X_n < k\}$.
For c) and d), use the result of part b).
Comment: How embarrassing! Found my mistake in b).  Thank your for your description. solved b) now. Unfortunately I'm stucked in c) and d). Could I consider $ P( M_n = y ) = P(M_n \ge y) - P(M_n \ge y+1) $?
Comment: @Mugumble For c), yes, that's exactly right. For d), just write down the result of b) for an appropriately chosen $k$, and see how the expression changes as $n \to \infty$.
Answer: Hint:
For b):
It is more easy to see $\Bbb P(\text{max}(X_1,\dots, X_n)) < k$
Comment: solved b) now ! Thank you.
Answer: I hope the image is clear and legible
Comment: @ Satish Ramanathan: First of all: Thank you for your reply. I understand b) now and found my mistake. Unfortunately I'm a beginner in probability theory. So It is forbidden to use the derivate or the the integral. Is there another possibility to solve c) and d)? Nevertheless your solution is awesome!


Central extension and direct product

Question: Let $G,H,K$ be finite groups and suppose $G$ is a
 central extension
   of $H$ by $K$. The question is that under which condition on this extension we will have $G \cong  K \times  H$.
Answer: We will have $G \cong  K \times  H$, if and only if the extension
$$
1\rightarrow K\rightarrow G\rightarrow H\rightarrow 1
$$
splits, which means that its equivalence class is the trivial one in the second cohomology group $H^2(H,K)$.
Comment: Can we get to this extension by putting some conditions on the groups $H,K$? I found a [relative question](http://math.stackexchange.com/questions/501150/non-split-extension-and-schur-multiplier) where  @DerekHolt   has answered and left a comment on splitting extensions giving conditions on $H,K$. My other question is that is there any reference dealing with this subjects?
Comment: I would say rather that if $H^2(G,A)=0$ (what is $A$?) then the extension defnitely splits, but otherwise it may or may not split.
Comment: $A$ stands for abelian, because it is a $G$-module. I have adapted the notation.
Comment: We get this extensions without any further conditions, by using the obvious injection $K\rightarrow K\times H$, and the obvious surjection $K\times H\rightarrow H$. There are really many references, e.g.  all texts on group cohomology. I have a [lecture note](https://homepage.univie.ac.at/Dietrich.Burde/papers/burde_16_coho_course.pdf), too.
Comment: @DietrichBurde

If   $H$ is  perfect and $(|K|,|{\rm Mult}(H)|)=1$ then can we claim that the central extension results the direct product $ G \cong H \times K $. In general, we look for such conditions on $H,K$.
Comment: Yes, this is true. Another condition is $H^2(H,K)=0$, as I said.
Comment: @DietrichBurde Is there any other conditions?
Comment: Well, see Theorem $3.3$ [here](https://www.google.at/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwi0psLAn-_SAhVKKMAKHRvADKYQFggaMAA&url=http%3A%2F%2Fwww.math.uconn.edu%2F~kconrad%2Fblurbs%2Fgrouptheory%2Fsplittinggp.pdf&usg=AFQjCNFCKdspc_BHDm938WHUXOdtRNGoIA&sig2=6zldjonU70kBKO_4zNpbCw&bvm=bv.150475504,d.ZGg). It splits if and only we have a semidirect product. There are many equivalent formulations for this, see [this question](http://math.stackexchange.com/questions/1898697/equivalent-conditions-for-an-exact-sequence-of-groups-being-split).
Comment: Is a direct product $K \times H$ of *any* two groups $H$ and $K$ (even non-abelian ones) necessarily a central extension of $K$ by $H$ or $H$ by $K$? I'm a bit confused as I hear people say that direct products are central split extensions. But non-abelian subgroups can't be in the center of any group!
Answer: I am not sure what sort of answer you are looking for, but it is true that it is a direct sum if and only if the sequence left splits, i.e. if for the short exact sequence $1 \rightarrow K \xrightarrow{\psi} G \rightarrow H \rightarrow 1$ there is a group homomorphism $\phi: G \rightarrow K$ "back" in such a way that $\phi \circ \psi = id_K $. This is part of the Splitting Lemma.

Central extension and direct product