App crashes on backgrounding because of SimpleAudioEngine

Question: So I׳m trying to play some effects in my Cocos2D game using SimpleAudioEngine , but after I have added them my app crashes when it goes to background (multitasked).
I searched for this problem in the internet but all the solutions that I found didn't work for me. What I did find out is that this problem happens because my app is somehow trying to play sounds when backgrounded.
In console it shows me (which is the same error I found other people had):

sgx error (background gpu access not permitted):

And another thing, when I run my app on the simulator, or even on my device while debugging carefully (going line-by-line with XCode while the app is running) this doesn't happen.
Answer: I just had this issue. I resolved it by having a bool to check if the app is running or in background that I set to true when the app goes to foreground ( applicationWillEnterForeground ) and that I set to false when the app goes to background ( applicationDidEnterbackground ) . So using the bool you can tell if the app is in the background and if it is, I just exit out of drawView function in EAGLView (thus not doing any graphics rendering which was causing the error).
I am a very dodge programmer but that method has worked for me and I hope it works for someone else. I did not need to unload and reload my sounds or anything and my app now has Multitasking XD
Comment: UIApplication seems to have a property applicationState that provides this information as well. This is iOS4+ only, though, so a check with "respondsToSelector:" is in order.
Answer: I was experiencing this, on about 25% of the occasions that my application re-entered the foreground. Like you, when I removed the sounds, the problem went away. That is how I came across your question here.
I may have found a solution to this. I have made what appears to be an unrelated change, but the problem seems to have gone away. Now, when my app enters the background, I invalidate my main scheduled timer. When my app re-enters the foreground, I then re-schedule the timer (after reloading my sounds, which I completely shut down on entering background).
So far, the problem has not come back. I would be interested to know if this helps.
Answer: I just resolved this issue on my end. Here's what was wrong in my case and, from what I can tell from the other answers and comments on this page, many other people's case as well:
By default, when I started my project, CCDirector::sharedDirector()->pause(); and CCDirector::sharedDirector()->resume(); were both being called twice, once by (void)applicationWillResignActive:(UIApplication *) and (void)applicationDidBecomeActive:(UIApplication *) respectively in AppController.mm, and once by AppDelegate::applicationDidEnterBackground() and AppDelegate::applicationWillEnterForeground() respectively in AppDelegate.cpp.
Make absolutely sure that these methods are only being called once, in AppController.mm. In AppDelegate.cpp, instead make sure that you are calling CCDirector::sharedDirector()->stopAnimation(); in place of CCDirector::sharedDirector()->pause(); and CCDirector::sharedDirector()->startAnimation(); in place of CCDirector::sharedDirector()->resume();.
Hope that's helpful to anyone else stuck in this crappy situation!
Answer: Are you sure it's related to audio? "background gpu access" sounds like it's using OpenGL.
Comment: Yep, many people on the Internet said that this problem happened to them because of audio, and when I remove the effects it doesn't happen.
Answer: I had the same issue in my application and spent some 4 hours to find out. Going background was OK the first time, but crash application the second time. With a short error message related to OpenGL. I had the same questions: how audio can crash graphics. But it wasn't a question of audio, but a question of notifications...
I discovered that going foreground was creating 2 timers in my custom level meter class.
I had registered UIApplicationWillEnterForegroundNotification and UIApplicationWillResignActiveNotification. Then, going background invalidated only one, since I registered only on notification... That was it!
One need's count its notifications!


TotalVirtualMemory returns unrealistic number for my application

Question:
My application is returning a very large number for TotalVirtualMemory. I instantiate a ComputerInfo() object and call TotalVirtualMemory and the value returned is ~130TB. Creating a basic project to test this seems to return the correct value: ~4GB. What could be causing this? My Code is below:

using System;
using Microsoft.VisualBasic.Devices;

namespace ConsoleApp1
{
    public class Program
    {
        private static void Main(string[] args)
        {
            var test = new Program();
            Console.WriteLine($"Total Virtual Memory: {test.GetTotalVirtualMemory()}");
            Console.WriteLine($"Total Virtual Memory Readable: {test.GetTotalVirtualMemory() * (1.0 / 1024.0 / 1024.0 / 1024.0)}");
        }

        public ulong GetTotalVirtualMemory()
        {
            return new ComputerInfo().TotalVirtualMemory;
        }
    }
}

Comment: What is so unrealistic about that value? Modern versions of Windows provide `128TiB` of address space for x64 applications.
Comment: What do you mean with "Creating a basic project to test this"?
Comment: Your "basic project" has the "Prefer 32-bit" checkbox turned on.  Project > Properties > Build tab.  You would get 2GB on a 32-bit OS or when you set the Platform Target to x86.  The ~130 terabyte is truly virtual, you can't get the paging file to grow that large quickly enough.  Nor would you ever want to garbage-collect that much heap.  A 64-bit OS is going to be good enough for a while to come.
Comment: I think I may be confusing what TotalVirtualMemory is. My understanding of it is basically that it is a swap file for an application. Is it possible to find the total virtual memory available for a certain application rather than the total virtual memory available to the system?
Comment: You are probably looking for `var p = Process.GetCurrentProcess(); var mem = p.VirtualMemorySize64;p.Dispose()`
Answer: 4GB is only expected for 32 bit processes, the number you got is the expected number for 64 bit processes
using System;
using Microsoft.VisualBasic.Devices;

namespace ConsoleApp1
{
    public class Program
    {
        private static void Main(string[] args)
        {
            var test = new Program();
            Console.WriteLine($"Is 64 Bit Process: {Environment.Is64BitProcess}");
            Console.WriteLine($"Total Virtual Memory: {test.GetTotalVirtualMemory()}");
            Console.WriteLine($"Total Virtual Memory Readable: {test.GetTotalVirtualMemory() * (1.0 / 1024.0 / 1024.0 / 1024.0)}");
        }

        public ulong GetTotalVirtualMemory()
        {
            return new ComputerInfo().TotalVirtualMemory;
        }
    }
}

Change your "platform target" in the "project properties -> build tab", to be only run on x86 instead of being set to x64 or AnyCPU and you will see the 4GB number you expected.
Comment: AFAIK, C# compiler do not set *Large address space aware* bit when compiling x32 applications, thus it is likely only `2GiB` will be available in that case.
Comment: Ah I see. My understanding of TotalVirtualMemory was incorrect. Is it possible to check the total virtual memory available for a certain application? Surely Windows wouldn't let a single application take up 130TBs worth of swap space?
Comment: Yes it will, swap does not take up space in the swap file unless the memory gets faulted (accessed for the first time) then space is assigned to it in the swap file. Also there are things like Memory Mapped Files that don't ever go in to swap but do take up room in the virtual address space. See [this superuser answer](https://superuser.com/questions/943175/windows-says-ram-ran-out-while-there-is-still-4-gb-of-physical-memory-available/943185#943185) that goes in to very good detail about how virtual memory actually works.


What is the Caio Hack?

Question: I was playing around right-clicking my line numbers in Dreamweaver, trying to bookmark a line.
I noticed this menu entry:

What is the Caio Hack? With alert('hi'); highlighted, this is the result:
Comment: Not sure this really warranted its own (self-answered) question.
Comment: Try this, for an explanation : http://bit.ly/14zJYNS
Comment: I agree with @MattBall, I am not against answering your own questions, but a simple Google search for this can provide you with more information then what you can (will) put in your post
Comment: @musefan I was curious to what the option did. Naturally, being an avid SO user, I searched SO instead of Google. No matches. That's why I posted the question & answer.
Answer: It's an old CSS hack.

"Caio Hack is a simple CSS comments-based hack used in 'inline' and
  'external' CSS declarations to hide information from Netscape 4"

For example, this code hides the .foo2 selector to Netscape 4:
.foo1
{
  color: green;
  background-color: yellow;
}
/*/*/
.foo2
{
  color: red;
}
/* */
.foo3
{
  color: blue;
}

Source: http://en.wikibooks.org/wiki/Cascading_Style_Sheets/Hacks_and_Filters/Caio_Hack
Answer: The Caio Hack is named after its discoverer, Caio Chassot.
It is a CSS hack for hiding rules from Netscape 4, exploiting a bug in NN4's parser.
By opening a comment using /*/*/, all subsequent CSS would be ignored by NN, because it thinks the comment didn't close.
To end the block, you'd use /* */.
For example:
.foo1
{
  color: green;
  background-color: yellow;
}
/*/*/
.foo2
{
  color: red;
}
/* */
.foo3
{
  color: blue;
}

More info at:

Wikibooks
CSS Discuss
Answer: http://css-discuss.incutio.com/wiki/Caio_Hack
It hides CSS codes from Netscape4 and sometimes Opera.

What is the Caio Hack?


broken mariadb debian update

Question: I have debian 8.0 with backports and the official mariadb repositories are set up. I already had mariadb-server-10.1 and it was trying to upgrade to an other version. The upgrade of mariadb failed and now it is broken. I can not use owncloud anymore. The other service using mysql is wordpress but it works without issues.
When I want to upgrade mariadb: I got this message:
Job for mariadb.service failed because the control process exited with error code.
See "systemctl status mariadb.service" and "journalctl -xe" for details.
invoke-rc.d: initscript mysql, action "start" failed.
dpkg: error processing package mariadb-server-10.1 (--configure):
 subprocess installed post-installation script returned error exit status 1
dpkg: dependency problems prevent configuration of mariadb-server:
 mariadb-server depends on mariadb-server-10.1 (= 10.1.22+maria-1~jessie); however:
  Package mariadb-server-10.1 is not configured yet.

dpkg: error processing package mariadb-server (--configure):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 mariadb-server-10.1
 mariadb-server
E: Sub-process /usr/bin/dpkg returned an error code (1)

systemctl status mariadb.service gives:
Apr 22 14:01:56 ctl mysqld[10359]: 2017-04-22 14:01:56 139845057845504 [ERROR] mysqld: Got error 'Could not get an exclusive lock; file is probably in use by another process' when trying to use aria control file '/var/lib/mysql/aria_log_control'
Apr 22 14:01:56 ctl mysqld[10359]: 2017-04-22 14:01:56 139845057845504 [ERROR] Plugin 'Aria' init function returned error.
Apr 22 14:01:56 ctl mysqld[10359]: 2017-04-22 14:01:56 139845057845504 [ERROR] Plugin 'Aria' registration as a STORAGE ENGINE failed.
Apr 22 14:01:56 ctl mysqld[10359]: 2017-04-22 14:01:56 139845057845504 [Note] Plugin 'FEEDBACK' is disabled.
Apr 22 14:01:56 ctl mysqld[10359]: 2017-04-22 14:01:56 139845057845504 [ERROR] Unknown/unsupported storage engine: InnoDB
Apr 22 14:01:56 ctl mysqld[10359]: 2017-04-22 14:01:56 139845057845504 [ERROR] Aborting
Apr 22 14:01:57 ctl systemd[1]: mariadb.service: Main process exited, code=exited, status=1/FAILURE
Apr 22 14:01:57 ctl systemd[1]: Failed to start MariaDB database server.
Apr 22 14:01:57 ctl systemd[1]: mariadb.service: Unit entered failed state.
Apr 22 14:01:57 ctl systemd[1]: mariadb.service: Failed with result 'exit-code'.

an journalctl -xe gives:
Apr 22 15:05:25 ctl sshd[10944]: Received disconnect from 22.214.171.124: 11:  [preauth]
Apr 22 15:05:25 ctl sshd[10944]: PAM 2 more authentication failures; logname= uid=0 euid=0 tty=ssh ruser= rhost=126.96.36.199  user=root
Apr 22 15:06:12 ctl sshd[10946]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=184.108.40.206  user
Apr 22 15:06:14 ctl sshd[10946]: Failed password for root from 22.214.171.124 port 51871 ssh2
Apr 22 15:06:17 ctl sshd[10946]: Failed password for root from 220.127.116.11 port 51871 ssh2
Apr 22 15:06:20 ctl sshd[10946]: Failed password for root from 126.96.36.199 port 51871 ssh2
Apr 22 15:06:21 ctl sshd[10946]: Received disconnect from 184.108.40.206: 11:  [preauth]

Output of ps aux | grep mysql is:
tchokap+ 11212 0.0 0.0 12728 2208 pts/0 S+ 15:31 0:00
grep mysql root 16860 0.0 0.0 40540 3196 ? S Feb01 0:00
sudo mysqld --binlog_format=MIXED mysql 16861 0.0 8.2 1064928 333048 ? Sl Feb01 103:34
mysqld --binlog_format=MIXED

I think the journal ctl refers to an other issue that my server is unable to resolve host ctl.
Comment: Is there already some form of a mariadb / mysqld running? If not, why are its files locked? (That's what the cut off message appears to be saying...?)
Comment: How can I check it specifically for mysqld? Mariadb server status is down. But I have wordpress working thus it should be using mysqld, shouldn't it?
Comment: The output of `ps aux | grep mysql` is `tchokap+ 11212  0.0  0.0  12728  2208 pts/0    S+   15:31   0:00 grep mysql
root     16860  0.0  0.0  40540  3196 ?        S    Feb01   0:00 sudo mysqld --binlog_format=MIXED
mysql    16861  0.0  8.2 1064928 333048 ?      Sl   Feb01 103:34 mysqld --binlog_format=MIXED`
Answer: It looks like you, for whatever reason, started mariadb manually using the command sudo mysqld --binlog_format=MIXED on February 1st.
Invoking mysqld directly instead of starting it through the init system (systemd in this case) is why things are in a weird state now.
The upgrade process assumed it could ask the init system to stop mariadb and then do the upgrade, but you have a mysqld instance that the init system knows nothing about.
Hence why there's a still a mysqld running despite the status being "down".
You should make sure the setting you provided on the command line (binlog_format=MIXED) is in the configuration file (my.cnf), stop your manually started mysqld and then try again.
Comment: It is not in `my.cnf`. What do I have to do?
Comment: @EtienneBorocco Presumably you added that command line argument when you started `mysqld` because you needed that setting? If so, add it to `my.cnf` (in the `[mysqld]` section).
Comment: I did `service mysqld stop`. I did `dist-upgrade` and `systemctl status mariadb.service` gave this: `ExecStart=/usr/sbin/mysqld $MYSQLD_OPTS $_WSREP_NEW_CLUSTER $_WSREP_START_POSITION (code=exited, status=1/FAILURE)`
Comment: That's kind of the point I was making, `service mysqld stop` won't stop something that you started entirely manually on the side like that.
Comment: How can I stop it? I don't understand.
Comment: I did `killall mysqld` and it works.
Answer: In my case was the mysqld_safe process which was restarting the mysqld each time I killed it.
Do a ps aux | grep mysqld
Take the PID of each process (the second column)
Run a kill -s 9 PID for each process (you can write more than one PID separating they by one space.
After that, try to run another time the apt-get upgrade or apt-get dist-upgrade
Comment: I was less subtle. I used `killall`.
Comment: It works too obviously ;-). I prefer to see before which processes I will finish by force.

broken mariadb debian update


Does every functor from Set to Set preserve products?

Question: In general, not all functors preserve products.  But my question is, is it at least true that all functors from Set to Set preserve products?
If not, does anyone know of a counterexample?
Comment: By "product", do you mean Cartesian product?
Answer: There are a lot of counterexamples, actually.
For example, if $S$ is has more than two elements, then the functor that map every set to $S$ and every function to the identity of $S$ does not preserve products, since the two projections $S\times S\to S$ are not equal.
The functor $X\mapsto S\times X$ does not preserve products either, because the function $$S\times X\times Y\to S\times X\times S\times Y:(s,x,y)\mapsto (s,x,s,y)$$
is never surjective.
Answer: If you consider the powerset functor $\mathcal{P}$, which takes any $A$ to its powerset $\mathcal{P}A$, and any function $f : A \to B$ to the function $\mathcal{P}f : \mathcal{P}A \to \mathcal{P}B$, defined by the direct image, for $X\subset A$, $(\mathcal{P}f)(X) = f(X) \subset B$. This defines a functor from Set to Set.
Now you can check that this functor doesn't preserve products, since, for instance you have :
$\mathcal{P}\{0\} = \{\emptyset,\{0\}\}$, so taking any non-empty finite set $A$, you have $\mathcal{P}(A\times\{0\}) = \mathcal{P}(A) \neq \mathcal{P}(A)\times\mathcal{P}(\{0\})$. You can check that they are indeed different by looking at their cardinal :
$|\mathcal{P}(A)\times\mathcal{P}(\{0\})| = 2  |\mathcal{P}(A)| $


Python code that counts the number of distinct words with a specific length in a file

Question: I'm looking for a way in Python to write a function that, having two input(name of a text file and a natural number n), returns the number of all the distinct words in the file (House and HOUSE are two different words for example) with the length given in input
Comment: What have you tried so far ?
Comment: Please read https://stackoverflow.com/help/how-to-ask and edit your question accordingly.
Answer: Try something like this. A Set is more appropriate than a list for coutning unique word.
def f(filename: str, n: int) -> list:
    res = set()
    with open(filename, "r") as file:
        lines = file.readlines()

    for line in lines:
        for word in line.split(' '):
            if len(word) == n:
                res.add(word)
    return list(res)

Answer: Using the Word count answer approach we can find all the words and their counts.
from collections import Counter

with open('myfile.txt') as f:
    wordcount = Counter(f.read().split())

Then, you can just filter the desired length:
n = 5
result = {k: v for k, v in result.items() if len(k) == n}


I am confused with ranef function in R

Question: Do the ranef and fixef functions in lmer give the random and fixed effect coefficients? If not what do they really give?
Data looks something like (this is a fake data):
id      1  1  1  2  2  2
weight 34 45 56 78 12 45
count  23 12 13 16 14 22

Model looks like mod <- lmer(weight ~ count + (1+count|id), data=d1)
where id is a random effect in the model and count is fixed effect.
I believed that the statement coef(model)$id[,"count"] in R will give the random coefficients for count by each id.
Am I correct?
If yes then what does ranef(mod) give?
Any help is much appreciated. Sorry for the confusion.
Comment: This post repeatedly references a "below statement" that seems to be missing.  Please edit it to include the absent material, which seems to be crucial for its understanding.
Comment: For better understanding please provide details of your question and the R codes you tried.
Comment: I have edited the question Please let me know if it clear the doubts
Answer: Example from the lme4 package:
fm1 <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy)

For this model coef(fm1) gives
$Subject
    (Intercept)       Days
308    253.6637 19.6662581
309    211.0065  1.8475834
310    212.4449  5.0184067
...

This is the 'summed up' version, assuming you want to know the subject-specific intercept and subject specific slope for Day.  This is constructed by combining the fixed effects, which provide the mean, with the random effects, which are zero centred and provide the variation.  fixef(fm1) gives
(Intercept)        Days
  251.40510    10.46729

and ranef(fm1) gives
$Subject
    (Intercept)        Days
308   2.2585637   9.1989722
309 -40.3985802  -8.6197026
310 -38.9602496  -5.4488792
...

Looking at subject 308 we see that their personal intercept 253.6637 is equal to the grand mean 251.40510 plus 2.2585637 and their personal slope 19.6662581 is equal to the fixed effect slope 10.46729 plus their personal slope 9.1989722.
The advantage of ranef in all this is that you can get the posterior uncertainty (or whatever it is that lme4 actually computes) over the random effects using ranef(fm1, condVar = TRUE).  What you got before were only point estimates of random variables.
Comment: You might want to read something on mixed or multilevel models, but in short you can treat the distributions that you get if you, say, `dotplot(ranef(fm1, condVar=TRUE))` as measures of uncertainty about what the subject-specific effects are (you'll want to `require(lattice)` before doing this) in roughly the same way as standard errors work for the fixed effects.
Comment: In case you're looking for further reading, this is all covered in detail with examples in Gelman and Hill's textbook on mixed effects modeling. It's a very, very good reference.
Comment: Thank you! Can you explain what does posterior uncertainty mean and how to interpret them?
Comment: If you have level 1 and level 2 randomized predictors (e.g., year and site), how can I get ranef to give me site and not year as default?

I am confused with ranef function in R


Class 'views_plugin_display' not found

Question: Getting this
PHP Fatal error:  Class 'views_plugin_display' not found in ../sites/all/modules/contrib/media/includes/media_views_plugin_display_media_browser.inc on line 18, referer: ..
Any ideas how I can fix that?
Thanks,
Dmytro
Answer: If you have Views enabled, this might be an issue with Media.  This has been previously reported the issue queue for the project, and there it was suggested to reinstall the latest version of the Media module, in case the files had become corrupt.

Class 'views_plugin_display' not found


What is UpdateProcessor(solr) equivalent in elasticsearch?

Question: I am using elasticsearch. I want to do some processing of text content during indexing and store in different fields. I used to do this in Solr by using UpdateProcessors(Python,Java or Javascript).
I am new to elasticsearch.
I could see some posts saying elastic search doesnt support such operations during indexing.
But, I do not want to do this outside indexing to avoid additional layers.
Can someone help me with some pointers or samples?
Answer: There is none. Some of the things that Solr does with UpdateRequestProcessors (such as id generation, dynamic schema, etc) Elasticsearch has built in and - mostly - automatic.
But there is no way to specify a pipeline of components to apply to the incoming documents.
According to Shay Banon (Elasticsearch creator), such functionality belong to the client.


Homomorphisms of the algebraic Torus

Question:
Any (holomorphic) group homomorphism $f:\mathbb{C}^\ast\rightarrow\mathbb{C}^\ast$ is of the form $f(z)=z^k$ ?

Is this true? I tried this: differentiating $f(zw)=f(z)f(w)$ with respect to $z$ gives:
$$\forall w\in\mathbb{C}^\ast \quad f_z(z)=w\cdot f_z(zw)\cdot f(1/w) $$
where $f_z=\partial_z f$. Choosing $w=1/z$, this leads to
$$ df=c\frac{f(z)}{z} dz ,$$
where $c=f_z(1)$. But then I am not sure how to use this to show $f(z)=z^c$. Is this correct?
Answer: Write $f$ as a Laurent series $f(z)=\sum_{n\in \mathbb Z}a_nz^n$.
   Now since $f(2z)=f(2)f(z)$, we have $$f(2z)=\sum a_n2^nz^n=f(2)\sum a_nz^n$$ so that for all $n\in \mathbb Z$ we deduce $2^na_n=f(2) a_n$.
This proves that  $a_n$ can be nonzero for only one $n$ : the $n_0=k$ with $f(2)=2^k$ .
Thus $f(z)$ is of the form $f(z)=a_kz^k$and the equation $f(zw)=f(z)f(w)$ translates into $a_kz^kw^k=a_kz^ka_kw^k$, forcing $a_k=a_k^2$ and thus $a_k=1$ (recall  $k$ was chosen so that $a_k\neq 0)$.
Hence  necessarily $f(z)=z^k$ for some integer $k\in \mathbb Z$, just as you wished.
Comment: That's very neat. Thank you.
Comment: It's a pleasure, Heitor.

Homomorphisms of the algebraic Torus


IIS ASP Redirect Removal

Question: We have a website that is setup on IIS 7 and are trying to replace it with a new site, but need a redirect that is in place removed.
The old site used a custom file as the homepage (WN-main.asp).  We removed all the old site files, including web.config, and placed them in a subdirectory for safe keeping.
The new site no longer uses ASP, and we'd like to use a regular index.html as the default. However, when we go to the website, it keeps trying to redirect our .com to .com/WN-main.asp -- and that gives us a 404 Error in the Application for "Default Web Site" because we removed that page.
In the IIS "Default Document" settings we have index.html at the top, and WN-main.asp is nowhere to be found in the list (it never was there). We've also removed the web.config file from the root directory, and put the entire old website in a subdirectory. As well as restarted IIS. We're assuming that the redirect is setup somewhere in IIS because if I navigate to .com/index.html which is our new site, it works. Our problem is that oursite.com redirects to oursite.com/WN-main.asp. Grr.  If you go to www.worzalla.com you can see how it redirects to the WN-main.asp page right now as the homepage.
Any ideas where this redirect could have been setup so we can remove it?
Thanks!
Answer: Take a look for the IIS Redirect Module, it would be configured under the site settings.  You may also have the IIS Rewrite Module as well.  You will need to look for the rules there.  Also, if you happen to have a load balancer or some other intelligent device between your server and the internet you will also need to check there.
Answer: A redirect could also be setup in IIS manager under HTTP redirect or in an ISAPI filter
Answer: Found nothing in the IIS Redirect Module, and had checked it multiple times.  We disabled and enabled it.
We are not sure exactly what ended up being the issue - somewhere, somehow, the old homepage was possibly cached on the server and the page itself had a redirect to the /WN-main.asp page...even though the server should not have been caching anything and we had checked that multiple times initially. After playing around with lots of settings, it just suddenly started working! Grrr Microsoft. The fact that we disabled and enabled asp and .net may have helped, but I'm not sure...at least it's working now!

IIS ASP Redirect Removal


Gunicorn with gevent does not enforce timeout

Question: Let's say I have a simple flask app:
import time
from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    for i in range(10):
        print(f"Slept for {i + 1}/{seconds} seconds")
        time.sleep(1)
    return "Hello world"

I can run it with gunicorn with a 5 second timeout:
gunicorn app:app -b 127.0.0.1:5000 -t 5

As expected, http://127.0.0.1:5000 times out after 5 seconds:
Slept for 1/10 seconds
Slept for 2/10 seconds
Slept for 3/10 seconds
Slept for 4/10 seconds
Slept for 5/10 seconds
[2022-07-07 22:45:01 -0700] [57177] [CRITICAL] WORKER TIMEOUT (pid:57196)

Now, I want to run gunicorn with an async worker to allow the web server to use its available resources more efficiently, maximizing time that otherwise would be spent idling to do additional work instead. I'm using gevent, still with a timeout of 5 seconds.
gunicorn app:app -b 127.0.0.1:5000 -t 5 -k gevent

Unexpectedly, http://127.0.0.1:5000 does NOT time out:
Slept for 1/10 seconds
Slept for 2/10 seconds
Slept for 3/10 seconds
Slept for 4/10 seconds
Slept for 5/10 seconds
Slept for 6/10 seconds
Slept for 7/10 seconds
Slept for 8/10 seconds
Slept for 9/10 seconds
Slept for 10/10 seconds

Looks like this is a known issue with gunicorn. The timeout only applies to the default sync worker, not async workers: https://github.com/benoitc/gunicorn/issues/2695

uWSGI is an alternate option to gunicorn. I'm not as familiar with it. Looks like its timeout option is called harakiri and it can be run with gevent:
uwsgi --http 127.0.0.1:5000 --harakiri 5 --master -w app:app --gevent 100

uWSGI's timeout sometimes works as expected with gevent:
Slept for 1/10 seconds
Slept for 2/10 seconds
Slept for 3/10 seconds
Slept for 4/10 seconds
Slept for 5/10 seconds
Thu Jul  7 23:20:59 2022 - *** HARAKIRI ON WORKER 1 (pid: 59836, try: 1) ***
Thu Jul  7 23:20:59 2022 - HARAKIRI !!! worker 1 status !!!
Thu Jul  7 23:20:59 2022 - HARAKIRI [core 99] 127.0.0.1 - GET / since 1657261253
Thu Jul  7 23:20:59 2022 - HARAKIRI !!! end of worker 1 status !!!
DAMN ! worker 1 (pid: 59836) died, killed by signal 9 :( trying respawn ...

But other times it doesn't time out so it appears to be pretty flaky.

Is there anyway to enforce a timeout using gunicorn with an async worker? If not, are there any other web servers that enforce a consistent timeout with an async worker, similar to uWSGI?
Answer: From https://docs.gunicorn.org/en/stable/settings.html#timeout:

Workers silent for more than this many seconds are killed and restarted.

For the non sync workers it just means that the worker process is still communicating and is not tied to the length of time required to handle a single request.

So timeout is likely functioning by design — as worker timeout, not request timeout.
You can subclass GeventWorker to override handle_request() with gevent.Timeout:
import gevent
from gunicorn.workers.ggevent import GeventWorker

class MyGeventWorker(GeventWorker):

    def handle_request(self, listener_name, req, sock, addr):
        with gevent.Timeout(self.cfg.timeout):
            super().handle_request(listener_name, req, sock, addr)

Usage:
# gunicorn app:app -b 127.0.0.1:5000 -t 5 -k gevent
gunicorn app:app -b 127.0.0.1:5000 -t 5 -k app.MyGeventWorker


How to remove search bar from Firebug?

Question: I use Firebug for development. However, it kind of seriously interrupts my development workflow because it prevents me from using the Tab key to switch the focus to the address bar of Firefox such that I can reload the page after some modification. Instead, it seems as if Tab will strictly only direct focus to the Firebug search bar. Even repeated hits of Tab will stay on the firebug search bar.
That's annoying. How can I remove the Firebug search bar?
Comment: I cannot reproduce your problem using Firefox 30.0 + Firebug 2.0 on Windows. Pressing Tab lets me switch to the address bar of Firefox. What configuration do you have?
Answer: To remove the search bar from Firebug you would need to change it's code. I don't think you want to do this, but to remove the search bar you have to remove the following code line (in Firebug 2.0) from the firebugOverlay.xul file:
<textbox flex="70" id="fbSearchBox" type="fbSearchBox"/>

See this line on GitHub:
https://github.com/firebug/firebug/blob/7f621b61c3961e3390e1caf60a733e28d3b42336/extension/content/firebug/firebugOverlay.xul#L117
To switch to the Firefox address bar you can also simply press F6. If you just want to reload the page, you can press F5. Both keys work fine in combination with Firebug.
Furthermore there's a list of all shortcuts at the Mozilla website.
Answer: Check this one : https://addons.mozilla.org/en-us/firefox/addon/hide-navigation-bar/?src=search
parent link : https://support.mozilla.org/en-US/questions/939601

How to remove search bar from Firebug?


Why can't datatables display data in descending order by default?

Question: In addition to the normal sorting capability in datatable, I want to display my datatable in descending order (order by id from mysql result) by default. However without any error, it keeps displaying the datatable in ascending order.
Here are what I have done so far:
JS:
$('#example').dataTable({
    "aaSorting": [[0, "desc"]]
});

and my serverside:
PHP:
SELECT s . * , c.name AS cls, sec.name AS sect
                    FROM `student` s
                    INNER JOIN cls c
                    ON s.cls = c.id
                    INNER JOIN sect sec
                    ON s.sect = sec.id
                    ORDER BY s.id DESC

HTML:

//table data here

Any suggestion and help is greatly appreciated.
Comment: Could it be  that JS is reversing order from SQL?
Comment: Maybe you are ordering twice:
In your SQL: DESC, and then in JS: Again DESC. DESC*DESC=ASC
Answer: I'm facing the same problem. we can solve it by adding data one by one in data table in descending order. create an empty table by html and
var table = $("#example").dataTable();

use ajax and get data in descending order in variable.
 $.ajax({
          // params
          success(data){
            table.fnClearTable(); // to clear the table
            $.each(data, function(i,item)){
               table.fnAddData([data.item1, data.item2,data.item3,.....]) // adding data
            }
            table.fnDraw(); // re draw the table
      }
    })


How can I delete a directory in a Zip file using .NET?

Question: How would I delete a directory in a .zip and all the files in it (preferably using DotNetZip)?
Right now I'm running through all the files in the zip, but it doesn't work:
foreach (ZipEntry e in zip)
{
    //If the file is in the directory I want to delete
    if(e.FileName.Substring(0, 9) == "FolderName/")
    {
        zip.RemoveEntry(e.FileName);
    }
}

Is there a better way, if not, how would I make this work?
Comment: Can't help but notice you retrieve a substring of length 9 chars, only to compare it to one of 11 chars, so it will *always* return false. (or is this just an example string?)
Comment: -1 really? I researched for a few hours. I was just stuck on this couldn't figure it out...
Answer: Here's a simple way to do this:
using (ZipFile zip = ZipFile.Read(@"C:\path\to\MyZipFile.zip"))
{
    zip.RemoveSelectedEntries("foldername/*"); // Delete folder and its contents
    zip.Save();
}

Documentation here http://dotnetzip.herobo.com/DNZHelp/Index.html
Answer: First tought. Don't loop with foreach while removing elements from the collection.
I will try in this way
for(int x = zip.Count -1; x >= 0; x--)
{
    ZipEntry e = zip[x];
    if(e.FileName.Substring(0, 9) == "FolderName/")
        zip.RemoveEntry(e.FileName);
}

However, looking at the methods of the ZipFile class, I noticed the method:
SelectEntries that return a ICollection. So I think it's possible to do:
EDIT: Use overloaded version SelectEntries(string,string)
var selection = zip1.SelectEntries("*.*", "FolderName");
for(x = selection.Count - 1; x >= 0; x--)
{
    ZipEntry e = selection[x];
    zip.RemoveEntry(e.FileName);
}

removing the loop on all entries in the zipfile
Comment: If you remove an item from a collection while you're enumerating through it, it's hardly surprising you'll had seen issues. This rather neat approach iterates through the collection by index, in reverse order, which avoids the issue.
Comment: That worked great. Why do you think mine failed? (Also, if possible, is there a way to delete the folder now?)
Comment: @Chris what error did you get when you tried removing the file?
Comment: I love you guys, Haha. Thanks a bunch!
Comment: Remove folder? Not necessary. If I remember well, removing all the "foldername/*.*" files will cause the 'folder' to disappear
Comment: @Greg "Collection was modified; enumeration operation may not be executed."
Comment: @Chris, so as you've already learned, the runtime doesn't like you changing the contents of an enumerable while you're enumerating it. If you think about it, you can imagine it could cause all kinds of weirdness.
Comment: I get an error saying, can't apply index on Ionic.Zip.ZipEntry for line, selection[x];
Comment: jeez, this seems like a lot of work. There should be a RemoveDirectory method
Comment: @TheUnrealMegashark Why don't you ask your own question? You could reference this question and tell everyone what error do you get.
Comment: Most people said you had to unzip it first... http://stackoverflow.com/questions/17904973/delete-folder-from-jar-while-treating-as-a-zip
Answer: You can achieve it as follows
using (ZipArchive zip = ZipFile.Open(@"C:\path\to\MyZipFile.zip", ZipArchiveMode.Update))
{
    zip.Entries.Where(x => x.FullName.Contains("Foldername")).ToList()
        .ForEach(y =>
        {
            zip.GetEntry(y.FullName).Delete();
        });
}

Note : If all the files from the folder is deleted then the folder will be automatically removed.
Answer: In order to delete the directory and all nested child entries, I used
var sel = (from x in zip.Entries where x.FileName.StartsWith(path, StringComparison.OrdinalIgnoreCase) select x.FileName).ToList();
foreach (var fn in sel)
{
     zip.RemoveEntry(fn);
}

Note that the path must end with a slash, like dir/subdir/


AWS IAM policy issue: unable to permit all but RunInstances

Question: We are struggling to create an IAM policy that permits all EC2 actions EXCEPT RunInstances.  This is to prevent an API key compromise from launching unauthorized instances.  We tried it both with and without the EC2 allow * because I'm not clear if NotAction implies all actions.
With the NotAction in place I cannot provision EBS volumes (below).  Do we need to converge the EC2 allow * and Notaction Runinstances into the same policy section?
EC2 All permissions:
"Action": "ec2:",
"Effect": "Allow",
"Resource": "",
and then a second policy that denies RunInstances (from previous IAM policy answer on similar topic
{
  "Statement": [
    {
      "NotAction": [
        "ec2:RunInstances*"
      ],
      "Effect": "Deny",
      "Resource": "*"
    }
  ]
}
ec2-54-196-184-11.compute-1.amazonaws.com   * aws_ebs_volume[ip-10-140-10-132.volume15] action create
ec2-54-196-184-11.compute-1.amazonaws.com [2014-06-26T18:17:53+00:00] WARN: ##### RightAws::Ec2 returned an error: 403 Forbidden
ec2-54-196-184-11.compute-1.amazonaws.com
ec2-54-196-184-11.compute-1.amazonaws.com UnauthorizedOperationYou are not authorized to perform this operation.fcd71112-db50-4102-9855-a46749574de9 #####
ec2-54-196-184-11.compute-1.amazonaws.com [2014-06-26T18:17:53+00:00] WARN: ##### RightAws::Ec2 request: https://us-east-1.ec2.amazonaws.com:443/?AWSAccessKeyId=XXXXXXXXXXXXXXXXXXX&Action=DescribeVolumes&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2014-06-26T18%3A17%3A53.000Z&Version=2012-06-15&Signature=cRMAxfs3RP0R9rlQeb7JU9zYeey8L3CWQI2Pkj2o3V0%3D ####
ec2-54-196-184-11.compute-1.amazonaws.com
ec2-54-196-184-11.compute-1.amazonaws.com ================================================================================
ec2-54-196-184-11.compute-1.amazonaws.com Error executing action create on resource 'aws_ebs_volume[ip-10-140-10-132.volume15]'
ec2-54-196-184-11.compute-1.amazonaws.com ================================================================================
ec2-54-196-184-11.compute-1.amazonaws.com
ec2-54-196-184-11.compute-1.amazonaws.com
ec2-54-196-184-11.compute-1.amazonaws.com RightAws::AwsError
ec2-54-196-184-11.compute-1.amazonaws.com ------------------
ec2-54-196-184-11.compute-1.amazonaws.com UnauthorizedOperation: You are not authorized to perform this operation.
ec2-54-196-184-11.compute-1.amazonaws.com
ec2-54-196-184-11.compute-1.amazonaws.com
ec2-54-196-184-11.compute-1.amazonaws.com Cookbook Trace:
ec2-54-196-184-11.compute-1.amazonaws.com ---------------
ec2-54-196-184-11.compute-1.amazonaws.com /var/chef/cache/cookbooks/aws/providers/ebs_volume.rb:138:in `currently_attached_volume'
ec2-54-196-184-11.compute-1.amazonaws.com /var/chef/cache/cookbooks/aws/providers/ebs_volume.rb:26:in `block in class_from_file'
ec2-54-196-184-11.compute-1.amazonaws.com
ec2-54-196-184-11.compute-1.amazonaws.com
ec2-54-196-184-11.compute-1.amazonaws.com Resource Declaration:
ec2-54-196-184-11.compute-1.amazonaws.com ---------------------
ec2-54-196-184-11.compute-1.amazonaws.com # In /var/chef/cache/cookbooks/cook_aws/recipes/ebs.rb
ec2-54-196-184-11.compute-1.amazonaws.com
ec2-54-196-184-11.compute-1.amazonaws.com  26:   aws_ebs_volume node['w2o']['ebs']['volume_name'] do
ec2-54-196-184-11.compute-1.amazonaws.com  27:     action [:create, :attach]
ec2-54-196-184-11.compute-1.amazonaws.com  28:     aws_access_key node['aws']['access_key_id']
ec2-54-196-184-11.compute-1.amazonaws.com  29:     aws_secret_access_key node['aws']['secret_access_key']
ec2-54-196-184-11.compute-1.amazonaws.com  30:     device node['w2o']['ebs']['ebs_device']
ec2-54-196-184-11.compute-1.amazonaws.com  31:     size node['w2o']['ebs']['ebs_mount_size']
ec2-54-196-184-11.compute-1.amazonaws.com  32:
ec2-54-196-184-11.compute-1.amazonaws.com  33:     # specify piops if present in node attr
ec2-54-196-184-11.compute-1.amazonaws.com  34:     if node['w2o']['ebs']['ebs_piops'] > 0
ec2-54-196-184-11.compute-1.amazonaws.com  35:       piops node['w2o']['ebs']['ebs_piops']
ec2-54-196-184-11.compute-1.amazonaws.com  36:       volume_type 'io1'
ec2-54-196-184-11.compute-1.amazonaws.com  37:     end
ec2-54-196-184-11.compute-1.amazonaws.com  38:
ec2-54-196-184-11.compute-1.amazonaws.com
ec2-54-196-184-11.compute-1.amazonaws.com
ec2-54-196-184-11.compute-1.amazonaws.com
ec2-54-196-184-11.compute-1.amazonaws.com Compiled Resource:
ec2-54-196-184-11.compute-1.amazonaws.com ------------------
ec2-54-196-184-11.compute-1.amazonaws.com # Declared in /var/chef/cache/cookbooks/cook_aws/recipes/ebs.rb:26:in `from_file'
ec2-54-196-184-11.compute-1.amazonaws.com
ec2-54-196-184-11.compute-1.amazonaws.com aws_ebs_volume("ip-10-140-10-132.volume15") do
ec2-54-196-184-11.compute-1.amazonaws.com   action [:create, :attach]
ec2-54-196-184-11.compute-1.amazonaws.com   retries 0
ec2-54-196-184-11.compute-1.amazonaws.com   retry_delay 2
ec2-54-196-184-11.compute-1.amazonaws.com   cookbook_name "cook_aws"
ec2-54-196-184-11.compute-1.amazonaws.com   recipe_name "ebs"
ec2-54-196-184-11.compute-1.amazonaws.com   aws_access_key "XXXXXXXXXXXXXXXXXXXXX"
ec2-54-196-184-11.compute-1.amazonaws.com   aws_secret_access_key "XXXXXXXXXXXXXXXXXXXXX"
ec2-54-196-184-11.compute-1.amazonaws.com   device "/dev/xvdf"
ec2-54-196-184-11.compute-1.amazonaws.com   size 50
ec2-54-196-184-11.compute-1.amazonaws.com end
ec2-54-196-184-11.compute-1.amazonaws.com
ec2-54-196-184-11.compute-1.amazonaws.com
ec2-54-196-184-11.compute-1.amazonaws.com
ec2-54-196-184-11.compute-1.amazonaws.com [2014-06-26T18:17:53+00:00] ERROR: Running exception handlers
ec2-54-196-184-11.compute-1.amazonaws.com [2014-06-26T18:17:53+00:00] ERROR: Exception handlers complete
ec2-54-196-184-11.compute-1.amazonaws.com [2014-06-26T18:17:53+00:00] FATAL: Stacktrace dumped to /var/chef/cache/chef-stacktrace.out
ec2-54-196-184-11.compute-1.amazonaws.com Chef Client failed. 2 resources updated
ec2-54-196-184-11.compute-1.amazonaws.com [2014-06-26T18:17:54+00:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)
Answer: Spent an hour with a trial account and the IAM simulator to get:
{
"Version": "2012-10-17",
"Statement": [
    {
        "NotAction": [
            "ec2:RunInstances*"
        ],
        "Effect": "Allow",
        "Resource": "*"
    },
    {
        "Effect": "Allow",
        "Action": "elasticloadbalancing:*",
        "Resource": "*"
    },
    {
        "Effect": "Allow",
        "Action": "cloudwatch:*",
        "Resource": "*"
    },
    {
        "Effect": "Allow",
        "Action": "autoscaling:*",
        "Resource": "*"
    }
]

}
Posting in case this is useful to someone, you can put whatever actions you want under NotAction
Comment: Careful - that policy will allow users to perform any action in the whole AWS account other than ec2:RunInstances. For example, creating RDS instances, elasticache clusters and even full access to IAM which allows them to change their own permissions. They would then be able to change the policy to allow ec2:RunInstances anyway.
Comment: TYVM will retry with  "Resource": "ec2:*" instead, I did not think of the IAM hole.  The RDS thing is okay in our case.  But the IAM hole needs to be fixed!  I will attach another policy that has IAM Deny *.


Qual a diferença entre {} e ({}) em uma arrow function?

Question: Nesta arrow function, para que retornasse um objeto por que foi necessário o parenteses?
const calculator = (number1, number2) => ({
  sum: number1 + number2,
  mult: number1 * number2,
  div: Math.floor(number1 / number2),
  sub: number1 - number2,
});

Answer: Achei um post aqui no Stackoverflow mesmo que acho que pode te ajudar nessa duvida, mas basicamente pelo que eu compreendi:
os () servem para e quando vc vai fazer uma ação aonde o código que a variável invoca  tiver mais de uma linha e quando e uma ação única que só será executada quando a variável for chamada
as {} e pra criar um bloco de ações que pode ter retorno tipo o os exemplos que foram colocados no post que me baseei
const fn1 = () => {
  return 'Olá, mundo!'
};

const fn2 = (x, y) => {
  // `if` é um exemplo de declaração (statement):
  if (x > y) {
    return 'X é maior que Y.';
  }
};

já quando temos ({}) e quando vc quer retornar um objeto e quando vc tem múltiplas linhas de código separados por ( , )
Não leve oq eu disse como verdade absoluta da uma pesquisada a mais tmb , e da uma olhada no post que aborda esse assuntos de parênteses e chaves
Qual a diferença entre chaves e parênteses em uma arrow function no JavaScript?
Comment: Muito obrigada!!
Comment: Não há de que :)


Prevent several threads from entering the same method of different objects

Question:  Please skip to the TLTR if you do not want to read the whole story but the question:)
I need to fix a bug in our system and I have found the bug but could not find an optimal solution for this problem.
As an illustration, what it is aimed to be done is; when there are three files to be closed and for each file, a different thread (3 threads in this example) is created and should get the id of the file and by using file's id, it should close the file.
However, the person, who programs this, did not think something genuinely. At the moment, three threads are created for three different files and they access to the method, which distributes the ids, at the same time and the method gives the id of the first file (normally, first id to first thread, second id to second thread and third id to the third thread should be given) to three threads and these three threads try to close the same file (which causes the bug).
I cannot change this structure and it should be remain as it is.

TLTR
What I try to achieve is; how can I prevent several threads from entering the same method at the same time?
I tried synchronized (and lock) strategies for this but they did not help me in this situation, because each thread has its own lock (there are several objects created).
Comment: You need to synchronize on the same object. You'll probably have to paste some code illustrating your problem better.
Comment: That doesn't contradict anything I said. I am just asking for more information and telling you the gist of the solution.
Comment: Thank for the comment. The system, which I am current working on, is a legacy system and I cannot change anything except for solving the problem because it is tightly coupled.
Comment: @matt I will try your solution, if it does not work, I will give more information. Thanks for the answer btw.
Answer: Create a singleton.
public static final Object globalLock = new Object();

Then in your methods where you need to protect.
synchronized(globalLock){
     //get your file ids.
}

Comment: Thank you again. This solution worked for me. I did not know about this static global lock. Again learnt something :)
Comment: @AdInfinitum it is just a static field that all of your threads have access to, which lets you synchronize on the same object. It would be very similar to using the `MyClass.class` solution below. Glad to hear it works.
Answer: Couple of ways for doing this, here are some:
Make method synchronized
    public class MyClass{
         public void synchronized mySynchronizedMethod(); // only single thread will be allowed to invoke this method on the SAME INSTANCE OF MyClass

         public void notSynchronizedMethod();
    }

Use synchronized block:
MyClass obj=new MyClass();
synchronized(obj){
  // only single thread is allowed to enter that block WITH obj INSTANCE.
      obj.notSynchronizedMethod():
}

Synchronize on class
MyClass obj=new MyClass();
synchronized(MyClass.class){
//single thread is allowed for this block in a scope of WHOLE CLASS LOADER so in most cases you can say it is "globally" synchronized
}

Use Semaphore
Semaphore sem=new Sempahore(1);
sem.aquire(); // Thread will aquire permit, another thread will wait
//this will be synchronized block
sem.release(); allows another thread to aquire permit

Comment: Hi, thanks for your answer. Even if your solutions are perfect, I needed something like a global lock, which matt gave in his answer. Because, the system creates different objects instead of working on the same object and the classical way of synchronizing did not help me. But I upvoted your answer because I think you give a very good overview on different locks.


Seeking help in understanding the proof of the mean value property for harmonic functions

Question: I am currently trying to understand the proof of the mean value property from 'Harmonic Function Theory' by Axler, Bourdon, and Ramet.
Mean-Value Property: If $u$ is harmonic on $\bar{B}(a, r)$, then $u$ equals the average of $u$ over $\partial B(a, r)$. More precisely,
$$u(a) = \int_S u(a + r\zeta) \, d\sigma(\zeta)$$
Here is the beginning of the proof:
First assume that $n > 2$. Without loss of generality we may assume that $B(a, r) = B$. Fix $\epsilon \in (0, 1)$. Apply Green's identity with $\Omega = \{x \in \mathbb{R}^n : \epsilon < |x| < 1\}$ and $v(x) = |x|^{2 - n}$ to obtain
$$0 = (2 - n) \int_S u \, ds - (2 - n)\epsilon^{1 - n} \int _{\epsilon S}u \, ds - \int_S D_\textbf{n}u \, ds - \epsilon^{2 - n} \int_{\epsilon S}D_\textbf{n}u \, ds$$
They use Green's identity:
$$\int_{\Omega} (u\Delta v - v\Delta u) \, dV = \int_{\partial\Omega} (uD_\textbf{n} v - vD_\textbf{n} u) \, dS$$
Where $D_\mathbf{n}$ represents the directional derivative with respect to the normal vector $\mathbf{n}$.
I understand that the left side is $0$ because $u$ and $v$ are both harmonic, but I am having trouble understanding the right side of the equation. This is what I have done so far, and I'm unsure if it is correct.
$$D_\textbf{n}|x|^{2 - n} = \nabla |x|^{2 - n}\cdot\textbf{n} = (2 - n)|x|^{-n}x \cdot \textbf{n} = (2 - n)|x|^{-n}|x| = (2 - n)|x|^{1-n}$$
Then I don't know how to proceed.
Answer: Note that $\partial\Omega$ is the union of two connected components. The first is the unit sphere $S$, and the second is the sphere $\epsilon S$ of radius $\epsilon$ and centered at the origin. So, for any (nice enough) function $f$, when we integrate against the area measure $dA$, we get
\begin{align}
\int_{\partial \Omega}f\,dA&=\int_Sf\,dA+\int_{\epsilon S}f\,dA.
\end{align}
Now, plug in
\begin{align}
f&=uD_\mathbf{n_{\partial\Omega}}v-vD_{\mathbf{n}_{\partial\Omega}}u.
\end{align}
This is when we have to be extra careful with signs. Note that since $\partial \Omega$ is oriented using its outward unit normal, $S$ has the usual orientation "outward", but on the surface $\epsilon S$, the outward direction to $\partial\Omega$ is actually the opposite of its usual orientation (draw a picture, so this should be clear).
So, at points $x\in S$, we have $\mathbf{n}_{\partial\Omega}(x)=\frac{x}{|x|}=x$, since $|x|=1$, so on $S$, we have
\begin{align}
f(x)&=u(x)\cdot (2-n)(1)^{n-1}-(1)^{n-2}D_{\mathbf{n}_{\partial \Omega}}u(x)=(2-n)u(x)-D_{\mathbf{n}_{\partial\Omega}}u(x).
\end{align}
For points $x\in \epsilon S$, we have $\mathbf{n}_{\partial\Omega}(x):=-\mathbf{n}_{\epsilon S}(x)=-\frac{x}{|x|}=-\frac{x}{\epsilon}$, so when evaluating $D_{\mathbf{n}_{\partial\Omega}}v(x)$, we get an extra minus sign:
\begin{align}
D_{\mathbf{n}_{\partial\Omega}}v(x)&=\langle\nabla v(x),\mathbf{n}_{\partial\Omega}(x)\rangle=\left\langle (2-n)|x|^{1-n}\frac{x}{|x|},-\frac{x}{|x|}\right\rangle=-(2-n)\epsilon^{1-n}.
\end{align}
Thus,
\begin{align}
\int_{\partial\Omega}(uD_{\mathbf{n_{\partial\Omega}}}v-vD_{\mathbf{n}_{\partial\Omega}}u)\,dA&=\int_S\left[(2-n)u-D_{\mathbf{n}_{\partial\Omega}}u\right]\,dA\\
&+\int_{\epsilon S}\left[u\cdot \left(-(2-n)\epsilon^{1-n}\right)-|\epsilon|^{2-n}D_{\mathbf{n}_{\partial\Omega}}u\right]\,dA\\
&=(2-n)\int_Su\,dA-(2-n)\epsilon^{1-n}\int_{\epsilon S}u\,dA\\
&-\int_{S}D_{\mathbf{n}_{\partial\Omega}}u\,dA-\epsilon^{2-n}\int_{\epsilon S}D_{\mathbf{n}_{\partial\Omega}}u\,dA.
\end{align}
This is exactly what you have. If it were me, I would have liked (because I just like it:) to simplify the $\mathbf{n}_{\partial\Omega}$ on the two spheres, which amounts to flipping the sign of the fourth term.
To finish off, note that the third term is actually zero (use the divergence theorem to write it as $\int_{B_1(0)}\Delta u\,dV$, and use that $u$ is harmonic in the ball). The fourth term vanishes as $\epsilon\to 0$, because the surface area of $\epsilon S$ grows like $\epsilon^{n-1}$, and $u$ is well-behaved, so that integral is $\mathcal{O}(\epsilon)$. The second term approaches $(2-n)A_{n-1}u(0)$, where $A_{n-1}$ is the surface area of the unit sphere, by continuity (you're essentially taking the average of a continuous function, over spheres of smaller radii). By cleaning up, you get the mean-value theorem.


How to style overall form

Question: Problem
I have a lot of pages with standalone forms. Because of webdesign issues I ended up using the form element to style.
The problem is certain actions cause the form-id to change.
<form id="user-profile-form">

 //a failed file upload causes the above to become

<form id="user-profile-form--2">

Which breaks a lot of my css.
An example form HTML profile:
<form id="user-profile-form" accept-charset="UTF-8" method="post" action="/drupalie/user/184/edit" enctype="multipart/form-data">

        /*form is built in here*/

</form>

Is there a way to add a CSS class to my form, add a class to the empty div which surrounds all the form elements or as a last resort, prevent the form increment on certain forms.
Comment: I posted an answer, but next time please at least read the docs, OK? [Form API reference](https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7s) is a must-have, no one can remember everything so I strongly suggest bookmarking it and keeping it open during form development.
Comment: Aah shoot, sorry I should've checked that. I just assumed it was only used for elements. Thank you for answering anyway!
Comment: It's somehow misleading format of Form API docs... there is "pseudo-element" form listed in it, that represents overall form. But I agree it's easy to miss it - it looks like real elements in the table.
Comment: Feature request to documentation team [here](https://drupal.org/node/2120411#comment-8000475)
Answer: You can add classes you need directly to your form with #attributes. This is example directly from the official documentation:
$form['#attributes'] = array('class' => array('search-form'));

If it's not your code that creates form, you can add this with hook_form_alter(). Just be careful not to overwrite any attributes or classes that might be already in place:
$form['#attributes']['class'][] = 'search-form';

How to style overall form


can the require user's permission be set in a gpo?

Question: We are using Windows 2008R2 Server for our Domain Controller and a Windows 2008 for our Remote Desktop users.
We have to support them or get them out of something on a regular basis. We have quite a few users. I checked the group policy but I couldn't find it but that doesn't mean it does not exist.
Can the Require user's permission, as shown below, be set in the group policy or does it have to be set on each user?  If so, where do I change it?

If not, is there an easy way to change this on all users so I don't have to manually do it for our large number of users?
Comment: Also can be done per Terminal Server: http://technet.microsoft.com/en-us/library/cc771538.aspx
Answer: Q: "Can it be set in Group Policy?". A: "Yes it can."
Go to Computer Configuration>Policies>Administrative Templates>Windows Components>Remote Desktop Services>Remote Desktop Session Host>Connections
Specifically the Set rules for remote control of Remote Desktop Services user sessions and change it to Enabled and set the option to Full Control with User's Permission
EDIT:
You can also se it under User Configuration. If you set it under Computer Configuration it will apply to all users logging onto the server where that GPO is applied. If you set it under User Configuration it will apply to all users that the GPO applies to. If you set it under both Computer Configuration and User Configuration then the Computer Configuration setting takes precedence.
Thanks to TheCleaner for the assist in adding the additional detail for the actual setting.
Comment: Glad to help. See my edit.


howto get HttpException statusCode from HttpException variable

Question: I have this exception:
HttpException {#689 ▼
    -statusCode: 403
    -headers: []
    #message: ""
    #code: 0
    #file: "/var/www/hqse/vendor/laravel/framework/src/Illuminate/Foundation/Application.php"
   #line: 905
  -trace: {▶}
}

I can not get the statusCode of the exception.  I need to get "403".
The getCode() function returns 0.
Instead if I do:
$exc->statusCode

it returns an empty string.
Answer: In order to get statusCode there is method $exc->getStatusCode().


AngularJs: can't get ng-model in ng-repeat in component's controller

Question: I want to use ng-model="model.ind[$index]" to record which tag is active, then when I click the tag(the a tag) parentIndex and $index will be passed to my controller, and the model.ind[$index] would be set equal to current index.
However, in my function select, I can't get this.model.tag[parentIndex] and get an error TypeError: Cannot read property '0' of undefined
    at angular.module.component.controller.select
What can I do to fix this problem?
my component is:

{{tag.name}}

            {{t}}

my component js is :
angular.module('myApp').component('filterBar',{
    templateUrl: 'component/filter-bar/filter-bar.html',
    controller: ['$log',function filterBarCtrl($log){
        this.select = function(parentIndex,index){
            this.model.ind[parentIndex] = index;
        };
        this.selected = 0;

        this.model = {};

        this.tagList = [
            {
                name: 'type',
                tags:["a","b"]
            }
        ];
    }]
});

Answer: You need to use $ctrl.model in template for bind it with controller field. And this.model.ind must to be defined, if you want to use $ctrl.model.ind[...] in template


Checking if a nominal variable is important in a GLM model

Question: Is it possible to put a nominal explanatory variable as a continuous variable in a GLM in R (instead of telling R that its a factor with different levels) to see if this variable (treatment) is a significant driver of the response variable that we are interested in before looking at the levels?
Thanks!
Comment: @why would you want to do that? You mean to code a nominal with arbitrary numbers (e.g. "blue" =2)?? Very bad idea.
Comment: What is a "significant driver"?
Comment: @ ttnphns (significant driver, I suppose a better word would be "determiner")
Answer: Treating a nominal variable as continuous is never a good idea because a simple relabeling of the numerical value of the levels can lead to different estimates and different hypothesis test decisions, which is a very undesirable property.
It sounds like you want to know how to test the significance of a nominal variable without examining the difference between levels of the nominal variable - since this is a GLM (fit by maximum likelihood) you can do this with the likelihood ratio test. Suppose you have a number of 'other' covariates $X_{1}, ..., X_{p}$ and an $m$-level categorical variable with dummy variables $B_{1}, ..., B_{m-1}$ indicating which level (excluding the reference level) of the nominal variable you are in (in R, these variables are generated automatically and incorporated in the fit if the predictor is a factor). So, then you fit two models
$$ Y_{i} = \beta_{0} + \sum_{j=1}^{p} X_{ij} \beta_{j} + \sum_{k=1}^{m-1} B_{k} \alpha_{k} + \varepsilon_{i} $$
and
$$ Y_{i} = \beta_{0} + \sum_{j=1}^{p} X_{ij} \beta_{j} + \varepsilon_{i} $$
where the second model reflects the belief that the nominal predictor has no effect (irrespective of the effect of particular levels). Extract the maximized log-likelihoods from the first and second model $L_{1}, L_{0}$, respectively, (using, for example the logLik() function in R) and calculate
$$ 2 \Big( L_{1} - L_{0} \Big) $$
which has an approximate $\chi^{2}_{m-1}$ distribution, which you can use for significance testing.
Comment: When you say "use for significance testing" do you mean as a p-value?
Comment: and thanks for the very informative and excellent answer. I appreciate the time put into the answer, thanks so much.
Comment: No problem. When I say significance testing I mean that the $p$-value will be calculated by using areas under the $\chi^{2}_{m-1}$ distribution (and not, for example, the normal).
Comment: okay, so my model with the nominal variable of interest with all the levels gives a maximized log-likelihood value of (-16.8898) after using the MASS logLik() function as you mentioned. The null model gives -15.87208. This gives -0.66802 I believe using your above formula. "using areas under the χ2m−1 distribution" how do I do this? Excuse my inept understanding....
Comment: Well, that is fishy, because your null model gives a larger log-likelihood than the larger model (which is impossible). Do you have those mixed up? I also need to know how many levels your categorical variable has. It should also be noted that when I said "approximate" I meant that the test is valid for large samples. Your small log-likelihood values make me think you might be working with small samples.
Comment: If there are any missing values in the categorical predictor then R will eliminate them automatically from the model and they will be treated as though they don't exist - this may be a reason why the null model has a larger log-likelihood (since the likelihood scales with the sample size, and the sample size is smaller). If this is the case, the log-likelihoods are not comparable and you'd have to remove the missing cases before doing the test to make them comparable.
Comment: My nullmodel with missing cases removed gives
-15.04497 (df=12). Model1 which has the nominal variable removed gives a baffling -15.12846 (df=11). I am working with a small sample size yes.
Comment: You seem to have to role of the null and alternative model confused - the one with more parameters (df=12) is not the null model. In this case, your likelihood ratio test is incredibly small, indicating little is gained from adding the predictor. Also, the difference in degrees of freedom indicates that your categorical predictor has only two levels. If this isn't the case, you may have made a mistake. Make sure you declare the variable as a factor before fitting the model


API 'variant.getJavaCompile()' is obsolete

Question: I'm new to Kotlin development and just after I added Kotlin to my project there's a problem with something obsoleted.
I saw something like this before when we had to change compile to implementation, but I really don't understand what is this about.
the warning I get:
API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'.
It will be removed at the end of 2019.

build.gradle:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-android'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.sinamn75.androidtest"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        targetCompatibility 1.8
        sourceCompatibility 1.8
    }
}
repositories {
    mavenCentral()
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    // Support
    implementation 'com.android.support:appcompat-v7:28.0.0-rc02'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:design:28.0.0-rc02'
    implementation 'com.android.support:recyclerview-v7:28.0.0-rc02'
    implementation 'com.android.support:cardview-v7:28.0.0-rc02'
    implementation 'com.android.support:support-v4:28.0.0-rc02'
    implementation 'com.android.support:support-core-utils:28.0.0-rc02'
    implementation 'com.android.support:preference-v14:28.0.0-rc02'
    implementation 'com.android.support:exifinterface:28.0.0-rc02'
    // GooglePlay
    implementation 'com.google.android.gms:play-services-maps:15.0.1'
    implementation 'com.google.android.gms:play-services-location:15.0.1'
    implementation 'com.google.android.gms:play-services-plus:15.0.1'
    implementation 'com.google.android.gms:play-services-places:15.0.1'
    implementation 'com.google.android.gms:play-services-vision:15.0.2'
    //AndPermission
    implementation 'com.yanzhenjie:permission:2.0.0-rc6'
    // AHNavigation
    implementation 'com.aurelhubert:ahbottomnavigation:2.1.0'
    // Lottie
    implementation 'com.airbnb.android:lottie:2.2.5'
    // SwitchButton
    implementation 'lib.kingja.switchbutton:switchbutton:1.1.7'
    // RoundedImageView
    implementation 'com.makeramen:roundedimageview:2.3.0'
    // Picasso
    implementation 'com.squareup.picasso:picasso:2.71828'
    // MaterialDialog
    implementation 'com.afollestad.material-dialogs:core:0.9.6.0'
    // Retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
}

build.gradle:
buildscript {
    ext.kotlin_version = '1.2.70'

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.0-alpha11'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
apply plugin: 'kotlin'

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

task customClean(type: Delete) {
    delete rootProject.buildDir
}
clean.dependsOn customClean
repositories {
    mavenCentral()
}
dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
}
compileKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}
compileTestKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

Comment: Can you paste the `Build.gradle` file codes so we can help you easily-more? Also, `variant.getJavaCompile()` seems to be obsolete but not sure where that is to be replaced by `variant.getJavaCompileProvider()`.
Comment: thanks for answering, the problem is I ca'nt find this `variant.getJavaCompile() ` I added the gradle files @ʍѳђઽ૯ท
Comment: Can you add the IDE & Version you are using?
Comment: Android studio 3.3 canary @AbhinavSuman
Comment: the last working alpha is
        classpath 'com.android.tools.build:gradle:3.3.0-alpha10'. anything more than that, and the app will not be able to resolve the R resources
Answer: Update: It seems like this is a bug in kotlin plugins which mentioned in here
However, using new release of kotlin plugin (When kotlin started using the new APIs) might get rid of the error as stated in here:
https://github.com/JetBrains/kotlin/pull/1884/commits/1a17cb54a775ab3e55db66109cb12b7d54fbba6c
And: https://github.com/JetBrains/kotlin/pull/1884
The commit was actually for the fix of this issue:

This commit does not change anything functionally, it is only to avoid
  the warning message, as reporter in
  https://issuetracker.google.com/116198439

After a deep search into codes, seems like getJavaCompile() is obsolete in your current gradle (alpha11 version). However, you were using alpha version of gradle which I don't really recommend that.
Instead, try using the stable versions like:
classpath 'com.android.tools.build:gradle:3.1.4'

And then warning should be gone I hope.
Comment: Even though this will get rid of the warning for now, this is not a solution. If the op wants to use the Canary version of Android Studio, why not? The thing is, it's a warning, not caused by anything the op wrote. It can be safely ignored, as it will be fixed way before the end of 2019, without the op doing anything.
Comment: Absolutely, that's just **a warning** however. Since the OP was concerned about this issue, I think I've explained everything and using the stable version of `gradle` should help (for now).
Comment: it not correct answer, not every user always on same version... if just warning then it has solution
Comment: @Lokesh Updated the answer. Thanks for mentioning BTW.
Answer: This warning is related to the Kotlin plugins still using the older (deprecated) APIs.
Please check the below issue on Google issue tracker:
https://issuetracker.google.com/issues/116198439
Duplicate issue with some more info:
https://issuetracker.google.com/issues/116148147
It will be fixed when Kotlin plugin will start using the newer APIs. Please check the issues here:
https://youtrack.jetbrains.com/issue/KT-25428
https://github.com/JetBrains/kotlin/pull/1884
Answer: If used to google crashlytics
Please do upgrade your gradle dependencies:
implementation 'com.crashlytics.sdk.android:crashlytics:2.9.9'
classpath 'io.fabric.tools:gradle:1.26.1'

Answer: buildscript {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.2'
        classpath 'com.google.gms:google-services:4.2.0' // Change classpath 'com.google.gms:google-services:4.3.0' to classpath 'com.google.gms:google-services:4.2.0'
    }
}


How to get server current date and time in JQuery

Question: How to get server current date and time in JQuery?
My server time is in UK..
and we use in the system in India i get current date and time in JQuery it display India time.
But I want UK time in JQuery
Comment: Are you asking how to use jQuery to send an AJAX request to a server that will report its time?
Comment: No ajax checking countdown the display the time
Answer:
The getTimezoneOffset() method returns the time difference between UTC time and local time, in minutes.

and also with the help of this question, your answer will be this

var d = new Date();
var n = d.getTimezoneOffset();
var ans = new Date(d.getTime() + n * 60 * 1000);
console.log(ans.getHours()+':'+ans.getMinutes()+':'+ans.getSeconds());

Reading this question and also this one also helps you.
Answer: In JavaScript you can get the current date and time using the Date object
var now = new Date();

in php this code return server
<? echo '{serverTime: new Date(' . time()*1000 .')}';?>

or test this code

var myVar = setInterval(myTimer, 1000);

function myTimer() {
    var d = new Date();
    var t = d.toLocaleTimeString();
    document.getElementById("demo").innerHTML = t;
}
<!DOCTYPE html>

A script on this page starts this clock:

Comment: i use this in but setInterval(function()) Jquery not working
Comment: How do you use this code? Do you want to have the current time realtime?


How can I print something only when cck field has certain value on node.tpl.php?

Question: I need to print something conditionally in my node.tpl.php depending on the cck value of a field on my content type.
For example, if field_color has "red" or "blue", then print "It has color" and if it has other values print empty text.
Answer: The following should work:
if (isset($node->field_color[0]['value'])) {
  //If you want the field value to be displayed
  print $node->field_color[0]['value'];
  //If you want some custom text to be displayed
  print 'It has colour';
}
else {
  print 'Empty Text';
}

Or with ternary operators:
print (!empty($node->field_color[0]['value']) ? $node->field_color[0]['value'] : 'Empty text';

You'll probably either want to put in some logic to make sure the field exists though, or create a node-TYPE.tpl.php for your specific content type.
EDIT
This should sort out your red or blue issue:
if (isset($node->field_color[0]['value'])) {

  $colour_value = $node->field_color[0]['value'];

  if ($colour_value == 'red' || $colour_value == 'blue') {
    $colour = $colour_value;
  }
}

print (isset($colour)) ? $colour : t('Empty Text');

I've only put the field value into a variable to save space - you don't have to do this if you don't want to :-)
Comment: Go with the first one...the second one's over 80 characters :P
Comment: Thanks. But I would like to narrow down the condition of value to only "red" or "blue" and print "Empty Text" for the rest of the color (other than "red" or "blue").
Comment: I've edited my answer.  If the colour is user input, you might also want to run `$colour` through `check_plain` before outputting it!


Is the Euler phi function bounded below?

Question: I am working on a question for my number theory class that asks:

Prove that for every integer $n \geq 1$, $\phi(n) \geq \frac{\sqrt{n}}{\sqrt{2}}$.

However, I was searching around Google, and on various websites I have found people explaining that the phi function has a defined upper bound, but no lower bound. Am I reading these sites incorrectly, or am I missing something in the problem itself?
Comment: Well of course it has a lower bound...$0$.
Comment: I've got another bound.
Answer: Let me begin with the explicit lower bound at LOWER,
$$ \phi(n) > \frac{n}{e^\gamma \log \log n + \frac{3}{\log \log n}}  $$ for $n>2.$
and then do your easier result separately.  It is a procedure due to Ramanujan, in that we can explicitly find, for any $1 > \delta > 0,$ the integer that gives the minimum of $$  \frac{\phi(n)}{n^{1-\delta}}  $$
My memory is that the optima always occur at primorials, but I will need to check. Oh, before I forget, it is theorem 327 on page 267 of Hardy and Wright that the fraction goes to infinity as $n$ goes to infinity, so it does attain a minimum.
Alright, checked, the minimum occurs at the primorial $2 \cdot 3 \cdot 5 \cdots p,$ the product of consecutive primes, where the $p$ is that largest prime that satisfies
$$  p - 1 \leq p^{1 - \delta}.  $$
So, with $\delta = 1/2,$ we find $2 - 1 \leq \sqrt 2,$  but $3-1 > \sqrt 3,$ so the minimum of $$  \frac{\phi(n)}{\sqrt n}  $$ occurs at $n=2$ and
$$  \phi(n) \geq \sqrt{ \frac{n}{ 2} }.  $$
With $\delta = \log (3/2) / \log 3 = 0.36907\ldots,$ we find $3 - 1 \leq 3^{1-\delta},$   so the minimum of $$  \frac{\phi(n)}{n^{0.63092975\ldots}}  $$ occurs at $n=2 \cdot 3 = 6$ and
$$  \frac{\phi(n)}{n^{0.63092975\ldots}} \geq  \frac{2}{6^{0.63092975\ldots}} = 0.645760\ldots.  $$
It is not quite optimal, but prettier. Take $\delta = 1/3,$ we get
$$  \frac{\phi(n)}{n^{2/3}} \geq  \frac{2}{6^{2/3}}.  $$
$$ \bigcirc  \bigcirc  \bigcirc  \bigcirc  \bigcirc  \bigcirc  \bigcirc  \bigcirc \bigcirc  \bigcirc  \bigcirc  \bigcirc  \bigcirc  \bigcirc  \bigcirc  \bigcirc   $$
We already had, with $\delta = 1/2,$
$$  \phi(n) \geq \sqrt{ \frac{n}{ 2} }.  $$
With $\delta = 1/3,$ we get
$$  \phi(n) \geq 2 \cdot   \left( \frac{n}{6} \right)^{2/3}.  $$
Take $\delta = 1/8,$ we get
$$  \phi(n) \geq 8 \cdot   \left( \frac{n}{30} \right)^{7/8}.  $$
Take $\delta = 1/13,$ we get
$$  \phi(n) \geq 48 \cdot   \left( \frac{n}{210} \right)^{12/13}.  $$
Take $\delta = 1/26,$ we get
$$  \phi(n) \geq 480 \cdot   \left( \frac{n}{2310} \right)^{25/26}.  $$
Take $\delta = 1/33,$ we get
$$  \phi(n) \geq 5760 \cdot   \left( \frac{n}{30030} \right)^{32/33}.  $$
Take $\delta = 1/47,$ we get
$$  \phi(n) \geq 92160 \cdot   \left( \frac{n}{510510} \right)^{46/47}.  $$
This is exactly the same procedure used in Ramanujan's Superior Highly Composite numbers and Alaoglu and Erdos' Colossally Abundant numbers, but I'm not sure I know anywhere that shows how you get the primorials. EDIT: I put a proof as a separate answer, also give reference for the relationship to the Riemann Hypothesis, due to Jean-Louis Nicolas.
Comment: The initial lower bound I quoted is by Rosser and Schoenfeld (1962), Theorem 15, Wikipedia actually gives a slight weakening of formula (3.42) to simplify the presentation.
Comment: I proved the bit about primorials in a separate answer.
Comment: Excellent answers! I'd like to add that your inequality with optimal exponent, with decimal expansions, can also be stated as follows:
$$\phi(n)\geq\left(\frac{n}{2}\right)^{\frac{\ln{2}}{\ln{3}}}.$$
Answer: You'll find a complete proof of the result in the appendix of this paper. Here's a hint to give you a start on doing it yourself.
First show that if $n$ is odd or a multiple of $4$, then $\varphi(n)\ge\sqrt n$; for this you'll use the prime factorization of $n$ and the multiplicativity of $\varphi$. Then handle the case $n=2m$ with $m$ odd by using the multiplicativity of $\varphi$ to write $\varphi(n)=\varphi(2)\varphi(m)$.
Comment: @Aditya_math: The argument at your link appears to be correct. In [this paper](https://www.jstor.org/stable/2303988?seq=1#metadata_info_tab_contents) Shapiro showed that $\varphi(n)>n^{\log 2/log 3}$ for all $n$ except $1,2,3,4,6,10,12,18$, and $30$. (There are a few more exceptions in this case because $\log 2/\log 3>\frac12$.)
Comment: @Aditya_math: You're very welcome.
Comment: I had read in a book, that phi(n)>sqrt{n} whenever n is not 2 or 6. For egs, https://artofproblemsolving.com/community/c1610044h2360114_problem_331 , I was also able to prove(?) this but when I looked it up on google, I only saw the weaker sqrt{n/2} bound (this question). So I am wondering if the sqrt{n} bound is even correct? Have you heard of/know the validity of the sqrt{n} bound?
Comment: Thank you so much, that perfectly answers my question! Thanks!
Answer: EEDDIITT: this gives a proof of my main claim in my first answer, that a certain function takes its minimum value at a certain primorial. I actually put that information, with a few examples, into the wikipedia article, but it was edited out within a minute as irrelevant. No accounting for taste.
ORIGINAL: We take as given Theorem 327 on page 267 of Hardy and Wright, that for some fixed $0 < \delta < 1,$ the function
$$ g(n) = \frac{\phi(n)}{n^{1-\delta}}  $$
 goes to infinity as $n$ goes to infinity.
Note that $g(1) = 1$ but $g(2) < 1.$ For some $N_\delta,$ whenever $ n > N_\delta$ we get $g(n) > 1.$ It follows that, checking all $1 \leq n \leq N_\delta,$ the quantity $g(n)$ assumes a minimum which is less than 1. Perhaps it assumes this minimum at more than one point. If so, we are taking the largest such value of $n.$
Here we are going to prove that the value of $n$ at which the minimum occurs is the primorial created by taking the product of all the primes $p$ that satisfy
$$   p^{1-\delta} \geq p-1.   $$
As I mentioned, in case two the minimum occurs at two different $n,$ this gives the larger of the two.
So, the major task of existence is done by Hardy and Wright. We have the minimum of $g$ at some
$$  n = p_1^{a_1} p_2^{a_2}  p_3^{a_3} \cdots  p_r^{a_r},    $$
with $$ p_1 < p_2 < \cdots < p_r.  $$
First, ASSUME that one or more of the $a_i > 1.$ Now,
$$ \frac{  g(p_i)}{g(p_i^{a_i})} = p^{\delta - a_i \delta} = p^{\delta (1 - a_i)} < 1. $$
As a result, if we decrease that exponent to one, the value of $g$ is lowered, contradicting minimality. So
all exponents are actually 1.
Second, ASSUME that there is some gap, some prime $q < p_r $ such that $q \neq p_j$ for all $j,$ that is $q$ does not divide $n.$
Well, for real variable $x > 0,$ the function $$ \frac{x-1}{x^{1-\delta}}  $$ is always increasing, as the first derivative is
$$ x^{\delta - 2} (\delta x +(1-\delta)). $$
It follows that, in the factorization of $n,$ if we replace $p_r$ by $q,$ the value of $g$ is lowered, contradicting minimality. So
the prime factors of $n$ are consecutive, beginning with 2, and $n$ is called a primorial.
Finally, what is the largest prime factor of $n?$ Beginning with 2, multiplying by any prime $p$ with
 $$ \frac{p-1}{p^{1-\delta}} \leq 1  $$
shrinks the value of $g$ or keeps it the same, so in demanding the largest $n$ in case there are two attaining the minimum of $g,$ we take $n$ to be the product of all primes $p$ satisfying
$$  p - 1 \leq  p^{1-\delta},   $$ or
$$   p^{1-\delta} \geq p-1   $$
as I first wrote it.
Examples are given in my first answer to this same question.
EEDDIITTTT: Jean-Louis Nicolas showed, in 1983, that the Riemann Hypothesis is true if and only if, for all primorials $P,$
$$  \frac{e^\gamma \phi(P) \log \log P}{P} < 1.   $$
Alright, the exact reference is: Petites valeurs de la fonction d'Euler. Journal of Number Theory, volume 17 (1983), number 3, pages 375-388.
On the other hand, if RH is false, the inequality is true for infinitely many primorials and false for infinitely many. So, either way, it is true for infinitely many primorials (once again, these are $P = 2 \cdot 3 \cdot 5 \cdots p$ the product of consecutive primes beginning with 2).
For whatever reason, the criterion of Guy Robin, who was a student of Nicolas, got to be better known.
Answer: Firstly: the function $\phi(n)$ does not have the lower limit in the form of a straight line with a positive slope.
This follows from the formula
$$\dfrac{\phi(n)}n = \prod\limits_{p\,|\, n}\dfrac{p-1}p,$$ formula, which illustrates non-increasing of $\dfrac{\phi(n)}n$.
Analysis of the formula leads to the following conclusions for :
$$\dfrac{\phi(np^k)}{np^k} = \begin{cases}\dfrac{\phi(n)}{n},\text{ if }p\,|\,n\\\dfrac{\phi(n)}{n}\dfrac{p-1}p,\text{ if }p\!\not|\:n\end{cases}$$
These findings can be illustrated by a simple table:
So, not difficult to prove that
$$\dfrac{\phi(n)}n \geq H(n),$$ where $H(n)$ is a step function
$$H(n) = \begin{cases}
    \dfrac12,\text{ if } n \in [2,6)\\
    \dfrac13,\text{ if } n \in [6,30)\\
    \dots\\
    r_k,\text{ if } n \in [p_k\#, p_{k+1}\#)\\
    \dots,
\end{cases}$$
$\qquad p_k\# = \prod\limits_{i=1}^{k}p_i$ is primorial,
$$\left\{p_k\#\right\}=\{2,6,30,210,2310,30030,510510,96996900,223092870,6469693230,\dots\}$$
$$r_k = \dfrac1{p_k\#}\prod\limits_{i=1}^{k}(p_i-1),\dots,
\quad \{r_k\}=\left\{\dfrac12,\dfrac13,\dfrac4{15},\dfrac8{35},\dfrac{16}{77},\dfrac{192}{1001},\dfrac{3072}{17017},\dfrac{55396}{323323},\dfrac{110592}{676039},\dfrac{442368}{2800733},\dots\right\}$$
$$\{p_i\}=\{2,3,5,\dots\}.$$
This function is susceptible to various approximations.
As $p_i\geq i,$ then for not increasing consequence $R_k$ is valid ratio
$$r_k = \prod\limits_{i=1}^k\left(1-\dfrac1{p_i}\right)\geq \prod\limits_{i=1}^k\left(1-\dfrac1{i+1}\right) = \dfrac1{k+1}.$$
On the other hand, is not difficult to prove that $$p_k\#\geq k(k+1).$$
So for $(k-1)k < n \leq k(k+1):$
$$\sqrt{n}>k-1,$$
$$\dfrac{\phi(n)}n \geq\dfrac1{k(k+1)}\phi\left(k(k+1)\right) \geq \dfrac {\phi(p_k\#)}{p_k\#}=r_k \geq \dfrac1{k+1} > \dfrac1{\sqrt n +2}.$$
$$\boxed{\phi(n) \geq \dfrac n{\sqrt n+2}},$$


Jquery plugin. Combobox. Event onChange

Question: I have a problem with this plugin http://jquery.sanchezsalvador.com/jquery/page/jquerycombobox.aspx
On my page there are a few select boxes, which transformed by jquery.combobox. As far as it's transformed, it has different html like this
<input class="combobox_hidden" type="hidden" name="prtnr" id="prtnr" value="Value">

I read documentation about events in this plugin. I wanna listen to onChange event and do something, but it doesn't work.
var allsels;
var sels = $("select");
if (sels.length)allsels = sels.combobox();
........
allsels.combobox.onChange=function(){....};

What is wrong here?
Answer: On the last line, try
allsels.onChange = function () {...};

I find this documentation confusing, personally:

usage:
var elementJQ = $("#id").combobox();
  elementJQ.combobox.onChange = function(){};
or
  $("#id").combobox().onChange = function(){};

So the return result of $('#id').combobox() is a combobox object... with a combobox attribute?
Comment: Still doesn't work. I tried simple alert(); in this function and it has no effect. Maybe it's connected with two different .js files...
Comment: var allsels;
var sels = $("select");
if (sels.length)allsels = sels.combobox();   --- this 3 lines are in init.js
allsels.combobox.onChange=function(){....};  --- this is inline js-code, but follow after init.js
Answer: You can always just attach an onchange handler to the original  element.
see the source of the page (specifically the "animation types" select on line 116) in the live example: jquery.sanchezsalvador.com/samples/example.htm
I designed jquery.combobox so that when used, existing code would not break and your event handlers are respected.
@Anton: this was my first jquery widget. I also don't like what I've done with $(selector).combobox, where it is both a function and a state object.

Jquery plugin. Combobox. Event onChange


Implicit Wait in Robot Framework

Question: I am using below code to implement implicit wait in robot framework in PyCharm , it does not seem to work.
<code>*** Settings ***
Resource        resource.robot
Test Setup      open admin portal url
Test Teardown   Close Browser Session
Library     Collections
Library     SeleniumLibrary

*** Test Cases ***

Usergroup Creation

    Login       ${username}   ${validpassword}
    Create Group

*** Keywords ***
Create Group
    #Set Selenium Implicit Wait          10 seconds
    Sleep               3
    Click Element       xpath://span[contains(text(),'User Groups')]

    Click Element       xpath://*[@class='row']/div[2]/div/a[1]/i[1]

    Input Text          id:displayName      TestGroup2
    Double Click Element    xpath://span[contains(text(),'email@example.com')]
    Click Element       xpath://button[contains(text(),'Confirm')]

    Click Element       xpath://button[contains(text(),'Save')]

    Wait Until Page Contains        User Group created
</code>
I tried multiple library and stuff but to no use.
Answer: To add implicit wait in robot framework we need to add,
Sleep 3s

Implicit Wait in Robot Framework


Alterar Página de Categoria Woocommerce Wordpress

Question: Boa noite pessoal tudo certo ?
Estou com uma pequena duvida, eu gostaria de ajustar minha página de listagem de produtos de categoria igual a minha home desse meu site http://enprodutos.com.br/ obs: fiz um Shortcode no function.php que faz listar desse seguinte modo 'titulo', 'valor' 'inf1' e 'inf2', eu gostaria que minha pagina de categoria que lista os produtos conforme a categoria que o usuário selecione fique no mesmo modo, não encontro de modo algum o arquivo para eu editar e nem sei por onde começar
Comment: Para customizar os templates você pode copiar o diretório `templates` do woocommerce, para seu tema alterando o nome para `woocommerce`. Desta forma os arquivos do seu tema serão considerados. É necessário copiar somente os arquivos que serão alterados.
Exemplo: Copiar: `wp-content/plugins/woocommerce/templates/archive-product.php` para `wp-content/themes/TEMA/woocommerce/archive-product.php`

Falando especificamente da página de categorias, os arquivos que deve considerar são o `archive-product.php` e também os contidos no diretório `loop`.
Comment: Obrigado pela ajuda compreendi o funcionamento, fiz uma personalização conforme a solicitação do meu cliente grande abraços e espero puder te reatribuir algum dia com conhecimento
Comment: Consegui resolver conforme o código a baixo, mas também queria saber como consigo listar somente a categoria selecionada
Answer: Consegui resolver o meu problema, o meu código ficou do seguinte modo, dentro do meu tema
tema/woocommerce/archive-product.php

                            <?php
                                $args = array( 'post_type' => 'product', 'posts_per_page' => 1, 'product-category' => 'shoes', 'orderby' => 'rand' );
                                $loop = new WP_Query( $args );
                                while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>

Shoes

                                            <a href="<?php echo get_permalink( $loop->post->ID ) ?>" title="<?php echo esc_attr($loop->post->post_title ? $loop->post->post_title : $loop->post->ID); ?>">

                                                <?php woocommerce_show_product_sale_flash( $post, $product ); ?>

                                                <?php if (has_post_thumbnail( $loop->post->ID )) echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog'); else echo ''; ?>

<?php the_title(); ?>

                                                <?php echo $product->get_price_html(); ?>

                                            <?php woocommerce_template_loop_add_to_cart( $loop->post, $product ); ?>

                            <?php endwhile; ?>
                        <?php wp_reset_query(); ?>


How to pass cookie value into Drupal View

Question: We want to create some logic using JS that creates a cookie and set the node's taxonomy term id (preferred) or taxonomy term name as the cookie value. Then we want to use the cookie value to filter a View so that when a user visits a page, the view that is shown is filter based on the cookie value.
How can I pass a cookie value into the View?
/******************** Update - 9/23/2015 **************************/
I ended up using a mixture of a list block, javascript, and a custom module that on full node view, the taxonomy term id is stored into the browser's locale storage. I am no longer using a filter view based on cookie. Also, the custom module stores the taxonomy term ids into the block.
Comment: so you want when a user visits page x to grab the tax term id of page x and put it cookies, so when the user goes to page y, the page y view gets filtered  by the page x tax term id?
Comment: You could embed the view using php ex: `print views_embed_view('my_view_name', 'block_1', $termIDcookie);` You would then need to figure out how to pass a cookie for $termIDcookie in PHP
Comment: @NoSssweat Yes, you are correct. We are having trouble figuring out what is the best way to get the taxonomy term into a cookie value via JS. We have heard it is possible, but we are finding it to be difficult. Once we have the cookie value, we want to pass that cookie value into a view which always displayed on page x and y.

the View essentially would filter based on the cookie value. The most difficult part has been that we do not see a way to take in a cookie value from a View. Any thoughts or know of any tutorials we could use to help us?
Answer: On May 26th 2011 a new EU originated law came into effect that requires website owners to make significant changes to their sites and may fundamentally change the whole web browsing and shopping experience for everybody.This Cookie Law is amended privacy legislation that requires websites to obtain informed consent from visitors before they can store or retrieve any information on a computer or any other web connected device.
Cookie Control does just that, presenting users with clear information on whether cookies are present, linking to your privacy policy (where you should have specific information about what cookies are in use), and advising users on how to adjust browser settings and what cookies mean for them.


How to get parameter from dynamic route in route subscriber

Question: I am trying to restrict access for non admin users on admin/structure/menu so that only admins can create any new links via admin/structure/menu.
Now I want that for one special menu with the ID "Focus" the "Add Link" button is available for another role too.
Here is a Screenshot of the actual backend with the "Add Link" still availabe. I want this to be gone for Hauptnavigation but not for Fokusnavigation.

Same thing when you click on a Menu. You get an "Add Link" button. I can disable this with me code below, but I don't know how to allow it for non Admin Roles again.

I can get the menu->id() in the my_menu.module file, with the same code like in the routesubscriber below but somehow it doesn't work in the routesubscriber.
Drush CR returns an
PHP Fatal error:  Uncaught Error: Call to a member function id() on null in /var/www/html/web/modules/custom/my_menu/src/Routing/RouteSubscriber.php:31
Stack trace:
#0 /var/www/html/web/core/lib/Drupal/Core/Routing/RouteSubscriberBase.php(37): Drupal\my_menu\Routing\RouteSubscriber->alterRoutes(Object(Symfony\Component\Routing\RouteCollection))
#1 [internal function]: Drupal\Core\Routing\RouteSubscriberBase->onAlterRoutes(Object(Drupal\Core\Routing\RouteBuildEvent), 'routing.route_a...', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher))
#2 /var/www/html/web/core/lib/Drupal/Component/EventDispatcher/ContainerAwareEventDispatcher.php(142): call_user_func(Array, Object(Drupal\Core\Routing\RouteBuildEvent), 'routing.route_a...', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher))
#3 /var/www/html/web/core/lib/Drupal/Core/Routing/RouteBuilder.php(189): Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch(Object(Drupal\Core\Routing\RouteBuildEvent), 'routing.route_a...')
 in /var/www/html/web/modules/custom/my_menu/src/Routing/RouteSubscriber.php on line 31

Are there other ways to get the value? What am I doing wrong.
Here is my code.
<?php

namespace Drupal\my_menu\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\Routing\RouteCollection;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Class RouteSubscriber
 *
 * hiding menu editing components for non-admins
 *
 * @package Drupal\hw_menu\Routing
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    if ($route = $collection->get('entity.menu.add_link_form')) {

  //    dpm($route->getRequirements());

      $menu instanceof \Drupal\system\Entity\Menu;
      $menu = \Drupal::routeMatch()->getParameter('menu');
      if($menu->id() != 'focus') {
        $route->setRequirement('_role', 'administrator');
      }
    //  dpm($route->getRequirements());
    }

  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    // Run after content_translation, which has priority -210.
    $events[RoutingEvents::ALTER] = ['onAlterRoutes', -230];
    return $events;
  }

}

Comment: Route definitions don't contain parameter values, those are only available when a route is built. The literal answer to what I think your question is, is to add a custom access callback for the route (as described [here](https://www.drupal.org/docs/8/api/routing-system/access-checking-on-routes/custom-route-access-checking)), but there might be a more robust way to solve the problem if you can edit the question to provide some more context
Comment: Your post isn't very clear. Who are 'they'? What is 'focus'? What are you trying to do? You've shown some code, but not given the clear goal, or even clearly explained what is not working. You've told us how you're trying to do something, and shown code that does something, but you never explained clearly what the end goal is in human terms.
Comment: Sorry, thougt it should be clear by reading the code. Will add further details for humans.
Comment: I still don't see your actual goal, other than trying to solve some coding issue. But why are you even doing this coding? What is your goal for the front-end user? Without knowing what you want the expected behavior to be, we can't tell you where you're going wrong, we can't even tell you if you are on the right track with your approach, or going the entirely wrong direction altogether. There are 10 ways do do anything in Drupal.
Comment: Added some more explanation. I really don't know how to explain it better or even simpler.
Answer: Would say that you code is failing because there is no menu entity available since the menu parameter converter works when the route gets resolved as commented by @Clive not during route build, which is when the alter event is fired.
On the other hand, why don't you use the Administer menus and menu links permission from core to deny your non-admin user's access to the menu administration? Also you can use Simple Menu Permissions or the Menu Admin per Menu modules if you want more control over your menus.
But if you still want to handle the menu access by yourself you can do that implementing your own access check using the route subscriber you have already.


Confusion between a general global variable and object as a variable in javaScript

Question: Below is my code. When I'm calling myDate variable outside of myTime() function to create a Date() object, the setInterval() function don't fire but when it's inside myTime() function. As I know myDate variable is a global variable and it should work same inside or outside of the function. But why here the setInterval() method not firing while I'm creating the Date() object outside of the function? Experts explain the things. TIA
var myDate = new Date();
    function myTime(){
        document.getElementById('text').innerHTML = myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds();
    }
    setInterval(myTime, 1000);

Answer: You are right: myDate variable is accessible from myTime() function, but if it is declared outside of it, its value doesn't change. In the following snippet i've created one more external variable i to show that it is accessible from within the function:

var myDate = new Date();
var i = 0;
function myTime() {
    document.getElementById('text').innerHTML = myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds() + " (" + i++ + ")";
}
setInterval(myTime, 1000);

On the other hand, if you declare myDate variable inside the function, it will be created each time function is called - every second:

function myTime() {
    var myDate = new Date();
    document.getElementById('text').innerHTML = myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds();
}
setInterval(myTime, 1000);

Comment: updated the question. maybe it will help you to better understand.
Comment: @AshikurRahman why do you think that `setInterval()` doesn't fire?
Comment: If you run the first snippet you will se that `i` changes every second
Comment: yes, but then the seconds not changing as interval time? I'm new in programming
Comment: @AshikurRahman _"but if it is declared outside of it, its value doesn't change"_.
Comment: Right, the seconds not changing because you don't change them - you create this variable only once and it holds the same value