Running a recursive DNS server on localhost

Question: Every so often, people here ask "should I use my ISP DNS or (google/opendns)"?
What I want to know is, why not run a local recursive server yourself on your own computer or local network?  Then just use 127.0.0.1 for your DNS server and let that server find out names directly, instead of trusting / relying on the servers run by your ISP (or google/opendns)?
For instance, the recursive server that comes with PowerDNS works quite well, has both linux and windows versions, and is free. With unix, you've got both the PowerDNS and dnscache, though dnscache has wacky issues with really long cname chains...
What are some reasons for and against running a local recursive server?
Comment: Both dnscache and powerdns have easy to use recursors.  I kinda prefer powerdns these days because there are windows versions of it and I don't worry about the dnscache issues with following long cname chains which breaks some CDN stuff like akamai.
Comment: Have a look at dnscache.  It's very efficient and means you don't need to run a full blown dns server as well - just the bit that you need.
Answer: The DNS system was designed to run more efficiently with regional caching via your ISP.
Unless you have a security concern, or you ISP's DNS servers are somehow limited, you should use them.
Comment: Many ISP DNS servers respond with incorrect data if you ask for a record that doesn't exist.  That breaks all kinds of things and is in violation of the spec, but they do it anyhow.  Other ISP DNS servers are poisoned because they're running bind8, or are just flakey.
Answer: I think you need to approach this differently:
What problem are you trying to resolve?
Is running a local DNS server the best solution to that problem.  I've often seen people deploy a local DNS server with really no good justification for doing so.  In this case, you've added another service to be maintained, another vector for attack, and another link in your network for which you are responsible.
I've seen local DNS servers deployed for very good reasons.  For example, I've seen cases where the ISP's supplied DNS servers have a lot of latency.  We tracked and measured this latency, up to 800ms in some cases.  Installing a local caching server fixed this latency.
I've had mail servers be slowed by the providers public DNS resolvers.  By installing a local DNS server, this issue was resolved.
I've seen the need to resolve some domains differently on the internal network vs. the external network, once again a local DNS server was the answer.
IT solutions are highly dependent on the environment that they are deployed.
Comment: I've seen plenty of situations where the DNS server for a local network is the wireless router, which in turn forwards the DNS requests to the ISP server, which responds with their "search" site for nonexistent domains.  So, you've got the slowest computer on your network (the nat router) forwarding requests to a broken DNS server.  Rather than worry about these sorts of problems, why not just install pdns-recursor on systems in the same way people install anti-spyware software?  Is the power-dns recursor not reliable, or is it just a theory that it *may* cause problems?
Comment: Take a look at:
https://secunia.com/advisories/product/9556/?task=statistics

One again, this highly depends on your environment and needs. I operate from the standpoint of less is more.  The leaner your environment, the less software you have to look after, the smaller your threat surface, and the fewer licenses to manage.  I'm not against installing such local resolver tools if they add real value. In the environment you describe, it could be better to get a router with a built-in DNS server.  Depends on the needs.
Answer: I prefer to utilize my own recursive server as well, chris.  It's one less piece of information that is readily given to a third party.  The only service I like utilizing an ISP for is the uplink.
Chris S makes a good point, however.  If every end-user ran a local cache, it would put substantially more DNS load on the Internet.
Comcast DNS Hijacking
Comment: Perhaps this'll help reduce the amount of casual monitoring of your traffic that might happen, but realize your DNS requests are still trivially logged by your ISP.
Comment: As will any plaintext request, et cetera.  However, it's less easily manipulated for otherwise 'benign' activities such as DNS redirection for analytics and advertising.
Comment: Has anyone done research into how much more load (or less load) would be put on the internet if clients did their own recursive DNS?  A decade ago, it made sense to have DNS centralized because the root servers weren't that robust, but these days, does it still make sense?  I've seen lots of hand-waving and superstition, but not a whole lot of actual evidence.
Answer: If your ISP provides you with a recursive DNS server that

Is at least as reliable as your link
Low latency (presumably it would be, it's probably very close to you network-wise)
Is properly configured and secured

Then there aren't many significant benefits for recursively resolving your DNS queries.
You can set up a DNS server to forward recursive queries instead of resolving them itself, and simply have those requests go to your ISP's server.  What you gain from doing this is the ability to have a cache hit at your ISP's server, which could save you dozens of milliseconds in many typical setups.
There are lots of reasons why you might want to use this setup - say, you might be running .local zones for your site (or split-horizon on your site's domain), or you might want to blackhole DNS certain zones.
Comment: But if I run a local recursor, say of powerdns or dnscache, wouldn't that have a lower latency (for things already looked up) and be properly configured and secured (after all, it only accepts requests on 127.0.0.1 so no cache poisoning).
Comment: There's no reason to think a local recursing server would be any faster than a local forwarding server, and plenty of reasons to think it'd be slower.
Answer: What Chris S said, and performance. If someone else is worrying about CPU load, you don't sacrifice speed of your own machine.
Answer: Name servers that recurse may be vulnerable to cache poisoning attacks - if that nameserver is also authoritative for any domains it could make you vulnerable to some nasty hijacking attacks.
To minimize this threat, if you do choose to operate a recursive server, you should only permit recursion for client IPs under your control.
Comment: This is precisely why I would run a DNS server on 127.0.0.1 of a given machine -- only that machine would be able to make requests against itself so cache poisoning attacks would be impossible.  Similarly, a machine could be configured to allow requests from the local subnet, which would be presumably be trustworthy.  The configuration issues, at least with pdns and dnscache, are pretty trivial even including split horizon DNS and private local namespaces.
Answer: I run a non recursive DNS server with Caching under Server 2012, and have always done it for my clients. I see a huge performance benefit from "knowing" dns info at the local LAN. Run any  DNS test and you will always see the local DNS is faster. A recursive DNS is still a matter of opinion or setup. Smaller configs do not gain anything from doing their own recursive look ups and can actually slow things down. Maybe not the best answer but you have to test the performance with your connection and  host to see if it's faster.


Webform not working

Question: We're trying to get a custom module to work. For some reason, it's giving us an error, regardless of which version of Drupal we're trying to run. Here's the image:

Also, are there any modules which can be a replacement for this one?
Comment: If you are working on a custom module, how is this question related to a Webform not working? You ask if there are any modules which can replace "this one" yet you provide no details on what features your custom module has.
Answer: You're trying to delete from a table that doesn't exist.  That's why it doesn't matter what version of Drupal you're running.
What are you trying to achieve with your custom module?  Maybe you could post some example code.

Webform not working


Understanding the decomposed matrices in Singular Value Decomposition

Question: I am trying to get some intuition regarding the U and V matrices in SVD ($M=UEV^T$). I think these are orthonormal basis vectors, but I am struggling to get an intuition if they represent anything more than matrix transformations.
For example, in NMF, I understand that the decomposed matrices can be combined as a linear combination of basis vectors in one matrix with weights in the other matrix. In PCA, I understand that the eigenvectors have real significance in representing orthogonal axes of maximal variation, defined by the eigenvalues. But in SVD, I don't see any immediate connection.
Could someone enlighten me?
Answer: In a singular value decomposition, $M$ is not (necessarily) symmetric or even square; it's a transformation from one space ($\mathbb{R}^M$) to another ($\mathbb{R}^n$).
Let's supppose $m>n$. $M$ can be decomposed into a transformation into a convenient basis for $\mathbb{R}^n$ by $U$, then a projection and scaling by $E$ into a basis for $\mathbb{R}^n$ , then a rotation into the target basis in $\mathbb{R}^n$ by $V^T$.
(Alternatively, for the compact SVD, $U$ is $m\times n$ and includes the projection, and $E$ is just the scaling)
Also, just as in PCA, it's no loss of generality (and is standard) to organise $E$ from largest to smallest singular value, and $U$ and $V$ represent orthogonal axes of maximal variation in the two spaces. There are various efficient algorithms for giving you just the largest few singular values and corresponding vectors (either Lanczos-type or stochastic algorithms)
Comment: "Also, just as in PCA, it's no loss of generality (and is standard) to organise  from largest to smallest singular value, and  and  represent orthogonal axes of maximal variation in the two spaces"
Would you mind elaborating? This isn't immediately obvious to me. In PCA, I saw how this would be the case because of the objective function (https://stats.stackexchange.com/questions/217995/what-is-an-intuitive-explanation-for-how-pca-turns-from-a-geometric-problem-wit), but here I'm not so sure


How to format a text input as a decimal in jquery

Question: I have this jQuery code:
$('#amount').change(function() {
  $('#amount').val( $('#amount').val().toFixed(2) );
}); // end .change()

I need it to format the input in decmial format. Can it be done in jquery?
Example:
In a text box,
if I enter 5 I want the value to be shown as 5.00
if I enter 5.1 I want the value to be shown as 5.10
if I enter 5.12 I want the value to be shown as 5.12
seems to be a simple need. I have to be missing something because I cannot imagine that javascript or jquery does not provide a function to do this.
Comment: decimal format how exactly, could you give some examples of input and output ?
Answer: An elements value is always a string, and toFixed only works on numbers, so you have to convert the value to a number before you run toFixed on it
$('#amount').on('change', function() {
    this.value = parseFloat(this.value).toFixed(2);
});

FIDDLE
Comment: thanks @adeneo. I was going down that same path. glad you confirmed I was thinking along the proper lines. appreciate your help
Answer: Use this as the base:
Math.round(num * 100) / 100

So your code will be:
$('#amount').change(function() {
    $('#amount').val( Math.round($('#amount').val() * 100) / 100 );
});

Comment: @H.Ferrence Sure, waiting.. :D
Comment: well it did not work in my script @PraveenKumar I entered `5` and got `5`
Comment: this works: `$('#amount').val('5.25');` so I at least proved to myself the onChange() is working.
Comment: @H.Ferrence - `(5 * 100) / 100` still equals 5, so this only works with something like `5.222222` which would give `5.22` etc. but this is generally where `toFixed` comes in, but you're already using that, and you still seem to have a problem, it's just not clear what the problem is ?
Comment: the problem @adeneo is that when I enter `5` in the textbox I expect to get `5.00` but I am only getting `5` -- that's the problem.
Comment: @H.Ferrence - Oh, now I see, you're using the value directly, and that's a string, not a number, it should be like this -> http://jsfiddle.net/adeneo/ZC387/8/


How to show fontawesome icons in admin page inside Ckeditor?

Question: I managed to insert fontawesome iconS using Ckeditor with the Font Awesome Icons v1 module.
I just put this code in the HTML view of Ckeditor.

The icon is shown correctly in frontend but in CKEditor it is not shown at all.
I guess I need to load all fontawesome files inside Ckeditor. How can I do this? I need to see the icon in ckeditor in the same way as I see it in frontend.
Fontawesome is located at: sites/all/libraries/fontawesome
Comment: Is fontawesome implemented in the backend? For the backend theme?
Comment: @leymannx I just enabled the fontawesome module, I think it not implemented in backend. How can I do this?
Answer: A CKEditor plugin for fontawesome exists. If you're using the WYSIWYG module there are a number of hooks that allows you to modify your WYSIWYG editor. In fact, someone has done a write up on how to manually add CKEditor plugins using Drupal.
Comment: The tutorial works fine to install the Leaflet plugin. But is not that easy for the Fontawesome plugin.
Comment: What's the problem with the CKEditor plugin?
Comment: the icon is not shown at all under Editor appearance/Available buttons
Comment: Update: the icon is SHOWN under Editor appearance/Available buttons. I drag it to the Toolbar. But the icon is not shown when editing a page.
Answer: I use the add-on CKEditor Font Awesome by DOKSoft. This plugin will attach Font Awesome CSS automatically. See demo.
Comment: Unfortunately that is a non-free add-on.
Answer: You can have the Font-Awesome icons in the Drupal wysiwyg area as well. Add the following line in the wysiwyg advanced options > Custom JavaScript config. (admin/config/content/ckeditor/edit/xxx):
config.contentsCss = ['//cdn.jsdelivr.net/fontawesome/4.5.0/css/font-awesome.min.css','//cdn.jsdelivr.net/bootswatch/3.3.6/readable/bootstrap.css'];

ps: you may like to add this second line to allow empty tag (then you can avoid the useless  in the  tag)
CKEDITOR.dtd.$removeEmpty.i = 0;

At the end  you should have something similar to:
config.allowedContent = true;
CKEDITOR.dtd.$removeEmpty['i'] = false
CKEDITOR.dtd.$removeEmpty.i = 0;
CKEDITOR.dtd.$removeEmpty['span'] = false;
config.contentsCss = ['//cdn.jsdelivr.net/fontawesome/4.5.0/css/font-awesome.min.css','//cdn.jsdelivr.net/bootswatch/3.3.6/readable/bootstrap.css'];


bg color of view controller status bar area in UIViewControllerRepresentable

Question: I am using a UIViewControllerRepresentable for a view controller that can accomplish things I can't do in SwiftUI. I am trying to get the status bar area appear the same color as the dark blue, but it persists in being white. I tried earlier to embed it in a navigation controller, but that didn't worked either. (Ignore the Table and View beneath it in the hierarchy on the left, I have them hidden while I try to figure out what is going on with the colors at top). Any ideas how I might force the top area to conform to the desired color?
Thank you.

EDITED TO ADD:
My code in my UIViewControllerRepresentable:
<code>    func makeUIViewController(context: Context) -> UINavigationController {
        let storyboard = UIStoryboard(name: "RoundEntry", bundle: nil)

        let roundEntryVC = storyboard.instantiateViewController(identifier:
                "RoundEntry") as! RoundEntryVC
        let navigationController  = UINavigationController(rootViewController: roundEntryVC)
        return navigationController
    }
</code>
Here's my attempt to change the navbar color in the RoundEntry VC (in viewDidLoad):
<code>        let navBarAppearance = UINavigationBarAppearance()
        navBarAppearance.configureWithOpaqueBackground()
        navBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]
        navBarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
        navBarAppearance.backgroundColor = UIColor(.orange)
        navigationController?.navigationBar.standardAppearance = navBarAppearance
        navigationController?.navigationBar.scrollEdgeAppearance = navBarAppearance
        navigationController?.navigationBar.tintColor = .white
</code>
Comment: That is called the safe area
Answer: You might be looking for
<code>.edgesIgnoringSafeArea(.top)
</code>
where your UIViewControllerRepresentable is used in SwiftUI.
It worked in my case where I was also embedding container view controller. There could be some side effects I'm not aware of so please play with it.


How to get the latest version of git-core on debian lenny

Question: I'm trying to update my version of git that I'm using on the debian 5.0 lenny webserver (from 1.5 in the default package repository to at least 1.7 in the latest stable updates, according to the ubuntu ppa archives).
How would I add a repository to get a more stable version in Debian?
Answer: You can:

Update your distro
See if backports has the version you need and add lenny-backports to your apt
Get the source package and rebuild it on your server (or on a Lenny machine, wich is more safe)
Add squeeze repository to apt sources, then add the APT::Default-Release option to apt configuration and ask to install the new version. I will not describe that option in depth because I am very against it (and it will possibly break a lot of stuff) so only try that if you really want.
Comment: This, I found out just a bit ago, (should have refreshed) is true.
Answer: Ah, found it, here:
http://backports.debian.org/Instructions/
Had to switch out "squeeze-backports" with "lenny-backports" before it would work, but it worked in the end, and got me up to version 1.7, so that's all I needed.


Negative binomial for catch data with GAM

Question: I work with landing data (kg or tons), which don't follow a normal distribution and are more often than not over-dispersed.
I'm trying to obtain a standardized index of abundance using GAM to model the landings as a function of year, month, and region and using the effort (number of vessels) as an offset. I'm currently using a negative binomial with a log-link and it actually perform reasonably well, but I was wondering if there would be a more appropriate way to approach the problem.
I know the negative binomial is for count data, but I don't fully understand the implications of using it with continuous data. Also, shall I take the log of the effort when using it as an offset, and if yes, why so?
Here an example:
set.seed(123)

landings=round(rnegbin(100,theta=3)+runif(50, 0, 0.8),1)
nvessels=round(landings*0.2+runif(50,0,5))

mydata <- data.frame(landings=landings, year=rep(2020:2021,each=50), month=c(1:12,2:11,1:11,6:12,1:10,2:11,1:11,1:10,6:12,1:12), region=c(rep("A",12),rep("B",10),rep("C",11),rep("D",7),rep("E",10),rep("A",10),rep("B",11),rep("C",10),rep("D",7),rep("E",12)),effort=nvessels)

mydata <- mydata %>% mutate(year_f=as.factor(year),region_f=as.factor(region))

mod <- gam(landings ~ year_f + region_f + s(month), offset(effort), data=mydata, family=nb(link="log"), method="REML")

Apologies if this is a duplicate, but couldn't find an appropriate answer to this specific questions.
Thanks for any help.
Val
Comment: You should certainly add your offset in the log scale because your response also uses a log link, the offset $t$ turns your model $log(\mu)=X\beta$ into $log(\mu / t)=X\beta$ or equivalently $log(\mu)=X\beta + log(t)$ (because $log(a/b)=log(a)-log(b)$). That's assuming your implementation doesn't take the log for you but I've never encountered that.
Answer: For things like this, the Tweedie (family of) distribution(s) is often used. The Tweedie distribution is a family of distributions and contains as special cases the Poisson and gamma distributions (for the parameter values allowed in mgcv; the family is richer than this but the distributions where the Tweedie power parameter $p$ is in the interval 1–2 are most typically used in applied work.)
The Tweedie family is defined for non-negative reals. One of the justifications of the Tweedie is that the response is the sum of events each yielding a real. Think of daily rainfall as the response, where the daily total is 0 or the sum of $\ge 1$ rainfall events each contributing >0 mm precipitation.
The landing data can be thought of as biomass. You could catch nothing (zero fish) and get $y_i = 0$ biomass, or for each landing you could catch $F$ fish, each having a non-negative weight, which sum to the total landing (biomass) observed as $y_i$. What is not observed are the weights of the individual fish. Hence the response is the aggregate of those $F$ weights and can take on any real value between 0 and infinity (theoretically).
Technically, the Tweedie with $p = 1$ is the Poisson and $p = 2$ the gamma distributions, so there is a transition point at somewhere as $p$ tends to 1 where the distribution becomes discrete.
To use this in gam(), we can modify your model to the following and fixing the offset specification as per @PBulls' comment
mod <- gam(landings ~ year_f + region_f + s(month) + offset(log(effort)),
           data = mydata,
           family = tw(link="log"),
           method = "REML")

If your data are overdispersed compared to the estimated conditional distribution (test this using say the DHARMa pkg, which will work for the tw() family and GAMs fitted with {mgcv} now), then you might need to go more exotic and model one or more of the other parameters of the Tweedie, namely the power $p$ and/or the scale $\phi$, using family twlss(), in which case your model might be (assuming you have sufficient data!)
mod <- gam(list(landings ~ year_f + region_f + s(month) + offset(log(effort)),
                         ~ region_f,
                         ~ year_f),
           data = mydata,
           family = twlss(),
           method = "REML")

where I have (randomly) decided that the power parameter $p$ varies by region and the scale parameter $\phi$ varies by year. There's nothing stopping you including the same covariates in all three linear predictors, but that will require a lot of data!
Comment: Here the landing data is best thought of as biomass. You could catch nothing and get 0 biomass, or you can catch F fish, each of those F fish having a nonnegative weight, that sun to the total landing observed. What is not observed is the weights of the individual fish. Hence the response is the aggregate of those F weights and can take on any real value between 0 - infinity (theoretically). Technically, the Tweedie with $p =1$ is the Poisson & $p=2$ the gamma distributions, so there is a transition point at somewhere close to $p=1$ where the distribution becomes more discrete. It's an odd one
Comment: The NB is defined for the set of  non-negative integers, while the Tweedie family is defined for non-negative reals. One of the justifications of the Tweedie is that the response is the sum of events each yielding a real. Think of daily rainfall as the response, where the daily total is the sum or 0 or more rainfall events.
Comment: Could you comment in your answer why one should use the Tweedie distribution instead of negative binomial for this use-case? They are both combinations of gamma and poisson distributions, so I guess this has to do with the outcome being continuous vs. discrete. But I'm not familiar with "landing data" so I think that explanation could be really useful.
Comment: Thank you Gavin! That is very useful and much clearer. How many zeros do you think a Tweedie can handle before entering in the realm of zero-inflated models?


Simple interesting problem with numbers

Question: I say that a number $a$ is digitally contained in a number $b (a \leq  b)$ if there exist integers $m$ and $n$, both less than the number of digits of $a$, such that $\Big\lfloor\frac{b}{10^n}\Big\rfloor \equiv a \mod 10^m$. For example, $3$ is digitally contained in $37$, because $\Big\lfloor\frac{37}{10^1}\Big\rfloor \equiv 3 \mod 10^1$. Similarly, $47$ is contained in $9472$ because $\Big\lfloor\frac{9472}{10^1}\Big\rfloor \equiv 47 \mod 10^2$.
Now the best meaning of digital containment can be put in: $b$ "contains" $a$ when you write it down.
Now, my question is the following: What is the smallest number digitally containing all the digits $1,...,9$? Answer is easy: $123456789$.
Now, if it had to contain $10$ also? The answer would be $1023456789$.
Here's my question: What is the smallest number digitally containing all numbers from $1$ to $20$? I would like an approach, and eventually be able to generalize this for general $k$.

Upon request, I'll add a caution about the definition with some counterexamples:
My definition should make it clear that $19$ is not contained in $189$, for example. Similarly, $20$ is not contained in $230$ or $2303$. Thus, an unacceptable answer to the above question is $10203456789$, because none of $11,12,...,19$ are contained in this.
Comment: Might be useful if you could explain why the answer is not simply $10203456789$.
Comment: Okay,I'll edit the question.
Comment: Might be useful if you could explain why the answer is not simply $1011121314151617181920$
Comment: It may be. Why don't you prove that this is the answer? And I can find a smaller number, namely $101112013141516171819$.
Comment: My point is that there doesn't seem to be any special trick here. You need to sort the input numbers by alphabetic order (i.e., like on a file system (e.g., "105.txt" comes before "12.txt")). Then you may be able to get rid of some of the last numbers in the sorted list.
Comment: Special trick or not, I'd like a proved answer for $1,...,20$. It may be trial and error with sorting as you say, but I'd at least like an answer for a few concrete cases so that I can develop an algorithm. Actually, there is a trick, because a very similar question appeared in the IMO a few years  back.
Comment: Might be useful to add a link to that question.
Comment: I think this gets interesting as you go into the twenties and beyond. And for the original question, surely its $10112013141516171819$?
Answer: Your definition of digital containment is  not intrinsic. (It depends on base 10 expression of those two  numbers. e.g.in base 2, six = 110 digitally contains two = 10, but in decimal 6 does not contain 2.). So best is to use computer programmer's parlance and use string, substring to define it.
Then it is natural to write a computer program that generates all such strings, and then pass it to another program that sorts them.

Simple interesting problem with numbers


Sharepoint 2010 Multilingual Issue

Question: I have one issue in my sharepoint server 2010 multilingual issue..
Hindi language pack is available for windows server 2008 R2??
can i type letter and it convert to hindi or directly type in hindi language is possible in sharepoint server 2010??
My requirement is that m not able to use "Google translator"
I have to use Unicode for convert language
Please help me to solve this issue..
Thanks In Advance
Answer: What are you trying to do translate text or just convert characters? Both has actually nothing to do, in this case, with Windows Server or SharePoint.
For SharePoint you can install the Hindi Language pack - that will make your SharePoint have all it's labels/UI in Hinid. Download it here: http://www.microsoft.com/downloads/details.aspx?FamilyID=046f16a9-4bce-4149-8679-223755560d54&displayLang=hi

Sharepoint 2010 Multilingual Issue


Sending different json requests but getting similar results in Python

Question: I am trying to send json requests to scrape an infinite scroll element in this link.Though, I know some parameters are not neccessary, but to be sure, I define exactly the same parameters  that are sent to the server:my parameters and code are
import requests
import json
parameters1 = {'ticker':'XOM', 'countryCode':'US',
           'dateTime':'12%3A38+p.m.+Oct.+24%2C+2016', 'docId':'',
           'docType':'806','sequence':'e5a00f51-8821-4fbc-8ac6-e5f64b5eb0f2',
           'messageNumber':'8541','count':'10',
          'channelName':'%2Fnews%2Flatest%2Fcompany%2Fus%2Fxom', 'topic':'',
           '_':'1479888927416' }

parameters2 = {'ticker':'XOM', 'countryCode':'US',
           'dateTime':'12%3A38+p.m.+Oct.+24%2C+2016','docId':'',
           'docType':'806'  ,'sequence':'e5a00f51-8821-4fbc-8ac6-e5f64b5eb0f2',
           'messageNumber':'8525','count':'10',
           'channelName':'%2Fnews%2Flatest%2Fcompany%2Fus%2Fxom', 'topic':'',
           '_':'1479888927417' }

firstUrl = "http://www.marketwatch.com/news/headline/getheadlines"
html1 = requests.get(firstUrl, params = parameters1)
result1 = (json.loads(html1.text))

html2 = requests.get(firstUrl, params = parameters2)
result2 = (json.loads(html2.text))

and I check if they are same:
if(result2 == result1):
     print(True)

The answer is always True. I changed many parameters and it didn't work. What is wrong with my code or prodecure that I go through?
Answer: Your problem is, that you are sending JSON but using encoded strings. Instead of %2F you should use /, instead of + a whitespace, instead of %3A a : and so on. You can decode your string for example on this site.
import requests
import json
parameters1 = {'ticker':'XOM', 'countryCode':'US',
           'dateTime':'12:38 p.m. Oct., 2016', 'docId':'',
           'docType':'806','sequence':'e5a00f51-8821-4fbc-8ac6-e5f64b5eb0f2',
           'messageNumber':'8541','count':'10',
          'channelName':'/news/latest/company/us/xom', 'topic':'',
           '_':'1479888927416' }

parameters2 = {'ticker':'XOM', 'countryCode':'US',
           'dateTime':'12:38 p.m. Oct., 2016','docId':'',
           'docType':'806'  ,'sequence':'e5a00f51-8821-4fbc-8ac6-e5f64b5eb0f2',
           'messageNumber':'8525','count':'10',
           'channelName':'/news/latest/company/us/xom', 'topic':'',
           '_':'1479888927417' };

firstUrl = "http://www.marketwatch.com/news/headline/getheadlines"
html1 = requests.get(firstUrl, params = parameters1)
result1 = (json.loads(html1.text))

html2 = requests.get(firstUrl, params = parameters2);
result2 = (json.loads(html2.text))

Then result1==result2 will be False


Condição ternária JavaScript com somente um valor

Question: Um dúvida bem básica de Javascript, em uma condição ternária como posso fazer para ter ação somente em um if sem a necessidade do else?
Exemplo
(test) ? test1() : test2();

Se não quiser que aconteça nada no Else, como ficaria?
Tentei, fazer como no PHP mais não deu certo:
(!test) ?: test1();

Answer: Isso é possível com o operador && da seguinte forma:
(test) && test1();

Nessa outra resposta, O que significa o operador && em entre strings?, eu mostro como exatamente funciona o operador && no JavaScript, e porque é possível usar ele dessa forma... na verdade é uma equivalência direta: a && b => a ? b : a.
Quando se usa isso na forma de statement, o valor resultante é descartado, o que acaba fazendo com que pareça um if sem else.


E(log(x)) to E(x)

Question: Sorry if this is a straightforward question, but I have tried digging into econometrics book and cannot find anything about it. I worked on a model with log(wage) = experience + experience^2 + experience^3 and i have the results for that now. However, my results are in the form of E(log(wage)). Instead, now, I wanna move to E(wage).
Is there a transformation I should perform? Or does anyone have literature or terms I should google for?
Hopefully someone can help me
Comment: By Jensen's inequality, $\mathbb E[\log(X)]\le\log(\mathbb E[X])$ assuming both expectations are defined.
Comment: Maybe asking about [Duan's smearing](https://www.healthcare-economist.com/2010/11/16/duans-smearing-estimator/)?
Comment: Is this a duplicate of [Transforming back after a log transformation](https://stats.stackexchange.com/q/260942/36229)?
Comment: If you want $\mathbb{E}[\mathrm{wage}]$ instead, you should use a different model, perhaps with a logarithmic link function. How did you fit your model for $\log(\mathrm{wage})$?
Comment: Okay, and is there a way to make a transformation such that E(log(x)) transfers to log(E(x))?
Answer: The relationship between $E[\ln(x)]$ and $E[x]$ will in general depend on the distribution of $\ln(x)$.
If you fit $\ln(x)$ with an ordinary least squares (OLS) regression, then by assumption $\ln(x)$ is normally distributed around its expectation value with some standard deviation $\sigma_{\log}$, which should have been reported in by your OLS fitting software.  Therefore, $x$ is log-normal distributed.  Conveniently, the log-normal distribution is parameterized by the mean and standard deviation of the log, $\mu_{\log}$ and $\sigma_{\log}$.  In terms of these parameters, the expectation value of $x$ is $\exp\left(\mu_{\log} + \frac{\sigma^2_{\log}}{2}\right)$.  (The median, btw, is independent of $\sigma_{\log}$ in this case; it's just $\exp(\mu_{\log})$).
If you did something other than an OLS regression (e.g., you fit a GLM with a log link function), then the assumed conditional distribution for $\ln(x)$ is different, and therefore the relationship between the expectations of the log and the variable will be different.  In particular, for a Poisson regression, $E[x]$ is just $\exp(E[\ln(x)])$.  For other families you may have to look up the relationship.
Also, note that all of these formulae ignore the uncertainty in your estimate of $E[\ln(x)]$, which may or may not be a reasonable thing to do in your application.

E(log(x)) to E(x)


How to add a column with most resent recurring observation within a group, but within a certain time period, in R

Question: If I had:
person_ID     visit date
1               2/25/2001
1               2/27/2001
1               4/2/2001
2               3/18/2004
3               9/22/2004
3               10/27/2004
3               5/15/2008

and I wanted another column to indicate the earliest recurring observation within 90 days, grouped by patient ID, with the desired output:
person_ID     visit date           date
1               2/25/2001         2/27/2001
1               2/27/2001         4/2/2001
1               4/2/2001            NA
2               3/18/2004           NA
3               9/22/2004         10/27/2004
3               10/27/2004          NA
3               5/15/2008           NA

Thank you!
Answer: We convert the 'visit_date' to Date class, grouped by 'person_ID', create a binary column that returns 1 if the difference between the current and next visit_date is less than 90 or else 0, using this column, get the correponding next visit_date' where the value is 1
library(dplyr)
library(lubridate)
library(tidyr)
df1 %>%
   mutate(visit_date = mdy(visit_date)) %>%
   group_by(person_ID) %>%
   mutate(i1 = replace_na(+(difftime(lead(visit_date),
   visit_date, units = 'day') < 90), 0),
   date = case_when(as.logical(i1)~ lead(visit_date)), i1 = NULL ) %>%
   ungroup

-output
# A tibble: 7 x 3
#  person_ID visit_date date
#      <int> <date>     <date>
#1         1 2001-02-25 2001-02-27
#2         1 2001-02-27 2001-04-02
#3         1 2001-04-02 NA
#4         2 2004-03-18 NA
#5         3 2004-09-22 2004-10-27
#6         3 2004-10-27 NA
#7         3 2008-05-15 NA


Subset of an inner product space

Question: Lets say you have and Inner product space $V$ and we are told that $A$ is a subset of $V$.
If I am asked if $A$ is a subspace of $V$, does one have to show that $A $is a subspace from the rules of showing closure of addition, multiplication and has zero vector. Or do we have to show that the inner product is the same on this space?
Thanks.
Thomas
Comment: What does it mean to show that "the inner product is the same on this space"?
Answer: Whether $A$ is a vector subspace of $V$ depends only on the vector space structure of $V$ and how $A$ sits with respect to that structure. In any case, one can simply restrict the inner product $B : V \times V \to \Bbb R$ on $V$ to a map $B \vert_{A \times A}$. If $A$ is a vector subspace of $V$ and $B$ is positive-definite (sometimes positive-definiteness is taken as part of the definition of inner product) then checking the axioms quickly shows that $B \vert_{A \times A}$ is automatically an inner product on $A$.
On the other hand, given an inner product space $(V, B)$, a subspace $A$, and an inner product $C$ on $A$, we can ask whether the inner product structures are compatible---this just means that the inner product $C$ on $A$ is the same as the inner product $B\vert_{A \times A}$ it inherits from the ambient inner product space $(V, B)$.
Answer: Formally, to prove it is a subspace you just have to show closure. However, if you want to show it is an inner product subspace, you have to make sure the inner product is defined correctly on the limited subset...
Comment: which is completely trivial if the inner product on $A$ is defined to be whatever it was on $V$.
Comment: @mathematician i am just not sure it will always function as intended on the limited set, but indeed cannot pick a counterexample
Comment: Closure alone will not do. Also $0$ vector must belong to the subspace.
Comment: @Hirak -- it will, since $0\cdot \vec{v} = \vec{0}$

Subset of an inner product space


Changing the color of elements in a React Form when loading

Question: I need to show a react form, styled with a color passed to it through a prop in a function.
Getting the color passed is not a problem.
Somewhere, I need to apply this color to the style of some elements of the form.
<code>  document.getElementById("loginanchorlink").style.color = ctaColor;
  document.getElementById("loginsubmitbutton").style.backgroundColor = ctaColor;
  document.getElementById("loginsubmitbutton").style.borderColor = ctaColor;
  document.getElementById("loginanchorforgot").style.color = ctaColor;
</code>
I have tried the useEffect and useLayoutEffect hooks to do this, even a timer,  but the style property is not rendered yet and returns a null.
Maybe i am going about doing it the wrong way?
I'm new @this so plse be kind :)
Answer: When you create the loginanchorlink and loginsubmitbutton (and so on) in your JSX, you can pass in either a CSS class name or a style parameter with CSS (see here: https://www.geeksforgeeks.org/8-ways-to-style-react-components/).
If you reference the color property you mentioned as part of the CSS style object you pass in, then it should update when the prop updates.


Solving optimization problems using derivatives and critical points

Question: I have a homework question which I have completed 2/3 of; however I am stuck on the last part of the question.
The question is:

A drug used to treat cancer is effective at low doses with an efficacy that increases with the quantity of the drug. However, at sufficiently high doses, the drug becomes lethal. For positive values of the constants k_1 and k_2, the fraction of patients surviving cancer with this drug treatment is given by
  $$S(q)=\frac{q^2}{k_1^2+q^2}-\frac{q^2}{k_2^2+q^2}.$$

There are three parts to the question. I have answered the first two parts, but I don't know how to approach the last part, which in this case is question 3.

1) Find $S(0)$ and $\lim_{q\to\infty}S(q)$ and in each case explain what your findings mean in medical terms.

For part 1 I made $s(q)$ equal to $0$, which gave me
$$\frac 0 {k_1^2} - \frac 0 {k_2^2} = 0-0 = 0.$$
This indicates that when $q$ is equal to $0$, no patients have survived. I also used the limits for when $q$ is equal to $+\infty$; this gave me $(1-1)$, which is also equal to $0$. Therefore the conclusion here is that when $q$ is very high, hence infinity, the patients will not survive either.

2) What is the optimal daily drug quantity to administer in terms of $k_1$ and $k_2$?

For part two, I found the derivative of $s(q)$ and made is equal to $0$. So I found $s'(q)=0$.
This was a very long process which will take me forever to type here, however my final answer here was $q=\sqrt{k_2k_1}$, where $k_2$ and $k_1$ are constants. I am not sure if this is correct, but it looks pretty right to me.

3) Suppose Health Canada has only approved the use of the drug of up to 45 mg/day and suppose $k_1=25 \mathrm{mg}/\mathrm{day}$ is the same for all patients but $k_2$ varies from patient to patient. To determine a personalized treatment strategy it would be useful for physicians to have a plot of the optimal daily drug quantity as a function of $k_2$, call it $q∗(k_2)$. Sketch a plot of $q∗(k_2)$ and explain why you drew it that way. Hint: don't forget that $k_1<k_2$!

Tthis is the question that I need help approaching, any one care to help please? Am I meant to find the critical points..? Isn't that what I found in Part two? The graph it? If $k_2$ is meant to be greater than $k_1$ and $k_1$ is 25mg and overall it is 45mg, should $k_2$ be between 0 and 20mg?
Is this how my graph should be?
Answer: Your calculation of the optimal $q$ is correct.
The rest is easy. As a function of $k_2$, we have $q(k_2)=\sqrt{k_1k_2}=5\sqrt{k_2}$, at least for $25\lt k_2\lt 45$. This is not difficult to plot: the curve $y=5\sqrt{x}$ has a familiar shape. Our curve is (part of) a rightward opening parabola.
Comment: Taking second derivatives is usually not a good idea, too messy. More generally useful is the sign of the first derivative. But in this case I would argue thus. Take $k_2\gt k_1$, else we would not care about the drug. The survival function is $0$ when $q=0$, and positive near $0$ when $q$ is large. So the survival function attains a maximum somewhere. At the maximum, the derivative is $0$. But there is only **one place** in $(0,\infty)$ where the derivative is $0$ (you computed it). So what we found is it.
Comment: I found K2 to equal to 81, because K1<K2 and if K1 is equal to 25 then substituting the values into the local max I got in part 2, will give an answer of 81.
Comment: So I just plot y= 5 root x? What about the 81, do I start from 25? because k2 must be greater than k1? and it's max is 81?
Comment: You plot the curve $y=\sqrt{25x}=5\sqrt{x}$ for all permissible $x$, which means for all $x$ such that $25\lt x\le 45$. What $81$? There is no $81$ in the game. And by the way, it is not $q\ast k_2$, as in "times." It is $q(k_2)$, as in $q$ of $k_2$.
Comment: Ohh, the 81 I found is the domain so [25,81] How do I graph that? would k2 be my x axis?
Comment: The domain is $25$ to $45$, since max allowed dose is $45$. One could go beyond $45$ in case regulations change. The natural choice is to label the horizontal axis as $k_2$, and then the vertical axis can be labelled optimal dosage, or something like that.
Comment: I added an edit to my first post with at image of the graph, Is that how it should look? with my x axis as k2 and y axis as optimal dosage and thus highest would be sqrtK1K2
Comment: One more question.. How do I prove that the critical point so the local max found in part 2, is the local max? Other than the 2nd derivative test..
Comment: Thank you for your help!!! Is the graph that I plotted correct? I edited the image in to the very first post
Comment: You are welcome. Changes need to be made. You really should only draw the part from $k_2$ ("$x$") $=25$ to $x=45$. That part is not shown at all in your graph.
Comment: Ohh :s, I edited the first comment again, Is this one correct?
Comment: It looks right. There may be reason to get rid of the "dead space" below $y=20$ and above $y=40$, but that's a matter of presentation.
Comment: Alright perfect, I will Just draw it by hand! Thank you once again.


How to send hid data to android device? (Using python)

Question: I want to send hid data (from a mouse and a keyboard) from a windows computer to an android device. What is the general approach I should take for this?
What would such a hid packet look like?
OS: windows
target device: android 6.0+
Answer: To send HID data to your Android device from Python, you can use the pyhidapi library. Here is some help on how to use it:
1st step:
Install the pyhidapi library:
pip install pyhidapi

Second step:
Import the modules:
import hid
import time

Third step: Find the hid device:
vendor_id = 0x1234  # Replace with your HID device's vendor ID
product_id = 0x6969  # Replace with your HID device's product ID

# Get the list of connected HID devices
devices = hid.enumerate(vendor_id, product_id)

if len(devices) == 0:
    print("Nope, no Hid devices.")
    exit()

device_info = devices[0]
device_path = device_info['path']
device = hid.device()
device.open_path(device_path)

Fourth step: Send HID data:
report_id = 0x01  # Replace with your HID report ID
data = [0x00, 0x01, 0x02]  # Replace with the data you want to send

# Prepare the data to be sent
if report_id is not None:
    data.insert(0, report_id)

# Send the data to the phone

device.write(data)

time.sleep(0.1)

# Close the connection
device.close()

i hope this helps you send stuff to your phone from python.
Comment: Hello i am only using pyhidapi to send keyboard input (i was making a custom game controller) so i dont know how to send mouse siginals with this library but i think there is a simpler library for mouse input somewhere
Comment: Also this code isn't the best example. I think there is better info about the pyhidapi on other sources like the library's documentation on https://github.com/apmorton/pyhidapi
Comment: Thank you, your answer was informative. I was also looking into the interrupt and read signals (from or for a mouse). What would this data look like? Is it driver dependent?


Prevent jQuery .scroll function to run while doing what's inside the .scroll function


Poles and normals of an ellipse

Question: If the pole of the normal at P on an ellipse x^2/a^2 + y^2/b^2 = 1 lies on the normal at Q, show that the pole of the normal at Q lies on the normal at P.
How do we solve this using coordinate geometry?
Comment: Do you know how to generate the equation of the normal at an arbitrary point? Do you know how to compute the pole of a line? Start there.
Comment: If it helps, this is true of any two lines: they don't have to be normal to the ellipse.
Comment: Yes, I generated the normal. Should I use parametric coordinates?
Answer: This follows from a basic fact about pole-polar relationships: the poles of all of the lines through a point are colinear. So, in particular, if you take an arbitrary line $M$ through the pole of any other arbitrary line $L$, the pole of $M$ lies on $L$.
It's fairly easy to prove this reciprocity property for this specific ellipse. The pole of the line $lx+my+n=0$ is $\left(-\frac{a^2l}n,-\frac{b^2m}n\right)$. (Ignoring for now the case $n=0$.) An arbitrary line through this point has an equation of the form $$\lambda nx+\mu ny=\lambda a^2l+\mu b^2m.$$ Its pole works out to be $\left(-{\lambda a^2n\over \lambda a^2l+\mu b^2m},-{\mu b^2n\over \lambda a^2l+\mu b^2m}\right).$ It's easy to see that this point satisfies the equation of the original line. I'll leave verifying the special cases of poles at infinity to you.
If you use homogeneous coordinate vectors and a matrix representation of the ellipse, you can do all of the above without having to worry about any special cases. In fact, we can prove this pole reciprocity for any nondegenerate conic $Q$. The pole of the line $\mathbf l$ is $Q^{-1}\mathbf l$. An arbitrary line through this point can be written as $\mathbf p\times Q^{-1}\mathbf l$, where $\mathbf p$ is some other point on the line. Its pole is then $$Q^{-1}\left(\mathbf p\times Q^{-1}\mathbf l\right) = \frac1{\det(Q)}\left(Q\mathbf p\times QQ^{-1}\mathbf l\right) = \frac1{\det(Q)}\left(Q\mathbf p\times\mathbf l\right)$$ using a standard cross-product identity, symmetry of $Q$ and $\det(Q)\ne0$. (Incidentally, this says that the pole of the line through two points is the intersection of their polars.) Since $Q\mathbf p\times\mathbf l$ is orthogonal to $\mathbf l$, we have $$\mathbf l^T(Q\mathbf p\times\mathbf l) = 0,$$ so this point lies on $\mathbf l$.

Poles and normals of an ellipse


Use text field value on another text field on same node on save

Question: I have two fields on a Content Type called Property that requires the same information and I am trying to have it so that it only needs to be inputted one time be the user.
I am using the module Address Field and Locations and need to fill out the zip codes with the same zip code. I need to get it so I only have to input the zip code one time and it fills both. I have tried a hook form alter (my example below) but the second field does not get the text unless I save the node again. I understand why but I am not sure how to go about fixing this.
function zip_to_zip_form_alter(&$form, $form_state, $form_id) {

switch($form_id) {
  case 'property_node_form':

$form['locations'][0]['#default_value']['postal_code'] = $form['field_address']['und'][0]['#address']['postal_code'];

  break;

}
}
Suggestions welcome. Thanks!
Comment: You can do this by `hook_node_api`.
Answer: What you are doing is happening in the browser, so drupal, or anything else on the server, obviously doesn't know what's going on until you hit submit.
So you have to use jQuery that is running there in the client, and one way would be along the lines of:
$('#IDOFYOURFIRSTZIPCODE').live('change', function() {
  $('#IDOFYOURSECONDZIPCODE').val($('#IDOFYOURFIRSTZIPCODE').val());
});

The #IDs will look something like #edit-field-FIELDNAME-0-value but basically what it is doing is changing the second value to the first when the first changes.
Put that in a module's or theme's js and you should be set.  (I suppose you could [should?] add it with a drupal_add_js() right from your form_alter().)
(For those jQuery experts out there, I suppose I should have used on() or delegate() instead of live() but this works on both D6 and D7 with stock jQuery)
Comment: I just wanted to say thanks! This worked. I needed to do this for Drupal 7 and it was for the admin overlay. I ended up creating a module that hooked into the admin overlay and called the jQuery script. Worked like a charm!
Comment: glad I could help!


Regular expression with javascript

Question: I have following code in java script
    var regexp = /\$[A-Z]+[0-9]+/g;
    for (var i = 0; i < 6; i++) {
        if (regexp.test("$A1")) {
            console.log("Matched");
        }
        else {
            console.log("Unmatched");
        }
    }

Please run it on your browser console. It will print alternative Matched and Unmatched. Can anyone tell the reason for it.
Comment: http://stackoverflow.com/q/7331753/1917390
Answer: After call test on a string, the lastIndex pointer will be set after the match.
Before:
$A1
^

After:
$A1
   ^

and when it comes to the end, the pointer will be reset to the start of the string.
You can try '$A1$A1', the result will be
Matched
Matched
Unmatched
...

This behavior is defined in 22.214.171.124, ECMAScript Language Spec.

Step 11. If global is true,
  a. Call the [[Put]] internal method of R with arguments "lastIndex", e, and true.
Comment: Hi Hoacheng +1 for your good answer. But still I am confused with the concept. can you please describe it in simple way.
Comment: @Workonphp There's a pointer `lastIndex` when using `g` flag on your RE, which means the place matched last time will be stored. This behavior causes your problem.
Answer: I've narrowed your code down to a simple example:
var re = /a/g, // global expression to test for the occurrence of 'a'
s = 'aa';     // a string with multiple 'a'

> re.test(s)
  true
> re.lastIndex
  1
> re.test(s)
  true
> re.lastIndex
  2
> re.test(s)
  false
> re.lastIndex
  0

This only happens with global regular expressions!
From the MDN documentation on .test():

As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match.
Answer: This is because you use the global flag g, every time you called .test, the .lastIndex property of the regex object is updated.
If you don't use the g flag, then you could see the different result.
Answer: The 'g' in line one is not correct, you are not performing a substitution here, but a match, remove it and you will get your expected behavior.
var regexp = /\$[A-Z]+[0-9]+/g;  should be: var regexp = /\$[A-Z]+[0-9]+/
Comment: The global modifier is not only useful for substitutions.

Regular expression with javascript


How to paste examples into IPython?

Question: The web is full with python code examples that are either taken from vanila Python shell
>>> for i in range(10):
...  print(i)
...

.... or from IPython shell:
In [1]: for i in range(10):
   ...:     print(i)
   ...:     print(i + 1)
   ...:

When I want to paste such snippets into IPython, I need to paste them into a text editor, do some find-and-replace and then paste it into IPython. I'm sure there is a better way, but can't find it.
Answer: In IPython you can call %paste it will paste your clipboard in terminal.
Note: As far as I know you should install tkinter for using %paste.
Answer: The %paste command works, but what I was actually looking for was %doctest_mode. More cool hacks can be found here

How to paste examples into IPython?


how value assigned to __image_copy_start in U-boot

Question: As per my understanding below command is loading value of "__image_copy_start" to r1 register.
    ldr     r1, =__image_copy_start

I am trying to understand how value is assigned to "__image_copy_start". I couldn't find any assignment statement which is assigning value to "__image_copy_start", but I could see following declarations in "arch/arc/lib/sections.c" file.
char __image_copy_start[0] __attribute__((section(".__image_copy_start")));
char __image_copy_end[0] __attribute__((section(".__image_copy_end")));

It seems __attribute__((section(""))) is used to place the variables in special sections(In the above statement "__image_copy_start[0]" will be placed at ".__image_copy_start" section). Can you help to understand the following.

How value is assigned to "__image_copy_start[0]" ?
Why "__image_copy_start" declared as array "char __image_copy_start[0]" why not "char __image_copy_start" ?
Answer: __image_copy_start is assigned later by the linker.
The value come from the linker script. The compiler just left the variable empty, just keeping the reference in the symbol table for the linker to make the job. When linking, the linker place there an address corresponding to the start ot the "__image_copy_start" section. A "section" in the context of the linker just means some address space. It can be fix address range or placed sequentially.
The trick in your C code is just telling the compiler & the linker to create a pointer that will be initialized pointing to the beginning of this section.
Comment: Thanks for the paste. Yes, if you look at the flags, you will see that one of the symbol bears the "d" flags, which means its a debug symbol that will only be used by the debugger but not loaded at run-time (it helps putting a name on the address). The other has the "g" and "O" flags means that is a global object. see http://linux.die.net/man/1/objdump.
Comment: Thanks for the reply. Why it is declared as array? In your reply object table means symbol table?
Comment: Its a way of having on char reserved in the section. Yes I mean symbol table.
Comment: I could see following two entries for "__image_copy_start" in symbol table. Can you help to understand this.

#arm-linux-gnueabihf-objdump  -t arch/arm/lib/sections.o;

Entry 1: 00000000 l    d  .__image_copy_start 00000000 .__image_copy_start
Entry 2: 00000000 g     O .__image_copy_start 00000000 __image_copy_start
Comment: This is hard to read (maybe a good idea to place this in a pastebin). I presume one is the debug symbol, the other is the real variable.
Comment: I have pasted the content in pastbin @ http://pastebin.com/f601rD35. The output is having 6 columns, I searched for symboltable but couldn't find info related to 6 columns.
Comment: Thanks for the reply. I have a doubht, as per the declaration `char __image_copy_start[0] __attribute__((section(".__image_copy_start")));` address will be stored in __image_copy_start[0], which is a char variable. char size is one byte, but the address can be more than one byte.
Comment: No. In C array are implemented as a pointer. So this line will declare a pointer on char called `__image_copy_start` pointing to the beginning of the section with the same name. But the pointer will have as usual the same size of the address bus (32bits = 4bytes or 64bits). The array notation is just a "trick" here. It says "points to some array of char in the __image_copy_start section".
Comment: In C , array name will contain the starting address of that array and we can't assign different address to that variable, so we can understood that array name is a constant pointer. Now we can understood like " `__image_copy_start[0]` will be placed at starting of `.__image_copy_start` section, so that array name `__image_copy_start` will contain the starting address of the section `.__image_copy_start` ".
Comment: As per the symbol table entry in the final object file(linker generated) "u-boot", the `__image_copy_start` symbol size is zero `80800000 g     O .text  00000000 __image_copy_start` (number after the scation name). I tried by initializing the variable `char __image_copy_start[0] __attribute__((section(".__image_copy_start"))) = {`c`};` but still size of the symbol is zero in the symbol table. Can you please help me to understand why size of symbol is zero.


Prove that the process Zt is covariance stationary if and only if Xt is covariance stationary

Question:
I would really appreciate it if someone could help show and explain please.
Thank you
Answer: Start by writing the auto-covariance of $Z_t$:
$$\begin{align}\operatorname{cov}(Z_t,Z_{t-j})&=\mathbb E[Z_t Z_{t-j}]-\mathbb E[Z_t]\mathbb E[Z_{t-j}]\\&=\mathbb E[X_tX_{t-j}]+\mathbb E[v_tv_{t-j}]-\mathbb E[X_t]\mathbb E[X_{t-j}]\end{align}$$
Next steps:

Simplify the expression to contain the covariances of $X_t$ and $v_t$
Decide what should be satisfied in order for the RHS expression to be independent of $t$


Como obter somente strings que contenham a palavra "x"

Question: Eu estou pegando através de um parser com DOM PHP todos os links de uma página.
Eu eu preciso pegar apenas os links que contenha a palavra "comprar-toyota"
Eu estava utilizando o seguinte código, mas de uma hora pra outra parou de funcionar:
//array que pega o valor do parser
$toyota =array();

$dom1 = new DOMDocument();
$dom1->loadHTMLFile('http://www.webmotors.com.br/comprar/carros/novos-usados/sp-sao-paulo/toyota/?tipoveiculo=carros&anunciante=pessoa%20f%C3%ADsica&tipoanuncio=novos%7Cusados&estado1=s%C3%A3o%20paulo&marca1=toyota&anode=2012&anoate=&kmde=&kmate=30000&p=1&o=1&qt=36');

// Consultando os links
$links1 = $dom1->getElementsByTagName('a');

foreach ($links1 as $link) {

   //aqui pega o link
   $string = $link->getAttribute('href').PHP_EOL;

            //apenas verifica se o link nao tem a string "comprar/toyota"
            if(strpos($string, 'comprar/toyota') != 1){
                //nadafaz;
            }else{
                //verifica se o link tem a string "comprar/toyota"
                if(strpos($string, 'comprar/toyota') == 1){
                    //guarda a string encontrada
                    $linky = $string;

                    $n++;

                    #echo $n."
";

                    //insere o link no array
                    $toyota[$n] = $linky;

                    //imprime oo link
                    echo $toyota[$n]."
";
                }
    }
}

Então inverti a condição do strpos em meu if ficando assim:
//array que pega o valor do parser
$toyota =array();

$dom1 = new DOMDocument();
$dom1->loadHTMLFile('http://www.webmotors.com.br/comprar/carros/novos-usados/sp-sao-paulo/toyota/?tipoveiculo=carros&anunciante=pessoa%20f%C3%ADsica&tipoanuncio=novos%7Cusados&estado1=s%C3%A3o%20paulo&marca1=toyota&anode=2012&anoate=&kmde=&kmate=30000&p=1&o=1&qt=36');

// Consultando os links
$links1 = $dom1->getElementsByTagName('a');

foreach ($links1 as $link) {

   //aqui pega o link
   $string = $link->getAttribute('href').PHP_EOL;

            //apenas verifica se o link nao tem a string "comprar/toyota"
            if(strpos($string, 'comprar/toyota') == 1){
                //nadafaz;
            }else{
                //verifica se o link tem a string "comprar/toyota"
                if(strpos($string, 'comprar/toyota') != 1){
                    //guarda a string encontrada
                    $linky = $string;

                    $n++;

                    #echo $n."
";

                    //insere o link no array
                    $toyota[$n] = $linky;

                    //imprime oo link
                    echo $toyota[$n]."
";
                }
    }
}

Agora está puxando todos os links da página...eu precisava pegar somente os que tem a string "comprar-toyota" em qualquer parte do link
Como posso fazer para arrumar isso?
Answer: Substitua
//apenas verifica se o link nao tem a string "comprar/toyota"
if(strpos($string, 'comprar/toyota') == 1){
    //nadafaz;
}else{
            //verifica se o link tem a string "comprar/toyota"
            if(strpos($string, 'comprar/toyota') != 1){
                //guarda a string encontrada
                $linky = $string;

                $n++;

                #echo $n."
";

                //insere o link no array
                $toyota[$n] = $linky;

                //imprime oo link
                echo $toyota[$n]."
";
            }
}

POR
// apenas verifica se o link nao tem a string "comprar/toyota"
if (strpos($string, 'comprar/toyota') !== false) {
    //guarda a string encontrada
    $linky = $string;
    $n++;
    #echo $n."
";

    //insere o link no array
    $toyota[$n] = $linky;

    //imprime oo link
    echo $toyota[$n]."
";
}

Comment: Contempla o desejado pelo AP, mas não esta 100% correto.
Comment: @GuilhermeLautert, voce tinha razão. O pior que eu tinha usado comparação de tipo no teste que fiz, porém quando postei a resposta usei > 0 .
Comment: Muito obrigado fera! Foi certeiro...
Answer: Como diz no manual  sobre strpos:

Retorna a posição numérica da primeira ocorrência de needle dentro de haystack.
  Se needle não for encontrado, strpos() irá retornar o boolean FALSE.

Se você esta apenas verificando se sua string possui uma determinada string deve se usar strpos($minhaStr, $checkStr) !== false, pois a string pode existir na na primeiro posição 0, assim não retornaria o desejado em :
if(strpos($minhaStr, $checkStr))   // se a string existir em 0 não entrara no if, pois 0 é considerado false.
if(strpos($minhaStr, $checkStr) > 0)

Answer: Apenas um detalhe para ficar 100%,  a sua condição deve ser modificada para:
if (strpos($string, 'comprar-toyota'))

e não:
if (strpos($string, 'comprar/toyota') > 0)

O problema esta exatamente  no retorno da função como especificado na documentação do php:

Se needle não for encontrado, strpos() irá retornar o boolean FALSE.

Exemplo 1:
$string = 'www.loja.com.br/comprar-toyota';

 if (strpos($string, 'comprar-toyota') > 0) {
      // funcionará.
}

Exemplo 2:
$string = 'comprar-toyota';

 if (strpos($string, 'comprar-toyota') > 0) {
      // não funcionará.
}


Chown: filebeat.yml: operation not permitted

Question: I started learning how to code two months ago, so everything is very new to me. Currently I'm trying to learn how to use logstash from the elastic website (learning how to move from mysql to elasticsearch using logstash). I've got some problems and I don't know how to solve this issue:
I tried to follow the instructions from the link:
https://www.elastic.co/guide/en/logstash/current/advanced-pipeline.html
and
https://www.elastic.co/guide/en/beats/libbeat/6.4/config-file-permissions.html
After I tried:
sudo ./filebeat -e -c filebeat.yml -d "publish"

I've got an error message saying:
"config file ("filebeat.yml") must be owned by the beat user (uid=0) or root"

So I tried
"chown 0 filebeat.yml" and "chown root filebeat.yml"

But it says : "chown: filebeat.yml: Operation not permitted"
How can I solve this problem?
I've also tried to use
"--strict.perms=false"

but it says "-bash: --strict.perms=false: command not found"
Can anyone please help me with this?
Answer: Try sudo -i enter your password root and run as it again
Answer: sudo ./filebeat -e --strict.perms=false

This starts filebeat with the flag "--strict.perms=false" set at start.


Unable to open PNG file with kview or PictureViewer; opens fine with other viewers

Question: I have a PNG file created using libPNG library. The file opens perfectly on Windows picture viewer and MS Paint, but opening with kview (on Linux RHEL5) or QuickTime PictureViewer (on Windows) fails - the former reports a "libpng read error whereas the latter reports the file as being corrupted. A similar problem is seen when trying to process the PNG using ImageMagick library on Linux. Given that the PNG opens fine on some applications, it doesn't seem that the file is really corrupted; I therefore suspect some problem with version compatibility, but I am not sure. I tried searching the web but couldn't find any information on the root cause or a solution to this problem. Can someone please guide me on this?
Comment: Try this: http://entropymine.com/jason/tweakpng/
Comment: @leonbloy Thanks! Unfortunately, I don't have the option of modifying the PNG files manually using such tools; instead, I would like to identify what is causing the problem on some of the viewers and modify my code to circumvent the problem.

By the way, I did try out inspecting the problematic PNG files using tweakpng tool. The inspection view didn't report any error but the "image viewer" of the tool wasn't able to display the file - it reported an "unexpected end of file" error. Any pointers on the root cause and ways to fix it would be very helpful.
Comment: It's hard to say without more info, it would seem to be some buggy/non-standard zlib encoding in the IDAT chunkds. Can't you post an example image?
Comment: @leonbloy Sorry, missed replying earlier. Here is one such PNG: http://i.stack.imgur.com/2WM9H.png
Answer: Judging from the  example image you posted in the comments, the problem is that your PNG lacks  the ending IEND chunk -something you can test by opening it with tweakpng and inspecting the structure visually, or choosing "Check Validity-F5". It is somewhat predictable that those kind of PNG are displayed by some viewers and rejected by others.
If you are using libpng, it seems you forgot to call png_write_end()
Comment: Thanks! That solved the problem! It turned out that I was indeed not calling `png_write_end()`; after modifying my code to call that method, the created PNG files are opening on kview.


$L^1$ convergence of PDFs vs $L^2$ convergence of CDFs

Question: Let $f_n$ denote a sequence of PDFs, and $F_n$ denote the corresponding sequence of CDFs. Given $L^1$ convergence of the PDFs to some PDF $f$,
$$\int_\mathbb{R} |f_n(x) -f(x)| dx \rightarrow 0$$
does this imply $L^2$ convergence of the corresponding CDFs to the corresponding CDF $F$,
$$\int_\mathbb{R} \left(F_n(x) - F(x)\right)^2 dx \rightarrow 0$$
Answer: First note that $0\leqslant F(x),F_n(x)\leqslant 1$ for all $n,x$ so $\sup_{n,x}|F_n(x)-F(x)|=2$. It follows that $$\sup_{n,x}(F_n(x)-F(x))^2\leqslant 2|F_n(x)-F(x)|.$$
From $L^1$ convergence of $f_n$, continuity of $F_n, F$, and nonnegativity of $f_n,f$, we have for each $t\in\mathbb R$
\begin{align}
|F_n(t)-F(t)| &= \left| \int_{-\infty}^t f_n(x)\ \mathsf dx -\int_{-\infty}^t f(x)\ \mathsf dx\right|\\
&\leqslant \int_{-\infty}^t |f_n(x)-f(x)|\ \mathsf dx\\
&\leqslant \int_{\mathbb R} |f_n(x)-f(x)|\ \mathsf dx\stackrel{n\to\infty}\longrightarrow 0,
\end{align}
and hence $F_n$ converges in distribution to $F$. In fact, as $F$ and $F_n$ are bounded, continuous, and monotone, it follows from Pólya's extension to Dini's theorem (cf. *Problems and Theorems in Analysis, I, p. 270) that $F_n$ converges uniformly to $F$ on any compact subset of $\mathbb R$. Since $F$ is a CDF, we may extend it to a continuous function $\overline F$ on the extended real line $[-\infty,\infty]$ by $\overline F(-\infty)=0$, $\overline F(\infty)=1$ (and similarly for $F_n$, and therefore $F_n$ converges uniformly to $F$ on $[-\infty,\infty]$. Since $F$ and $F_n$ are uniformly continuous, given $\varepsilon>0$ we may choose $N$ so that $n\geqslant N$ implies $$\sup_{x\in\mathbb R}|F_n(x)-F(x)|<\varepsilon. $$ Then $$\int_{\mathbb R} (F_n(x)-F(x))^2\ \mathsf dx\leqslant 2 \int_{\mathbb R}|F_n(x)-F(x)|\ \mathsf dx\stackrel{n\to\infty}\longrightarrow 0$$
so that $F_n$ converges to $F$ in $L^2$.
Comment: The convergence of $|F_n-F|\to{0}$ is uniform; thus, the limit and the integral can be exchanged by the dominated convergence theorem (by definition of uniformity $|F_n-F|\leq{g_n}\to{0}$).
Comment: Wow. It's been really long since I last saw such a complete, hardcore $\varepsilon-\delta$-style proof. Not sure it was necessary here, but +1 for the patience!
Comment: @Math1000 thanks for your efforts! So convergence of the integral then follows because $[-\infty, \infty]$ is compact and $|F_n - F|$ converges uniformly on this closed interval?
Comment: @user3825755 Just a minor clarification in response to Math1000's earlier comment: "The interchange in order of limit operations is justified by uniform convergence, not by dominated convergence": the uniform convergence criterion for exchanging integral and limit is actually a consequence of the DCT.
Comment: Sorry that this has taken a while to reply. Isn't the critical requirement for uniform convergence to imply the desired convergence that the measure of the space over which is integrated is finite? For "normal" compact subsets of $\mathbb{R}$, this is of course so, but the measure of $[-\infty,\infty]$ is no longer finite. e.g. see answers in [this question](http://math.stackexchange.com/questions/279248/what-is-wrong-in-my-proof-uniform-convergence-and-lebesgue-integral)
Comment: @Vossler Thanks for the hint!
Comment: Thanks for this detailed answer! So the basic idea is to show that the convergence of $|F_n - F| \rightarrow 0$ is uniform in order to exchange the integral and the limit? Regarding the accepted answer [here](http://math.stackexchange.com/questions/24171/lebesgue-integral-uniform-convergence), wouldn't the set over which is integrated have to be finite?
Comment: @user3825755 Indeed, $F_n$ converges to $F$ uniformly on any compact set, but $|F_n-F|$ need not have compact support. So we need a way to bound the tails - perhaps there is a more elegant method, but I believe my approach is correct.
Comment: @Math1000 Sorry but I still am confused about the very last step. So we have that $|F_n - F| < \varepsilon$ everywhere, even uniformly on compact sets. But how does the convergence of $\int_\mathbb{R} |F_n - F| dx$ then follow? The dominated convergence theorem would require an integrable upper bound, which the constant $\varepsilon$ is not, right?
Comment: The interchange in order of limit operations is justified by uniform convergence of $F_n$, not by dominated converge.
Comment: @Math1000 Could you potentially point me to a suitable reference? For example [here](https://en.wikipedia.org/wiki/Uniform_convergence#To_integrability), the statement is only given for integrals over compact sets.
Comment: @user3825755 I found a different approach (with much fewer Greek letters ;) ).
Comment: Yes, that is the idea.
Comment: @Math1000 In addition to my comment from earlier, also the [wikipedia page on uniform convergence](https://en.wikipedia.org/wiki/Uniform_convergence#To_integrability) indicates that the measure of the integration space is important (although no specific results are given for the Lebesgue integral)


Pode-se distribuir programa com Licença GPL junto com não GPL

Question: Acredito que isso faz parte do nosso escopo (penúltimo item).
Minha dúvida é a seguinte:
Se eu criar um programa (Interface Gráfica) que comunique (de forma dinâmica) com um programa GPL, poderia distribuir os dois juntos ? [Sei que se for comunicação estática é uma infração da licença]
Claro que espeficicando a lincença de cada, os direitos permitidos aos usuários etc.
Answer:
Alerta: não tenho conhecimento profundo de licenças e leis, portanto não considere esta resposta como definitiva do ponto de vista legal. Na dúvida, consulte um advogado especializado.

A FAQ da licença GPL apresenta o conceito de "mera agregação", isto é, dois programas lado a lado no mesmo disco, mas separados, não sendo parte de um único programa.
Segundo a FAQ:

Neste caso, se um dos programas é coberto pela GPL, isso não tem efeito no outro programa.

O motivo é simples:

Pipes, sockets e argumentos de linha de comando são mecanismos de comunicação normalmente utilizados entre programas separados

Mas note que os programas não poderiam ser colocados num mesmo instalador, pois:

Se os módulos são incluídos no mesmo arquivo executável, então eles estão definitivamente combinados em um único programa.

O mesmo vale se os dois programas usarem um endereço de memória compartilhado, isto é, eles seriam consideradas um único programa.
Enfim, imagino um cenário possível para combinar GPL e alguma licença menos restritiva:

Usuário recebe um disco ou um ZIP contendo dois arquivos de instalação, o do programa principal não-GPL outro do programa secundário GPL.
A instalação do programa principal não-GPL, após encerrar, executa a instalação do programa GPL em um processo separado.
Os dois programas ficam em diretórios separados, como dois aplicativos independentes no sistema operacional.
O programa não-GPL pode fazer chamadas ao programa GPL, via API do sistema operacional, utilizando parâmetros, pipes, sockets e outros recursos comuns de comunicação.

O que não pode ser feito, por exemplo, é carregar um módulo ou DLL de um programa no outro.
Comment: Um bom exemplo é o BlueZ (Pilha Bluetooth para Linux), que é GPL e implementa toda sua API em cima do D-Bus justamente para não "contaminar" programas que vão usar Bluetooth com a licença GPL.
Comment: É bom frisar que essa é a interpretação que a FSF dá para o que é uma "obra derivada". A justiça pode interpretar diferente (seja a favor do autor do software GPL, seja a favor de quem o redistribuiu "irregularmente") - inclusive países diferentes podem aplicar as leis de modo diferente. A **intenção** conta muito, ao contrário do nosso senso comum [de que a justiça é uma coisa rígida, que vale o que está no papel e pronto], e se os propósitos dos dois sistemas são próximos ou distantes. de todo modo, as informações apresentadas aqui estão corretas - e bem próximas do que ocorreria na prática.
Answer: Conforme consta no FAQ da GPL

The installer and the files it installs are separate works. As a result, the terms of the GPL do not apply to the installation software.

Ou seja:

O instalativo e os arquivos que o mesmo instala são trabalhos separados. Como resultado os termos da GPL não se applicam ao programa de instalação.

Para o meu entendimento sequer o instalativo deve seguir a GPL. Portanto pode-se sim incluir programas GPL junto com não GPL sem que o não GPL caia nos termos dessa licença mas é importante deixar claro que o programa não livre precisará obrigatóriamente comunicar-se com o GPL (quando o fizer) por:

Pipe
Sockets
interface de linha de comando.

Essa resposta é uma adaptação dessa resposta do Doc Brown no Programmers.SE
* Referente ao entendimento do autor original


Can't process MySQL FULL JOIN query

Question: I want to FULL JOIN following two tables
Table 1: Persons
P_Id      Name
 1         A
 2         B
 3         C
 4         D
 5         E

Table 2: Invoice
  Id       P_Id
 111        3
 112        3
 113        1
 114        1
 115       15

I used this query :
SELECT Persons.Name, Persons.P_Id, Invoice.Id
FROM Persons
FULL JOIN Invoice
ON Persons.P_Id=Invoice.P_Id
ORDER BY Persons.Name

But this generates an error

Unknown column 'Persons.Name' in 'Field list'

MySQL server version is 5.5.19 and I used command line client in Microsoft Windows7
INNER JOIN, RIGHT JOIN and LEFT JOIN worked for me but I can't perform FULL JOIN. What is the error please tell me I'm still a student. How can I perform FULL JOIN here ?
Thank You!
Comment: Have a look here http://explainextended.com/2009/04/06/emulating-full-outer-join-in-mysql/
Comment: Solved by using UNION of LEFT JOIN and the RIGHT JOIN of both tables
Thank you!
Answer: in order to simulate FULL JOIN in mysql, you need to UNION the result of Right Join and Left Join from both tables
SELECT  Persons.Name, Persons.P_Id, Invoice.Id
FROM    Persons
        LEFT JOIN Invoice
            ON Persons.P_Id=Invoice.P_Id
UNION
SELECT  Persons.Name, Persons.P_Id, Invoice.Id
FROM    Invoice
        LEFT JOIN Persons
            ON Persons.P_Id=Invoice.P_Id

SQLFiddle Demo
Comment: @LolCoder nope, i used to use all `LEFT` join rather the left and right join. see the interchanging of columns. `:D`

Can't process MySQL FULL JOIN query


What is the unstable or stable space of the Smale-Williams solenoid?

Question: Consider the set
$$
N =  S^1 \times \{ (x,y)\in \mathbb{R} : x^2+y^2 \leq 1 \}
$$
and the $\operatorname{map} f: N \rightarrow N$ defined by
$$
f(\theta, x, y)=\left(2 \theta, \lambda x+\frac{1}{2} \cos (2 \pi \theta), \mu y+\frac{1}{2} \sin (2 \pi \theta)\right)
$$
for some constants $\lambda, \mu \in(0,1 / 2)$.
Define $ \text { the solenoid } \Lambda=\bigcap_{n \in \mathbb{N}} f^n(N)$ which is an f-invariant compact set.
To prove hyperbolicity of $\Lambda$ I need to construct the unstable space $E^u(x)$ or stable space $E^s(x)$ of $\Lambda$.
Does anyone know what is the unstable space or stable space of $\Lambda$ ?
Edit - Regarding the importance of the question
This question is relevant because the solenoid has great importance in dynamical systems and this importance stems from the fact that the solenoid is a hyperbolic set.
Comment: Do you know the fact (and the proof) that the tangent bundle of $\Lambda$ is $1$-dimensional?
Comment: @LeeMosher I have seen it written, but no proof.
Comment: So if I wrote an answer assuming the existence of a 1-dimensional tangent bundle, would that make sense to you? If not then probably that's the kind of thing you should be focussing on.
Comment: Yes I can accept that.
Answer: First of all, for each $p = (\theta,x,y) \in N$ we have
$$D_p f =
\begin{pmatrix}
\partial f_1 / \partial \theta & \partial f_1 / \partial x& \partial f_1 / \partial y\\
\partial f_2 / \partial \theta & \partial f_2 / \partial x & \partial f_2 / \partial y \\
\partial f_3 / \partial \theta & \partial f_3 / \partial x & \partial f_3 / \partial y
\end{pmatrix}
=
\begin{pmatrix}
2 & 0 & 0 \\
-\pi \sin(2\pi\theta) & \lambda & 0 \\
\pi \cos(\pi\theta) & 0 & \mu
\end{pmatrix}
$$
where $f = (f_1,f_2,f_3)$ as in your post.
It follows that when we decompose $T_p N = \underbrace{\langle \partial / \partial \theta \rangle}_{T^\theta_p N} \oplus \underbrace{\langle \partial / \partial x, \partial / \partial y \rangle}_{T^{x,y}_p N}$, then second direct factor $T^{xy}_p N$ defines a $Df$-invariant 2-dimensional subbundle of $T N$ that I shall denote $T^{xy} N$. Furthemore, the action of $Df$ on this bundle shrinks every vector of $T^{xy} N$ by a factor greater than $2$, because of the fact that $\lambda,\mu \in (0,1/2)$. So we can now define
$$E^s \Lambda = T^{xy} N \, \big| \, \Lambda
$$
Defining $E^u\Lambda$ is a bit trickier, although I can cheat a bit by incorporating some knowledge about the topological structure of $\Lambda$. For each $p = (\theta,x,y) \in \Lambda$ there is a unique 1-dimensional subspace $T_p\Lambda \subset T_p N$ having the property that $\Lambda$ contains a smooth arc through $x$ that is tangent to $T_p\Lambda$. (Even more is true: these smooth arcs piece can be pieced together to give a neighborhood of $p$ homeomorphic to the Cartesian product of an open interval and a Cantor set.) Also, the tangent line $T_p\Lambda$ is never horizontal, meaning that it is never tangent to the $(x,y)$ plane of the $(\theta,x,y)$ coordinate system. Also, these 1-d subspaces $T_p \Lambda$ fit together continuously, to form a 1-dimensional vector space $T\Lambda$ over $\Lambda$. Finally, $T\Lambda$ is invariant under the action of $f$, meaning that $D_p f(T_p \Lambda) = T_{f(p)}\Lambda$.
The final fact we need is that $T_p \Lambda = E^u_p \Lambda$. To prove this, consider a unit vector $\vec u_p \in T_p \Lambda$, and write it as a sum $\vec u_p = \vec u^\theta_p + \vec u^{xy}_p$ of a vector in $T^\theta_p N$ and $T^{xy}_p N$. Since $\vec u_p$ is not horizontal, the angle it makes with the $T^{xy}_p N$ is positive. Since this angle varies continuously as a function of $p \in \Lambda$ and since $\Lambda$ is compact, there is a positive lower bound to this angle, independent of $p$. It follows that the length of $\vec u^\theta_p$ has a positive lower bound $c$ independent of $p$. Putting this together we have $0 < c \le |\vec u^\theta_p| \le |\vec u_p|$. But now, as we iterate, the lengths of the vectors $D_p f^i \vec u^\theta_p$ grow by powers of $2$. It follows that the lengths of the vectors $D_p f^i \vec u_p$ grow at least as fast as $c2^i$, proving that $E^u_p \Lambda$ contains vector $\vec u_p$.


Dúvida com árvore binárias

Question: Tenho essa questão:
Escrever uma função que recebe uma árvore e um id e retorna um vetor com os ids do caminho desde o nó raiz até o nó passado como parâmetro.
int[] caminho_arvore(Arvore a, int n);

Exemplos:
Arvore a:

caminho_arvore(a, 9) retorna  [1,4,2,12,13,9]
caminho_arvore(a,1) retorna [1]
caminho_arvore(a, 17) retorna []
caminho_arvore(a, 4) retorna [1,4]

A pergunta é uma só: Como eu faço para representar essa imagem(arvore) num array ou algo parecido. Apesar de haver muitos elementos na construção da pergunta, estão aí apenas para vocês entenderem, mas a resposta é uma só, como representar a imagem em C#.
Comment: Tens aqui uma implementação de uma árvore binária: https://msdn.microsoft.com/en-us/library/ms379572%28v=vs.80%29.aspx
Comment: Representa-se uma arvore binaria em um array da seguinte forma: [pai, filho esquerda, filho direita, ...]. Mais precisamente, o indice do pai vale `(i - 1) / 2`, o do filho esquerdo `2*i + 1` e o do direito `2*i + 2`.
Comment: Parecido com o que precisa: http://www.introprogramming.info/tag/binary-search-trees/
Comment: @Alex, como eu representaria a imagem postada, num array conforme você está colocando. Ainda não consegui implementar.
Comment: pnet, conseguiu chegar a uma solução, se possível posta ai ..
Comment: Ainda não. Estou lendo bastante sobre o assunto.,
Answer: Representa-se uma arvore binaria em um array da seguinte forma: [pai, filho esquerda, filho direita, ...]. Mais precisamente, o indice do pai vale (i - 1) / 2, o do filho esquerdo 2*i + 1 e o do direito 2*i + 2.
Implementacao quick and dirty, assumindo uma AB (nao ABP) de numeros:
/* Retorna o indice do nodo na arvore, ou UINT_MAX se nao encontrado -- O(n) */
size_t
index(int *tree, size_t nmemb, int node)
{
  size_t i = 0;
  while (i < nmemb && tree[i] != node)
    ++i;
  return i < nmemb ? i : -1;
}

int
parent(int *tree, size_t nmemb, int node)
{
  size_t i = index(tree, nmemb, node);
  if (i >= nmemb || !i)
    return INT_MAX;
  return tree[(i - 1) / 2];
}

int
left(int *tree, size_t nmemb, int node)
{
  size_t i = index(tree, nmemb, node);
  size_t ans = 2*i + 1;
  if (i >= nmemb || ans >= nmemb)
    return INT_MAX;
  return tree[ans];
}

int
right(int *tree, size_t nmemb, int node)
{
  size_t i = index(tree, nmemb, node);
  size_t ans = 2*i + 2;
  if (i >= nmemb || ans >= nmemb)
    return INT_MAX;
  return tree[ans];
}

E.g. http://pastebin.com/iGkk0UPq
debian@pc:~ ./a.out 2
Pai de 1: 2147483647 Esquerda: 2 Direita: 2147483647
Pai de 2: 1 Esquerda: 2147483647 Direita: 2147483647
debian@pc:~ ./a.out 3
Pai de 1: 2147483647 Esquerda: 2 Direita: 3
Pai de 2: 1 Esquerda: 2147483647 Direita: 2147483647
debian@pc:~ ./a.out 4
Pai de 1: 2147483647 Esquerda: 2 Direita: 3
Pai de 2: 1 Esquerda: 4 Direita: 2147483647
debian@pc:~ ./a.out 5
Pai de 1: 2147483647 Esquerda: 2 Direita: 3
Pai de 2: 1 Esquerda: 4 Direita: 5

Comment: Alex, quem é size_t? Não consegui entender essa parte do código.
Comment: @pnet `size_t` é um tipo inteiro positivo, e, como o nome indica, é usado para valores de "tamanho", índices, etc. Funções como `malloc` recebem-no como parâmetro. Por definição, é o tipo retornado por `sizeof`, e portanto suporta garantidamente pelo menos o índice máximo que uma array em memória virutal pode receber. Tanto a definição de `size_t` como a representação da arvore em array podem ser facilmente encontrados com uma busca no Google. Procure utiliza-lo mais antes de perguntar.

Dúvida com árvore binárias


How to change specific XML attribute of custom UI element programmatically in android

Question: I am using a custom UI component in my project which has it's own few attributes. I want to change a specific one using a function when it is clicked. I don't know how to access it though, I am fairly new in this department.
<com.chinodev.androidneomorphframelayout.NeomorphFrameLayout
                    android:id="@+id/btnsystem"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    app:neomorph_background_color="@color/appBackground"
                    app:neomorph_corner_radius="10dp"
                    app:neomorph_elevation="4dp"
                    app:neomorph_highlight_color="#ffffff"
                    app:neomorph_shadow_color="#CDCDCD"
                    app:neomorph_view_type="rectangular">

here say I want to change the app:neomorph_elevation using onclick function how can I do that?
Answer: In NeomorphFrameLayout you can add a public function changeElevation ex
 fun changeElevation(elevation :Float){
      neomorph_elevation = elevation
    }

and can use in onClickListener like
btnsystem.changeElevation(5f)

Answer: As they specified in library that,
Attributes: neomorph_clickable option set it to true and onClick trigger a function from xml or from setOnClickListener whichever you prefer...
https://github.com/4inodev/Neomorphic-FrameLayout-Android
Answer: android-repository-history
History of Android repository XML
repository2-$N.xml and addons_list-3.xml
Used by sdkmanager command.
repository-$N.xml and addons_list-2.xml
Used by android command, which is deprecated and unavailable in the latest Android SDK Tools (since r25.3.0)


Java Application Crashes After Playing Sounds

Question: I'm trying to make a game with bunch of sound effects added.
A lot of different sound effects will be played during the gameplay and I wasn't sure how to
play sounds in java so I just used the code example from the link below:
http://www.anyexample.com/programming/java/java_play_wav_sound_file.xml
However, the following error keeps coming up and crashes the application about couple minutes after.
(sometimes in few seconds, sometimes in few minutes)
Invalid memory access of location 0x54008 rip=0x11c7737fd

I'm simply making a new AePlayWave object and starting it whenever it needs to be played.
like this:
new AePlayWave("Effect.wav").start();

Everything is perfect except for the program randomly crashing because of this.
How could I solve this?
Thanks in advance.
Answer: This seems like a low-level access problem.  Maybe your audio driver has a bug in the way Java is trying to access it?
Comment: Yeah, it seems like a bug too but I don't know what I should do then :( Is there another simple way to play audio files like this one that you would suggest?
Comment: Unfortunately, I do not have enough experience playing audio files (from Java or otherwise).  Btw, can you try this on another computer -- preferably one that has a different sound card/audio driver?
Comment: Yeah I should try this on another computer. I can't do it right now but I will later tonight. I should probably try another way to play the sound..
Comment: OK so before trying my program on another computer, I decided to just try it on Windows on my computer first (I'm using a macbook btw) using Parallels, and it runs perfectly fine on windows! So I guess it's not even the sound card. After some searching, it looks like there have already been some problems reported for handling audio on mac.. I'm not sure what I should do...
Comment: I can see two possibilities: 1) switch to Windows :); 2) search for a working sound library/driver and use JNI to interface with it
Comment: Well.. I can't switch to Windows first of all as this is the only computer that I have right now :( and I'm not really sure where to find the working sound library/driver and use JNI to interface with it? (I get that it's a Java Native Interface, but I'm not really sure where to go from there) I'm quite new to java and I have never worked with these kinds of things so please pardon my ignorance...
Comment: I was just joking about switching to Windows :)  Unfortunately, I'm not familiar with mac, so I don't think I will be of much help from heare on out.  I also did not work with JNI much, so all I can offer for you is to read some documentation/tutorials -- your favorite search engine should be able to provide you a lot of hits.  But first find a _working_ sound library for mac
Comment: Alright. I'll try to do my best to find the working sound library for mac but I'm already not doing so good :'( I can't believe there is no easy way to audio files on mac right now. I just need to play a really short wav file...


Bootstrap Carousel not Working (showing all images at once)

Question: I'm trying to add a carousel to my Bootstrap 3 website. The code used is directly from http://getbootstrap.com/javascript/#carousel. The code is also quite undocumented, so I had to make some guesses. The carousel just displays all three images stacked on top of one another. I am fairly certain that my javascript and jQuery are working, because I have a navbar set up that has working dropdowns.

Slide 1

Slide 1 Description

Slide 2

Slide to Description

Slide 3

Slide 3 Description

EDIT:
I did some more work on it (thanks answering guys) and I think I got it. The slides actually animate and, unlike a few of my attempts, it loops back to the start. Hopefully this is it.

Slide 1

Slide 1 Description

Slide 2

Slide 2 Description

Slide 3

Slide 3 Description

Answer: As already told all your carousel items has been marked active and these items are wrapped in different carousel-inner class.
You need to wrap only items in carousel-inner class and not link containing carousel-control class.
In order to carousel slide automatically you need to include:
$(function(){
  $('#carousel-example-generic').carousel();
});

Check this link:Updated code
Comment: Any reason why your code isn't showing a sliding animation when the slide changes?
Comment: That's because I don't have the image src so its showing the contents in alt attribute i.e slide1,slide2...
Comment: @Rohitha your fix saved my day. Finally after 2 days, my carousel is working.
Answer: All of your slides are marked as active... Only one should have active class at any one time.
You also have too many carousel-inner divs. All slides need wrapping in one carousel-inner.
Answer:

remove active class from all div excluding first one
Answer: I faced the same issue today. I downloaded bootstrap.min.css from http://getbootstrap.com and was using that css. That css was showing the issue. I changed the css source to
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css
and it solved the problem.
Comment: Thank you! Wow, didn't expect there to be an issue with a prebuilt bootstrap.min.css


Linear Algebra Problem about Direct Sums, Kernel and Image.

Question: Let $V$ be a vector space, $W$ a subspace of $V$ and $T : V \to V$ a linear operator. Suppose $V = \text{Im } T \oplus W$ and $W$ is $T$-invariant. I have to prove that
(a) $W \subseteq \text{Ker }T$, where $\text{Ker }T$ is the kernel of $T$.
(b) If $V$ is finite dimensional, then $W = \text{Ker }T$.
For (a), I take $w \in W$, and I have prove that $T(w)=0$. Since $W$ is $T$-invariant, then $T(w) \in W$. I really don't know what's next, because I don't know how to use the fact that $V = \text{Im } T \oplus W$. Can I say  $W = \text{Im } T \oplus V$ from this fact? Also, I don't have any idea of how to prove (b). Any hints or ideas will be very appreciated. Thanks.
Answer: a) Since $V = \operatorname{im} T \oplus W$, then $\operatorname{im} T \cap W = \{0\}$. To see why, let $v \in \operatorname{im} T \cap W$. We have $v = v + 0 = 0 + v$. $v$ can be uniquely written as the sum of two vectors in each of $\operatorname{im} T$ and $W$. Therefore we must have $v = 0$. Now let $w \in W$. Since $T w \in W$ and $T w \in \operatorname{im} T$, it follows that $T w = 0$ and $w \in \ker T$.
b) We have $\dim V = \dim \operatorname{im} T + \dim \ker T = \dim \operatorname{im} T + \dim W$. Thus $\dim \ker T = \dim W$. Since $W \subset \ker T$, it follows that $\ker T = W$.
Comment: Sorry I'm a little confused. Is $V=W_1 \oplus W_2$ if and only if $V=W_1+W_2$ and $W_1 \cap W_2 = \{0\}$ a theorem for any vector space $V$ or do we have to prove this for a particular $V$?, and also, if it's valid for all $V$, can we take it as the definition of direct sum? so, we wouldn't have to prove that for every particular $V$?
Comment: @Twink It is valid for any vector space. See for example theorem 1.9 in Linear Algebra Done Right. In fact, my proof above holds with little change for any vector space. How do you define the direct sum?
Comment: You don't have to prove that $\operatorname{im}T\cap W=\{0\}$, because it's assumed by hypothesis when writing $V=\operatorname{im}T\oplus W$.
Comment: @egreg It really depends on how you define the direct sum. It looks like Twink has a different definition. Of course, the definitions are equivalent as shown by the proof I've provided.
Comment: @Twink Please tell us how you define it. My answer assumes the definition of $V = W_1 \oplus W_2$ is $V = W_1 + W_2$ and each vector in $V$ can be *uniquely* written as the sum of a vector in $W_1$ and a vector in $W_2$. Again, the definitions are equivalent as shown in my answer.
Comment: @AymanHourieh I have the same definition that you have. But I was confused because in the book I'm reading (Linear Algebra of Lang) they prove that if $V=W_1+W_2$ and $W_1 \cap W_2 = \{0\}$ then $V=W_1 \oplus W_2$, but they don't mention the converse, that's why I wasn't sure it was equivalent.